PageRenderTime 66ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/erts/emulator/sys/win32/sys.c

https://github.com/bsmr-erlang/otp
C | 3291 lines | 2901 code | 167 blank | 223 comment | 209 complexity | 42bf62a5a9ccf009101fd19c86970b87 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1, MPL-2.0-no-copyleft-exception, Apache-2.0
  1. /*
  2. * %CopyrightBegin%
  3. *
  4. * Copyright Ericsson AB 1996-2017. All Rights Reserved.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * %CopyrightEnd%
  19. */
  20. /*
  21. * system-dependent functions
  22. *
  23. */
  24. #ifdef HAVE_CONFIG_H
  25. # include "config.h"
  26. #endif
  27. #include "sys.h"
  28. #include "erl_alloc.h"
  29. #include "erl_sys_driver.h"
  30. #include "global.h"
  31. #include "erl_threads.h"
  32. #include "../../drivers/win32/win_con.h"
  33. #include "erl_cpu_topology.h"
  34. #include <malloc.h>
  35. void erts_sys_init_float(void);
  36. void erl_start(int, char**);
  37. void erts_exit(int n, char*, ...);
  38. void erl_error(char*, va_list);
  39. /*
  40. * Microsoft-specific function to map a WIN32 error code to a Posix errno.
  41. */
  42. extern void _dosmaperr(DWORD);
  43. #ifdef ERL_RUN_SHARED_LIB
  44. #ifdef __argc
  45. #undef __argc
  46. #endif
  47. #define __argc e_argc
  48. #ifdef __argv
  49. #undef __argv
  50. #endif
  51. #define __argv e_argv
  52. #endif
  53. typedef struct driver_data DriverData;
  54. static void init_console();
  55. static int get_and_remove_option(int* argc, char** argv, const char* option);
  56. static char *get_and_remove_option2(int *argc, char **argv,
  57. const char *option);
  58. static int init_async_io(DriverData *dp, struct async_io* aio, int use_threads);
  59. static void release_async_io(struct async_io* aio, ErlDrvPort);
  60. static void async_read_file(struct async_io* aio, LPVOID buf, DWORD numToRead);
  61. static int async_write_file(struct async_io* aio, LPVOID buf, DWORD numToWrite);
  62. static int get_overlapped_result(struct async_io* aio,
  63. LPDWORD pBytesRead, BOOL wait);
  64. static BOOL create_child_process(wchar_t *, HANDLE, HANDLE,
  65. HANDLE, LPHANDLE, LPDWORD, BOOL,
  66. LPVOID, wchar_t*, unsigned,
  67. wchar_t **, int *);
  68. static int create_pipe(LPHANDLE, LPHANDLE, BOOL, BOOL);
  69. static int application_type(const wchar_t* originalName, wchar_t fullPath[MAX_PATH],
  70. BOOL search_in_path, BOOL handle_quotes,
  71. int *error_return);
  72. static void *build_env_block(const erts_osenv_t *env);
  73. HANDLE erts_service_event;
  74. static erts_tsd_key_t win32_errstr_key;
  75. static erts_atomic_t pipe_creation_counter;
  76. /* Results from application_type(_w) is one of */
  77. #define APPL_NONE 0
  78. #define APPL_DOS 1
  79. #define APPL_WIN3X 2
  80. #define APPL_WIN32 3
  81. static int driver_write(long, HANDLE, byte*, int);
  82. static int create_file_thread(struct async_io* aio, int mode);
  83. static void close_active_handle(DriverData *, HANDLE handle);
  84. static DWORD WINAPI threaded_handle_closer(LPVOID param);
  85. static DWORD WINAPI threaded_reader(LPVOID param);
  86. static DWORD WINAPI threaded_writer(LPVOID param);
  87. static DWORD WINAPI threaded_exiter(LPVOID param);
  88. #ifdef DEBUG
  89. static void debug_console(void);
  90. #endif
  91. BOOL WINAPI ctrl_handler(DWORD dwCtrlType);
  92. #define PORT_BUFSIZ 4096
  93. #define DRV_BUF_ALLOC(SZ) \
  94. erts_alloc_fnf(ERTS_ALC_T_DRV_DATA_BUF, (SZ))
  95. #define DRV_BUF_REALLOC(P, SZ) \
  96. erts_realloc_fnf(ERTS_ALC_T_DRV_DATA_BUF, (P), (SZ))
  97. #define DRV_BUF_FREE(P) \
  98. erts_free(ERTS_ALC_T_DRV_DATA_BUF, (P))
  99. /********************* General functions ****************************/
  100. /*
  101. * Whether create_pipe() should use a named pipe or an anonymous.
  102. * (Named pipes are not supported on Windows 95.)
  103. */
  104. static int max_files = 1024;
  105. static BOOL use_named_pipes;
  106. static BOOL win_console = FALSE;
  107. static OSVERSIONINFO int_os_version; /* Version information for Win32. */
  108. /*#define USE_CANCELIOEX
  109. Disabled the use of CancelIoEx as its been seen to cause problem with some
  110. drivers. Not sure what to blame; faulty drivers or some form of invalid use.
  111. */
  112. #if defined(USE_CANCELIOEX)
  113. static BOOL (WINAPI *fpCancelIoEx)(HANDLE,LPOVERLAPPED);
  114. #endif
  115. /* This is the system's main function (which may or may not be called "main")
  116. - do general system-dependent initialization
  117. - call erl_start() to parse arguments and do other init
  118. */
  119. static erts_atomic_t sys_misc_mem_sz;
  120. HMODULE beam_module = NULL;
  121. void erl_sys_init();
  122. void erl_sys_args(int* argc, char** argv);
  123. int nohup;
  124. #ifndef __GNUC__
  125. void erts_sys_invalid_parameter_handler(const wchar_t * expression,
  126. const wchar_t * function,
  127. const wchar_t * file,
  128. unsigned int line,
  129. uintptr_t pReserved
  130. )
  131. {
  132. #ifdef DEBUG
  133. fprintf(stderr,
  134. "Debug: Invalid parameter\"%ls\" "
  135. "(detected in \"%ls\" [%ls:%d]) \n",
  136. (expression) ? expression : L"(unknown)",
  137. (function) ? function : L"(unknown)",
  138. (file) ? file : L"(unknown)",
  139. line);
  140. #endif
  141. return;
  142. }
  143. #endif
  144. void sys_primitive_init(HMODULE beam)
  145. {
  146. #ifndef __GNUC__
  147. /* Initialize this module handle (the beam.dll module handle) and
  148. take care of the standard library's aggressive invalid parameter
  149. handling... */
  150. _set_invalid_parameter_handler(&erts_sys_invalid_parameter_handler);
  151. #endif
  152. beam_module = (HMODULE) beam;
  153. }
  154. UWord
  155. erts_sys_get_page_size(void)
  156. {
  157. SYSTEM_INFO info;
  158. GetSystemInfo(&info);
  159. return (UWord)info.dwPageSize;
  160. }
  161. Uint
  162. erts_sys_misc_mem_sz(void)
  163. {
  164. Uint res = (Uint) erts_check_io_size();
  165. res += (Uint) erts_atomic_read_mb(&sys_misc_mem_sz);
  166. return res;
  167. }
  168. /*
  169. * Reset the terminal to the original settings on exit
  170. */
  171. void sys_tty_reset(int exit_code)
  172. {
  173. if (exit_code == ERTS_ERROR_EXIT)
  174. ConWaitForExit();
  175. else
  176. ConNormalExit();
  177. }
  178. void erl_sys_args(int* argc, char** argv)
  179. {
  180. char *event_name;
  181. erts_sys_env_init();
  182. nohup = get_and_remove_option(argc, argv, "-nohup");
  183. #ifdef DEBUG
  184. /*
  185. * Start a debug console if -console option given.
  186. */
  187. if (get_and_remove_option(argc, argv, "-console")) {
  188. debug_console();
  189. }
  190. #endif
  191. if (nohup && (event_name = get_and_remove_option2(argc, argv,
  192. "-service_event"))) {
  193. if ((erts_service_event =
  194. OpenEvent(EVENT_ALL_ACCESS,FALSE,event_name)) == NULL) {
  195. erts_fprintf(stderr,
  196. "Warning: could not open service event: %s\r\n",
  197. event_name);
  198. }
  199. } else {
  200. erts_service_event = NULL;
  201. }
  202. #ifdef DEBUG
  203. /*
  204. * Given the "-threads" option, always use threads instead of
  205. * named pipes.
  206. */
  207. if (get_and_remove_option(argc, argv, "-threads")) {
  208. use_named_pipes = FALSE;
  209. }
  210. #endif
  211. }
  212. /*
  213. * Function returns 1 if we can read from all values in between
  214. * start and stop.
  215. */
  216. int
  217. erts_sys_is_area_readable(char *start, char *stop) {
  218. volatile char tmp;
  219. __try
  220. {
  221. while(start < stop) {
  222. tmp = *start;
  223. start++;
  224. }
  225. }
  226. __except(EXCEPTION_EXECUTE_HANDLER)
  227. {
  228. return 0;
  229. }
  230. return 1;
  231. }
  232. int erts_sys_prepare_crash_dump(int secs)
  233. {
  234. Port *heart_port;
  235. Eterm heap[3];
  236. Eterm *hp = heap;
  237. Eterm list = NIL;
  238. heart_port = erts_get_heart_port();
  239. if (heart_port) {
  240. list = CONS(hp, make_small(8), list); hp += 2;
  241. /* send to heart port, CMD = 8, i.e. prepare crash dump =o */
  242. erts_port_output(NULL, ERTS_PORT_SIG_FLG_FORCE_IMM_CALL, heart_port,
  243. heart_port->common.id, list, NULL);
  244. return 1;
  245. }
  246. /* Windows - free file descriptors are hopefully available */
  247. /* Alarm not used on windows */
  248. return 0;
  249. }
  250. int erts_set_signal(Eterm signal, Eterm type) {
  251. return 0;
  252. }
  253. static void
  254. init_console(void)
  255. {
  256. char* mode = erts_read_env("ERL_CONSOLE_MODE");
  257. if (!mode || strcmp(mode, "window") == 0) {
  258. win_console = TRUE;
  259. ConInit();
  260. /*nohup = 0;*/
  261. } else if (strncmp(mode, "tty:", 4) == 0) {
  262. if (mode[5] == 'c') {
  263. setvbuf(stdout, NULL, _IONBF, 0);
  264. }
  265. if (mode[6] == 'c') {
  266. setvbuf(stderr, NULL, _IONBF, 0);
  267. }
  268. }
  269. erts_free_read_env(mode);
  270. }
  271. int sys_max_files(void)
  272. {
  273. return max_files;
  274. }
  275. /*
  276. * Looks for the given option in the argv vector. If it is found,
  277. * it will be removed from the argv vector.
  278. *
  279. * If the return value indicates that the option was found and removed,
  280. * it is the responsibility of the caller to decrement the value of argc.
  281. *
  282. * Returns: 0 if the option wasn't found, 1 if it was found
  283. */
  284. static int
  285. get_and_remove_option(int* argc, char* argv[], const char *option)
  286. {
  287. int i;
  288. for (i = 1; i < *argc; i++) {
  289. if (strcmp(argv[i], option) == 0) {
  290. (*argc)--;
  291. while (i < *argc) {
  292. argv[i] = argv[i+1];
  293. i++;
  294. }
  295. argv[i] = NULL;
  296. return 1;
  297. }
  298. }
  299. return 0;
  300. }
  301. static char *get_and_remove_option2(int *argc, char **argv,
  302. const char *option)
  303. {
  304. char *ret;
  305. int i;
  306. for (i = 1; i < *argc; i++) {
  307. if (strcmp(argv[i], option) == 0) {
  308. if (i+1 < *argc) {
  309. ret = argv[i+1];
  310. (*argc) -= 2;
  311. while (i < *argc) {
  312. argv[i] = argv[i+2];
  313. i++;
  314. }
  315. argv[i] = NULL;
  316. return ret;
  317. }
  318. }
  319. }
  320. return NULL;
  321. }
  322. /************************** OS info *******************************/
  323. /* Used by erlang:info/1. */
  324. /* (This code was formerly in drv.XXX/XXX_os_drv.c) */
  325. char os_type[] = "win32";
  326. void
  327. os_flavor(char *namebuf, unsigned size)
  328. {
  329. switch (int_os_version.dwPlatformId) {
  330. case VER_PLATFORM_WIN32_WINDOWS:
  331. strcpy(namebuf, "windows");
  332. break;
  333. case VER_PLATFORM_WIN32_NT:
  334. strcpy(namebuf, "nt");
  335. break;
  336. default: /* Can't happen. */
  337. strcpy(namebuf, "unknown");
  338. break;
  339. }
  340. }
  341. void
  342. os_version(pMajor, pMinor, pBuild)
  343. int* pMajor; /* Pointer to major version. */
  344. int* pMinor; /* Pointer to minor version. */
  345. int* pBuild; /* Pointer to build number. */
  346. {
  347. *pMajor = int_os_version.dwMajorVersion;
  348. *pMinor = int_os_version.dwMinorVersion;
  349. *pBuild = int_os_version.dwBuildNumber;
  350. }
  351. /************************** Port I/O *******************************/
  352. /* I. Common stuff */
  353. /* II. The spawn/fd/vanilla drivers */
  354. /*
  355. * Definitions for driver flags.
  356. */
  357. #define DF_OVR_READY 1 /* Overlapped result is ready. */
  358. #define DF_EXIT_THREAD 2 /* The thread should exit. */
  359. #define DF_XLAT_CR 4 /* The thread should translate CRs. */
  360. #define DF_DROP_IF_INVH 8 /* Drop packages instead of crash if
  361. invalid handle (stderr) */
  362. #define DF_THREAD_FLUSHED 16 /* The thread should exit. */
  363. #define OV_BUFFER_PTR(dp) ((LPVOID) ((dp)->ov.Internal))
  364. #define OV_NUM_TO_READ(dp) ((dp)->ov.InternalHigh)
  365. /*
  366. * This data is used to make overlapped I/O operations work on both
  367. * Windows NT (using true overlapped I/O) and Windows 95 (using threads).
  368. */
  369. typedef struct async_io {
  370. unsigned flags; /* Driver flags, definitions found above. */
  371. HANDLE thread; /* If -1, overlapped I/O is used (Windows NT).
  372. * Otherwise, it is the handle of the thread used
  373. * for simulating overlapped I/O (Windows 95 and
  374. * the console for Windows NT).
  375. */
  376. HANDLE fd; /* Handle for file or pipe. */
  377. int async_io_active; /* if true, a close of the file will signal the event in ov */
  378. OVERLAPPED ov; /* Control structure for overlapped reading.
  379. * When overlapped reading is simulated with
  380. * a thread, the fields are used as follows:
  381. * ov.Internal - Read buffer.
  382. * ov.InternalHigh - Number of bytes to read.
  383. * See macros above.
  384. */
  385. HANDLE ioAllowed; /* The thread will wait for this event
  386. * before starting a new read or write.
  387. */
  388. HANDLE flushEvent; /* Used to signal that a flush should be done. */
  389. HANDLE flushReplyEvent; /* Used to signal that a flush has been done. */
  390. DWORD pendingError; /* Used to delay presentating an error to Erlang
  391. * until the check_io function is entered.
  392. */
  393. DWORD bytesTransferred; /* Bytes read or write in the last operation.
  394. * Valid only when DF_OVR_READY is set.
  395. */
  396. DriverData *dp; /* Pointer to driver data struct which
  397. this struct is part of */
  398. } AsyncIo;
  399. /*
  400. * Input thread for fd_driver (if fd_driver is running).
  401. */
  402. static AsyncIo* fd_driver_input = NULL;
  403. static BOOL (WINAPI *fpSetHandleInformation)(HANDLE,DWORD,DWORD);
  404. /*
  405. * This data is used by the spawn and vanilla drivers.
  406. * There will be one entry for each port, even if the input
  407. * and output HANDLES are different. Since handles are not
  408. * guaranteed to be small numbers in Win32, we cannot index
  409. * with them. I.e. the index for each entry is not equal to
  410. * none of the file handles.
  411. */
  412. struct driver_data {
  413. int totalNeeded; /* Total number of bytes needed to fill
  414. * up the packet header or packet. */
  415. int bytesInBuffer; /* Number of bytes read so far in
  416. * the input buffer.
  417. */
  418. int inBufSize; /* Size of input buffer. */
  419. byte *inbuf; /* Buffer to use for overlapped read. */
  420. int outBufSize; /* Size of output buffer. */
  421. byte *outbuf; /* Buffer to use for overlapped write. */
  422. ErlDrvPort port_num; /* The port handle. */
  423. int packet_bytes; /* 0: continuous stream, 1, 2, or 4: the number
  424. * of bytes in the packet header.
  425. */
  426. HANDLE port_pid; /* PID of the port process. */
  427. AsyncIo in; /* Control block for overlapped reading. */
  428. AsyncIo out; /* Control block for overlapped writing. */
  429. int report_exit; /* Do report exit status for the port */
  430. erts_atomic32_t refc; /* References to this struct */
  431. };
  432. /* Driver interfaces */
  433. static ErlDrvData spawn_start(ErlDrvPort, char*, SysDriverOpts*);
  434. static ErlDrvData fd_start(ErlDrvPort, char*, SysDriverOpts*);
  435. static ErlDrvData vanilla_start(ErlDrvPort, char*, SysDriverOpts*);
  436. static int spawn_init(void);
  437. static int fd_init(void);
  438. static void fd_stop(ErlDrvData);
  439. static void stop(ErlDrvData);
  440. static void output(ErlDrvData, char*, ErlDrvSizeT);
  441. static void ready_input(ErlDrvData, ErlDrvEvent);
  442. static void ready_output(ErlDrvData, ErlDrvEvent);
  443. static void stop_select(ErlDrvEvent, void*);
  444. struct erl_drv_entry spawn_driver_entry = {
  445. spawn_init,
  446. spawn_start,
  447. stop,
  448. output,
  449. ready_input,
  450. ready_output,
  451. "spawn",
  452. NULL, /* finish */
  453. NULL, /* handle */
  454. NULL, /* control */
  455. NULL, /* timeout */
  456. NULL, /* outputv */
  457. NULL, /* ready_async */
  458. NULL, /* flush */
  459. NULL, /* call */
  460. NULL, /* event */
  461. ERL_DRV_EXTENDED_MARKER,
  462. ERL_DRV_EXTENDED_MAJOR_VERSION,
  463. ERL_DRV_EXTENDED_MINOR_VERSION,
  464. 0, /* ERL_DRV_FLAGs */
  465. NULL,
  466. NULL, /* process_exit */
  467. stop_select
  468. };
  469. #ifdef HARD_POLL_DEBUG
  470. extern void poll_debug_set_active_fd(ErtsSysFdType fd);
  471. extern void poll_debug_read_begin(ErtsSysFdType fd);
  472. extern void poll_debug_read_done(ErtsSysFdType fd, int bytes);
  473. extern void poll_debug_async_initialized(ErtsSysFdType fd);
  474. extern void poll_debug_async_immediate(ErtsSysFdType fd, int bytes);
  475. extern void poll_debug_write_begin(ErtsSysFdType fd);
  476. extern void poll_debug_write_done(ErtsSysFdType fd, int bytes);
  477. #endif
  478. extern int null_func(void);
  479. struct erl_drv_entry fd_driver_entry = {
  480. fd_init,
  481. fd_start,
  482. fd_stop,
  483. output,
  484. ready_input,
  485. ready_output,
  486. "fd",
  487. NULL, /* finish */
  488. NULL, /* handle */
  489. NULL, /* control */
  490. NULL, /* timeout */
  491. NULL, /* outputv */
  492. NULL, /* ready_async */
  493. NULL, /* flush */
  494. NULL, /* call */
  495. NULL, /* event */
  496. ERL_DRV_EXTENDED_MARKER,
  497. ERL_DRV_EXTENDED_MAJOR_VERSION,
  498. ERL_DRV_EXTENDED_MINOR_VERSION,
  499. 0, /* ERL_DRV_FLAGs */
  500. NULL,
  501. NULL, /* process_exit */
  502. stop_select
  503. };
  504. struct erl_drv_entry vanilla_driver_entry = {
  505. null_func,
  506. vanilla_start,
  507. stop,
  508. output,
  509. ready_input,
  510. ready_output,
  511. "vanilla",
  512. NULL, /* finish */
  513. NULL, /* handle */
  514. NULL, /* control */
  515. NULL, /* timeout */
  516. NULL, /* outputv */
  517. NULL, /* ready_async */
  518. NULL, /* flush */
  519. NULL, /* call */
  520. NULL, /* event */
  521. ERL_DRV_EXTENDED_MARKER,
  522. ERL_DRV_EXTENDED_MAJOR_VERSION,
  523. ERL_DRV_EXTENDED_MINOR_VERSION,
  524. 0, /* ERL_DRV_FLAGs */
  525. NULL,
  526. NULL, /* process_exit */
  527. stop_select
  528. };
  529. static ERTS_INLINE void
  530. refer_driver_data(DriverData *dp)
  531. {
  532. #ifdef DEBUG
  533. erts_aint32_t refc = erts_atomic32_inc_read_nob(&dp->refc);
  534. ASSERT(refc > 1);
  535. #else
  536. erts_atomic32_inc_nob(&dp->refc);
  537. #endif
  538. }
  539. static ERTS_INLINE void
  540. unrefer_driver_data(DriverData *dp)
  541. {
  542. erts_aint32_t refc = erts_atomic32_dec_read_mb(&dp->refc);
  543. ASSERT(refc >= 0);
  544. if (refc == 0)
  545. driver_free(dp);
  546. }
  547. /*
  548. * Initialises a DriverData structure.
  549. *
  550. * Results: Returns a pointer to a DriverData structure, or NULL
  551. * if the initialsation failed.
  552. */
  553. static DriverData*
  554. new_driver_data(ErlDrvPort port_num, int packet_bytes, int wait_objs_required, int use_threads)
  555. {
  556. DriverData* dp;
  557. DEBUGF(("new_driver_data(%p, pb %d)\n", port_num, packet_bytes));
  558. dp = driver_alloc(sizeof(DriverData));
  559. if (!dp)
  560. return NULL;
  561. /*
  562. * We used to test first at all that there is enough room in the
  563. * array used by WaitForMultipleObjects(), but that is not necessary
  564. * any more, since driver_select() can't fail.
  565. */
  566. erts_atomic32_init_nob(&dp->refc, 1);
  567. dp->bytesInBuffer = 0;
  568. dp->totalNeeded = packet_bytes;
  569. dp->inBufSize = PORT_BUFSIZ;
  570. dp->inbuf = DRV_BUF_ALLOC(dp->inBufSize);
  571. if (dp->inbuf == NULL)
  572. goto buf_alloc_error;
  573. erts_atomic_add_nob(&sys_misc_mem_sz, dp->inBufSize);
  574. dp->outBufSize = 0;
  575. dp->outbuf = NULL;
  576. dp->port_num = port_num;
  577. dp->packet_bytes = packet_bytes;
  578. dp->port_pid = INVALID_HANDLE_VALUE;
  579. if (init_async_io(dp, &dp->in, use_threads) == -1)
  580. goto async_io_error1;
  581. if (init_async_io(dp, &dp->out, use_threads) == -1)
  582. goto async_io_error2;
  583. return dp;
  584. async_io_error2:
  585. release_async_io(&dp->in, dp->port_num);
  586. async_io_error1:
  587. release_async_io(&dp->out, dp->port_num);
  588. buf_alloc_error:
  589. driver_free(dp);
  590. return NULL;
  591. }
  592. static void
  593. release_driver_data(DriverData* dp)
  594. {
  595. #ifdef USE_CANCELIOEX
  596. if (fpCancelIoEx != NULL) {
  597. if (dp->in.thread == (HANDLE) -1 && dp->in.fd != INVALID_HANDLE_VALUE) {
  598. (*fpCancelIoEx)(dp->in.fd, NULL);
  599. }
  600. if (dp->out.thread == (HANDLE) -1 && dp->out.fd != INVALID_HANDLE_VALUE) {
  601. (*fpCancelIoEx)(dp->out.fd, NULL);
  602. }
  603. }
  604. else
  605. #endif
  606. {
  607. /* This is a workaround for the fact that CancelIo cant cancel
  608. requests issued by another thread and that we cant use
  609. CancelIoEx as that's only available in Vista etc.
  610. R14: Avoid scheduler deadlock by only wait for 10ms, and then spawn
  611. a thread that will keep waiting in in order to close handles. */
  612. HANDLE handles[2];
  613. int i = 0;
  614. int timeout = 10;
  615. if(dp->in.async_io_active && dp->in.fd != INVALID_HANDLE_VALUE) {
  616. CloseHandle(dp->in.fd);
  617. dp->in.fd = INVALID_HANDLE_VALUE;
  618. DEBUGF(("Waiting for the in event thingie"));
  619. if (WaitForSingleObject(dp->in.ov.hEvent,timeout) == WAIT_TIMEOUT) {
  620. close_active_handle(dp, dp->in.ov.hEvent);
  621. dp->in.ov.hEvent = NULL;
  622. timeout = 0;
  623. }
  624. DEBUGF(("...done\n"));
  625. }
  626. if(dp->out.async_io_active && dp->out.fd != INVALID_HANDLE_VALUE) {
  627. CloseHandle(dp->out.fd);
  628. dp->out.fd = INVALID_HANDLE_VALUE;
  629. DEBUGF(("Waiting for the out event thingie"));
  630. if (WaitForSingleObject(dp->out.ov.hEvent,timeout) == WAIT_TIMEOUT) {
  631. close_active_handle(dp, dp->out.ov.hEvent);
  632. dp->out.ov.hEvent = NULL;
  633. }
  634. DEBUGF(("...done\n"));
  635. }
  636. }
  637. if (dp->inbuf != NULL) {
  638. ASSERT(erts_atomic_read_nob(&sys_misc_mem_sz) >= dp->inBufSize);
  639. erts_atomic_add_nob(&sys_misc_mem_sz, -1*dp->inBufSize);
  640. DRV_BUF_FREE(dp->inbuf);
  641. dp->inBufSize = 0;
  642. dp->inbuf = NULL;
  643. }
  644. ASSERT(dp->inBufSize == 0);
  645. if (dp->outbuf != NULL) {
  646. ASSERT(erts_atomic_read_nob(&sys_misc_mem_sz) >= dp->outBufSize);
  647. erts_atomic_add_nob(&sys_misc_mem_sz, -1*dp->outBufSize);
  648. DRV_BUF_FREE(dp->outbuf);
  649. dp->outBufSize = 0;
  650. dp->outbuf = NULL;
  651. }
  652. ASSERT(dp->outBufSize == 0);
  653. if (dp->port_pid != INVALID_HANDLE_VALUE) {
  654. CloseHandle(dp->port_pid);
  655. dp->port_pid = INVALID_HANDLE_VALUE;
  656. }
  657. release_async_io(&dp->in, dp->port_num);
  658. release_async_io(&dp->out, dp->port_num);
  659. /*
  660. * This must be last, because this function might be executed from
  661. * the exit thread.
  662. */
  663. unrefer_driver_data(dp);
  664. }
  665. struct handles_to_be_closed {
  666. HANDLE handles[MAXIMUM_WAIT_OBJECTS];
  667. DriverData *drv_data[MAXIMUM_WAIT_OBJECTS];
  668. unsigned cnt;
  669. };
  670. static struct handles_to_be_closed* htbc_curr = NULL;
  671. CRITICAL_SECTION htbc_lock;
  672. static void close_active_handle(DriverData *dp, HANDLE handle)
  673. {
  674. struct handles_to_be_closed* htbc;
  675. int i;
  676. EnterCriticalSection(&htbc_lock);
  677. htbc = htbc_curr;
  678. if (htbc == NULL || htbc->cnt >= MAXIMUM_WAIT_OBJECTS) {
  679. DWORD tid;
  680. HANDLE thread;
  681. htbc = (struct handles_to_be_closed*) erts_alloc(ERTS_ALC_T_DRV_TAB,
  682. sizeof(*htbc));
  683. htbc->handles[0] = CreateAutoEvent(FALSE);
  684. htbc->drv_data[0] = NULL;
  685. htbc->cnt = 1;
  686. thread = (HANDLE *) _beginthreadex(NULL, 0, threaded_handle_closer, htbc, 0, &tid);
  687. CloseHandle(thread);
  688. }
  689. i = htbc->cnt++;
  690. htbc->handles[i] = handle;
  691. htbc->drv_data[i] = dp;
  692. if (dp)
  693. refer_driver_data(dp); /* Need to keep driver data until we have
  694. closed the event; outstanding operation
  695. might write into it.. */
  696. SetEvent(htbc->handles[0]);
  697. htbc_curr = htbc;
  698. LeaveCriticalSection(&htbc_lock);
  699. }
  700. static DWORD WINAPI
  701. threaded_handle_closer(LPVOID param)
  702. {
  703. struct handles_to_be_closed* htbc = (struct handles_to_be_closed*) param;
  704. unsigned ix;
  705. DWORD res;
  706. DEBUGF(("threaded_handle_closer %p started\r\n", htbc));
  707. EnterCriticalSection(&htbc_lock);
  708. for (;;) {
  709. {
  710. HANDLE* handles = htbc->handles;
  711. unsigned cnt = htbc->cnt;
  712. DWORD timeout = (htbc == htbc_curr) ? INFINITE : 10*1000;
  713. LeaveCriticalSection(&htbc_lock);
  714. DEBUGF(("threaded_handle_closer %p waiting for %d handles\r\n", htbc, cnt));
  715. res = WaitForMultipleObjects(cnt, handles, FALSE, timeout);
  716. }
  717. EnterCriticalSection(&htbc_lock);
  718. switch (res) {
  719. case WAIT_OBJECT_0:
  720. case WAIT_TIMEOUT:
  721. break; /* got some more handles to wait for maybe */
  722. default:
  723. ix = res - WAIT_OBJECT_0;
  724. if (ix > 0 && ix < htbc->cnt) {
  725. int move_ix;
  726. CloseHandle(htbc->handles[ix]);
  727. if (htbc->drv_data[ix])
  728. unrefer_driver_data(htbc->drv_data[ix]);
  729. move_ix = --htbc->cnt;
  730. htbc->handles[ix] = htbc->handles[move_ix];
  731. htbc->drv_data[ix] = htbc->drv_data[move_ix];
  732. }
  733. }
  734. if (htbc != htbc_curr) {
  735. if (htbc->cnt == 1) { /* no real handles left */
  736. break;
  737. }
  738. /* The thread with most free slots will be "current" */
  739. if (htbc->cnt < htbc_curr->cnt) {
  740. htbc_curr = htbc;
  741. DEBUGF(("threaded_handle_closer %p made current\r\n", htbc));
  742. }
  743. }
  744. }
  745. LeaveCriticalSection(&htbc_lock);
  746. CloseHandle(htbc->handles[0]);
  747. ASSERT(!htbc->drv_data[0]);
  748. erts_free(ERTS_ALC_T_DRV_TAB, htbc);
  749. DEBUGF(("threaded_handle_closer %p terminating\r\n", htbc));
  750. return 0;
  751. }
  752. /*
  753. * Stores input and output file descriptors in the DriverData structure,
  754. * and calls driver_select().
  755. *
  756. * This function fortunately can't fail!
  757. */
  758. static ErlDrvData
  759. set_driver_data(DriverData* dp, HANDLE ifd, HANDLE ofd, int read_write, int report_exit)
  760. {
  761. int result;
  762. dp->in.fd = ifd;
  763. dp->out.fd = ofd;
  764. dp->report_exit = report_exit;
  765. if (read_write & DO_READ) {
  766. result = driver_select(dp->port_num, (ErlDrvEvent)dp->in.ov.hEvent,
  767. ERL_DRV_READ|ERL_DRV_USE, 1);
  768. ASSERT(result != -1);
  769. async_read_file(&dp->in, dp->inbuf, dp->inBufSize);
  770. }
  771. if (read_write & DO_WRITE) {
  772. result = driver_select(dp->port_num, (ErlDrvEvent)dp->out.ov.hEvent,
  773. ERL_DRV_WRITE|ERL_DRV_USE, 1);
  774. ASSERT(result != -1);
  775. }
  776. return (ErlDrvData) dp;
  777. }
  778. static ErlDrvData
  779. reuse_driver_data(DriverData *dp, HANDLE ifd, HANDLE ofd, int read_write, ErlDrvPort port_num)
  780. {
  781. int result;
  782. dp->port_num = port_num;
  783. dp->in.fd = ifd;
  784. dp->out.fd = ofd;
  785. dp->report_exit = 0;
  786. if (read_write & DO_READ) {
  787. result = driver_select(dp->port_num, (ErlDrvEvent)dp->in.ov.hEvent,
  788. ERL_DRV_READ|ERL_DRV_USE, 1);
  789. ASSERT(result != -1);
  790. }
  791. if (read_write & DO_WRITE) {
  792. result = driver_select(dp->port_num, (ErlDrvEvent)dp->out.ov.hEvent,
  793. ERL_DRV_WRITE|ERL_DRV_USE, 1);
  794. ASSERT(result != -1);
  795. }
  796. return (ErlDrvData) dp;
  797. }
  798. /*
  799. * Initialises an AsyncIo structure.
  800. */
  801. static int
  802. init_async_io(DriverData *dp, AsyncIo* aio, int use_threads)
  803. {
  804. aio->dp = dp;
  805. aio->flags = 0;
  806. aio->thread = (HANDLE) -1;
  807. aio->fd = INVALID_HANDLE_VALUE;
  808. aio->ov.hEvent = NULL;
  809. aio->ov.Offset = 0L;
  810. aio->ov.OffsetHigh = 0L;
  811. aio->ioAllowed = NULL;
  812. aio->flushEvent = NULL;
  813. aio->flushReplyEvent = NULL;
  814. aio->pendingError = 0;
  815. aio->bytesTransferred = 0;
  816. aio->async_io_active = 0;
  817. aio->ov.hEvent = CreateManualEvent(FALSE);
  818. if (aio->ov.hEvent == NULL)
  819. return -1;
  820. if (use_threads) {
  821. OV_BUFFER_PTR(aio) = NULL;
  822. OV_NUM_TO_READ(aio) = 0;
  823. aio->ioAllowed = CreateAutoEvent(FALSE);
  824. if (aio->ioAllowed == NULL)
  825. return -1;
  826. aio->flushEvent = CreateAutoEvent(FALSE);
  827. if (aio->flushEvent == NULL)
  828. return -1;
  829. aio->flushReplyEvent = CreateAutoEvent(FALSE);
  830. if (aio->flushReplyEvent == NULL)
  831. return -1;
  832. }
  833. return 0;
  834. }
  835. /*
  836. * Releases everything allocated in an AsyncIo structure.
  837. */
  838. static void
  839. release_async_io(AsyncIo* aio, ErlDrvPort port_num)
  840. {
  841. aio->flags = 0;
  842. if (aio->thread != (HANDLE) -1)
  843. CloseHandle(aio->thread);
  844. aio->thread = (HANDLE) -1;
  845. if (aio->fd != INVALID_HANDLE_VALUE)
  846. CloseHandle(aio->fd);
  847. aio->fd = INVALID_HANDLE_VALUE;
  848. if (aio->ov.hEvent != NULL)
  849. CloseHandle(aio->ov.hEvent);
  850. aio->ov.hEvent = NULL;
  851. if (aio->ioAllowed != NULL)
  852. CloseHandle(aio->ioAllowed);
  853. aio->ioAllowed = NULL;
  854. if (aio->flushEvent != NULL)
  855. CloseHandle(aio->flushEvent);
  856. aio->flushEvent = NULL;
  857. if (aio->flushReplyEvent != NULL)
  858. CloseHandle(aio->flushReplyEvent);
  859. aio->flushReplyEvent = NULL;
  860. }
  861. /* ----------------------------------------------------------------------
  862. * async_read_file --
  863. * Initiaties an asynchronous file read, or simulates that using
  864. * the thread associated with this driver data. To get the results,
  865. * call get_overlapped_result().
  866. *
  867. * Results:
  868. * None.
  869. * ----------------------------------------------------------------------
  870. */
  871. static void
  872. async_read_file(AsyncIo* aio, LPVOID buf, DWORD numToRead)
  873. {
  874. aio->pendingError = NO_ERROR;
  875. #ifdef HARD_POLL_DEBUG
  876. poll_debug_async_initialized(aio->ov.hEvent);
  877. #endif
  878. if (aio->thread != (HANDLE) -1) {
  879. DEBUGF(("async_read_file: signaling thread 0x%x, event 0x%x\n",
  880. aio->thread, aio->ioAllowed));
  881. OV_BUFFER_PTR(aio) = buf;
  882. OV_NUM_TO_READ(aio) = numToRead;
  883. ResetEvent(aio->ov.hEvent);
  884. SetEvent(aio->ioAllowed);
  885. } else {
  886. aio->async_io_active = 1; /* Will get 0 when the event actually happened */
  887. if (ReadFile(aio->fd, buf, numToRead,
  888. &aio->bytesTransferred, &aio->ov)) {
  889. DEBUGF(("async_read_file: ReadFile() suceeded: %d bytes\n",
  890. aio->bytesTransferred));
  891. #ifdef HARD_POLL_DEBUG
  892. poll_debug_async_immediate(aio->ov.hEvent, aio->bytesTransferred);
  893. #endif
  894. aio->flags |= DF_OVR_READY;
  895. SetEvent(aio->ov.hEvent);
  896. } else {
  897. DWORD error = GetLastError();
  898. if (error != ERROR_IO_PENDING) {
  899. #ifdef HARD_POLL_DEBUG
  900. poll_debug_async_immediate(aio->ov.hEvent, 0);
  901. #endif
  902. aio->pendingError = error;
  903. SetEvent(aio->ov.hEvent);
  904. }
  905. DEBUGF(("async_read_file: ReadFile() -> %s\n", win32_errorstr(error)));
  906. }
  907. }
  908. }
  909. /* ----------------------------------------------------------------------
  910. * async_write_file --
  911. * Initiaties an asynchronous file write, or simulates that using
  912. * the output thread associated with this driver data.
  913. * To get the results, call get_overlapped_result().
  914. *
  915. * Results:
  916. * None.
  917. * ----------------------------------------------------------------------
  918. */
  919. static int
  920. async_write_file(AsyncIo* aio, /* Pointer to async control block. */
  921. LPVOID buf, /* Pointer to buffer with data to write. */
  922. DWORD numToWrite) /* Number of bytes to write. */
  923. {
  924. aio->pendingError = NO_ERROR;
  925. if (aio->thread != (HANDLE) -1) {
  926. DEBUGF(("async_write_file: signaling thread 0x%x, event 0x%x\n",
  927. aio->thread, aio->ioAllowed));
  928. OV_BUFFER_PTR(aio) = buf;
  929. OV_NUM_TO_READ(aio) = numToWrite;
  930. ResetEvent(aio->ov.hEvent);
  931. SetEvent(aio->ioAllowed);
  932. } else {
  933. aio->async_io_active = 1; /* Will get 0 when the event actually happened */
  934. if (WriteFile(aio->fd, buf, numToWrite,
  935. &aio->bytesTransferred, &aio->ov)) {
  936. DEBUGF(("async_write_file: WriteFile() suceeded: %d bytes\n",
  937. aio->bytesTransferred));
  938. aio->async_io_active = 0; /* The event will not be signalled */
  939. ResetEvent(aio->ov.hEvent);
  940. return TRUE;
  941. } else {
  942. DWORD error = GetLastError();
  943. if (error != ERROR_IO_PENDING) {
  944. aio->pendingError = error;
  945. SetEvent(aio->ov.hEvent);
  946. }
  947. DEBUGF(("async_write_file: WriteFile() -> %s\n", win32_errorstr(error)));
  948. }
  949. }
  950. return FALSE;
  951. }
  952. /* ----------------------------------------------------------------------
  953. * get_overlapped_result --
  954. *
  955. * Results:
  956. * Returns the error code for the overlapped result, or NO_ERROR
  957. * if no error.
  958. * ----------------------------------------------------------------------
  959. */
  960. static int
  961. get_overlapped_result(AsyncIo* aio, /* Pointer to async control block. */
  962. LPDWORD pBytesRead, /* Where to place the number of bytes
  963. * transferred.
  964. */
  965. BOOL wait /* If true, wait until result is ready. */
  966. )
  967. {
  968. DWORD error = NO_ERROR; /* Error status from last function. */
  969. if (aio->thread != (HANDLE) -1) {
  970. /*
  971. * Simulate overlapped io with a thread.
  972. */
  973. DEBUGF(("get_overlapped_result: about to wait for event 0x%x\n",
  974. aio->ov.hEvent));
  975. error = WaitForSingleObject(aio->ov.hEvent, wait ? INFINITE : 0);
  976. switch (error) {
  977. case WAIT_OBJECT_0:
  978. error = aio->pendingError;
  979. aio->pendingError = NO_ERROR;
  980. *pBytesRead = aio->bytesTransferred;
  981. ResetEvent(aio->ov.hEvent);
  982. DEBUGF(("get_overlapped_result -> %s\n",
  983. win32_errorstr(error)));
  984. return error;
  985. case WAIT_TIMEOUT:
  986. DEBUGF(("get_overlapped_result -> %s\n",
  987. ERROR_IO_INCOMPLETE));
  988. return ERROR_IO_INCOMPLETE;
  989. case WAIT_FAILED: /* XXX: Shouldn't happen? */
  990. error = GetLastError();
  991. DEBUGF(("get_overlapped_result (WAIT_FAILED) -> %s\n",
  992. win32_errorstr(error)));
  993. return error;
  994. }
  995. } else if (aio->pendingError != NO_ERROR) { /* Pending error. */
  996. error = aio->pendingError;
  997. aio->pendingError = NO_ERROR;
  998. ResetEvent(aio->ov.hEvent);
  999. DEBUGF(("get_overlapped_result: pending error: %s\n",
  1000. win32_errorstr(error)));
  1001. return error;
  1002. } else if (aio->flags & DF_OVR_READY) { /* Operation succeded. */
  1003. aio->flags &= ~DF_OVR_READY;
  1004. *pBytesRead = aio->bytesTransferred;
  1005. ResetEvent(aio->ov.hEvent);
  1006. DEBUGF(("get_overlapped_result: delayed success: %d bytes\n",
  1007. aio->bytesTransferred));
  1008. } else if (!GetOverlappedResult(aio->fd, &aio->ov, pBytesRead, wait)) {
  1009. error = GetLastError();
  1010. ResetEvent(aio->ov.hEvent);
  1011. DEBUGF(("get_overlapped_result: error: %s\n", win32_errorstr(error)));
  1012. return error;
  1013. } else { /* Success. */
  1014. DEBUGF(("get_overlapped_result: success\n"));
  1015. ResetEvent(aio->ov.hEvent);
  1016. }
  1017. return NO_ERROR;
  1018. }
  1019. static int
  1020. fd_init(void)
  1021. {
  1022. char kernel_dll_name[] = "kernel32";
  1023. HMODULE module;
  1024. module = GetModuleHandle(kernel_dll_name);
  1025. fpSetHandleInformation = (module != NULL) ?
  1026. (BOOL (WINAPI *)(HANDLE,DWORD,DWORD))
  1027. GetProcAddress(module,"SetHandleInformation") :
  1028. NULL;
  1029. return 0;
  1030. }
  1031. static int
  1032. spawn_init(void)
  1033. {
  1034. int i;
  1035. #if defined(USE_CANCELIOEX)
  1036. HMODULE module = GetModuleHandle("kernel32");
  1037. fpCancelIoEx = (BOOL (WINAPI *)(HANDLE,LPOVERLAPPED))
  1038. ((module != NULL) ? GetProcAddress(module,"CancelIoEx") : NULL);
  1039. DEBUGF(("fpCancelIoEx = %p\r\n", fpCancelIoEx));
  1040. #endif
  1041. return 0;
  1042. }
  1043. static ErlDrvData
  1044. spawn_start(ErlDrvPort port_num, char* utf8_name, SysDriverOpts* opts)
  1045. {
  1046. HANDLE hToChild = INVALID_HANDLE_VALUE; /* Write handle to child. */
  1047. HANDLE hFromChild = INVALID_HANDLE_VALUE; /* Read handle from child. */
  1048. HANDLE hChildStdin = INVALID_HANDLE_VALUE; /* Child's stdin. */
  1049. HANDLE hChildStdout = INVALID_HANDLE_VALUE; /* Child's stout. */
  1050. HANDLE hChildStderr = INVALID_HANDLE_VALUE; /* Child's sterr. */
  1051. DWORD pid;
  1052. int close_child_stderr = 0;
  1053. DriverData* dp; /* Pointer to driver data. */
  1054. ErlDrvData retval = ERL_DRV_ERROR_GENERAL; /* Return value. */
  1055. int ok;
  1056. int neededSelects = 0;
  1057. SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
  1058. int errno_return = -1;
  1059. wchar_t *name;
  1060. int len;
  1061. if (opts->read_write & DO_READ)
  1062. neededSelects++;
  1063. if (opts->read_write & DO_WRITE)
  1064. neededSelects++;
  1065. if ((dp = new_driver_data(port_num, opts->packet_bytes, neededSelects,
  1066. !use_named_pipes)) == NULL)
  1067. return ERL_DRV_ERROR_GENERAL;
  1068. /*
  1069. * Create two pipes to communicate with the port program.
  1070. */
  1071. if (opts->read_write & DO_READ) {
  1072. if (!create_pipe(&hFromChild, &hChildStdout, FALSE,
  1073. opts->overlapped_io))
  1074. goto error;
  1075. } else {
  1076. hChildStdout = CreateFile("nul", GENERIC_WRITE, 0,
  1077. &sa, OPEN_EXISTING,
  1078. FILE_ATTRIBUTE_NORMAL, NULL);
  1079. DEBUGF(("Created nul file for hChildStdout = %d\n",hChildStdout));
  1080. }
  1081. if (opts->read_write & DO_WRITE) {
  1082. if (!create_pipe(&hChildStdin, &hToChild, TRUE, opts->overlapped_io)) {
  1083. CloseHandle(hFromChild);
  1084. hFromChild = INVALID_HANDLE_VALUE;
  1085. CloseHandle(hChildStdout);
  1086. goto error;
  1087. }
  1088. } else {
  1089. hChildStdin = CreateFile("nul", GENERIC_READ, 0,
  1090. &sa, OPEN_EXISTING,
  1091. FILE_ATTRIBUTE_NORMAL, NULL);
  1092. DEBUGF(("Created nul file for hChildStdin = %d\n",hChildStdin));
  1093. }
  1094. /*
  1095. * Make sure that standard error is valid handle, because a Command Prompt
  1096. * window not work properly otherwise. We leave standard error alone if
  1097. * it is okay and no redirection was specified.
  1098. */
  1099. hChildStderr = GetStdHandle(STD_ERROR_HANDLE);
  1100. if (opts->redir_stderr) {
  1101. hChildStderr = hChildStdout;
  1102. } else if (hChildStderr == INVALID_HANDLE_VALUE || hChildStderr == 0) {
  1103. hChildStderr = CreateFile("nul", GENERIC_WRITE, 0, &sa, OPEN_EXISTING,
  1104. FILE_ATTRIBUTE_NORMAL, NULL);
  1105. close_child_stderr = 1;
  1106. }
  1107. if (fpSetHandleInformation != NULL) {
  1108. (*fpSetHandleInformation)(hChildStderr, HANDLE_FLAG_INHERIT, 1);
  1109. }
  1110. /*
  1111. * Spawn the port program.
  1112. */
  1113. if ((len = MultiByteToWideChar(CP_UTF8, 0, utf8_name, -1, NULL, 0)) > 0) {
  1114. name = erts_alloc(ERTS_ALC_T_TMP, len*sizeof(wchar_t));
  1115. MultiByteToWideChar(CP_UTF8, 0, utf8_name, -1, name, len);
  1116. } else { /* Not valid utf-8, just convert byte to wchar */
  1117. int i;
  1118. len = strlen(utf8_name);
  1119. name = erts_alloc(ERTS_ALC_T_TMP, (1+len)*sizeof(wchar_t));
  1120. for(i=0; i<len; i++) {
  1121. name[i] = (wchar_t) utf8_name[i];
  1122. }
  1123. name[i] = L'\0';
  1124. }
  1125. DEBUGF(("Spawning \"%S\"\n", name));
  1126. {
  1127. void *environment_block = build_env_block(&opts->envir);
  1128. ok = create_child_process(name,
  1129. hChildStdin,
  1130. hChildStdout,
  1131. hChildStderr,
  1132. &dp->port_pid,
  1133. &pid,
  1134. opts->hide_window,
  1135. environment_block,
  1136. (wchar_t *) opts->wd,
  1137. opts->spawn_type,
  1138. (wchar_t **) opts->argv,
  1139. &errno_return);
  1140. CloseHandle(hChildStdin);
  1141. CloseHandle(hChildStdout);
  1142. if (close_child_stderr && hChildStderr != INVALID_HANDLE_VALUE &&
  1143. hChildStderr != 0) {
  1144. CloseHandle(hChildStderr);
  1145. }
  1146. erts_free(ERTS_ALC_T_TMP, environment_block);
  1147. erts_free(ERTS_ALC_T_TMP, name);
  1148. }
  1149. if (!ok) {
  1150. dp->port_pid = INVALID_HANDLE_VALUE;
  1151. if (errno_return >= 0) {
  1152. retval = ERL_DRV_ERROR_ERRNO;
  1153. }
  1154. } else {
  1155. if (!use_named_pipes) {
  1156. if ((opts->read_write & DO_READ) &&
  1157. !create_file_thread(&dp->in, DO_READ))
  1158. goto error;
  1159. if ((opts->read_write & DO_WRITE) &&
  1160. !create_file_thread(&dp->out, DO_WRITE)) {
  1161. dp->in.flags = DF_EXIT_THREAD;
  1162. SetEvent(dp->in.ioAllowed);
  1163. WaitForSingleObject(dp->in.thread, INFINITE);
  1164. dp->in.thread = (HANDLE) -1;
  1165. goto error;
  1166. }
  1167. }
  1168. #ifdef HARD_POLL_DEBUG
  1169. if (strncmp(name,"inet_gethost",12) == 0) {
  1170. erts_printf("Debugging \"%s\"\n", name);
  1171. poll_debug_set_active_fd(dp->in.ov.hEvent);
  1172. }
  1173. #endif
  1174. retval = set_driver_data(dp, hFromChild, hToChild, opts->read_write,
  1175. opts->exit_status);
  1176. if (retval != ERL_DRV_ERROR_GENERAL && retval != ERL_DRV_ERROR_ERRNO) {
  1177. /* We assume that this cannot generate a negative number */
  1178. erl_drv_set_os_pid(port_num, pid);
  1179. }
  1180. }
  1181. if (retval != ERL_DRV_ERROR_GENERAL && retval != ERL_DRV_ERROR_ERRNO)
  1182. return retval;
  1183. error:
  1184. if (hFromChild != INVALID_HANDLE_VALUE)
  1185. CloseHandle(hFromChild);
  1186. if (hToChild != INVALID_HANDLE_VALUE)
  1187. CloseHandle(hToChild);
  1188. release_driver_data(dp);
  1189. if (retval == ERL_DRV_ERROR_ERRNO) {
  1190. errno = errno_return;
  1191. }
  1192. return retval;
  1193. }
  1194. struct __build_env_state {
  1195. WCHAR *next_variable;
  1196. };
  1197. static void build_env_foreach(void *_state, const erts_osenv_data_t *key,
  1198. const erts_osenv_data_t *value)
  1199. {
  1200. struct __build_env_state *state = (struct __build_env_state*)(_state);
  1201. sys_memcpy(state->next_variable, key->data, key->length);
  1202. state->next_variable += (int)key->length / sizeof(WCHAR);
  1203. *state->next_variable++ = L'=';
  1204. sys_memcpy(state->next_variable, value->data, value->length);
  1205. state->next_variable += (int)value->length / sizeof(WCHAR);
  1206. *state->next_variable++ = L'\0';
  1207. }
  1208. /* Builds an environment block suitable for CreateProcessW. */
  1209. static void *build_env_block(const erts_osenv_t *env) {
  1210. struct __build_env_state build_state;
  1211. WCHAR *env_block;
  1212. env_block = erts_alloc(ERTS_ALC_T_TMP, env->content_size +
  1213. (env->variable_count * sizeof(L"=\0") + sizeof(L'\0')));
  1214. build_state.next_variable = env_block;
  1215. erts_osenv_foreach_native(env, &build_state, build_env_foreach);
  1216. (*build_state.next_variable) = L'\0';
  1217. return env_block;
  1218. }
  1219. static int
  1220. create_file_thread(AsyncIo* aio, int mode)
  1221. {
  1222. DWORD tid; /* Id for thread. */
  1223. refer_driver_data(aio->dp);
  1224. aio->thread = (HANDLE)
  1225. _beginthreadex(NULL, 0,
  1226. (mode & DO_WRITE) ? threaded_writer : threaded_reader,
  1227. aio, 0, &tid);
  1228. if (aio->thread != (HANDLE) -1)
  1229. return 1;
  1230. unrefer_driver_data(aio->dp);
  1231. return 0;
  1232. }
  1233. /*
  1234. * A helper function used by create_child_process().
  1235. * Parses a command line with arguments and returns the length of the
  1236. * first part containing the program name.
  1237. * Example: input = "\"Program Files\"\\erl arg1 arg2"
  1238. * gives 19 as result.
  1239. * The length returned is equivalent with length(argv[0]) if the
  1240. * command line should have been prepared by _setargv for the main function
  1241. */
  1242. int parse_command(wchar_t* cmd){
  1243. #define NORMAL 2
  1244. #define STRING 1
  1245. #define STOP 0
  1246. int i =0;
  1247. int state = NORMAL;
  1248. while (cmd[i]) {
  1249. switch (cmd[i]) {
  1250. case L'"':
  1251. if (state == NORMAL)
  1252. state = STRING;
  1253. else
  1254. state = NORMAL;
  1255. break;
  1256. case L'\\':
  1257. if ((state == STRING) && (cmd[i+1]==L'"'))
  1258. i++;
  1259. break;
  1260. case L' ':
  1261. if (state == NORMAL)
  1262. state = STOP;
  1263. break;
  1264. default:
  1265. break;
  1266. }
  1267. if (state == STOP) {
  1268. return i;
  1269. }
  1270. i++;
  1271. }
  1272. return i;
  1273. }
  1274. /*
  1275. * Translating of command line arguments to correct format. In the examples
  1276. * below the '' are not part of the actual string.
  1277. * 'io:format("hello").' -> 'io:format(\"hello\").'
  1278. * 'io:format("is anybody in there?").' -> '"io:format(\"is anybody in there?\")."'
  1279. * 'Just nod if you can hear me.' -> '"Just nod if you can hear me."'
  1280. * 'Is there ""anyone at home?' -> '"Is there \"\"anyone at home?"'
  1281. * 'Relax."' -> 'Relax.\"'
  1282. *
  1283. * If new == NULL we just calculate the length.
  1284. *
  1285. * The reason for having to quote all of the is because CreateProcessW removes
  1286. * one level of escaping since it takes a single long command line rather
  1287. * than the argument chunks that unix uses.
  1288. */
  1289. static int escape_and_quote(wchar_t *str, wchar_t *new, BOOL *quoted) {
  1290. int i, j = 0;
  1291. if (new == NULL)
  1292. *quoted = FALSE;
  1293. else if (*quoted)
  1294. new[j++] = L'"';
  1295. for ( i = 0; str[i] != L'\0'; i++,j++) {
  1296. if (str[i] == L' ' && new == NULL && *quoted == FALSE) {
  1297. *quoted = TRUE;
  1298. j++;
  1299. }
  1300. /* check if we have to escape quotes */
  1301. if (str[i] == L'"') {
  1302. if (new) new[j] = L'\\';
  1303. j++;
  1304. }
  1305. if (new) new[j] = str[i];
  1306. }
  1307. if (*quoted) {
  1308. if (new) new[j] = L'"';
  1309. j++;
  1310. }
  1311. return j;
  1312. }
  1313. /*
  1314. *----------------------------------------------------------------------
  1315. *
  1316. * create_child_process --
  1317. *
  1318. * Create a child process that has pipes as its
  1319. * standard input, output, and error. The child process runs
  1320. * synchronously under Win32s and asynchronously under Windows NT
  1321. * and Windows 95, and runs with the same environment variables
  1322. * as the creating process.
  1323. *
  1324. * The complete Windows search path is searched to find the specified
  1325. * executable. If an executable by the given name is not found,
  1326. * automatically tries appending ".com", ".exe", and ".bat" to the
  1327. * executable name.
  1328. *
  1329. * Results:
  1330. * The return value is FALSE if there was a problem creating the child process.
  1331. * Otherwise, the return value is 0 and *phPid is
  1332. * filled with the process id of the child process.
  1333. *
  1334. * Side effects:
  1335. * A process is created.
  1336. *
  1337. *----------------------------------------------------------------------
  1338. */
  1339. static BOOL
  1340. create_child_process
  1341. (
  1342. wchar_t *origcmd, /* Command line for child process (including
  1343. * name of executable). Or whole executable if st is
  1344. * ERTS_SPAWN_EXECUTABLE
  1345. */
  1346. HANDLE hStdin, /* The standard input handle for child. */
  1347. HANDLE hStdout, /* The standard output handle for child. */
  1348. HANDLE hStderr, /* The standard error handle for child. */
  1349. LPHANDLE phPid, /* Pointer to variable to received Process handle. */
  1350. LPDWORD pdwID, /* Pointer to variable to received Process ID */
  1351. BOOL hide, /* Hide the window unconditionally. */
  1352. LPVOID env, /* Environment for the child */
  1353. wchar_t *wd, /* Working dir for the child */
  1354. unsigned st, /* Flags for spawn, tells us how to interpret origcmd */
  1355. wchar_t **argv, /* Argument vector if given. */
  1356. int *errno_return /* Place to put an errno in in case of failure */
  1357. )
  1358. {
  1359. PROCESS_INFORMATION piProcInfo = {0};
  1360. BOOL ok = FALSE;
  1361. int applType;
  1362. /* Not to be changed for different types of executables */
  1363. int staticCreateFlags = GetPriorityClass(GetCurrentProcess());
  1364. int createFlags = DETACHED_PROCESS;
  1365. wchar_t *newcmdline = NULL;
  1366. int cmdlength;
  1367. wchar_t* thecommand;
  1368. wchar_t* appname = NULL;
  1369. HANDLE hProcess = GetCurrentProcess();
  1370. STARTUPINFOW siStartInfo = {0};
  1371. wchar_t execPath[MAX_PATH];
  1372. *errno_return = -1;
  1373. siStartInfo.cb = sizeof(STARTUPINFOW);
  1374. siStartInfo.dwFlags = STARTF_USESTDHANDLES;
  1375. siStartInfo.hStdInput = hStdin;
  1376. siStartInfo.hStdOutput = hStdout;
  1377. siStartInfo.hStdError = hStderr;
  1378. if (st != ERTS_SPAWN_EXECUTABLE) {
  1379. /*
  1380. * Parse out the program name from the command line (it can be quoted and
  1381. * contain spaces).
  1382. */
  1383. cmdlength = parse_command(origcmd);
  1384. newcmdline = (wchar_t *) erts_alloc(ERTS_ALC_T_TMP, (MAX_PATH+wcslen(origcmd)-cmdlength)*sizeof(wchar_t));
  1385. thecommand = (wchar_t *) erts_alloc(ERTS_ALC_T_TMP, (cmdlength+1)*sizeof(wchar_t));
  1386. wcsncpy(thecommand, origcmd, cmdlength);
  1387. thecommand[cmdlength] = L'\0';
  1388. DEBUGF(("spawn command: %S\n", thecommand));
  1389. applType = application_type(thecommand, execPath, TRUE, TRUE, errno_return);
  1390. DEBUGF(("application_type returned for (%S) is %d\n", thecommand, applType));
  1391. erts_free(ERTS_ALC_T_TMP, (void *) thecommand);
  1392. if (applType == APPL_NONE) {
  1393. erts_free(ERTS_ALC_T_TMP,newcmdline);
  1394. return FALSE;
  1395. }
  1396. newcmdline[0] = L'\0';
  1397. if (applType == APPL_DOS) {
  1398. /*
  1399. * Under NT, 16-bit DOS applications will not run unless they
  1400. * can be attached to a console. Run the 16-bit program as
  1401. * a normal process inside of a hidden console application,
  1402. * and then run that hidden console as a detached process.
  1403. */
  1404. siStartInfo.wShowWindow = SW_HIDE;
  1405. siStartInfo.dwFlags |= STARTF_USESHOWWINDOW;
  1406. createFlags = CREATE_NEW_CONSOLE;
  1407. wcscat(newcmdline, L"cmd.exe /c ");
  1408. } else if (hide) {
  1409. DEBUGF(("hiding window\n"));
  1410. siStartInfo.wShowWindow = SW_HIDE;
  1411. siStartInfo.dwFlags |= STARTF_USESHOWWINDOW;
  1412. createFlags = 0;
  1413. }
  1414. wcscat(newcmdline, execPath);
  1415. wcscat(newcmdline, origcmd+cmdlength);
  1416. DEBUGF(("Creating child process: %S, createFlags = %d\n", newcmdline, createFlags));
  1417. ok = CreateProcessW(appname,
  1418. newcmdline,
  1419. NULL,
  1420. NULL,
  1421. TRUE,
  1422. createFlags | staticCreateFlags |
  1423. CREATE_UNICODE_ENVIRONMENT,
  1424. env,
  1425. wd,
  1426. &siStartInfo,
  1427. &piProcInfo);
  1428. } else { /* ERTS_SPAWN_EXECUTABLE, filename and args are in unicode ({utf16,little}) */
  1429. int run_cmd = 0;
  1430. applType = application_type(origcmd, execPath, FALSE, FALSE, errno_return);
  1431. if (applType == APPL_NONE) {
  1432. return FALSE;
  1433. }
  1434. if (applType == APPL_DOS) {
  1435. /*
  1436. * See comment above
  1437. */
  1438. siStartInfo.wShowWindow = SW_HIDE;
  1439. siStartInfo.dwFlags |= STARTF_USESHOWWINDOW;
  1440. createFlags = CREATE_NEW_CONSOLE;
  1441. run_cmd = 1;
  1442. } else if (hide) {
  1443. DEBUGF(("hiding window\n"));
  1444. siStartInfo.wShowWindow = SW_HIDE;
  1445. siStartInfo.dwFlags |= STARTF_USESHOWWINDOW;
  1446. createFlags = 0;
  1447. }
  1448. if (run_cmd) {
  1449. wchar_t cmdPath[MAX_PATH];
  1450. int cmdType;
  1451. cmdType = application_type(L"cmd.exe", cmdPath, TRUE, FALSE, errno_return);
  1452. if (cmdType == APPL_NONE || cmdType == APPL_DOS) {
  1453. return FALSE;
  1454. }
  1455. appname = (wchar_t *) erts_alloc(ERTS_ALC_T_TMP, (wcslen(cmdPath)+1)*sizeof(wchar_t));
  1456. wcscpy(appname,cmdPath);
  1457. } else {
  1458. appname = (wchar_t *) erts_alloc(ERTS_ALC_T_TMP, (wcslen(execPath)+1)*sizeof(wchar_t));
  1459. wcscpy(appname, execPath);
  1460. }
  1461. if (argv == NULL) {
  1462. BOOL orig_need_q;
  1463. wchar_t *ptr;
  1464. int ocl = escape_and_quote(execPath, NULL, &orig_need_q);
  1465. if (run_cmd) {
  1466. newcmdline = (wchar_t *) erts_alloc(ERTS_ALC_T_TMP,
  1467. (ocl + 1 + 11)*sizeof(wchar_t));
  1468. memcpy(newcmdline,L"cmd.exe /c ",11*sizeof(wchar_t));
  1469. ptr = newcmdline + 11;
  1470. } else {
  1471. newcmdline = (wchar_t *) erts_alloc(ERTS_ALC_T_TMP,
  1472. (ocl + 1)*sizeof(wchar_t));
  1473. ptr = (wchar_t *) newcmdline;
  1474. }
  1475. ptr += escape_and_quote(execPath, ptr, &orig_need_q);
  1476. ptr[0] = L'\0';
  1477. } else {
  1478. int sum = 0;
  1479. BOOL *qte = NULL;
  1480. wchar_t **ar = argv;
  1481. wchar_t *n;
  1482. wchar_t *save_arg0 = NULL;
  1483. if (argv[0] == (wchar_t *) erts_default_arg0 || run_cmd) {
  1484. save_arg0 = argv[0];
  1485. argv[0] = execPath;
  1486. }
  1487. if (run_cmd) {
  1488. sum += 11; /* cmd.exe /c */
  1489. }
  1490. while (*ar != NULL) ar++;
  1491. qte = erts_alloc(ERTS_ALC_T_TMP, (ar - argv)*sizeof(BOOL));
  1492. ar = argv;
  1493. while (*ar != NULL) {
  1494. sum += escape_and_quote(*ar,NULL,qte+(ar - argv));
  1495. sum++; /* space */
  1496. ++ar;
  1497. }
  1498. ar = argv;
  1499. newcmdline = (wchar_t *) erts_alloc(ERTS_ALC_T_TMP, sum*sizeof(wchar_t));
  1500. n = newcmdline;
  1501. if (run_cmd) {
  1502. memcpy(n,L"cmd.exe /c ",11*sizeof(wchar_t));
  1503. n += 11;
  1504. }
  1505. while (*ar != NULL) {
  1506. n += escape_and_quote(*ar,n,qte+(ar - argv));
  1507. *n++ = L' ';
  1508. ++ar;
  1509. }
  1510. *(n-1) = L'\0'; /* overwrite last space with '\0' */
  1511. if (save_arg0 != NULL) {
  1512. argv[0] = save_arg0;
  1513. }
  1514. erts_free(ERTS_ALC_T_TMP, qte);
  1515. }
  1516. DEBUGF((stderr,"Creating child process: %S, createFlags = %d\n", newcmdline, createFlags));
  1517. ok = CreateProcessW((wchar_t *) appname,
  1518. (wchar_t *) newcmdline,
  1519. NULL,
  1520. NULL,
  1521. TRUE,
  1522. createFlags | staticCreateFlags |
  1523. CREATE_UNICODE_ENVIRONMENT,
  1524. env,
  1525. wd,
  1526. &siStartInfo,
  1527. &piProcInfo);
  1528. } /* end SPAWN_EXECUTABLE */
  1529. if (newcmdline != NULL) {
  1530. erts_free(ERTS_ALC_T_TMP,newcmdline);
  1531. }
  1532. if (appname != NULL) {
  1533. erts_free(ERTS_ALC_T_TMP,appname);
  1534. }
  1535. if (!ok) {
  1536. DEBUGF(("CreateProcess failed: %s\n", last_error()));
  1537. if (*errno_return < 0) {
  1538. *errno_return = EACCES;
  1539. }
  1540. return FALSE;
  1541. }
  1542. CloseHandle(piProcInfo.hThread); /* Necessary to avoid resource leak. */
  1543. *phPid = piProcInfo.hProcess;
  1544. *pdwID = piProcInfo.dwProcessId;
  1545. if (applType == APPL_DOS) {
  1546. WaitForSingleObject(hProcess, 50);
  1547. }
  1548. return ok;
  1549. }
  1550. /*
  1551. * Note, inheritRead == FALSE means "inhetitWrite", i e one of the
  1552. * pipe ends is always expected to be inherited. The pipe end that should
  1553. * be inherited is opened without overlapped io flags, as the child program
  1554. * would expect stdout not to demand overlapped I/O.
  1555. */
  1556. static int create_pipe(HANDLE *phRead, HANDLE *phWrite, BOOL inheritRead, BOOL overlapped_io)
  1557. {
  1558. SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
  1559. char pipe_name[256]; /* Name of pipe. */
  1560. Uint calls;
  1561. /*
  1562. * If we should't use named pipes, create anonmous pipes.
  1563. */
  1564. if (!use_named_pipes) {
  1565. int success;
  1566. HANDLE non_inherited; /* Non-inherited copy of handle. */
  1567. if (!CreatePipe(phRead, phWrite, &sa, 0)) {
  1568. DEBUGF(("Error creating anonyomous pipe: %s\n", last_error()));
  1569. return FALSE;
  1570. }
  1571. if (inheritRead) {
  1572. success = DuplicateHandle(GetCurrentProcess(), *phWrite,
  1573. GetCurrentProcess(), &non_inherited, 0,
  1574. FALSE, DUPLICATE_SAME_ACCESS);
  1575. CloseHandle(*phWrite);
  1576. *phWrite = non_inherited;
  1577. } else {
  1578. success = DuplicateHandle(GetCurrentProcess(), *phRead,
  1579. GetCurrentProcess(), &non_inherited, 0,
  1580. FALSE, DUPLICATE_SAME_ACCESS);
  1581. CloseHandle(*phRead);
  1582. *phRead = non_inherited;
  1583. }
  1584. return success;
  1585. }
  1586. /*
  1587. * Otherwise, create named pipes.
  1588. */
  1589. calls = (UWord) erts_atomic_inc_read_nob(&pipe_creation_counter);
  1590. erts_snprintf(pipe_name, sizeof(pipe_name),
  1591. "\\\\.\\pipe\\erlang44_%d_%bpu", getpid(), calls);
  1592. DEBUGF(("Creating pipe %s\n", pipe_name));
  1593. sa.bInheritHandle = inheritRead;
  1594. if ((*phRead = CreateNamedPipe(pipe_name,
  1595. PIPE_ACCESS_INBOUND |
  1596. ((inheritRead && !overlapped_io) ? 0 : FILE_FLAG_OVERLAPPED),
  1597. PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
  1598. 1,
  1599. 0,
  1600. 0,
  1601. 2000,
  1602. &sa)) == NULL) {
  1603. DEBUGF(("Error creating pipe: %s\n", last_error()));
  1604. return FALSE;
  1605. }
  1606. sa.bInheritHandle = !inheritRead;
  1607. if ((*phWrite = CreateFile(pipe_name,
  1608. GENERIC_WRITE,
  1609. 0, /* No sharing */
  1610. &sa,
  1611. OPEN_EXISTING,
  1612. FILE_ATTRIBUTE_NORMAL |
  1613. ((inheritRead || overlapped_io) ? FILE_FLAG_OVERLAPPED : 0),
  1614. NULL)) == INVALID_HANDLE_VALUE) {
  1615. CloseHandle(*phRead);
  1616. DEBUGF(("Error opening other end of pipe: %s\n", last_error()));
  1617. return FALSE;
  1618. }
  1619. return TRUE;
  1620. }
  1621. static int application_type (const wchar_t *originalName, /* Name of the application to find. */
  1622. wchar_t wfullpath[MAX_PATH],/* Filled with complete path to
  1623. * application. */
  1624. BOOL search_in_path, /* If we should search the system wide path */
  1625. BOOL handle_quotes, /* If we should handle quotes around executable */
  1626. int *error_return) /* A place to put an error code */
  1627. {
  1628. int applType, i;
  1629. HANDLE hFile;
  1630. wchar_t *ext, *rest;
  1631. char buf[2];
  1632. DWORD read;
  1633. IMAGE_DOS_HEADER header;
  1634. static wchar_t extensions[][5] = {L"", L".com", L".exe", L".bat"};
  1635. int is_quoted;
  1636. int len;
  1637. wchar_t xfullpath[MAX_PATH];
  1638. len = wcslen(originalName);
  1639. is_quoted = handle_quotes && len > 0 && originalName[0] == L'"' &&
  1640. originalName[len-1] == L'"';
  1641. applType = APPL_NONE;
  1642. *error_return = ENOENT;
  1643. for (i = 0; i < (int) (sizeof(extensions) / sizeof(extensions[0])); i++) {
  1644. if(is_quoted) {
  1645. lstrcpynW(xfullpath, originalName+1, MAX_PATH - 7); /* Cannot start using StringCchCopy yet, we support
  1646. older platforms */
  1647. len = wcslen(xfullpath);
  1648. if(len > 0) {
  1649. xfullpath[len-1] = L'\0';
  1650. }
  1651. } else {
  1652. lstrcpynW(xfullpath, originalName, MAX_PATH - 5);
  1653. }
  1654. wcscat(xfullpath, extensions[i]);
  1655. /* It seems that the Unicode version does not allow in and out parameter to overlap. */
  1656. SearchPathW((search_in_path) ? NULL : L".", xfullpath, NULL, MAX_PATH, wfullpath, &rest);
  1657. /*
  1658. * Ignore matches on directories or data files, return if identified
  1659. * a known type.
  1660. */
  1661. if (GetFileAttributesW(wfullpath) & FILE_ATTRIBUTE_DIRECTORY) {
  1662. continue;
  1663. }
  1664. ext = wcsrchr(wfullpath, L'.');
  1665. if ((ext != NULL) && (_wcsicmp(ext, L".bat") == 0)) {
  1666. *error_return = EACCES;
  1667. applType = APPL_DOS;
  1668. break;
  1669. }
  1670. hFile = CreateFileW(wfullpath, GENERIC_READ, FILE_SHARE_READ, NULL,
  1671. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1672. if (hFile == INVALID_HANDLE_VALUE) {
  1673. continue;
  1674. }
  1675. *error_return = EACCES; /* If considered an error,
  1676. it's an access error */
  1677. header.e_magic = 0;
  1678. ReadFile(hFile, (void *) &header, sizeof(header), &read, NULL);
  1679. if (header.e_magic != IMAGE_DOS_SIGNATURE) {
  1680. /*
  1681. * Doesn't have the magic number for relocatable executables. If
  1682. * filename ends with .com, assume it's a DOS application anyhow.
  1683. * Note that we didn't make this assumption at first, because some
  1684. * supposed .com files are really 32-bit executables with all the
  1685. * magic numbers and everything.
  1686. */
  1687. CloseHandle(hFile);
  1688. if ((ext != NULL) && (_wcsicmp(ext, L".com") == 0)) {
  1689. applType = APPL_DOS;
  1690. break;
  1691. }
  1692. continue;
  1693. }
  1694. if (header.e_lfarlc != sizeof(header)) {
  1695. /*
  1696. * All Windows 3.X and Win32 and some DOS programs have this value
  1697. * set here. If it doesn't, assume that since it already had the
  1698. * other magic number it was a DOS application.
  1699. */
  1700. CloseHandle(hFile);
  1701. applType = APPL_DOS;
  1702. break;
  1703. }
  1704. /*
  1705. * The DWORD at header.e_lfanew points to yet another magic number.
  1706. */
  1707. buf[0] = '\0';
  1708. SetFilePointer(hFile, header.e_lfanew, NULL, FILE_BEGIN);
  1709. ReadFile(hFile, (void *) buf, 2, &read, NULL);
  1710. CloseHandle(hFile);
  1711. if ((buf[0] == 'L') && (buf[1] == 'E')) {
  1712. applType = APPL_DOS;
  1713. } else if ((buf[0] == 'N') && (buf[1] == 'E')) {
  1714. applType = APPL_WIN3X;
  1715. } else if ((buf[0] == 'P') && (buf[1] == 'E')) {
  1716. applType = APPL_WIN32;
  1717. } else {
  1718. continue;
  1719. }
  1720. break;
  1721. }
  1722. if (applType == APPL_NONE) {
  1723. return APPL_NONE;
  1724. }
  1725. if ((applType == APPL_DOS) || (applType == APPL_WIN3X)) {
  1726. /*
  1727. * Replace long path name of executable with short path name for
  1728. * 16-bit applications. Otherwise the application may not be able
  1729. * to correctly parse its own command line to separate off the
  1730. * application name from the arguments.
  1731. */
  1732. GetShortPathNameW(wfullpath, wfullpath, MAX_PATH);
  1733. }
  1734. if (is_quoted) {
  1735. /* restore quotes on quoted program name */
  1736. len = wcslen(wfullpath);
  1737. memmove(wfullpath+1,wfullpath,len*sizeof(wchar_t));
  1738. wfullpath[0]=L'"';
  1739. wfullpath[len+1]=L'"';
  1740. wfullpath[len+2]=L'\0';
  1741. }
  1742. return applType;
  1743. }
  1744. /*
  1745. * Thread function used to emulate overlapped reading.
  1746. */
  1747. DWORD WINAPI
  1748. threaded_reader(LPVOID param)
  1749. {
  1750. AsyncIo* aio = (AsyncIo *) param;
  1751. HANDLE thread = GetCurrentThread();
  1752. char* buf;
  1753. DWORD numToRead;
  1754. for (;;) {
  1755. WaitForSingleObject(aio->ioAllowed, INFINITE);
  1756. if (aio->flags & DF_EXIT_THREAD)
  1757. break;
  1758. buf = OV_BUFFER_PTR(aio);
  1759. numToRead = OV_NUM_TO_READ(aio);
  1760. aio->pendingError = 0;
  1761. if (!ReadFile(aio->fd, buf, numToRead, &aio->bytesTransferred, NULL)) {
  1762. int error = GetLastError();
  1763. aio->pendingError = error;
  1764. } else if (aio->flags & DF_XLAT_CR) {
  1765. char *s;
  1766. int n;
  1767. n = aio->bytesTransferred;
  1768. for (s = buf; s < buf+n; s++) {
  1769. if (*s == '\r') {
  1770. if (s < buf + n - 1 && s[1] == '\n') {
  1771. memmove(s, s+1, (buf+n - s - 1));
  1772. --n;
  1773. } else {
  1774. *s = '\n';
  1775. }
  1776. }
  1777. }
  1778. aio->bytesTransferred = n;
  1779. }
  1780. SetEvent(aio->ov.hEvent);
  1781. if ((aio->flags & DF_XLAT_CR) == 0 && aio->bytesTransferred == 0) {
  1782. break;
  1783. }
  1784. if (aio->pendingError != NO_ERROR) {
  1785. break;
  1786. }
  1787. if (aio->flags & DF_EXIT_THREAD)
  1788. break;
  1789. }
  1790. unrefer_driver_data(aio->dp);
  1791. return 0;
  1792. }
  1793. /*
  1794. * Thread function used to emulate overlapped writing
  1795. */
  1796. DWORD WINAPI
  1797. threaded_writer(LPVOID param)
  1798. {
  1799. AsyncIo* aio = (AsyncIo *) param;
  1800. HANDLE thread = GetCurrentThread();
  1801. char* buf;
  1802. DWORD numToWrite, handle;
  1803. int ok;
  1804. HANDLE handles[2];
  1805. handles[0] = aio->ioAllowed;
  1806. handles[1] = aio->flushEvent;
  1807. for (;;) {
  1808. handle = WaitForMultipleObjects(2, handles, FALSE, INFINITE);
  1809. if (aio->flags & DF_EXIT_THREAD) {
  1810. break;
  1811. }
  1812. buf = OV_BUFFER_PTR(aio);
  1813. numToWrite = OV_NUM_TO_READ(aio);
  1814. aio->pendingError = 0;
  1815. if (handle == (WAIT_OBJECT_0 + 1) && numToWrite == 0) {
  1816. SetEvent(aio->flushReplyEvent);
  1817. aio->flags |= DF_THREAD_FLUSHED;
  1818. continue;
  1819. }
  1820. ok = WriteFile(aio->fd, buf, numToWrite, &aio->bytesTransferred, NULL);
  1821. if (!ok) {
  1822. aio->pendingError = GetLastError();
  1823. if (aio->pendingError == ERROR_INVALID_HANDLE &&
  1824. aio->flags & DF_DROP_IF_INVH) {
  1825. /* This is standard error and we'we got an
  1826. invalid standard error FD (non-inheritable) from parent.
  1827. Just drop the message and be happy. */
  1828. aio->pendingError = 0;
  1829. aio->bytesTransferred = numToWrite;
  1830. } else if (aio->pendingError == ERROR_NOT_ENOUGH_MEMORY) {
  1831. /* This could be a console, which limits utput to 64kbytes,
  1832. which might translate to less on a unicode system.
  1833. Try 16k chunks and see if it works before giving up. */
  1834. int done = 0;
  1835. DWORD transferred;
  1836. aio->pendingError = 0;
  1837. aio->bytesTransferred = 0;
  1838. ok = 1;
  1839. while (ok && (numToWrite - done) > 0x4000) {
  1840. ok = WriteFile(aio->fd, buf + done, 0x4000, &transferred, NULL);
  1841. aio->bytesTransferred += transferred;
  1842. done += 0x4000;
  1843. }
  1844. if (ok && (numToWrite - done) > 0) {
  1845. ok = WriteFile(aio->fd, buf + done, (numToWrite - done),
  1846. &transferred, NULL);
  1847. aio->bytesTransferred += transferred;
  1848. }
  1849. if (!ok) {
  1850. aio->pendingError = GetLastError();
  1851. }
  1852. }
  1853. }
  1854. OV_NUM_TO_READ(aio) = 0;
  1855. if (handle == (WAIT_OBJECT_0 + 1))
  1856. SetEvent(aio->flushReplyEvent);
  1857. else
  1858. SetEvent(aio->ov.hEvent);
  1859. if (aio->pendingError != NO_ERROR || aio->bytesTransferred == 0)
  1860. break;
  1861. if (aio->flags & DF_EXIT_THREAD)
  1862. break;
  1863. }
  1864. aio->flags |= DF_THREAD_FLUSHED;
  1865. CloseHandle(aio->fd);
  1866. aio->fd = INVALID_HANDLE_VALUE;
  1867. unrefer_driver_data(aio->dp);
  1868. return 0;
  1869. }
  1870. static HANDLE
  1871. translate_fd(int fd)
  1872. {
  1873. DWORD access;
  1874. HANDLE handle;
  1875. switch (fd) {
  1876. case 0:
  1877. access = GENERIC_READ;
  1878. handle = GetStdHandle(STD_INPUT_HANDLE);
  1879. break;
  1880. case 1:
  1881. access = GENERIC_WRITE;
  1882. handle = GetStdHandle(STD_OUTPUT_HANDLE);
  1883. break;
  1884. case 2:
  1885. access = GENERIC_WRITE;
  1886. handle = GetStdHandle(STD_ERROR_HANDLE);
  1887. break;
  1888. default:
  1889. return (HANDLE) fd;
  1890. }
  1891. DEBUGF(("translate_fd(%d) -> std(%d)\n", fd, handle));
  1892. if (handle == INVALID_HANDLE_VALUE || handle == 0) {
  1893. handle = CreateFile("nul", access, 0,
  1894. NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  1895. }
  1896. DEBUGF(("translate_fd(%d) -> %d\n", fd, handle));
  1897. return handle;
  1898. }
  1899. /* Driver level locking, start function is serialized */
  1900. static DriverData *save_01_port = NULL;
  1901. static DriverData *save_22_port = NULL;
  1902. static ErlDrvData
  1903. fd_start(ErlDrvPort port_num, char* name, SysDriverOpts* opts)
  1904. {
  1905. DriverData* dp;
  1906. int is_std_error = (opts->ofd == 2);
  1907. int in = opts->ifd, out = opts->ofd;
  1908. opts->ifd = (Uint) translate_fd(in);
  1909. opts->ofd = (Uint) translate_fd(out);
  1910. if ( in == 0 && out == 1 && save_01_port != NULL) {
  1911. dp = save_01_port;
  1912. return reuse_driver_data(dp, (HANDLE) opts->ifd, (HANDLE) opts->ofd, opts->read_write, port_num);
  1913. } else if (in == 2 && out == 2 && save_22_port != NULL) {
  1914. dp = save_22_port;
  1915. return reuse_driver_data(dp, (HANDLE) opts->ifd, (HANDLE) opts->ofd, opts->read_write, port_num);
  1916. } else {
  1917. if ((dp = new_driver_data(port_num, opts->packet_bytes, 2, TRUE)) == NULL)
  1918. return ERL_DRV_ERROR_GENERAL;
  1919. /**
  1920. * Here is a brief description about how the fd driver works on windows.
  1921. *
  1922. * fd_init:
  1923. * For each in/out fd pair a threaded_reader and threaded_writer thread is
  1924. * created. Within the DriverData struct each of the threads have an AsyncIO
  1925. * sctruct associated with it. Within AsyncIO there are two important HANDLEs,
  1926. * ioAllowed and ov.hEvent. ioAllowed is used to signal the threaded_* threads
  1927. * should read/write some data, and ov.hEvent is driver_select'ed to be used to
  1928. * signal that the thread is done reading/writing.
  1929. *
  1930. * The reason for the driver being threaded like this is because once the FD is open
  1931. * on windows, it is not possible to set the it in overlapped mode. So we have to
  1932. * simulate this using threads.
  1933. *
  1934. * output:
  1935. * When an output occurs the data to be outputted is copied to AsyncIO.ov. Then
  1936. * the ioAllowed HANDLE is set, ov.hEvent is cleared and the port is marked as busy.
  1937. * The threaded_writer thread is lying in WaitForMultipleObjects on ioAllowed, and
  1938. * when signalled it writes all data in AsyncIO.ov and then sets ov.hEvent so that
  1939. * ready_output gets triggered and (potentially) sends the reply to the port and
  1940. * marks the port an non-busy.
  1941. *
  1942. * input:
  1943. * The threaded_reader is lying waiting in ReadFile on the in fd and when a new
  1944. * line is written it sets ov.hEvent that new data is available and then goes
  1945. * and waits for ioAllowed to be set. ready_input is run when ov.hEvent is set and
  1946. * delivers the data to the port. Then ioAllowed is signalled again and threaded_reader
  1947. * goes back to ReadFile.
  1948. *
  1949. * shutdown:
  1950. * In order to guarantee that all io is outputted before the driver is stopped,
  1951. * fd_stop uses flushEvent and flushReplyEvent to make sure that there is no data
  1952. * in ov which needs writing before returning from fd_stop.
  1953. *
  1954. **/
  1955. if (!create_file_thread(&dp->in, DO_READ)) {
  1956. return ERL_DRV_ERROR_GENERAL;
  1957. }
  1958. if (!create_file_thread(&dp->out, DO_WRITE)) {
  1959. return ERL_DRV_ERROR_GENERAL;
  1960. }
  1961. fd_driver_input = &(dp->in);
  1962. dp->in.flags = DF_XLAT_CR;
  1963. if (is_std_error) {
  1964. dp->out.flags |= DF_DROP_IF_INVH; /* Just drop messages if stderror
  1965. is an invalid handle */
  1966. }
  1967. if ( in == 0 && out == 1) {
  1968. save_01_port = dp;
  1969. } else if (in == 2 && out == 2) {
  1970. save_22_port = dp;
  1971. }
  1972. return set_driver_data(dp, (HANDLE) opts->ifd, (HANDLE) opts->ofd, opts->read_write, 0);
  1973. }
  1974. }
  1975. static void fd_stop(ErlDrvData data)
  1976. {
  1977. DriverData * dp = (DriverData *) data;
  1978. /*
  1979. * There's no way we can terminate an fd port in a consistent way.
  1980. * Instead we let it live until it's opened again (which it is,
  1981. * as the only FD-drivers are for 0,1 and 2 adn the only time they
  1982. * get closed is by init:reboot).
  1983. * So - just deselect them and let everything be as is.
  1984. * They get woken up in fd_start again, where the DriverData is
  1985. * remembered. /PaN
  1986. */
  1987. if (dp->in.ov.hEvent != NULL) {
  1988. (void) driver_select(dp->port_num,
  1989. (ErlDrvEvent)dp->in.ov.hEvent,
  1990. ERL_DRV_READ, 0);
  1991. }
  1992. if (dp->out.ov.hEvent != NULL) {
  1993. (void) driver_select(dp->port_num,
  1994. (ErlDrvEvent)dp->out.ov.hEvent,
  1995. ERL_DRV_WRITE, 0);
  1996. do {
  1997. ASSERT(dp->out.flushEvent);
  1998. SetEvent(dp->out.flushEvent);
  1999. } while (WaitForSingleObject(dp->out.flushReplyEvent, 10) == WAIT_TIMEOUT
  2000. && !(dp->out.flags & DF_THREAD_FLUSHED));
  2001. }
  2002. }
  2003. static ErlDrvData
  2004. vanilla_start(ErlDrvPort port_num, char* name, SysDriverOpts* opts)
  2005. {
  2006. HANDLE ofd,ifd;
  2007. DriverData* dp;
  2008. DWORD access; /* Access mode: GENERIC_READ, GENERIC_WRITE. */
  2009. DWORD crFlags;
  2010. HANDLE this_process = GetCurrentProcess();
  2011. access = 0;
  2012. if (opts->read_write == DO_READ)
  2013. access |= GENERIC_READ;
  2014. if (opts->read_write == DO_WRITE)
  2015. access |= GENERIC_WRITE;
  2016. if (opts->read_write == DO_READ)
  2017. crFlags = OPEN_EXISTING;
  2018. else if (opts->read_write == DO_WRITE)
  2019. crFlags = CREATE_ALWAYS;
  2020. else
  2021. crFlags = OPEN_ALWAYS;
  2022. if ((dp = new_driver_data(port_num, opts->packet_bytes, 2, FALSE)) == NULL)
  2023. return ERL_DRV_ERROR_GENERAL;
  2024. ofd = CreateFile(name, access, FILE_SHARE_READ | FILE_SHARE_WRITE,
  2025. NULL, crFlags, FILE_ATTRIBUTE_NORMAL, NULL);
  2026. if (!DuplicateHandle(this_process, (HANDLE) ofd,
  2027. this_process, &ifd, 0,
  2028. FALSE, DUPLICATE_SAME_ACCESS)) {
  2029. CloseHandle(ofd);
  2030. ofd = INVALID_HANDLE_VALUE;
  2031. }
  2032. if (ofd == INVALID_HANDLE_VALUE)
  2033. return ERL_DRV_ERROR_GENERAL;
  2034. return set_driver_data(dp, ifd, ofd, opts->read_write,0);
  2035. }
  2036. static void
  2037. stop(ErlDrvData data)
  2038. {
  2039. DriverData *dp = (DriverData *) data;
  2040. DEBUGF(("stop(%p)\n", dp));
  2041. if (dp->in.ov.hEvent != NULL) {
  2042. (void) driver_select(dp->port_num,
  2043. (ErlDrvEvent)dp->in.ov.hEvent,
  2044. ERL_DRV_READ|ERL_DRV_USE_NO_CALLBACK, 0);
  2045. }
  2046. if (dp->out.ov.hEvent != NULL) {
  2047. (void) driver_select(dp->port_num,
  2048. (ErlDrvEvent)dp->out.ov.hEvent,
  2049. ERL_DRV_WRITE|ERL_DRV_USE_NO_CALLBACK, 0);
  2050. }
  2051. if (dp->out.thread == (HANDLE) -1 && dp->in.thread == (HANDLE) -1) {
  2052. release_driver_data(dp);
  2053. } else {
  2054. /*
  2055. * If there are read or write threads, start a thread which will
  2056. * wait for them to finish.
  2057. */
  2058. HANDLE thread;
  2059. DWORD tid;
  2060. /* threaded_exiter implicitly takes over refc from us... */
  2061. thread = (HANDLE *) _beginthreadex(NULL, 0, threaded_exiter, dp, 0, &tid);
  2062. CloseHandle(thread);
  2063. }
  2064. }
  2065. DWORD WINAPI
  2066. threaded_exiter(LPVOID param)
  2067. {
  2068. DriverData* dp = (DriverData *) param;
  2069. HANDLE handles[2];
  2070. int i;
  2071. /*
  2072. * Ask the threads to terminated.
  2073. *
  2074. * Note that we can't reliable test the state of the ioAllowed event,
  2075. * because it is an auto reset event. Therefore, always set the
  2076. * exit flag and signal the event.
  2077. */
  2078. i = 0;
  2079. if (dp->out.thread != (HANDLE) -1) {
  2080. dp->out.flags |= DF_EXIT_THREAD;
  2081. SetEvent(dp->out.ioAllowed);
  2082. handles[i++] = dp->out.thread;
  2083. }
  2084. if (dp->in.thread != (HANDLE) -1) {
  2085. dp->in.flags |= DF_EXIT_THREAD;
  2086. SetEvent(dp->in.ioAllowed);
  2087. handles[i++] = dp->in.thread;
  2088. }
  2089. /*
  2090. * If we were lucky, the following happened above:
  2091. * 1) The output thread terminated (and closed the pipe).
  2092. * 2) As a consequence of that, the port program received
  2093. * EOF on its standard input.
  2094. * 3) Hopefully, because of (2), the port program terminated.
  2095. * 4) Because of (3), the input thread terminated.
  2096. *
  2097. * But this might need some time; therefore, we must wait for
  2098. * both threads to terminate.
  2099. */
  2100. if (i > 0) {
  2101. switch (WaitForMultipleObjects(i, handles, TRUE, 5000)) {
  2102. case WAIT_TIMEOUT:
  2103. DEBUGF(("Timeout waiting for %d threads failed\n", i));
  2104. break;
  2105. case WAIT_FAILED:
  2106. DEBUGF(("Wait for %d threads failed: %s\n",
  2107. i, win32_errorstr(GetLastError())));
  2108. break;
  2109. default:
  2110. break;
  2111. }
  2112. }
  2113. /*
  2114. * Wait for threads to terminate didn't help. Now use some force.
  2115. * TerminateThread() is *not* a good idea, because it doesn't clean
  2116. * up the thread's stack.
  2117. *
  2118. * Instead we well terminate the port program and wait for the
  2119. * threads to terminate themselves when they receive end of file.
  2120. */
  2121. if (dp->out.thread != (HANDLE) -1) {
  2122. int error;
  2123. if (WaitForSingleObject(dp->out.thread, 0) == WAIT_OBJECT_0) {
  2124. CloseHandle(dp->out.thread);
  2125. dp->out.thread = (HANDLE) -1;
  2126. } else if (dp->port_pid != INVALID_HANDLE_VALUE) {
  2127. DEBUGF(("Killing port process 0x%x (output thread)\n", dp->port_pid));
  2128. TerminateProcess(dp->port_pid, 0);
  2129. if (!CloseHandle(dp->port_pid))
  2130. DEBUGF(("Failed to close output handle!!!\n"));
  2131. dp->port_pid = INVALID_HANDLE_VALUE;
  2132. DEBUGF(("Waiting for output thread 0x%x to finish\n", dp->out.thread));
  2133. error = WaitForSingleObject(dp->out.thread, INFINITE);
  2134. }
  2135. }
  2136. if (dp->in.thread != (HANDLE) -1) {
  2137. if (WaitForSingleObject(dp->in.thread, 0) == WAIT_OBJECT_0) {
  2138. CloseHandle(dp->in.thread);
  2139. dp->in.thread = (HANDLE) -1;
  2140. } else if (dp->port_pid != INVALID_HANDLE_VALUE) {
  2141. DEBUGF(("Killing port process 0x%x (input thread)\n", dp->port_pid));
  2142. TerminateProcess(dp->port_pid, 0);
  2143. if (!CloseHandle(dp->port_pid))
  2144. DEBUGF(("Failed to close input handle!!!\n"));
  2145. dp->port_pid = INVALID_HANDLE_VALUE;
  2146. DEBUGF(("Waiting for input thread 0x%x to finish\n", dp->in.thread));
  2147. switch (WaitForSingleObject(dp->in.thread, INFINITE)) {
  2148. case WAIT_OBJECT_0:
  2149. CloseHandle(dp->in.thread);
  2150. dp->in.thread = (HANDLE) -1;
  2151. break;
  2152. default:
  2153. DEBUGF(("Wait for input thread to finish failed: %s\n",
  2154. win32_errorstr(GetLastError())));
  2155. break;
  2156. }
  2157. }
  2158. }
  2159. release_driver_data(dp);
  2160. return 0;
  2161. }
  2162. /* ----------------------------------------------------------------------
  2163. * output --
  2164. * Outputs data from Erlang to the port program.
  2165. *
  2166. * Results:
  2167. * Returns the actual number of bytes written (including the
  2168. * packet header) or -1 if an error occurred.
  2169. * ----------------------------------------------------------------------
  2170. */
  2171. static void
  2172. output(ErlDrvData drv_data, char* buf, ErlDrvSizeT len)
  2173. /* ErlDrvData drv_data; /* The slot to use in the driver data table.
  2174. * For Windows NT, this is *NOT* a file handle.
  2175. * The handle is found in the driver data.
  2176. */
  2177. /* char *buf; /* Pointer to data to write to the port program. */
  2178. /* ErlDrvSizeT len; /* Number of bytes to write. */
  2179. {
  2180. DriverData* dp = (DriverData *) drv_data;
  2181. int pb; /* The header size for this port. */
  2182. char* current;
  2183. pb = dp->packet_bytes;
  2184. if ((pb+len) == 0)
  2185. return ; /* 0; */
  2186. /*
  2187. * Check that the message can be sent with given header length.
  2188. */
  2189. if ((pb == 2 && len > 65535) || (pb == 1 && len > 255)) {
  2190. driver_failure_posix(dp->port_num, EINVAL);
  2191. return ; /* -1; */
  2192. }
  2193. /*
  2194. * Allocate memory for both the message and the header.
  2195. */
  2196. ASSERT(dp->outbuf == NULL);
  2197. ASSERT(dp->outBufSize == 0);
  2198. ASSERT(!dp->outbuf);
  2199. dp->outbuf = DRV_BUF_ALLOC(pb+len);
  2200. if (!dp->outbuf) {
  2201. driver_failure_posix(dp->port_num, ENOMEM);
  2202. return ; /* -1; */
  2203. }
  2204. dp->outBufSize = pb+len;
  2205. erts_atomic_add_nob(&sys_misc_mem_sz, dp->outBufSize);
  2206. /*
  2207. * Store header bytes (if any).
  2208. */
  2209. current = dp->outbuf;
  2210. switch (pb) {
  2211. case 4:
  2212. *current++ = (len >> 24) & 255;
  2213. *current++ = (len >> 16) & 255;
  2214. case 2:
  2215. *current++ = (len >> 8) & 255;
  2216. case 1:
  2217. *current++ = len & 255;
  2218. }
  2219. /*
  2220. * Start the write.
  2221. */
  2222. if (len)
  2223. memcpy(current, buf, len);
  2224. if (!async_write_file(&dp->out, dp->outbuf, pb+len)) {
  2225. set_busy_port(dp->port_num, 1);
  2226. } else {
  2227. dp->out.ov.Offset += pb+len; /* For vanilla driver. */
  2228. /* XXX OffsetHigh should be changed too. */
  2229. ASSERT(erts_atomic_read_nob(&sys_misc_mem_sz) >= dp->outBufSize);
  2230. erts_atomic_add_nob(&sys_misc_mem_sz, -1*dp->outBufSize);
  2231. DRV_BUF_FREE(dp->outbuf);
  2232. dp->outBufSize = 0;
  2233. dp->outbuf = NULL;
  2234. }
  2235. /*return 0;*/
  2236. }
  2237. /* ----------------------------------------------------------------------
  2238. * ready_input --
  2239. * This function is called (indirectly) from check_io() when an
  2240. * event object has been signaled, indicating that there is
  2241. * something to read on the corresponding file handle.
  2242. *
  2243. * If the port is working in the continuous stream mode (packet_bytes == 0),
  2244. * whatever data read will be sent straight to Erlang.
  2245. *
  2246. * Results:
  2247. * Always 0.
  2248. * ----------------------------------------------------------------------
  2249. */
  2250. static void
  2251. ready_input(ErlDrvData drv_data, ErlDrvEvent ready_event)
  2252. /* long drv_data; /* Driver data. */
  2253. /* HANDLE ready_event; /* The handle for the ready event. */
  2254. {
  2255. int error = 0; /* The error code (assume initially no errors). */
  2256. DWORD bytesRead; /* Number of bytes read. */
  2257. DriverData* dp = (DriverData *) drv_data;
  2258. int pb;
  2259. pb = dp->packet_bytes;
  2260. if(dp->in.thread == (HANDLE) -1) {
  2261. dp->in.async_io_active = 0;
  2262. }
  2263. DEBUGF(("ready_input: dp %p, event 0x%x\n", dp, ready_event));
  2264. /*
  2265. * Evaluate the result of the overlapped read.
  2266. */
  2267. #ifdef HARD_POLL_DEBUG
  2268. poll_debug_read_begin(dp->in.ov.hEvent);
  2269. #endif
  2270. error = get_overlapped_result(&dp->in, &bytesRead, TRUE);
  2271. #ifdef HARD_POLL_DEBUG
  2272. poll_debug_read_done(dp->in.ov.hEvent,bytesRead);
  2273. #endif
  2274. if (error == NO_ERROR) {
  2275. if (pb == 0) { /* Continuous stream. */
  2276. #ifdef DEBUG
  2277. DEBUGF(("ready_input: %d: ", bytesRead));
  2278. erl_bin_write(dp->inbuf, 16, bytesRead);
  2279. DEBUGF(("\n"));
  2280. #endif
  2281. driver_output(dp->port_num, dp->inbuf, bytesRead);
  2282. } else { /* Packet mode */
  2283. dp->bytesInBuffer += bytesRead;
  2284. /*
  2285. * Loop until we've exhausted the data in the buffer.
  2286. */
  2287. for (;;) {
  2288. /*
  2289. * Check for completion of a header read.
  2290. */
  2291. if (dp->bytesInBuffer >= dp->totalNeeded &&
  2292. dp->totalNeeded == pb) {
  2293. /*
  2294. * We have successfully read the packet header
  2295. * (and perhaps even the packet). Get the packet size
  2296. * from the header and update dp->totalNeeded to include
  2297. * the packet size.
  2298. */
  2299. int packet_size = 0;
  2300. unsigned char *header = (unsigned char *) dp->inbuf;
  2301. switch (pb) {
  2302. case 4:
  2303. packet_size = (packet_size << 8) | *header++;
  2304. packet_size = (packet_size << 8) | *header++;
  2305. case 2:
  2306. packet_size = (packet_size << 8) | *header++;
  2307. case 1:
  2308. packet_size = (packet_size << 8) | *header++;
  2309. }
  2310. dp->totalNeeded += packet_size;
  2311. /*
  2312. * Make sure that the receive buffer is big enough.
  2313. */
  2314. if (dp->inBufSize < dp->totalNeeded) {
  2315. char* new_buf;
  2316. new_buf = DRV_BUF_REALLOC(dp->inbuf, dp->totalNeeded);
  2317. if (new_buf == NULL) {
  2318. error = ERROR_NOT_ENOUGH_MEMORY;
  2319. break; /* Break out of loop into error handler. */
  2320. }
  2321. ASSERT(erts_atomic_read_nob(&sys_misc_mem_sz) >= dp->inBufSize);
  2322. erts_atomic_add_nob(&sys_misc_mem_sz,
  2323. dp->totalNeeded - dp->inBufSize);
  2324. dp->inBufSize = dp->totalNeeded;
  2325. dp->inbuf = new_buf;
  2326. }
  2327. }
  2328. /*
  2329. * Check for completion of a packet read.
  2330. */
  2331. if (dp->bytesInBuffer < dp->totalNeeded) {
  2332. /*
  2333. * Not enough bytes in the buffer. Break out of
  2334. * the loop and initiate a new read.
  2335. */
  2336. break;
  2337. } else {
  2338. /*
  2339. * We have successfully read a complete packet, which
  2340. * can be passed to Erlang.
  2341. */
  2342. driver_output(dp->port_num, dp->inbuf+pb, dp->totalNeeded-pb);
  2343. /*
  2344. * Update the number of bytes remaining in the buffer,
  2345. * and move the data remaining (if any) to the beginning
  2346. * of the buffer.
  2347. */
  2348. dp->bytesInBuffer -= dp->totalNeeded;
  2349. if (dp->bytesInBuffer > 0) {
  2350. memmove(dp->inbuf, dp->inbuf+dp->totalNeeded,
  2351. dp->bytesInBuffer);
  2352. }
  2353. /*
  2354. * Indicate that we need the size of a header, and
  2355. * go through the loop once more (to either process
  2356. * remaining bytes or initiate reading more).
  2357. */
  2358. dp->totalNeeded = pb;
  2359. }
  2360. }
  2361. }
  2362. }
  2363. /*
  2364. * Start a new overlapped read, or report the error.
  2365. */
  2366. if (error == NO_ERROR) {
  2367. async_read_file(&dp->in, dp->inbuf+dp->bytesInBuffer,
  2368. dp->inBufSize - dp->bytesInBuffer);
  2369. } else {
  2370. DEBUGF(("ready_input(): error: %s\n", win32_errorstr(error)));
  2371. if (error == ERROR_BROKEN_PIPE || error == ERROR_HANDLE_EOF) {
  2372. /* Maybe check exit status */
  2373. if (dp->report_exit) {
  2374. DWORD exitcode;
  2375. if (GetExitCodeProcess(dp->port_pid, &exitcode) &&
  2376. exitcode != STILL_ACTIVE) {
  2377. driver_report_exit(dp->port_num, exitcode);
  2378. }
  2379. }
  2380. driver_failure_eof(dp->port_num);
  2381. } else { /* Report real errors. */
  2382. int error = GetLastError();
  2383. (void) driver_select(dp->port_num, ready_event, ERL_DRV_READ, 0);
  2384. _dosmaperr(error);
  2385. driver_failure_posix(dp->port_num, errno);
  2386. }
  2387. }
  2388. /*return 0;*/
  2389. }
  2390. static void
  2391. ready_output(ErlDrvData drv_data, ErlDrvEvent ready_event)
  2392. {
  2393. DWORD bytesWritten;
  2394. DriverData *dp = (DriverData *) drv_data;
  2395. int error;
  2396. if(dp->out.thread == (HANDLE) -1) {
  2397. dp->out.async_io_active = 0;
  2398. }
  2399. DEBUGF(("ready_output(%p, 0x%x)\n", drv_data, ready_event));
  2400. set_busy_port(dp->port_num, 0);
  2401. if (!(dp->outbuf)) {
  2402. /* Happens because event sometimes get signalled during a successful
  2403. write... */
  2404. return;
  2405. }
  2406. ASSERT(erts_atomic_read_nob(&sys_misc_mem_sz) >= dp->outBufSize);
  2407. erts_atomic_add_nob(&sys_misc_mem_sz, -1*dp->outBufSize);
  2408. DRV_BUF_FREE(dp->outbuf);
  2409. dp->outBufSize = 0;
  2410. dp->outbuf = NULL;
  2411. #ifdef HARD_POLL_DEBUG
  2412. poll_debug_write_begin(dp->out.ov.hEvent);
  2413. #endif
  2414. error = get_overlapped_result(&dp->out, &bytesWritten, TRUE);
  2415. #ifdef HARD_POLL_DEBUG
  2416. poll_debug_write_done(dp->out.ov.hEvent,bytesWritten);
  2417. #endif
  2418. if (error == NO_ERROR) {
  2419. dp->out.ov.Offset += bytesWritten; /* For vanilla driver. */
  2420. return ; /* 0; */
  2421. }
  2422. (void) driver_select(dp->port_num, ready_event, ERL_DRV_WRITE, 0);
  2423. _dosmaperr(error);
  2424. driver_failure_posix(dp->port_num, errno);
  2425. /* return 0; */
  2426. }
  2427. static void stop_select(ErlDrvEvent e, void* _)
  2428. {
  2429. CloseHandle((HANDLE)e);
  2430. }
  2431. /* Fills in the systems representation of the beam process identifier.
  2432. ** The Pid is put in STRING representation in the supplied buffer,
  2433. ** no interpretation of this should be done by the rest of the
  2434. ** emulator. The buffer should be at least 21 bytes long.
  2435. */
  2436. void sys_get_pid(char *buffer, size_t buffer_size){
  2437. DWORD p = GetCurrentProcessId();
  2438. /* The pid is scalar and is an unsigned long. */
  2439. erts_snprintf(buffer, buffer_size, "%lu",(unsigned long) p);
  2440. }
  2441. void
  2442. sys_init_io(void)
  2443. {
  2444. /* Now heres an icky one... This is called before drivers are, so we
  2445. can change our view of the number of open files possible.
  2446. We estimate the number to twice the amount of ports.
  2447. We really dont know on windows, do we? */
  2448. max_files = 2*erts_ptab_max(&erts_port);
  2449. }
  2450. void
  2451. erts_sys_main_thread(void)
  2452. {
  2453. HANDLE dummy;
  2454. #ifdef ERTS_ENABLE_LOCK_CHECK
  2455. erts_lc_set_thread_name("parent_thread");
  2456. #endif
  2457. dummy = CreateEvent(NULL, FALSE, FALSE, NULL);
  2458. for(;;) {
  2459. WaitForSingleObject(dummy, INFINITE);
  2460. }
  2461. }
  2462. void erts_sys_alloc_init(void)
  2463. {
  2464. }
  2465. void *erts_sys_alloc(ErtsAlcType_t t, void *x, Uint sz)
  2466. {
  2467. return malloc((size_t) sz);
  2468. }
  2469. void *erts_sys_realloc(ErtsAlcType_t t, void *x, void *p, Uint sz)
  2470. {
  2471. return realloc(p, (size_t) sz);
  2472. }
  2473. void erts_sys_free(ErtsAlcType_t t, void *x, void *p)
  2474. {
  2475. free(p);
  2476. }
  2477. void *erts_sys_aligned_alloc(UWord alignment, UWord size)
  2478. {
  2479. void *ptr;
  2480. ASSERT(alignment && (alignment & (alignment-1)) == 0); /* power of 2 */
  2481. ptr = _aligned_malloc((size_t) size, (size_t) alignment);
  2482. ASSERT(!ptr || (((UWord) ptr) & (alignment - 1)) == 0);
  2483. return ptr;
  2484. }
  2485. void erts_sys_aligned_free(UWord alignment, void *ptr)
  2486. {
  2487. ASSERT(alignment && (alignment & (alignment-1)) == 0); /* power of 2 */
  2488. _aligned_free(ptr);
  2489. }
  2490. void *erts_sys_aligned_realloc(UWord alignment, void *ptr, UWord size, UWord old_size)
  2491. {
  2492. void *new_ptr;
  2493. ASSERT(alignment && (alignment & (alignment-1)) == 0); /* power of 2 */
  2494. new_ptr = _aligned_realloc(ptr, (size_t) size, (size_t) alignment);
  2495. ASSERT(!new_ptr || (((UWord) new_ptr) & (alignment - 1)) == 0);
  2496. return new_ptr;
  2497. }
  2498. static Preload* preloaded = NULL;
  2499. static unsigned* res_name = NULL;
  2500. static int num_preloaded = 0;
  2501. /* Return a pointer to a vector of names of preloaded modules */
  2502. Preload* sys_preloaded(void)
  2503. {
  2504. HRSRC hRes;
  2505. unsigned char* data;
  2506. #define GETWORD(p) (0[p] | 1[p] << 8)
  2507. #define GETDWORD(p) (GETWORD(p) | GETWORD(p+2) << 16)
  2508. if (preloaded == NULL) {
  2509. int i;
  2510. ASSERT(beam_module != NULL);
  2511. hRes = FindResource(beam_module, 0, "ERLANG_DICT");
  2512. /* We might have a resource compiler laying out the 0 resource with
  2513. "0" as a textual name instead... */
  2514. if (hRes == NULL) {
  2515. hRes = FindResource(beam_module, "0", "ERLANG_DICT");
  2516. }
  2517. if (hRes == NULL) {
  2518. DWORD n = GetLastError();
  2519. fprintf(stderr, "No ERLANG_DICT resource\n");
  2520. exit(1);
  2521. }
  2522. data = (unsigned char *) LoadResource(beam_module, hRes);
  2523. num_preloaded = GETWORD(data);
  2524. if (num_preloaded == 0) {
  2525. fprintf(stderr, "No preloaded modules\n");
  2526. exit(1);
  2527. }
  2528. data += 2;
  2529. preloaded = erts_alloc(ERTS_ALC_T_PRELOADED,
  2530. (num_preloaded+1)*sizeof(Preload));
  2531. res_name = erts_alloc(ERTS_ALC_T_PRELOADED,
  2532. (num_preloaded+1)*sizeof(unsigned));
  2533. erts_atomic_add_nob(&sys_misc_mem_sz,
  2534. (num_preloaded+1)*sizeof(Preload)
  2535. + (num_preloaded+1)*sizeof(unsigned));
  2536. for (i = 0; i < num_preloaded; i++) {
  2537. int n;
  2538. preloaded[i].size = GETDWORD(data);
  2539. data += 4;
  2540. res_name[i] = GETWORD(data);
  2541. data += 2;
  2542. n = GETWORD(data);
  2543. data += 2;
  2544. preloaded[i].name = erts_alloc(ERTS_ALC_T_PRELOADED, n+1);
  2545. erts_atomic_add_nob(&sys_misc_mem_sz, n+1);
  2546. sys_memcpy(preloaded[i].name, data, n);
  2547. preloaded[i].name[n] = '\0';
  2548. data += n;
  2549. DEBUGF(("name: %s; size: %d; resource: %p\n",
  2550. preloaded[i].name, preloaded[i].size, res_name[i]));
  2551. }
  2552. preloaded[i].name = NULL;
  2553. }
  2554. #undef GETWORD
  2555. #undef GETDWORD
  2556. return preloaded;
  2557. }
  2558. /* Return a pointer to preloaded code for module "module" */
  2559. unsigned char* sys_preload_begin(Preload* pp)
  2560. {
  2561. HRSRC hRes;
  2562. unsigned resource;
  2563. ASSERT(beam_module != NULL);
  2564. resource = res_name[pp-preloaded];
  2565. DEBUGF(("Loading name: %s; size: %d; resource: %p\n",
  2566. pp->name, pp->size, resource));
  2567. hRes = FindResource(beam_module, (char *) resource, "ERLANG_CODE");
  2568. return pp->code = LoadResource(beam_module, hRes);
  2569. }
  2570. /* Clean up if allocated */
  2571. void sys_preload_end(Preload* pp)
  2572. {
  2573. }
  2574. /* Read a key from console */
  2575. int
  2576. sys_get_key(int fd)
  2577. {
  2578. ASSERT(fd == 0);
  2579. if (win_console) {
  2580. return ConGetKey();
  2581. }
  2582. /*
  2583. * Black magic follows. (Code stolen from get_overlapped_result())
  2584. */
  2585. if (fd_driver_input != NULL && fd_driver_input->thread != (HANDLE)-1) {
  2586. DWORD error;
  2587. int key;
  2588. error = WaitForSingleObject(fd_driver_input->ov.hEvent, INFINITE);
  2589. if (error == WAIT_OBJECT_0) {
  2590. if (fd_driver_input->bytesTransferred > 0) {
  2591. int n;
  2592. int i;
  2593. char* buf = OV_BUFFER_PTR(fd_driver_input);
  2594. fd_driver_input->bytesTransferred--;
  2595. n = fd_driver_input->bytesTransferred;
  2596. key = buf[0];
  2597. for (i = n; i > 0; i--) {
  2598. buf[i-1] = buf[i];
  2599. }
  2600. return key;
  2601. }
  2602. }
  2603. }
  2604. return '*'; /* Error! */
  2605. }
  2606. /*
  2607. * Returns a human-readable description of the last error.
  2608. * The returned pointer will be valid only as long as last-error()
  2609. * isn't called again.
  2610. */
  2611. char* win32_errorstr(int error)
  2612. {
  2613. LPTSTR lpBufPtr = erts_tsd_get(win32_errstr_key);
  2614. if (lpBufPtr) {
  2615. LocalFree(lpBufPtr);
  2616. }
  2617. FormatMessage(
  2618. FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
  2619. FORMAT_MESSAGE_IGNORE_INSERTS,
  2620. NULL,
  2621. error,
  2622. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  2623. (LPTSTR) &lpBufPtr,
  2624. 0,
  2625. NULL);
  2626. SetLastError(error);
  2627. erts_tsd_set(win32_errstr_key,lpBufPtr);
  2628. return lpBufPtr;
  2629. }
  2630. char* last_error(void)
  2631. {
  2632. return win32_errorstr(GetLastError());
  2633. }
  2634. static void* sys_func_memzero(void* s, size_t n)
  2635. {
  2636. return sys_memzero(s, n);
  2637. }
  2638. #ifdef DEBUG
  2639. static HANDLE hDebugWrite = INVALID_HANDLE_VALUE;
  2640. void erl_debug(char *fmt,...)
  2641. {
  2642. char sbuf[1024]; /* Temporary buffer. */
  2643. DWORD written; /* Actual number of chars written. */
  2644. va_list va;
  2645. if (hDebugWrite != INVALID_HANDLE_VALUE) {
  2646. va_start(va, fmt);
  2647. vsprintf(sbuf, fmt, va);
  2648. WriteFile(hDebugWrite, sbuf, strlen(sbuf), &written, NULL);
  2649. va_end(va);
  2650. }
  2651. }
  2652. static void debug_console(void)
  2653. {
  2654. HANDLE hRead; /* Handle to read end of pipe. */
  2655. SECURITY_ATTRIBUTES sa;
  2656. PROCESS_INFORMATION procInfo;
  2657. STARTUPINFO startInfo;
  2658. BOOL ok;
  2659. /*
  2660. * Create a pipe for communicating with the sub process.
  2661. */
  2662. sa.nLength = sizeof(sa);
  2663. sa.lpSecurityDescriptor = NULL;
  2664. sa.bInheritHandle = TRUE;
  2665. if (!CreatePipe(&hRead, &hDebugWrite, &sa, 0)) {
  2666. fprintf(stderr, "Failed to create pipe: %d\n",
  2667. GetLastError());
  2668. exit(1);
  2669. }
  2670. startInfo.cb = sizeof(STARTUPINFO);
  2671. startInfo.lpTitle = "Erlang Debug Log";
  2672. startInfo.lpReserved = NULL;
  2673. startInfo.lpReserved2 = NULL;
  2674. startInfo.cbReserved2 = 0;
  2675. startInfo.lpDesktop = NULL;
  2676. startInfo.dwFlags = STARTF_USESTDHANDLES;
  2677. startInfo.hStdInput = hRead;
  2678. /* The following handles are not intended to be used. */
  2679. startInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
  2680. startInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  2681. ok = CreateProcess(NULL,
  2682. "erl_log.exe", /* Application */
  2683. NULL, /* Process security attributes. */
  2684. NULL, /* Thread security attributes. */
  2685. TRUE, /* Handle inheritance flag. */
  2686. CREATE_NEW_CONSOLE, /* Flags. */
  2687. NULL, /* Environment. */
  2688. NULL, /* Current directory. */
  2689. &startInfo,/* Startup info. */
  2690. &procInfo /* Process information. */
  2691. );
  2692. CloseHandle(hRead);
  2693. if (ok) {
  2694. /*
  2695. * Since we don't use these, close them at once to avoid a resource
  2696. * leak.
  2697. */
  2698. CloseHandle(procInfo.hProcess);
  2699. CloseHandle(procInfo.hThread);
  2700. } else {
  2701. fprintf(stderr, "Create process failed: %s\n", last_error());
  2702. exit(1);
  2703. }
  2704. }
  2705. void
  2706. erl_bin_write(buf, sz, max)
  2707. unsigned char* buf;
  2708. int sz;
  2709. int max;
  2710. {
  2711. int i, imax;
  2712. char comma[5] = ",";
  2713. if (hDebugWrite == INVALID_HANDLE_VALUE)
  2714. return;
  2715. if (!sz)
  2716. return;
  2717. if (sz > max)
  2718. imax = max;
  2719. else
  2720. imax = sz;
  2721. for (i=0; i<imax; i++) {
  2722. if (i == imax-1) {
  2723. if (sz > max)
  2724. strcpy(comma, ",...");
  2725. else
  2726. comma[0] = 0;
  2727. }
  2728. if (isdigit(buf[i]))
  2729. erl_debug("%u%s", (int)(buf[i]), comma);
  2730. else {
  2731. if (isalpha(buf[i])) {
  2732. erl_debug("%c%s", buf[i], comma);
  2733. }
  2734. else
  2735. erl_debug("%u%s", (int)(buf[i]), comma);
  2736. }
  2737. }
  2738. }
  2739. #endif /* DEBUG */
  2740. void
  2741. erl_assert_error(const char* expr, const char* func, const char* file, int line)
  2742. {
  2743. char message[1024];
  2744. erts_snprintf(message, sizeof(message),
  2745. "File %hs, line %d: %hs", file, line, expr);
  2746. MessageBox(GetActiveWindow(), message, "Assertion failed",
  2747. MB_OK | MB_ICONERROR);
  2748. #if 0
  2749. erl_crash_dump(file, line, "Assertion failed: %hs\n", expr);
  2750. #endif
  2751. DebugBreak();
  2752. }
  2753. static void
  2754. check_supported_os_version(void)
  2755. {
  2756. #if defined(_WIN32_WINNT)
  2757. {
  2758. DWORD major = (_WIN32_WINNT >> 8) & 0xff;
  2759. DWORD minor = _WIN32_WINNT & 0xff;
  2760. if (int_os_version.dwPlatformId != VER_PLATFORM_WIN32_NT
  2761. || int_os_version.dwMajorVersion < major
  2762. || (int_os_version.dwMajorVersion == major
  2763. && int_os_version.dwMinorVersion < minor))
  2764. erts_exit(1,
  2765. "Windows version not supported "
  2766. "(min required: winnt %d.%d)\n",
  2767. major, minor);
  2768. }
  2769. #else
  2770. erts_exit(1,
  2771. "Windows version not supported "
  2772. "(min required: win %d.%d)\n",
  2773. nt_major, nt_minor);
  2774. #endif
  2775. }
  2776. typedef struct {
  2777. int sched_bind_data;
  2778. } erts_thr_create_data_t;
  2779. /*
  2780. * thr_create_prepare() is called in parent thread before thread creation.
  2781. * Returned value is passed as argument to thr_create_cleanup().
  2782. */
  2783. static void *
  2784. thr_create_prepare(void)
  2785. {
  2786. erts_thr_create_data_t *tcdp;
  2787. tcdp = erts_alloc(ERTS_ALC_T_TMP, sizeof(erts_thr_create_data_t));
  2788. tcdp->sched_bind_data = erts_sched_bind_atthrcreate_prepare();
  2789. return (void *) tcdp;
  2790. }
  2791. /* thr_create_cleanup() is called in parent thread after thread creation. */
  2792. static void
  2793. thr_create_cleanup(void *vtcdp)
  2794. {
  2795. erts_thr_create_data_t *tcdp = (erts_thr_create_data_t *) vtcdp;
  2796. erts_sched_bind_atthrcreate_parent(tcdp->sched_bind_data);
  2797. erts_free(ERTS_ALC_T_TMP, tcdp);
  2798. }
  2799. static void
  2800. thr_create_prepare_child(void *vtcdp)
  2801. {
  2802. erts_thr_create_data_t *tcdp = (erts_thr_create_data_t *) vtcdp;
  2803. #ifdef ERTS_ENABLE_LOCK_COUNT
  2804. erts_lcnt_thread_setup();
  2805. #endif /* ERTS_ENABLE_LOCK_COUNT */
  2806. erts_sched_bind_atthrcreate_child(tcdp->sched_bind_data);
  2807. }
  2808. void
  2809. erts_sys_pre_init(void)
  2810. {
  2811. erts_thr_init_data_t eid = ERTS_THR_INIT_DATA_DEF_INITER;
  2812. int_os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  2813. GetVersionEx(&int_os_version);
  2814. check_supported_os_version();
  2815. eid.thread_create_child_func = thr_create_prepare_child;
  2816. /* Before creation in parent */
  2817. eid.thread_create_prepare_func = thr_create_prepare;
  2818. /* After creation in parent */
  2819. eid.thread_create_parent_func = thr_create_cleanup;
  2820. #ifdef ERTS_ENABLE_LOCK_COUNT
  2821. erts_lcnt_pre_thr_init();
  2822. #endif
  2823. erts_thr_init(&eid);
  2824. #ifdef ERTS_ENABLE_LOCK_COUNT
  2825. erts_lcnt_post_thr_init();
  2826. #endif
  2827. #ifdef ERTS_ENABLE_LOCK_CHECK
  2828. erts_lc_init();
  2829. #endif
  2830. erts_init_sys_time_sup();
  2831. erts_atomic_init_nob(&sys_misc_mem_sz, 0);
  2832. }
  2833. void noinherit_std_handle(DWORD type)
  2834. {
  2835. HANDLE h = GetStdHandle(type);
  2836. if (h != 0 && h != INVALID_HANDLE_VALUE) {
  2837. SetHandleInformation(h,HANDLE_FLAG_INHERIT,0);
  2838. }
  2839. }
  2840. void erl_sys_init(void)
  2841. {
  2842. HANDLE handle;
  2843. noinherit_std_handle(STD_OUTPUT_HANDLE);
  2844. noinherit_std_handle(STD_INPUT_HANDLE);
  2845. noinherit_std_handle(STD_ERROR_HANDLE);
  2846. erts_tsd_key_create(&win32_errstr_key,"win32_errstr_key");
  2847. InitializeCriticalSection(&htbc_lock);
  2848. erts_atomic_init_nob(&pipe_creation_counter,0);
  2849. /*
  2850. * Test if we have named pipes or not.
  2851. */
  2852. switch (int_os_version.dwPlatformId) {
  2853. case VER_PLATFORM_WIN32_WINDOWS:
  2854. DEBUGF(("Running on Windows 95"));
  2855. use_named_pipes = FALSE;
  2856. break;
  2857. case VER_PLATFORM_WIN32_NT:
  2858. DEBUGF(("Running on Windows NT"));
  2859. #ifdef DISABLE_NAMED_PIPES
  2860. use_named_pipes = FALSE;
  2861. #else
  2862. use_named_pipes = TRUE;
  2863. #endif
  2864. break;
  2865. default: /* Unsupported platform. */
  2866. exit(1);
  2867. }
  2868. DEBUGF((" %d.%d, build %d, %s\n",
  2869. int_os_version.dwMajorVersion, int_os_version.dwMinorVersion,
  2870. int_os_version.dwBuildNumber, int_os_version.szCSDVersion));
  2871. ASSERT(beam_module != NULL);
  2872. init_console();
  2873. /*
  2874. * The following makes sure that the current directory for the current drive
  2875. * is remembered (in the environment).
  2876. */
  2877. chdir(".");
  2878. /*
  2879. * Make sure that the standard error handle is valid.
  2880. */
  2881. handle = GetStdHandle(STD_ERROR_HANDLE);
  2882. if (handle == INVALID_HANDLE_VALUE || handle == 0) {
  2883. SetStdHandle(STD_ERROR_HANDLE, GetStdHandle(STD_OUTPUT_HANDLE));
  2884. }
  2885. erts_sys_init_float();
  2886. /* Suppress windows error message popups */
  2887. SetErrorMode(SetErrorMode(0) |
  2888. SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
  2889. }
  2890. void erts_poll_late_init(void);
  2891. void
  2892. erl_sys_late_init(void)
  2893. {
  2894. /* do nothing */
  2895. erts_poll_late_init();
  2896. }