kservice.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. /*
  2. * Copyright (c) 2006-2024, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2006-03-16 Bernard the first version
  9. * 2006-05-25 Bernard rewrite vsprintf
  10. * 2006-08-10 Bernard add rt_show_version
  11. * 2010-03-17 Bernard remove rt_strlcpy function
  12. * fix gcc compiling issue.
  13. * 2010-04-15 Bernard remove weak definition on ICCM16C compiler
  14. * 2012-07-18 Arda add the alignment display for signed integer
  15. * 2012-11-23 Bernard fix IAR compiler error.
  16. * 2012-12-22 Bernard fix rt_kprintf issue, which found by Grissiom.
  17. * 2013-06-24 Bernard remove rt_kprintf if RT_USING_CONSOLE is not defined.
  18. * 2013-09-24 aozima make sure the device is in STREAM mode when used by rt_kprintf.
  19. * 2015-07-06 Bernard Add rt_assert_handler routine.
  20. * 2021-02-28 Meco Man add RT_KSERVICE_USING_STDLIB
  21. * 2021-12-20 Meco Man implement rt_strcpy()
  22. * 2022-01-07 Gabriel add __on_rt_assert_hook
  23. * 2022-06-04 Meco Man remove strnlen
  24. * 2022-08-24 Yunjie make rt_memset word-independent to adapt to ti c28x (16bit word)
  25. * 2022-08-30 Yunjie make rt_vsnprintf adapt to ti c28x (16bit int)
  26. * 2023-02-02 Bernard add Smart ID for logo version show
  27. * 2023-10-16 Shell Add hook point for rt_malloc services
  28. * 2023-10-21 Shell support the common backtrace API which is arch-independent
  29. * 2023-12-10 xqyjlj perf rt_hw_interrupt_disable/enable, fix memheap lock
  30. * 2024-03-10 Meco Man move std libc related functions to rtklibc
  31. */
  32. #include <rtthread.h>
  33. /* include rt_hw_backtrace macro defined in cpuport.h */
  34. #define RT_HW_INCLUDE_CPUPORT
  35. #include <rthw.h>
  36. #define DBG_TAG "kernel.service"
  37. #ifdef RT_DEBUG_DEVICE
  38. #define DBG_LVL DBG_LOG
  39. #else
  40. #define DBG_LVL DBG_WARNING
  41. #endif /* defined (RT_DEBUG_DEVICE) */
  42. #include <rtdbg.h>
  43. #ifdef RT_USING_MODULE
  44. #include <dlmodule.h>
  45. #endif /* RT_USING_MODULE */
  46. #ifdef RT_USING_SMART
  47. #include <lwp.h>
  48. #include <lwp_user_mm.h>
  49. #endif
  50. /**
  51. * @addtogroup KernelService
  52. * @{
  53. */
  54. #if defined(RT_USING_DEVICE) && defined(RT_USING_CONSOLE)
  55. static rt_device_t _console_device = RT_NULL;
  56. #endif
  57. rt_weak void rt_hw_us_delay(rt_uint32_t us)
  58. {
  59. (void) us;
  60. LOG_W("rt_hw_us_delay() doesn't support for this board."
  61. "Please consider implementing rt_hw_us_delay() in another file.");
  62. }
  63. rt_weak void rt_hw_cpu_reset(void)
  64. {
  65. LOG_W("rt_hw_cpu_reset() doesn't support for this board."
  66. "Please consider implementing rt_hw_cpu_reset() in another file.");
  67. return;
  68. }
  69. rt_weak void rt_hw_cpu_shutdown(void)
  70. {
  71. LOG_I("CPU shutdown...");
  72. LOG_W("Using default rt_hw_cpu_shutdown()."
  73. "Please consider implementing rt_hw_cpu_shutdown() in another file.");
  74. rt_hw_interrupt_disable();
  75. RT_ASSERT(0);
  76. return;
  77. }
  78. /**
  79. * @note can be overridden by cpuport.h which is defined by a specific arch
  80. */
  81. #ifndef RT_HW_BACKTRACE_FRAME_GET_SELF
  82. #ifdef __GNUC__
  83. #define RT_HW_BACKTRACE_FRAME_GET_SELF(frame) do { \
  84. (frame)->fp = (rt_base_t)__builtin_frame_address(0U); \
  85. (frame)->pc = ({__label__ pc; pc: (rt_base_t)&&pc;}); \
  86. } while (0)
  87. #else
  88. #define RT_HW_BACKTRACE_FRAME_GET_SELF(frame) do { \
  89. (frame)->fp = 0; \
  90. (frame)->pc = 0; \
  91. } while (0)
  92. #endif /* __GNUC__ */
  93. #endif /* RT_HW_BACKTRACE_FRAME_GET_SELF */
  94. /**
  95. * @brief Get the inner most frame of target thread
  96. *
  97. * @param thread the thread which frame belongs to
  98. * @param frame the specified frame to be unwound
  99. * @return rt_err_t 0 is succeed, otherwise a failure
  100. */
  101. rt_weak rt_err_t rt_hw_backtrace_frame_get(rt_thread_t thread, struct rt_hw_backtrace_frame *frame)
  102. {
  103. RT_UNUSED(thread);
  104. RT_UNUSED(frame);
  105. LOG_W("%s is not implemented", __func__);
  106. return -RT_ENOSYS;
  107. }
  108. /**
  109. * @brief Unwind the target frame
  110. *
  111. * @param thread the thread which frame belongs to
  112. * @param frame the specified frame to be unwound
  113. * @return rt_err_t 0 is succeed, otherwise a failure
  114. */
  115. rt_weak rt_err_t rt_hw_backtrace_frame_unwind(rt_thread_t thread, struct rt_hw_backtrace_frame *frame)
  116. {
  117. RT_UNUSED(thread);
  118. RT_UNUSED(frame);
  119. LOG_W("%s is not implemented", __func__);
  120. return -RT_ENOSYS;
  121. }
  122. rt_weak const char *rt_hw_cpu_arch(void)
  123. {
  124. return "unknown";
  125. }
  126. /**
  127. * @brief This function will show the version of rt-thread rtos
  128. */
  129. void rt_show_version(void)
  130. {
  131. rt_kprintf("\n \\ | /\n");
  132. #if defined(RT_USING_SMART)
  133. rt_kprintf("- RT - Thread Smart Operating System\n");
  134. #elif defined(RT_USING_NANO)
  135. rt_kprintf("- RT - Thread Nano Operating System\n");
  136. #else
  137. rt_kprintf("- RT - Thread Operating System\n");
  138. #endif
  139. rt_kprintf(" / | \\ %d.%d.%d build %s %s\n",
  140. (rt_int32_t)RT_VERSION_MAJOR, (rt_int32_t)RT_VERSION_MINOR, (rt_int32_t)RT_VERSION_PATCH, __DATE__, __TIME__);
  141. rt_kprintf(" 2006 - 2024 Copyright by RT-Thread team\n");
  142. }
  143. RTM_EXPORT(rt_show_version);
  144. #ifdef RT_USING_CONSOLE
  145. #ifdef RT_USING_DEVICE
  146. /**
  147. * @brief This function returns the device using in console.
  148. *
  149. * @return Returns the console device pointer or RT_NULL.
  150. */
  151. rt_device_t rt_console_get_device(void)
  152. {
  153. return _console_device;
  154. }
  155. RTM_EXPORT(rt_console_get_device);
  156. /**
  157. * @brief This function will set a device as console device.
  158. * After set a device to console, all output of rt_kprintf will be
  159. * redirected to this new device.
  160. *
  161. * @param name is the name of new console device.
  162. *
  163. * @return the old console device handler on successful, or RT_NULL on failure.
  164. */
  165. rt_device_t rt_console_set_device(const char *name)
  166. {
  167. rt_device_t new_device, old_device;
  168. /* save old device */
  169. old_device = _console_device;
  170. /* find new console device */
  171. new_device = rt_device_find(name);
  172. /* check whether it's a same device */
  173. if (new_device == old_device) return RT_NULL;
  174. if (new_device != RT_NULL)
  175. {
  176. if (_console_device != RT_NULL)
  177. {
  178. /* close old console device */
  179. rt_device_close(_console_device);
  180. }
  181. /* set new console device */
  182. rt_device_open(new_device, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_STREAM);
  183. _console_device = new_device;
  184. }
  185. return old_device;
  186. }
  187. RTM_EXPORT(rt_console_set_device);
  188. #endif /* RT_USING_DEVICE */
  189. rt_weak void rt_hw_console_output(const char *str)
  190. {
  191. /* empty console output */
  192. RT_UNUSED(str);
  193. }
  194. RTM_EXPORT(rt_hw_console_output);
  195. #ifdef RT_USING_THREADSAFE_PRINTF
  196. /* system console lock */
  197. static struct rt_spinlock _syscon_lock = RT_SPINLOCK_INIT;
  198. /* lock of kprintf buffer */
  199. static struct rt_spinlock _prbuf_lock = RT_SPINLOCK_INIT;
  200. /* current user of system console */
  201. static rt_thread_t _pr_curr_user;
  202. #ifdef RT_USING_DEBUG
  203. static rt_base_t _pr_critical_level;
  204. #endif /* RT_USING_DEBUG */
  205. /* nested level of current user */
  206. static volatile int _pr_curr_user_nested;
  207. rt_thread_t rt_console_current_user(void)
  208. {
  209. return _pr_curr_user;
  210. }
  211. static void _console_take(void)
  212. {
  213. rt_ubase_t level = rt_spin_lock_irqsave(&_syscon_lock);
  214. rt_thread_t self_thread = rt_thread_self();
  215. rt_base_t critical_level;
  216. RT_UNUSED(critical_level);
  217. while (_pr_curr_user != self_thread)
  218. {
  219. if (_pr_curr_user == RT_NULL)
  220. {
  221. /* no preemption is allowed to avoid dead lock */
  222. critical_level = rt_enter_critical();
  223. #ifdef RT_USING_DEBUG
  224. _pr_critical_level = _syscon_lock.critical_level;
  225. _syscon_lock.critical_level = critical_level;
  226. #endif
  227. _pr_curr_user = self_thread;
  228. break;
  229. }
  230. else
  231. {
  232. rt_spin_unlock_irqrestore(&_syscon_lock, level);
  233. rt_thread_yield();
  234. level = rt_spin_lock_irqsave(&_syscon_lock);
  235. }
  236. }
  237. _pr_curr_user_nested++;
  238. rt_spin_unlock_irqrestore(&_syscon_lock, level);
  239. }
  240. static void _console_release(void)
  241. {
  242. rt_ubase_t level = rt_spin_lock_irqsave(&_syscon_lock);
  243. rt_thread_t self_thread = rt_thread_self();
  244. RT_UNUSED(self_thread);
  245. RT_ASSERT(_pr_curr_user == self_thread);
  246. _pr_curr_user_nested--;
  247. if (!_pr_curr_user_nested)
  248. {
  249. _pr_curr_user = RT_NULL;
  250. #ifdef RT_USING_DEBUG
  251. rt_exit_critical_safe(_syscon_lock.critical_level);
  252. _syscon_lock.critical_level = _pr_critical_level;
  253. #else
  254. rt_exit_critical();
  255. #endif
  256. }
  257. rt_spin_unlock_irqrestore(&_syscon_lock, level);
  258. }
  259. #define CONSOLE_TAKE _console_take()
  260. #define CONSOLE_RELEASE _console_release()
  261. #define PRINTF_BUFFER_TAKE rt_ubase_t level = rt_spin_lock_irqsave(&_prbuf_lock)
  262. #define PRINTF_BUFFER_RELEASE rt_spin_unlock_irqrestore(&_prbuf_lock, level)
  263. #else
  264. #define CONSOLE_TAKE
  265. #define CONSOLE_RELEASE
  266. #define PRINTF_BUFFER_TAKE
  267. #define PRINTF_BUFFER_RELEASE
  268. #endif /* RT_USING_THREADSAFE_PRINTF */
  269. /**
  270. * @brief This function will put string to the console.
  271. *
  272. * @param str is the string output to the console.
  273. */
  274. static void _kputs(const char *str, long len)
  275. {
  276. RT_UNUSED(len);
  277. CONSOLE_TAKE;
  278. #ifdef RT_USING_DEVICE
  279. if (_console_device == RT_NULL)
  280. {
  281. rt_hw_console_output(str);
  282. }
  283. else
  284. {
  285. rt_device_write(_console_device, 0, str, len);
  286. }
  287. #else
  288. rt_hw_console_output(str);
  289. #endif /* RT_USING_DEVICE */
  290. CONSOLE_RELEASE;
  291. }
  292. /**
  293. * @brief This function will put string to the console.
  294. *
  295. * @param str is the string output to the console.
  296. */
  297. void rt_kputs(const char *str)
  298. {
  299. if (!str)
  300. {
  301. return;
  302. }
  303. _kputs(str, rt_strlen(str));
  304. }
  305. /**
  306. * @brief This function will print a formatted string on system console.
  307. *
  308. * @param fmt is the format parameters.
  309. *
  310. * @return The number of characters actually written to buffer.
  311. */
  312. rt_weak int rt_kprintf(const char *fmt, ...)
  313. {
  314. va_list args;
  315. rt_size_t length = 0;
  316. static char rt_log_buf[RT_CONSOLEBUF_SIZE];
  317. va_start(args, fmt);
  318. PRINTF_BUFFER_TAKE;
  319. /* the return value of vsnprintf is the number of bytes that would be
  320. * written to buffer had if the size of the buffer been sufficiently
  321. * large excluding the terminating null byte. If the output string
  322. * would be larger than the rt_log_buf, we have to adjust the output
  323. * length. */
  324. length = rt_vsnprintf(rt_log_buf, sizeof(rt_log_buf) - 1, fmt, args);
  325. if (length > RT_CONSOLEBUF_SIZE - 1)
  326. {
  327. length = RT_CONSOLEBUF_SIZE - 1;
  328. }
  329. _kputs(rt_log_buf, length);
  330. PRINTF_BUFFER_RELEASE;
  331. va_end(args);
  332. return length;
  333. }
  334. RTM_EXPORT(rt_kprintf);
  335. #endif /* RT_USING_CONSOLE */
  336. /**
  337. * @brief Print backtrace of current thread to system console device
  338. *
  339. * @return rt_err_t 0 is success, otherwise a failure
  340. */
  341. rt_weak rt_err_t rt_backtrace(void)
  342. {
  343. struct rt_hw_backtrace_frame frame;
  344. rt_thread_t thread = rt_thread_self();
  345. RT_HW_BACKTRACE_FRAME_GET_SELF(&frame);
  346. if (!frame.fp)
  347. return -RT_EINVAL;
  348. /* we don't want this frame to be printed which is nearly garbage info */
  349. rt_hw_backtrace_frame_unwind(thread, &frame);
  350. return rt_backtrace_frame(thread, &frame);
  351. }
  352. /**
  353. * @brief Print backtrace from frame to system console device
  354. *
  355. * @param thread the thread which frame belongs to
  356. * @param frame where backtrace starts from
  357. * @return rt_err_t 0 is success, otherwise a failure
  358. */
  359. rt_weak rt_err_t rt_backtrace_frame(rt_thread_t thread, struct rt_hw_backtrace_frame *frame)
  360. {
  361. long nesting = 0;
  362. rt_kprintf("please use: addr2line -e rtthread.elf -a -f");
  363. while (nesting < RT_BACKTRACE_LEVEL_MAX_NR)
  364. {
  365. rt_kprintf(" 0x%lx", (rt_ubase_t)frame->pc);
  366. if (rt_hw_backtrace_frame_unwind(thread, frame))
  367. {
  368. break;
  369. }
  370. nesting++;
  371. }
  372. rt_kprintf("\n");
  373. return RT_EOK;
  374. }
  375. /**
  376. * @brief Print backtrace from buffer to system console
  377. *
  378. * @param buffer where traced frames saved
  379. * @param buflen number of items in buffer
  380. * @return rt_err_t 0 is success, otherwise a failure
  381. */
  382. rt_weak rt_err_t rt_backtrace_formatted_print(rt_ubase_t *buffer, long buflen)
  383. {
  384. rt_kprintf("please use: addr2line -e rtthread.elf -a -f");
  385. for (size_t i = 0; i < buflen && buffer[i] != 0; i++)
  386. {
  387. rt_kprintf(" 0x%lx", (rt_ubase_t)buffer[i]);
  388. }
  389. rt_kprintf("\n");
  390. return RT_EOK;
  391. }
  392. /**
  393. * @brief Print backtrace from frame to the given buffer
  394. *
  395. * @param thread the thread which frame belongs to
  396. * @param frame where backtrace starts from. NULL if it's the current one
  397. * @param skip the number of frames to discarded counted from calling function.
  398. * Noted that the inner most frame is always discarded and not counted,
  399. * which is obviously reasonable since that's this function itself.
  400. * @param buffer where traced frames saved
  401. * @param buflen max number of items can be saved in buffer. If there are no more
  402. * than buflen items to be saved, there will be a NULL after the
  403. * last saved item in the buffer.
  404. * @return rt_err_t 0 is success, otherwise a failure
  405. */
  406. rt_weak rt_err_t rt_backtrace_to_buffer(rt_thread_t thread,
  407. struct rt_hw_backtrace_frame *frame,
  408. long skip,
  409. rt_ubase_t *buffer,
  410. long buflen)
  411. {
  412. long nesting = 0;
  413. struct rt_hw_backtrace_frame cur_frame;
  414. if (!thread)
  415. return -RT_EINVAL;
  416. RT_ASSERT(rt_object_get_type(&thread->parent) == RT_Object_Class_Thread);
  417. if (!frame)
  418. {
  419. frame = &cur_frame;
  420. RT_HW_BACKTRACE_FRAME_GET_SELF(frame);
  421. if (!frame->fp)
  422. return -RT_EINVAL;
  423. }
  424. /* discard frames as required. The inner most is always threw. */
  425. do {
  426. rt_hw_backtrace_frame_unwind(thread, frame);
  427. } while (skip-- > 0);
  428. while (nesting < buflen)
  429. {
  430. *buffer++ = (rt_ubase_t)frame->pc;
  431. if (rt_hw_backtrace_frame_unwind(thread, frame))
  432. {
  433. break;
  434. }
  435. nesting++;
  436. }
  437. if (nesting < buflen)
  438. *buffer = RT_NULL;
  439. return RT_EOK;
  440. }
  441. /**
  442. * @brief Print backtrace of a thread to system console device
  443. *
  444. * @param thread which call stack is traced
  445. * @return rt_err_t 0 is success, otherwise a failure
  446. */
  447. rt_err_t rt_backtrace_thread(rt_thread_t thread)
  448. {
  449. rt_err_t rc;
  450. struct rt_hw_backtrace_frame frame;
  451. if (thread)
  452. {
  453. rc = rt_hw_backtrace_frame_get(thread, &frame);
  454. if (rc == RT_EOK)
  455. {
  456. rc = rt_backtrace_frame(thread, &frame);
  457. }
  458. }
  459. else
  460. {
  461. rc = -RT_EINVAL;
  462. }
  463. return rc;
  464. }
  465. #if defined(RT_USING_LIBC) && defined(RT_USING_FINSH)
  466. #include <stdlib.h> /* for string service */
  467. static void cmd_backtrace(int argc, char** argv)
  468. {
  469. rt_ubase_t pid;
  470. char *end_ptr;
  471. if (argc != 2)
  472. {
  473. if (argc == 1)
  474. {
  475. rt_kprintf("[INFO] No thread specified\n"
  476. "[HELP] You can use commands like: backtrace %p\n"
  477. "Printing backtrace of calling stack...\n",
  478. rt_thread_self());
  479. rt_backtrace();
  480. return ;
  481. }
  482. else
  483. {
  484. rt_kprintf("please use: backtrace [thread_address]\n");
  485. return;
  486. }
  487. }
  488. pid = strtoul(argv[1], &end_ptr, 0);
  489. if (end_ptr == argv[1])
  490. {
  491. rt_kprintf("Invalid input: %s\n", argv[1]);
  492. return ;
  493. }
  494. if (pid && rt_object_get_type((void *)pid) == RT_Object_Class_Thread)
  495. {
  496. rt_thread_t target = (rt_thread_t)pid;
  497. rt_kprintf("backtrace %s(0x%lx), from %s\n", target->parent.name, pid, argv[1]);
  498. rt_backtrace_thread(target);
  499. }
  500. else
  501. rt_kprintf("Invalid pid: %ld\n", pid);
  502. }
  503. MSH_CMD_EXPORT_ALIAS(cmd_backtrace, backtrace, print backtrace of a thread);
  504. #endif /* RT_USING_LIBC */
  505. #if defined(RT_USING_HEAP) && !defined(RT_USING_USERHEAP)
  506. #ifdef RT_USING_HOOK
  507. static void (*rt_malloc_hook)(void **ptr, rt_size_t size);
  508. static void (*rt_realloc_entry_hook)(void **ptr, rt_size_t size);
  509. static void (*rt_realloc_exit_hook)(void **ptr, rt_size_t size);
  510. static void (*rt_free_hook)(void **ptr);
  511. /**
  512. * @ingroup Hook
  513. * @{
  514. */
  515. /**
  516. * @brief This function will set a hook function, which will be invoked when a memory
  517. * block is allocated from heap memory.
  518. *
  519. * @param hook the hook function.
  520. */
  521. void rt_malloc_sethook(void (*hook)(void **ptr, rt_size_t size))
  522. {
  523. rt_malloc_hook = hook;
  524. }
  525. /**
  526. * @brief This function will set a hook function, which will be invoked when a memory
  527. * block is allocated from heap memory.
  528. *
  529. * @param hook the hook function.
  530. */
  531. void rt_realloc_set_entry_hook(void (*hook)(void **ptr, rt_size_t size))
  532. {
  533. rt_realloc_entry_hook = hook;
  534. }
  535. /**
  536. * @brief This function will set a hook function, which will be invoked when a memory
  537. * block is allocated from heap memory.
  538. *
  539. * @param hook the hook function.
  540. */
  541. void rt_realloc_set_exit_hook(void (*hook)(void **ptr, rt_size_t size))
  542. {
  543. rt_realloc_exit_hook = hook;
  544. }
  545. /**
  546. * @brief This function will set a hook function, which will be invoked when a memory
  547. * block is released to heap memory.
  548. *
  549. * @param hook the hook function
  550. */
  551. void rt_free_sethook(void (*hook)(void **ptr))
  552. {
  553. rt_free_hook = hook;
  554. }
  555. /**@}*/
  556. #endif /* RT_USING_HOOK */
  557. #if defined(RT_USING_HEAP_ISR)
  558. static struct rt_spinlock _heap_spinlock;
  559. #elif defined(RT_USING_MUTEX)
  560. static struct rt_mutex _lock;
  561. #endif
  562. rt_inline void _heap_lock_init(void)
  563. {
  564. #if defined(RT_USING_HEAP_ISR)
  565. rt_spin_lock_init(&_heap_spinlock);
  566. #elif defined(RT_USING_MUTEX)
  567. rt_mutex_init(&_lock, "heap", RT_IPC_FLAG_PRIO);
  568. #endif
  569. }
  570. rt_inline rt_base_t _heap_lock(void)
  571. {
  572. #if defined(RT_USING_HEAP_ISR)
  573. return rt_spin_lock_irqsave(&_heap_spinlock);
  574. #elif defined(RT_USING_MUTEX)
  575. if (rt_thread_self())
  576. return rt_mutex_take(&_lock, RT_WAITING_FOREVER);
  577. else
  578. return RT_EOK;
  579. #else
  580. rt_enter_critical();
  581. return RT_EOK;
  582. #endif
  583. }
  584. rt_inline void _heap_unlock(rt_base_t level)
  585. {
  586. #if defined(RT_USING_HEAP_ISR)
  587. rt_spin_unlock_irqrestore(&_heap_spinlock, level);
  588. #elif defined(RT_USING_MUTEX)
  589. RT_ASSERT(level == RT_EOK);
  590. if (rt_thread_self())
  591. rt_mutex_release(&_lock);
  592. #else
  593. rt_exit_critical();
  594. #endif
  595. }
  596. #ifdef RT_USING_UTESTCASES
  597. /* export to utest to observe the inner statements */
  598. #ifdef _MSC_VER
  599. #define rt_heap_lock() _heap_lock()
  600. #define rt_heap_unlock() _heap_unlock()
  601. #else
  602. rt_base_t rt_heap_lock(void) __attribute__((alias("_heap_lock")));
  603. void rt_heap_unlock(rt_base_t level) __attribute__((alias("_heap_unlock")));
  604. #endif /* _MSC_VER */
  605. #endif
  606. #if defined(RT_USING_SMALL_MEM_AS_HEAP)
  607. static rt_smem_t system_heap;
  608. rt_inline void _smem_info(rt_size_t *total,
  609. rt_size_t *used, rt_size_t *max_used)
  610. {
  611. if (total)
  612. *total = system_heap->total;
  613. if (used)
  614. *used = system_heap->used;
  615. if (max_used)
  616. *max_used = system_heap->max;
  617. }
  618. #define _MEM_INIT(_name, _start, _size) \
  619. system_heap = rt_smem_init(_name, _start, _size)
  620. #define _MEM_MALLOC(_size) \
  621. rt_smem_alloc(system_heap, _size)
  622. #define _MEM_REALLOC(_ptr, _newsize)\
  623. rt_smem_realloc(system_heap, _ptr, _newsize)
  624. #define _MEM_FREE(_ptr) \
  625. rt_smem_free(_ptr)
  626. #define _MEM_INFO(_total, _used, _max) \
  627. _smem_info(_total, _used, _max)
  628. #elif defined(RT_USING_MEMHEAP_AS_HEAP)
  629. static struct rt_memheap system_heap;
  630. void *_memheap_alloc(struct rt_memheap *heap, rt_size_t size);
  631. void _memheap_free(void *rmem);
  632. void *_memheap_realloc(struct rt_memheap *heap, void *rmem, rt_size_t newsize);
  633. #define _MEM_INIT(_name, _start, _size) \
  634. do {\
  635. rt_memheap_init(&system_heap, _name, _start, _size); \
  636. system_heap.locked = RT_TRUE; \
  637. } while(0)
  638. #define _MEM_MALLOC(_size) \
  639. _memheap_alloc(&system_heap, _size)
  640. #define _MEM_REALLOC(_ptr, _newsize) \
  641. _memheap_realloc(&system_heap, _ptr, _newsize)
  642. #define _MEM_FREE(_ptr) \
  643. _memheap_free(_ptr)
  644. #define _MEM_INFO(_total, _used, _max) \
  645. rt_memheap_info(&system_heap, _total, _used, _max)
  646. #elif defined(RT_USING_SLAB_AS_HEAP)
  647. static rt_slab_t system_heap;
  648. rt_inline void _slab_info(rt_size_t *total,
  649. rt_size_t *used, rt_size_t *max_used)
  650. {
  651. if (total)
  652. *total = system_heap->total;
  653. if (used)
  654. *used = system_heap->used;
  655. if (max_used)
  656. *max_used = system_heap->max;
  657. }
  658. #define _MEM_INIT(_name, _start, _size) \
  659. system_heap = rt_slab_init(_name, _start, _size)
  660. #define _MEM_MALLOC(_size) \
  661. rt_slab_alloc(system_heap, _size)
  662. #define _MEM_REALLOC(_ptr, _newsize) \
  663. rt_slab_realloc(system_heap, _ptr, _newsize)
  664. #define _MEM_FREE(_ptr) \
  665. rt_slab_free(system_heap, _ptr)
  666. #define _MEM_INFO _slab_info
  667. #else
  668. #define _MEM_INIT(...)
  669. #define _MEM_MALLOC(...) RT_NULL
  670. #define _MEM_REALLOC(...) RT_NULL
  671. #define _MEM_FREE(...)
  672. #define _MEM_INFO(...)
  673. #endif
  674. /**
  675. * @brief This function will do the generic system heap initialization.
  676. *
  677. * @param begin_addr the beginning address of system page.
  678. *
  679. * @param end_addr the end address of system page.
  680. */
  681. void rt_system_heap_init_generic(void *begin_addr, void *end_addr)
  682. {
  683. rt_ubase_t begin_align = RT_ALIGN((rt_ubase_t)begin_addr, RT_ALIGN_SIZE);
  684. rt_ubase_t end_align = RT_ALIGN_DOWN((rt_ubase_t)end_addr, RT_ALIGN_SIZE);
  685. RT_ASSERT(end_align > begin_align);
  686. /* Initialize system memory heap */
  687. _MEM_INIT("heap", (void *)begin_align, end_align - begin_align);
  688. /* Initialize multi thread contention lock */
  689. _heap_lock_init();
  690. }
  691. /**
  692. * @brief This function will init system heap. User can override this API to
  693. * complete other works, like heap sanitizer initialization.
  694. *
  695. * @param begin_addr the beginning address of system page.
  696. *
  697. * @param end_addr the end address of system page.
  698. */
  699. rt_weak void rt_system_heap_init(void *begin_addr, void *end_addr)
  700. {
  701. rt_system_heap_init_generic(begin_addr, end_addr);
  702. }
  703. /**
  704. * @brief Allocate a block of memory with a minimum of 'size' bytes.
  705. *
  706. * @param size is the minimum size of the requested block in bytes.
  707. *
  708. * @return the pointer to allocated memory or NULL if no free memory was found.
  709. */
  710. rt_weak void *rt_malloc(rt_size_t size)
  711. {
  712. rt_base_t level;
  713. void *ptr;
  714. /* Enter critical zone */
  715. level = _heap_lock();
  716. /* allocate memory block from system heap */
  717. ptr = _MEM_MALLOC(size);
  718. /* Exit critical zone */
  719. _heap_unlock(level);
  720. /* call 'rt_malloc' hook */
  721. RT_OBJECT_HOOK_CALL(rt_malloc_hook, (&ptr, size));
  722. return ptr;
  723. }
  724. RTM_EXPORT(rt_malloc);
  725. /**
  726. * @brief This function will change the size of previously allocated memory block.
  727. *
  728. * @param ptr is the pointer to memory allocated by rt_malloc.
  729. *
  730. * @param newsize is the required new size.
  731. *
  732. * @return the changed memory block address.
  733. */
  734. rt_weak void *rt_realloc(void *ptr, rt_size_t newsize)
  735. {
  736. rt_base_t level;
  737. void *nptr;
  738. /* Entry hook */
  739. RT_OBJECT_HOOK_CALL(rt_realloc_entry_hook, (&ptr, newsize));
  740. /* Enter critical zone */
  741. level = _heap_lock();
  742. /* Change the size of previously allocated memory block */
  743. nptr = _MEM_REALLOC(ptr, newsize);
  744. /* Exit critical zone */
  745. _heap_unlock(level);
  746. /* Exit hook */
  747. RT_OBJECT_HOOK_CALL(rt_realloc_exit_hook, (&nptr, newsize));
  748. return nptr;
  749. }
  750. RTM_EXPORT(rt_realloc);
  751. /**
  752. * @brief This function will contiguously allocate enough space for count objects
  753. * that are size bytes of memory each and returns a pointer to the allocated
  754. * memory.
  755. *
  756. * @note The allocated memory is filled with bytes of value zero.
  757. *
  758. * @param count is the number of objects to allocate.
  759. *
  760. * @param size is the size of one object to allocate.
  761. *
  762. * @return pointer to allocated memory / NULL pointer if there is an error.
  763. */
  764. rt_weak void *rt_calloc(rt_size_t count, rt_size_t size)
  765. {
  766. void *p;
  767. /* allocate 'count' objects of size 'size' */
  768. p = rt_malloc(count * size);
  769. /* zero the memory */
  770. if (p)
  771. {
  772. rt_memset(p, 0, count * size);
  773. }
  774. return p;
  775. }
  776. RTM_EXPORT(rt_calloc);
  777. /**
  778. * @brief This function will release the previously allocated memory block by
  779. * rt_malloc. The released memory block is taken back to system heap.
  780. *
  781. * @param ptr the address of memory which will be released.
  782. */
  783. rt_weak void rt_free(void *ptr)
  784. {
  785. rt_base_t level;
  786. /* call 'rt_free' hook */
  787. RT_OBJECT_HOOK_CALL(rt_free_hook, (&ptr));
  788. /* NULL check */
  789. if (ptr == RT_NULL) return;
  790. /* Enter critical zone */
  791. level = _heap_lock();
  792. _MEM_FREE(ptr);
  793. /* Exit critical zone */
  794. _heap_unlock(level);
  795. }
  796. RTM_EXPORT(rt_free);
  797. /**
  798. * @brief This function will caculate the total memory, the used memory, and
  799. * the max used memory.
  800. *
  801. * @param total is a pointer to get the total size of the memory.
  802. *
  803. * @param used is a pointer to get the size of memory used.
  804. *
  805. * @param max_used is a pointer to get the maximum memory used.
  806. */
  807. rt_weak void rt_memory_info(rt_size_t *total,
  808. rt_size_t *used,
  809. rt_size_t *max_used)
  810. {
  811. rt_base_t level;
  812. /* Enter critical zone */
  813. level = _heap_lock();
  814. _MEM_INFO(total, used, max_used);
  815. /* Exit critical zone */
  816. _heap_unlock(level);
  817. }
  818. RTM_EXPORT(rt_memory_info);
  819. #if defined(RT_USING_SLAB) && defined(RT_USING_SLAB_AS_HEAP)
  820. void *rt_page_alloc(rt_size_t npages)
  821. {
  822. rt_base_t level;
  823. void *ptr;
  824. /* Enter critical zone */
  825. level = _heap_lock();
  826. /* alloc page */
  827. ptr = rt_slab_page_alloc(system_heap, npages);
  828. /* Exit critical zone */
  829. _heap_unlock(level);
  830. return ptr;
  831. }
  832. void rt_page_free(void *addr, rt_size_t npages)
  833. {
  834. rt_base_t level;
  835. /* Enter critical zone */
  836. level = _heap_lock();
  837. /* free page */
  838. rt_slab_page_free(system_heap, addr, npages);
  839. /* Exit critical zone */
  840. _heap_unlock(level);
  841. }
  842. #endif
  843. /**
  844. * @brief This function allocates a memory block, which address is aligned to the
  845. * specified alignment size.
  846. *
  847. * @param size is the allocated memory block size.
  848. *
  849. * @param align is the alignment size.
  850. *
  851. * @return The memory block address was returned successfully, otherwise it was
  852. * returned empty RT_NULL.
  853. */
  854. rt_weak void *rt_malloc_align(rt_size_t size, rt_size_t align)
  855. {
  856. void *ptr = RT_NULL;
  857. void *align_ptr = RT_NULL;
  858. int uintptr_size = 0;
  859. rt_size_t align_size = 0;
  860. /* sizeof pointer */
  861. uintptr_size = sizeof(void*);
  862. uintptr_size -= 1;
  863. /* align the alignment size to uintptr size byte */
  864. align = ((align + uintptr_size) & ~uintptr_size);
  865. /* get total aligned size */
  866. align_size = ((size + uintptr_size) & ~uintptr_size) + align;
  867. /* allocate memory block from heap */
  868. ptr = rt_malloc(align_size);
  869. if (ptr != RT_NULL)
  870. {
  871. /* the allocated memory block is aligned */
  872. if (((rt_ubase_t)ptr & (align - 1)) == 0)
  873. {
  874. align_ptr = (void *)((rt_ubase_t)ptr + align);
  875. }
  876. else
  877. {
  878. align_ptr = (void *)(((rt_ubase_t)ptr + (align - 1)) & ~(align - 1));
  879. }
  880. /* set the pointer before alignment pointer to the real pointer */
  881. *((rt_ubase_t *)((rt_ubase_t)align_ptr - sizeof(void *))) = (rt_ubase_t)ptr;
  882. ptr = align_ptr;
  883. }
  884. return ptr;
  885. }
  886. RTM_EXPORT(rt_malloc_align);
  887. /**
  888. * @brief This function release the memory block, which is allocated by
  889. * rt_malloc_align function and address is aligned.
  890. *
  891. * @param ptr is the memory block pointer.
  892. */
  893. rt_weak void rt_free_align(void *ptr)
  894. {
  895. void *real_ptr = RT_NULL;
  896. /* NULL check */
  897. if (ptr == RT_NULL) return;
  898. real_ptr = (void *) * (rt_ubase_t *)((rt_ubase_t)ptr - sizeof(void *));
  899. rt_free(real_ptr);
  900. }
  901. RTM_EXPORT(rt_free_align);
  902. #endif /* RT_USING_HEAP */
  903. #ifndef RT_USING_CPU_FFS
  904. #ifdef RT_USING_TINY_FFS
  905. const rt_uint8_t __lowest_bit_bitmap[] =
  906. {
  907. /* 0 - 7 */ 0, 1, 2, 27, 3, 24, 28, 32,
  908. /* 8 - 15 */ 4, 17, 25, 31, 29, 12, 32, 14,
  909. /* 16 - 23 */ 5, 8, 18, 32, 26, 23, 32, 16,
  910. /* 24 - 31 */ 30, 11, 13, 7, 32, 22, 15, 10,
  911. /* 32 - 36 */ 6, 21, 9, 20, 19
  912. };
  913. /**
  914. * @brief This function finds the first bit set (beginning with the least significant bit)
  915. * in value and return the index of that bit.
  916. *
  917. * Bits are numbered starting at 1 (the least significant bit). A return value of
  918. * zero from any of these functions means that the argument was zero.
  919. *
  920. * @param value is the value to find the first bit set in.
  921. *
  922. * @return return the index of the first bit set. If value is 0, then this function
  923. * shall return 0.
  924. */
  925. int __rt_ffs(int value)
  926. {
  927. return __lowest_bit_bitmap[(rt_uint32_t)(value & (value - 1) ^ value) % 37];
  928. }
  929. #else
  930. const rt_uint8_t __lowest_bit_bitmap[] =
  931. {
  932. /* 00 */ 0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  933. /* 10 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  934. /* 20 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  935. /* 30 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  936. /* 40 */ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  937. /* 50 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  938. /* 60 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  939. /* 70 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  940. /* 80 */ 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  941. /* 90 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  942. /* A0 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  943. /* B0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  944. /* C0 */ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  945. /* D0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  946. /* E0 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  947. /* F0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
  948. };
  949. /**
  950. * @brief This function finds the first bit set (beginning with the least significant bit)
  951. * in value and return the index of that bit.
  952. *
  953. * Bits are numbered starting at 1 (the least significant bit). A return value of
  954. * zero from any of these functions means that the argument was zero.
  955. *
  956. * @param value is the value to find the first bit set in.
  957. *
  958. * @return Return the index of the first bit set. If value is 0, then this function
  959. * shall return 0.
  960. */
  961. int __rt_ffs(int value)
  962. {
  963. if (value == 0)
  964. {
  965. return 0;
  966. }
  967. if (value & 0xff)
  968. {
  969. return __lowest_bit_bitmap[value & 0xff] + 1;
  970. }
  971. if (value & 0xff00)
  972. {
  973. return __lowest_bit_bitmap[(value & 0xff00) >> 8] + 9;
  974. }
  975. if (value & 0xff0000)
  976. {
  977. return __lowest_bit_bitmap[(value & 0xff0000) >> 16] + 17;
  978. }
  979. return __lowest_bit_bitmap[(value & 0xff000000) >> 24] + 25;
  980. }
  981. #endif /* RT_USING_TINY_FFS */
  982. #endif /* RT_USING_CPU_FFS */
  983. #ifdef RT_DEBUGING_ASSERT
  984. /* RT_ASSERT(EX)'s hook */
  985. void (*rt_assert_hook)(const char *ex, const char *func, rt_size_t line);
  986. /**
  987. * This function will set a hook function to RT_ASSERT(EX). It will run when the expression is false.
  988. *
  989. * @param hook is the hook function.
  990. */
  991. void rt_assert_set_hook(void (*hook)(const char *ex, const char *func, rt_size_t line))
  992. {
  993. rt_assert_hook = hook;
  994. }
  995. /**
  996. * The RT_ASSERT function.
  997. *
  998. * @param ex_string is the assertion condition string.
  999. *
  1000. * @param func is the function name when assertion.
  1001. *
  1002. * @param line is the file line number when assertion.
  1003. */
  1004. void rt_assert_handler(const char *ex_string, const char *func, rt_size_t line)
  1005. {
  1006. volatile char dummy = 0;
  1007. if (rt_assert_hook == RT_NULL)
  1008. {
  1009. #ifdef RT_USING_MODULE
  1010. if (dlmodule_self())
  1011. {
  1012. /* close assertion module */
  1013. dlmodule_exit(-1);
  1014. }
  1015. else
  1016. #endif /*RT_USING_MODULE*/
  1017. {
  1018. rt_kprintf("(%s) assertion failed at function:%s, line number:%d \n", ex_string, func, line);
  1019. rt_backtrace();
  1020. while (dummy == 0);
  1021. }
  1022. }
  1023. else
  1024. {
  1025. rt_assert_hook(ex_string, func, line);
  1026. }
  1027. }
  1028. RTM_EXPORT(rt_assert_handler);
  1029. #endif /* RT_DEBUGING_ASSERT */
  1030. /**@}*/