kservice.c 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335
  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-12-10 xqyjlj perf rt_hw_interrupt_disable/enable, fix memheap lock
  29. */
  30. #include <rtthread.h>
  31. #include <rthw.h>
  32. #define DBG_TAG "kernel.service"
  33. #ifdef RT_DEBUG_DEVICE
  34. #define DBG_LVL DBG_LOG
  35. #else
  36. #define DBG_LVL DBG_WARNING
  37. #endif /* defined (RT_DEBUG_DEVICE) */
  38. #include <rtdbg.h>
  39. #ifdef RT_USING_MODULE
  40. #include <dlmodule.h>
  41. #endif /* RT_USING_MODULE */
  42. #ifdef RT_USING_SMART
  43. #include <lwp.h>
  44. #include <lwp_user_mm.h>
  45. #include <console.h>
  46. #endif
  47. /**
  48. * @addtogroup KernelService
  49. * @{
  50. */
  51. /* global errno in RT-Thread */
  52. static volatile int __rt_errno;
  53. #if defined(RT_USING_DEVICE) && defined(RT_USING_CONSOLE)
  54. static rt_device_t _console_device = RT_NULL;
  55. #endif
  56. rt_weak void rt_hw_us_delay(rt_uint32_t us)
  57. {
  58. (void) us;
  59. LOG_W("rt_hw_us_delay() doesn't support for this board."
  60. "Please consider implementing rt_hw_us_delay() in another file.");
  61. }
  62. rt_weak void rt_hw_cpu_reset(void)
  63. {
  64. LOG_W("rt_hw_cpu_reset() doesn't support for this board."
  65. "Please consider implementing rt_hw_cpu_reset() in another file.");
  66. return;
  67. }
  68. rt_weak void rt_hw_cpu_shutdown(void)
  69. {
  70. rt_base_t level;
  71. LOG_I("CPU shutdown...");
  72. LOG_W("Using default rt_hw_cpu_shutdown()."
  73. "Please consider implementing rt_hw_cpu_reset() in another file.");
  74. level = rt_hw_interrupt_disable();
  75. while (level)
  76. {
  77. RT_ASSERT(RT_NULL);
  78. }
  79. return;
  80. }
  81. rt_weak rt_err_t rt_hw_backtrace_frame_get(rt_thread_t thread, struct rt_hw_backtrace_frame *frame)
  82. {
  83. RT_UNUSED(thread);
  84. RT_UNUSED(frame);
  85. LOG_W("%s is not implemented", __func__);
  86. return -RT_ENOSYS;
  87. }
  88. rt_weak rt_err_t rt_hw_backtrace_frame_unwind(rt_thread_t thread, struct rt_hw_backtrace_frame *frame)
  89. {
  90. RT_UNUSED(thread);
  91. RT_UNUSED(frame);
  92. LOG_W("%s is not implemented", __func__);
  93. return -RT_ENOSYS;
  94. }
  95. rt_weak const char *rt_hw_cpu_arch(void)
  96. {
  97. return "unknown";
  98. }
  99. struct _errno_str_t
  100. {
  101. rt_err_t error;
  102. const char *str;
  103. };
  104. static struct _errno_str_t rt_errno_strs[] =
  105. {
  106. {RT_EOK , "OK "},
  107. {RT_ERROR , "ERROR "},
  108. {RT_ETIMEOUT, "ETIMOUT"},
  109. {RT_EFULL , "ERSFULL"},
  110. {RT_EEMPTY , "ERSEPTY"},
  111. {RT_ENOMEM , "ENOMEM "},
  112. {RT_ENOSYS , "ENOSYS "},
  113. {RT_EBUSY , "EBUSY "},
  114. {RT_EIO , "EIO "},
  115. {RT_EINTR , "EINTRPT"},
  116. {RT_EINVAL , "EINVAL "},
  117. {RT_ENOENT , "ENOENT "},
  118. {RT_ENOSPC , "ENOSPC "},
  119. {RT_EPERM , "EPERM "},
  120. {RT_ETRAP , "ETRAP "},
  121. };
  122. /**
  123. * @brief This function return a pointer to a string that contains the
  124. * message of error.
  125. *
  126. * @param error the errorno code
  127. * @return a point to error message string
  128. */
  129. const char *rt_strerror(rt_err_t error)
  130. {
  131. int i = 0;
  132. if (error < 0)
  133. error = -error;
  134. for (i = 0; i < sizeof(rt_errno_strs) / sizeof(rt_errno_strs[0]); i++)
  135. {
  136. if (rt_errno_strs[i].error == error)
  137. return rt_errno_strs[i].str;
  138. }
  139. return "EUNKNOW";
  140. }
  141. RTM_EXPORT(rt_strerror);
  142. /**
  143. * @brief This function gets the global errno for the current thread.
  144. *
  145. * @return errno
  146. */
  147. rt_err_t rt_get_errno(void)
  148. {
  149. rt_thread_t tid = RT_NULL;
  150. if (rt_interrupt_get_nest() != 0)
  151. {
  152. /* it's in interrupt context */
  153. return __rt_errno;
  154. }
  155. tid = rt_thread_self();
  156. if (tid == RT_NULL)
  157. {
  158. return __rt_errno;
  159. }
  160. return tid->error;
  161. }
  162. RTM_EXPORT(rt_get_errno);
  163. /**
  164. * @brief This function sets the global errno for the current thread.
  165. *
  166. * @param error is the errno shall be set.
  167. */
  168. void rt_set_errno(rt_err_t error)
  169. {
  170. rt_thread_t tid = RT_NULL;
  171. if (rt_interrupt_get_nest() != 0)
  172. {
  173. /* it's in interrupt context */
  174. __rt_errno = error;
  175. return;
  176. }
  177. tid = rt_thread_self();
  178. if (tid == RT_NULL)
  179. {
  180. __rt_errno = error;
  181. return;
  182. }
  183. tid->error = error;
  184. }
  185. RTM_EXPORT(rt_set_errno);
  186. /**
  187. * @brief This function returns the address of the current thread errno.
  188. *
  189. * @return The errno address.
  190. */
  191. int *_rt_errno(void)
  192. {
  193. rt_thread_t tid = RT_NULL;
  194. if (rt_interrupt_get_nest() != 0)
  195. {
  196. return (int *)&__rt_errno;
  197. }
  198. tid = rt_thread_self();
  199. if (tid != RT_NULL)
  200. {
  201. return (int *) & (tid->error);
  202. }
  203. return (int *)&__rt_errno;
  204. }
  205. RTM_EXPORT(_rt_errno);
  206. #ifndef RT_KSERVICE_USING_STDLIB_MEMORY
  207. /**
  208. * @brief This function will set the content of memory to specified value.
  209. *
  210. * @param s is the address of source memory, point to the memory block to be filled.
  211. *
  212. * @param c is the value to be set. The value is passed in int form, but the function
  213. * uses the unsigned character form of the value when filling the memory block.
  214. *
  215. * @param count number of bytes to be set.
  216. *
  217. * @return The address of source memory.
  218. */
  219. rt_weak void *rt_memset(void *s, int c, rt_ubase_t count)
  220. {
  221. #ifdef RT_KSERVICE_USING_TINY_SIZE
  222. char *xs = (char *)s;
  223. while (count--)
  224. *xs++ = c;
  225. return s;
  226. #else
  227. #define LBLOCKSIZE (sizeof(rt_ubase_t))
  228. #define UNALIGNED(X) ((long)X & (LBLOCKSIZE - 1))
  229. #define TOO_SMALL(LEN) ((LEN) < LBLOCKSIZE)
  230. unsigned int i = 0;
  231. char *m = (char *)s;
  232. unsigned long buffer = 0;
  233. unsigned long *aligned_addr = RT_NULL;
  234. unsigned char d = (unsigned int)c & (unsigned char)(-1); /* To avoid sign extension, copy C to an
  235. unsigned variable. (unsigned)((char)(-1))=0xFF for 8bit and =0xFFFF for 16bit: word independent */
  236. RT_ASSERT(LBLOCKSIZE == 2 || LBLOCKSIZE == 4 || LBLOCKSIZE == 8);
  237. if (!TOO_SMALL(count) && !UNALIGNED(s))
  238. {
  239. /* If we get this far, we know that count is large and s is word-aligned. */
  240. aligned_addr = (unsigned long *)s;
  241. /* Store d into each char sized location in buffer so that
  242. * we can set large blocks quickly.
  243. */
  244. for (i = 0; i < LBLOCKSIZE; i++)
  245. {
  246. *(((unsigned char *)&buffer)+i) = d;
  247. }
  248. while (count >= LBLOCKSIZE * 4)
  249. {
  250. *aligned_addr++ = buffer;
  251. *aligned_addr++ = buffer;
  252. *aligned_addr++ = buffer;
  253. *aligned_addr++ = buffer;
  254. count -= 4 * LBLOCKSIZE;
  255. }
  256. while (count >= LBLOCKSIZE)
  257. {
  258. *aligned_addr++ = buffer;
  259. count -= LBLOCKSIZE;
  260. }
  261. /* Pick up the remainder with a bytewise loop. */
  262. m = (char *)aligned_addr;
  263. }
  264. while (count--)
  265. {
  266. *m++ = (char)d;
  267. }
  268. return s;
  269. #undef LBLOCKSIZE
  270. #undef UNALIGNED
  271. #undef TOO_SMALL
  272. #endif /* RT_KSERVICE_USING_TINY_SIZE */
  273. }
  274. RTM_EXPORT(rt_memset);
  275. /**
  276. * @brief This function will copy memory content from source address to destination address.
  277. *
  278. * @param dst is the address of destination memory, points to the copied content.
  279. *
  280. * @param src is the address of source memory, pointing to the data source to be copied.
  281. *
  282. * @param count is the copied length.
  283. *
  284. * @return The address of destination memory
  285. */
  286. rt_weak void *rt_memcpy(void *dst, const void *src, rt_ubase_t count)
  287. {
  288. #ifdef RT_KSERVICE_USING_TINY_SIZE
  289. char *tmp = (char *)dst, *s = (char *)src;
  290. rt_ubase_t len = 0;
  291. if (tmp <= s || tmp > (s + count))
  292. {
  293. while (count--)
  294. *tmp ++ = *s ++;
  295. }
  296. else
  297. {
  298. for (len = count; len > 0; len --)
  299. tmp[len - 1] = s[len - 1];
  300. }
  301. return dst;
  302. #else
  303. #define UNALIGNED(X, Y) \
  304. (((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
  305. #define BIGBLOCKSIZE (sizeof (long) << 2)
  306. #define LITTLEBLOCKSIZE (sizeof (long))
  307. #define TOO_SMALL(LEN) ((LEN) < BIGBLOCKSIZE)
  308. char *dst_ptr = (char *)dst;
  309. char *src_ptr = (char *)src;
  310. long *aligned_dst = RT_NULL;
  311. long *aligned_src = RT_NULL;
  312. rt_ubase_t len = count;
  313. /* If the size is small, or either SRC or DST is unaligned,
  314. then punt into the byte copy loop. This should be rare. */
  315. if (!TOO_SMALL(len) && !UNALIGNED(src_ptr, dst_ptr))
  316. {
  317. aligned_dst = (long *)dst_ptr;
  318. aligned_src = (long *)src_ptr;
  319. /* Copy 4X long words at a time if possible. */
  320. while (len >= BIGBLOCKSIZE)
  321. {
  322. *aligned_dst++ = *aligned_src++;
  323. *aligned_dst++ = *aligned_src++;
  324. *aligned_dst++ = *aligned_src++;
  325. *aligned_dst++ = *aligned_src++;
  326. len -= BIGBLOCKSIZE;
  327. }
  328. /* Copy one long word at a time if possible. */
  329. while (len >= LITTLEBLOCKSIZE)
  330. {
  331. *aligned_dst++ = *aligned_src++;
  332. len -= LITTLEBLOCKSIZE;
  333. }
  334. /* Pick up any residual with a byte copier. */
  335. dst_ptr = (char *)aligned_dst;
  336. src_ptr = (char *)aligned_src;
  337. }
  338. while (len--)
  339. *dst_ptr++ = *src_ptr++;
  340. return dst;
  341. #undef UNALIGNED
  342. #undef BIGBLOCKSIZE
  343. #undef LITTLEBLOCKSIZE
  344. #undef TOO_SMALL
  345. #endif /* RT_KSERVICE_USING_TINY_SIZE */
  346. }
  347. RTM_EXPORT(rt_memcpy);
  348. /**
  349. * @brief This function will move memory content from source address to destination
  350. * address. If the destination memory does not overlap with the source memory,
  351. * the function is the same as memcpy().
  352. *
  353. * @param dest is the address of destination memory, points to the copied content.
  354. *
  355. * @param src is the address of source memory, point to the data source to be copied.
  356. *
  357. * @param n is the copied length.
  358. *
  359. * @return The address of destination memory.
  360. */
  361. void *rt_memmove(void *dest, const void *src, rt_size_t n)
  362. {
  363. char *tmp = (char *)dest, *s = (char *)src;
  364. if (s < tmp && tmp < s + n)
  365. {
  366. tmp += n;
  367. s += n;
  368. while (n--)
  369. *(--tmp) = *(--s);
  370. }
  371. else
  372. {
  373. while (n--)
  374. *tmp++ = *s++;
  375. }
  376. return dest;
  377. }
  378. RTM_EXPORT(rt_memmove);
  379. /**
  380. * @brief This function will compare two areas of memory.
  381. *
  382. * @param cs is a block of memory.
  383. *
  384. * @param ct is another block of memory.
  385. *
  386. * @param count is the size of the area.
  387. *
  388. * @return Compare the results:
  389. * If the result < 0, cs is smaller than ct.
  390. * If the result > 0, cs is greater than ct.
  391. * If the result = 0, cs is equal to ct.
  392. */
  393. rt_int32_t rt_memcmp(const void *cs, const void *ct, rt_size_t count)
  394. {
  395. const unsigned char *su1 = RT_NULL, *su2 = RT_NULL;
  396. int res = 0;
  397. for (su1 = (const unsigned char *)cs, su2 = (const unsigned char *)ct; 0 < count; ++su1, ++su2, count--)
  398. if ((res = *su1 - *su2) != 0)
  399. break;
  400. return res;
  401. }
  402. RTM_EXPORT(rt_memcmp);
  403. #endif /* RT_KSERVICE_USING_STDLIB_MEMORY*/
  404. #ifndef RT_KSERVICE_USING_STDLIB
  405. /**
  406. * @brief This function will return the first occurrence of a string, without the
  407. * terminator '\0'.
  408. *
  409. * @param s1 is the source string.
  410. *
  411. * @param s2 is the find string.
  412. *
  413. * @return The first occurrence of a s2 in s1, or RT_NULL if no found.
  414. */
  415. char *rt_strstr(const char *s1, const char *s2)
  416. {
  417. int l1 = 0, l2 = 0;
  418. l2 = rt_strlen(s2);
  419. if (!l2)
  420. {
  421. return (char *)s1;
  422. }
  423. l1 = rt_strlen(s1);
  424. while (l1 >= l2)
  425. {
  426. l1 --;
  427. if (!rt_memcmp(s1, s2, l2))
  428. {
  429. return (char *)s1;
  430. }
  431. s1 ++;
  432. }
  433. return RT_NULL;
  434. }
  435. RTM_EXPORT(rt_strstr);
  436. /**
  437. * @brief This function will compare two strings while ignoring differences in case
  438. *
  439. * @param a is the string to be compared.
  440. *
  441. * @param b is the string to be compared.
  442. *
  443. * @return Compare the results:
  444. * If the result < 0, a is smaller than a.
  445. * If the result > 0, a is greater than a.
  446. * If the result = 0, a is equal to a.
  447. */
  448. rt_int32_t rt_strcasecmp(const char *a, const char *b)
  449. {
  450. int ca = 0, cb = 0;
  451. do
  452. {
  453. ca = *a++ & 0xff;
  454. cb = *b++ & 0xff;
  455. if (ca >= 'A' && ca <= 'Z')
  456. ca += 'a' - 'A';
  457. if (cb >= 'A' && cb <= 'Z')
  458. cb += 'a' - 'A';
  459. }
  460. while (ca == cb && ca != '\0');
  461. return ca - cb;
  462. }
  463. RTM_EXPORT(rt_strcasecmp);
  464. /**
  465. * @brief This function will copy string no more than n bytes.
  466. *
  467. * @param dst points to the address used to store the copied content.
  468. *
  469. * @param src is the string to be copied.
  470. *
  471. * @param n is the maximum copied length.
  472. *
  473. * @return The address where the copied content is stored.
  474. */
  475. char *rt_strncpy(char *dst, const char *src, rt_size_t n)
  476. {
  477. if (n != 0)
  478. {
  479. char *d = dst;
  480. const char *s = src;
  481. do
  482. {
  483. if ((*d++ = *s++) == 0)
  484. {
  485. /* NUL pad the remaining n-1 bytes */
  486. while (--n != 0)
  487. {
  488. *d++ = 0;
  489. }
  490. break;
  491. }
  492. } while (--n != 0);
  493. }
  494. return (dst);
  495. }
  496. RTM_EXPORT(rt_strncpy);
  497. /**
  498. * @brief This function will copy string.
  499. *
  500. * @param dst points to the address used to store the copied content.
  501. *
  502. * @param src is the string to be copied.
  503. *
  504. * @return The address where the copied content is stored.
  505. */
  506. char *rt_strcpy(char *dst, const char *src)
  507. {
  508. char *dest = dst;
  509. while (*src != '\0')
  510. {
  511. *dst = *src;
  512. dst++;
  513. src++;
  514. }
  515. *dst = '\0';
  516. return dest;
  517. }
  518. RTM_EXPORT(rt_strcpy);
  519. /**
  520. * @brief This function will compare two strings with specified maximum length.
  521. *
  522. * @param cs is the string to be compared.
  523. *
  524. * @param ct is the string to be compared.
  525. *
  526. * @param count is the maximum compare length.
  527. *
  528. * @return Compare the results:
  529. * If the result < 0, cs is smaller than ct.
  530. * If the result > 0, cs is greater than ct.
  531. * If the result = 0, cs is equal to ct.
  532. */
  533. rt_int32_t rt_strncmp(const char *cs, const char *ct, rt_size_t count)
  534. {
  535. signed char __res = 0;
  536. while (count)
  537. {
  538. if ((__res = *cs - *ct++) != 0 || !*cs++)
  539. {
  540. break;
  541. }
  542. count --;
  543. }
  544. return __res;
  545. }
  546. RTM_EXPORT(rt_strncmp);
  547. /**
  548. * @brief This function will compare two strings without specified length.
  549. *
  550. * @param cs is the string to be compared.
  551. *
  552. * @param ct is the string to be compared.
  553. *
  554. * @return Compare the results:
  555. * If the result < 0, cs is smaller than ct.
  556. * If the result > 0, cs is greater than ct.
  557. * If the result = 0, cs is equal to ct.
  558. */
  559. rt_int32_t rt_strcmp(const char *cs, const char *ct)
  560. {
  561. while (*cs && *cs == *ct)
  562. {
  563. cs++;
  564. ct++;
  565. }
  566. return (*cs - *ct);
  567. }
  568. RTM_EXPORT(rt_strcmp);
  569. /**
  570. * @brief This function will return the length of a string, which terminate will
  571. * null character.
  572. *
  573. * @param s is the string
  574. *
  575. * @return The length of string.
  576. */
  577. rt_size_t rt_strlen(const char *s)
  578. {
  579. const char *sc = RT_NULL;
  580. for (sc = s; *sc != '\0'; ++sc) /* nothing */
  581. ;
  582. return sc - s;
  583. }
  584. RTM_EXPORT(rt_strlen);
  585. #endif /* RT_KSERVICE_USING_STDLIB */
  586. /**
  587. * @brief The strnlen() function returns the number of characters in the
  588. * string pointed to by s, excluding the terminating null byte ('\0'),
  589. * but at most maxlen. In doing this, strnlen() looks only at the
  590. * first maxlen characters in the string pointed to by s and never
  591. * beyond s+maxlen.
  592. *
  593. * @param s is the string.
  594. *
  595. * @param maxlen is the max size.
  596. *
  597. * @return The length of string.
  598. */
  599. rt_size_t rt_strnlen(const char *s, rt_ubase_t maxlen)
  600. {
  601. const char *sc;
  602. for (sc = s; *sc != '\0' && (rt_ubase_t)(sc - s) < maxlen; ++sc) /* nothing */
  603. ;
  604. return sc - s;
  605. }
  606. RTM_EXPORT(rt_strnlen);
  607. #ifdef RT_USING_HEAP
  608. /**
  609. * @brief This function will duplicate a string.
  610. *
  611. * @param s is the string to be duplicated.
  612. *
  613. * @return The string address of the copy.
  614. */
  615. char *rt_strdup(const char *s)
  616. {
  617. rt_size_t len = rt_strlen(s) + 1;
  618. char *tmp = (char *)rt_malloc(len);
  619. if (!tmp)
  620. {
  621. return RT_NULL;
  622. }
  623. rt_memcpy(tmp, s, len);
  624. return tmp;
  625. }
  626. RTM_EXPORT(rt_strdup);
  627. #endif /* RT_USING_HEAP */
  628. /**
  629. * @brief This function will show the version of rt-thread rtos
  630. */
  631. void rt_show_version(void)
  632. {
  633. rt_kprintf("\n \\ | /\n");
  634. #if defined(RT_USING_SMART)
  635. rt_kprintf("- RT - Thread Smart Operating System\n");
  636. #elif defined(RT_USING_NANO)
  637. rt_kprintf("- RT - Thread Nano Operating System\n");
  638. #else
  639. rt_kprintf("- RT - Thread Operating System\n");
  640. #endif
  641. rt_kprintf(" / | \\ %d.%d.%d build %s %s\n",
  642. (rt_int32_t)RT_VERSION_MAJOR, (rt_int32_t)RT_VERSION_MINOR, (rt_int32_t)RT_VERSION_PATCH, __DATE__, __TIME__);
  643. rt_kprintf(" 2006 - 2024 Copyright by RT-Thread team\n");
  644. }
  645. RTM_EXPORT(rt_show_version);
  646. /* private function */
  647. #define _ISDIGIT(c) ((unsigned)((c) - '0') < 10)
  648. /**
  649. * @brief This function will duplicate a string.
  650. *
  651. * @param n is the string to be duplicated.
  652. *
  653. * @param base is support divide instructions value.
  654. *
  655. * @return the duplicated string pointer.
  656. */
  657. #ifdef RT_KPRINTF_USING_LONGLONG
  658. rt_inline int divide(unsigned long long *n, int base)
  659. #else
  660. rt_inline int divide(unsigned long *n, int base)
  661. #endif /* RT_KPRINTF_USING_LONGLONG */
  662. {
  663. int res;
  664. /* optimized for processor which does not support divide instructions. */
  665. #ifdef RT_KPRINTF_USING_LONGLONG
  666. res = (int)((*n) % base);
  667. *n = (long long)((*n) / base);
  668. #else
  669. res = (int)((*n) % base);
  670. *n = (long)((*n) / base);
  671. #endif
  672. return res;
  673. }
  674. rt_inline int skip_atoi(const char **s)
  675. {
  676. int i = 0;
  677. while (_ISDIGIT(**s))
  678. i = i * 10 + *((*s)++) - '0';
  679. return i;
  680. }
  681. #define ZEROPAD (1 << 0) /* pad with zero */
  682. #define SIGN (1 << 1) /* unsigned/signed long */
  683. #define PLUS (1 << 2) /* show plus */
  684. #define SPACE (1 << 3) /* space if plus */
  685. #define LEFT (1 << 4) /* left justified */
  686. #define SPECIAL (1 << 5) /* 0x */
  687. #define LARGE (1 << 6) /* use 'ABCDEF' instead of 'abcdef' */
  688. static char *print_number(char *buf,
  689. char *end,
  690. #ifdef RT_KPRINTF_USING_LONGLONG
  691. unsigned long long num,
  692. #else
  693. unsigned long num,
  694. #endif /* RT_KPRINTF_USING_LONGLONG */
  695. int base,
  696. int qualifier,
  697. int s,
  698. int precision,
  699. int type)
  700. {
  701. char c = 0, sign = 0;
  702. #ifdef RT_KPRINTF_USING_LONGLONG
  703. char tmp[64] = {0};
  704. #else
  705. char tmp[32] = {0};
  706. #endif /* RT_KPRINTF_USING_LONGLONG */
  707. int precision_bak = precision;
  708. const char *digits = RT_NULL;
  709. static const char small_digits[] = "0123456789abcdef";
  710. static const char large_digits[] = "0123456789ABCDEF";
  711. int i = 0;
  712. int size = 0;
  713. size = s;
  714. digits = (type & LARGE) ? large_digits : small_digits;
  715. if (type & LEFT)
  716. {
  717. type &= ~ZEROPAD;
  718. }
  719. c = (type & ZEROPAD) ? '0' : ' ';
  720. /* get sign */
  721. sign = 0;
  722. if (type & SIGN)
  723. {
  724. switch (qualifier)
  725. {
  726. case 'h':
  727. if ((rt_int16_t)num < 0)
  728. {
  729. sign = '-';
  730. num = (rt_uint16_t)-num;
  731. }
  732. break;
  733. case 'L':
  734. case 'l':
  735. if ((long)num < 0)
  736. {
  737. sign = '-';
  738. num = (unsigned long)-num;
  739. }
  740. break;
  741. case 0:
  742. default:
  743. if ((rt_int32_t)num < 0)
  744. {
  745. sign = '-';
  746. num = (rt_uint32_t)-num;
  747. }
  748. break;
  749. }
  750. if (sign != '-')
  751. {
  752. if (type & PLUS)
  753. {
  754. sign = '+';
  755. }
  756. else if (type & SPACE)
  757. {
  758. sign = ' ';
  759. }
  760. }
  761. }
  762. if (type & SPECIAL)
  763. {
  764. if (base == 2 || base == 16)
  765. {
  766. size -= 2;
  767. }
  768. else if (base == 8)
  769. {
  770. size--;
  771. }
  772. }
  773. i = 0;
  774. if (num == 0)
  775. {
  776. tmp[i++] = '0';
  777. }
  778. else
  779. {
  780. while (num != 0)
  781. tmp[i++] = digits[divide(&num, base)];
  782. }
  783. if (i > precision)
  784. {
  785. precision = i;
  786. }
  787. size -= precision;
  788. if (!(type & (ZEROPAD | LEFT)))
  789. {
  790. if ((sign) && (size > 0))
  791. {
  792. size--;
  793. }
  794. while (size-- > 0)
  795. {
  796. if (buf < end)
  797. {
  798. *buf = ' ';
  799. }
  800. ++ buf;
  801. }
  802. }
  803. if (sign)
  804. {
  805. if (buf < end)
  806. {
  807. *buf = sign;
  808. }
  809. -- size;
  810. ++ buf;
  811. }
  812. if (type & SPECIAL)
  813. {
  814. if (base == 2)
  815. {
  816. if (buf < end)
  817. *buf = '0';
  818. ++ buf;
  819. if (buf < end)
  820. *buf = 'b';
  821. ++ buf;
  822. }
  823. else if (base == 8)
  824. {
  825. if (buf < end)
  826. *buf = '0';
  827. ++ buf;
  828. }
  829. else if (base == 16)
  830. {
  831. if (buf < end)
  832. {
  833. *buf = '0';
  834. }
  835. ++ buf;
  836. if (buf < end)
  837. {
  838. *buf = type & LARGE ? 'X' : 'x';
  839. }
  840. ++ buf;
  841. }
  842. }
  843. /* no align to the left */
  844. if (!(type & LEFT))
  845. {
  846. while (size-- > 0)
  847. {
  848. if (buf < end)
  849. {
  850. *buf = c;
  851. }
  852. ++ buf;
  853. }
  854. }
  855. while (i < precision--)
  856. {
  857. if (buf < end)
  858. {
  859. *buf = '0';
  860. }
  861. ++ buf;
  862. }
  863. /* put number in the temporary buffer */
  864. while (i-- > 0 && (precision_bak != 0))
  865. {
  866. if (buf < end)
  867. {
  868. *buf = tmp[i];
  869. }
  870. ++ buf;
  871. }
  872. while (size-- > 0)
  873. {
  874. if (buf < end)
  875. {
  876. *buf = ' ';
  877. }
  878. ++ buf;
  879. }
  880. return buf;
  881. }
  882. #ifdef __GNUC__
  883. #pragma GCC diagnostic push
  884. /* ignore warning: this statement may fall through */
  885. #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
  886. #endif /* __GNUC__ */
  887. /**
  888. * @brief This function will fill a formatted string to buffer.
  889. *
  890. * @param buf is the buffer to save formatted string.
  891. *
  892. * @param size is the size of buffer.
  893. *
  894. * @param fmt is the format parameters.
  895. *
  896. * @param args is a list of variable parameters.
  897. *
  898. * @return The number of characters actually written to buffer.
  899. */
  900. rt_weak int rt_vsnprintf(char *buf, rt_size_t size, const char *fmt, va_list args)
  901. {
  902. #ifdef RT_KPRINTF_USING_LONGLONG
  903. unsigned long long num = 0;
  904. #else
  905. unsigned long num = 0;
  906. #endif /* RT_KPRINTF_USING_LONGLONG */
  907. int i = 0, len = 0;
  908. char *str = RT_NULL, *end = RT_NULL, c = 0;
  909. const char *s = RT_NULL;
  910. rt_uint8_t base = 0; /* the base of number */
  911. rt_uint8_t flags = 0; /* flags to print number */
  912. rt_uint8_t qualifier = 0; /* 'h', 'l', or 'L' for integer fields */
  913. rt_int32_t field_width = 0; /* width of output field */
  914. int precision = 0; /* min. # of digits for integers and max for a string */
  915. str = buf;
  916. end = buf + size;
  917. /* Make sure end is always >= buf */
  918. if (end < buf)
  919. {
  920. end = ((char *) - 1);
  921. size = end - buf;
  922. }
  923. for (; *fmt ; ++fmt)
  924. {
  925. if (*fmt != '%')
  926. {
  927. if (str < end)
  928. {
  929. *str = *fmt;
  930. }
  931. ++ str;
  932. continue;
  933. }
  934. /* process flags */
  935. flags = 0;
  936. while (1)
  937. {
  938. /* skips the first '%' also */
  939. ++fmt;
  940. if (*fmt == '-') flags |= LEFT;
  941. else if (*fmt == '+') flags |= PLUS;
  942. else if (*fmt == ' ') flags |= SPACE;
  943. else if (*fmt == '#') flags |= SPECIAL;
  944. else if (*fmt == '0') flags |= ZEROPAD;
  945. else break;
  946. }
  947. /* get field width */
  948. field_width = -1;
  949. if (_ISDIGIT(*fmt))
  950. {
  951. field_width = skip_atoi(&fmt);
  952. }
  953. else if (*fmt == '*')
  954. {
  955. ++fmt;
  956. /* it's the next argument */
  957. field_width = va_arg(args, int);
  958. if (field_width < 0)
  959. {
  960. field_width = -field_width;
  961. flags |= LEFT;
  962. }
  963. }
  964. /* get the precision */
  965. precision = -1;
  966. if (*fmt == '.')
  967. {
  968. ++fmt;
  969. if (_ISDIGIT(*fmt))
  970. {
  971. precision = skip_atoi(&fmt);
  972. }
  973. else if (*fmt == '*')
  974. {
  975. ++fmt;
  976. /* it's the next argument */
  977. precision = va_arg(args, int);
  978. }
  979. if (precision < 0)
  980. {
  981. precision = 0;
  982. }
  983. }
  984. qualifier = 0; /* get the conversion qualifier */
  985. if (*fmt == 'h' || *fmt == 'l' ||
  986. #ifdef RT_KPRINTF_USING_LONGLONG
  987. *fmt == 'L' ||
  988. #endif /* RT_KPRINTF_USING_LONGLONG */
  989. *fmt == 'z')
  990. {
  991. qualifier = *fmt;
  992. ++fmt;
  993. #ifdef RT_KPRINTF_USING_LONGLONG
  994. if (qualifier == 'l' && *fmt == 'l')
  995. {
  996. qualifier = 'L';
  997. ++fmt;
  998. }
  999. #endif /* RT_KPRINTF_USING_LONGLONG */
  1000. if (qualifier == 'h' && *fmt == 'h')
  1001. {
  1002. qualifier = 'H';
  1003. ++fmt;
  1004. }
  1005. }
  1006. /* the default base */
  1007. base = 10;
  1008. switch (*fmt)
  1009. {
  1010. case 'c':
  1011. if (!(flags & LEFT))
  1012. {
  1013. while (--field_width > 0)
  1014. {
  1015. if (str < end) *str = ' ';
  1016. ++ str;
  1017. }
  1018. }
  1019. /* get character */
  1020. c = (rt_uint8_t)va_arg(args, int);
  1021. if (str < end)
  1022. {
  1023. *str = c;
  1024. }
  1025. ++ str;
  1026. /* put width */
  1027. while (--field_width > 0)
  1028. {
  1029. if (str < end) *str = ' ';
  1030. ++ str;
  1031. }
  1032. continue;
  1033. case 's':
  1034. s = va_arg(args, char *);
  1035. if (!s)
  1036. {
  1037. s = "(NULL)";
  1038. }
  1039. for (len = 0; (len != field_width) && (s[len] != '\0'); len++);
  1040. if (precision > 0 && len > precision)
  1041. {
  1042. len = precision;
  1043. }
  1044. if (!(flags & LEFT))
  1045. {
  1046. while (len < field_width--)
  1047. {
  1048. if (str < end) *str = ' ';
  1049. ++ str;
  1050. }
  1051. }
  1052. for (i = 0; i < len; ++i)
  1053. {
  1054. if (str < end) *str = *s;
  1055. ++ str;
  1056. ++ s;
  1057. }
  1058. while (len < field_width--)
  1059. {
  1060. if (str < end) *str = ' ';
  1061. ++ str;
  1062. }
  1063. continue;
  1064. case 'p':
  1065. if (field_width == -1)
  1066. {
  1067. field_width = sizeof(void *) << 1;
  1068. field_width += 2; /* `0x` prefix */
  1069. flags |= SPECIAL;
  1070. flags |= ZEROPAD;
  1071. }
  1072. str = print_number(str, end, (unsigned long)va_arg(args, void *),
  1073. 16, qualifier, field_width, precision, flags);
  1074. continue;
  1075. case '%':
  1076. if (str < end)
  1077. {
  1078. *str = '%';
  1079. }
  1080. ++ str;
  1081. continue;
  1082. /* integer number formats - set up the flags and "break" */
  1083. case 'b':
  1084. base = 2;
  1085. break;
  1086. case 'o':
  1087. base = 8;
  1088. break;
  1089. case 'X':
  1090. flags |= LARGE;
  1091. case 'x':
  1092. base = 16;
  1093. break;
  1094. case 'd':
  1095. case 'i':
  1096. flags |= SIGN;
  1097. case 'u':
  1098. break;
  1099. case 'e':
  1100. case 'E':
  1101. case 'G':
  1102. case 'g':
  1103. case 'f':
  1104. case 'F':
  1105. va_arg(args, double);
  1106. default:
  1107. if (str < end)
  1108. {
  1109. *str = '%';
  1110. }
  1111. ++ str;
  1112. if (*fmt)
  1113. {
  1114. if (str < end)
  1115. {
  1116. *str = *fmt;
  1117. }
  1118. ++ str;
  1119. }
  1120. else
  1121. {
  1122. -- fmt;
  1123. }
  1124. continue;
  1125. }
  1126. if (qualifier == 'L')
  1127. {
  1128. num = va_arg(args, unsigned long long);
  1129. }
  1130. else if (qualifier == 'l')
  1131. {
  1132. num = va_arg(args, unsigned long);
  1133. }
  1134. else if (qualifier == 'H')
  1135. {
  1136. num = (rt_int8_t)va_arg(args, rt_int32_t);
  1137. if (flags & SIGN)
  1138. {
  1139. num = (rt_int8_t)num;
  1140. }
  1141. }
  1142. else if (qualifier == 'h')
  1143. {
  1144. num = (rt_uint16_t)va_arg(args, rt_int32_t);
  1145. if (flags & SIGN)
  1146. {
  1147. num = (rt_int16_t)num;
  1148. }
  1149. }
  1150. else if (qualifier == 'z')
  1151. {
  1152. num = va_arg(args, rt_size_t);
  1153. if (flags & SIGN)
  1154. {
  1155. num = (rt_ssize_t)num;
  1156. }
  1157. }
  1158. else
  1159. {
  1160. num = (rt_uint32_t)va_arg(args, unsigned long);
  1161. }
  1162. str = print_number(str, end, num, base, qualifier, field_width, precision, flags);
  1163. }
  1164. if (size > 0)
  1165. {
  1166. if (str < end)
  1167. {
  1168. *str = '\0';
  1169. }
  1170. else
  1171. {
  1172. end[-1] = '\0';
  1173. }
  1174. }
  1175. /* the trailing null byte doesn't count towards the total
  1176. * ++str;
  1177. */
  1178. return str - buf;
  1179. }
  1180. RTM_EXPORT(rt_vsnprintf);
  1181. #ifdef __GNUC__
  1182. #pragma GCC diagnostic pop /* ignored "-Wimplicit-fallthrough" */
  1183. #endif /* __GNUC__ */
  1184. /**
  1185. * @brief This function will fill a formatted string to buffer.
  1186. *
  1187. * @param buf is the buffer to save formatted string.
  1188. *
  1189. * @param size is the size of buffer.
  1190. *
  1191. * @param fmt is the format parameters.
  1192. *
  1193. * @return The number of characters actually written to buffer.
  1194. */
  1195. int rt_snprintf(char *buf, rt_size_t size, const char *fmt, ...)
  1196. {
  1197. rt_int32_t n = 0;
  1198. va_list args;
  1199. va_start(args, fmt);
  1200. n = rt_vsnprintf(buf, size, fmt, args);
  1201. va_end(args);
  1202. return n;
  1203. }
  1204. RTM_EXPORT(rt_snprintf);
  1205. /**
  1206. * @brief This function will fill a formatted string to buffer.
  1207. *
  1208. * @param buf is the buffer to save formatted string.
  1209. *
  1210. * @param format is the format parameters.
  1211. *
  1212. * @param arg_ptr is a list of variable parameters.
  1213. *
  1214. * @return The number of characters actually written to buffer.
  1215. */
  1216. int rt_vsprintf(char *buf, const char *format, va_list arg_ptr)
  1217. {
  1218. return rt_vsnprintf(buf, (rt_size_t) - 1, format, arg_ptr);
  1219. }
  1220. RTM_EXPORT(rt_vsprintf);
  1221. /**
  1222. * @brief This function will fill a formatted string to buffer
  1223. *
  1224. * @param buf the buffer to save formatted string.
  1225. *
  1226. * @param format is the format parameters.
  1227. *
  1228. * @return The number of characters actually written to buffer.
  1229. */
  1230. int rt_sprintf(char *buf, const char *format, ...)
  1231. {
  1232. rt_int32_t n = 0;
  1233. va_list arg_ptr;
  1234. va_start(arg_ptr, format);
  1235. n = rt_vsprintf(buf, format, arg_ptr);
  1236. va_end(arg_ptr);
  1237. return n;
  1238. }
  1239. RTM_EXPORT(rt_sprintf);
  1240. #ifdef RT_USING_CONSOLE
  1241. #ifdef RT_USING_DEVICE
  1242. /**
  1243. * @brief This function returns the device using in console.
  1244. *
  1245. * @return Returns the console device pointer or RT_NULL.
  1246. */
  1247. rt_device_t rt_console_get_device(void)
  1248. {
  1249. return _console_device;
  1250. }
  1251. RTM_EXPORT(rt_console_get_device);
  1252. /**
  1253. * @brief This function will set a device as console device.
  1254. * After set a device to console, all output of rt_kprintf will be
  1255. * redirected to this new device.
  1256. *
  1257. * @param name is the name of new console device.
  1258. *
  1259. * @return the old console device handler on successful, or RT_NULL on failure.
  1260. */
  1261. rt_device_t rt_console_set_device(const char *name)
  1262. {
  1263. #ifdef RT_USING_SMART
  1264. rt_device_t new_iodev = RT_NULL, old_iodev = RT_NULL;
  1265. /* find new console device */
  1266. new_iodev = rt_device_find(name);
  1267. if (new_iodev != RT_NULL)
  1268. {
  1269. if (_console_device != RT_NULL)
  1270. {
  1271. old_iodev = console_set_iodev(new_iodev);
  1272. }
  1273. else
  1274. {
  1275. console_register("console", new_iodev);
  1276. _console_device = rt_device_find("console");
  1277. rt_device_open(_console_device, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_STREAM);
  1278. }
  1279. }
  1280. return old_iodev;
  1281. #else
  1282. rt_device_t new_device, old_device;
  1283. /* save old device */
  1284. old_device = _console_device;
  1285. /* find new console device */
  1286. new_device = rt_device_find(name);
  1287. /* check whether it's a same device */
  1288. if (new_device == old_device) return RT_NULL;
  1289. if (new_device != RT_NULL)
  1290. {
  1291. if (_console_device != RT_NULL)
  1292. {
  1293. /* close old console device */
  1294. rt_device_close(_console_device);
  1295. }
  1296. /* set new console device */
  1297. rt_device_open(new_device, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_STREAM);
  1298. _console_device = new_device;
  1299. }
  1300. return old_device;
  1301. #endif
  1302. }
  1303. RTM_EXPORT(rt_console_set_device);
  1304. #endif /* RT_USING_DEVICE */
  1305. rt_weak void rt_hw_console_output(const char *str)
  1306. {
  1307. /* empty console output */
  1308. RT_UNUSED(str);
  1309. }
  1310. RTM_EXPORT(rt_hw_console_output);
  1311. #ifdef RT_USING_THREADSAFE_PRINTF
  1312. /* system console lock */
  1313. static struct rt_spinlock _syscon_lock = RT_SPINLOCK_INIT;
  1314. /* lock of kprintf buffer */
  1315. static struct rt_spinlock _prbuf_lock = RT_SPINLOCK_INIT;
  1316. /* current user of system console */
  1317. static rt_thread_t _pr_curr_user;
  1318. #ifdef RT_USING_DEBUG
  1319. static rt_base_t _pr_critical_level;
  1320. #endif /* RT_USING_DEBUG */
  1321. /* nested level of current user */
  1322. static volatile int _pr_curr_user_nested;
  1323. rt_thread_t rt_console_current_user(void)
  1324. {
  1325. return _pr_curr_user;
  1326. }
  1327. static void _console_take(void)
  1328. {
  1329. rt_ubase_t level = rt_spin_lock_irqsave(&_syscon_lock);
  1330. rt_thread_t self_thread = rt_thread_self();
  1331. rt_base_t critical_level;
  1332. RT_UNUSED(critical_level);
  1333. while (_pr_curr_user != self_thread)
  1334. {
  1335. if (_pr_curr_user == RT_NULL)
  1336. {
  1337. /* no preemption is allowed to avoid dead lock */
  1338. critical_level = rt_enter_critical();
  1339. #ifdef RT_USING_DEBUG
  1340. _pr_critical_level = _syscon_lock.critical_level;
  1341. _syscon_lock.critical_level = critical_level;
  1342. #endif
  1343. _pr_curr_user = self_thread;
  1344. break;
  1345. }
  1346. else
  1347. {
  1348. rt_spin_unlock_irqrestore(&_syscon_lock, level);
  1349. rt_thread_yield();
  1350. level = rt_spin_lock_irqsave(&_syscon_lock);
  1351. }
  1352. }
  1353. _pr_curr_user_nested++;
  1354. rt_spin_unlock_irqrestore(&_syscon_lock, level);
  1355. }
  1356. static void _console_release(void)
  1357. {
  1358. rt_ubase_t level = rt_spin_lock_irqsave(&_syscon_lock);
  1359. rt_thread_t self_thread = rt_thread_self();
  1360. RT_UNUSED(self_thread);
  1361. RT_ASSERT(_pr_curr_user == self_thread);
  1362. _pr_curr_user_nested--;
  1363. if (!_pr_curr_user_nested)
  1364. {
  1365. _pr_curr_user = RT_NULL;
  1366. #ifdef RT_USING_DEBUG
  1367. rt_exit_critical_safe(_syscon_lock.critical_level);
  1368. _syscon_lock.critical_level = _pr_critical_level;
  1369. #else
  1370. rt_exit_critical();
  1371. #endif
  1372. }
  1373. rt_spin_unlock_irqrestore(&_syscon_lock, level);
  1374. }
  1375. #define CONSOLE_TAKE _console_take()
  1376. #define CONSOLE_RELEASE _console_release()
  1377. #define PRINTF_BUFFER_TAKE rt_ubase_t level = rt_spin_lock_irqsave(&_prbuf_lock)
  1378. #define PRINTF_BUFFER_RELEASE rt_spin_unlock_irqrestore(&_prbuf_lock, level)
  1379. #else
  1380. #define CONSOLE_TAKE
  1381. #define CONSOLE_RELEASE
  1382. #define PRINTF_BUFFER_TAKE
  1383. #define PRINTF_BUFFER_RELEASE
  1384. #endif /* RT_USING_THREADSAFE_PRINTF */
  1385. /**
  1386. * @brief This function will put string to the console.
  1387. *
  1388. * @param str is the string output to the console.
  1389. */
  1390. static void _kputs(const char *str, long len)
  1391. {
  1392. RT_UNUSED(len);
  1393. CONSOLE_TAKE;
  1394. #ifdef RT_USING_DEVICE
  1395. if (_console_device == RT_NULL)
  1396. {
  1397. rt_hw_console_output(str);
  1398. }
  1399. else
  1400. {
  1401. rt_device_write(_console_device, 0, str, len);
  1402. }
  1403. #else
  1404. rt_hw_console_output(str);
  1405. #endif /* RT_USING_DEVICE */
  1406. CONSOLE_RELEASE;
  1407. }
  1408. /**
  1409. * @brief This function will put string to the console.
  1410. *
  1411. * @param str is the string output to the console.
  1412. */
  1413. void rt_kputs(const char *str)
  1414. {
  1415. if (!str)
  1416. {
  1417. return;
  1418. }
  1419. _kputs(str, rt_strlen(str));
  1420. }
  1421. /**
  1422. * @brief This function will print a formatted string on system console.
  1423. *
  1424. * @param fmt is the format parameters.
  1425. *
  1426. * @return The number of characters actually written to buffer.
  1427. */
  1428. rt_weak int rt_kprintf(const char *fmt, ...)
  1429. {
  1430. va_list args;
  1431. rt_size_t length = 0;
  1432. static char rt_log_buf[RT_CONSOLEBUF_SIZE];
  1433. va_start(args, fmt);
  1434. PRINTF_BUFFER_TAKE;
  1435. /* the return value of vsnprintf is the number of bytes that would be
  1436. * written to buffer had if the size of the buffer been sufficiently
  1437. * large excluding the terminating null byte. If the output string
  1438. * would be larger than the rt_log_buf, we have to adjust the output
  1439. * length. */
  1440. length = rt_vsnprintf(rt_log_buf, sizeof(rt_log_buf) - 1, fmt, args);
  1441. if (length > RT_CONSOLEBUF_SIZE - 1)
  1442. {
  1443. length = RT_CONSOLEBUF_SIZE - 1;
  1444. }
  1445. _kputs(rt_log_buf, length);
  1446. PRINTF_BUFFER_RELEASE;
  1447. va_end(args);
  1448. return length;
  1449. }
  1450. RTM_EXPORT(rt_kprintf);
  1451. #endif /* RT_USING_CONSOLE */
  1452. #ifdef __GNUC__
  1453. rt_weak rt_err_t rt_backtrace(void)
  1454. {
  1455. struct rt_hw_backtrace_frame frame = {
  1456. .fp = (rt_base_t)__builtin_frame_address(0U),
  1457. .pc = ({__label__ pc; pc: (rt_base_t)&&pc;})
  1458. };
  1459. rt_hw_backtrace_frame_unwind(rt_thread_self(), &frame);
  1460. return rt_backtrace_frame(&frame);
  1461. }
  1462. #else /* otherwise not implemented */
  1463. rt_weak rt_err_t rt_backtrace(void)
  1464. {
  1465. /* LOG_W cannot work under this environment */
  1466. rt_kprintf("%s is not implemented\n", __func__);
  1467. return -RT_ENOSYS;
  1468. }
  1469. #endif
  1470. rt_err_t rt_backtrace_frame(struct rt_hw_backtrace_frame *frame)
  1471. {
  1472. long nesting = 0;
  1473. rt_kprintf("please use: addr2line -e rtthread.elf -a -f");
  1474. while (nesting < RT_BACKTRACE_LEVEL_MAX_NR)
  1475. {
  1476. rt_kprintf(" 0x%lx", (rt_ubase_t)frame->pc);
  1477. if (rt_hw_backtrace_frame_unwind(rt_thread_self(), frame))
  1478. {
  1479. break;
  1480. }
  1481. nesting++;
  1482. }
  1483. rt_kprintf("\n");
  1484. return RT_EOK;
  1485. }
  1486. rt_err_t rt_backtrace_thread(rt_thread_t thread)
  1487. {
  1488. rt_err_t rc;
  1489. struct rt_hw_backtrace_frame frame;
  1490. if (thread)
  1491. {
  1492. rc = rt_hw_backtrace_frame_get(thread, &frame);
  1493. if (rc == RT_EOK)
  1494. {
  1495. rc = rt_backtrace_frame(&frame);
  1496. }
  1497. }
  1498. else
  1499. {
  1500. rc = -RT_EINVAL;
  1501. }
  1502. return rc;
  1503. }
  1504. #if defined(RT_USING_LIBC) && defined(RT_USING_FINSH)
  1505. #include <stdlib.h> /* for string service */
  1506. static void cmd_backtrace(int argc, char** argv)
  1507. {
  1508. rt_ubase_t pid;
  1509. char *end_ptr;
  1510. if (argc != 2)
  1511. {
  1512. if (argc == 1)
  1513. {
  1514. rt_kprintf("[INFO] No thread specified\n"
  1515. "[HELP] You can use commands like: backtrace %p\n"
  1516. "Printing backtrace of calling stack...\n",
  1517. rt_thread_self());
  1518. rt_backtrace();
  1519. return ;
  1520. }
  1521. else
  1522. {
  1523. rt_kprintf("please use: backtrace [thread_address]\n");
  1524. return;
  1525. }
  1526. }
  1527. pid = strtoul(argv[1], &end_ptr, 0);
  1528. if (end_ptr == argv[1])
  1529. {
  1530. rt_kprintf("Invalid input: %s\n", argv[1]);
  1531. return ;
  1532. }
  1533. if (pid && rt_object_get_type((void *)pid) == RT_Object_Class_Thread)
  1534. {
  1535. rt_thread_t target = (rt_thread_t)pid;
  1536. rt_kprintf("backtrace %s(0x%lx), from %s\n", target->parent.name, pid, argv[1]);
  1537. rt_backtrace_thread(target);
  1538. }
  1539. else
  1540. rt_kprintf("Invalid pid: %ld\n", pid);
  1541. }
  1542. MSH_CMD_EXPORT_ALIAS(cmd_backtrace, backtrace, print backtrace of a thread);
  1543. #endif /* RT_USING_LIBC */
  1544. #if defined(RT_USING_HEAP) && !defined(RT_USING_USERHEAP)
  1545. #ifdef RT_USING_HOOK
  1546. static void (*rt_malloc_hook)(void **ptr, rt_size_t size);
  1547. static void (*rt_realloc_entry_hook)(void **ptr, rt_size_t size);
  1548. static void (*rt_realloc_exit_hook)(void **ptr, rt_size_t size);
  1549. static void (*rt_free_hook)(void **ptr);
  1550. /**
  1551. * @addtogroup Hook
  1552. * @{
  1553. */
  1554. /**
  1555. * @brief This function will set a hook function, which will be invoked when a memory
  1556. * block is allocated from heap memory.
  1557. *
  1558. * @param hook the hook function.
  1559. */
  1560. void rt_malloc_sethook(void (*hook)(void **ptr, rt_size_t size))
  1561. {
  1562. rt_malloc_hook = hook;
  1563. }
  1564. /**
  1565. * @brief This function will set a hook function, which will be invoked when a memory
  1566. * block is allocated from heap memory.
  1567. *
  1568. * @param hook the hook function.
  1569. */
  1570. void rt_realloc_set_entry_hook(void (*hook)(void **ptr, rt_size_t size))
  1571. {
  1572. rt_realloc_entry_hook = hook;
  1573. }
  1574. /**
  1575. * @brief This function will set a hook function, which will be invoked when a memory
  1576. * block is allocated from heap memory.
  1577. *
  1578. * @param hook the hook function.
  1579. */
  1580. void rt_realloc_set_exit_hook(void (*hook)(void **ptr, rt_size_t size))
  1581. {
  1582. rt_realloc_exit_hook = hook;
  1583. }
  1584. /**
  1585. * @brief This function will set a hook function, which will be invoked when a memory
  1586. * block is released to heap memory.
  1587. *
  1588. * @param hook the hook function
  1589. */
  1590. void rt_free_sethook(void (*hook)(void **ptr))
  1591. {
  1592. rt_free_hook = hook;
  1593. }
  1594. /**@}*/
  1595. #endif /* RT_USING_HOOK */
  1596. #if defined(RT_USING_HEAP_ISR)
  1597. static struct rt_spinlock _heap_spinlock;
  1598. #elif defined(RT_USING_MUTEX)
  1599. static struct rt_mutex _lock;
  1600. #endif
  1601. rt_inline void _heap_lock_init(void)
  1602. {
  1603. #if defined(RT_USING_HEAP_ISR)
  1604. rt_spin_lock_init(&_heap_spinlock);
  1605. #elif defined(RT_USING_MUTEX)
  1606. rt_mutex_init(&_lock, "heap", RT_IPC_FLAG_PRIO);
  1607. #endif
  1608. }
  1609. rt_inline rt_base_t _heap_lock(void)
  1610. {
  1611. #if defined(RT_USING_HEAP_ISR)
  1612. return rt_spin_lock_irqsave(&_heap_spinlock);
  1613. #elif defined(RT_USING_MUTEX)
  1614. if (rt_thread_self())
  1615. return rt_mutex_take(&_lock, RT_WAITING_FOREVER);
  1616. else
  1617. return RT_EOK;
  1618. #else
  1619. rt_enter_critical();
  1620. return RT_EOK;
  1621. #endif
  1622. }
  1623. rt_inline void _heap_unlock(rt_base_t level)
  1624. {
  1625. #if defined(RT_USING_HEAP_ISR)
  1626. rt_spin_unlock_irqrestore(&_heap_spinlock, level);
  1627. #elif defined(RT_USING_MUTEX)
  1628. RT_ASSERT(level == RT_EOK);
  1629. if (rt_thread_self())
  1630. rt_mutex_release(&_lock);
  1631. #else
  1632. rt_exit_critical();
  1633. #endif
  1634. }
  1635. #ifdef RT_USING_UTESTCASES
  1636. /* export to utest to observe the inner statements */
  1637. #ifdef _MSC_VER
  1638. #define rt_heap_lock() _heap_lock()
  1639. #define rt_heap_unlock() _heap_unlock()
  1640. #else
  1641. rt_base_t rt_heap_lock(void) __attribute__((alias("_heap_lock")));
  1642. void rt_heap_unlock(rt_base_t level) __attribute__((alias("_heap_unlock")));
  1643. #endif /* _MSC_VER */
  1644. #endif
  1645. #if defined(RT_USING_SMALL_MEM_AS_HEAP)
  1646. static rt_smem_t system_heap;
  1647. rt_inline void _smem_info(rt_size_t *total,
  1648. rt_size_t *used, rt_size_t *max_used)
  1649. {
  1650. if (total)
  1651. *total = system_heap->total;
  1652. if (used)
  1653. *used = system_heap->used;
  1654. if (max_used)
  1655. *max_used = system_heap->max;
  1656. }
  1657. #define _MEM_INIT(_name, _start, _size) \
  1658. system_heap = rt_smem_init(_name, _start, _size)
  1659. #define _MEM_MALLOC(_size) \
  1660. rt_smem_alloc(system_heap, _size)
  1661. #define _MEM_REALLOC(_ptr, _newsize)\
  1662. rt_smem_realloc(system_heap, _ptr, _newsize)
  1663. #define _MEM_FREE(_ptr) \
  1664. rt_smem_free(_ptr)
  1665. #define _MEM_INFO(_total, _used, _max) \
  1666. _smem_info(_total, _used, _max)
  1667. #elif defined(RT_USING_MEMHEAP_AS_HEAP)
  1668. static struct rt_memheap system_heap;
  1669. void *_memheap_alloc(struct rt_memheap *heap, rt_size_t size);
  1670. void _memheap_free(void *rmem);
  1671. void *_memheap_realloc(struct rt_memheap *heap, void *rmem, rt_size_t newsize);
  1672. #define _MEM_INIT(_name, _start, _size) \
  1673. do {\
  1674. rt_memheap_init(&system_heap, _name, _start, _size); \
  1675. system_heap.locked = RT_TRUE; \
  1676. } while(0)
  1677. #define _MEM_MALLOC(_size) \
  1678. _memheap_alloc(&system_heap, _size)
  1679. #define _MEM_REALLOC(_ptr, _newsize) \
  1680. _memheap_realloc(&system_heap, _ptr, _newsize)
  1681. #define _MEM_FREE(_ptr) \
  1682. _memheap_free(_ptr)
  1683. #define _MEM_INFO(_total, _used, _max) \
  1684. rt_memheap_info(&system_heap, _total, _used, _max)
  1685. #elif defined(RT_USING_SLAB_AS_HEAP)
  1686. static rt_slab_t system_heap;
  1687. rt_inline void _slab_info(rt_size_t *total,
  1688. rt_size_t *used, rt_size_t *max_used)
  1689. {
  1690. if (total)
  1691. *total = system_heap->total;
  1692. if (used)
  1693. *used = system_heap->used;
  1694. if (max_used)
  1695. *max_used = system_heap->max;
  1696. }
  1697. #define _MEM_INIT(_name, _start, _size) \
  1698. system_heap = rt_slab_init(_name, _start, _size)
  1699. #define _MEM_MALLOC(_size) \
  1700. rt_slab_alloc(system_heap, _size)
  1701. #define _MEM_REALLOC(_ptr, _newsize) \
  1702. rt_slab_realloc(system_heap, _ptr, _newsize)
  1703. #define _MEM_FREE(_ptr) \
  1704. rt_slab_free(system_heap, _ptr)
  1705. #define _MEM_INFO _slab_info
  1706. #else
  1707. #define _MEM_INIT(...)
  1708. #define _MEM_MALLOC(...) RT_NULL
  1709. #define _MEM_REALLOC(...) RT_NULL
  1710. #define _MEM_FREE(...)
  1711. #define _MEM_INFO(...)
  1712. #endif
  1713. static void _rt_system_heap_init(void *begin_addr, void *end_addr)
  1714. {
  1715. rt_ubase_t begin_align = RT_ALIGN((rt_ubase_t)begin_addr, RT_ALIGN_SIZE);
  1716. rt_ubase_t end_align = RT_ALIGN_DOWN((rt_ubase_t)end_addr, RT_ALIGN_SIZE);
  1717. RT_ASSERT(end_align > begin_align);
  1718. /* Initialize system memory heap */
  1719. _MEM_INIT("heap", (void *)begin_align, end_align - begin_align);
  1720. /* Initialize multi thread contention lock */
  1721. _heap_lock_init();
  1722. }
  1723. /**
  1724. * @brief This function will init system heap.
  1725. *
  1726. * @param begin_addr the beginning address of system page.
  1727. *
  1728. * @param end_addr the end address of system page.
  1729. */
  1730. rt_weak void rt_system_heap_init(void *begin_addr, void *end_addr)
  1731. {
  1732. _rt_system_heap_init(begin_addr, end_addr);
  1733. }
  1734. /**
  1735. * @brief Allocate a block of memory with a minimum of 'size' bytes.
  1736. *
  1737. * @param size is the minimum size of the requested block in bytes.
  1738. *
  1739. * @return the pointer to allocated memory or NULL if no free memory was found.
  1740. */
  1741. rt_weak void *rt_malloc(rt_size_t size)
  1742. {
  1743. rt_base_t level;
  1744. void *ptr;
  1745. /* Enter critical zone */
  1746. level = _heap_lock();
  1747. /* allocate memory block from system heap */
  1748. ptr = _MEM_MALLOC(size);
  1749. /* Exit critical zone */
  1750. _heap_unlock(level);
  1751. /* call 'rt_malloc' hook */
  1752. RT_OBJECT_HOOK_CALL(rt_malloc_hook, (&ptr, size));
  1753. return ptr;
  1754. }
  1755. RTM_EXPORT(rt_malloc);
  1756. /**
  1757. * @brief This function will change the size of previously allocated memory block.
  1758. *
  1759. * @param ptr is the pointer to memory allocated by rt_malloc.
  1760. *
  1761. * @param newsize is the required new size.
  1762. *
  1763. * @return the changed memory block address.
  1764. */
  1765. rt_weak void *rt_realloc(void *ptr, rt_size_t newsize)
  1766. {
  1767. rt_base_t level;
  1768. void *nptr;
  1769. /* Entry hook */
  1770. RT_OBJECT_HOOK_CALL(rt_realloc_entry_hook, (&ptr, newsize));
  1771. /* Enter critical zone */
  1772. level = _heap_lock();
  1773. /* Change the size of previously allocated memory block */
  1774. nptr = _MEM_REALLOC(ptr, newsize);
  1775. /* Exit critical zone */
  1776. _heap_unlock(level);
  1777. /* Exit hook */
  1778. RT_OBJECT_HOOK_CALL(rt_realloc_exit_hook, (&nptr, newsize));
  1779. return nptr;
  1780. }
  1781. RTM_EXPORT(rt_realloc);
  1782. /**
  1783. * @brief This function will contiguously allocate enough space for count objects
  1784. * that are size bytes of memory each and returns a pointer to the allocated
  1785. * memory.
  1786. *
  1787. * @note The allocated memory is filled with bytes of value zero.
  1788. *
  1789. * @param count is the number of objects to allocate.
  1790. *
  1791. * @param size is the size of one object to allocate.
  1792. *
  1793. * @return pointer to allocated memory / NULL pointer if there is an error.
  1794. */
  1795. rt_weak void *rt_calloc(rt_size_t count, rt_size_t size)
  1796. {
  1797. void *p;
  1798. /* allocate 'count' objects of size 'size' */
  1799. p = rt_malloc(count * size);
  1800. /* zero the memory */
  1801. if (p)
  1802. {
  1803. rt_memset(p, 0, count * size);
  1804. }
  1805. return p;
  1806. }
  1807. RTM_EXPORT(rt_calloc);
  1808. /**
  1809. * @brief This function will release the previously allocated memory block by
  1810. * rt_malloc. The released memory block is taken back to system heap.
  1811. *
  1812. * @param ptr the address of memory which will be released.
  1813. */
  1814. rt_weak void rt_free(void *ptr)
  1815. {
  1816. rt_base_t level;
  1817. /* call 'rt_free' hook */
  1818. RT_OBJECT_HOOK_CALL(rt_free_hook, (&ptr));
  1819. /* NULL check */
  1820. if (ptr == RT_NULL) return;
  1821. /* Enter critical zone */
  1822. level = _heap_lock();
  1823. _MEM_FREE(ptr);
  1824. /* Exit critical zone */
  1825. _heap_unlock(level);
  1826. }
  1827. RTM_EXPORT(rt_free);
  1828. /**
  1829. * @brief This function will caculate the total memory, the used memory, and
  1830. * the max used memory.
  1831. *
  1832. * @param total is a pointer to get the total size of the memory.
  1833. *
  1834. * @param used is a pointer to get the size of memory used.
  1835. *
  1836. * @param max_used is a pointer to get the maximum memory used.
  1837. */
  1838. rt_weak void rt_memory_info(rt_size_t *total,
  1839. rt_size_t *used,
  1840. rt_size_t *max_used)
  1841. {
  1842. rt_base_t level;
  1843. /* Enter critical zone */
  1844. level = _heap_lock();
  1845. _MEM_INFO(total, used, max_used);
  1846. /* Exit critical zone */
  1847. _heap_unlock(level);
  1848. }
  1849. RTM_EXPORT(rt_memory_info);
  1850. #if defined(RT_USING_SLAB) && defined(RT_USING_SLAB_AS_HEAP)
  1851. void *rt_page_alloc(rt_size_t npages)
  1852. {
  1853. rt_base_t level;
  1854. void *ptr;
  1855. /* Enter critical zone */
  1856. level = _heap_lock();
  1857. /* alloc page */
  1858. ptr = rt_slab_page_alloc(system_heap, npages);
  1859. /* Exit critical zone */
  1860. _heap_unlock(level);
  1861. return ptr;
  1862. }
  1863. void rt_page_free(void *addr, rt_size_t npages)
  1864. {
  1865. rt_base_t level;
  1866. /* Enter critical zone */
  1867. level = _heap_lock();
  1868. /* free page */
  1869. rt_slab_page_free(system_heap, addr, npages);
  1870. /* Exit critical zone */
  1871. _heap_unlock(level);
  1872. }
  1873. #endif
  1874. /**
  1875. * @brief This function allocates a memory block, which address is aligned to the
  1876. * specified alignment size.
  1877. *
  1878. * @param size is the allocated memory block size.
  1879. *
  1880. * @param align is the alignment size.
  1881. *
  1882. * @return The memory block address was returned successfully, otherwise it was
  1883. * returned empty RT_NULL.
  1884. */
  1885. rt_weak void *rt_malloc_align(rt_size_t size, rt_size_t align)
  1886. {
  1887. void *ptr = RT_NULL;
  1888. void *align_ptr = RT_NULL;
  1889. int uintptr_size = 0;
  1890. rt_size_t align_size = 0;
  1891. /* sizeof pointer */
  1892. uintptr_size = sizeof(void*);
  1893. uintptr_size -= 1;
  1894. /* align the alignment size to uintptr size byte */
  1895. align = ((align + uintptr_size) & ~uintptr_size);
  1896. /* get total aligned size */
  1897. align_size = ((size + uintptr_size) & ~uintptr_size) + align;
  1898. /* allocate memory block from heap */
  1899. ptr = rt_malloc(align_size);
  1900. if (ptr != RT_NULL)
  1901. {
  1902. /* the allocated memory block is aligned */
  1903. if (((rt_ubase_t)ptr & (align - 1)) == 0)
  1904. {
  1905. align_ptr = (void *)((rt_ubase_t)ptr + align);
  1906. }
  1907. else
  1908. {
  1909. align_ptr = (void *)(((rt_ubase_t)ptr + (align - 1)) & ~(align - 1));
  1910. }
  1911. /* set the pointer before alignment pointer to the real pointer */
  1912. *((rt_ubase_t *)((rt_ubase_t)align_ptr - sizeof(void *))) = (rt_ubase_t)ptr;
  1913. ptr = align_ptr;
  1914. }
  1915. return ptr;
  1916. }
  1917. RTM_EXPORT(rt_malloc_align);
  1918. /**
  1919. * @brief This function release the memory block, which is allocated by
  1920. * rt_malloc_align function and address is aligned.
  1921. *
  1922. * @param ptr is the memory block pointer.
  1923. */
  1924. rt_weak void rt_free_align(void *ptr)
  1925. {
  1926. void *real_ptr = RT_NULL;
  1927. /* NULL check */
  1928. if (ptr == RT_NULL) return;
  1929. real_ptr = (void *) * (rt_ubase_t *)((rt_ubase_t)ptr - sizeof(void *));
  1930. rt_free(real_ptr);
  1931. }
  1932. RTM_EXPORT(rt_free_align);
  1933. #endif /* RT_USING_HEAP */
  1934. #ifndef RT_USING_CPU_FFS
  1935. #ifdef RT_USING_TINY_FFS
  1936. const rt_uint8_t __lowest_bit_bitmap[] =
  1937. {
  1938. /* 0 - 7 */ 0, 1, 2, 27, 3, 24, 28, 32,
  1939. /* 8 - 15 */ 4, 17, 25, 31, 29, 12, 32, 14,
  1940. /* 16 - 23 */ 5, 8, 18, 32, 26, 23, 32, 16,
  1941. /* 24 - 31 */ 30, 11, 13, 7, 32, 22, 15, 10,
  1942. /* 32 - 36 */ 6, 21, 9, 20, 19
  1943. };
  1944. /**
  1945. * @brief This function finds the first bit set (beginning with the least significant bit)
  1946. * in value and return the index of that bit.
  1947. *
  1948. * Bits are numbered starting at 1 (the least significant bit). A return value of
  1949. * zero from any of these functions means that the argument was zero.
  1950. *
  1951. * @param value is the value to find the first bit set in.
  1952. *
  1953. * @return return the index of the first bit set. If value is 0, then this function
  1954. * shall return 0.
  1955. */
  1956. int __rt_ffs(int value)
  1957. {
  1958. return __lowest_bit_bitmap[(rt_uint32_t)(value & (value - 1) ^ value) % 37];
  1959. }
  1960. #else
  1961. const rt_uint8_t __lowest_bit_bitmap[] =
  1962. {
  1963. /* 00 */ 0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1964. /* 10 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1965. /* 20 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1966. /* 30 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1967. /* 40 */ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1968. /* 50 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1969. /* 60 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1970. /* 70 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1971. /* 80 */ 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1972. /* 90 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1973. /* A0 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1974. /* B0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1975. /* C0 */ 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1976. /* D0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1977. /* E0 */ 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
  1978. /* F0 */ 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
  1979. };
  1980. /**
  1981. * @brief This function finds the first bit set (beginning with the least significant bit)
  1982. * in value and return the index of that bit.
  1983. *
  1984. * Bits are numbered starting at 1 (the least significant bit). A return value of
  1985. * zero from any of these functions means that the argument was zero.
  1986. *
  1987. * @param value is the value to find the first bit set in.
  1988. *
  1989. * @return Return the index of the first bit set. If value is 0, then this function
  1990. * shall return 0.
  1991. */
  1992. int __rt_ffs(int value)
  1993. {
  1994. if (value == 0)
  1995. {
  1996. return 0;
  1997. }
  1998. if (value & 0xff)
  1999. {
  2000. return __lowest_bit_bitmap[value & 0xff] + 1;
  2001. }
  2002. if (value & 0xff00)
  2003. {
  2004. return __lowest_bit_bitmap[(value & 0xff00) >> 8] + 9;
  2005. }
  2006. if (value & 0xff0000)
  2007. {
  2008. return __lowest_bit_bitmap[(value & 0xff0000) >> 16] + 17;
  2009. }
  2010. return __lowest_bit_bitmap[(value & 0xff000000) >> 24] + 25;
  2011. }
  2012. #endif /* RT_USING_TINY_FFS */
  2013. #endif /* RT_USING_CPU_FFS */
  2014. #ifdef RT_USING_DEBUG
  2015. /* RT_ASSERT(EX)'s hook */
  2016. void (*rt_assert_hook)(const char *ex, const char *func, rt_size_t line);
  2017. /**
  2018. * This function will set a hook function to RT_ASSERT(EX). It will run when the expression is false.
  2019. *
  2020. * @param hook is the hook function.
  2021. */
  2022. void rt_assert_set_hook(void (*hook)(const char *ex, const char *func, rt_size_t line))
  2023. {
  2024. rt_assert_hook = hook;
  2025. }
  2026. /**
  2027. * The RT_ASSERT function.
  2028. *
  2029. * @param ex_string is the assertion condition string.
  2030. *
  2031. * @param func is the function name when assertion.
  2032. *
  2033. * @param line is the file line number when assertion.
  2034. */
  2035. void rt_assert_handler(const char *ex_string, const char *func, rt_size_t line)
  2036. {
  2037. volatile char dummy = 0;
  2038. if (rt_assert_hook == RT_NULL)
  2039. {
  2040. #ifdef RT_USING_MODULE
  2041. if (dlmodule_self())
  2042. {
  2043. /* close assertion module */
  2044. dlmodule_exit(-1);
  2045. }
  2046. else
  2047. #endif /*RT_USING_MODULE*/
  2048. {
  2049. rt_kprintf("(%s) assertion failed at function:%s, line number:%d \n", ex_string, func, line);
  2050. rt_backtrace();
  2051. while (dummy == 0);
  2052. }
  2053. }
  2054. else
  2055. {
  2056. rt_assert_hook(ex_string, func, line);
  2057. }
  2058. }
  2059. RTM_EXPORT(rt_assert_handler);
  2060. #endif /* RT_USING_DEBUG */
  2061. /**@}*/