shim_init.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. /* Copyright (C) 2014 OSCAR lab, Stony Brook University
  4. This file is part of Graphene Library OS.
  5. Graphene Library OS is free software: you can redistribute it and/or
  6. modify it under the terms of the GNU General Public License
  7. as published by the Free Software Foundation, either version 3 of the
  8. License, or (at your option) any later version.
  9. Graphene Library OS is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  15. /*
  16. * shim_init.c
  17. *
  18. * This file contains entry and exit functions of library OS.
  19. */
  20. #include <shim_internal.h>
  21. #include <shim_tls.h>
  22. #include <shim_thread.h>
  23. #include <shim_handle.h>
  24. #include <shim_vma.h>
  25. #include <shim_checkpoint.h>
  26. #include <shim_fs.h>
  27. #include <shim_ipc.h>
  28. #include <shim_profile.h>
  29. #include <pal.h>
  30. #include <pal_debug.h>
  31. #include <pal_error.h>
  32. #include <sys/mman.h>
  33. #include <asm/unistd.h>
  34. #include <asm/fcntl.h>
  35. unsigned long allocsize;
  36. unsigned long allocshift;
  37. unsigned long allocmask;
  38. /* The following constants will help matching glibc version with compatible
  39. SHIM libraries */
  40. #include "glibc-version.h"
  41. const unsigned int glibc_vers_2_17 = GLIBC_VERSION_2_17;
  42. static void handle_failure (PAL_PTR event, PAL_NUM arg, PAL_CONTEXT * context)
  43. {
  44. SHIM_GET_TLS()->pal_errno = (arg <= PAL_ERROR_BOUND) ? arg : 0;
  45. }
  46. void __assert_fail (const char * assertion, const char * file,
  47. unsigned int line, const char * function)
  48. {
  49. __sys_printf("assert failed %s:%d %s\n", file, line, assertion);
  50. pause();
  51. shim_terminate();
  52. }
  53. void __stack_chk_fail (void)
  54. {
  55. }
  56. static int pal_errno_to_unix_errno [PAL_ERROR_BOUND + 1] = {
  57. /* reserved */ 0,
  58. /* PAL_ERROR_NOTIMPLEMENTED */ ENOSYS,
  59. /* PAL_ERROR_NOTDEFINED */ ENOSYS,
  60. /* PAL_ERROR_NOTSUPPORT */ EACCES,
  61. /* PAL_ERROR_INVAL */ EINVAL,
  62. /* PAL_ERROR_TOOLONG */ ENAMETOOLONG,
  63. /* PAL_ERROR_DENIED */ EACCES,
  64. /* PAL_ERROR_BADHANDLE */ EFAULT,
  65. /* PAL_ERROR_STREAMEXIST */ EEXIST,
  66. /* PAL_ERROR_STREAMNOTEXIST */ ENOENT,
  67. /* PAL_ERROR_STREAMISFILE */ ENOTDIR,
  68. /* PAL_ERROR_STREAMISDIR */ EISDIR,
  69. /* PAL_ERROR_STREAMISDEVICE */ ESPIPE,
  70. /* PAL_ERROR_INTERRUPTED */ EINTR,
  71. /* PAL_ERROR_OVERFLOW */ EFAULT,
  72. /* PAL_ERROR_BADADDR */ EFAULT,
  73. /* PAL_ERROR_NOMEM */ ENOMEM,
  74. /* PAL_ERROR_NOTKILLABLE */ EACCES,
  75. /* PAL_ERROR_INCONSIST */ EFAULT,
  76. /* PAL_ERROR_TRYAGAIN */ EAGAIN,
  77. /* PAL_ERROR_ENDOFSTREAM */ 0,
  78. /* PAL_ERROR_NOTSERVER */ EINVAL,
  79. /* PAL_ERROR_NOTCONNECTION */ ENOTCONN,
  80. /* PAL_ERROR_ZEROSIZE */ 0,
  81. /* PAL_ERROR_CONNFAILED */ ECONNRESET,
  82. /* PAL_ERROR_ADDRNOTEXIST */ EADDRNOTAVAIL,
  83. };
  84. long convert_pal_errno (long err)
  85. {
  86. return (err >= 0 && err <= PAL_ERROR_BOUND) ?
  87. pal_errno_to_unix_errno[err] : 0;
  88. }
  89. void * initial_stack = NULL;
  90. const char ** initial_envp __attribute_migratable = NULL;
  91. void * migrated_memory_start = 0;
  92. void * migrated_memory_end = 0;
  93. extern void * migrated_shim_addr;
  94. const char ** library_paths = NULL;
  95. bool in_gdb = false;
  96. LOCKTYPE __master_lock;
  97. bool lock_enabled = false;
  98. void init_tcb (shim_tcb_t * tcb)
  99. {
  100. tcb->canary = SHIM_TLS_CANARY;
  101. tcb->self = tcb;
  102. }
  103. void copy_tcb (shim_tcb_t * new_tcb, const shim_tcb_t * old_tcb)
  104. {
  105. memset(new_tcb, 0, sizeof(shim_tcb_t));
  106. new_tcb->canary = SHIM_TLS_CANARY;
  107. new_tcb->self = new_tcb;
  108. new_tcb->tp = old_tcb->tp;
  109. memcpy(&new_tcb->context, &old_tcb->context, sizeof(struct shim_context));
  110. new_tcb->tid = old_tcb->tid;
  111. new_tcb->debug_buf = old_tcb->debug_buf;
  112. }
  113. /* This function is used to allocate tls before interpreter start running */
  114. void allocate_tls (void * tcb_location, struct shim_thread * thread)
  115. {
  116. __libc_tcb_t * tcb = tcb_location;
  117. assert(tcb);
  118. tcb->tcb = tcb;
  119. init_tcb(&tcb->shim_tcb);
  120. if (thread) {
  121. thread->tcb = tcb;
  122. thread->user_tcb = false;
  123. tcb->shim_tcb.tp = thread;
  124. tcb->shim_tcb.tid = thread->tid;
  125. } else {
  126. tcb->shim_tcb.tp = NULL;
  127. tcb->shim_tcb.tid = 0;
  128. }
  129. DkThreadPrivate(tcb);
  130. assert(SHIM_TLS_CHECK_CANARY());
  131. }
  132. void populate_tls (void * tcb_location, bool user)
  133. {
  134. __libc_tcb_t * tcb = (__libc_tcb_t *) tcb_location;
  135. assert(tcb);
  136. tcb->tcb = tcb;
  137. copy_tcb(&tcb->shim_tcb, SHIM_GET_TLS());
  138. struct shim_thread * thread = (struct shim_thread *) tcb->shim_tcb.tp;
  139. if (thread) {
  140. thread->tcb = tcb;
  141. thread->user_tcb = user;
  142. }
  143. DkThreadPrivate(tcb);
  144. assert(SHIM_TLS_CHECK_CANARY());
  145. }
  146. DEFINE_PROFILE_OCCURENCE(alloc_stack, memory);
  147. DEFINE_PROFILE_OCCURENCE(alloc_stack_count, memory);
  148. #define STACK_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS|VMA_INTERNAL)
  149. void * allocate_stack (size_t size, size_t protect_size, bool user)
  150. {
  151. size = ALIGN_UP(size);
  152. protect_size = ALIGN_UP(protect_size);
  153. /* preserve a non-readable, non-writeable page below the user
  154. stack to stop user program to clobber other vmas */
  155. void * stack = user ?
  156. get_unmapped_vma(size + protect_size, STACK_FLAGS) :
  157. NULL;
  158. if (user)
  159. stack = DkVirtualMemoryAlloc(stack, size + protect_size,
  160. 0, PAL_PROT_READ|PAL_PROT_WRITE);
  161. else
  162. stack = system_malloc(size + protect_size);
  163. if (!stack)
  164. return NULL;
  165. ADD_PROFILE_OCCURENCE(alloc_stack, size + protect_size);
  166. INC_PROFILE_OCCURENCE(alloc_stack_count);
  167. if (protect_size &&
  168. !DkVirtualMemoryProtect(stack, protect_size, PAL_PROT_NONE))
  169. return NULL;
  170. stack += protect_size;
  171. if (user) {
  172. if (bkeep_mmap(stack, size, PROT_READ|PROT_WRITE,
  173. STACK_FLAGS, NULL, 0, "stack") < 0)
  174. return NULL;
  175. if (protect_size &&
  176. bkeep_mmap(stack - protect_size, protect_size, 0,
  177. STACK_FLAGS, NULL, 0, NULL) < 0)
  178. return NULL;
  179. }
  180. debug("allocated stack at %p (size = %d)\n", stack, size);
  181. return stack;
  182. }
  183. int populate_user_stack (void * stack, size_t stack_size,
  184. int nauxv, elf_auxv_t ** auxpp,
  185. const char *** argvp, const char *** envpp)
  186. {
  187. const char ** argv = *argvp, ** envp = *envpp;
  188. const char ** new_argv = NULL, ** new_envp = NULL;
  189. void * stack_bottom = stack;
  190. void * stack_top = stack + stack_size;
  191. #define ALLOCATE_TOP(size) \
  192. ({ if ((stack_top -= (size)) < stack_bottom) return -ENOMEM; \
  193. stack_top; })
  194. #define ALLOCATE_BOTTOM(size) \
  195. ({ if ((stack_bottom += (size)) > stack_top) return -ENOMEM; \
  196. stack_bottom - (size); })
  197. if (!argv) {
  198. *(const char **) ALLOCATE_BOTTOM(sizeof(const char *)) = NULL;
  199. goto copy_envp;
  200. }
  201. new_argv = stack_bottom;
  202. while (argv) {
  203. for (const char ** a = argv ; *a ; a++) {
  204. const char ** t = ALLOCATE_BOTTOM(sizeof(const char *));
  205. int len = strlen(*a) + 1;
  206. char * abuf = ALLOCATE_TOP(len);
  207. memcpy(abuf, *a, len);
  208. *t = abuf;
  209. }
  210. *((const char **) ALLOCATE_BOTTOM(sizeof(const char *))) = NULL;
  211. copy_envp:
  212. if (!envp)
  213. break;
  214. new_envp = stack_bottom;
  215. argv = envp;
  216. envp = NULL;
  217. }
  218. if (!new_envp)
  219. *(const char **) ALLOCATE_BOTTOM(sizeof(const char *)) = NULL;
  220. stack_bottom = (void *) ((unsigned long) stack_bottom & ~7UL);
  221. *((unsigned long *) ALLOCATE_TOP(sizeof(unsigned long))) = 0;
  222. if (nauxv) {
  223. elf_auxv_t * old_auxp = *auxpp;
  224. *auxpp = ALLOCATE_TOP(sizeof(elf_auxv_t) * nauxv);
  225. if (old_auxp)
  226. memcpy(*auxpp, old_auxp, nauxv * sizeof(elf_auxv_t));
  227. }
  228. memmove(stack_top - (stack_bottom - stack), stack, stack_bottom - stack);
  229. if (new_argv)
  230. *argvp = (void *) new_argv + (stack_top - stack_bottom);
  231. if (new_envp)
  232. *envpp = (void *) new_envp + (stack_top - stack_bottom);
  233. return 0;
  234. }
  235. unsigned long sys_stack_size = 0;
  236. int init_stack (const char ** argv, const char ** envp, const char *** argpp,
  237. int nauxv, elf_auxv_t ** auxpp)
  238. {
  239. if (!sys_stack_size) {
  240. sys_stack_size = DEFAULT_SYS_STACK_SIZE;
  241. if (root_config) {
  242. char stack_cfg[CONFIG_MAX];
  243. if (get_config(root_config, "sys.stack.size", stack_cfg,
  244. CONFIG_MAX) > 0)
  245. sys_stack_size = ALIGN_UP(atoi(stack_cfg));
  246. }
  247. }
  248. struct shim_thread * cur_thread = get_cur_thread();
  249. if (!cur_thread || cur_thread->stack)
  250. return 0;
  251. void * stack = allocate_stack(sys_stack_size, allocsize, true);
  252. if (!stack)
  253. return -ENOMEM;
  254. if (initial_envp)
  255. envp = initial_envp;
  256. int ret = populate_user_stack(stack, sys_stack_size,
  257. nauxv, auxpp, &argv, &envp);
  258. if (ret < 0)
  259. return ret;
  260. *argpp = argv;
  261. initial_envp = envp;
  262. cur_thread->stack_top = stack + sys_stack_size;
  263. cur_thread->stack = stack;
  264. cur_thread->stack_red = stack - allocsize;
  265. return 0;
  266. }
  267. int read_environs (const char ** envp)
  268. {
  269. for (const char ** e = envp ; *e ; e++) {
  270. switch ((*e)[0]) {
  271. case 'L': {
  272. if (!memcmp(*e, "LD_LIBRARY_PATH=", 16)) {
  273. int npaths = 0;
  274. for (const char * s = (*e) + 16 ; *s ; s++)
  275. if (*s == ':')
  276. npaths++;
  277. const char ** paths = malloc(sizeof(const char *) *
  278. (npaths + 1));
  279. if (!paths)
  280. return -ENOMEM;
  281. const char * s = (*e) + 16, * next;
  282. int cnt = 0;
  283. while (*s) {
  284. for (next = s ; *next && *next != ':' ; next++);
  285. int len = next - s;
  286. char * str = malloc(len + 1);
  287. if (!str)
  288. return -ENOMEM;
  289. memcpy(str, s, len);
  290. str[len] = 0;
  291. paths[cnt++] = str;
  292. s = *next ? next + 1 : next;
  293. }
  294. paths[cnt] = NULL;
  295. library_paths = paths;
  296. break;
  297. }
  298. break;
  299. }
  300. case 'I': {
  301. if (!memcmp(*e, "IN_GDB=1", 8)) {
  302. in_gdb = true;
  303. break;
  304. }
  305. break;
  306. }
  307. }
  308. }
  309. return 0;
  310. }
  311. struct config_store * root_config = NULL;
  312. static void * __malloc (int size)
  313. {
  314. return malloc(size);
  315. }
  316. static void __free (void * mem)
  317. {
  318. free(mem);
  319. }
  320. extern bool ask_for_checkpoint;
  321. int init_manifest (PAL_HANDLE manifest_handle)
  322. {
  323. PAL_STREAM_ATTR attr;
  324. if (!DkStreamAttributesQuerybyHandle(manifest_handle, &attr))
  325. return -PAL_ERRNO;
  326. size_t cfg_size = attr.size;
  327. void * cfg_addr = DkStreamMap(manifest_handle, NULL,
  328. PAL_PROT_READ|PAL_PROT_WRITECOPY, 0,
  329. ALIGN_UP(cfg_size));
  330. if (!cfg_addr)
  331. return -PAL_ERRNO;
  332. root_config = malloc(sizeof(struct config_store));
  333. root_config->raw_data = cfg_addr;
  334. root_config->raw_size = cfg_size;
  335. root_config->malloc = __malloc;
  336. root_config->free = __free;
  337. const char * errstring = "Unexpected error";
  338. int ret = 0;
  339. if ((ret = read_config(root_config, NULL, &errstring)) < 0) {
  340. root_config = NULL;
  341. sys_printf("Unable to read manifest file: %s\n", errstring);
  342. return ret;
  343. }
  344. char cfgbuf[CONFIG_MAX];
  345. if (get_config(root_config, "sys.ask_for_checkpoint", cfgbuf,
  346. CONFIG_MAX) > 0 &&
  347. cfgbuf[0] == '1' && !cfgbuf[1])
  348. ask_for_checkpoint = true;
  349. return 0;
  350. }
  351. #ifdef PROFILE
  352. struct shim_profile profile_root;
  353. #endif
  354. # define FIND_ARG_COMPONENTS(cookie, argc, argv, envp, auxp) \
  355. do { \
  356. void *_tmp = (cookie); \
  357. (argv) = _tmp; \
  358. _tmp += sizeof(char *) * ((argc) + 1); \
  359. (envp) = _tmp; \
  360. for ( ; *(char **) _tmp; _tmp += sizeof(char *)); \
  361. (auxp) = _tmp + sizeof(char *); \
  362. } while (0)
  363. static void * __process_auxv (elf_auxv_t * auxp)
  364. {
  365. elf_auxv_t * av;
  366. for (av = auxp; av->a_type != AT_NULL; av++)
  367. switch (av->a_type) {
  368. default: break;
  369. }
  370. return av + 1;
  371. }
  372. #define FIND_LAST_STACK(stack) \
  373. do { \
  374. /* check if exist a NULL end */ \
  375. assert(*(uint64_t *) stack == 0); \
  376. stack += sizeof(uint64_t); \
  377. } while (0)
  378. #ifdef PROFILE
  379. static void set_profile_enabled (const char ** envp)
  380. {
  381. const char ** p;
  382. for (p = envp ; (*p) ; p++)
  383. if (!memcmp(*p, "PROFILE_ENABLED=", 16))
  384. break;
  385. if (!(*p))
  386. return;
  387. for (int i = 0 ; i < N_PROFILE ; i++)
  388. PROFILES[i].disabled = true;
  389. const char * str = (*p) + 16;
  390. bool enabled = false;
  391. while (*str) {
  392. const char * next = str;
  393. for ( ; (*next) && (*next) != ',' ; next++);
  394. if (next > str) {
  395. int len = next - str;
  396. for (int i = 0 ; i < N_PROFILE ; i++) {
  397. struct shim_profile * profile = &PROFILES[i];
  398. if (!memcmp(profile->name, str, len) && !profile->name[len]) {
  399. profile->disabled = false;
  400. if (profile->type == CATAGORY)
  401. enabled = true;
  402. }
  403. }
  404. }
  405. str = (*next) ? next + 1 : next;
  406. }
  407. while (enabled) {
  408. enabled = false;
  409. for (int i = 0 ; i < N_PROFILE ; i++) {
  410. struct shim_profile * profile = &PROFILES[i];
  411. if (!profile->disabled || profile->root == &profile_)
  412. continue;
  413. if (!profile->root->disabled) {
  414. profile->disabled = false;
  415. if (profile->type == CATAGORY)
  416. enabled = true;
  417. }
  418. }
  419. }
  420. for (int i = 0 ; i < N_PROFILE ; i++) {
  421. struct shim_profile * profile = &PROFILES[i];
  422. if (profile->type == CATAGORY || profile->disabled)
  423. continue;
  424. for (profile = profile->root ;
  425. profile != &profile_ && profile->disabled ;
  426. profile = profile->root)
  427. profile->disabled = false;
  428. }
  429. }
  430. #endif
  431. DEFINE_PROFILE_CATAGORY(resume, );
  432. DEFINE_PROFILE_INTERVAL(child_created_in_new_process, resume);
  433. DEFINE_PROFILE_INTERVAL(child_receive_header, resume);
  434. DEFINE_PROFILE_INTERVAL(child_total_migration_time, resume);
  435. static int init_newproc (struct newproc_header * hdr)
  436. {
  437. int bytes = DkStreamRead(PAL_CB(parent_process), 0,
  438. sizeof(struct newproc_header), hdr,
  439. NULL, 0);
  440. if (!bytes)
  441. return -PAL_ERRNO;
  442. SAVE_PROFILE_INTERVAL_SINCE(child_receive_header, hdr->write_proc_time);
  443. return hdr->failure;
  444. }
  445. DEFINE_PROFILE_CATAGORY(init, );
  446. DEFINE_PROFILE_INTERVAL(init_signal, init);
  447. DEFINE_PROFILE_INTERVAL(init_heap, init);
  448. DEFINE_PROFILE_INTERVAL(init_slab, init);
  449. DEFINE_PROFILE_INTERVAL(init_str_mgr, init);
  450. DEFINE_PROFILE_INTERVAL(init_internal_map, init);
  451. DEFINE_PROFILE_INTERVAL(init_vma, init);
  452. DEFINE_PROFILE_INTERVAL(init_fs, init);
  453. DEFINE_PROFILE_INTERVAL(init_handle, init);
  454. DEFINE_PROFILE_INTERVAL(init_randgen, init);
  455. DEFINE_PROFILE_INTERVAL(read_from_checkpoint, init);
  456. DEFINE_PROFILE_INTERVAL(read_from_file, init);
  457. DEFINE_PROFILE_INTERVAL(init_newproc, init);
  458. DEFINE_PROFILE_INTERVAL(init_checkpoint, init);
  459. DEFINE_PROFILE_INTERVAL(init_mount_root, init);
  460. DEFINE_PROFILE_INTERVAL(restore_from_checkpoint, init);
  461. DEFINE_PROFILE_INTERVAL(restore_from_file, init);
  462. DEFINE_PROFILE_INTERVAL(restore_from_stack, init);
  463. DEFINE_PROFILE_INTERVAL(init_manifest, init);
  464. DEFINE_PROFILE_INTERVAL(init_ipc, init);
  465. DEFINE_PROFILE_INTERVAL(init_thread, init);
  466. DEFINE_PROFILE_INTERVAL(init_important_handles, init);
  467. DEFINE_PROFILE_INTERVAL(init_mount, init);
  468. DEFINE_PROFILE_INTERVAL(init_async, init);
  469. DEFINE_PROFILE_INTERVAL(init_stack, init);
  470. DEFINE_PROFILE_INTERVAL(read_environs, init);
  471. DEFINE_PROFILE_INTERVAL(init_loader, init);
  472. DEFINE_PROFILE_INTERVAL(init_ipc_helper, init);
  473. #define CALL_INIT(func, args ...) func(args)
  474. #define RUN_INIT(func, ...) \
  475. do { \
  476. int _err = CALL_INIT(func, ##__VA_ARGS__); \
  477. if (_err < 0) { \
  478. sys_printf("shim initialization failed in " #func " (%e)", \
  479. -_err); \
  480. shim_terminate(); \
  481. } \
  482. SAVE_PROFILE_INTERVAL(func); \
  483. } while (0)
  484. extern PAL_HANDLE thread_start_event;
  485. int shim_init (int argc, void * args, void ** return_stack)
  486. {
  487. debug_handle = PAL_CB(debug_stream);
  488. /* create the initial TCB, shim can not be run without a tcb */
  489. __libc_tcb_t tcb;
  490. memset(&tcb, 0, sizeof(__libc_tcb_t));
  491. allocate_tls(&tcb, NULL);
  492. debug_setbuf(&tcb.shim_tcb, true);
  493. debug("set tcb to %p\n", &tcb);
  494. #ifdef PROFILE
  495. unsigned long begin_time = GET_PROFILE_INTERVAL();
  496. #endif
  497. DkSetExceptionHandler(&handle_failure, PAL_EVENT_FAILURE, 0);
  498. allocsize = PAL_CB(alloc_align);
  499. allocshift = allocsize - 1;
  500. allocmask = ~allocshift;
  501. create_lock(__master_lock);
  502. const char ** argv, ** envp, ** argp = NULL;
  503. elf_auxv_t * auxp;
  504. /* call to figure out where the arguments are */
  505. FIND_ARG_COMPONENTS(args, argc, argv, envp, auxp);
  506. initial_stack = __process_auxv(auxp);
  507. int nauxv = (elf_auxv_t *) initial_stack - auxp;
  508. FIND_LAST_STACK(initial_stack);
  509. #ifdef PROFILE
  510. set_profile_enabled(envp);
  511. #endif
  512. struct newproc_header hdr;
  513. void * cpaddr = NULL;
  514. #ifdef PROFILE
  515. unsigned long begin_create_time = 0;
  516. #endif
  517. BEGIN_PROFILE_INTERVAL();
  518. RUN_INIT(init_signal);
  519. RUN_INIT(init_heap);
  520. RUN_INIT(init_slab);
  521. RUN_INIT(init_str_mgr);
  522. RUN_INIT(init_internal_map);
  523. RUN_INIT(init_vma);
  524. RUN_INIT(init_fs);
  525. RUN_INIT(init_handle);
  526. RUN_INIT(init_randgen);
  527. debug("shim loaded at %p, ready to initialize\n", &__load_address);
  528. if (argc && argv[0][0] == '-') {
  529. if (!memcmp(argv[0], "-resume", 8) && argc >= 2) {
  530. const char * filename = *(argv + 1);
  531. argc -= 2;
  532. argv += 2;
  533. RUN_INIT(init_mount_root);
  534. RUN_INIT(restore_from_checkpoint, filename, &hdr.checkpoint,
  535. &cpaddr);
  536. goto restore;
  537. }
  538. if (!memcmp(argv[0], "-resume-file", 13) && argc >= 2) {
  539. const char * filename = *(argv + 1);
  540. argc -= 2;
  541. argv += 2;
  542. RUN_INIT(init_mount_root);
  543. RUN_INIT(restore_from_file, filename, &hdr.checkpoint, &cpaddr);
  544. goto restore;
  545. }
  546. }
  547. if (PAL_CB(parent_process)) {
  548. RUN_INIT(init_newproc, &hdr);
  549. SAVE_PROFILE_INTERVAL_SET(child_created_in_new_process,
  550. hdr.create_time, begin_time);
  551. #ifdef PROFILE
  552. begin_create_time = hdr.begin_create_time;
  553. #endif
  554. if (hdr.checkpoint.data.cpsize)
  555. RUN_INIT(init_checkpoint, &hdr.checkpoint, &cpaddr);
  556. }
  557. if (cpaddr) {
  558. restore:
  559. thread_start_event = DkNotificationEventCreate(0);
  560. RUN_INIT(restore_from_stack, cpaddr, &hdr.checkpoint.data, 0);
  561. }
  562. if (PAL_CB(manifest_handle))
  563. RUN_INIT(init_manifest, PAL_CB(manifest_handle));
  564. RUN_INIT(init_mount_root);
  565. RUN_INIT(init_ipc);
  566. RUN_INIT(init_thread);
  567. RUN_INIT(init_important_handles);
  568. RUN_INIT(init_mount);
  569. RUN_INIT(init_async);
  570. RUN_INIT(init_stack, argv, envp, &argp, nauxv, &auxp);
  571. RUN_INIT(read_environs, envp);
  572. RUN_INIT(init_loader);
  573. RUN_INIT(init_ipc_helper);
  574. debug("shim process initialized\n");
  575. #ifdef PROFILE
  576. if (begin_create_time)
  577. SAVE_PROFILE_INTERVAL_SINCE(child_total_migration_time,
  578. begin_create_time);
  579. #endif
  580. if (thread_start_event)
  581. DkEventSet(thread_start_event);
  582. shim_tcb_t * cur_tcb = SHIM_GET_TLS();
  583. struct shim_thread * cur_thread = (struct shim_thread *) cur_tcb->tp;
  584. if (cur_tcb->context.sp)
  585. restore_context(&cur_tcb->context);
  586. if (cur_thread->exec)
  587. execute_elf_object(cur_thread->exec,
  588. argc, argp, nauxv, auxp);
  589. *return_stack = initial_stack;
  590. return 0;
  591. }
  592. static int create_unique (int (*mkname) (char *, size_t, void *),
  593. int (*create) (const char *, void *),
  594. int (*output) (char *, size_t, const void *,
  595. struct shim_qstr *),
  596. char * name, size_t size, void * id, void * obj,
  597. struct shim_qstr * qstr)
  598. {
  599. int ret, len;
  600. while (1) {
  601. len = mkname(name, size, id);
  602. if (len < 0)
  603. return len;
  604. if ((ret = create(name, obj)) < 0)
  605. return ret;
  606. if (ret)
  607. continue;
  608. if (output)
  609. return output(name, size, id, qstr);
  610. if (qstr)
  611. qstrsetstr(qstr, name, len);
  612. return len;
  613. }
  614. }
  615. static int name_pipe (char * uri, size_t size, void * id)
  616. {
  617. IDTYPE pipeid;
  618. int len;
  619. if (getrand(&pipeid, sizeof(IDTYPE)) < sizeof(IDTYPE))
  620. return -EACCES;
  621. if ((len = snprintf(uri, size, "pipe.srv:%u", pipeid)) == size)
  622. return -ERANGE;
  623. *((IDTYPE *) id) = pipeid;
  624. return len;
  625. }
  626. static int open_pipe (const char * uri, void * obj)
  627. {
  628. PAL_HANDLE pipe = DkStreamOpen(uri, 0, 0, 0, 0);
  629. if (!pipe)
  630. return PAL_NATIVE_ERRNO == PAL_ERROR_STREAMEXIST ? 1 :
  631. -PAL_ERRNO;
  632. if (obj)
  633. *((PAL_HANDLE *) obj) = pipe;
  634. else
  635. DkObjectClose(pipe);
  636. return 0;
  637. }
  638. static int pipe_addr (char * uri, size_t size, const void * id,
  639. struct shim_qstr * qstr)
  640. {
  641. IDTYPE pipeid = *((IDTYPE *) id);
  642. int len;
  643. if ((len = snprintf(uri, size, "pipe:%u", pipeid)) == size)
  644. return -ERANGE;
  645. if (qstr)
  646. qstrsetstr(qstr, uri, len);
  647. return len;
  648. }
  649. int create_pipe (IDTYPE * id, char * uri, size_t size, PAL_HANDLE * hdl,
  650. struct shim_qstr * qstr)
  651. {
  652. IDTYPE pipeid;
  653. int ret = create_unique(&name_pipe, &open_pipe, &pipe_addr,
  654. uri, size, &pipeid, hdl, qstr);
  655. if (ret > 0 && id)
  656. *id = pipeid;
  657. return ret;
  658. }
  659. static int name_path (char * path, size_t size, void * id)
  660. {
  661. unsigned int suffix;
  662. int prefix_len = strlen(path);
  663. int len;
  664. if (getrand(&suffix, sizeof(unsigned int)) < sizeof(unsigned int))
  665. return -EACCES;
  666. len = snprintf(path + prefix_len, size - prefix_len, "%08x", suffix);
  667. if (len == size)
  668. return -ERANGE;
  669. *((unsigned int *) id) = suffix;
  670. return prefix_len + len;
  671. }
  672. static int open_dir (const char * path, void * obj)
  673. {
  674. struct shim_handle * dir = NULL;
  675. if (obj) {
  676. dir = get_new_handle();
  677. if (!dir)
  678. return -ENOMEM;
  679. }
  680. int ret = open_namei(dir, NULL, path, O_CREAT|O_EXCL|O_DIRECTORY, 0700,
  681. NULL);
  682. if (ret < 0)
  683. return ret = -EEXIST ? 1 : ret;
  684. if (obj)
  685. *((struct shim_handle **) obj) = dir;
  686. return 0;
  687. }
  688. static int open_file (const char * path, void * obj)
  689. {
  690. struct shim_handle * file = NULL;
  691. if (obj) {
  692. file = get_new_handle();
  693. if (!file)
  694. return -ENOMEM;
  695. }
  696. int ret = open_namei(file, NULL, path, O_CREAT|O_EXCL|O_RDWR, 0600,
  697. NULL);
  698. if (ret < 0)
  699. return ret = -EEXIST ? 1 : ret;
  700. if (obj)
  701. *((struct shim_handle **) obj) = file;
  702. return 0;
  703. }
  704. static int open_pal_handle (const char * uri, void * obj)
  705. {
  706. PAL_HANDLE hdl;
  707. if (!memcmp(uri, "dir:", 4))
  708. hdl = DkStreamOpen(uri, 0,
  709. PAL_SHARE_OWNER_X|PAL_SHARE_OWNER_W|
  710. PAL_SHARE_OWNER_R,
  711. PAL_CREAT_TRY|PAL_CREAT_ALWAYS,
  712. 0);
  713. else
  714. hdl = DkStreamOpen(uri, PAL_ACCESS_RDWR,
  715. PAL_SHARE_OWNER_W|PAL_SHARE_OWNER_R,
  716. PAL_CREAT_TRY|PAL_CREAT_ALWAYS,
  717. 0);
  718. if (!hdl) {
  719. if (PAL_NATIVE_ERRNO == PAL_ERROR_STREAMEXIST)
  720. return 0;
  721. else
  722. return -PAL_ERRNO;
  723. }
  724. if (obj)
  725. *((PAL_HANDLE *) obj) = hdl;
  726. return 0;
  727. }
  728. static int output_path (char * path, size_t size, const void * id,
  729. struct shim_qstr * qstr)
  730. {
  731. int len = strlen(path);
  732. if (qstr)
  733. qstrsetstr(qstr, path, len);
  734. return len;
  735. }
  736. int create_dir (const char * prefix, char * path, size_t size,
  737. struct shim_handle ** hdl)
  738. {
  739. unsigned int suffix;
  740. if (prefix) {
  741. int len = strlen(prefix);
  742. if (len >= size)
  743. return -ERANGE;
  744. memcpy(path, prefix, len + 1);
  745. }
  746. return create_unique(&name_path, &open_dir, &output_path, path, size,
  747. &suffix, hdl, NULL);
  748. }
  749. int create_file (const char * prefix, char * path, size_t size,
  750. struct shim_handle ** hdl)
  751. {
  752. unsigned int suffix;
  753. if (prefix) {
  754. int len = strlen(prefix);
  755. if (len >= size)
  756. return -ERANGE;
  757. memcpy(path, prefix, len + 1);
  758. }
  759. return create_unique(&name_path, &open_file, &output_path, path, size,
  760. &suffix, hdl, NULL);
  761. }
  762. int create_handle (const char * prefix, char * uri, size_t size,
  763. PAL_HANDLE * hdl, unsigned int * id)
  764. {
  765. unsigned int suffix;
  766. if (prefix) {
  767. int len = strlen(prefix);
  768. if (len >= size)
  769. return -ERANGE;
  770. memcpy(uri, prefix, len + 1);
  771. }
  772. return create_unique(&name_path, &open_pal_handle, &output_path, uri, size,
  773. id ? : &suffix, hdl, NULL);
  774. }
  775. void check_stack_hook (void)
  776. {
  777. struct shim_thread * cur_thread = get_cur_thread();
  778. void * rsp;
  779. asm volatile ("movq %%rsp, %0" : "=r"(rsp) :: "memory");
  780. if (rsp <= cur_thread->stack_top && rsp > cur_thread->stack) {
  781. if (rsp - cur_thread->stack < PAL_CB(pagesize))
  782. sys_printf("*** stack is almost drained (RSP = %p, stack = %p-%p) ***\n",
  783. rsp, cur_thread->stack, cur_thread->stack_top);
  784. } else {
  785. sys_printf("*** context dismateched with thread stack (RSP = %p, stack = %p-%p) ***\n",
  786. rsp, cur_thread->stack, cur_thread->stack_top);
  787. }
  788. }
  789. #ifdef PROFILE
  790. static void print_profile_result (PAL_HANDLE hdl, struct shim_profile * root,
  791. int level)
  792. {
  793. unsigned long total_interval_time = 0;
  794. unsigned long total_interval_count = 0;
  795. for (int i = 0 ; i < N_PROFILE ; i++) {
  796. struct shim_profile * profile = &PROFILES[i];
  797. if (profile->root != root || profile->disabled)
  798. continue;
  799. switch (profile->type) {
  800. case OCCURENCE: {
  801. unsigned int count =
  802. atomic_read(&profile->val.occurence.count);
  803. if (count) {
  804. for (int j = 0 ; j < level ; j++)
  805. __sys_fprintf(hdl, " ");
  806. __sys_fprintf(hdl, "- %s: %u times\n", profile->name, count);
  807. }
  808. break;
  809. }
  810. case INTERVAL: {
  811. unsigned int count =
  812. atomic_read(&profile->val.interval.count);
  813. if (count) {
  814. unsigned long time =
  815. atomic_read(&profile->val.interval.time);
  816. unsigned long ind_time = time / count;
  817. total_interval_time += time;
  818. total_interval_count += count;
  819. for (int j = 0 ; j < level ; j++)
  820. __sys_fprintf(hdl, " ");
  821. __sys_fprintf(hdl, "- (%11.11lu) %s: %u times, %lu msec\n",
  822. time, profile->name, count, ind_time);
  823. }
  824. break;
  825. }
  826. case CATAGORY:
  827. for (int j = 0 ; j < level ; j++)
  828. __sys_fprintf(hdl, " ");
  829. __sys_fprintf(hdl, "- %s:\n", profile->name);
  830. print_profile_result(hdl, profile, level + 1);
  831. break;
  832. }
  833. }
  834. if (total_interval_count) {
  835. __sys_fprintf(hdl, "- (%11.11u) total: %u times, %lu msec\n",
  836. total_interval_time, total_interval_count,
  837. total_interval_time / total_interval_count);
  838. }
  839. }
  840. #endif /* PROFILE */
  841. static struct shim_atomic in_terminate = { .counter = 0, };
  842. int shim_terminate (void)
  843. {
  844. debug("teminating the whole process\n");
  845. /* do last clean-up of the process */
  846. shim_clean();
  847. DkProcessExit(0);
  848. return 0;
  849. }
  850. int shim_clean (void)
  851. {
  852. /* preventing multiple cleanup, this is mostly caused by
  853. assertion in shim_clean */
  854. atomic_inc(&in_terminate);
  855. if (atomic_read(&in_terminate) > 1)
  856. return 0;
  857. store_all_msg_persist();
  858. #ifdef PROFILE
  859. if (ENTER_TIME) {
  860. switch (SHIM_GET_TLS()->context.syscall_nr) {
  861. case __NR_exit_group:
  862. SAVE_PROFILE_INTERVAL_SINCE(syscall_exit_group, ENTER_TIME);
  863. break;
  864. case __NR_exit:
  865. SAVE_PROFILE_INTERVAL_SINCE(syscall_exit, ENTER_TIME);
  866. break;
  867. }
  868. }
  869. if (ipc_cld_profile_send()) {
  870. master_lock();
  871. PAL_HANDLE hdl = __open_shim_stdio();
  872. if (hdl) {
  873. __sys_fprintf(hdl, "******************************\n");
  874. __sys_fprintf(hdl, "profiling:\n");
  875. print_profile_result(hdl, &profile_root, 0);
  876. __sys_fprintf(hdl, "******************************\n");
  877. }
  878. master_unlock();
  879. }
  880. #endif
  881. del_all_ipc_ports(0);
  882. if (shim_stdio && shim_stdio != (PAL_HANDLE) -1)
  883. DkObjectClose(shim_stdio);
  884. shim_stdio = NULL;
  885. debug("process %u successfully terminated\n", cur_process.vmid);
  886. master_lock();
  887. DkProcessExit(cur_process.exit_code);
  888. return 0;
  889. }
  890. int message_confirm (const char * message, const char * options)
  891. {
  892. char answer;
  893. int noptions = strlen(options);
  894. char * option_str = __alloca(noptions * 2 + 3), * str = option_str;
  895. int ret = 0;
  896. *(str++) = ' ';
  897. *(str++) = '[';
  898. for (int i = 0 ; i < noptions ; i++) {
  899. *(str++) = options[i];
  900. *(str++) = '/';
  901. }
  902. str--;
  903. *(str++) = ']';
  904. *(str++) = ' ';
  905. master_lock();
  906. PAL_HANDLE hdl = __open_shim_stdio();
  907. if (!hdl) {
  908. master_unlock();
  909. return -EACCES;
  910. }
  911. #define WRITE(buf, len) \
  912. ({ int _ret = DkStreamWrite(hdl, 0, len, buf, NULL); \
  913. _ret ? : -PAL_ERRNO; })
  914. #define READ(buf, len) \
  915. ({ int _ret = DkStreamRead(hdl, 0, len, buf, NULL, 0); \
  916. _ret ? : -PAL_ERRNO; })
  917. if ((ret = WRITE(message, strlen(message))) < 0)
  918. goto out;
  919. if ((ret = WRITE(option_str, noptions * 2 + 3)) < 0)
  920. goto out;
  921. if ((ret = READ(&answer, 1)) < 0)
  922. goto out;
  923. out:
  924. master_unlock();
  925. return (ret < 0) ? ret : answer;
  926. }