kservice.c 32 KB

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