Debian Codegraph @

src/system.c

raw
1 /*
2 * system.c - system interface
3 *
4 * Copyright (c) 2000-2024 Shiro Kawai <[email protected]>
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the authors nor the names of its contributors
18 * may be used to endorse or promote products derived from this
19 * software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 #define LIBGAUCHE_BODY
35 #include "gauche.h"
36 #include "gauche/priv/configP.h"
37 #include "gauche/priv/bignumP.h"
38 #include "gauche/priv/builtin-syms.h"
39 #include "gauche/priv/fastlockP.h"
40
41 #include <locale.h>
42 #include <errno.h>
43 #include <string.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <ctype.h>
47 #include <fcntl.h>
48 #include <math.h>
49 #include <dirent.h>
50
51 #if !defined(GAUCHE_WINDOWS)
52 #include <grp.h>
53 #include <pwd.h>
54 #include <sys/times.h>
55 #include <sys/wait.h>
56
57 # if !defined(HAVE_CRT_EXTERNS_H)
58 /* POSIX defines environ, and ISO C defines __environ.
59 Modern C seems to have the latter declared in unistd.h */
60 extern char **environ;
61 # else /* HAVE_CRT_EXTERNS_H */
62 /* On newer OSX, we can't directly access global 'environ' variable.
63 We need to use _NSGetEnviron(), and this header defines it. */
64 #include <crt_externs.h>
65 # endif /* HAVE_CRT_EXTERNS_H */
66 #else /* GAUCHE_WINDOWS */
67 #include <lm.h>
68 #include <tlhelp32.h>
69 /* For windows redirection; win_prepare_handles creats and returns
70 win_redirects[3]. Each entry contains an inheritable handle for
71 the child process' stdin, stdout and stderr, respectively, and the flag
72 duped indicates whether the parent process must close the handle. */
73 typedef struct win_redirects_rec {
74 HANDLE *h;
75 int duped;
76 } win_redirects;
77 static win_redirects *win_prepare_handles(int *fds);
78 static int win_wait_for_handles(HANDLE *handles, int nhandles, int options,
79 int *status /*out*/);
80 #endif /* GAUCHE_WINDOWS */
81
82 #ifdef HAVE_GLOB_H
83 #include <glob.h>
84 #endif
85 #ifdef HAVE_SCHED_H
86 #include <sched.h>
87 #endif
88
89 /*
90 * Auxiliary system interface functions. See libsys.scm for
91 * Scheme binding.
92 */
93
94 /*===============================================================
95 * Windows specific - conversion between mbs and wcs.
96 */
97 #if defined(GAUCHE_WINDOWS) && defined(UNICODE)
98 #include "win-compat.c"
99
100 WCHAR *Scm_MBS2WCS(const char *s)
101 {
102 return mbs2wcs(s, TRUE, Scm_Error);
103 }
104
105 const char *Scm_WCS2MBS(const WCHAR *s)
106 {
107 return wcs2mbs(s, TRUE, Scm_Error);
108 }
109 #endif /* defined(GAUCHE_WINDOWS) && defined(UNICODE) */
110
111 /*===============================================================
112 * OBSOLETED: Wrapper to the system call to handle signals.
113 * Use SCM_SYSCALL_{I|P} macro instead.
114 */
115 int Scm_SysCall(int r)
116 {
117 Scm_Warn("Obsoleted API Scm_SysCall is called.");
118 if (r < 0 && errno == EINTR) {
119 ScmVM *vm = Scm_VM();
120 errno = 0;
121 SCM_SIGCHECK(vm);
122 }
123 return r;
124 }
125
126 void *Scm_PtrSysCall(void *r)
127 {
128 Scm_Warn("Obsoleted API Scm_PtrSysCall is called.");
129 if (r == NULL && errno == EINTR) {
130 ScmVM *vm = Scm_VM();
131 errno = 0;
132 SCM_SIGCHECK(vm);
133 }
134 return r;
135 }
136
137 /*
138 * A utility function for the procedures that accepts either port or
139 * integer file descriptor. Returns the file descriptor. If port_or_fd
140 * is a port that is not associated with the system file, and needfd is
141 * true, signals error. Otherwise it returns -1.
142 */
143 int Scm_GetPortFd(ScmObj port_or_fd, int needfd)
144 {
145 int fd = -1;
146 if (SCM_INTP(port_or_fd)) {
147 fd = SCM_INT_VALUE(port_or_fd);
148 } else if (SCM_PORTP(port_or_fd)) {
149 fd = Scm_PortFileNo(SCM_PORT(port_or_fd));
150 if (fd < 0 && needfd) {
151 Scm_Error("the port is not associated with a system file descriptor: %S",
152 port_or_fd);
153 }
154 } else {
155 Scm_Error("port or small integer required, but got %S", port_or_fd);
156 }
157 return fd;
158 }
159
160 /*===============================================================
161 * Directory primitives (dirent.h)
162 * We don't provide the iterator primitives, but a function which
163 * reads entire directory.
164 */
165
166 /* Returns a list of directory entries. If pathname is not a directory,
167 or can't be opened by some reason, an error is signalled. */
168 ScmObj Scm_ReadDirectory(ScmString *pathname)
169 {
170 ScmObj head = SCM_NIL, tail = SCM_NIL;
171 #if !defined(GAUCHE_WINDOWS)
172 ScmVM *vm = Scm_VM();
173 struct dirent *dire;
174 DIR *dirp = opendir(Scm_GetStringConst(pathname));
175
176 if (dirp == NULL) {
177 SCM_SIGCHECK(vm);
178 Scm_SysError("couldn't open directory %S", pathname);
179 }
180 while ((dire = readdir(dirp)) != NULL) {
181 ScmObj ent = SCM_MAKE_STR_COPYING(dire->d_name);
182 SCM_APPEND1(head, tail, ent);
183 }
184 SCM_SIGCHECK(vm);
185 closedir(dirp);
186 return head;
187 #else /* GAUCHE_WINDOWS */
188 WIN32_FIND_DATA fdata;
189 DWORD winerrno;
190 ScmObj pattern;
191
192 int pathlen = SCM_STRING_LENGTH(pathname);
193 if (pathlen == 0) {
194 Scm_Error("Couldn't open directory \"\"");
195 }
196 ScmChar lastchar = Scm_StringRef(pathname, pathlen-1, FALSE);
197 if (lastchar == SCM_CHAR('/') || lastchar == SCM_CHAR('\\')) {
198 pattern = Scm_StringAppendC(pathname, "*", 1, 1);
199 } else {
200 pattern = Scm_StringAppendC(pathname, "\\*", 2, 2);
201 }
202 const char *path = Scm_GetStringConst(SCM_STRING(pattern));
203
204 HANDLE dirp = FindFirstFile(SCM_MBS2WCS(path), &fdata);
205 if (dirp == INVALID_HANDLE_VALUE) {
206 if ((winerrno = GetLastError()) != ERROR_FILE_NOT_FOUND) goto err;
207 return head;
208 }
209 const char *tpath = SCM_WCS2MBS(fdata.cFileName);
210 SCM_APPEND1(head, tail, SCM_MAKE_STR_COPYING(tpath));
211 while (FindNextFile(dirp, &fdata) != 0) {
212 tpath = SCM_WCS2MBS(fdata.cFileName);
213 SCM_APPEND1(head, tail, SCM_MAKE_STR_COPYING(tpath));
214 }
215 winerrno = GetLastError();
216 FindClose(dirp);
217 if (winerrno != ERROR_NO_MORE_FILES) goto err;
218 return head;
219 err:
220 Scm_Error("Searching directory failed by windows error %d",
221 winerrno);
222 return SCM_UNDEFINED; /* dummy */
223 #endif
224 }
225
226 /* getcwd compatibility layer.
227 Some implementations of getcwd accepts NULL as buffer to allocate
228 enough buffer memory in it, but that's not standardized and we avoid
229 relying on it.
230 */
231 ScmObj Scm_GetCwd(void)
232 {
233 #if defined(GAUCHE_WINDOWS)&&defined(UNICODE)
234 # define CHAR_T wchar_t
235 # define GETCWD _wgetcwd
236 #else /*!(defined(GAUCHE_WINDOWS)&&defined(UNICODE))*/
237 # define CHAR_T char
238 # define GETCWD getcwd
239 #endif /*!(defined(GAUCHE_WINDOWS)&&defined(UNICODE))*/
240
241 #define GETCWD_INITIAL_BUFFER_SIZE 1024
242 int bufsiz = GETCWD_INITIAL_BUFFER_SIZE;
243 CHAR_T sbuf[GETCWD_INITIAL_BUFFER_SIZE];
244 CHAR_T *buf = sbuf;
245 CHAR_T *r;
246
247 for (;;) {
248 SCM_SYSCALL3(r, GETCWD(buf, bufsiz), r == NULL);
249 if (r != NULL) break;
250 if (errno == ERANGE) {
251 bufsiz *= 2;
252 buf = SCM_NEW_ATOMIC_ARRAY(CHAR_T, bufsiz);
253 } else {
254 Scm_SysError("getcwd failed");
255 }
256 }
257 #if defined(GAUCHE_WINDOWS) && defined(UNICODE)
258 return Scm_MakeString(Scm_WCS2MBS(buf), -1, -1, 0);
259 #else /*!(defined(GAUCHE_WINDOWS) && defined(UNICODE))*/
260 return Scm_MakeString(buf, -1, -1, SCM_STRING_COPYING);
261 #endif /*!(defined(GAUCHE_WINDOWS) && defined(UNICODE))*/
262 #undef CHAR_T
263 }
264
265 /*===============================================================
266 * Pathname manipulation
267 *
268 * It gets complicated since the byte '/' and '\\' can appear in
269 * the trailing octets of a multibyte character.
270 * Assuming these operations won't be a bottleneck, we use simple and
271 * straightforward code rather than tricky and fast one.
272 */
273
274 /* Returns the system's native pathname delimiter. */
275 const char *Scm_PathDelimiter(void)
276 {
277 #if !defined(GAUCHE_WINDOWS)
278 return "/";
279 #else /* GAUCHE_WINDOWS */
280 return "\\";
281 #endif /* GAUCHE_WINDOWS */
282 }
283
284 /* On Windows, '/' is *allowed* to be an alternative separator. */
285 #if defined(GAUCHE_WINDOWS)
286 #define SEPARATOR '\\'
287 #define ROOTDIR "\\"
288 #define SEPARATOR_P(c) ((c) == SEPARATOR || (c) == '/')
289 #else
290 #define SEPARATOR '/'
291 #define ROOTDIR "/"
292 #define SEPARATOR_P(c) ((c) == SEPARATOR)
293 #endif
294
295 /* Returns the pointer to the first path separator character,
296 or NULL if no separator is found. */
297 static const char *get_first_separator(const char *path, const char *end)
298 {
299 const char *p = path;
300 while (p < end) {
301 if (SEPARATOR_P(*p)) return p;
302 p += SCM_CHAR_NFOLLOWS(*p)+1;
303 }
304 return NULL;
305 }
306
307 /* Returns the pointer to the last path separator character,
308 or NULL if no separator is found. */
309 static const char *get_last_separator(const char *path, const char *end)
310 {
311 const char *p = path, *last = NULL;
312 while (p < end) {
313 if (SEPARATOR_P(*p)) last = p;
314 p += SCM_CHAR_NFOLLOWS(*p)+1;
315 }
316 return last;
317 }
318
319 static const char *skip_separators(const char *p, const char *end)
320 {
321 while (p < end) {
322 if (!SEPARATOR_P(*p)) break;
323 p += SCM_CHAR_NFOLLOWS(*p)+1;
324 }
325 return p;
326 }
327
328 /* Returns the end pointer sans trailing separators. */
329 static const char *truncate_trailing_separators(const char *path,
330 const char *end)
331 {
332 const char *p = get_first_separator(path, end);
333 if (p == NULL) return end;
334 for (;;) {
335 const char *q = skip_separators(p, end);
336 if (q == end) return p;
337 p = get_first_separator(q, end);
338 if (p == NULL) return end;
339 }
340 }
341
342 /* for keyword arguments */
343 static ScmObj key_absolute = SCM_FALSE;
344 static ScmObj key_expand = SCM_FALSE;
345 static ScmObj key_canonicalize = SCM_FALSE;
346
347 ScmObj Scm_NormalizePathname(ScmString *pathname, int flags)
348 {
349 static ScmObj proc = SCM_UNDEFINED;
350 SCM_BIND_PROC(proc, "sys-normalize-pathname", Scm_GaucheModule());
351
352 ScmObj h = SCM_NIL, t = SCM_NIL;
353 SCM_APPEND1(h, t, SCM_OBJ(pathname));
354 if (flags & SCM_PATH_ABSOLUTE) {
355 SCM_APPEND1(h, t, key_absolute);
356 SCM_APPEND1(h, t, SCM_TRUE);
357 }
358 if (flags & SCM_PATH_CANONICALIZE) {
359 SCM_APPEND1(h, t, key_canonicalize);
360 SCM_APPEND1(h, t, SCM_TRUE);
361 }
362 if (flags & SCM_PATH_EXPAND) {
363 SCM_APPEND1(h, t, key_expand);
364 SCM_APPEND1(h, t, SCM_TRUE);
365 }
366 return Scm_ApplyRec(proc, h);
367 }
368
369 /* Returns system's temporary directory. */
370 ScmObj Scm_TmpDir(void)
371 {
372 #if defined(GAUCHE_WINDOWS)
373 # define TMP_PATH_MAX 1024
374 TCHAR buf[TMP_PATH_MAX+1], *tbuf = buf;
375 /* According to the windows document, this API checks environment
376 variables TMP, TEMP, and USERPROFILE. Fallback is the Windows
377 directory. */
378 DWORD r = GetTempPath(TMP_PATH_MAX, buf);
379 if (r == 0) Scm_SysError("GetTempPath failed");
380 if (r > TMP_PATH_MAX) {
381 tbuf = SCM_NEW_ATOMIC_ARRAY(TCHAR, r+1);
382 DWORD r2 = GetTempPath(r, tbuf);
383 if (r2 != r) Scm_SysError("GetTempPath failed");
384 }
385 return SCM_MAKE_STR_COPYING(SCM_WCS2MBS(tbuf));
386 #else /*!GAUCHE_WINDOWS*/
387 const char *s;
388 if ((s = Scm_GetEnv("TMPDIR")) != NULL) return SCM_MAKE_STR_COPYING(s);
389 if ((s = Scm_GetEnv("TMP")) != NULL) return SCM_MAKE_STR_COPYING(s);
390 else return SCM_MAKE_STR("/tmp"); /* fallback */
391 #endif /*!GAUCHE_WINDOWS*/
392 }
393
394 /* Basename and dirname.
395 On Win32, we need to treat drive names specially, e.g.:
396 (sys-dirname "C:/a") == (sys-dirname "C:/") == (sys-dirname "C:") == "C:\\"
397 (sys-basename "C:/") == (sys-basename "C:) == ""
398 */
399
400 ScmObj Scm_BaseName(ScmString *filename)
401 {
402 ScmSmallInt size;
403 const char *path = Scm_GetStringContent(filename, &size, NULL, NULL);
404
405 #if defined(GAUCHE_WINDOWS)
406 /* Ignore drive letter, for it can never be a part of basename. */
407 if (size >= 2 && path[1] == ':' && isalpha(path[0])) {
408 path += 2;
409 size -= 2;
410 }
411 #endif /* GAUCHE_WINDOWS) */
412
413 if (size == 0) return SCM_MAKE_STR("");
414 const char *endp = truncate_trailing_separators(path, path+size);
415 const char *last = get_last_separator(path, endp);
416 if (last == NULL) {
417 return Scm_MakeString(path, (int)(endp-path), -1, 0);
418 } else {
419 return Scm_MakeString(last+1, (int)(endp-last-1), -1, 0);
420 }
421 }
422
423 ScmObj Scm_DirName(ScmString *filename)
424 {
425 ScmSmallInt size;
426 const char *path = Scm_GetStringContent(filename, &size, NULL, NULL);
427 #if defined(GAUCHE_WINDOWS)
428 int drive_letter = -1;
429 if (size >= 2 && path[1] == ':' && isalpha(path[0])) {
430 drive_letter = path[0];
431 path += 2;
432 size -= 2;
433 }
434 #endif /* GAUCHE_WINDOWS */
435
436 if (size == 0) { path = NULL; goto finale; }
437 const char *endp = truncate_trailing_separators(path, path+size);
438 if (endp == path) { path = ROOTDIR, size = 1; goto finale; }
439 const char *last = get_last_separator(path, endp);
440 if (last == NULL) { path = ".", size = 1; goto finale; }
441
442 /* we have "something/", and 'last' points to the last separator. */
443 last = truncate_trailing_separators(path, last);
444 if (last == path) {
445 path = ROOTDIR, size = 1;
446 } else {
447 size = (int)(last - path);
448 }
449 finale:
450 #if defined(GAUCHE_WINDOWS)
451 if (drive_letter > 0) {
452 ScmObj z;
453 char p[3] = "x:";
454 p[0] = (char)drive_letter;
455 z = Scm_MakeString(p, 2, 2, SCM_MAKSTR_COPYING);
456 if (path) {
457 return Scm_StringAppendC(SCM_STRING(z), path, size, -1);
458 } else {
459 return Scm_StringAppendC(SCM_STRING(z), ROOTDIR, 1, -1);
460 }
461 }
462 #endif /* GAUCHE_WINDOWS */
463 if (path) return Scm_MakeString(path, size, -1, 0);
464 else return Scm_MakeString(".", 1, 1, 0);
465 }
466
467 #undef ROOTDIR
468 #undef SEPARATOR
469
470
471 #if !defined(HAVE_MKSTEMP) || !defined(HAVE_MKDTEMP)
472 /*
473 * Helper function to emulate mkstemp or mkdtemp. FUNC returns 0 on
474 * success and non-zero otherwize. NAME is a name of operation
475 * performed by FUNC. ARG is caller supplied data passed to FUNC.
476 */
477 static void emulate_mkxtemp(char *name, char *templat,
478 int (*func)(char *, void *), void *arg)
479 {
480 /* Emulate mkxtemp. */
481 int siz = (int)strlen(templat);
482 if (siz < 6) {
483 Scm_Error("%s - invalid template: %s", name, templat);
484 }
485 #define MKXTEMP_MAX_TRIALS 65535 /* avoid infinite loop */
486 {
487 u_long seed = (u_long)time(NULL);
488 int numtry, rv;
489 char suffix[7];
490 for (numtry=0; numtry<MKXTEMP_MAX_TRIALS; numtry++) {
491 snprintf(suffix, 7, "%06lx", (seed>>8)&0xffffff);
492 memcpy(templat+siz-6, suffix, 7);
493 rv = (*func)(templat, arg);
494 if (rv == 0) break;
495 seed *= 2654435761UL;
496 }
497 if (numtry == MKXTEMP_MAX_TRIALS) {
498 Scm_Error("%s failed", name);
499 }
500 }
501 }
502 #endif /* !defined(HAVE_MKSTEMP) || !defined(HAVE_MKDTEMP) */
503
504 #define MKXTEMP_PATH_MAX 1025 /* Geez, remove me */
505 static void build_template(ScmString *templat, char *name)
506 {
507 ScmSmallInt siz;
508 const char *t = Scm_GetStringContent(templat, &siz, NULL, NULL);
509 if (siz >= MKXTEMP_PATH_MAX-6) {
510 Scm_Error("pathname too long: %S", templat);
511 }
512 memcpy(name, t, siz);
513 memcpy(name + siz, "XXXXXX", 6);
514 name[siz+6] = '\0';
515 }
516
517 #if !defined(HAVE_MKSTEMP)
518 static int create_tmpfile(char *templat, void *arg)
519 {
520 int *fdp = (int *)arg;
521 int flags;
522
523 #if defined(GAUCHE_WINDOWS)
524 flags = O_CREAT|O_EXCL|O_WRONLY|O_BINARY;
525 #else /* !GAUCHE_WINDOWS */
526 flags = O_CREAT|O_EXCL|O_WRONLY;
527 #endif /* !GAUCHE_WINDOWS */
528 SCM_SYSCALL(*fdp, open(templat, flags, 0600));
529 return *fdp < 0;
530 }
531 #endif
532
533 /* Make mkstemp() work even if the system doesn't have one. */
534 int Scm_Mkstemp(char *templat)
535 {
536 int fd = -1;
537 #if defined(HAVE_MKSTEMP)
538 SCM_SYSCALL(fd, mkstemp(templat));
539 if (fd < 0) Scm_SysError("mkstemp failed");
540 return fd;
541 #else /*!defined(HAVE_MKSTEMP)*/
542 emulate_mkxtemp("mkstemp", templat, create_tmpfile, &fd);
543 return fd;
544 #endif /*!defined(HAVE_MKSTEMP)*/
545 }
546
547
548 ScmObj Scm_SysMkstemp(ScmString *templat)
549 {
550 char name[MKXTEMP_PATH_MAX];
551 build_template(templat, name);
552 int fd = Scm_Mkstemp(name);
553 ScmObj sname = SCM_MAKE_STR_COPYING(name);
554 SCM_RETURN(Scm_Values2(Scm_MakePortWithFd(sname, SCM_PORT_OUTPUT, fd,
555 SCM_PORT_BUFFER_FULL, TRUE),
556 sname));
557 }
558
559 #if !defined(HAVE_MKDTEMP)
560 static int create_tmpdir(char *templat, void *arg SCM_UNUSED)
561 {
562 int r;
563
564 #if defined(GAUCHE_WINDOWS)
565 SCM_SYSCALL(r, mkdir(templat));
566 #else /* !GAUCHE_WINDOWS */
567 SCM_SYSCALL(r, mkdir(templat, 0700));
568 #endif /* !GAUCHE_WINDOWS */
569 return r < 0;
570 }
571 #endif
572
573 ScmObj Scm_SysMkdtemp(ScmString *templat)
574 {
575 char name[MKXTEMP_PATH_MAX];
576 build_template(templat, name);
577
578 #if defined(HAVE_MKDTEMP)
579 {
580 char *p = NULL;
581 SCM_SYSCALL3(p, mkdtemp(name), (p == NULL));
582 if (p == NULL) Scm_SysError("mkdtemp failed");
583 }
584 #else /*!defined(HAVE_MKDTEMP)*/
585 emulate_mkxtemp("mkdtemp", name, create_tmpdir, NULL);
586 #endif /*!defined(HAVE_MKDTEMP)*/
587
588 return SCM_MAKE_STR_COPYING(name);
589 }
590
591 /*===============================================================
592 * Stat (sys/stat.h)
593 */
594
595 static ScmObj stat_allocate(ScmClass *klass, ScmObj initargs SCM_UNUSED)
596 {
597 return SCM_OBJ(SCM_NEW_INSTANCE(ScmSysStat, klass));
598 }
599
600 static ScmSmallInt stat_hash(ScmObj obj, ScmSmallInt salt, u_long flags)
601 {
602 ScmStat *s = SCM_SYS_STAT_STAT(obj);
603 ScmSmallInt h = salt;
604 #define STAT_HASH_UI(name) \
605 h = Scm_CombineHashValue(Scm_SmallIntHash((ScmSmallInt)s->SCM_CPP_CAT(st_, name), \
606 salt, flags), h)
607 #define STAT_HASH_TIME(name) \
608 h = Scm_CombineHashValue(Scm_Int64Hash((int64_t)s->SCM_CPP_CAT(st_, name), \
609 salt, flags), h)
610 #define STAT_HASH_TIMESPEC(name) \
611 h = Scm_CombineHashValue(Scm_Int64Hash((int64_t)s->SCM_CPP_CAT(st_, name).tv_sec, \
612 salt, flags), \
613 Scm_CombineHashValue(Scm_Int64Hash((int64_t)s->SCM_CPP_CAT(st_, name).tv_nsec, \
614 salt, flags),h))
615
616
617 STAT_HASH_UI(mode);
618 STAT_HASH_UI(ino);
619 STAT_HASH_UI(dev);
620 STAT_HASH_UI(rdev);
621 STAT_HASH_UI(nlink);
622 STAT_HASH_UI(uid);
623 STAT_HASH_UI(gid);
624 #if HAVE_STRUCT_STAT_ST_ATIM
625 STAT_HASH_TIMESPEC(atim);
626 #else
627 STAT_HASH_TIME(atime);
628 #endif
629 #if HAVE_STRUCT_STAT_ST_MTIM
630 STAT_HASH_TIMESPEC(mtim);
631 #else
632 STAT_HASH_TIME(mtime);
633 #endif
634 #if HAVE_STRUCT_STAT_ST_CTIM
635 STAT_HASH_TIMESPEC(ctim);
636 #else
637 STAT_HASH_TIME(ctime);
638 #endif
639 return h;
640 }
641
642 SCM_DEFINE_BUILTIN_CLASS(Scm_SysStatClass,
643 NULL, NULL, stat_hash,
644 stat_allocate,
645 SCM_CLASS_DEFAULT_CPL);
646
647 ScmObj Scm_MakeSysStat(void)
648 {
649 return stat_allocate(&Scm_SysStatClass, SCM_NIL);
650 }
651
652 static ScmObj stat_type_get(ScmSysStat *stat)
653 {
654 if (S_ISDIR(SCM_SYS_STAT_STAT(stat)->st_mode)) return (SCM_SYM_DIRECTORY);
655 if (S_ISREG(SCM_SYS_STAT_STAT(stat)->st_mode)) return (SCM_SYM_REGULAR);
656 if (S_ISCHR(SCM_SYS_STAT_STAT(stat)->st_mode)) return (SCM_SYM_CHARACTER);
657 if (S_ISBLK(SCM_SYS_STAT_STAT(stat)->st_mode)) return (SCM_SYM_BLOCK);
658 if (S_ISFIFO(SCM_SYS_STAT_STAT(stat)->st_mode)) return (SCM_SYM_FIFO);
659 #ifdef S_ISLNK
660 if (S_ISLNK(SCM_SYS_STAT_STAT(stat)->st_mode)) return (SCM_SYM_SYMLINK);
661 #endif
662 #ifdef S_ISSOCK
663 if (S_ISSOCK(SCM_SYS_STAT_STAT(stat)->st_mode)) return (SCM_SYM_SOCKET);
664 #endif
665 return (SCM_FALSE);
666 }
667
668 static ScmObj stat_perm_get(ScmSysStat *stat)
669 {
670 return Scm_MakeIntegerFromUI(SCM_SYS_STAT_STAT(stat)->st_mode & 0777);
671 }
672
673 static ScmObj stat_size_get(ScmSysStat *stat)
674 {
675 return Scm_OffsetToInteger(SCM_SYS_STAT_STAT(stat)->st_size);
676 }
677
678
679 #define STAT_GETTER_UI(name) \
680 static ScmObj SCM_CPP_CAT3(stat_, name, _get)(ScmSysStat *s) \
681 { return Scm_MakeIntegerFromUI((u_long)(SCM_SYS_STAT_STAT(s)->SCM_CPP_CAT(st_, name))); }
682 #define STAT_GETTER_TIME(name) \
683 static ScmObj SCM_CPP_CAT3(stat_, name, _get)(ScmSysStat *s) \
684 { return Scm_MakeSysTime(SCM_SYS_STAT_STAT(s)->SCM_CPP_CAT(st_, name)); }
685
686 STAT_GETTER_UI(mode)
687 STAT_GETTER_UI(ino)
688 STAT_GETTER_UI(dev)
689 STAT_GETTER_UI(rdev)
690 STAT_GETTER_UI(nlink)
691 STAT_GETTER_UI(uid)
692 STAT_GETTER_UI(gid)
693 STAT_GETTER_TIME(atime)
694 STAT_GETTER_TIME(mtime)
695 STAT_GETTER_TIME(ctime)
696
697 static ScmObj stat_atim_get(ScmSysStat *s)
698 {
699 #if HAVE_STRUCT_STAT_ST_ATIM
700 return Scm_MakeTime64(SCM_SYM_TIME_UTC,
701 (int64_t)s->statrec.st_atim.tv_sec,
702 s->statrec.st_atim.tv_nsec);
703 #else
704 return Scm_MakeTime64(SCM_SYM_TIME_UTC,
705 (int64_t)s->statrec.st_atime,
706 0);
707 #endif
708 }
709
710 static ScmObj stat_mtim_get(ScmSysStat *s)
711 {
712 #if HAVE_STRUCT_STAT_ST_MTIM
713 return Scm_MakeTime64(SCM_SYM_TIME_UTC,
714 (int64_t)s->statrec.st_mtim.tv_sec,
715 s->statrec.st_mtim.tv_nsec);
716 #else
717 return Scm_MakeTime64(SCM_SYM_TIME_UTC,
718 (int64_t)s->statrec.st_mtime,
719 0);
720 #endif
721 }
722
723 static ScmObj stat_ctim_get(ScmSysStat *s)
724 {
725 #if HAVE_STRUCT_STAT_ST_CTIM
726 return Scm_MakeTime64(SCM_SYM_TIME_UTC,
727 (int64_t)s->statrec.st_ctim.tv_sec,
728 s->statrec.st_ctim.tv_nsec);
729 #else
730 return Scm_MakeTime64(SCM_SYM_TIME_UTC,
731 (int64_t)s->statrec.st_ctime,
732 0);
733 #endif
734 }
735
736 static ScmClassStaticSlotSpec stat_slots[] = {
737 SCM_CLASS_SLOT_SPEC("type", stat_type_get, NULL),
738 SCM_CLASS_SLOT_SPEC("perm", stat_perm_get, NULL),
739 SCM_CLASS_SLOT_SPEC("mode", stat_mode_get, NULL),
740 SCM_CLASS_SLOT_SPEC("ino", stat_ino_get, NULL),
741 SCM_CLASS_SLOT_SPEC("dev", stat_dev_get, NULL),
742 SCM_CLASS_SLOT_SPEC("rdev", stat_rdev_get, NULL),
743 SCM_CLASS_SLOT_SPEC("nlink", stat_nlink_get, NULL),
744 SCM_CLASS_SLOT_SPEC("uid", stat_uid_get, NULL),
745 SCM_CLASS_SLOT_SPEC("gid", stat_gid_get, NULL),
746 SCM_CLASS_SLOT_SPEC("size", stat_size_get, NULL),
747 SCM_CLASS_SLOT_SPEC("atime", stat_atime_get, NULL),
748 SCM_CLASS_SLOT_SPEC("mtime", stat_mtime_get, NULL),
749 SCM_CLASS_SLOT_SPEC("ctime", stat_ctime_get, NULL),
750 SCM_CLASS_SLOT_SPEC("atim", stat_atim_get, NULL),
751 SCM_CLASS_SLOT_SPEC("mtim", stat_mtim_get, NULL),
752 SCM_CLASS_SLOT_SPEC("ctim", stat_ctim_get, NULL),
753 SCM_CLASS_SLOT_SPEC_END()
754 };
755
756 /*===============================================================
757 * Time (sys/time.h and time.h)
758 */
759
760 /* Gauche has two notion of time. A simple number is used by the low-level
761 * system interface (sys-time, sys-gettimeofday). An object of <time> class
762 * is used for higher-level interface, including threads.
763 */
764
765 /* <time> object */
766
767 static ScmObj time_allocate(ScmClass *klass, ScmObj initargs SCM_UNUSED)
768 {
769 ScmTime *t = SCM_NEW_INSTANCE(ScmTime, klass);
770 t->type = SCM_SYM_TIME_UTC;
771 t->sec = 0;
772 t->nsec = 0;
773 return SCM_OBJ(t);
774 }
775
776 static void time_print(ScmObj obj, ScmPort *port,
777 ScmWriteContext *ctx SCM_UNUSED)
778 {
779 ScmTime *t = SCM_TIME(obj);
780 ScmObj sec = Scm_MakeInteger64(t->sec);
781 long nsec = t->nsec;
782 /* t->sec can be negative for time-difference. */
783 if (Scm_Sign(sec) < 0 && t->nsec > 0) {
784 sec = Scm_Abs(Scm_Add(sec, SCM_MAKE_INT(1)));
785 nsec = 1000000000L - nsec;
786 Scm_Printf(port, "#<%S -%S.%09lu>", t->type, sec, nsec);
787 } else {
788 Scm_Printf(port, "#<%S %S.%09lu>", t->type, sec, nsec);
789 }
790 }
791
792 static int time_compare(ScmObj x, ScmObj y, int equalp)
793 {
794 ScmTime *tx = SCM_TIME(x);
795 ScmTime *ty = SCM_TIME(y);
796
797 if (equalp) {
798 if (SCM_EQ(tx->type, ty->type)
799 && tx->sec == ty->sec
800 && tx->nsec == ty->nsec) {
801 return 0;
802 } else {
803 return 1;
804 }
805 } else {
806 if (!SCM_EQ(tx->type, ty->type)) {
807 Scm_Error("cannot compare different types of time objects: %S vs %S", x, y);
808 }
809 if (tx->sec < ty->sec) return -1;
810 if (tx->sec == ty->sec) {
811 if (tx->nsec < ty->nsec) return -1;
812 if (tx->nsec == ty->nsec) return 0;
813 else return 1;
814 }
815 else return 1;
816 }
817 }
818
819 static ScmSmallInt time_hash(ScmObj x, ScmSmallInt salt, u_long flags)
820 {
821 ScmTime *t = SCM_TIME(x);
822 ScmSmallInt h = salt;
823 h = Scm_CombineHashValue(Scm_RecursiveHash(t->type, salt, flags), h);
824 h = Scm_CombineHashValue(Scm_Int64Hash(t->sec, salt, flags), h);
825 h = Scm_CombineHashValue(Scm_SmallIntHash(t->nsec, salt, flags), h);
826 return h;
827 }
828
829 SCM_DEFINE_BUILTIN_CLASS(Scm_TimeClass,
830 time_print, time_compare, time_hash,
831 time_allocate, SCM_CLASS_DEFAULT_CPL);
832
833 static ScmTime *make_time_int(ScmObj type)
834 {
835 ScmTime *t = SCM_TIME(time_allocate(SCM_CLASS_TIME, SCM_NIL));
836 t->type = SCM_FALSEP(type)? SCM_SYM_TIME_UTC : type;
837 return t;
838 }
839
840
841 ScmObj Scm_MakeTime(ScmObj type, long sec, long nsec)
842 {
843 ScmTime *t = make_time_int(type);
844 t->sec = (int64_t)sec;
845 t->nsec = nsec;
846 return SCM_OBJ(t);
847 }
848
849 ScmObj Scm_MakeTime64(ScmObj type, int64_t sec, long nsec)
850 {
851 ScmTime *t = make_time_int(type);
852 t->sec = sec;
853 t->nsec = nsec;
854 return SCM_OBJ(t);
855 }
856
857 /* Abstract gettimeofday() */
858 void Scm_GetTimeOfDay(u_long *sec, u_long *usec)
859 {
860 #if defined(HAVE_GETTIMEOFDAY)
861 struct timeval tv;
862 int r;
863 SCM_SYSCALL(r, gettimeofday(&tv, NULL));
864 if (r < 0) Scm_SysError("gettimeofday failed");
865 *sec = (u_long)tv.tv_sec;
866 *usec = (u_long)tv.tv_usec;
867 #elif defined(GAUCHE_WINDOWS)
868 FILETIME ft;
869 GetSystemTimeAsFileTime(&ft);
870 SCM_FILETIME_TO_UNIXTIME(ft, *sec, *usec);
871 #else /* !HAVE_GETTIMEOFDAY && !GAUCHE_WINDOWS */
872 /* Last resort */
873 *sec = (u_long)time(NULL);
874 *usec = 0;
875 #endif /* !HAVE_GETTIMEOFDAY && !GAUCHE_WINDOWS */
876 }
877
878 /* Abstract clock_gettime and clock_getres.
879 If the system doesn't have these, those API returns FALSE; the caller
880 should make up fallback means.
881
882 NB: XCode8 breaks clock_getres on OSX 10.11---it's only provided in
883 OSX 10.12, but the SDK pretends it's available on all platforms.
884 For the workaround, we call OSX specific functions.
885 Cf. http://developer.apple.com/library/mac/#qa/qa1398/_index.html
886 */
887 #if defined(__APPLE__) && defined(__MACH__)
888 #include <mach/mach.h>
889 #include <mach/mach_time.h>
890 static mach_timebase_info_data_t tinfo;
891 #endif /* __APPLE__ && __MACH__ */
892
893 int Scm_ClockGetTimeMonotonic(u_long *sec, u_long *nsec)
894 {
895 #if defined(__APPLE__) && defined(__MACH__)
896 if (tinfo.denom == 0) {
897 (void)mach_timebase_info(&tinfo);
898 }
899 uint64_t t = mach_absolute_time();
900 uint64_t ns = t * tinfo.numer / tinfo.denom;
901 *sec = ns / 1000000000;
902 *nsec = ns % 1000000000;
903 return TRUE;
904 #elif defined(GAUCHE_WINDOWS)
905 /* On MinGW, clock_gettime is in libwinpthread-1.dll; we avoid depending
906 on it. */
907 LARGE_INTEGER qpf;
908 LARGE_INTEGER qpc;
909 if (!QueryPerformanceFrequency(&qpf)) {
910 Scm_SysError("QueryPerformanceFrequency failed");
911 }
912 if (!QueryPerformanceCounter(&qpc)) {
913 Scm_SysError("QueryPerformanceCounter failed");
914 }
915 *sec = (u_long)(qpc.QuadPart / qpf.QuadPart);
916 *nsec = (u_long)((qpc.QuadPart % qpf.QuadPart) * 1000000000 / qpf.QuadPart);
917 return TRUE;
918 #elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
919 ScmTimeSpec ts;
920 int r;
921 SCM_SYSCALL(r, clock_gettime(CLOCK_MONOTONIC, &ts));
922 if (r < 0) Scm_SysError("clock_gettime failed");
923 *sec = (u_long)ts.tv_sec;
924 *nsec = (u_long)ts.tv_nsec;
925 return TRUE;
926 #else /*!HAVE_CLOCK_GETTIME*/
927 *sec = *nsec = 0;
928 return FALSE;
929 #endif /*!HAVE_CLOCK_GETTIME*/
930 }
931
932 int Scm_ClockGetResMonotonic(u_long *sec, u_long *nsec)
933 {
934 #if defined(__APPLE__) && defined(__MACH__)
935 if (tinfo.denom == 0) {
936 (void)mach_timebase_info(&tinfo);
937 }
938 if (tinfo.numer <= tinfo.denom) {
939 /* The precision is finer than nano seconds, but we can only
940 represent nanosecond resolution. */
941 *sec = 0;
942 *nsec = 1;
943 } else {
944 *sec = 0;
945 *nsec = tinfo.numer / tinfo.denom;
946 }
947 return TRUE;
948 #elif defined(GAUCHE_WINDOWS)
949 /* On MinGW, clock_getres is in libwinpthread-1.dll; we avoid depending
950 on it. */
951 LARGE_INTEGER qpf;
952 if (!QueryPerformanceFrequency(&qpf)) {
953 Scm_SysError("QueryPerformanceFrequency failed");
954 }
955 *sec = 0;
956 *nsec = (u_long)(1000000000 / qpf.QuadPart);
957 if (*nsec == 0) *nsec = 1;
958 return TRUE;
959 #elif defined(HAVE_CLOCK_GETRES) && defined(CLOCK_MONOTONIC)
960 ScmTimeSpec ts;
961 int r;
962 SCM_SYSCALL(r, clock_getres(CLOCK_MONOTONIC, &ts));
963 if (r < 0) Scm_SysError("clock_getres failed");
964 *sec = (u_long)ts.tv_sec;
965 *nsec = (u_long)ts.tv_nsec;
966 return TRUE;
967 #else /*!HAVE_CLOCK_GETRES*/
968 *sec = *nsec = 0;
969 return FALSE;
970 #endif /*!HAVE_CLOCK_GETRES*/
971 }
972
973
974 /* Experimental. This returns the microsecond-resolution time, wrapped
975 around the fixnum resolution. In 32-bit architecture it's a bit more
976 than 1000seconds. Good for micro-profiling, since this guarantees
977 no allocation. Returned value can be negative. */
978 long Scm_CurrentMicroseconds()
979 {
980 u_long sec, usec;
981 Scm_GetTimeOfDay(&sec, &usec);
982 /* we ignore overflow */
983 usec += sec * 1000000;
984 usec &= (1UL<<(SCM_SMALL_INT_SIZE+1)) - 1;
985 if (usec > SCM_SMALL_INT_MAX) usec -= (1UL<<(SCM_SMALL_INT_SIZE+1));
986 return (long)usec;
987 }
988
989 ScmObj Scm_CurrentTime(void)
990 {
991 u_long sec, usec;
992 Scm_GetTimeOfDay(&sec, &usec);
993 return Scm_MakeTime(SCM_SYM_TIME_UTC, sec, usec*1000);
994 }
995
996 ScmObj Scm_IntSecondsToTime(long sec)
997 {
998 return Scm_MakeTime(SCM_SYM_TIME_UTC, sec, 0);
999 }
1000
1001 ScmObj Scm_Int64SecondsToTime(int64_t sec)
1002 {
1003 return Scm_MakeTime64(SCM_SYM_TIME_UTC, sec, 0);
1004 }
1005
1006 ScmObj Scm_RealSecondsToTime(double sec)
1007 {
1008 double s;
1009 double frac = modf(sec, &s);
1010 int64_t secs = (int64_t)s;
1011 return Scm_MakeTime64(SCM_SYM_TIME_UTC, secs, (long)(frac * 1.0e9));
1012 }
1013
1014 static ScmObj time_type_get(ScmTime *t)
1015 {
1016 return t->type;
1017 }
1018
1019 static void time_type_set(ScmTime *t, ScmObj val)
1020 {
1021 if (!SCM_SYMBOLP(val)) {
1022 Scm_Error("time type must be a symbol, but got %S", val);
1023 }
1024 t->type = val;
1025 }
1026
1027 static ScmObj time_sec_get(ScmTime *t)
1028 {
1029 return Scm_MakeInteger64(t->sec);
1030 }
1031
1032 static void time_sec_set(ScmTime *t, ScmObj val)
1033 {
1034 if (!SCM_REALP(val)) {
1035 Scm_Error("real number required, but got %S", val);
1036 }
1037 t->sec = Scm_GetInteger64(val);
1038 }
1039
1040 static ScmObj time_nsec_get(ScmTime *t)
1041 {
1042 return Scm_MakeInteger(t->nsec);
1043 }
1044
1045 static void time_nsec_set(ScmTime *t, ScmObj val)
1046 {
1047 if (!SCM_REALP(val)) {
1048 Scm_Error("real number required, but got %S", val);
1049 }
1050 long l = Scm_GetInteger(val);
1051 if (l >= 1000000000) {
1052 Scm_Error("nanoseconds out of range: %ld", l);
1053 }
1054 t->nsec = l;
1055 }
1056
1057 static ScmClassStaticSlotSpec time_slots[] = {
1058 SCM_CLASS_SLOT_SPEC("type", time_type_get, time_type_set),
1059 SCM_CLASS_SLOT_SPEC("second", time_sec_get, time_sec_set),
1060 SCM_CLASS_SLOT_SPEC("nanosecond", time_nsec_get, time_nsec_set),
1061 SCM_CLASS_SLOT_SPEC_END()
1062 };
1063
1064 /* time_t and conversion routines */
1065 /* NB: I assume time_t is typedefed to either an integral type or
1066 * a floating point type. As far as I know it is true on most
1067 * current architectures. POSIX doesn't specify so, however; it
1068 * may be some weird structure. If you find such an architecture,
1069 * tweak configure.in and modify the following two functions.
1070 */
1071 ScmObj Scm_MakeSysTime(time_t t)
1072 {
1073 #ifdef INTEGRAL_TIME_T
1074 return Scm_MakeIntegerFromUI((unsigned long)t);
1075 #else
1076 double val = (double)t;
1077 return Scm_MakeFlonum(val);
1078 #endif
1079 }
1080
1081 time_t Scm_GetSysTime(ScmObj val)
1082 {
1083 if (SCM_TIMEP(val)) {
1084 #ifdef INTEGRAL_TIME_T
1085 return (time_t)SCM_TIME(val)->sec;
1086 #else
1087 return (time_t)(Scm_Int64ToDouble(SCM_TIME(val)->sec) +
1088 (double)SCM_TIME(val)->nsec/1.0e9);
1089 #endif
1090 } else if (SCM_NUMBERP(val)) {
1091 #ifdef INTEGRAL_TIME_T
1092 return (time_t)Scm_GetUInteger(val);
1093 #else
1094 return (time_t)Scm_GetDouble(val);
1095 #endif
1096 } else {
1097 Scm_Error("bad time value: either a <time> object or a real number is required, but got %S", val);
1098 return (time_t)0; /* dummy */
1099 }
1100 }
1101
1102 /* strftime
1103 * On MinGW, strftime() returns a multibyte string in the system's language
1104 * setting. Unfortunately, wcsftime() seems broken and unusable
1105 * (cf. https://github.com/shirok/Gauche/pull/809 )
1106 * This is the common compatibility routine. The third argument is
1107 * reserved for future extension to specify a locale.
1108 */
1109 ScmObj Scm_StrfTime(const char *format,
1110 const struct tm *tm,
1111 ScmObj reserved SCM_UNUSED)
1112 {
1113 #if !defined(GAUCHE_WINDOWS) || !defined(UNICODE)
1114 const char *format1 = format;
1115 #else /* defined(GAUCHE_WINDOWS) && defined(UNICODE) */
1116 /* convert utf-8 to MB string */
1117 const wchar_t *wformat = Scm_MBS2WCS(format);
1118 int nb = WideCharToMultiByte(CP_ACP, 0, wformat, -1, NULL, 0, 0, 0);
1119 if (nb == 0) Scm_Error("strftime() failed (WideCharToMultiByte NULL)");
1120 char *format1 = SCM_NEW_ATOMIC_ARRAY(char, nb);
1121 if (WideCharToMultiByte(CP_ACP, 0, wformat, -1, format1, nb, 0, 0) == 0) {
1122 Scm_Error("strftime() failed (WideCharToMultiByte)");
1123 }
1124 #endif /* defined(GAUCHE_WINDOWS) && defined(UNICODE) */
1125
1126 size_t bufsiz = strlen(format1) + 30;
1127 char *buf = SCM_NEW_ATOMIC2(char*, bufsiz);
1128
1129 /* NB: Zero return value may mean the buffer size is not enough, OR
1130 the actual output is an empty string. We can't know which is the
1131 case. Here we give a few tries. */
1132 size_t r = 0;
1133 for (int retry = 0; retry < 3; retry++) {
1134 r = strftime(buf, bufsiz, format1, tm);
1135 if (r > 0) break;
1136 bufsiz *= 2;
1137 buf = SCM_NEW_ATOMIC2(char*, bufsiz);
1138 }
1139 if (r == 0) return SCM_MAKE_STR_IMMUTABLE("");
1140
1141 #if !defined(GAUCHE_WINDOWS) || !defined(UNICODE)
1142 return Scm_MakeString(buf, r, -1, SCM_STRING_COPYING);
1143 #else /* defined(GAUCHE_WINDOWS) && defined(UNICODE) */
1144 /* Here, buf contains MB string in system's language setting.
1145 Ensure we have utf-8 encoding.
1146 */
1147 int nc = MultiByteToWideChar(CP_ACP, 0, buf, -1, NULL, 0);
1148 if (nc == 0) Scm_Error("strftime() failed (MultiByteToWideChar NULL)");
1149 wchar_t *wb = SCM_NEW_ATOMIC_ARRAY(wchar_t, nc);
1150 if (MultiByteToWideChar(CP_ACP, 0, buf, -1, wb, nc) == 0) {
1151 Scm_Error("strftime() failed (MultiByteToWideChar)");
1152 }
1153 return Scm_MakeString(Scm_WCS2MBS(wb), -1, -1, SCM_STRING_COPYING);
1154 #endif /* defined(GAUCHE_WINDOWS) && defined(UNICODE) */
1155 }
1156
1157
1158 ScmObj Scm_TimeToSeconds(ScmTime *t)
1159 {
1160 if (t->nsec) {
1161 return Scm_MakeFlonum((double)(t->sec) + (double)t->nsec/1.0e9);
1162 } else {
1163 return Scm_MakeInteger64(t->sec);
1164 }
1165 }
1166
1167 #define NSECS_IN_A_SEC 1000000000 /* 1e9 */
1168
1169 /* Scheme time -> timespec conversion */
1170 ScmTimeSpec *Scm_ToTimeSpec(ScmObj t, ScmTime *t0, ScmTimeSpec *spec)
1171 {
1172 if (SCM_FALSEP(t)) return NULL;
1173 if (SCM_TIMEP(t)) {
1174 if (SCM_EQ(SCM_TIME(t)->type, SCM_SYM_TIME_UTC)) {
1175 spec->tv_sec = SCM_TIME(t)->sec;
1176 spec->tv_nsec = SCM_TIME(t)->nsec;
1177 } else if (SCM_EQ(SCM_TIME(t)->type, SCM_SYM_TIME_DURATION)) {
1178 ScmTime *ct = t0 ? t0 : SCM_TIME(Scm_CurrentTime());
1179 spec->tv_sec = ct->sec + SCM_TIME(t)->sec;
1180 spec->tv_nsec = ct->nsec + SCM_TIME(t)->nsec; /* always positive */
1181 while (spec->tv_nsec >= NSECS_IN_A_SEC) {
1182 spec->tv_nsec -= NSECS_IN_A_SEC;
1183 spec->tv_sec += 1;
1184 }
1185 }
1186 } else if (!SCM_REALP(t)) {
1187 Scm_Error("bad time spec: <time> object, real number, or #f is required, but got %S", t);
1188 } else {
1189 ScmTime *ct = t0? t0 : SCM_TIME(Scm_CurrentTime());
1190 spec->tv_sec = ct->sec;
1191 spec->tv_nsec = ct->nsec;
1192 if (SCM_INTP(t)) {
1193 spec->tv_sec += Scm_GetInteger(t);
1194 } else if (!SCM_REALP(t)) {
1195 Scm_Panic("implementation error: Scm_GetTimeSpec: something wrong");
1196 } else {
1197 double s;
1198 spec->tv_nsec += (long)(modf(Scm_GetDouble(t), &s)*1.0e9);
1199 spec->tv_sec += (long)s;
1200 while (spec->tv_nsec >= NSECS_IN_A_SEC) {
1201 spec->tv_nsec -= NSECS_IN_A_SEC;
1202 spec->tv_sec += 1;
1203 }
1204 while (spec->tv_nsec < 0) {
1205 spec->tv_nsec += NSECS_IN_A_SEC;
1206 spec->tv_sec -= 1;
1207 }
1208 }
1209 }
1210 return spec;
1211 }
1212
1213 /* Backward compatibility */
1214 ScmTimeSpec *Scm_GetTimeSpec(ScmObj t, ScmTimeSpec *spec)
1215 {
1216 return Scm_ToTimeSpec(t, NULL, spec);
1217 }
1218
1219 /*
1220 * nanosleep() compatibility layer
1221 */
1222 int Scm_NanoSleep(const ScmTimeSpec *req, ScmTimeSpec *rem)
1223 {
1224 #if defined(GAUCHE_WINDOWS)
1225 /* Recent mingw32 includes nanosleep but it seems broken, so we keep
1226 using this compatibility code for the time being. */
1227 DWORD msecs = 0;
1228 time_t sec;
1229 u_long overflow = 0, c;
1230 const DWORD MSEC_OVERFLOW = 4294967; /* 4294967*1000 = 0xfffffed8 */
1231
1232 /* It's very unlikely that we overflow msecs, but just in case... */
1233 if (req->tv_sec > 0 || (req->tv_sec == 0 && req->tv_nsec > 0)) {
1234 if ((unsigned)req->tv_sec >= MSEC_OVERFLOW) {
1235 overflow = req->tv_sec / MSEC_OVERFLOW;
1236 sec = req->tv_sec % MSEC_OVERFLOW;
1237 } else {
1238 sec = req->tv_sec;
1239 }
1240 msecs = (sec * 1000 + (req->tv_nsec + 999999)/1000000);
1241 }
1242 Sleep (msecs);
1243 for (c = 0; c < overflow; c++) {
1244 Sleep(MSEC_OVERFLOW * 1000);
1245 }
1246 if (rem) {
1247 rem->tv_sec = rem->tv_nsec = 0;
1248 }
1249 return 0;
1250 #elif defined(HAVE_NANOSLEEP)
1251 return nanosleep(req, rem);
1252 #else /* !defined(HAVE_NANOSLEEP) && !defined(GAUCHE_WINDOWS) */
1253 /* This case should be excluded at the caller site */
1254 errno = EINVAL;
1255 return -1;
1256 #endif
1257 }
1258
1259 /*===============================================================
1260 * Yielding CPU (sched.h, if available)
1261 */
1262
1263 /* If sched_yield is not available, we make the calling thread sleep
1264 small amount of time, hoping there are other threads that can run
1265 in place. */
1266 void
1267 Scm_YieldCPU(void)
1268 {
1269 #if defined(GAUCHE_WINDOWS)
1270 /* Windows have select(), but it doesn't allow all fds are NULL. */
1271 Sleep(0);
1272 #elif defined(HAVE_SCHED_YIELD)
1273 sched_yield();
1274 #elif defined(HAVE_NANOSLEEP)
1275 /* We can use struct timespec instead of ScmTimeSpec here, for mingw
1276 won't use this path. */
1277 struct timespec spec;
1278 spec.tv_sec = 0;
1279 spec.tv_nsec = 1;
1280 nanosleep(&spec, NULL);
1281 #elif defined(HAVE_SELECT)
1282 struct timeval tv;
1283 tv.tv_sec = 0;
1284 tv.tv_usec = 1;
1285 select(0, NULL, NULL, NULL, &tv);
1286 #else /* the last resort */
1287 sleep(1);
1288 #endif
1289 }
1290
1291 /*===============================================================
1292 * Groups (grp.h)
1293 */
1294
1295 static void grp_print(ScmObj obj, ScmPort *port, ScmWriteContext *ctx SCM_UNUSED)
1296 {
1297 Scm_Printf(port, "#<sys-group %S>",
1298 SCM_SYS_GROUP(obj)->name);
1299 }
1300
1301 static int grp_compare(ScmObj x, ScmObj y, int equalp)
1302 {
1303 ScmSysGroup *gx = SCM_SYS_GROUP(x);
1304 ScmSysGroup *gy = SCM_SYS_GROUP(y);
1305
1306 if (equalp) {
1307 return (Scm_EqualP(gx->name, gy->name)
1308 && Scm_EqualP(gx->gid, gy->gid)
1309 && Scm_EqualP(gx->passwd, gy->passwd)
1310 && Scm_EqualP(gx->mem, gy->mem));
1311 } else {
1312 /* This is arbitrary, but having some order allows the object
1313 to be used as a key in treemap. */
1314 int r = Scm_Compare(gx->gid, gy->gid);
1315 if (r != 0) return r;
1316 r = Scm_Compare(gx->name, gy->name);
1317 if (r != 0) return r;
1318 r = Scm_Compare(gx->passwd, gy->passwd);
1319 if (r != 0) return r;
1320 return Scm_Compare(gx->mem, gy->mem);
1321 }
1322 }
1323
1324 static ScmSmallInt grp_hash(ScmObj obj, ScmSmallInt salt, u_long flags)
1325 {
1326 ScmSysGroup *g = SCM_SYS_GROUP(obj);
1327 ScmSmallInt h = salt;
1328 h = Scm_CombineHashValue(Scm_RecursiveHash(g->name, salt, flags), h);
1329 h = Scm_CombineHashValue(Scm_RecursiveHash(g->gid, salt, flags), h);
1330 h = Scm_CombineHashValue(Scm_RecursiveHash(g->passwd, salt, flags), h);
1331 h = Scm_CombineHashValue(Scm_RecursiveHash(g->mem, salt, flags), h);
1332 return h;
1333 }
1334
1335 SCM_DEFINE_BUILTIN_CLASS(Scm_SysGroupClass,
1336 grp_print, grp_compare, grp_hash,
1337 NULL, SCM_CLASS_DEFAULT_CPL);
1338
1339 static ScmObj make_group(struct group *g)
1340 {
1341 ScmSysGroup *sg = SCM_NEW(ScmSysGroup);
1342 SCM_SET_CLASS(sg, SCM_CLASS_SYS_GROUP);
1343
1344 sg->name = SCM_MAKE_STR_COPYING(g->gr_name);
1345 #ifdef HAVE_STRUCT_GROUP_GR_PASSWD
1346 sg->passwd = SCM_MAKE_STR_COPYING(g->gr_passwd);
1347 #else
1348 sg->passwd = SCM_FALSE;
1349 #endif
1350 sg->gid = Scm_MakeInteger(g->gr_gid);
1351 sg->mem = Scm_CStringArrayToList((const char**)g->gr_mem, -1,
1352 SCM_MAKSTR_COPYING);
1353 return SCM_OBJ(sg);
1354 }
1355
1356 ScmObj Scm_GetGroupById(gid_t gid)
1357 {
1358 struct group *gdata = getgrgid(gid);
1359 if (gdata == NULL) {
1360 Scm_SigCheck(Scm_VM());
1361 return SCM_FALSE;
1362 } else {
1363 return make_group(gdata);
1364 }
1365 }
1366
1367 ScmObj Scm_GetGroupByName(ScmString *name)
1368 {
1369 struct group *gdata = getgrnam(Scm_GetStringConst(name));
1370 if (gdata == NULL) {
1371 Scm_SigCheck(Scm_VM());
1372 return SCM_FALSE;
1373 } else {
1374 return make_group(gdata);
1375 }
1376 }
1377
1378 #define GRP_GETTER(name) \
1379 static ScmObj SCM_CPP_CAT3(grp_, name, _get)(ScmSysGroup *s) \
1380 { return s->name; }
1381
1382 GRP_GETTER(name)
1383 GRP_GETTER(gid)
1384 GRP_GETTER(passwd)
1385 GRP_GETTER(mem)
1386
1387 static ScmClassStaticSlotSpec grp_slots[] = {
1388 SCM_CLASS_SLOT_SPEC("name", grp_name_get, NULL),
1389 SCM_CLASS_SLOT_SPEC("gid", grp_gid_get, NULL),
1390 SCM_CLASS_SLOT_SPEC("passwd", grp_passwd_get, NULL),
1391 SCM_CLASS_SLOT_SPEC("mem", grp_mem_get, NULL),
1392 SCM_CLASS_SLOT_SPEC_END()
1393 };
1394
1395 /*===============================================================
1396 * Passwords (pwd.h)
1397 * Patch provided by Yuuki Takahashi ([email protected])
1398 */
1399
1400 static void pwd_print(ScmObj obj, ScmPort *port,
1401 ScmWriteContext *ctx SCM_UNUSED)
1402 {
1403 Scm_Printf(port, "#<sys-passwd %S>",
1404 SCM_SYS_PASSWD(obj)->name);
1405 }
1406
1407 SCM_DEFINE_BUILTIN_CLASS_SIMPLE(Scm_SysPasswdClass, pwd_print);
1408
1409 static ScmObj make_passwd(struct passwd *pw)
1410 {
1411 ScmSysPasswd *sp = SCM_NEW(ScmSysPasswd);
1412 SCM_SET_CLASS(sp, SCM_CLASS_SYS_PASSWD);
1413
1414 sp->name = SCM_MAKE_STR_COPYING(pw->pw_name);
1415 sp->uid = Scm_MakeInteger(pw->pw_uid);
1416 sp->gid = Scm_MakeInteger(pw->pw_gid);
1417 #ifdef HAVE_STRUCT_PASSWD_PW_PASSWD
1418 sp->passwd = SCM_MAKE_STR_COPYING(pw->pw_passwd);
1419 #else
1420 sp->passwd = SCM_FALSE;
1421 #endif
1422 #ifdef HAVE_STRUCT_PASSWD_PW_GECOS
1423 sp->gecos = SCM_MAKE_STR_COPYING(pw->pw_gecos);
1424 #else
1425 sp->gecos = SCM_FALSE;
1426 #endif
1427 #ifdef HAVE_STRUCT_PASSWD_PW_CLASS
1428 sp->pwclass = SCM_MAKE_STR_COPYING(pw->pw_class);
1429 #else
1430 sp->pwclass = SCM_FALSE;
1431 #endif
1432 sp->dir = SCM_MAKE_STR_COPYING(pw->pw_dir);
1433 sp->shell = SCM_MAKE_STR_COPYING(pw->pw_shell);
1434 return SCM_OBJ(sp);
1435 }
1436
1437 ScmObj Scm_GetPasswdById(uid_t uid)
1438 {
1439 struct passwd *pdata = getpwuid(uid);
1440 if (pdata == NULL) {
1441 Scm_SigCheck(Scm_VM());
1442 return SCM_FALSE;
1443 } else {
1444 return make_passwd(pdata);
1445 }
1446 }
1447
1448 ScmObj Scm_GetPasswdByName(ScmString *name)
1449 {
1450 struct passwd *pdata = getpwnam(Scm_GetStringConst(name));
1451 if (pdata == NULL) {
1452 Scm_SigCheck(Scm_VM());
1453 return SCM_FALSE;
1454 } else {
1455 return make_passwd(pdata);
1456 }
1457 }
1458
1459 #define PWD_GETTER(name) \
1460 static ScmObj SCM_CPP_CAT3(pwd_, name, _get)(ScmSysPasswd *p) \
1461 { return p->name; }
1462
1463 PWD_GETTER(name)
1464 PWD_GETTER(uid)
1465 PWD_GETTER(gid)
1466 PWD_GETTER(passwd)
1467 PWD_GETTER(gecos)
1468 PWD_GETTER(dir)
1469 PWD_GETTER(shell)
1470 PWD_GETTER(pwclass)
1471
1472 static ScmClassStaticSlotSpec pwd_slots[] = {
1473 SCM_CLASS_SLOT_SPEC("name", pwd_name_get, NULL),
1474 SCM_CLASS_SLOT_SPEC("uid", pwd_uid_get, NULL),
1475 SCM_CLASS_SLOT_SPEC("gid", pwd_gid_get, NULL),
1476 SCM_CLASS_SLOT_SPEC("passwd", pwd_passwd_get, NULL),
1477 SCM_CLASS_SLOT_SPEC("gecos", pwd_gecos_get, NULL),
1478 SCM_CLASS_SLOT_SPEC("dir", pwd_dir_get, NULL),
1479 SCM_CLASS_SLOT_SPEC("shell", pwd_shell_get, NULL),
1480 SCM_CLASS_SLOT_SPEC("class", pwd_pwclass_get, NULL),
1481 SCM_CLASS_SLOT_SPEC_END()
1482 };
1483
1484 /*
1485 * Check if we're suid/sgid-ed.
1486 */
1487
1488 /* We "remember" the initial state, in case issetugid() isn't available.
1489 This isn't perfect, for the process may change euid/egid before calling
1490 Scm_Init(). */
1491 static int initial_ugid_differ = FALSE;
1492
1493 int Scm_IsSugid(void)
1494 {
1495 #if HAVE_ISSETUGID
1496 return issetugid();
1497 #else
1498 return initial_ugid_differ;
1499 #endif /* GAUCHE_WINDOWS */
1500 }
1501
1502 /*===============================================================
1503 * Process management
1504 */
1505
1506 /* Child process management (windows only)
1507 * On windows, parent-child relationship is very weak. The system
1508 * records parent's pid (and we can query it in a very twisted way), but
1509 * the child's process record is discarded upon child's termination
1510 * unless the parent keeps its process handle. To emulate exec-wait
1511 * semantics, we keep the list of child process handles whose status is
1512 * unclaimed.
1513 * One issue is that we cannot wait() for child processes that
1514 * are created by Gauche extension code and not using Scm_SysExec API.
1515 */
1516 #if defined(GAUCHE_WINDOWS)
1517 static struct process_mgr_rec {
1518 ScmObj children;
1519 ScmInternalMutex mutex;
1520 } process_mgr = { SCM_NIL, SCM_INTERNAL_MUTEX_INITIALIZER };
1521
1522 ScmObj win_process_register(ScmObj process)
1523 {
1524 SCM_ASSERT(Scm_WinProcessP(process));
1525 ScmObj pair = Scm_Cons(process, SCM_NIL);
1526 SCM_INTERNAL_MUTEX_LOCK(process_mgr.mutex);
1527 SCM_SET_CDR_UNCHECKED(pair, process_mgr.children);
1528 process_mgr.children = pair;
1529 SCM_INTERNAL_MUTEX_UNLOCK(process_mgr.mutex);
1530 return process;
1531 }
1532
1533 ScmObj win_process_unregister(ScmObj process)
1534 {
1535 SCM_INTERNAL_MUTEX_LOCK(process_mgr.mutex);
1536 process_mgr.children = Scm_DeleteX(process, process_mgr.children,
1537 SCM_CMP_EQ);
1538 SCM_INTERNAL_MUTEX_UNLOCK(process_mgr.mutex);
1539 return process;
1540 }
1541
1542 int win_process_active_child_p(ScmObj process)
1543 {
1544 SCM_INTERNAL_MUTEX_LOCK(process_mgr.mutex);
1545 ScmObj r = Scm_Member(process, process_mgr.children, SCM_CMP_EQ);
1546 SCM_INTERNAL_MUTEX_UNLOCK(process_mgr.mutex);
1547 return !SCM_FALSEP(r);
1548 }
1549
1550 ScmObj *win_process_get_array(int *size /*out*/)
1551 {
1552 SCM_INTERNAL_MUTEX_LOCK(process_mgr.mutex);
1553 ScmSize array_size;
1554 ScmObj *r = Scm_ListToArray(process_mgr.children, &array_size, NULL, TRUE);
1555 *size = (int)array_size;
1556 SCM_INTERNAL_MUTEX_UNLOCK(process_mgr.mutex);
1557 return r;
1558 }
1559
1560 void win_process_cleanup(void *data SCM_UNUSED)
1561 {
1562 SCM_INTERNAL_MUTEX_LOCK(process_mgr.mutex);
1563 ScmObj cp;
1564 SCM_FOR_EACH(cp, process_mgr.children) {
1565 CloseHandle(Scm_WinHandle(SCM_CAR(cp), SCM_FALSE));
1566 }
1567 process_mgr.children = SCM_NIL;
1568 SCM_INTERNAL_MUTEX_UNLOCK(process_mgr.mutex);
1569 }
1570 #endif /*GAUCHE_WINDOWS*/
1571
1572 /* Command line construction (Windows only)
1573 * In order to use CreateProcess we have to concatenate all arguments
1574 * into one command line string. Proper escaping should be considered
1575 * when the arguments include whitespaces or double-quotes.
1576 * It's pretty silly that we have to do this, since the child process
1577 * crt will re-parse the command line again. Besides, since the parsing
1578 * of the command line is up to each application, THERE IS NO WAY TO
1579 * GUARANTEE TO QUOTE THE ARGUMENTS PROPERLY. This is intolerably
1580 * broken specification.
1581 *
1582 * If the program to run is .BAT or .CMD file, it is possible to
1583 * manufacture an argument that injects undesired command execution.
1584 * It is practically impossible to avoid the situation, so we rejects
1585 * such an argument in the case. See:
1586 * https://flatt.tech/research/posts/batbadbut-you-cant-securely-execute-commands-on-windows/
1587 */
1588 #if defined(GAUCHE_WINDOWS)
1589 static _Bool unsafe_program(TCHAR *program_path, int program_path_len)
1590 {
1591 if (program_path_len < 4) return FALSE;
1592 TCHAR *extp = program_path + program_path_len - 4;
1593 if (*extp != '.') return FALSE;
1594 if ((extp[1] == 'b' || extp[1] == 'B')
1595 && (extp[2] == 'a' || extp[2] == 'A')
1596 && (extp[3] == 't' || extp[3] == 'T'))
1597 return TRUE;
1598 if ((extp[1] == 'c' || extp[1] == 'C')
1599 && (extp[2] == 'm' || extp[2] == 'M')
1600 && (extp[3] == 'd' || extp[3] == 'D'))
1601 return TRUE;
1602 return FALSE;
1603 }
1604
1605 static char *win_create_command_line(TCHAR *program_path,
1606 int program_path_len,
1607 ScmObj args)
1608 {
1609 static ScmObj proc = SCM_UNDEFINED;
1610 SCM_BIND_PROC(proc, "%sys-escape-windows-command-line", Scm_GaucheModule());
1611
1612 _Bool unsafep = unsafe_program(program_path, program_path_len);
1613 ScmObj ostr = Scm_MakeOutputStringPort(TRUE);
1614 ScmObj ap;
1615 SCM_FOR_EACH(ap, args) {
1616 ScmObj escaped = Scm_ApplyRec2(proc, SCM_CAR(ap), SCM_MAKE_BOOL(unsafep));
1617 Scm_Printf(SCM_PORT(ostr), "%A ", escaped);
1618 }
1619 ScmObj out = Scm_GetOutputStringUnsafe(SCM_PORT(ostr), 0);
1620 return Scm_GetString(SCM_STRING(out));
1621 }
1622 #endif /*GAUCHE_WINDOWS*/
1623
1624 /* Scm_SysExec
1625 * execvp(), with optionally setting stdios correctly.
1626 *
1627 * iomap argument, when provided, specifies how the open file descriptors
1628 * are treated. If it is not a pair, nothing will be changed for open
1629 * file descriptors. If it is a pair, it must be a list of
1630 * (<to> . <from>), where <tofd> is an integer file descriptor that
1631 * executed process will get, and <from> is either an integer file descriptor
1632 * or a port. If a list is passed to iomap, any file descriptors other
1633 * than specified in the list will be closed before exec().
1634 *
1635 * If forkp arg is TRUE, this function forks before swapping file
1636 * descriptors. It is more reliable way to fork&exec in multi-threaded
1637 * program. In such a case, this function returns Scheme integer to
1638 * show the children's pid. If fork arg is FALSE, this procedure
1639 * of course never returns.
1640 *
1641 * On Windows port, this returns a process handle obejct instead of
1642 * pid of the child process in fork mode. We need to keep handle, or
1643 * the process exit status will be lost when the child process terminates.
1644 */
1645 ScmObj Scm_SysExec(ScmString *file, ScmObj args, ScmObj iomap,
1646 ScmSysSigset *mask SCM_UNUSED, ScmString *dir,
1647 ScmObj env, u_long flags)
1648 {
1649 int argc = Scm_Length(args);
1650 int forkp = flags & SCM_EXEC_WITH_FORK;
1651 int detachp = flags & SCM_EXEC_DETACHED;
1652
1653 if (argc < 1) {
1654 Scm_Error("argument list must have at least one element: %S", args);
1655 }
1656
1657 /* make a C array of C strings */
1658 char **argv = Scm_ListToCStringArray(args, TRUE, NULL);
1659
1660 /* setting up iomap table */
1661 int *fds = Scm_SysPrepareFdMap(iomap);
1662
1663 /* find executable.
1664 If FILE contains path separators, we don't use path search.
1665 */
1666 const char *program;
1667 if (SCM_FALSEP(Scm_StringScanChar(file, '/', SCM_STRING_SCAN_INDEX))
1668 #if defined(GAUCHE_WINDOWS)
1669 && SCM_FALSEP(Scm_StringScanChar(file, '\\', SCM_STRING_SCAN_INDEX))
1670 #endif
1671 ) {
1672 static ScmObj sys_find_file_proc = SCM_UNDEFINED;
1673 SCM_BIND_PROC(sys_find_file_proc, "sys-find-file", Scm_GaucheModule());
1674 ScmObj fullpath = Scm_ApplyRec1(sys_find_file_proc, SCM_OBJ(file));
1675 if (!SCM_STRINGP(fullpath)) {
1676 Scm_Error("Can't find executable file %S in PATH.", SCM_OBJ(file));
1677 }
1678 program = Scm_GetStringConst(SCM_STRING(fullpath));
1679 } else {
1680 program = Scm_GetStringConst(file);
1681 }
1682
1683 /*
1684 * From now on, we have totally different code for Unix and Windows.
1685 */
1686 #if !defined(GAUCHE_WINDOWS)
1687 /*
1688 * Unix path
1689 */
1690 const char *cdir = NULL;
1691 if (dir != NULL) cdir = Scm_GetStringConst(dir);
1692
1693 /* When requested, call fork() here. */
1694 pid_t pid = 0;
1695 if (forkp) {
1696 SCM_SYSCALL(pid, fork());
1697 if (pid < 0) Scm_SysError("fork failed");
1698 }
1699
1700 if (!forkp || pid == 0) { /* possibly the child process */
1701
1702 /* If we're running the daemon, we fork again to detach the parent,
1703 and also reset the session id. */
1704 if (detachp) {
1705 SCM_SYSCALL(pid, fork());
1706 if (pid < 0) Scm_SysError("fork failed");
1707 if (pid > 0) exit(0); /* not Scm_Exit(), for we don't want to
1708 run the cleanup stuff. */
1709 setsid();
1710 }
1711
1712 if (cdir != NULL) {
1713 if (chdir(cdir) < 0) {
1714 Scm_Panic("chdir to %s failed before executing %s: %s",
1715 cdir, program, strerror(errno));
1716 }
1717 }
1718
1719 Scm_SysSwapFds(fds);
1720 if (mask) {
1721 Scm_ResetSignalHandlers(&mask->set);
1722 Scm_SysSigmask(SIG_SETMASK, mask);
1723 }
1724
1725 if (SCM_LISTP(env)) {
1726 execve(program, (char *const*)argv,
1727 Scm_ListToCStringArray(env, TRUE, NULL));
1728 } else {
1729 execv(program, (char *const*)argv);
1730 }
1731 /* here, we failed */
1732 Scm_Panic("exec failed: %s: %s", program, strerror(errno));
1733 }
1734
1735 /* We come here only when fork is requested. */
1736 return Scm_MakeInteger(pid);
1737 #else /* GAUCHE_WINDOWS */
1738 /*
1739 * Windows path
1740 */
1741 const char *cdir = NULL;
1742 if (dir != NULL) {
1743 /* we need full path for CreateProcess. */
1744 dir = SCM_STRING(Scm_NormalizePathname(dir, SCM_PATH_ABSOLUTE|SCM_PATH_CANONICALIZE));
1745 cdir = Scm_GetStringConst(dir);
1746
1747 /* If the program is given in relative pathname,
1748 it must be adjusted relative to the specified directory. */
1749 if (program[0] != '/' && program[0] != '\\'
1750 && !(program[0] && program[1] == ':')) {
1751 ScmDString ds;
1752 int c = cdir[strlen(cdir)-1];
1753 Scm_DStringInit(&ds);
1754 Scm_DStringPutz(&ds, cdir, -1);
1755 if (c != '/' && c != '\\') Scm_DStringPutc(&ds, SCM_CHAR('/'));
1756 Scm_DStringPutz(&ds, program, -1);
1757 program = Scm_DStringGetz(&ds);
1758 }
1759 }
1760
1761 if (forkp) {
1762 TCHAR program_path[MAX_PATH+1], *filepart;
1763 win_redirects *hs = win_prepare_handles(fds);
1764 PROCESS_INFORMATION pi;
1765 DWORD creation_flags = 0;
1766
1767 DWORD pathlen = SearchPath(NULL, SCM_MBS2WCS(program),
1768 _T(".exe"), MAX_PATH, program_path,
1769 &filepart);
1770 if (pathlen == 0) Scm_SysError("cannot find program '%s'", program);
1771 program_path[pathlen] = 0;
1772
1773 STARTUPINFO si;
1774 GetStartupInfo(&si);
1775 if (hs != NULL) {
1776 si.dwFlags |= STARTF_USESTDHANDLES;
1777 si.hStdInput = hs[0].h;
1778 si.hStdOutput = hs[1].h;
1779 si.hStdError = hs[2].h;
1780 }
1781
1782 LPCTSTR curdir = NULL;
1783 if (cdir != NULL) curdir = SCM_MBS2WCS(cdir);
1784
1785 if (detachp) {
1786 creation_flags |= CREATE_NEW_PROCESS_GROUP;
1787 }
1788
1789 char *cmdline = win_create_command_line(program_path, pathlen, args);
1790
1791 TCHAR *tenvp = NULL;
1792 if (SCM_NULLP(env)) {
1793 /* CreateProcess rejects empty emvironemnt block.
1794 (cf. https://nullprogram.com/blog/2023/08/23/)
1795 We insert a dummy environemnt variable to workaround it.
1796 */
1797 env = SCM_LIST1(SCM_MAKE_STR("AVOID_EMPTY_ENVIRONMENT=1"));
1798 }
1799 if (SCM_LISTP(env)) {
1800 /* We need to consturct a TCHAR[] block that contains NUL
1801 characters, which gets tricky, for our utility MBS2WCS does
1802 not handle the case. This is not a performance critical
1803 path, so we allocage temporary strings abundantly.
1804 */
1805 size_t numenvs = Scm_Length(env);
1806 TCHAR **envs = SCM_NEW_ATOMIC_ARRAY(TCHAR*, numenvs);
1807 size_t nc = 0;
1808 ScmObj ep = env;
1809 for (size_t i = 0; i < numenvs; i++) {
1810 if (!(SCM_PAIRP(ep) && SCM_STRINGP(SCM_CAR(ep)))) {
1811 Scm_Error("Invalid environment list: %S", env);
1812 }
1813 envs[i] =
1814 Scm_MBS2WCS(Scm_GetStringConst(SCM_STRING(SCM_CAR(ep))));
1815 nc += _tcslen(envs[i]) + 1;
1816 ep = SCM_CDR(ep);
1817 }
1818 nc += 1;
1819
1820 tenvp = SCM_NEW_ATOMIC_ARRAY(TCHAR, nc);
1821 TCHAR *tp = tenvp;
1822 for (size_t i = 0; i < numenvs; i++) {
1823 size_t elen = _tcslen(envs[i])+1;
1824 memcpy(tp, envs[i], elen * sizeof(TCHAR));
1825 tp += elen;
1826 }
1827 *tp = 0;
1828 creation_flags |= CREATE_UNICODE_ENVIRONMENT;
1829 }
1830
1831 BOOL r = CreateProcess(program_path,
1832 SCM_MBS2WCS(cmdline),
1833 NULL, /* process attr */
1834 NULL, /* thread addr */
1835 TRUE, /* inherit handles */
1836 creation_flags, /* creation flags */
1837 tenvp, /* nenvironment */
1838 curdir, /* current dir */
1839 &si, /* startup info */
1840 &pi); /* process info */
1841 if (hs != NULL) {
1842 for (int i=0; i<3; i++) {
1843 /* hs[i].h may be a handle duped in win_prepare_handles().
1844 We have to close it in parent process or they would be
1845 inherited to subsequent child process. (The higher-level
1846 Scheme routine closes the open end of the pipe, but that
1847 won't affect the duped one. */
1848 if (hs[i].duped) CloseHandle(hs[i].h);
1849 }
1850 }
1851 if (r == 0) Scm_SysError("spawning %s failed", program);
1852 CloseHandle(pi.hThread); /* we don't need it. */
1853 return win_process_register(Scm_MakeWinProcess(pi.hProcess));
1854 } else {
1855 Scm_SysSwapFds(fds);
1856 if (cdir != NULL) {
1857 if (_chdir(cdir) < 0) {
1858 Scm_SysError("Couldn't chdir to %s", cdir);
1859 }
1860 }
1861 /* TODO: We should probably use Windows API to handle various
1862 options consistently with fork-and-exec case above. */
1863 #if defined(__MINGW64_VERSION_MAJOR)
1864 execvp(program, (char *const*)argv);
1865 #else /* !defined(__MINGW64_VERSION_MAJOR) */
1866 execvp(program, (const char *const*)argv);
1867 #endif /* !defined(__MINGW64_VERSION_MAJOR) */
1868 Scm_Panic("exec failed: %s: %s", program, strerror(errno));
1869 }
1870 return SCM_FALSE; /* dummy */
1871 #endif /* GAUCHE_WINDOWS */
1872 }
1873
1874 /* Two auxiliary functions to support iomap feature. They are exposed
1875 so that the library can implement iomap feature as the same way as
1876 sys-exec.
1877
1878 The first function, Scm_SysPrepareFdMap, walks iomap structure and
1879 prepare a table of file descriptors to modify. The second function,
1880 Scm_SysSwapFds, takes the table and modifies process's file descriptors.
1881
1882 We need to split this feature to two function, since it is unsafe
1883 to raise an error after fork() in multi-threaded environment.
1884 Scm_SysPrepareFdMap may throw an error if passed iomap contains
1885 invalid entries. On the other hand, Scm_SysSwapFds just aborts if
1886 things goes wrong---not only because of the MT-safety issue, but also
1887 it is generally impossible to handle errors reasonably since we don't
1888 even sure we have stdios. And the client code is supposed to call
1889 fork() between these functions.
1890
1891 The client code should treat the returned pointer of Scm_SysPrepareFdMap
1892 opaque, and pass it to Scm_SysSwapFds as is.
1893 */
1894 int *Scm_SysPrepareFdMap(ScmObj iomap)
1895 {
1896 int *fds = NULL;
1897 if (SCM_PAIRP(iomap)) {
1898 int iollen = Scm_Length(iomap);
1899
1900 /* check argument vailidity before duping file descriptors, so that
1901 we can still use Scm_Error */
1902 if (iollen < 0) {
1903 Scm_Error("proper list required for iolist, but got %S", iomap);
1904 }
1905 fds = SCM_NEW_ATOMIC2(int *, 2 * iollen * sizeof(int) + 1);
1906 fds[0] = iollen;
1907 int *tofd = fds + 1;
1908 int *fromfd = fds + 1 + iollen;
1909
1910 ScmObj iop;
1911 int i = 0;
1912 SCM_FOR_EACH(iop, iomap) {
1913 ScmObj port, elt = SCM_CAR(iop);
1914 if (!SCM_PAIRP(elt) || !SCM_INTP(SCM_CAR(elt))
1915 || (!SCM_PORTP(SCM_CDR(elt)) && !SCM_INTP(SCM_CDR(elt)))) {
1916 Scm_Error("bad iomap specification: needs (int . int-or-port): %S", elt);
1917 }
1918 tofd[i] = SCM_INT_VALUE(SCM_CAR(elt));
1919 if (SCM_INTP(SCM_CDR(elt))) {
1920 fromfd[i] = SCM_INT_VALUE(SCM_CDR(elt));
1921 } else {
1922 port = SCM_CDAR(iop);
1923 fromfd[i] = Scm_PortFileNo(SCM_PORT(port));
1924 if (fromfd[i] < 0) {
1925 Scm_Error("iolist requires a port that has associated file descriptor, but got %S",
1926 SCM_CDAR(iop));
1927 }
1928 if (tofd[i] == 0 && !SCM_IPORTP(port))
1929 Scm_Error("input port required to make it stdin: %S",
1930 port);
1931 if (tofd[i] == 1 && !SCM_OPORTP(port))
1932 Scm_Error("output port required to make it stdout: %S",
1933 port);
1934 if (tofd[i] == 2 && !SCM_OPORTP(port))
1935 Scm_Error("output port required to make it stderr: %S",
1936 port);
1937 }
1938 i++;
1939 }
1940 }
1941 return fds;
1942 }
1943
1944 void Scm_SysSwapFds(int *fds)
1945 {
1946 if (fds == NULL) return;
1947
1948 int maxfd;
1949 int nfds = fds[0];
1950 int *tofd = fds + 1;
1951 int *fromfd = fds + 1 + nfds;
1952
1953 /* TODO: use getdtablehi if available */
1954 #if !defined(GAUCHE_WINDOWS)
1955 if ((maxfd = sysconf(_SC_OPEN_MAX)) < 0) {
1956 Scm_Panic("failed to get OPEN_MAX value from sysconf");
1957 }
1958 #else /*GAUCHE_WINDOWS*/
1959 maxfd = 256; /* guess it and cross your finger */
1960 #endif /*GAUCHE_WINDOWS*/
1961
1962 /* Dup fromfd to the corresponding tofd. We need to be careful
1963 not to override the destination fd if it will be used. */
1964 for (int i=0; i<nfds; i++) {
1965 if (tofd[i] == fromfd[i]) continue;
1966 for (int j=i+1; j<nfds; j++) {
1967 if (tofd[i] == fromfd[j]) {
1968 int tmp = dup(tofd[i]);
1969 if (tmp < 0) Scm_Panic("dup failed: %s", strerror(errno));
1970 fromfd[j] = tmp;
1971 }
1972 }
1973 if (dup2(fromfd[i], tofd[i]) < 0)
1974 Scm_Panic("dup2 failed: %s", strerror(errno));
1975 }
1976
1977 /* Close unused fds */
1978 for (int fd=0; fd<maxfd; fd++) {
1979 int j;
1980 for (j=0; j<nfds; j++) if (fd == tofd[j]) break;
1981 if (j == nfds) close(fd);
1982 }
1983 }
1984
1985 #if defined(GAUCHE_WINDOWS)
1986 /* Fds is Scm_SysPrepareFdMap returns. */
1987 static win_redirects *win_prepare_handles(int *fds)
1988 {
1989 if (fds == NULL) return NULL;
1990
1991 /* For the time being, we only consider stdin, stdout, and stderr. */
1992 win_redirects *hs = SCM_NEW_ATOMIC_ARRAY(win_redirects, 3);
1993 int count = fds[0];
1994
1995 for (int i=0; i<count; i++) {
1996 int to = fds[i+1], from = fds[i+1+count];
1997 if (to >= 0 && to < 3) {
1998 if (from >= 3) {
1999 /* FROM may be a pipe. in that case, it will be closed
2000 in the higher-level, so we shouldn't give
2001 DUPLICATE_CLOSE_SOURCE here. */
2002 HANDLE zh;
2003 if (!DuplicateHandle(GetCurrentProcess(),
2004 (HANDLE)_get_osfhandle(from),
2005 GetCurrentProcess(),
2006 &zh,
2007 0, TRUE,
2008 DUPLICATE_SAME_ACCESS)) {
2009 Scm_SysError("DuplicateHandle failed");
2010 }
2011 hs[to].h = zh;
2012 hs[to].duped = TRUE;
2013 } else {
2014 hs[to].h = (HANDLE)_get_osfhandle(from);
2015 hs[to].duped = FALSE;
2016 }
2017 }
2018 }
2019 for (int i=0; i<3; i++) {
2020 if (hs[i].h == NULL) {
2021 hs[i].h = (HANDLE)_get_osfhandle(i);
2022 hs[i].duped = FALSE;
2023 }
2024 }
2025 return hs;
2026 }
2027 #endif /*GAUCHE_WINDOWS*/
2028
2029 /*===============================================================
2030 * Kill
2031 *
2032 * It is simple on Unix, but on windows it is a lot more involved,
2033 * mainly due to the lack of signals as the means of IPC.
2034 */
2035 void Scm_SysKill(ScmObj process, int signal)
2036 {
2037 #if !defined(GAUCHE_WINDOWS)
2038 pid_t pid;
2039 int r;
2040 if (!SCM_INTEGERP(process)) SCM_TYPE_ERROR(process, "integer process id");
2041 pid = Scm_GetInteger(process);
2042 SCM_SYSCALL(r, kill(pid, signal));
2043 if (r < 0) Scm_SysError("kill failed");
2044 #else /*GAUCHE_WINDOWS*/
2045 /* You cannot really "send" signals to other processes on Windows.
2046 We try to emulate SIGKILL and SIGINT by Windows API.
2047 To send a signal to the current process we can use raise(). */
2048 HANDLE p;
2049 BOOL r;
2050 DWORD errcode;
2051 int pid_given = FALSE;
2052 pid_t pid = 0;
2053
2054 if (SCM_INTEGERP(process)) {
2055 pid_given = TRUE; pid = Scm_GetInteger(process);
2056 } else if (Scm_WinProcessP(process)) {
2057 pid = Scm_WinProcessPID(process);
2058 } else {
2059 SCM_TYPE_ERROR(process, "process handle or integer process id");
2060 }
2061
2062 if (signal == SIGKILL) {
2063 if (pid_given) {
2064 p = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
2065 if (p == NULL) Scm_SysError("OpenProcess failed for pid %d", pid);
2066 } else {
2067 p = Scm_WinProcess(process);
2068 }
2069 /* We send 0xff00 + KILL, so that the receiving process (if it is
2070 Gauche) can yield an exit status that indicates it is kill. */
2071 r = TerminateProcess(p, SIGKILL+0xff00);
2072 errcode = GetLastError();
2073 if (pid_given) CloseHandle(p);
2074 SetLastError(errcode);
2075 if (r == 0) Scm_SysError("TerminateProcess failed");
2076 return;
2077 }
2078 /* another idea; we may map SIGTERM to WM_CLOSE message. */
2079
2080 if (signal == 0) {
2081 /* We're supposed to do the error check without actually sending
2082 the signal. For now we just pretend nothing's wrong. */
2083 return;
2084 }
2085 if (pid == getpid()) {
2086 /* we're sending signal to the current process. */
2087 int r = raise(signal); /* r==0 is success */
2088 if (r < 0) Scm_SysError("raise failed");
2089 return;
2090 }
2091 if (signal == SIGINT || signal == SIGABRT) {
2092 /* we can emulate these signals by console event, although the
2093 semantics of process group differ from unix significantly.
2094 Process group id is the same as the pid of the process
2095 that started the group. So you cannot send SIGABRT only
2096 to the process group leader. OTOH, for SIGINT, the windows
2097 manual says it always directed to the specified process,
2098 not the process group, unless pid == 0 */
2099 if (pid < 0) pid = -pid;
2100 r = GenerateConsoleCtrlEvent(pid,
2101 (signal == SIGINT)?
2102 CTRL_C_EVENT : CTRL_BREAK_EVENT);
2103 if (r == 0) {
2104 Scm_SysError("GenerateConsoleCtrlEvent failed for process %d", pid);
2105 }
2106 return;
2107 }
2108 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2109 #endif /*GAUCHE_WINDOWS*/
2110 }
2111
2112 /*===============================================================
2113 * Wait
2114 *
2115 * A wrapper of waitpid. Returns two values---the process object or pid that
2116 * whose status has been taken, and the exit status.
2117 * Again, it is simple on Unix, but on windows it is a lot more involved.
2118 */
2119
2120 ScmObj Scm_SysWait(ScmObj process, int options)
2121 {
2122 #if !defined(GAUCHE_WINDOWS)
2123 pid_t r;
2124 int status = 0;
2125 if (!SCM_INTEGERP(process)) SCM_TYPE_ERROR(process, "integer process id");
2126 SCM_SYSCALL(r, waitpid(Scm_GetInteger(process), &status, options));
2127 if (r < 0) Scm_SysError("waitpid() failed");
2128 return Scm_Values2(Scm_MakeInteger(r), Scm_MakeInteger(status));
2129 #else /* GAUCHE_WINDOWS */
2130 /* We have four cases
2131 process is integer and < -1 -> not supported.
2132 process is -1 or 0 -> wait for all children (we ignore process group)
2133 process is integer and > 0 -> wait for specific pid
2134 process is #<win:process-handle> -> wait for specified process
2135 The common op is factored out in win_wait_for_handles. */
2136 int r, status = 0;
2137
2138 if (SCM_INTEGERP(process)) {
2139 pid_t pid = Scm_GetInteger(process);
2140 if (pid < -1) {
2141 /* Windows doesn't have the concept of "process group id" */
2142 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2143 Scm_SysError("waitpid cannot wait for process group on Windows.");
2144 }
2145 if (pid > 0) {
2146 /* wait for specific pid */
2147 HANDLE handle = OpenProcess(SYNCHRONIZE|PROCESS_QUERY_INFORMATION,
2148 FALSE, pid);
2149 DWORD errcode;
2150 if (handle == NULL) {
2151 Scm_SysError("OpenProcess failed for pid %d", pid);
2152 }
2153 r = win_wait_for_handles(&handle, 1, options, &status);
2154 errcode = GetLastError();
2155 CloseHandle(handle);
2156 SetLastError(errcode);
2157 if (r == -2) goto timeout;
2158 if (r == -1) goto error;
2159 return Scm_Values2(Scm_MakeInteger(pid), Scm_MakeInteger(status));
2160 }
2161 else {
2162 /* wait for any children. */
2163 ScmObj *children;
2164 int num_children, i;
2165 HANDLE *handles;
2166 children = win_process_get_array(&num_children);
2167 if (num_children == 0) {
2168 SetLastError(ERROR_WAIT_NO_CHILDREN);
2169 Scm_SysError("waitpid failed");
2170 }
2171 handles = SCM_NEW_ATOMIC_ARRAY(HANDLE, num_children);
2172 for (i=0; i<num_children; i++) {
2173 handles[i] = Scm_WinProcess(children[i]);
2174 }
2175 r = win_wait_for_handles(handles, num_children, options, &status);
2176 if (r == -2) goto timeout;
2177 if (r == -1) goto error;
2178 win_process_unregister(children[r]);
2179 return Scm_Values2(children[r], Scm_MakeInteger(status));
2180 }
2181 } else if (Scm_WinProcessP(process)) {
2182 /* wait for the specified process */
2183 HANDLE handle;
2184 if (!win_process_active_child_p(process)) {
2185 SetLastError(ERROR_WAIT_NO_CHILDREN);
2186 Scm_SysError("waitpid failed");
2187 }
2188 handle = Scm_WinProcess(process);
2189 r = win_wait_for_handles(&handle, 1, options, &status);
2190 if (r == -2) goto timeout;
2191 if (r == -1) goto error;
2192 win_process_unregister(process);
2193 return Scm_Values2(process, Scm_MakeInteger(status));
2194 }
2195 timeout:
2196 return Scm_Values2(SCM_MAKE_INT(0), SCM_MAKE_INT(0));
2197 error:
2198 Scm_SysError("waitpid failed");
2199 return SCM_UNDEFINED; /* dummy */
2200 #endif /* GAUCHE_WINDOWS */
2201 }
2202
2203 #if defined(GAUCHE_WINDOWS)
2204 /* aux fn. */
2205 static int win_wait_for_handles(HANDLE *handles, int nhandles, int options,
2206 int *status /*out*/)
2207 {
2208 DWORD r = MsgWaitForMultipleObjects(nhandles,
2209 handles,
2210 FALSE,
2211 (options&WNOHANG)? 0 : INFINITE,
2212 0);
2213 if (r == WAIT_FAILED) return -1;
2214 if (r == WAIT_TIMEOUT) return -2;
2215 if ((int)r >= (int)WAIT_OBJECT_0 && (int)r < (int)WAIT_OBJECT_0 + nhandles) {
2216 DWORD exitcode;
2217 int index = r - WAIT_OBJECT_0;
2218 r = GetExitCodeProcess(handles[index], &exitcode);
2219 if (r == 0) return -1;
2220 *status = exitcode;
2221 return index;
2222 }
2223 return -1;
2224 }
2225 #endif /*GAUCHE_WINDOWS*/
2226
2227 /*===============================================================
2228 * select
2229 */
2230
2231 #ifdef HAVE_SELECT
2232 static ScmObj fdset_allocate(ScmClass *klass, ScmObj initargs SCM_UNUSED)
2233 {
2234 ScmSysFdset *set = SCM_NEW_INSTANCE(ScmSysFdset, klass);
2235 set->maxfd = -1;
2236 FD_ZERO(&set->fdset);
2237 return SCM_OBJ(set);
2238 }
2239
2240 static ScmSysFdset *fdset_copy(ScmSysFdset *fdset)
2241 {
2242 ScmSysFdset *set = SCM_NEW(ScmSysFdset);
2243 SCM_SET_CLASS(set, SCM_CLASS_SYS_FDSET);
2244 set->maxfd = fdset->maxfd;
2245 set->fdset = fdset->fdset;
2246 return set;
2247 }
2248
2249 SCM_DEFINE_BUILTIN_CLASS(Scm_SysFdsetClass, NULL, NULL, NULL,
2250 fdset_allocate, SCM_CLASS_DEFAULT_CPL);
2251
2252 static ScmSysFdset *select_checkfd(ScmObj fds)
2253 {
2254 if (SCM_FALSEP(fds)) return NULL;
2255 if (!SCM_SYS_FDSET_P(fds))
2256 Scm_Error("sys-fdset object or #f is required, but got %S", fds);
2257 return SCM_SYS_FDSET(fds);
2258 }
2259
2260 static struct timeval *select_timeval(ScmObj timeout, struct timeval *tm)
2261 {
2262 if (SCM_FALSEP(timeout)) return NULL;
2263 if (SCM_INTP(timeout)) {
2264 int val = SCM_INT_VALUE(timeout);
2265 if (val < 0) goto badtv;
2266 tm->tv_sec = val / 1000000;
2267 tm->tv_usec = val % 1000000;
2268 return tm;
2269 } else if (SCM_BIGNUMP(timeout)) {
2270 long usec;
2271 ScmObj sec;
2272 if (Scm_Sign(timeout) < 0) goto badtv;
2273 sec = Scm_BignumDivSI(SCM_BIGNUM(timeout), 1000000, &usec);
2274 tm->tv_sec = Scm_GetInteger(sec);
2275 tm->tv_usec = usec;
2276 return tm;
2277 } else if (SCM_FLONUMP(timeout)) {
2278 long val = Scm_GetInteger(timeout);
2279 if (val < 0) goto badtv;
2280 tm->tv_sec = val / 1000000;
2281 tm->tv_usec = val % 1000000;
2282 return tm;
2283 } else if (SCM_PAIRP(timeout) && SCM_PAIRP(SCM_CDR(timeout))) {
2284 ScmObj sec = SCM_CAR(timeout);
2285 ScmObj usec = SCM_CADR(timeout);
2286 long isec, iusec;
2287 if (!Scm_IntegerP(sec) || !Scm_IntegerP(usec)) goto badtv;
2288 isec = Scm_GetInteger(sec);
2289 iusec = Scm_GetInteger(usec);
2290 if (isec < 0 || iusec < 0) goto badtv;
2291 tm->tv_sec = isec;
2292 tm->tv_usec = iusec;
2293 return tm;
2294 }
2295 badtv:
2296 Scm_Error("timeval needs to be a real number (in microseconds) or a list of two integers (seconds and microseconds), but got %S", timeout);
2297 return NULL; /* dummy */
2298 }
2299
2300 static ScmObj select_int(ScmSysFdset *rfds, ScmSysFdset *wfds,
2301 ScmSysFdset *efds, ScmObj timeout)
2302 {
2303 int numfds, maxfds = 0;
2304 struct timeval tm;
2305 if (rfds) maxfds = rfds->maxfd;
2306 if (wfds && wfds->maxfd > maxfds) maxfds = wfds->maxfd;
2307 if (efds && efds->maxfd > maxfds) maxfds = efds->maxfd;
2308
2309 SCM_SYSCALL(numfds,
2310 select(maxfds+1,
2311 (rfds? &rfds->fdset : NULL),
2312 (wfds? &wfds->fdset : NULL),
2313 (efds? &efds->fdset : NULL),
2314 select_timeval(timeout, &tm)));
2315 if (numfds < 0) Scm_SysError("select failed");
2316 return Scm_Values4(Scm_MakeInteger(numfds),
2317 (rfds? SCM_OBJ(rfds) : SCM_FALSE),
2318 (wfds? SCM_OBJ(wfds) : SCM_FALSE),
2319 (efds? SCM_OBJ(efds) : SCM_FALSE));
2320 }
2321
2322 ScmObj Scm_SysSelect(ScmObj rfds, ScmObj wfds, ScmObj efds, ScmObj timeout)
2323 {
2324 ScmSysFdset *r = select_checkfd(rfds);
2325 ScmSysFdset *w = select_checkfd(wfds);
2326 ScmSysFdset *e = select_checkfd(efds);
2327 return select_int((r? fdset_copy(r) : NULL),
2328 (w? fdset_copy(w) : NULL),
2329 (e? fdset_copy(e) : NULL),
2330 timeout);
2331 }
2332
2333 ScmObj Scm_SysSelectX(ScmObj rfds, ScmObj wfds, ScmObj efds, ScmObj timeout)
2334 {
2335 ScmSysFdset *r = select_checkfd(rfds);
2336 ScmSysFdset *w = select_checkfd(wfds);
2337 ScmSysFdset *e = select_checkfd(efds);
2338 return select_int(r, w, e, timeout);
2339 }
2340
2341 #endif /* HAVE_SELECT */
2342
2343 /*===============================================================
2344 * Environment
2345 */
2346
2347 /* We provide a compatibility layer for getenv/setenv stuff, whose semantics
2348 slightly differ among platforms.
2349
2350 POSIX putenv() has a flaw that passed string can't be freed reliably;
2351 the system may retain the pointer, so the caller can't free it afterwards,
2352 while putenv() itself can't know if the passed pointer is malloc-ed or
2353 static. Some Unixes appears to change the semantics, guaranteeing
2354 the system copies the passed string so that the caller can free it;
2355 however, it's not easy to check which semantics the given platform uses.
2356
2357 What POSIX suggests is setenv() when you want to pass malloc-ed
2358 strings. Unfortunately it is a newer addition and not all platforms
2359 supports it. Windows doesn't, either, but it offers _[w]putenv_s
2360 as an alternative. Unfortunately again, current MinGW doesn't include
2361 _[w]putenv_s in its headers and import libraries.
2362
2363 So, for those platforms, we use putenv/_wputenv. We track allocated
2364 memory in env_string table, keyed by names of envvars, and free them
2365 whenever we put a new definition of envvars we've inserted before.
2366
2367 Another merit of this compatibility layer is to guarantee MT-safeness;
2368 Putenv/setenv aren't usually MT-safe, neither is getenv when environment
2369 is being modified.
2370 */
2371
2372 static ScmInternalMutex env_mutex;
2373 static ScmHashCore env_strings; /* name -> malloc-ed mem.
2374 used with putenv()/_wputenv() to prevent
2375 leak. */
2376
2377 const char *Scm_GetEnv(const char *name)
2378 {
2379 #if defined(GAUCHE_WINDOWS) && defined(UNICODE)
2380 const wchar_t *wname = Scm_MBS2WCS(name);
2381 const char *value = NULL;
2382 (void)SCM_INTERNAL_MUTEX_LOCK(env_mutex);
2383 const wchar_t *wvalue = _wgetenv(wname);
2384 if (wvalue != NULL) {
2385 value = Scm_WCS2MBS(wvalue);
2386 }
2387 (void)SCM_INTERNAL_MUTEX_UNLOCK(env_mutex);
2388 return value;
2389 #else /*!(defined(GAUCHE_WINDOWS) && defined(UNICODE))*/
2390 (void)SCM_INTERNAL_MUTEX_LOCK(env_mutex);
2391 const char *value = SCM_STRDUP(getenv(name));
2392 (void)SCM_INTERNAL_MUTEX_UNLOCK(env_mutex);
2393 return value;
2394 #endif /*!(defined(GAUCHE_WINDOWS) && defined(UNICODE))*/
2395 }
2396
2397 void Scm_SetEnv(const char *name, const char *value, int overwrite)
2398 {
2399 #if defined(GAUCHE_WINDOWS) && defined(UNICODE)
2400 /* We need to use _wputenv for wide-character support. Since we pass
2401 the converted strings to OS, we have to allocate them by malloc.
2402 To prevent leak, we register the allocated memory to the global
2403 hash table, and free it when Scm_SetEnv is called with the same NAME
2404 again. */
2405 wchar_t *wname = Scm_MBS2WCS(name);
2406 wchar_t *wvalue = Scm_MBS2WCS(value);
2407 int nlen = wcslen(wname);
2408 int vlen = wcslen(wvalue);
2409 wchar_t *wnameval = (wchar_t*)malloc((nlen+vlen+2)*sizeof(wchar_t));
2410 if (wnameval == NULL) {
2411 Scm_Error("sys-setenv: out of memory");
2412 }
2413 wcscpy(wnameval, wname);
2414 wcscpy(wnameval+nlen, L"=");
2415 wcscpy(wnameval+nlen+1, wvalue);
2416
2417 ScmObj sname = Scm_MakeString(name, -1, -1, SCM_STRING_COPYING);
2418
2419 int result = 0;
2420 wchar_t *prev_mem = NULL;
2421
2422 (void)SCM_INTERNAL_MUTEX_LOCK(env_mutex);
2423 if (overwrite || _wgetenv(wname) == NULL) {
2424 result = _wputenv(wnameval);
2425 if (result >= 0) {
2426 ScmDictEntry *e = Scm_HashCoreSearch(&env_strings,
2427 (intptr_t)sname,
2428 SCM_DICT_CREATE);
2429 /* SCM_DICT_VALUE is only for ScmObj, so we directly access value
2430 field here. */
2431 prev_mem = (wchar_t*)e->value;
2432 e->value = (intptr_t)wnameval;
2433 }
2434 }
2435 (void)SCM_INTERNAL_MUTEX_UNLOCK(env_mutex);
2436
2437 if (result < 0) {
2438 free(wnameval);
2439 Scm_SysError("setenv failed on '%s=%s'", name, value);
2440 }
2441 if (prev_mem != NULL) {
2442 free(prev_mem);
2443 }
2444 #elif defined(HAVE_SETENV)
2445 (void)SCM_INTERNAL_MUTEX_LOCK(env_mutex);
2446 int r = setenv(name, value, overwrite);
2447 (void)SCM_INTERNAL_MUTEX_UNLOCK(env_mutex);
2448 if (r < 0) Scm_SysError("setenv failed on '%s=%s'", name, value);
2449 #elif defined(HAVE_PUTENV)
2450 int nlen = (int)strlen(name);
2451 int vlen = (int)strlen(value);
2452 char *nameval = (char*)malloc(nlen+vlen+2);
2453 if (nameval == NULL) {
2454 Scm_Error("sys-setenv: out of memory");
2455 }
2456 strcpy(nameval, name);
2457 strcpy(nameval+nlen, "=");
2458 strcpy(nameval+nlen+1, value);
2459
2460 ScmObj sname = Scm_MakeString(name, -1, -1, SCM_STRING_COPYING);
2461
2462 int result = 0;
2463 char *prev_mem = NULL;
2464
2465 (void)SCM_INTERNAL_MUTEX_LOCK(env_mutex);
2466 if (overwrite || getenv(name) == NULL) {
2467 result = putenv(nameval);
2468 if (result >= 0) {
2469 ScmDictEntry *e = Scm_HashCoreSearch(&env_strings,
2470 (intptr_t)sname,
2471 SCM_DICT_CREATE);
2472 /* SCM_DICT_VALUE is only for ScmObj, so we directly access value
2473 field here. */
2474 prev_mem = (char*)e->value;
2475 e->value = (intptr_t)nameval;
2476 }
2477 }
2478 (void)SCM_INTERNAL_MUTEX_UNLOCK(env_mutex);
2479 if (result < 0) {
2480 free (nameval);
2481 Scm_SysError("putenv failed on '%s=%s'", name, value);
2482 }
2483 if (prev_mem != NULL) {
2484 free(prev_mem);
2485 }
2486 #else /* !HAVE_SETENV && !HAVE_PUTENV */
2487 /* We can't do much. we may replace environ by ourselves, but
2488 it is unlikely that the system have extern environ and not putenv.
2489 */
2490 Scm_Error("neither setenv nor putenv is supported on this platform.");
2491 #endif
2492 }
2493
2494 /* Returns the system's environment table as a list of strings.
2495 Each string is in the format of "key=value". */
2496 ScmObj Scm_Environ(void)
2497 {
2498 #if defined(GAUCHE_WINDOWS)
2499 #define ENV_BUFSIZ 64
2500 LPVOID ss = GetEnvironmentStrings();
2501 ScmObj h = SCM_NIL, t = SCM_NIL;
2502 TCHAR *cp = (TCHAR*)ss, *pp;
2503 TCHAR sbuf[ENV_BUFSIZ], *buf=sbuf;
2504 int bsize = ENV_BUFSIZ, size;
2505
2506 do {
2507 for (pp=cp; *pp; pp++) /*proceed ptr*/;
2508 size = (int)(pp - cp) + 1;
2509 if (size >= bsize) {
2510 buf = SCM_NEW_ATOMIC_ARRAY(TCHAR, size);
2511 bsize = size;
2512 }
2513 memcpy(buf, cp, size*sizeof(TCHAR));
2514 SCM_APPEND1(h, t, SCM_MAKE_STR_COPYING(SCM_WCS2MBS(buf)));
2515 cp = pp+1;
2516 } while (pp[1] != 0);
2517 FreeEnvironmentStrings(ss);
2518 return h;
2519 #else
2520 (void)SCM_INTERNAL_MUTEX_LOCK(env_mutex);
2521 # if defined(HAVE_CRT_EXTERNS_H)
2522 char **environ = *_NSGetEnviron(); /* OSX Hack*/
2523 # endif
2524 ScmObj r = (environ == NULL
2525 ? SCM_NIL
2526 : Scm_CStringArrayToList((const char**)environ, -1,
2527 SCM_STRING_COPYING));
2528 (void)SCM_INTERNAL_MUTEX_UNLOCK(env_mutex);
2529 return r;
2530 #endif /*!GAUCHE_WINDOWS*/
2531 }
2532
2533 void Scm_UnsetEnv(const char *name)
2534 {
2535 #if defined(HAVE_UNSETENV)
2536 /* NB: If we HAVE_SETENV, we don't have any entries in env_strings,
2537 so the lookup of snv_strings is a waste; but the result is always
2538 NULL and it won't harm the operation, and we expect sys-unsetenv
2539 is rarely used, so we just let it waste cpu cycles. */
2540 char *prev_mem = NULL;
2541 ScmObj sname = Scm_MakeString(name, -1, -1, SCM_STRING_COPYING);
2542 (void)SCM_INTERNAL_MUTEX_LOCK(env_mutex);
2543 int r = unsetenv(name);
2544 ScmDictEntry *e = Scm_HashCoreSearch(&env_strings,
2545 (intptr_t)sname,
2546 SCM_DICT_DELETE);
2547 if (e != NULL) { prev_mem = (char*)e->value; e->value = (intptr_t)NULL; }
2548 (void)SCM_INTERNAL_MUTEX_UNLOCK(env_mutex);
2549 if (r < 0) Scm_SysError("unsetenv failed on %s", name);
2550 if (prev_mem != NULL) free(prev_mem);
2551 #else /*!HAVE_UNSETENV*/
2552 (void)name; /* suppress unused var warning */
2553 Scm_Error("sys-unsetenv is not supported on this platform.");
2554 #endif /*!HAVE_UNSETENV*/
2555 }
2556
2557 void Scm_ClearEnv()
2558 {
2559 #if defined(HAVE_CLEARENV)
2560 /* As in Scm_UnsetEnv, we don't need env_strings business if
2561 we HAVE_SETENV, but it does no harm either. */
2562 (void)SCM_INTERNAL_MUTEX_LOCK(env_mutex);
2563 int r = clearenv();
2564 ScmHashIter iter;
2565 Scm_HashIterInit(&iter, &env_strings);
2566 ScmDictEntry *e;
2567 while ((e = Scm_HashIterNext(&iter)) != NULL) {
2568 free((void*)e->value);
2569 e->value = (intptr_t)NULL;
2570 }
2571 Scm_HashCoreClear(&env_strings);
2572 (void)SCM_INTERNAL_MUTEX_UNLOCK(env_mutex);
2573 if (r < 0) Scm_SysError("clearenv failed");
2574 #else /*!HAVE_UNSETENV*/
2575 Scm_Error("sys-clearenv is not supported on this platform.");
2576 #endif /*!HAVE_UNSETENV*/
2577 }
2578
2579 /*===============================================================
2580 * Closer-to-metal thingy
2581 */
2582
2583 /* Try to find # of available processors. If we don't know how to
2584 find that info on the platform, we fall back to 1.
2585 If GAUCHE_AVAILABLE_PROCESSORS environment variable is defined and
2586 has the value interpreted as a positive integer, we use that value
2587 instead.
2588 */
2589 int Scm_AvailableProcessors()
2590 {
2591 const char *env = Scm_GetEnv("GAUCHE_AVAILABLE_PROCESSORS");
2592 if (env && env[0] != '\0') {
2593 char *ep;
2594 long v = strtol(env, &ep, 10);
2595 if (v > 0 && *ep == '\0') return (int)v;
2596 }
2597 #if !defined(GAUCHE_WINDOWS)
2598 #if defined(_SC_NPROCESSORS_ONLN)
2599 return (int)sysconf(_SC_NPROCESSORS_ONLN);
2600 #else /*!defined(_SC_NPROCESSORS_ONLN)*/
2601 return 1; /* fallback */
2602 #endif /*!defined(_SC_NPROCESSORS_ONLN)*/
2603 #else /*defined(GAUCHE_WINDOWS)*/
2604 SYSTEM_INFO sysinfo;
2605 GetSystemInfo( &sysinfo );
2606 return (int)sysinfo.dwNumberOfProcessors;
2607 #endif /*defined(GAUCHE_WINDOWS)*/
2608 }
2609
2610 /*===============================================================
2611 * Emulation layer for Windows
2612 */
2613 #if defined(GAUCHE_WINDOWS)
2614
2615 /* Dynamically obtain an entry point that may not be available on
2616 all Windows versions. If throw_error is TRUE, throws an error
2617 if DLL mapping failed, or entry cannot be found. Otherwise,
2618 returns NULL on error. */
2619 static void *get_api_entry(const TCHAR *module, const char *proc,
2620 int throw_error)
2621 {
2622 void *entry;
2623 HMODULE m = LoadLibrary(module);
2624 if (m == NULL) {
2625 if (throw_error)
2626 Scm_SysError("LoadLibrary(%s) failed", SCM_WCS2MBS(module));
2627 else
2628 return NULL;
2629 }
2630 entry = (void*)GetProcAddress(m, proc);
2631 if (entry == NULL) {
2632 DWORD errcode = GetLastError();
2633 FreeLibrary(m);
2634 SetLastError(errcode);
2635 if (throw_error)
2636 Scm_SysError("GetProcAddress(%s) failed", proc);
2637 else
2638 return NULL;
2639 }
2640 return entry;
2641 }
2642
2643 /* Scan the processes to find out either the parent process, or the
2644 child processes of the current process. I cannot imagine why we
2645 need such a hassle to perform this kind of simple task, but this
2646 is the way the MS document suggests.
2647 Returns a single Scheme integer of the parent process id if childrenp
2648 is FALSE; returns a list of Scheme integers of child process ids if
2649 childrenp is TRUE. */
2650 static ScmObj get_relative_processes(int childrenp)
2651 {
2652 HANDLE snapshot;
2653 PROCESSENTRY32 entry;
2654 DWORD myid = GetCurrentProcessId(), parentid = 0;
2655 int found = FALSE;
2656 ScmObj h = SCM_NIL, t = SCM_NIL; /* children pids */
2657
2658 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
2659 if (snapshot == INVALID_HANDLE_VALUE) {
2660 Scm_Error("couldn't take process snapshot in getppid()");
2661 }
2662 entry.dwSize = sizeof(PROCESSENTRY32);
2663 if (!Process32First(snapshot, &entry)) {
2664 CloseHandle(snapshot);
2665 Scm_Error("Process32First failed in getppid()");
2666 }
2667 do {
2668 if (childrenp) {
2669 if (entry.th32ParentProcessID == myid) {
2670 SCM_APPEND1(h, t, Scm_MakeInteger(entry.th32ProcessID));
2671 }
2672 } else {
2673 if (entry.th32ProcessID == myid) {
2674 parentid = entry.th32ParentProcessID;
2675 found = TRUE;
2676 break;
2677 }
2678 }
2679 } while (Process32Next(snapshot, &entry));
2680 CloseHandle(snapshot);
2681
2682 if (childrenp) {
2683 return h;
2684 } else {
2685 if (!found) {
2686 Scm_Error("couldn't find the current process entry in getppid()");
2687 }
2688 return Scm_MakeInteger(parentid);
2689 }
2690 }
2691
2692 /* Retrieve PID from windows process handle wrapper. */
2693
2694 pid_t Scm_WinProcessPID(ScmObj handle)
2695 {
2696 /* GetProcessId seems very primitive procedure, but somehow Windows
2697 only provides it in XP SP1 or after. Before that it seems you
2698 can only map pid -> handle by OpenProcess but you can't do the
2699 reverse (except you enumerate all process ids, calling OpenProcess
2700 on each and look for one whose handle matches the given handle.
2701 Sounds expensive. */
2702 static DWORD (WINAPI *pGetProcessId)(HANDLE) = NULL;
2703 static int queried = FALSE;
2704
2705 if (!Scm_WinProcessP(handle)) {
2706 SCM_TYPE_ERROR(handle, "<win:handle process>");
2707 }
2708
2709 if (pGetProcessId == NULL) {
2710 if (queried) return (pid_t)-1;
2711 pGetProcessId = get_api_entry(_T("kernel32.dll"), "GetProcessId",
2712 FALSE);
2713 if (pGetProcessId == NULL) {
2714 queried = TRUE;
2715 return (pid_t)-1;
2716 }
2717 }
2718 return pGetProcessId(Scm_WinProcess(handle));
2719 }
2720
2721 /*
2722 * Users and groups
2723 * Kinda Kluge, since we don't have "user id" associated with each
2724 * user. (If a domain server is active, Windows security manager seems
2725 * to assign an unique user id for every user; but it doesn't seem available
2726 * for stand-alone machine.)
2727 */
2728
2729 static void convert_user(const USER_INFO_2 *wuser, struct passwd *res)
2730 {
2731 res->pw_name = (const char*)SCM_WCS2MBS(wuser->usri2_name);
2732 res->pw_passwd = "*";
2733 res->pw_uid = 0;
2734 res->pw_gid = 0;
2735 res->pw_comment = (const char*)SCM_WCS2MBS(wuser->usri2_comment);
2736 res->pw_gecos = (const char*)SCM_WCS2MBS(wuser->usri2_full_name);
2737 res->pw_dir = (const char*)SCM_WCS2MBS(wuser->usri2_home_dir);
2738 res->pw_shell = "";
2739 }
2740
2741 /* Arrgh! thread unsafe! just for the time being...*/
2742 static struct passwd pwbuf = { "dummy", "", 0, 0, "", "", "", "" };
2743
2744 struct passwd *getpwnam(const char *name)
2745 {
2746 USER_INFO_2 *res;
2747 if (NetUserGetInfo(NULL, (LPCWSTR)SCM_MBS2WCS(name), 2, (LPBYTE*)&res)
2748 != NERR_Success) {
2749 return NULL;
2750 }
2751 convert_user(res, &pwbuf);
2752 NetApiBufferFree(res);
2753 return &pwbuf;
2754 }
2755
2756 struct passwd *getpwuid(uid_t uid SCM_UNUSED)
2757 {
2758 /* for the time being, we just ignore uid and returns the current
2759 user info. */
2760 #define NAMELENGTH 256
2761 TCHAR buf[NAMELENGTH];
2762 DWORD len = NAMELENGTH;
2763 if (GetUserName(buf, &len) == 0) {
2764 return NULL;
2765 }
2766 return getpwnam(SCM_WCS2MBS(buf));
2767 }
2768
2769 static struct group dummy_group = {
2770 "dummy",
2771 "",
2772 100,
2773 NULL
2774 };
2775
2776 struct group *getgrgid(gid_t gid SCM_UNUSED)
2777 {
2778 return &dummy_group;
2779 }
2780
2781 struct group *getgrnam(const char *name SCM_UNUSED)
2782 {
2783 return &dummy_group;
2784 }
2785
2786 /* Kluge kluge kluge */
2787 uid_t getuid(void)
2788 {
2789 return 0;
2790 }
2791
2792 uid_t geteuid(void)
2793 {
2794 return 0;
2795 }
2796
2797 gid_t getgid(void)
2798 {
2799 return 0;
2800 }
2801
2802 gid_t getegid(void)
2803 {
2804 return 0;
2805 }
2806
2807 pid_t getppid(void)
2808 {
2809 ScmObj ppid = get_relative_processes(FALSE);
2810 return Scm_GetInteger(ppid);
2811 }
2812
2813 const char *getlogin(void)
2814 {
2815 static TCHAR buf[256]; /* this isn't thread-safe, but getlogin() is
2816 inherently thread-unsafe call anyway */
2817 DWORD size = sizeof(buf)/sizeof(TCHAR);
2818 BOOL r;
2819 r = GetUserName(buf, &size);
2820 if (r) {
2821 return SCM_WCS2MBS(buf);
2822 } else {
2823 return NULL;
2824 }
2825 }
2826
2827 clock_t times(struct tms *info)
2828 {
2829 HANDLE process = GetCurrentProcess();
2830 FILETIME ctime, xtime, utime, stime;
2831 int64_t val;
2832 const int factor = 10000000/CLK_TCK;
2833 const int bias = factor/2;
2834
2835 if (!GetProcessTimes(process, &ctime, &xtime, &stime, &utime)) {
2836 Scm_SysError("GetProcessTimes failed");
2837 }
2838 val = ((int64_t)stime.dwHighDateTime << 32) + stime.dwLowDateTime;
2839 info->tms_stime = (u_int)((val+bias) / factor);
2840 val = ((int64_t)utime.dwHighDateTime << 32) + utime.dwLowDateTime;
2841 info->tms_utime = (u_int)((val+bias) / factor);
2842
2843 info->tms_cstime = 0;
2844 info->tms_cutime = 0;
2845 return 0;
2846 }
2847
2848
2849
2850 /*
2851 * Other obscure stuff
2852 */
2853
2854 int fork(void)
2855 {
2856 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2857 return -1;
2858 }
2859
2860 int pipe(int fd[])
2861 {
2862 #define PIPE_BUFFER_SIZE 512
2863 /* NB: We create pipe with NOINHERIT to avoid complication when spawning
2864 child process. Scm_SysExec will dups the handle with inheritable flag
2865 for the children. */
2866 int r = _pipe(fd, PIPE_BUFFER_SIZE, O_BINARY|O_NOINHERIT);
2867 return r;
2868 }
2869
2870 /* If the given handle points to a pipe, returns its name.
2871 As of Oct 2016, mingw headers does not include
2872 GetFileInformationByHandleEx API, so we provide alternative. */
2873
2874 typedef struct {
2875 DWORD FileNameLength;
2876 WCHAR FileName[1];
2877 } X_FILE_NAME_INFO;
2878
2879 typedef enum {
2880 X_FileNameInfo = 2
2881 } X_FILE_INFO_BY_HANDLE_CLASS;
2882
2883 ScmObj Scm_WinGetPipeName(HANDLE h)
2884 {
2885 if (GetFileType(h) != FILE_TYPE_PIPE) return SCM_FALSE;
2886 static BOOL (WINAPI *pGetFileInformationByHandleEx)(HANDLE,
2887 X_FILE_INFO_BY_HANDLE_CLASS,
2888 LPVOID, DWORD) = NULL;
2889
2890 if (pGetFileInformationByHandleEx == NULL) {
2891 pGetFileInformationByHandleEx =
2892 get_api_entry(_T("kernel32.dll"),
2893 "GetFileInformationByHandleEx",
2894 FALSE);
2895 }
2896 if (pGetFileInformationByHandleEx == NULL) return SCM_FALSE;
2897
2898 DWORD size = sizeof(X_FILE_NAME_INFO) + sizeof(WCHAR)*MAX_PATH;
2899 X_FILE_NAME_INFO *info = SCM_MALLOC_ATOMIC(size);
2900 BOOL r = pGetFileInformationByHandleEx(h, X_FileNameInfo, info, size);
2901 if (!r) return SCM_FALSE;
2902
2903 info->FileName[info->FileNameLength / sizeof(WCHAR)] = 0;
2904 return SCM_MAKE_STR_COPYING(SCM_WCS2MBS(info->FileName));
2905 }
2906
2907 char *ttyname(int desc SCM_UNUSED)
2908 {
2909 return NULL;
2910 }
2911
2912 #if !HAVE_UTIMENSAT
2913 /* Emulate utimensat() by utime(). For MinGW. */
2914 int utimensat(int dirfd SCM_UNUSED,
2915 const char *path,
2916 const ScmTimeSpec times[2],
2917 int flags SCM_UNUSED)
2918 {
2919 struct utimbuf buf;
2920 buf.actime = times[0].tv_sec;
2921 buf.modtime = times[1].tv_sec;
2922
2923 if (times[0].tv_nsec == UTIME_NOW) {
2924 buf.actime = time(NULL);
2925 }
2926 if (times[1].tv_nsec == UTIME_NOW) {
2927 buf.modtime = time(NULL);
2928 }
2929 /* TODO: UTIME_OMIT case */
2930
2931 return utime(path, &buf);
2932 }
2933 #endif /*!HAVE_UTIMENSAT*/
2934
2935 #ifndef __MINGW64_VERSION_MAJOR /* MinGW64 has truncate and ftruncate */
2936
2937 static int win_truncate(HANDLE file, off_t len)
2938 {
2939 typedef BOOL (WINAPI *pSetEndOfFile_t)(HANDLE);
2940 typedef BOOL (WINAPI *pSetFilePointer_t)(HANDLE, LONG, PLONG, DWORD);
2941
2942 static pSetEndOfFile_t pSetEndOfFile = NULL;
2943 static pSetFilePointer_t pSetFilePointer = NULL;
2944
2945 DWORD r1;
2946 BOOL r2;
2947
2948 if (pSetEndOfFile == NULL) {
2949 pSetEndOfFile = (pSetEndOfFile_t)get_api_entry(_T("kernel32.dll"),
2950 "SetEndOfFile",
2951 FALSE);
2952 if (pSetEndOfFile == NULL) return -1;
2953 }
2954 if (pSetFilePointer == NULL) {
2955 pSetFilePointer = (pSetFilePointer_t)get_api_entry(_T("kernel32.dll"),
2956 "SetFilePointer",
2957 FALSE);
2958 if (pSetFilePointer == NULL) return -1;
2959 }
2960
2961 /* TODO: 64bit size support! */
2962 r1 = pSetFilePointer(file, (LONG)len, NULL, FILE_BEGIN);
2963 if (r1 == INVALID_SET_FILE_POINTER) return -1;
2964 r2 = pSetEndOfFile(file);
2965 if (r2 == 0) return -1;
2966 return 0;
2967 }
2968
2969 int truncate(const char *path, off_t len)
2970 {
2971 HANDLE file;
2972 int r;
2973
2974 file = CreateFile(SCM_MBS2WCS(path), GENERIC_WRITE,
2975 FILE_SHARE_READ|FILE_SHARE_WRITE,
2976 NULL, OPEN_EXISTING, 0, NULL);
2977 if (file == INVALID_HANDLE_VALUE) return -1;
2978 r = win_truncate(file, len);
2979 if (r < 0) {
2980 DWORD errcode = GetLastError();
2981 CloseHandle(file);
2982 SetLastError(errcode);
2983 return -1;
2984 }
2985 CloseHandle(file);
2986 return 0;
2987 }
2988
2989 int ftruncate(int fd, off_t len)
2990 {
2991 HANDLE h = (HANDLE)_get_osfhandle(fd);
2992 int r;
2993 if (h == INVALID_HANDLE_VALUE) return -1;
2994 r = win_truncate(h, len);
2995 if (r < 0) return -1;
2996 return 0;
2997 }
2998
2999 #endif /* __MINGW64_VERSION_MAJOR */
3000
3001 unsigned int alarm(unsigned int seconds SCM_UNUSED)
3002 {
3003 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
3004 Scm_SysError("alarm");
3005 return 0;
3006 }
3007
3008 /* file links */
3009 int link(const char *existing, const char *newpath)
3010 {
3011 /* CreateHardLink only exists in WinNT or later. Officially we don't
3012 support anything before, but let's try to be kind for the legacy
3013 system ...*/
3014 typedef BOOL (WINAPI *pCreateHardLink_t)(LPTSTR, LPTSTR,
3015 LPSECURITY_ATTRIBUTES);
3016 static pCreateHardLink_t pCreateHardLink = NULL;
3017 BOOL r;
3018 #if defined(UNICODE)
3019 #define CREATEHARDLINK "CreateHardLinkW"
3020 #else
3021 #define CREATEHARDLINK "CreateHardLinkA"
3022 #endif
3023
3024 if (pCreateHardLink == NULL) {
3025 pCreateHardLink = (pCreateHardLink_t)get_api_entry(_T("kernel32.dll"),
3026 CREATEHARDLINK,
3027 TRUE);
3028 }
3029 r = pCreateHardLink((LPTSTR)SCM_MBS2WCS(newpath),
3030 (LPTSTR)SCM_MBS2WCS(existing), NULL);
3031 return r? 0 : -1;
3032 }
3033
3034 /* Winsock requires some obscure initialization.
3035 We perform initialization here, since winsock module is used
3036 in both gauche.net and gauche.auxsys. */
3037 static WSADATA wsaData;
3038
3039 static void init_winsock(void)
3040 {
3041 int opt;
3042 int r = WSAStartup(MAKEWORD(2,2), &wsaData);
3043 if (r != 0) {
3044 SetLastError(r);
3045 Scm_SysError("WSAStartup failed");
3046 }
3047 /* windows voodoo to make _open_osfhandle magic work */
3048 opt = SO_SYNCHRONOUS_NONALERT;
3049 r = setsockopt(INVALID_SOCKET, SOL_SOCKET,
3050 SO_OPENTYPE, (char*)&opt, sizeof(opt));
3051 if (r == SOCKET_ERROR) {
3052 Scm_SysError("winsock initialization failed");
3053 }
3054 }
3055
3056 static void fini_winsock(void *data SCM_UNUSED)
3057 {
3058 (void)WSACleanup();
3059 }
3060
3061 /* Win32 thread support. See also gauche/wthread.h */
3062
3063 #if defined(GAUCHE_USE_WTHREADS)
3064
3065 HANDLE Scm__WinCreateMutex()
3066 {
3067 HANDLE m = CreateMutex(NULL, FALSE, NULL);
3068 if (m == NULL) Scm_SysError("couldn't create a mutex");
3069 return m;
3070 }
3071
3072 int Scm__WinMutexLock(HANDLE mutex)
3073 {
3074 DWORD r = WaitForSingleObject(mutex, INFINITE);
3075 if (r == WAIT_OBJECT_0) return 0;
3076 else return 1; /* TODO: proper error handling */
3077 }
3078
3079 /* Windows fast lock */
3080
3081 int Scm__WinFastLockInit(ScmInternalFastlock *spin)
3082 {
3083 *spin = SCM_NEW(struct win_spinlock_rec);
3084 Scm_AtomicStore(&(*spin)->lock_state, 0);
3085 return 0;
3086 }
3087
3088 int Scm__WinFastLockLock(ScmInternalFastlock spin)
3089 {
3090 /* spin may be NULL when FASTLOCK_LOCK is called on already-closed port. */
3091 if (spin != NULL) {
3092 ScmAtomicWord idle = 0;
3093 while (!Scm_AtomicCompareExchange(&spin->lock_state, &idle, 1)) {
3094 /* idle might be changed */
3095 idle = 0;
3096 /* it might be slow */
3097 Sleep(0);
3098 }
3099 }
3100 return 0;
3101 }
3102
3103 int Scm__WinFastLockUnlock(ScmInternalFastlock spin)
3104 {
3105 /* spin may be NULL when FASTLOCK_LOCK is called on already-closed port. */
3106 if (spin != NULL) {
3107 Scm_AtomicStoreFull(&spin->lock_state, 0);
3108 }
3109 return 0;
3110 }
3111
3112 int Scm__WinFastLockDestroy(ScmInternalFastlock *spin)
3113 {
3114 *spin = NULL;
3115 return 0;
3116 }
3117
3118 /* Win32 conditional variable emulation.
3119 Native condition variable support is only available on Windows Vista
3120 and later. We don't want to drop XP support (yet), so we avoid using
3121 it. Instead we emulate posix condition variable semantics.
3122 We enhanced the implementation described as the SignalObjectAndWait
3123 solution shown in
3124 <http://www1.cse.wustl.edu/~schmidt/win32-cv-1.html>
3125 */
3126 void Scm__InternalCondInit(ScmInternalCond *cond)
3127 {
3128 cond->numWaiters = 0;
3129 cond->broadcast = FALSE;
3130 cond->mutex = NULL; /* set by the first CondWait */
3131 cond->sem = CreateSemaphore(NULL, /* no security */
3132 0, 0x7fffffff, /* initial and max val */
3133 NULL); /* name */
3134 if (cond->sem == NULL) {
3135 Scm_SysError("couldn't create a semaphore for a condition variable");
3136 }
3137 cond->done = CreateEvent(NULL, /* no security */
3138 FALSE, /* auto-reset */
3139 FALSE, /* initially non-signalled */
3140 NULL); /* name */
3141 if (cond->done == NULL) {
3142 DWORD err = GetLastError();
3143 CloseHandle(cond->sem);
3144 SetLastError(err);
3145 Scm_SysError("couldn't create event for a condition variable");
3146 }
3147 InitializeCriticalSection(&cond->numWaitersLock);
3148 }
3149
3150 int Scm__InternalCondWait(ScmInternalCond *cond, ScmInternalMutex *mutex,
3151 ScmTimeSpec *pts)
3152 {
3153 DWORD r0, r1;
3154 DWORD timeout_msec;
3155 int badMutex = FALSE, lastWaiter;
3156
3157 if (pts) {
3158 u_long now_sec, now_usec;
3159 u_long target_sec, target_usec;
3160 Scm_GetTimeOfDay(&now_sec, &now_usec);
3161 target_sec = pts->tv_sec;
3162 target_usec = pts->tv_nsec / 1000;
3163 if (target_sec < now_sec
3164 || (target_sec == now_sec && target_usec <= now_usec)) {
3165 timeout_msec = 0;
3166 } else if (target_usec >= now_usec) {
3167 timeout_msec = ceil((target_sec - now_sec) * 1000
3168 + (target_usec - now_usec)/1000.0);
3169 } else {
3170 timeout_msec = ceil((target_sec - now_sec - 1) * 1000
3171 + (1.0e6 + target_usec - now_usec)/1000.0);
3172 }
3173 } else {
3174 timeout_msec = INFINITE;
3175 }
3176
3177 EnterCriticalSection(&cond->numWaitersLock);
3178 /* If we're the first one to wait on this cond var, set cond->mutex.
3179 We don't allow to use multiple mutexes together with single cond var.
3180 */
3181 if (cond->mutex != NULL && cond->mutex != mutex) {
3182 badMutex = TRUE;
3183 } else {
3184 cond->numWaiters++;
3185 if (cond->mutex == NULL) cond->mutex = mutex;
3186 }
3187 LeaveCriticalSection(&cond->numWaitersLock);
3188
3189 if (badMutex) {
3190 Scm_Error("Attempt to wait on condition variable %p with different"
3191 " mutex %p\n", cond, mutex);
3192 }
3193
3194 /* Signals mutex and atomically waits on the semaphore */
3195 r0 = SignalObjectAndWait(*mutex, cond->sem, timeout_msec, FALSE);
3196
3197 /* We're signaled, or timed out. There can be a case that cond is
3198 broadcasted between the timeout of SignalObjectAndWait and the
3199 following EnterCriticalSection. So we should check lastWaiter
3200 anyway. */
3201 EnterCriticalSection(&cond->numWaitersLock);
3202 cond->numWaiters--;
3203 lastWaiter = cond->broadcast && cond->numWaiters == 0;
3204 LeaveCriticalSection(&cond->numWaitersLock);
3205
3206 if (lastWaiter) {
3207 /* tell the broadcaster that all the waiters have gained
3208 control, and wait to acquire mutex. */
3209 r1 = SignalObjectAndWait(cond->done, *mutex, INFINITE, FALSE);
3210 } else {
3211 /* Acquire mutex */
3212 r1 = WaitForSingleObject(*mutex, INFINITE);
3213 }
3214 if (r0 == WAIT_TIMEOUT) return SCM_INTERNAL_COND_TIMEDOUT;
3215 if (r0 != WAIT_OBJECT_0 || r1 != WAIT_OBJECT_0) return -1;
3216 return 0;
3217 }
3218
3219 int Scm__InternalCondSignal(ScmInternalCond *cond)
3220 {
3221 int haveWaiters;
3222 BOOL r = TRUE;
3223
3224 if (!cond->mutex) return 0; /* nobody ever waited on this cond var. */
3225
3226 SCM_INTERNAL_MUTEX_SAFE_LOCK_BEGIN(cond->mutex);
3227
3228 EnterCriticalSection(&cond->numWaitersLock);
3229 haveWaiters = (cond->numWaiters > 0);
3230 LeaveCriticalSection(&cond->numWaitersLock);
3231
3232 if (haveWaiters) {
3233 r = ReleaseSemaphore(cond->sem, 1, 0);
3234 }
3235
3236 SCM_INTERNAL_MUTEX_SAFE_LOCK_END();
3237 if (!r) return -1;
3238 return 0;
3239 }
3240
3241 int Scm__InternalCondBroadcast(ScmInternalCond *cond)
3242 {
3243 int haveWaiters;
3244 DWORD err = 0;
3245 BOOL r0 = TRUE;
3246 DWORD r1 = WAIT_OBJECT_0;
3247
3248 if (!cond->mutex) return 0; /* nobody ever waited on this cond var. */
3249
3250 SCM_INTERNAL_MUTEX_SAFE_LOCK_BEGIN(cond->mutex);
3251
3252 EnterCriticalSection(&cond->numWaitersLock);
3253 cond->broadcast = haveWaiters = (cond->numWaiters > 0);
3254
3255 if (haveWaiters) {
3256 r0 = ReleaseSemaphore(cond->sem, cond->numWaiters, 0);
3257 if (!r0) err = GetLastError();
3258 LeaveCriticalSection(&cond->numWaitersLock);
3259
3260 if (r0) {
3261 /* Each waiter aquires mutex in turn, until the last waiter
3262 who will signal on 'done'. */
3263 r1 = WaitForSingleObject(cond->done, INFINITE);
3264 cond->broadcast = FALSE; /* safe; nobody will check this */
3265 }
3266 } else {
3267 /* nobody's waiting */
3268 LeaveCriticalSection(&cond->numWaitersLock);
3269 }
3270
3271 SCM_INTERNAL_MUTEX_SAFE_LOCK_END();
3272
3273 if (!r0) { SetLastError(err); return -1; }
3274 if (r1 != WAIT_OBJECT_0) return -1;
3275 return 0;
3276 }
3277
3278 void Scm__InternalCondDestroy(ScmInternalCond *cond)
3279 {
3280 CloseHandle(cond->sem);
3281 cond->sem = NULL;
3282 CloseHandle(cond->done);
3283 cond->done = NULL;
3284 }
3285
3286 void Scm__WinThreadExit()
3287 {
3288 ScmVM *vm = Scm_VM();
3289 ScmWinCleanup *cup = vm->winCleanup;
3290 while (cup) {
3291 cup->cleanup(cup->data);
3292 cup = cup->prev;
3293 }
3294 GC_ExitThread(0);
3295 }
3296
3297 #endif /* GAUCHE_USE_WTHREADS */
3298
3299 #endif /* GAUCHE_WINDOWS */
3300
3301 /*===============================================================
3302 * Initialization
3303 */
3304 void Scm__InitSystem(void)
3305 {
3306 ScmModule *mod = Scm_GaucheModule();
3307 Scm_InitStaticClass(&Scm_SysStatClass, "<sys-stat>", mod, stat_slots, 0);
3308 Scm_InitStaticClass(&Scm_TimeClass, "<time>", mod, time_slots, 0);
3309 Scm_InitStaticClass(&Scm_SysGroupClass, "<sys-group>", mod, grp_slots, 0);
3310 Scm_InitStaticClass(&Scm_SysPasswdClass, "<sys-passwd>", mod, pwd_slots, 0);
3311 #ifdef HAVE_SELECT
3312 Scm_InitStaticClass(&Scm_SysFdsetClass, "<sys-fdset>", mod, NULL, 0);
3313 #endif
3314 SCM_INTERNAL_MUTEX_INIT(env_mutex);
3315 Scm_HashCoreInitSimple(&env_strings, SCM_HASH_STRING, 0, NULL);
3316
3317 key_absolute = SCM_MAKE_KEYWORD("absolute");
3318 key_expand = SCM_MAKE_KEYWORD("expand");
3319 key_canonicalize = SCM_MAKE_KEYWORD("canonicalize");
3320
3321 initial_ugid_differ = (geteuid() != getuid() || getegid() != getgid());
3322
3323 #ifdef GAUCHE_WINDOWS
3324 init_winsock();
3325 SCM_INTERNAL_MUTEX_INIT(process_mgr.mutex);
3326 Scm_AddCleanupHandler(fini_winsock, NULL);
3327 Scm_AddCleanupHandler(win_process_cleanup, NULL);
3328 #endif
3329 }