shim_init.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  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. unsigned long parse_int (const char * str)
  90. {
  91. unsigned long num = 0;
  92. int radix = 10;
  93. char c;
  94. if (str[0] == '0') {
  95. str++;
  96. radix = 8;
  97. if (str[0] == 'x') {
  98. str++;
  99. radix = 16;
  100. }
  101. }
  102. while ((c = *(str++))) {
  103. int val;
  104. if (c >= 'A' && c <= 'F')
  105. val = c - 'A' + 10;
  106. else if (c >= 'a' && c <= 'f')
  107. val = c - 'a' + 10;
  108. else if (c >= '0' && c <= '9')
  109. val = c - '0';
  110. else
  111. break;
  112. if (val >= radix)
  113. break;
  114. num = num * radix + val;
  115. }
  116. if (c == 'G' || c == 'g')
  117. num *= 1024 * 1024 * 1024;
  118. else if (c == 'M' || c == 'm')
  119. num *= 1024 * 1024;
  120. else if (c == 'K' || c == 'k')
  121. num *= 1024;
  122. return num;
  123. }
  124. long int * glibc_option (const char * opt)
  125. {
  126. char cfg[CONFIG_MAX];
  127. if (!memcmp(opt, "heap_size", 9)) {
  128. return get_config(root_config, "glibc.heap_size", cfg, CONFIG_MAX) < 0 ?
  129. -ENOENT : parse_int(cfg);
  130. }
  131. return -EINVAL;
  132. }
  133. void * migrated_memory_start;
  134. void * migrated_memory_end;
  135. void * migrated_shim_addr;
  136. void * initial_stack;
  137. const char ** initial_envp __attribute_migratable;
  138. const char ** library_paths;
  139. LOCKTYPE __master_lock;
  140. bool lock_enabled;
  141. bool in_gdb;
  142. void init_tcb (shim_tcb_t * tcb)
  143. {
  144. tcb->canary = SHIM_TLS_CANARY;
  145. tcb->self = tcb;
  146. }
  147. void copy_tcb (shim_tcb_t * new_tcb, const shim_tcb_t * old_tcb)
  148. {
  149. memset(new_tcb, 0, sizeof(shim_tcb_t));
  150. new_tcb->canary = SHIM_TLS_CANARY;
  151. new_tcb->self = new_tcb;
  152. new_tcb->tp = old_tcb->tp;
  153. memcpy(&new_tcb->context, &old_tcb->context, sizeof(struct shim_context));
  154. new_tcb->tid = old_tcb->tid;
  155. new_tcb->debug_buf = old_tcb->debug_buf;
  156. }
  157. /* This function is used to allocate tls before interpreter start running */
  158. void allocate_tls (void * tcb_location, bool user, struct shim_thread * thread)
  159. {
  160. __libc_tcb_t * tcb = tcb_location;
  161. assert(tcb);
  162. tcb->tcb = tcb;
  163. init_tcb(&tcb->shim_tcb);
  164. if (thread) {
  165. thread->tcb = tcb;
  166. thread->user_tcb = user;
  167. tcb->shim_tcb.tp = thread;
  168. tcb->shim_tcb.tid = thread->tid;
  169. } else {
  170. tcb->shim_tcb.tp = NULL;
  171. tcb->shim_tcb.tid = 0;
  172. }
  173. DkSegmentRegister(PAL_SEGMENT_FS, tcb);
  174. assert(SHIM_TLS_CHECK_CANARY());
  175. }
  176. void populate_tls (void * tcb_location, bool user)
  177. {
  178. __libc_tcb_t * tcb = (__libc_tcb_t *) tcb_location;
  179. assert(tcb);
  180. tcb->tcb = tcb;
  181. copy_tcb(&tcb->shim_tcb, SHIM_GET_TLS());
  182. struct shim_thread * thread = (struct shim_thread *) tcb->shim_tcb.tp;
  183. if (thread) {
  184. thread->tcb = tcb;
  185. thread->user_tcb = user;
  186. }
  187. DkSegmentRegister(PAL_SEGMENT_FS, tcb);
  188. assert(SHIM_TLS_CHECK_CANARY());
  189. }
  190. DEFINE_PROFILE_OCCURENCE(alloc_stack, memory);
  191. DEFINE_PROFILE_OCCURENCE(alloc_stack_count, memory);
  192. #define STACK_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)
  193. void * allocate_stack (size_t size, size_t protect_size, bool user)
  194. {
  195. size = ALIGN_UP(size);
  196. protect_size = ALIGN_UP(protect_size);
  197. /* preserve a non-readable, non-writeable page below the user
  198. stack to stop user program to clobber other vmas */
  199. void * stack = user ?
  200. get_unmapped_vma(size + protect_size, STACK_FLAGS) :
  201. NULL;
  202. if (user)
  203. stack = (void *) DkVirtualMemoryAlloc(stack, size + protect_size,
  204. 0, PAL_PROT_READ|PAL_PROT_WRITE);
  205. else
  206. stack = system_malloc(size + protect_size);
  207. if (!stack)
  208. return NULL;
  209. ADD_PROFILE_OCCURENCE(alloc_stack, size + protect_size);
  210. INC_PROFILE_OCCURENCE(alloc_stack_count);
  211. if (protect_size &&
  212. !DkVirtualMemoryProtect(stack, protect_size, PAL_PROT_NONE))
  213. return NULL;
  214. stack += protect_size;
  215. if (user) {
  216. if (bkeep_mmap(stack, size, PROT_READ|PROT_WRITE,
  217. STACK_FLAGS, NULL, 0, "[stack]") < 0)
  218. return NULL;
  219. if (protect_size &&
  220. bkeep_mmap(stack - protect_size, protect_size, 0,
  221. STACK_FLAGS, NULL, 0, NULL) < 0)
  222. return NULL;
  223. }
  224. debug("allocated stack at %p (size = %d)\n", stack, size);
  225. return stack;
  226. }
  227. int populate_user_stack (void * stack, size_t stack_size,
  228. int nauxv, elf_auxv_t ** auxpp,
  229. const char *** argvp, const char *** envpp)
  230. {
  231. const char ** argv = *argvp, ** envp = *envpp;
  232. const char ** new_argv = NULL, ** new_envp = NULL;
  233. void * stack_bottom = stack;
  234. void * stack_top = stack + stack_size;
  235. #define ALLOCATE_TOP(size) \
  236. ({ if ((stack_top -= (size)) < stack_bottom) return -ENOMEM; \
  237. stack_top; })
  238. #define ALLOCATE_BOTTOM(size) \
  239. ({ if ((stack_bottom += (size)) > stack_top) return -ENOMEM; \
  240. stack_bottom - (size); })
  241. if (!argv) {
  242. *(const char **) ALLOCATE_BOTTOM(sizeof(const char *)) = NULL;
  243. goto copy_envp;
  244. }
  245. new_argv = stack_bottom;
  246. while (argv) {
  247. for (const char ** a = argv ; *a ; a++) {
  248. const char ** t = ALLOCATE_BOTTOM(sizeof(const char *));
  249. int len = strlen(*a) + 1;
  250. char * abuf = ALLOCATE_TOP(len);
  251. memcpy(abuf, *a, len);
  252. *t = abuf;
  253. }
  254. *((const char **) ALLOCATE_BOTTOM(sizeof(const char *))) = NULL;
  255. copy_envp:
  256. if (!envp)
  257. break;
  258. new_envp = stack_bottom;
  259. argv = envp;
  260. envp = NULL;
  261. }
  262. if (!new_envp)
  263. *(const char **) ALLOCATE_BOTTOM(sizeof(const char *)) = NULL;
  264. stack_bottom = (void *) ((unsigned long) stack_bottom & ~7UL);
  265. *((unsigned long *) ALLOCATE_TOP(sizeof(unsigned long))) = 0;
  266. if (nauxv) {
  267. elf_auxv_t * old_auxp = *auxpp;
  268. *auxpp = ALLOCATE_TOP(sizeof(elf_auxv_t) * nauxv);
  269. if (old_auxp)
  270. memcpy(*auxpp, old_auxp, nauxv * sizeof(elf_auxv_t));
  271. }
  272. memmove(stack_top - (stack_bottom - stack), stack, stack_bottom - stack);
  273. if (new_argv)
  274. *argvp = (void *) new_argv + (stack_top - stack_bottom);
  275. if (new_envp)
  276. *envpp = (void *) new_envp + (stack_top - stack_bottom);
  277. return 0;
  278. }
  279. unsigned long sys_stack_size = 0;
  280. int init_stack (const char ** argv, const char ** envp, const char *** argpp,
  281. int nauxv, elf_auxv_t ** auxpp)
  282. {
  283. if (!sys_stack_size) {
  284. sys_stack_size = DEFAULT_SYS_STACK_SIZE;
  285. if (root_config) {
  286. char stack_cfg[CONFIG_MAX];
  287. if (get_config(root_config, "sys.stack.size", stack_cfg,
  288. CONFIG_MAX) > 0)
  289. sys_stack_size = ALIGN_UP(parse_int(stack_cfg));
  290. }
  291. }
  292. struct shim_thread * cur_thread = get_cur_thread();
  293. if (!cur_thread || cur_thread->stack)
  294. return 0;
  295. void * stack = allocate_stack(sys_stack_size, allocsize, true);
  296. if (!stack)
  297. return -ENOMEM;
  298. if (initial_envp)
  299. envp = initial_envp;
  300. int ret = populate_user_stack(stack, sys_stack_size,
  301. nauxv, auxpp, &argv, &envp);
  302. if (ret < 0)
  303. return ret;
  304. *argpp = argv;
  305. initial_envp = envp;
  306. cur_thread->stack_top = stack + sys_stack_size;
  307. cur_thread->stack = stack;
  308. cur_thread->stack_red = stack - allocsize;
  309. return 0;
  310. }
  311. int read_environs (const char ** envp)
  312. {
  313. for (const char ** e = envp ; *e ; e++) {
  314. switch ((*e)[0]) {
  315. case 'L': {
  316. if (!memcmp(*e, "LD_LIBRARY_PATH=", 16)) {
  317. int npaths = 0;
  318. for (const char * s = (*e) + 16 ; *s ; s++)
  319. if (*s == ':')
  320. npaths++;
  321. const char ** paths = malloc(sizeof(const char *) *
  322. (npaths + 1));
  323. if (!paths)
  324. return -ENOMEM;
  325. const char * s = (*e) + 16, * next;
  326. int cnt = 0;
  327. while (*s) {
  328. for (next = s ; *next && *next != ':' ; next++);
  329. int len = next - s;
  330. char * str = malloc(len + 1);
  331. if (!str)
  332. return -ENOMEM;
  333. memcpy(str, s, len);
  334. str[len] = 0;
  335. paths[cnt++] = str;
  336. s = *next ? next + 1 : next;
  337. }
  338. paths[cnt] = NULL;
  339. library_paths = paths;
  340. break;
  341. }
  342. break;
  343. }
  344. case 'I': {
  345. if (!memcmp(*e, "IN_GDB=1", 8)) {
  346. in_gdb = true;
  347. break;
  348. }
  349. break;
  350. }
  351. }
  352. }
  353. return 0;
  354. }
  355. struct config_store * root_config = NULL;
  356. static void * __malloc (int size)
  357. {
  358. return malloc(size);
  359. }
  360. static void __free (void * mem)
  361. {
  362. free(mem);
  363. }
  364. int init_manifest (PAL_HANDLE manifest_handle)
  365. {
  366. PAL_STREAM_ATTR attr;
  367. if (!DkStreamAttributesQuerybyHandle(manifest_handle, &attr))
  368. return -PAL_ERRNO;
  369. size_t cfg_size = attr.pending_size;
  370. void * cfg_addr = (void *) DkStreamMap(manifest_handle, NULL,
  371. PAL_PROT_READ|PAL_PROT_WRITECOPY, 0,
  372. ALIGN_UP(cfg_size));
  373. if (!cfg_addr)
  374. return -PAL_ERRNO;
  375. root_config = malloc(sizeof(struct config_store));
  376. root_config->raw_data = cfg_addr;
  377. root_config->raw_size = cfg_size;
  378. root_config->malloc = __malloc;
  379. root_config->free = __free;
  380. const char * errstring = "Unexpected error";
  381. int ret = 0;
  382. if ((ret = read_config(root_config, NULL, &errstring)) < 0) {
  383. root_config = NULL;
  384. sys_printf("Unable to read manifest file: %s\n", errstring);
  385. return ret;
  386. }
  387. return 0;
  388. }
  389. #ifdef PROFILE
  390. struct shim_profile profile_root;
  391. #endif
  392. # define FIND_ARG_COMPONENTS(cookie, argc, argv, envp, auxp) \
  393. do { \
  394. void *_tmp = (cookie); \
  395. (argv) = _tmp; \
  396. _tmp += sizeof(char *) * ((argc) + 1); \
  397. (envp) = _tmp; \
  398. for ( ; *(char **) _tmp; _tmp += sizeof(char *)); \
  399. (auxp) = _tmp + sizeof(char *); \
  400. } while (0)
  401. static void * __process_auxv (elf_auxv_t * auxp)
  402. {
  403. elf_auxv_t * av;
  404. for (av = auxp; av->a_type != AT_NULL; av++)
  405. switch (av->a_type) {
  406. default: break;
  407. }
  408. return av + 1;
  409. }
  410. #define FIND_LAST_STACK(stack) \
  411. do { \
  412. /* check if exist a NULL end */ \
  413. assert(*(uint64_t *) stack == 0); \
  414. stack += sizeof(uint64_t); \
  415. } while (0)
  416. #ifdef PROFILE
  417. static void set_profile_enabled (const char ** envp)
  418. {
  419. const char ** p;
  420. for (p = envp ; (*p) ; p++)
  421. if (!memcmp(*p, "PROFILE_ENABLED=", 16))
  422. break;
  423. if (!(*p))
  424. return;
  425. for (int i = 0 ; i < N_PROFILE ; i++)
  426. PROFILES[i].disabled = true;
  427. const char * str = (*p) + 16;
  428. bool enabled = false;
  429. while (*str) {
  430. const char * next = str;
  431. for ( ; (*next) && (*next) != ',' ; next++);
  432. if (next > str) {
  433. int len = next - str;
  434. for (int i = 0 ; i < N_PROFILE ; i++) {
  435. struct shim_profile * profile = &PROFILES[i];
  436. if (!memcmp(profile->name, str, len) && !profile->name[len]) {
  437. profile->disabled = false;
  438. if (profile->type == CATAGORY)
  439. enabled = true;
  440. }
  441. }
  442. }
  443. str = (*next) ? next + 1 : next;
  444. }
  445. while (enabled) {
  446. enabled = false;
  447. for (int i = 0 ; i < N_PROFILE ; i++) {
  448. struct shim_profile * profile = &PROFILES[i];
  449. if (!profile->disabled || profile->root == &profile_)
  450. continue;
  451. if (!profile->root->disabled) {
  452. profile->disabled = false;
  453. if (profile->type == CATAGORY)
  454. enabled = true;
  455. }
  456. }
  457. }
  458. for (int i = 0 ; i < N_PROFILE ; i++) {
  459. struct shim_profile * profile = &PROFILES[i];
  460. if (profile->type == CATAGORY || profile->disabled)
  461. continue;
  462. for (profile = profile->root ;
  463. profile != &profile_ && profile->disabled ;
  464. profile = profile->root)
  465. profile->disabled = false;
  466. }
  467. }
  468. #endif
  469. static int init_newproc (struct newproc_header * hdr)
  470. {
  471. BEGIN_PROFILE_INTERVAL();
  472. int bytes = DkStreamRead(PAL_CB(parent_process), 0,
  473. sizeof(struct newproc_header), hdr,
  474. NULL, 0);
  475. if (!bytes)
  476. return -PAL_ERRNO;
  477. SAVE_PROFILE_INTERVAL(child_wait_header);
  478. SAVE_PROFILE_INTERVAL_SINCE(child_receive_header, hdr->write_proc_time);
  479. return hdr->failure;
  480. }
  481. DEFINE_PROFILE_CATAGORY(pal, );
  482. DEFINE_PROFILE_INTERVAL(pal_startup_time, pal);
  483. DEFINE_PROFILE_INTERVAL(pal_host_specific_startup_time, pal);
  484. DEFINE_PROFILE_INTERVAL(pal_relocation_time, pal);
  485. DEFINE_PROFILE_INTERVAL(pal_linking_time, pal);
  486. DEFINE_PROFILE_INTERVAL(pal_manifest_loading_time, pal);
  487. DEFINE_PROFILE_INTERVAL(pal_allocation_time, pal);
  488. DEFINE_PROFILE_INTERVAL(pal_tail_startup_time, pal);
  489. DEFINE_PROFILE_INTERVAL(pal_child_creation_time, pal);
  490. DEFINE_PROFILE_CATAGORY(init, );
  491. DEFINE_PROFILE_INTERVAL(init_randgen, init);
  492. DEFINE_PROFILE_INTERVAL(init_heap, init);
  493. DEFINE_PROFILE_INTERVAL(init_slab, init);
  494. DEFINE_PROFILE_INTERVAL(init_str_mgr, init);
  495. DEFINE_PROFILE_INTERVAL(init_internal_map, init);
  496. DEFINE_PROFILE_INTERVAL(init_vma, init);
  497. DEFINE_PROFILE_INTERVAL(init_fs, init);
  498. DEFINE_PROFILE_INTERVAL(init_dcache, init);
  499. DEFINE_PROFILE_INTERVAL(init_handle, init);
  500. DEFINE_PROFILE_INTERVAL(read_from_checkpoint, init);
  501. DEFINE_PROFILE_INTERVAL(read_from_file, init);
  502. DEFINE_PROFILE_INTERVAL(init_newproc, init);
  503. DEFINE_PROFILE_INTERVAL(init_mount_root, init);
  504. DEFINE_PROFILE_INTERVAL(init_from_checkpoint_file, init);
  505. DEFINE_PROFILE_INTERVAL(restore_from_file, init);
  506. DEFINE_PROFILE_INTERVAL(init_manifest, init);
  507. DEFINE_PROFILE_INTERVAL(init_ipc, init);
  508. DEFINE_PROFILE_INTERVAL(init_thread, init);
  509. DEFINE_PROFILE_INTERVAL(init_important_handles, init);
  510. DEFINE_PROFILE_INTERVAL(init_mount, init);
  511. DEFINE_PROFILE_INTERVAL(init_async, init);
  512. DEFINE_PROFILE_INTERVAL(init_stack, init);
  513. DEFINE_PROFILE_INTERVAL(read_environs, init);
  514. DEFINE_PROFILE_INTERVAL(init_loader, init);
  515. DEFINE_PROFILE_INTERVAL(init_ipc_helper, init);
  516. DEFINE_PROFILE_INTERVAL(init_signal, init);
  517. #define CALL_INIT(func, args ...) func(args)
  518. #define RUN_INIT(func, ...) \
  519. do { \
  520. int _err = CALL_INIT(func, ##__VA_ARGS__); \
  521. if (_err < 0) { \
  522. sys_printf("shim initialization failed in " #func " (%d)", \
  523. _err); \
  524. shim_terminate(); \
  525. } \
  526. SAVE_PROFILE_INTERVAL(func); \
  527. } while (0)
  528. extern PAL_HANDLE thread_start_event;
  529. int shim_init (int argc, void * args, void ** return_stack)
  530. {
  531. debug_handle = PAL_CB(debug_stream);
  532. cur_process.vmid = (IDTYPE) PAL_CB(process_id);
  533. /* create the initial TCB, shim can not be run without a tcb */
  534. __libc_tcb_t tcb;
  535. memset(&tcb, 0, sizeof(__libc_tcb_t));
  536. allocate_tls(&tcb, false, NULL);
  537. debug_setbuf(&tcb.shim_tcb, true);
  538. debug("set tcb to %p\n", &tcb);
  539. #ifdef PROFILE
  540. unsigned long begin_time = GET_PROFILE_INTERVAL();
  541. #endif
  542. DkSetExceptionHandler(&handle_failure, PAL_EVENT_FAILURE, 0);
  543. allocsize = PAL_CB(alloc_align);
  544. allocshift = allocsize - 1;
  545. allocmask = ~allocshift;
  546. create_lock(__master_lock);
  547. const char ** argv, ** envp, ** argp = NULL;
  548. elf_auxv_t * auxp;
  549. /* call to figure out where the arguments are */
  550. FIND_ARG_COMPONENTS(args, argc, argv, envp, auxp);
  551. initial_stack = __process_auxv(auxp);
  552. int nauxv = (elf_auxv_t *) initial_stack - auxp;
  553. FIND_LAST_STACK(initial_stack);
  554. #ifdef PROFILE
  555. set_profile_enabled(envp);
  556. #endif
  557. struct newproc_header hdr;
  558. void * cpaddr = NULL;
  559. #ifdef PROFILE
  560. unsigned long begin_create_time = 0;
  561. #endif
  562. BEGIN_PROFILE_INTERVAL();
  563. RUN_INIT(init_randgen);
  564. RUN_INIT(init_heap);
  565. RUN_INIT(init_slab);
  566. RUN_INIT(read_environs, envp);
  567. RUN_INIT(init_str_mgr);
  568. RUN_INIT(init_internal_map);
  569. RUN_INIT(init_vma);
  570. RUN_INIT(init_fs);
  571. RUN_INIT(init_dcache);
  572. RUN_INIT(init_handle);
  573. debug("shim loaded at %p, ready to initialize\n", &__load_address);
  574. if (argc && argv[0][0] == '-') {
  575. if (!memcmp(argv[0], "-resume", 8) && argc >= 2) {
  576. const char * filename = *(argv + 1);
  577. argc -= 2;
  578. argv += 2;
  579. RUN_INIT(init_mount_root);
  580. RUN_INIT(init_from_checkpoint_file, filename, &hdr.checkpoint,
  581. &cpaddr);
  582. goto restore;
  583. }
  584. }
  585. if (PAL_CB(parent_process)) {
  586. RUN_INIT(init_newproc, &hdr);
  587. SAVE_PROFILE_INTERVAL_SET(child_created_in_new_process,
  588. hdr.create_time, begin_time);
  589. #ifdef PROFILE
  590. begin_create_time = hdr.begin_create_time;
  591. #endif
  592. if (hdr.checkpoint.hdr.size)
  593. RUN_INIT(do_migration, &hdr.checkpoint, &cpaddr);
  594. }
  595. if (cpaddr) {
  596. restore:
  597. thread_start_event = DkNotificationEventCreate(0);
  598. RUN_INIT(restore_checkpoint,
  599. &hdr.checkpoint.hdr, &hdr.checkpoint.mem,
  600. (ptr_t) cpaddr, 0);
  601. }
  602. if (PAL_CB(manifest_handle))
  603. RUN_INIT(init_manifest, PAL_CB(manifest_handle));
  604. RUN_INIT(init_mount_root);
  605. RUN_INIT(init_ipc);
  606. RUN_INIT(init_thread);
  607. RUN_INIT(init_important_handles);
  608. RUN_INIT(init_mount);
  609. RUN_INIT(init_async);
  610. RUN_INIT(init_stack, argv, envp, &argp, nauxv, &auxp);
  611. RUN_INIT(init_loader);
  612. RUN_INIT(init_ipc_helper);
  613. RUN_INIT(init_signal);
  614. debug("shim process initialized\n");
  615. #ifdef PROFILE
  616. if (begin_create_time)
  617. SAVE_PROFILE_INTERVAL_SINCE(child_total_migration_time,
  618. begin_create_time);
  619. #endif
  620. SAVE_PROFILE_INTERVAL_SET(pal_startup_time, 0, pal_control.startup_time);
  621. SAVE_PROFILE_INTERVAL_SET(pal_host_specific_startup_time, 0,
  622. pal_control.host_specific_startup_time);
  623. SAVE_PROFILE_INTERVAL_SET(pal_relocation_time, 0,
  624. pal_control.relocation_time);
  625. SAVE_PROFILE_INTERVAL_SET(pal_linking_time, 0, pal_control.linking_time);
  626. SAVE_PROFILE_INTERVAL_SET(pal_manifest_loading_time, 0,
  627. pal_control.manifest_loading_time);
  628. SAVE_PROFILE_INTERVAL_SET(pal_allocation_time, 0,
  629. pal_control.allocation_time);
  630. SAVE_PROFILE_INTERVAL_SET(pal_tail_startup_time, 0,
  631. pal_control.tail_startup_time);
  632. SAVE_PROFILE_INTERVAL_SET(pal_child_creation_time, 0,
  633. pal_control.child_creation_time);
  634. if (thread_start_event)
  635. DkEventSet(thread_start_event);
  636. shim_tcb_t * cur_tcb = SHIM_GET_TLS();
  637. struct shim_thread * cur_thread = (struct shim_thread *) cur_tcb->tp;
  638. if (cur_tcb->context.sp)
  639. restore_context(&cur_tcb->context);
  640. if (cur_thread->exec)
  641. execute_elf_object(cur_thread->exec,
  642. argc, argp, nauxv, auxp);
  643. *return_stack = initial_stack;
  644. return 0;
  645. }
  646. static int create_unique (int (*mkname) (char *, size_t, void *),
  647. int (*create) (const char *, void *),
  648. int (*output) (char *, size_t, const void *,
  649. struct shim_qstr *),
  650. char * name, size_t size, void * id, void * obj,
  651. struct shim_qstr * qstr)
  652. {
  653. int ret, len;
  654. while (1) {
  655. len = mkname(name, size, id);
  656. if (len < 0)
  657. return len;
  658. if ((ret = create(name, obj)) < 0)
  659. return ret;
  660. if (ret)
  661. continue;
  662. if (output)
  663. return output(name, size, id, qstr);
  664. if (qstr)
  665. qstrsetstr(qstr, name, len);
  666. return len;
  667. }
  668. }
  669. static int name_pipe (char * uri, size_t size, void * id)
  670. {
  671. IDTYPE pipeid;
  672. int len;
  673. if (getrand(&pipeid, sizeof(IDTYPE)) < sizeof(IDTYPE))
  674. return -EACCES;
  675. if ((len = snprintf(uri, size, "pipe.srv:%u", pipeid)) == size)
  676. return -ERANGE;
  677. *((IDTYPE *) id) = pipeid;
  678. return len;
  679. }
  680. static int open_pipe (const char * uri, void * obj)
  681. {
  682. PAL_HANDLE pipe = DkStreamOpen(uri, 0, 0, 0, 0);
  683. if (!pipe)
  684. return PAL_NATIVE_ERRNO == PAL_ERROR_STREAMEXIST ? 1 :
  685. -PAL_ERRNO;
  686. if (obj)
  687. *((PAL_HANDLE *) obj) = pipe;
  688. else
  689. DkObjectClose(pipe);
  690. return 0;
  691. }
  692. static int pipe_addr (char * uri, size_t size, const void * id,
  693. struct shim_qstr * qstr)
  694. {
  695. IDTYPE pipeid = *((IDTYPE *) id);
  696. int len;
  697. if ((len = snprintf(uri, size, "pipe:%u", pipeid)) == size)
  698. return -ERANGE;
  699. if (qstr)
  700. qstrsetstr(qstr, uri, len);
  701. return len;
  702. }
  703. int create_pipe (IDTYPE * id, char * uri, size_t size, PAL_HANDLE * hdl,
  704. struct shim_qstr * qstr)
  705. {
  706. IDTYPE pipeid;
  707. int ret = create_unique(&name_pipe, &open_pipe, &pipe_addr,
  708. uri, size, &pipeid, hdl, qstr);
  709. if (ret > 0 && id)
  710. *id = pipeid;
  711. return ret;
  712. }
  713. static int name_path (char * path, size_t size, void * id)
  714. {
  715. unsigned int suffix;
  716. int prefix_len = strlen(path);
  717. int len;
  718. if (getrand(&suffix, sizeof(unsigned int)) < sizeof(unsigned int))
  719. return -EACCES;
  720. len = snprintf(path + prefix_len, size - prefix_len, "%08x", suffix);
  721. if (len == size)
  722. return -ERANGE;
  723. *((unsigned int *) id) = suffix;
  724. return prefix_len + len;
  725. }
  726. static int open_dir (const char * path, void * obj)
  727. {
  728. struct shim_handle * dir = NULL;
  729. if (obj) {
  730. dir = get_new_handle();
  731. if (!dir)
  732. return -ENOMEM;
  733. }
  734. int ret = open_namei(dir, NULL, path, O_CREAT|O_EXCL|O_DIRECTORY, 0700,
  735. NULL);
  736. if (ret < 0)
  737. return ret = -EEXIST ? 1 : ret;
  738. if (obj)
  739. *((struct shim_handle **) obj) = dir;
  740. return 0;
  741. }
  742. static int open_file (const char * path, void * obj)
  743. {
  744. struct shim_handle * file = NULL;
  745. if (obj) {
  746. file = get_new_handle();
  747. if (!file)
  748. return -ENOMEM;
  749. }
  750. int ret = open_namei(file, NULL, path, O_CREAT|O_EXCL|O_RDWR, 0600,
  751. NULL);
  752. if (ret < 0)
  753. return ret = -EEXIST ? 1 : ret;
  754. if (obj)
  755. *((struct shim_handle **) obj) = file;
  756. return 0;
  757. }
  758. static int open_pal_handle (const char * uri, void * obj)
  759. {
  760. PAL_HANDLE hdl;
  761. if (!memcmp(uri, "dir:", 4))
  762. hdl = DkStreamOpen(uri, 0,
  763. PAL_SHARE_OWNER_X|PAL_SHARE_OWNER_W|
  764. PAL_SHARE_OWNER_R,
  765. PAL_CREAT_TRY|PAL_CREAT_ALWAYS,
  766. 0);
  767. else
  768. hdl = DkStreamOpen(uri, PAL_ACCESS_RDWR,
  769. PAL_SHARE_OWNER_W|PAL_SHARE_OWNER_R,
  770. PAL_CREAT_TRY|PAL_CREAT_ALWAYS,
  771. 0);
  772. if (!hdl) {
  773. if (PAL_NATIVE_ERRNO == PAL_ERROR_STREAMEXIST)
  774. return 0;
  775. else
  776. return -PAL_ERRNO;
  777. }
  778. if (obj)
  779. *((PAL_HANDLE *) obj) = hdl;
  780. return 0;
  781. }
  782. static int output_path (char * path, size_t size, const void * id,
  783. struct shim_qstr * qstr)
  784. {
  785. int len = strlen(path);
  786. if (qstr)
  787. qstrsetstr(qstr, path, len);
  788. return len;
  789. }
  790. int create_dir (const char * prefix, char * path, size_t size,
  791. struct shim_handle ** hdl)
  792. {
  793. unsigned int suffix;
  794. if (prefix) {
  795. int len = strlen(prefix);
  796. if (len >= size)
  797. return -ERANGE;
  798. memcpy(path, prefix, len + 1);
  799. }
  800. return create_unique(&name_path, &open_dir, &output_path, path, size,
  801. &suffix, hdl, NULL);
  802. }
  803. int create_file (const char * prefix, char * path, size_t size,
  804. struct shim_handle ** hdl)
  805. {
  806. unsigned int suffix;
  807. if (prefix) {
  808. int len = strlen(prefix);
  809. if (len >= size)
  810. return -ERANGE;
  811. memcpy(path, prefix, len + 1);
  812. }
  813. return create_unique(&name_path, &open_file, &output_path, path, size,
  814. &suffix, hdl, NULL);
  815. }
  816. int create_handle (const char * prefix, char * uri, size_t size,
  817. PAL_HANDLE * hdl, unsigned int * id)
  818. {
  819. unsigned int suffix;
  820. if (prefix) {
  821. int len = strlen(prefix);
  822. if (len >= size)
  823. return -ERANGE;
  824. memcpy(uri, prefix, len + 1);
  825. }
  826. return create_unique(&name_path, &open_pal_handle, &output_path, uri, size,
  827. id ? : &suffix, hdl, NULL);
  828. }
  829. void check_stack_hook (void)
  830. {
  831. struct shim_thread * cur_thread = get_cur_thread();
  832. void * rsp;
  833. asm volatile ("movq %%rsp, %0" : "=r"(rsp) :: "memory");
  834. if (rsp <= cur_thread->stack_top && rsp > cur_thread->stack) {
  835. if (rsp - cur_thread->stack < PAL_CB(pagesize))
  836. sys_printf("*** stack is almost drained (RSP = %p, stack = %p-%p) ***\n",
  837. rsp, cur_thread->stack, cur_thread->stack_top);
  838. } else {
  839. sys_printf("*** context dismatched with thread stack (RSP = %p, stack = %p-%p) ***\n",
  840. rsp, cur_thread->stack, cur_thread->stack_top);
  841. }
  842. }
  843. #ifdef PROFILE
  844. static void print_profile_result (PAL_HANDLE hdl, struct shim_profile * root,
  845. int level)
  846. {
  847. unsigned long total_interval_time = 0;
  848. unsigned long total_interval_count = 0;
  849. for (int i = 0 ; i < N_PROFILE ; i++) {
  850. struct shim_profile * profile = &PROFILES[i];
  851. if (profile->root != root || profile->disabled)
  852. continue;
  853. switch (profile->type) {
  854. case OCCURENCE: {
  855. unsigned int count =
  856. atomic_read(&profile->val.occurence.count);
  857. if (count) {
  858. for (int j = 0 ; j < level ; j++)
  859. __sys_fprintf(hdl, " ");
  860. __sys_fprintf(hdl, "- %s: %u times\n", profile->name, count);
  861. }
  862. break;
  863. }
  864. case INTERVAL: {
  865. unsigned int count =
  866. atomic_read(&profile->val.interval.count);
  867. if (count) {
  868. unsigned long time =
  869. atomic_read(&profile->val.interval.time);
  870. unsigned long ind_time = time / count;
  871. total_interval_time += time;
  872. total_interval_count += count;
  873. for (int j = 0 ; j < level ; j++)
  874. __sys_fprintf(hdl, " ");
  875. __sys_fprintf(hdl, "- (%11.11lu) %s: %u times, %lu msec\n",
  876. time, profile->name, count, ind_time);
  877. }
  878. break;
  879. }
  880. case CATAGORY:
  881. for (int j = 0 ; j < level ; j++)
  882. __sys_fprintf(hdl, " ");
  883. __sys_fprintf(hdl, "- %s:\n", profile->name);
  884. print_profile_result(hdl, profile, level + 1);
  885. break;
  886. }
  887. }
  888. if (total_interval_count) {
  889. __sys_fprintf(hdl, " - (%11.11u) total: %u times, %lu msec\n",
  890. total_interval_time, total_interval_count,
  891. total_interval_time / total_interval_count);
  892. }
  893. }
  894. #endif /* PROFILE */
  895. static struct shim_atomic in_terminate = { .counter = 0, };
  896. int shim_terminate (void)
  897. {
  898. debug("teminating the whole process\n");
  899. /* do last clean-up of the process */
  900. shim_clean();
  901. DkProcessExit(0);
  902. return 0;
  903. }
  904. int shim_clean (void)
  905. {
  906. /* preventing multiple cleanup, this is mostly caused by
  907. assertion in shim_clean */
  908. atomic_inc(&in_terminate);
  909. if (atomic_read(&in_terminate) > 1)
  910. return 0;
  911. store_all_msg_persist();
  912. #ifdef PROFILE
  913. if (ENTER_TIME) {
  914. switch (SHIM_GET_TLS()->context.syscall_nr) {
  915. case __NR_exit_group:
  916. SAVE_PROFILE_INTERVAL_SINCE(syscall_exit_group, ENTER_TIME);
  917. break;
  918. case __NR_exit:
  919. SAVE_PROFILE_INTERVAL_SINCE(syscall_exit, ENTER_TIME);
  920. break;
  921. }
  922. }
  923. if (ipc_cld_profile_send()) {
  924. master_lock();
  925. PAL_HANDLE hdl = __open_shim_stdio();
  926. if (hdl) {
  927. __sys_fprintf(hdl, "******************************\n");
  928. __sys_fprintf(hdl, "profiling:\n");
  929. print_profile_result(hdl, &profile_root, 0);
  930. __sys_fprintf(hdl, "******************************\n");
  931. }
  932. master_unlock();
  933. }
  934. #endif
  935. del_all_ipc_ports(0);
  936. if (shim_stdio && shim_stdio != (PAL_HANDLE) -1)
  937. DkObjectClose(shim_stdio);
  938. shim_stdio = NULL;
  939. debug("process %u successfully terminated\n", cur_process.vmid);
  940. master_lock();
  941. DkProcessExit(cur_process.exit_code);
  942. return 0;
  943. }
  944. int message_confirm (const char * message, const char * options)
  945. {
  946. char answer;
  947. int noptions = strlen(options);
  948. char * option_str = __alloca(noptions * 2 + 3), * str = option_str;
  949. int ret = 0;
  950. *(str++) = ' ';
  951. *(str++) = '[';
  952. for (int i = 0 ; i < noptions ; i++) {
  953. *(str++) = options[i];
  954. *(str++) = '/';
  955. }
  956. str--;
  957. *(str++) = ']';
  958. *(str++) = ' ';
  959. master_lock();
  960. PAL_HANDLE hdl = __open_shim_stdio();
  961. if (!hdl) {
  962. master_unlock();
  963. return -EACCES;
  964. }
  965. #define WRITE(buf, len) \
  966. ({ int _ret = DkStreamWrite(hdl, 0, len, buf, NULL); \
  967. _ret ? : -PAL_ERRNO; })
  968. #define READ(buf, len) \
  969. ({ int _ret = DkStreamRead(hdl, 0, len, buf, NULL, 0); \
  970. _ret ? : -PAL_ERRNO; })
  971. if ((ret = WRITE(message, strlen(message))) < 0)
  972. goto out;
  973. if ((ret = WRITE(option_str, noptions * 2 + 3)) < 0)
  974. goto out;
  975. if ((ret = READ(&answer, 1)) < 0)
  976. goto out;
  977. out:
  978. master_unlock();
  979. return (ret < 0) ? ret : answer;
  980. }