shim_init.c 36 KB

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