1 /* run -- Wrapper program for console mode programs under Windows(TM)
2 * Copyright (C) 1998 Charles S. Wilson
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 * This program is based on the runemacs.c distributed with XEmacs 21.0
22 * Simple program to start gnu-win32 X11 programs (and native XEmacs)
23 * with its console window hidden.
25 * This program is provided purely for convenience, since most users will
26 * use XEmacs in windowing (GUI) mode, and will not want to have an extra
27 * console window lying around. Ditto for desktop shortcuts to gnu-win32
43 #if defined(__CYGWIN__)
44 #include <sys/types.h>
46 #include <sys/cygwin.h>
47 #include <sys/unistd.h>
48 WinMainCRTStartup() { mainCRTStartup(); }
57 WinMain (HINSTANCE hSelf, HINSTANCE hPrev, LPSTR cmdline, int nShow)
59 int wait_for_child = FALSE;
60 int compact_invocation = FALSE;
64 char execname[FILENAME_MAX];
65 char execpath[MAX_PATH];
66 char* argv[MAX_ARGS+1]; /* leave extra slot for compact_invocation argv[0] */
69 char exec[MAX_PATH + FILENAME_MAX + 100];
70 char cmdline2[MAX_ARGS * MAX_PATH];
76 compact_invocation = get_exec_name_and_path(execname,execpath);
78 if (compact_invocation)
81 argc = parse_cmdline_to_arg_array(&(argv[1]),cmdline);
86 argc = parse_cmdline_to_arg_array(argv,cmdline);
88 strcpy(execname,argv[0]);
90 /* at this point, execpath is defined, as are argv[] and execname */
92 j = sprintf(buffer,"\nexecname : %s\nexecpath : %s\n",execname,execpath);
93 for (i = 0; i < argc; i++)
94 j += sprintf(buffer+j,"argv[%d]\t: %s\n",i,argv[i]);
99 error("you must supply a program name to run");
101 #if defined(__CYGWIN__)
102 /* this insures that we search for symlinks before .exe's */
103 if (compact_invocation)
107 process_execname(exec,execname,execpath);
108 Trace(("exec\t%s\nexecname\t%s\nexecpath\t%s\n",
109 exec,execname,execpath));
111 wait_for_child = build_cmdline(cmdline2,exec,argc,argv);
114 xemacs_special(exec);
115 ret_code = start_child(cmdline2,wait_for_child);
116 if (compact_invocation)
117 for (i = 1; i < argc; i++) // argv[0] was not malloc'ed
120 for (i = 0; i < argc; i++)
122 return (int) ret_code;
124 int start_child(char* cmdline, int wait_for_child)
127 SECURITY_ATTRIBUTES sec_attrs;
128 PROCESS_INFORMATION child;
131 memset (&start, 0, sizeof (start));
132 start.cb = sizeof (start);
133 start.dwFlags = STARTF_USESHOWWINDOW;
134 start.wShowWindow = SW_HIDE;
136 sec_attrs.nLength = sizeof (sec_attrs);
137 sec_attrs.lpSecurityDescriptor = NULL;
138 sec_attrs.bInheritHandle = FALSE;
140 if (CreateProcess (NULL, cmdline, &sec_attrs, NULL, TRUE, 0,
141 NULL, NULL, &start, &child))
145 WaitForSingleObject (child.hProcess, INFINITE);
146 GetExitCodeProcess (child.hProcess, &retval);
148 CloseHandle (child.hThread);
149 CloseHandle (child.hProcess);
152 error("could not start %s",cmdline);
155 void xemacs_special(char* exec)
158 * if we're trying to run xemacs, AND this file was in %emacs_dir%\bin,
159 * then set emacs_dir environment variable
163 char exec2[MAX_PATH + FILENAME_MAX + 100];
164 #if defined(__CYGWIN__)
165 char tmp[MAX_PATH + FILENAME_MAX + 100];
168 /* this depends on short-circuit evaluation */
169 if ( ((p = strrchr(exec2,'\\')) && stricmp(p,"\\xemacs") == 0) ||
170 ((p = strrchr(exec2,'/')) && stricmp(p,"/xemacs") == 0) ||
171 ((p = strrchr(exec2,'\\')) && stricmp(p,"\\xemacs.exe") == 0) ||
172 ((p = strrchr(exec2,'/')) && stricmp(p,"/xemacs.exe") == 0) )
174 if ( ((p2 = strrchr(p, '\\')) && stricmp(p2, "\\bin") == 0) ||
175 ((p2 = strrchr(p, '/')) && stricmp(p2, "/bin") == 0) )
178 #if defined(__CYGWIN__)
179 CYGWIN_CONV_TO_POSIX_PATH((exec2,tmp));
181 #else /* NATIVE xemacs DOS-style paths with forward slashes */
182 for (p = exec2; *p; p++)
183 if (*p == '\\') *p = '/';
185 SetEnvironmentVariable ("emacs_dir", exec2);
189 int build_cmdline(char* new_cmdline, char* exec, int argc, char* argv[])
196 * look for "-wait" as first true argument; we'll apply that ourselves
198 if ((argc >= 2) && (stricmp(argv[1],"-wait") == 0))
204 char_cnt = strlen(exec);
205 for (i = first_arg; i < argc; i++)
206 char_cnt += strlen(argv[i]);
207 if (char_cnt > MAX_ARGS*MAX_PATH) /* then we ran out of room */
208 error("command line too long -\n%s",new_cmdline);
210 strcpy(new_cmdline,exec);
211 for (i = first_arg; i < argc; i++)
213 strcat(new_cmdline," ");
214 strcat(new_cmdline,argv[i]);
218 /* process exec_arg : if it
220 * 1) starts with '\\' or '/', it's a root-path and leave it alone
221 * 2) starts with 'x:\\' or 'x:/', it's a root-path and leave it alone
222 * 3) starts with '.\\' or './', two possible meanings:
223 * 1) exec is in the current directory
224 * 2) exec in same directory as this program
225 * 4) otherwise, search path (and _prepend_ "." to the path!!!)
226 * 5) convert all '/' to '\\'
228 * 1) starts with '\\' or '/', it's a root-path and leave it alone
229 * 2) starts with 'x:\\' or 'x:/', it's a root-path and leave it alone
230 * 3) starts with '.\\' or './', two possible meanings:
231 * 1) exec is in the current directory
232 * 2) exec in same directory as this program
233 * 4) otherwise, search path (and _prepend_ "." to the path!!!)
234 * 5) convert to cygwin-style path to resolve symlinks within the pathspec
235 * 6) check filename: if it's a symlink, resolve it by peeking inside
236 * 7) convert to win32-style path+filename since we're using Windows
237 * createProcess() to launch
239 void process_execname(char *exec, const char* execname,const char* execpath )
243 char exec_tmp[MAX_PATH + FILENAME_MAX + 100];
244 char exec_tmp2[MAX_PATH + FILENAME_MAX + 100];
245 char buf[MAX_PATH + FILENAME_MAX + 100];
252 if ((execname[0] == '\\') || (execname[0] == '/'))
254 #if defined(__CYGWIN__)
255 strcpy(exec_tmp,execname);
257 exec_tmp[0] = ((char) (_getdrive() + ((int) 'A') - 1));
260 strcat(exec_tmp,execname);
262 Trace(("/ -\nexec_tmp\t%s\nexecname\t%s\nexecpath\t%s\n",
263 exec_tmp,execname,execpath));
264 if (! fileExistsMulti(exec_tmp2,NULL,exec_tmp,exts,NUM_EXTENSIONS) )
267 for (i = 0; i < NUM_EXTENSIONS; i++)
268 j += sprintf(buf + j," [%d]: %s\n",i+1,exts[i]);
269 error("Couldn't locate %s\nI tried appending the following "
270 "extensions: \n%s",exec_tmp,buf);
275 * STARTS WITH x:\ or x:/
278 else if ((strlen(execname) > 3) && // avoid boundary errors
279 (execname[1] == ':') &&
280 ((execname[2] == '\\') || (execname[2] == '/')))
282 strcpy(exec_tmp,execname);
283 Trace(("x: -\nexec_tmp\t%s\nexecname\t%s\nexecpath\t%s\n",
284 exec_tmp,execname,execpath));
285 if (! fileExistsMulti(exec_tmp2,NULL,exec_tmp,exts,NUM_EXTENSIONS) )
288 for (i = 0; i < NUM_EXTENSIONS; i++)
289 j += sprintf(buf + j," [%d]: %s\n",i+1,exts[i]);
290 error("Couldn't locate %s\nI tried appending the following "
291 "extensions: \n%s",exec_tmp,buf);
296 * STARTS WITH ./ or .\
298 else if ((execname[0] == '.') &&
299 ((execname[1] == '\\') || (execname[1] == '/')))
301 if (((char*) getcwd(exec_tmp,MAX_PATH))==NULL)
302 error("can't find current working directory");
303 if (! fileExistsMulti(exec_tmp2,exec_tmp,&(execname[2]),
304 exts,NUM_EXTENSIONS) )
305 if (! fileExistsMulti(exec_tmp2,execpath,&(execname[2]),
306 exts,NUM_EXTENSIONS) )
309 for (i = 0; i < NUM_EXTENSIONS; i++)
310 j += sprintf(buf + j," [%d]: %s\n",i+1,exts[i]);
311 error("Couldn't locate %s\n"
312 "I looked in the following directories:\n [1]: %s\n [2]: %s\n"
313 "I also tried appending the following "
314 "extensions: \n%s",execname,exec_tmp,execpath,buf);
319 * OTHERWISE, SEARCH PATH (prepend '.' and run.exe's directory)
320 * can't use fileExistsMulti because we want to search entire path
321 * for exts[0], then for exts[1], etc.
325 orig_pathlist = getenv("PATH");
326 if ((pathlist = malloc (strlen(orig_pathlist)
328 + strlen(execpath)+ 3)) == NULL)
329 error("internal error - out of memory");
330 strcpy(pathlist,".");
331 strcat(pathlist,SEP_CHARS);
332 strcat(pathlist,execpath);
333 strcat(pathlist,SEP_CHARS);
334 strcat(pathlist,orig_pathlist);
337 for (i = 0; i < NUM_EXTENSIONS; i++)
339 strcpy(exec_tmp,execname);
340 strcat(exec_tmp,exts[i]);
341 pfopen(exec_tmp2,exec_tmp,pathlist);
342 if (fileExists(NULL,NULL,exec_tmp2))
346 Trace(("exec_tmp\t%s\npathlist\t%s\n",exec_tmp2,pathlist));
349 if (exec_tmp2[0] == '\0')
352 for (i = 0; i < NUM_EXTENSIONS; i++)
353 j += sprintf(buf + j," [%d]: %s\n",i+1,exts[i]);
354 error("Couldn't find %s anywhere.\n"
355 "I even looked in the PATH \n"
356 "I also tried appending the following "
357 "extensions: \n%s",execname,buf);
361 * At this point, we know that exec_tmp2 contains a filename
362 * and we know that exec_tmp2 exists.
364 #if defined(__CYGWIN__)
367 char sym_link_name[MAX_PATH+1];
368 char real_name[MAX_PATH+1];
369 char dummy[MAX_PATH+1];
371 strcpy(exec_tmp,exec_tmp2);
373 CYGWIN_CONV_TO_POSIX_PATH((exec_tmp,sym_link_name));
374 Trace((sym_link_name));
376 if (lstat(sym_link_name, &stbuf) == 0)
378 if ((stbuf.st_mode & S_IFLNK) == S_IFLNK)
380 if (readlink(sym_link_name, real_name, sizeof(real_name)) == -1)
381 error("problem reading symbolic link for %s",exec_tmp);
384 // if realname starts with '/' it's a rootpath
385 if (real_name[0] == '/')
386 strcpy(exec_tmp2,real_name);
387 else // otherwise, it's relative to the symlink's location
389 CYGWIN_SPLIT_PATH((sym_link_name,exec_tmp2,dummy));
390 if (!endsWith(exec_tmp2,PATH_SEP_CHAR_STR))
391 strcat(exec_tmp2,PATH_SEP_CHAR_STR);
392 strcat(exec_tmp2,real_name);
396 else /* NOT a symlink */
397 strcpy(exec_tmp2, sym_link_name);
400 error("can't locate executable - %s",sym_link_name);
402 CYGWIN_CONV_TO_FULL_WIN32_PATH((exec_tmp2,exec));
404 strcpy (exec, exec_tmp2);
407 int endsWith(const char* s1, const char* s2)
414 if (len1 - len2 >= 0)
415 if (stricmp(&(s1[len1-len2]),s2) == 0)
418 }void strip_exe(char* s)
420 if ((strlen(s) > 4) && // long enough to have .exe extension
421 // second part not evaluated (short circuit) if exec_arg too short
422 (stricmp(&(s[strlen(s)-4]),".exe") == 0))
423 s[strlen(s)-4] = '\0';
425 void error(char* fmt, ...)
431 j = sprintf(buf, "Error: ");
432 j += vsprintf(buf + j,fmt,args);
433 j += sprintf(buf + j,"\n");
435 MessageBox(NULL, buf, "Run.exe", MB_ICONSTOP);
438 void message(char* fmt, ...)
444 j = vsprintf(buf,fmt,args);
445 j += sprintf(buf + j,"\n");
447 MessageBox(NULL, buf, "Run.exe Message", MB_ICONSTOP);
449 void Trace_(char* fmt, ...)
455 j = vsprintf(buf,fmt,args);
456 j += sprintf(buf + j,"\n");
458 MessageBox(NULL, buf, "Run.exe DEBUG", MB_ICONSTOP);
461 * Uses system info to determine the path used to invoke run
462 * Also attempts to deduce the target execname if "compact_invocation"
465 * returns TRUE if compact_invocation method was used
466 * (and target execname was deduced successfully)
467 * otherwise returns FALSE, and execname == run or run.exe
469 int get_exec_name_and_path(char* execname, char* execpath)
471 char modname[MAX_PATH];
476 if (!GetModuleFileName (NULL, modname, MAX_PATH))
477 error("internal error - can't find my own name");
478 if ((p = strrchr (modname, '\\')) == NULL)
479 error("internal error - my own name has no path\n%s",modname);
480 tmp_execname = p + 1;
482 // if invoked by a name like "runxemacs" then strip off
483 // the "run" and let "xemacs" be execname.
484 // To check for this, make that:
485 // 1) first three chars are "run"
486 // 2) but the string doesn't end there, or start ".exe"
487 // Also, set "compact_invocation" TRUE
488 if ( ((tmp_execname[0] == 'r') || (tmp_execname[0] == 'R')) &&
489 ((tmp_execname[1] == 'u') || (tmp_execname[1] == 'U')) &&
490 ((tmp_execname[2] == 'n') || (tmp_execname[2] == 'N')) &&
491 ((tmp_execname[3] != '.') && (tmp_execname[3] != '\0')) )
499 if (tmp_execname == NULL)
502 strcpy(execname,tmp_execname);
503 #if defined(__CYGWIN__)
504 CYGWIN_CONV_TO_POSIX_PATH((modname,execpath));
506 strcpy(execpath,modname);
511 * works like strtok, but:
512 * double quotes (") suspends tokenizing until closing " reached
514 * additionally, backslash escapes next character, even if that
515 * next character is a delimiter. Or a double quote.
516 * WARNING: this means that backslash may NOT be a delimiter
518 char* my_strtok(char* s, const char* delim, char** lasts)
524 if ((s == NULL) && ((s = *lasts) == NULL))
526 /* Skip leading delimiters */
529 for (spanp = (char *)delim; (sc = *spanp++) != 0;) {
533 if (c == 0) { /* no non-delimiter characters */
539 * Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
540 * Note that delim must have one NUL; we stop if we see that, too.
541 * If we see a double quote, continue until next double quote, then
542 * start scanning for delimiters again.
543 * CYGWIN ONLY: if we see a backslash, just copy next character -
544 * don't consider it as a delimiter even if it is in delim string.
547 /* if this c is ", then scan until we find next " */
549 while ((c = *s++) != '\"')
550 if (c == 0) /* oops, forgot to close the ", clean up & return */
556 #if defined(__CYGWIN__)
559 c = *s++; /* skip the backslash */
560 if (c == 0) /* if escaped character is end-of-string, clean up & return */
566 c = *s++; /* otherwise, skip the escaped character */
569 spanp = (char *)delim;
571 if ((sc = *spanp++) == c) {
584 int parse_cmdline_to_arg_array(char* argv[MAX_ARGS], char* cmdline)
586 char seps[] = " \t\n";
591 token = my_strtok(cmdline, seps, &lasts);
592 while ((token != NULL) && (argc < MAX_ARGS))
594 if ((argv[argc] = malloc(strlen(token)+1)) == NULL)
596 error("internal error - out of memory");
598 strcpy(argv[argc++],token);
599 token = my_strtok(NULL,seps,&lasts);
601 if (argc >= MAX_ARGS)
602 error("too many arguments on commandline\n%s",cmdline);
605 /* Taken from pfopen.c by David Engel (5-Jul-97).
606 * Original comments appear below. Superseded by next comment block.
608 * Written and released to the public domain by David Engel.
610 * This function attempts to open a file which may be in any of
611 * several directories. It is particularly useful for opening
612 * configuration files. For example, PROG.EXE can easily open
613 * PROG.CFG (which is kept in the same directory) by executing:
615 * cfg_file = pfopen("PROG.CFG", "r", getenv("PATH"));
617 * NULL is returned if the file can't be opened.
621 * This function attempts to locate a file which may be in any of
622 * several directories. Unlike the original pfopen, it does not
623 * return a FILE pointer to the opened file, but rather returns
624 * the fully-qualified filename of the first match found. Returns
625 * empty string if not found.
627 char *pfopen(char *retval, const char *name, const char *dirs)
631 char returnval[MAX_PATH + FILENAME_MAX + 100];
636 if (dirs == NULL || dirs[0] == '\0')
639 if ((tdirs = malloc(strlen(dirs)+1)) == NULL)
644 for (ptr = strtok(tdirs, SEP_CHARS); (foundit == FALSE) && ptr != NULL;
645 ptr = strtok(NULL, SEP_CHARS))
647 foundit = fileExists(returnval,ptr,name);
654 strcpy(retval,returnval);
657 int fileExistsMulti(char* fullname, const char* path,
658 const char* name_noext, const char* exts[],
661 char tryName[MAX_PATH + FILENAME_MAX];
665 for (i = 0; i < extcnt; i++)
667 strcpy(tryName,name_noext);
668 strcat(tryName,exts[i]);
669 if (fileExists(fullname, path, tryName) == TRUE)
678 int fileExists(char* fullname, const char* path, const char* name)
683 char work[FILENAME_MAX];
684 char work2[MAX_PATH + FILENAME_MAX + 100];
689 if (len && work[len-1] != '/' && work[len-1] != '\\')
690 strcat(work, PATH_SEP_CHAR_STR);
696 #if defined(__CYGWIN__)
697 CYGWIN_CONV_TO_POSIX_PATH((work, work2));
703 Trace(("looking for...\t%s\n",work2));
706 file = fopen(work2, "rb");
709 if (fullname != NULL)
710 strcpy(fullname,work2);