dlmodule.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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. * 2018/08/29 Bernard first version
  9. */
  10. #include <rthw.h>
  11. #include "dlfcn.h"
  12. #include "dlmodule.h"
  13. #include "dlelf.h"
  14. #ifdef RT_USING_POSIX_FS
  15. #include <stdio.h>
  16. #include <fcntl.h>
  17. #include <unistd.h>
  18. #include <sys/stat.h>
  19. #include <sys/statfs.h>
  20. #endif
  21. #define DBG_TAG "DLMD"
  22. #define DBG_LVL DBG_INFO
  23. #include <rtdbg.h> /* must after of DEBUG_ENABLE or some other options*/
  24. static struct rt_module_symtab *_rt_module_symtab_begin = RT_NULL;
  25. static struct rt_module_symtab *_rt_module_symtab_end = RT_NULL;
  26. #if defined(__IAR_SYSTEMS_ICC__) /* for IAR compiler */
  27. #pragma section="RTMSymTab"
  28. #endif
  29. /**
  30. * @brief Extract module name from a file path by stripping directory and extension.
  31. *
  32. * @param path the file path (e.g., "/mnt/sdcard/apps/clock.so")
  33. * @param name buffer to store the extracted module name
  34. * @param name_size size of the name buffer
  35. *
  36. * @note This function extracts the base name without path and extension.
  37. * Examples:
  38. * - "/mnt/sdcard/apps/clock.so" -> "clock"
  39. * - "/mnt/v1.2/app.so" -> "app" (dots in path are ignored)
  40. * - ".hidden" -> ".hidden" (hidden files without extension)
  41. * - ".hidden.so" -> ".hidden" (hidden files with extension)
  42. */
  43. void dlmodule_extract_name(const char *path, char *name, int name_size)
  44. {
  45. int size;
  46. const char *first, *end, *ptr, *last_dot;
  47. RT_ASSERT(path != RT_NULL);
  48. RT_ASSERT(name != RT_NULL);
  49. RT_ASSERT(name_size > 0);
  50. ptr = first = path;
  51. end = path + rt_strlen(path);
  52. /* find the start of filename (after last '/') */
  53. while (*ptr != '\0')
  54. {
  55. if (*ptr == '/')
  56. first = ptr + 1;
  57. ptr++;
  58. }
  59. /* find last extension in filename portion only (after last '/') */
  60. last_dot = RT_NULL;
  61. ptr = first;
  62. while (*ptr != '\0')
  63. {
  64. if (*ptr == '.')
  65. last_dot = ptr;
  66. ptr++;
  67. }
  68. /* determine end position for module name */
  69. if (last_dot != RT_NULL && last_dot != first)
  70. {
  71. /* extension found (dot not at start of filename), strip it */
  72. end = last_dot;
  73. }
  74. /* else: no extension, or filename starts with dot only (e.g., ".hidden"),
  75. * use entire filename */
  76. size = end - first;
  77. if (size <= 0)
  78. {
  79. /* defensive: empty path or path ending with "/" */
  80. size = rt_strlen(first);
  81. }
  82. if (size >= name_size)
  83. size = name_size - 1;
  84. rt_strncpy(name, first, size);
  85. name[size] = '\0';
  86. }
  87. /* set the name of module */
  88. static void _dlmodule_set_name(struct rt_dlmodule *module, const char *path)
  89. {
  90. struct rt_object *object;
  91. object = &(module->parent);
  92. dlmodule_extract_name(path, object->name, RT_NAME_MAX);
  93. }
  94. #define RT_MODULE_ARG_MAX 8
  95. static int _rt_module_split_arg(char *cmd, rt_size_t length, char *argv[])
  96. {
  97. int argc = 0;
  98. char *ptr = cmd;
  99. while ((ptr - cmd) < length)
  100. {
  101. /* strip bank and tab */
  102. while ((*ptr == ' ' || *ptr == '\t') && (ptr - cmd) < length)
  103. *ptr++ = '\0';
  104. /* check whether it's the end of line */
  105. if ((ptr - cmd) >= length) break;
  106. /* handle string with quote */
  107. if (*ptr == '"')
  108. {
  109. argv[argc++] = ++ptr;
  110. /* skip this string */
  111. while (*ptr != '"' && (ptr - cmd) < length)
  112. if (*ptr ++ == '\\') ptr ++;
  113. if ((ptr - cmd) >= length) break;
  114. /* skip '"' */
  115. *ptr ++ = '\0';
  116. }
  117. else
  118. {
  119. argv[argc++] = ptr;
  120. while ((*ptr != ' ' && *ptr != '\t') && (ptr - cmd) < length)
  121. ptr ++;
  122. }
  123. if (argc >= RT_MODULE_ARG_MAX) break;
  124. }
  125. return argc;
  126. }
  127. /* invoked by main thread for exit */
  128. static void _dlmodule_exit(void)
  129. {
  130. struct rt_dlmodule *module;
  131. module = dlmodule_self();
  132. if (!module) return; /* not a module thread */
  133. rt_enter_critical();
  134. if (module->stat == RT_DLMODULE_STAT_RUNNING)
  135. {
  136. struct rt_object *object = RT_NULL;
  137. struct rt_list_node *node = RT_NULL;
  138. /* set stat to closing */
  139. module->stat = RT_DLMODULE_STAT_CLOSING;
  140. /* suspend all threads in this module */
  141. for (node = module->object_list.next; node != &(module->object_list); node = node->next)
  142. {
  143. object = rt_list_entry(node, struct rt_object, list);
  144. if ((object->type & ~RT_Object_Class_Static) == RT_Object_Class_Thread)
  145. {
  146. rt_thread_t thread = (rt_thread_t)object;
  147. /* stop timer and suspend thread*/
  148. if ((RT_SCHED_CTX(thread).stat & RT_THREAD_STAT_MASK) != RT_THREAD_CLOSE &&
  149. (RT_SCHED_CTX(thread).stat & RT_THREAD_STAT_MASK) != RT_THREAD_INIT)
  150. {
  151. rt_timer_stop(&(thread->thread_timer));
  152. rt_thread_suspend(thread);
  153. }
  154. }
  155. }
  156. }
  157. rt_exit_critical();
  158. return;
  159. }
  160. static void _dlmodule_thread_entry(void* parameter)
  161. {
  162. int argc = 0;
  163. char *argv[RT_MODULE_ARG_MAX];
  164. struct rt_dlmodule *module = (struct rt_dlmodule*)parameter;
  165. if (module == RT_NULL || module->cmd_line == RT_NULL)
  166. /* malloc for module_cmd_line failed. */
  167. return;
  168. if (module->cmd_line)
  169. {
  170. rt_memset(argv, 0x00, sizeof(argv));
  171. argc = _rt_module_split_arg((char *)module->cmd_line, rt_strlen(module->cmd_line), argv);
  172. if (argc == 0) goto __exit;
  173. }
  174. /* set status of module */
  175. module->stat = RT_DLMODULE_STAT_RUNNING;
  176. LOG_D("run main entry: 0x%p with %s",
  177. module->entry_addr,
  178. module->cmd_line);
  179. if (module->entry_addr)
  180. module->entry_addr(argc, argv);
  181. __exit:
  182. _dlmodule_exit();
  183. return ;
  184. }
  185. /**
  186. * @brief create a dynamic module object and initialize it.
  187. *
  188. * @return struct rt_dlmodule* If module create successfully, return the pointer to its rt_dlmodule structure.
  189. */
  190. struct rt_dlmodule *dlmodule_create(void)
  191. {
  192. struct rt_dlmodule *module = RT_NULL;
  193. module = (struct rt_dlmodule*) rt_object_allocate(RT_Object_Class_Module, "module");
  194. if (module)
  195. {
  196. module->stat = RT_DLMODULE_STAT_INIT;
  197. /* set initial priority and stack size */
  198. module->priority = RT_THREAD_PRIORITY_MAX - 1;
  199. module->stack_size = 2048;
  200. rt_list_init(&(module->object_list));
  201. }
  202. return module;
  203. }
  204. void dlmodule_destroy_subthread(struct rt_dlmodule *module, rt_thread_t thread)
  205. {
  206. RT_ASSERT(thread->parent.module_id== module);
  207. /* lock scheduler to prevent scheduling in cleanup function. */
  208. rt_enter_critical();
  209. rt_thread_close(thread);
  210. /* remove thread from thread_list (defunct thread list) */
  211. rt_list_remove(&RT_THREAD_LIST_NODE(thread));
  212. /* invoke thread cleanup */
  213. if (thread->cleanup != RT_NULL)
  214. thread->cleanup(thread);
  215. rt_exit_critical();
  216. #ifdef RT_USING_SIGNALS
  217. rt_thread_free_sig(thread);
  218. #endif
  219. if (thread->parent.type & RT_Object_Class_Static)
  220. {
  221. /* detach object */
  222. rt_object_detach((rt_object_t)thread);
  223. }
  224. #ifdef RT_USING_HEAP
  225. else
  226. {
  227. /* release thread's stack */
  228. RT_KERNEL_FREE(thread->stack_addr);
  229. /* delete thread object */
  230. rt_object_delete((rt_object_t)thread);
  231. }
  232. #endif
  233. }
  234. /**
  235. * @brief destroy dynamic module and cleanup all kernel objects inside it.
  236. *
  237. * @param module Pointer to the module to be destroyed.
  238. * @return rt_err_t On success, it returns RT_EOK. Otherwise, it returns the error code.
  239. */
  240. rt_err_t dlmodule_destroy(struct rt_dlmodule* module)
  241. {
  242. int i;
  243. RT_DEBUG_NOT_IN_INTERRUPT;
  244. /* check parameter */
  245. if (module == RT_NULL)
  246. return -RT_ERROR;
  247. /* can not destroy a running module */
  248. if (module->stat == RT_DLMODULE_STAT_RUNNING)
  249. return -RT_EBUSY;
  250. /* do module cleanup */
  251. if (module->cleanup_func)
  252. {
  253. rt_enter_critical();
  254. module->cleanup_func(module);
  255. rt_exit_critical();
  256. }
  257. /* list_object(&(module->object_list));*/
  258. /* cleanup for all kernel objects inside module*/
  259. {
  260. struct rt_object *object = RT_NULL;
  261. struct rt_list_node *node = RT_NULL;
  262. /* detach/delete all threads in this module */
  263. for (node = module->object_list.next; node != &(module->object_list); )
  264. {
  265. int object_type;
  266. object = rt_list_entry(node, struct rt_object, list);
  267. object_type = object->type & ~RT_Object_Class_Static;
  268. /* to next node */
  269. node = node->next;
  270. if (object->type & RT_Object_Class_Static)
  271. {
  272. switch (object_type)
  273. {
  274. case RT_Object_Class_Thread:
  275. dlmodule_destroy_subthread(module, (rt_thread_t)object);
  276. break;
  277. #ifdef RT_USING_SEMAPHORE
  278. case RT_Object_Class_Semaphore:
  279. rt_sem_detach((rt_sem_t)object);
  280. break;
  281. #endif
  282. #ifdef RT_USING_MUTEX
  283. case RT_Object_Class_Mutex:
  284. rt_mutex_detach((rt_mutex_t)object);
  285. break;
  286. #endif
  287. #ifdef RT_USING_EVENT
  288. case RT_Object_Class_Event:
  289. rt_event_detach((rt_event_t)object);
  290. break;
  291. #endif
  292. #ifdef RT_USING_MAILBOX
  293. case RT_Object_Class_MailBox:
  294. rt_mb_detach((rt_mailbox_t)object);
  295. break;
  296. #endif
  297. #ifdef RT_USING_MESSAGEQUEUE
  298. case RT_Object_Class_MessageQueue:
  299. rt_mq_detach((rt_mq_t)object);
  300. break;
  301. #endif
  302. #ifdef RT_USING_MEMHEAP
  303. case RT_Object_Class_MemHeap:
  304. rt_memheap_detach((struct rt_memheap*)object);
  305. break;
  306. #endif
  307. #ifdef RT_USING_MEMPOOL
  308. case RT_Object_Class_MemPool:
  309. rt_mp_detach((struct rt_mempool*)object);
  310. break;
  311. #endif
  312. case RT_Object_Class_Timer:
  313. rt_timer_detach((rt_timer_t)object);
  314. break;
  315. default:
  316. LOG_E("Unsupported oject type in module.");
  317. break;
  318. }
  319. }
  320. else
  321. {
  322. switch (object_type)
  323. {
  324. case RT_Object_Class_Thread:
  325. dlmodule_destroy_subthread(module, (rt_thread_t)object);
  326. break;
  327. #ifdef RT_USING_SEMAPHORE
  328. case RT_Object_Class_Semaphore:
  329. rt_sem_delete((rt_sem_t)object);
  330. break;
  331. #endif
  332. #ifdef RT_USING_MUTEX
  333. case RT_Object_Class_Mutex:
  334. rt_mutex_delete((rt_mutex_t)object);
  335. break;
  336. #endif
  337. #ifdef RT_USING_EVENT
  338. case RT_Object_Class_Event:
  339. rt_event_delete((rt_event_t)object);
  340. break;
  341. #endif
  342. #ifdef RT_USING_MAILBOX
  343. case RT_Object_Class_MailBox:
  344. rt_mb_delete((rt_mailbox_t)object);
  345. break;
  346. #endif
  347. #ifdef RT_USING_MESSAGEQUEUE
  348. case RT_Object_Class_MessageQueue:
  349. rt_mq_delete((rt_mq_t)object);
  350. break;
  351. #endif
  352. #ifdef RT_USING_MEMHEAP
  353. /* no delete operation */
  354. #endif
  355. #ifdef RT_USING_MEMPOOL
  356. case RT_Object_Class_MemPool:
  357. rt_mp_delete((struct rt_mempool*)object);
  358. break;
  359. #endif
  360. case RT_Object_Class_Timer:
  361. rt_timer_delete((rt_timer_t)object);
  362. break;
  363. default:
  364. LOG_E("Unsupported oject type in module.");
  365. break;
  366. }
  367. }
  368. }
  369. }
  370. if (module->cmd_line) rt_free(module->cmd_line);
  371. /* release module symbol table */
  372. for (i = 0; i < module->nsym; i ++)
  373. {
  374. rt_free((void *)module->symtab[i].name);
  375. }
  376. if (module->symtab != RT_NULL)
  377. {
  378. rt_free(module->symtab);
  379. }
  380. /* destory module */
  381. rt_free(module->mem_space);
  382. /* delete module object */
  383. rt_object_delete((rt_object_t)module);
  384. return RT_EOK;
  385. }
  386. /**
  387. * @brief retrieve the dynamically loaded module that the current thread belongs to.
  388. *
  389. * @return struct rt_dlmodule* On success, it returns a pointer to the module. otherwise, it returns RT_NULL.
  390. */
  391. struct rt_dlmodule *dlmodule_self(void)
  392. {
  393. rt_thread_t tid;
  394. struct rt_dlmodule *ret = RT_NULL;
  395. tid = rt_thread_self();
  396. if (tid)
  397. {
  398. ret = (struct rt_dlmodule*) tid->parent.module_id;
  399. }
  400. return ret;
  401. }
  402. /*
  403. * Compatible with old API
  404. */
  405. struct rt_dlmodule *rt_module_self(void)
  406. {
  407. return dlmodule_self();
  408. }
  409. /**
  410. * @brief load an ELF module to memory.
  411. *
  412. * @param filename the path to the module to load.
  413. * @return struct rt_dlmodule* On success, it returns a pointer to the module object. otherwise, RT_NULL is returned.
  414. *
  415. * @note the function is used to load an ELF (Executable and Linkable Format) module from a file, validate it,
  416. * and initialize it as a dynamically loaded module. what it implements are as follows:
  417. * 1. Load and Validate ELF: It loads an ELF file, checks its validity, and identifies it as either a relocatable or shared object.
  418. * 2. Memory Allocation and Cleanup: Uses rt_malloc and rt_free to allocate and free memory for module data.
  419. * Error handling ensures all resources are released if an error occurs.
  420. * 3. Symbol Resolution and Initialization: Sets up init function and cleanup function, and calls the module_init function if it is present.
  421. * 4. Cache Management: Optionally (when RT_USING_CACHE defined) flushes data and invalidates instruction caches to ensure the module is correctly loaded into memory.
  422. */
  423. struct rt_dlmodule* dlmodule_load(const char* filename)
  424. {
  425. #ifdef RT_USING_POSIX_FS
  426. int fd = -1, length = 0;
  427. #endif
  428. rt_err_t ret = RT_EOK;
  429. rt_uint8_t *module_ptr = RT_NULL;
  430. struct rt_dlmodule *module = RT_NULL;
  431. #ifdef RT_USING_POSIX_FS
  432. fd = open(filename, O_RDONLY, 0);
  433. if (fd >= 0)
  434. {
  435. length = lseek(fd, 0, SEEK_END);
  436. lseek(fd, 0, SEEK_SET);
  437. if (length == 0) goto __exit;
  438. module_ptr = (uint8_t*) rt_malloc (length);
  439. if (!module_ptr) goto __exit;
  440. if (read(fd, module_ptr, length) != length)
  441. goto __exit;
  442. /* close file and release fd */
  443. close(fd);
  444. fd = -1;
  445. }
  446. else
  447. {
  448. goto __exit;
  449. }
  450. #endif
  451. if (!module_ptr) goto __exit;
  452. /* check ELF header */
  453. if (rt_memcmp(elf_module->e_ident, RTMMAG, SELFMAG) != 0 &&
  454. rt_memcmp(elf_module->e_ident, ELFMAG, SELFMAG) != 0)
  455. {
  456. rt_kprintf("Module: magic error\n");
  457. goto __exit;
  458. }
  459. /* check ELF class */
  460. if ((elf_module->e_ident[EI_CLASS] != ELFCLASS32)&&(elf_module->e_ident[EI_CLASS] != ELFCLASS64))
  461. {
  462. rt_kprintf("Module: ELF class error\n");
  463. goto __exit;
  464. }
  465. module = dlmodule_create();
  466. if (!module) goto __exit;
  467. /* set the name of module */
  468. _dlmodule_set_name(module, filename);
  469. LOG_D("rt_module_load: %.*s", RT_NAME_MAX, module->parent.name);
  470. if (elf_module->e_type == ET_REL)
  471. {
  472. ret = dlmodule_load_relocated_object(module, module_ptr);
  473. }
  474. else if (elf_module->e_type == ET_DYN)
  475. {
  476. ret = dlmodule_load_shared_object(module, module_ptr);
  477. }
  478. else
  479. {
  480. rt_kprintf("Module: unsupported elf type\n");
  481. goto __exit;
  482. }
  483. /* check return value */
  484. if (ret != RT_EOK) goto __exit;
  485. /* release module data */
  486. rt_free(module_ptr);
  487. /* increase module reference count */
  488. module->nref ++;
  489. /* deal with cache */
  490. #ifdef RT_USING_CACHE
  491. rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, module->mem_space, module->mem_size);
  492. rt_hw_cpu_icache_ops(RT_HW_CACHE_INVALIDATE, module->mem_space, module->mem_size);
  493. #endif
  494. /* set module initialization and cleanup function */
  495. module->init_func = dlsym(module, "module_init");
  496. module->cleanup_func = dlsym(module, "module_cleanup");
  497. module->stat = RT_DLMODULE_STAT_INIT;
  498. /* do module initialization */
  499. if (module->init_func)
  500. {
  501. module->init_func(module);
  502. }
  503. return module;
  504. __exit:
  505. #ifdef RT_USING_POSIX_FS
  506. if (fd >= 0) close(fd);
  507. #endif
  508. if (module_ptr) rt_free(module_ptr);
  509. if (module) dlmodule_destroy(module);
  510. return RT_NULL;
  511. }
  512. /**
  513. * @brief load a dynamic module, and create a thread to excute the module main function.
  514. *
  515. * @param pgname path of the module to be loaded.
  516. * @param cmd the command string (with commandline options) for startup module.
  517. * @param cmd_size the command's length.
  518. * @return struct rt_dlmodule* On success, it returns a pointer to the module object. otherwise, RT_NULL is returned.
  519. */
  520. struct rt_dlmodule* dlmodule_exec(const char* pgname, const char* cmd, int cmd_size)
  521. {
  522. struct rt_dlmodule *module = RT_NULL;
  523. module = dlmodule_load(pgname);
  524. if (module)
  525. {
  526. if (module->entry_addr)
  527. {
  528. /* exec this module */
  529. rt_thread_t tid;
  530. module->cmd_line = rt_strdup(cmd);
  531. /* check stack size and priority */
  532. if (module->priority > RT_THREAD_PRIORITY_MAX) module->priority = RT_THREAD_PRIORITY_MAX - 1;
  533. if (module->stack_size < 2048 || module->stack_size > (1024 * 32)) module->stack_size = 2048;
  534. tid = rt_thread_create(module->parent.name, _dlmodule_thread_entry, (void*)module,
  535. module->stack_size, module->priority, 10);
  536. if (tid)
  537. {
  538. tid->parent.module_id= module;
  539. module->main_thread = tid;
  540. rt_thread_startup(tid);
  541. }
  542. else
  543. {
  544. /* destory dl module */
  545. dlmodule_destroy(module);
  546. module = RT_NULL;
  547. }
  548. }
  549. }
  550. return module;
  551. }
  552. #if defined(RT_USING_CUSTOM_DLMODULE)
  553. struct rt_dlmodule* dlmodule_load_custom(const char* filename, struct rt_dlmodule_ops* ops)
  554. {
  555. #ifdef RT_USING_POSIX_FS
  556. int fd = -1, length = 0;
  557. #endif
  558. rt_err_t ret = RT_EOK;
  559. rt_uint8_t *module_ptr = RT_NULL;
  560. struct rt_dlmodule *module = RT_NULL;
  561. if (ops)
  562. {
  563. RT_ASSERT(ops->load);
  564. RT_ASSERT(ops->unload);
  565. module_ptr = ops->load(filename);
  566. }
  567. #ifdef RT_USING_POSIX_FS
  568. else
  569. {
  570. fd = open(filename, O_RDONLY, 0);
  571. if (fd >= 0)
  572. {
  573. length = lseek(fd, 0, SEEK_END);
  574. lseek(fd, 0, SEEK_SET);
  575. if (length == 0) goto __exit;
  576. module_ptr = (uint8_t*) rt_malloc (length);
  577. if (!module_ptr) goto __exit;
  578. if (read(fd, module_ptr, length) != length)
  579. goto __exit;
  580. /* close file and release fd */
  581. close(fd);
  582. fd = -1;
  583. }
  584. else
  585. {
  586. goto __exit;
  587. }
  588. }
  589. #endif
  590. if (!module_ptr) goto __exit;
  591. /* check ELF header */
  592. if (rt_memcmp(elf_module->e_ident, RTMMAG, SELFMAG) != 0 &&
  593. rt_memcmp(elf_module->e_ident, ELFMAG, SELFMAG) != 0)
  594. {
  595. rt_kprintf("Module: magic error\n");
  596. goto __exit;
  597. }
  598. /* check ELF class */
  599. if (elf_module->e_ident[EI_CLASS] != ELFCLASS32)
  600. {
  601. rt_kprintf("Module: ELF class error\n");
  602. goto __exit;
  603. }
  604. module = dlmodule_create();
  605. if (!module) goto __exit;
  606. /* set the name of module */
  607. _dlmodule_set_name(module, filename);
  608. LOG_D("rt_module_load: %.*s", RT_NAME_MAX, module->parent.name);
  609. if (elf_module->e_type == ET_REL)
  610. {
  611. ret = dlmodule_load_relocated_object(module, module_ptr);
  612. }
  613. else if (elf_module->e_type == ET_DYN)
  614. {
  615. ret = dlmodule_load_shared_object(module, module_ptr);
  616. }
  617. else
  618. {
  619. rt_kprintf("Module: unsupported elf type\n");
  620. goto __exit;
  621. }
  622. /* check return value */
  623. if (ret != RT_EOK) goto __exit;
  624. /* release module data */
  625. if (ops)
  626. {
  627. ops->unload(module_ptr);
  628. }
  629. else
  630. {
  631. rt_free(module_ptr);
  632. }
  633. /* increase module reference count */
  634. module->nref ++;
  635. /* deal with cache */
  636. #ifdef RT_USING_CACHE
  637. rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, module->mem_space, module->mem_size);
  638. rt_hw_cpu_icache_ops(RT_HW_CACHE_INVALIDATE, module->mem_space, module->mem_size);
  639. #endif
  640. /* set module initialization and cleanup function */
  641. module->init_func = dlsym(module, "module_init");
  642. module->cleanup_func = dlsym(module, "module_cleanup");
  643. module->stat = RT_DLMODULE_STAT_INIT;
  644. /* do module initialization */
  645. if (module->init_func)
  646. {
  647. module->init_func(module);
  648. }
  649. return module;
  650. __exit:
  651. #ifdef RT_USING_POSIX_FS
  652. if (fd >= 0) close(fd);
  653. #endif
  654. if (module_ptr)
  655. {
  656. if (ops)
  657. {
  658. ops->unload(module_ptr);
  659. }
  660. else
  661. {
  662. rt_free(module_ptr);
  663. }
  664. }
  665. if (module) dlmodule_destroy(module);
  666. return RT_NULL;
  667. }
  668. struct rt_dlmodule* dlmodule_exec_custom(const char* pgname, const char* cmd, int cmd_size, struct rt_dlmodule_ops* ops)
  669. {
  670. struct rt_dlmodule *module = RT_NULL;
  671. module = dlmodule_load_custom(pgname, ops);
  672. if (module)
  673. {
  674. if (module->entry_addr)
  675. {
  676. /* exec this module */
  677. rt_thread_t tid;
  678. module->cmd_line = rt_strdup(cmd);
  679. /* check stack size and priority */
  680. if (module->priority > RT_THREAD_PRIORITY_MAX) module->priority = RT_THREAD_PRIORITY_MAX - 1;
  681. if (module->stack_size < 2048 || module->stack_size > (1024 * 32)) module->stack_size = 2048;
  682. tid = rt_thread_create(module->parent.name, _dlmodule_thread_entry, (void*)module,
  683. module->stack_size, module->priority, 10);
  684. if (tid)
  685. {
  686. tid->parent.module_id= module;
  687. module->main_thread = tid;
  688. rt_thread_startup(tid);
  689. }
  690. else
  691. {
  692. /* destory dl module */
  693. dlmodule_destroy(module);
  694. module = RT_NULL;
  695. }
  696. }
  697. }
  698. return module;
  699. }
  700. #endif
  701. /**
  702. * @brief exit a dynamically loaded module.
  703. *
  704. * @param ret_code the return code for module exit.
  705. *
  706. * @note this function is responsible for gracefully exiting a dynamically loaded module, releasing resources associated with the module,
  707. * and handling cleanup operations. what it implements are as follows:
  708. * 1. Thread and Resource Cleanup: The function safely exits a module by deleting its main thread and freeing resources associated with it.
  709. * 2. Status Management: Checks and updates the module's state, setting a return code and calling _dlmodule_exit() to transition to a closing state.
  710. * 3. Critical Sections: Critical sections ensure that the exit process is atomic and free from race conditions.
  711. */
  712. void dlmodule_exit(int ret_code)
  713. {
  714. rt_thread_t thread;
  715. struct rt_dlmodule *module;
  716. module = dlmodule_self();
  717. if (!module) return;
  718. /* disable scheduling */
  719. rt_enter_critical();
  720. /* module is not running */
  721. if (module->stat != RT_DLMODULE_STAT_RUNNING)
  722. {
  723. /* restore scheduling */
  724. rt_exit_critical();
  725. return;
  726. }
  727. /* set return code */
  728. module->ret_code = ret_code;
  729. /* do exit for this module */
  730. _dlmodule_exit();
  731. /* the stat of module was changed to CLOSING in _dlmodule_exit */
  732. thread = module->main_thread;
  733. if ((RT_SCHED_CTX(thread).stat & RT_THREAD_STAT_MASK) == RT_THREAD_CLOSE)
  734. {
  735. /* main thread already closed */
  736. rt_exit_critical();
  737. return ;
  738. }
  739. /* delete thread: insert to defunct thread list */
  740. rt_thread_delete(thread);
  741. /* enable scheduling */
  742. rt_exit_critical();
  743. }
  744. /**
  745. * @brief search for a symbol by its name in the kernel symbol table.
  746. *
  747. * @param sym_str the symbol name string.
  748. * @return rt_ubase_t On success, it returns the address of the symbol.
  749. * Otherwise, it returns 0 (indicating the symbol was not found).
  750. */
  751. rt_ubase_t dlmodule_symbol_find(const char *sym_str)
  752. {
  753. /* find in kernel symbol table */
  754. struct rt_module_symtab *index;
  755. for (index = _rt_module_symtab_begin; index != _rt_module_symtab_end; index ++)
  756. {
  757. if (rt_strcmp(index->name, sym_str) == 0)
  758. return (rt_ubase_t)index->addr;
  759. }
  760. return 0;
  761. }
  762. int rt_system_dlmodule_init(void)
  763. {
  764. #if defined(__GNUC__) && !defined(__CC_ARM)
  765. extern int __rtmsymtab_start;
  766. extern int __rtmsymtab_end;
  767. _rt_module_symtab_begin = (struct rt_module_symtab *)&__rtmsymtab_start;
  768. _rt_module_symtab_end = (struct rt_module_symtab *)&__rtmsymtab_end;
  769. #elif defined (__CC_ARM)
  770. extern int RTMSymTab$$Base;
  771. extern int RTMSymTab$$Limit;
  772. _rt_module_symtab_begin = (struct rt_module_symtab *)&RTMSymTab$$Base;
  773. _rt_module_symtab_end = (struct rt_module_symtab *)&RTMSymTab$$Limit;
  774. #elif defined (__IAR_SYSTEMS_ICC__)
  775. _rt_module_symtab_begin = __section_begin("RTMSymTab");
  776. _rt_module_symtab_end = __section_end("RTMSymTab");
  777. #endif
  778. return 0;
  779. }
  780. INIT_COMPONENT_EXPORT(rt_system_dlmodule_init);
  781. /**
  782. * This function will find the specified module.
  783. *
  784. * @param name the name of module finding
  785. *
  786. * @return the module
  787. */
  788. struct rt_dlmodule *dlmodule_find(const char *name)
  789. {
  790. rt_object_t object;
  791. struct rt_dlmodule *ret = RT_NULL;
  792. object = rt_object_find(name, RT_Object_Class_Module);
  793. if (object)
  794. {
  795. ret = (struct rt_dlmodule*) object;
  796. }
  797. return ret;
  798. }
  799. RTM_EXPORT(dlmodule_find);
  800. int list_symbols(void)
  801. {
  802. extern int __rtmsymtab_start;
  803. extern int __rtmsymtab_end;
  804. /* find in kernel symbol table */
  805. struct rt_module_symtab *index;
  806. for (index = _rt_module_symtab_begin;
  807. index != _rt_module_symtab_end;
  808. index ++)
  809. {
  810. rt_kprintf("%s => 0x%08x\n", index->name, index->addr);
  811. }
  812. return 0;
  813. }
  814. MSH_CMD_EXPORT(list_symbols, list symbols information);
  815. int list_module(void)
  816. {
  817. struct rt_dlmodule *module;
  818. struct rt_list_node *list, *node;
  819. struct rt_object_information *info;
  820. info = rt_object_get_information(RT_Object_Class_Module);
  821. list = &info->object_list;
  822. rt_kprintf("module ref address \n");
  823. rt_kprintf("-------- -------- ------------\n");
  824. for (node = list->next; node != list; node = node->next)
  825. {
  826. module = (struct rt_dlmodule *)(rt_list_entry(node, struct rt_object, list));
  827. rt_kprintf("%-*.*s %-04d 0x%08x\n",
  828. RT_NAME_MAX, RT_NAME_MAX, module->parent.name, module->nref, module->mem_space);
  829. }
  830. return 0;
  831. }
  832. MSH_CMD_EXPORT(list_module, list modules in system);