reent_init.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <string.h>
  7. #include <stdbool.h>
  8. #include <stdlib.h>
  9. #include <stdio.h>
  10. #include <sys/reent.h>
  11. #include "esp_attr.h"
  12. /**
  13. * This is the replacement for newlib's _REENT_INIT_PTR and __sinit.
  14. * The problem with __sinit is that it allocates three FILE structures
  15. * (stdin, stdout, stderr). Having individual standard streams for each task
  16. * is a bit too much on a small embedded system. So we point streams
  17. * to the streams of the global struct _reent, which are initialized in
  18. * startup code.
  19. */
  20. void IRAM_ATTR esp_reent_init(struct _reent* r)
  21. {
  22. memset(r, 0, sizeof(*r));
  23. _REENT_STDIN(r) = _REENT_STDIN(_GLOBAL_REENT);
  24. _REENT_STDOUT(r) = _REENT_STDOUT(_GLOBAL_REENT);
  25. _REENT_STDERR(r) = _REENT_STDERR(_GLOBAL_REENT);
  26. _REENT_CLEANUP(r) = _REENT_CLEANUP(_GLOBAL_REENT);
  27. _REENT_SDIDINIT(r) = _REENT_SDIDINIT(_GLOBAL_REENT);
  28. }
  29. /* only declared in private stdio header file, local.h */
  30. extern void __sfp_lock_acquire(void);
  31. extern void __sfp_lock_release(void);
  32. void esp_reent_cleanup(void)
  33. {
  34. struct _reent* r = __getreent();
  35. _reclaim_reent(r);
  36. r->_emergency = NULL;
  37. r->_mp = NULL;
  38. r->_r48 = NULL;
  39. r->_localtime_buf = NULL;
  40. r->_asctime_buf = NULL;
  41. r->_signal_buf = NULL;
  42. r->_misc = NULL;
  43. r->_cvtbuf = NULL;
  44. /* Clean up "glue" (lazily-allocated FILE objects) */
  45. struct _glue* prev = &_REENT_SGLUE(_GLOBAL_REENT);
  46. for (struct _glue* cur = _REENT_SGLUE(_GLOBAL_REENT)._next; cur != NULL;) {
  47. if (cur->_niobs == 0) {
  48. cur = cur->_next;
  49. continue;
  50. }
  51. bool has_open_files = false;
  52. for (int i = 0; i < cur->_niobs; ++i) {
  53. FILE* fp = &cur->_iobs[i];
  54. if (fp->_flags != 0) {
  55. has_open_files = true;
  56. break;
  57. }
  58. }
  59. if (has_open_files) {
  60. prev = cur;
  61. cur = cur->_next;
  62. continue;
  63. }
  64. struct _glue* next = cur->_next;
  65. prev->_next = next;
  66. free(cur);
  67. cur = next;
  68. }
  69. }