2 * Copyright (c) 2015, 2017
3 * KO Myung-Hun <komh@chollian.net>
5 * mirabilos <m@mirbsd.org>
7 * Provided that these terms and disclaimer and all copyright notices
8 * are retained or reproduced in an accompanying document, permission
9 * is granted to deal in this work without restriction, including un-
10 * limited rights to use, publicly perform, distribute, sell, modify,
11 * merge, give away, or sublicence.
13 * This work is provided "AS IS" and WITHOUT WARRANTY of any kind, to
14 * the utmost extent permitted by applicable law, neither express nor
15 * implied; without malicious intent or gross negligence. In no event
16 * may a licensor, author or contributor be held liable for indirect,
17 * direct, other damage, loss, or other issues arising in any way out
18 * of dealing in the work, even if advised of the possibility of such
19 * damage or existence of a defect, except proven that it results out
20 * of said person's immediate fault when using the work as intended.
28 #include <klibc/startup.h>
34 __RCSID("$MirOS: src/bin/mksh/os2.c,v 1.8 2017/12/22 16:41:42 tg Exp $");
36 static char *remove_trailing_dots(char *);
37 static int access_stat_ex(int (*)(), const char *, void *);
38 static int test_exec_exist(const char *, char *);
39 static void response(int *, const char ***);
40 static char *make_response_file(char * const *);
41 static void add_temp(const char *);
42 static void cleanup_temps(void);
43 static void cleanup(void);
45 #define RPUT(x) do { \
46 if (new_argc >= new_alloc) { \
48 if (!(new_argv = realloc(new_argv, \
49 new_alloc * sizeof(char *)))) \
50 goto exit_out_of_memory; \
52 new_argv[new_argc++] = (x); \
53 } while (/* CONSTCOND */ 0)
55 #define KLIBC_ARG_RESPONSE_EXCLUDE \
56 (__KLIBC_ARG_DQUOTE | __KLIBC_ARG_WILDCARD | __KLIBC_ARG_SHELL)
59 response(int *argcp, const char ***argvp)
61 int i, old_argc, new_argc, new_alloc = 0;
62 const char **old_argv, **new_argv;
68 for (i = 1; i < old_argc; ++i)
70 !(old_argv[i][-1] & KLIBC_ARG_RESPONSE_EXCLUDE) &&
71 old_argv[i][0] == '@')
80 for (i = 0; i < old_argc; ++i) {
81 if (i == 0 || !old_argv[i] ||
82 (old_argv[i][-1] & KLIBC_ARG_RESPONSE_EXCLUDE) ||
83 old_argv[i][0] != '@' ||
84 !(f = fopen(old_argv[i] + 1, "rt")))
89 fseek(f, 0, SEEK_END);
91 fseek(f, 0, SEEK_SET);
93 line = malloc(filesize + /* type */ 1 + /* NUL */ 1);
96 fputs("Out of memory while reading response file\n", stderr);
100 line[0] = __KLIBC_ARG_NONZERO | __KLIBC_ARG_RESPONSE;
102 while (fgets(l, (filesize + 1) - (l - (line + 1)), f)) {
106 * if a line ends with a backslash,
107 * concatenate with the next line
109 if (p > l && p[-1] == '\\') {
113 for (p1 = p - 1; p1 >= l &&
128 goto exit_out_of_memory;
138 fputs("Cannot read response file\n", stderr);
154 init_extlibpath(void)
156 const char *vars[] = {
165 for (flag = 0; vars[flag]; flag++) {
166 DosQueryExtLIBPATH(val, flag + 1);
168 setenv(vars[flag], val, 1);
173 os2_init(int *argcp, const char ***argvp)
175 response(argcp, argvp);
179 if (!isatty(STDIN_FILENO))
180 setmode(STDIN_FILENO, O_BINARY);
181 if (!isatty(STDOUT_FILENO))
182 setmode(STDOUT_FILENO, O_BINARY);
183 if (!isatty(STDERR_FILENO))
184 setmode(STDERR_FILENO, O_BINARY);
190 setextlibpath(const char *name, const char *val)
195 if (!strcmp(name, "BEGINLIBPATH"))
196 flag = BEGIN_LIBPATH;
197 else if (!strcmp(name, "ENDLIBPATH"))
199 else if (!strcmp(name, "LIBPATHSTRICT"))
200 flag = LIBPATHSTRICT;
204 /* convert slashes to backslashes */
205 strdupx(cp, val, ATEMP);
206 for (p = cp; *p; p++) {
211 DosSetExtLIBPATH(cp, flag);
216 /* remove trailing dots */
218 remove_trailing_dots(char *name)
220 char *p = strnul(name);
222 while (--p > name && *p == '.')
225 if (*p != '.' && *p != '/' && *p != '\\' && *p != ':')
231 #define REMOVE_TRAILING_DOTS(name) \
232 remove_trailing_dots(memcpy(alloca(strlen(name) + 1), name, strlen(name) + 1))
234 /* alias of stat() */
235 extern int _std_stat(const char *, struct stat *);
237 /* replacement for stat() of kLIBC which fails if there are trailing dots */
239 stat(const char *name, struct stat *buffer)
241 return (_std_stat(REMOVE_TRAILING_DOTS(name), buffer));
244 /* alias of access() */
245 extern int _std_access(const char *, int);
247 /* replacement for access() of kLIBC which fails if there are trailing dots */
249 access(const char *name, int mode)
252 * On OS/2 kLIBC, X_OK is set only for executable files.
253 * This prevents scripts from being executed.
256 mode = (mode & ~X_OK) | R_OK;
258 return (_std_access(REMOVE_TRAILING_DOTS(name), mode));
261 #define MAX_X_SUFFIX_LEN 4
263 static const char *x_suffix_list[] =
264 { "", ".ksh", ".exe", ".sh", ".cmd", ".com", ".bat", NULL };
266 /* call fn() by appending executable extensions */
268 access_stat_ex(int (*fn)(), const char *name, void *arg)
271 const char **x_suffix;
273 size_t x_namelen = strlen(name) + MAX_X_SUFFIX_LEN + 1;
275 /* otherwise, try to append executable suffixes */
276 x_name = alloc(x_namelen, ATEMP);
278 for (x_suffix = x_suffix_list; rc && *x_suffix; x_suffix++) {
279 strlcpy(x_name, name, x_namelen);
280 strlcat(x_name, *x_suffix, x_namelen);
282 rc = fn(x_name, arg);
285 afree(x_name, ATEMP);
290 /* access()/search_access() version */
292 access_ex(int (*fn)(const char *, int), const char *name, int mode)
294 /*XXX this smells fishy --mirabilos */
295 return (access_stat_ex(fn, name, (void *)mode));
300 stat_ex(const char *name, struct stat *buffer)
302 return (access_stat_ex(stat, name, buffer));
306 test_exec_exist(const char *name, char *real_name)
310 if (stat(name, &sb) < 0 || !S_ISREG(sb.st_mode))
313 /* safe due to calculations in real_exec_name() */
314 memcpy(real_name, name, strlen(name) + 1);
320 real_exec_name(const char *name)
322 char x_name[strlen(name) + MAX_X_SUFFIX_LEN + 1];
323 const char *real_name = name;
325 if (access_stat_ex(test_exec_exist, real_name, x_name) != -1)
327 strdupx(real_name, x_name, ATEMP);
332 /* make a response file to pass a very long command line */
334 make_response_file(char * const *argv)
336 char rsp_name_arg[] = "@mksh-rsp-XXXXXX";
337 char *rsp_name = &rsp_name_arg[1];
342 if ((fd = mkstemp(rsp_name)) == -1)
345 /* write all the arguments except a 0th program name */
346 for (i = 1; argv[i]; i++) {
347 write(fd, argv[i], strlen(argv[i]));
353 strdupx(result, rsp_name_arg, ATEMP);
358 /* alias of execve() */
359 extern int _std_execve(const char *, char * const *, char * const *);
361 /* replacement for execve() of kLIBC */
363 execve(const char *name, char * const *argv, char * const *envp)
365 const char *exec_name;
376 * #! /bin/sh : append .exe
377 * extproc sh : search sh.exe in PATH
379 exec_name = search_path(name, path, X_OK, NULL);
386 * kLIBC execve() has problems when executing scripts.
387 * 1. it fails to execute a script if a directory whose name
388 * is same as an interpreter exists in a current directory.
389 * 2. it fails to execute a script not starting with sharpbang.
390 * 3. it fails to execute a batch file if COMSPEC is set to a shell
391 * incompatible with cmd.exe, such as /bin/sh.
392 * And ksh process scripts more well, so let ksh process scripts.
395 if (!(fp = fopen(exec_name, "rb")))
398 if (!errno && fread(sign, 1, sizeof(sign), fp) != sizeof(sign))
401 if (fp && fclose(fp))
405 !((sign[0] == 'M' && sign[1] == 'Z') ||
406 (sign[0] == 'N' && sign[1] == 'E') ||
407 (sign[0] == 'L' && sign[1] == 'X')))
410 if (errno == ENOEXEC)
414 * Normal OS/2 programs expect that standard IOs, especially stdin,
415 * are opened in text mode at the startup. By the way, on OS/2 kLIBC
416 * child processes inherit a translation mode of a parent process.
417 * As a result, if stdin is set to binary mode in a parent process,
418 * stdin of child processes is opened in binary mode as well at the
419 * startup. In this case, some programs such as sed suffer from CR.
421 saved_mode = setmode(STDIN_FILENO, O_TEXT);
423 pid = spawnve(P_NOWAIT, exec_name, argv, envp);
426 /* arguments too long? */
427 if (pid == -1 && saved_errno == EINVAL) {
428 /* retry with a response file */
429 char *rsp_name_arg = make_response_file(argv);
432 char *rsp_argv[3] = { argv[0], rsp_name_arg, NULL };
434 pid = spawnve(P_NOWAIT, exec_name, rsp_argv, envp);
437 afree(rsp_name_arg, ATEMP);
441 /* restore translation mode of stdin */
442 setmode(STDIN_FILENO, saved_mode);
451 /* close all opened handles */
452 for (fd = 0; fd < NUFILE; fd++) {
453 if (fcntl(fd, F_GETFD) == -1)
459 while ((rc = waitpid(pid, &status, 0)) < 0 && errno == EINTR)
464 /* Is this possible? And is this right? */
468 if (WIFSIGNALED(status))
469 _exit(ksh_sigmask(WTERMSIG(status)));
471 _exit(WEXITSTATUS(status));
474 static struct temp *templist = NULL;
477 add_temp(const char *name)
481 tp = alloc(offsetof(struct temp, tffn[0]) + strlen(name) + 1, APERM);
482 memcpy(tp->tffn, name, strlen(name) + 1);
487 /* alias of unlink() */
488 extern int _std_unlink(const char *);
491 * Replacement for unlink() of kLIBC not supporting to remove files used by
495 unlink(const char *name)
499 rc = _std_unlink(name);
500 if (rc == -1 && errno != ENOENT)
510 struct temp **tpnext;
512 for (tpnext = &templist, tp = templist; tp; tp = *tpnext) {
513 if (_std_unlink(tp->tffn) == 0 || errno == ENOENT) {
529 getdrvwd(char **cpp, unsigned int drvltr)
536 if (DosQuerySysInfo(QSV_MAX_PATH_LENGTH, QSV_MAX_PATH_LENGTH,
537 &sz, sizeof(sz)) != 0) {
542 /* allocate 'X:/' plus sz plus NUL */
543 checkoktoadd((size_t)sz, (size_t)4);
544 cp = aresize(*cpp, (size_t)sz + (size_t)4, ATEMP);
545 cp[0] = ksh_toupper(drvltr);
548 drvno = ksh_numuc(cp[0]) + 1;
549 /* NUL is part of space within buffer passed */
551 if ((rc = DosQueryCurrentDir(drvno, cp + 3, &sz)) == 0) {
559 case 15: /* invalid drive */
562 case 26: /* not dos disk */
565 case 108: /* drive locked */
568 case 111: /* buffer overflow */
569 errno = ENAMETOOLONG;