PageRenderTime 36ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

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

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