launcher.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /* Setuptools Script Launcher for Windows
  2. This is a stub executable for Windows that functions somewhat like
  3. Effbot's "exemaker", in that it runs a script with the same name but
  4. a .py extension, using information from a #! line. It differs in that
  5. it spawns the actual Python executable, rather than attempting to
  6. hook into the Python DLL. This means that the script will run with
  7. sys.executable set to the Python executable, where exemaker ends up with
  8. sys.executable pointing to itself. (Which means it won't work if you try
  9. to run another Python process using sys.executable.)
  10. To build/rebuild with mingw32, do this in the setuptools project directory:
  11. gcc -DGUI=0 -mno-cygwin -O -s -o setuptools/cli.exe launcher.c
  12. gcc -DGUI=1 -mwindows -mno-cygwin -O -s -o setuptools/gui.exe launcher.c
  13. To build for Windows RT, install both Visual Studio Express for Windows 8
  14. and for Windows Desktop (both freeware), create "win32" application using
  15. "Windows Desktop" version, create new "ARM" target via
  16. "Configuration Manager" menu and modify ".vcxproj" file by adding
  17. "<WindowsSDKDesktopARMSupport>true</WindowsSDKDesktopARMSupport>" tag
  18. as child of "PropertyGroup" tags that has "Debug|ARM" and "Release|ARM"
  19. properties.
  20. It links to msvcrt.dll, but this shouldn't be a problem since it doesn't
  21. actually run Python in the same process. Note that using 'exec' instead
  22. of 'spawn' doesn't work, because on Windows this leads to the Python
  23. executable running in the *background*, attached to the same console
  24. window, meaning you get a command prompt back *before* Python even finishes
  25. starting. So, we have to use spawnv() and wait for Python to exit before
  26. continuing. :(
  27. */
  28. #include <stdlib.h>
  29. #include <stdio.h>
  30. #include <string.h>
  31. #include <windows.h>
  32. #include <tchar.h>
  33. #include <fcntl.h>
  34. int child_pid=0;
  35. int fail(char *format, char *data) {
  36. /* Print error message to stderr and return 2 */
  37. fprintf(stderr, format, data);
  38. return 2;
  39. }
  40. char *quoted(char *data) {
  41. int i, ln = strlen(data), nb;
  42. /* We allocate twice as much space as needed to deal with worse-case
  43. of having to escape everything. */
  44. char *result = calloc(ln*2+3, sizeof(char));
  45. char *presult = result;
  46. *presult++ = '"';
  47. for (nb=0, i=0; i < ln; i++)
  48. {
  49. if (data[i] == '\\')
  50. nb += 1;
  51. else if (data[i] == '"')
  52. {
  53. for (; nb > 0; nb--)
  54. *presult++ = '\\';
  55. *presult++ = '\\';
  56. }
  57. else
  58. nb = 0;
  59. *presult++ = data[i];
  60. }
  61. for (; nb > 0; nb--) /* Deal w trailing slashes */
  62. *presult++ = '\\';
  63. *presult++ = '"';
  64. *presult++ = 0;
  65. return result;
  66. }
  67. char *loadable_exe(char *exename) {
  68. /* HINSTANCE hPython; DLL handle for python executable */
  69. char *result;
  70. /* hPython = LoadLibraryEx(exename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
  71. if (!hPython) return NULL; */
  72. /* Return the absolute filename for spawnv */
  73. result = calloc(MAX_PATH, sizeof(char));
  74. strncpy(result, exename, MAX_PATH);
  75. /*if (result) GetModuleFileNameA(hPython, result, MAX_PATH);
  76. FreeLibrary(hPython); */
  77. return result;
  78. }
  79. char *find_exe(char *exename, char *script) {
  80. char drive[_MAX_DRIVE], dir[_MAX_DIR], fname[_MAX_FNAME], ext[_MAX_EXT];
  81. char path[_MAX_PATH], c, *result;
  82. /* convert slashes to backslashes for uniform search below */
  83. result = exename;
  84. while (c = *result++) if (c=='/') result[-1] = '\\';
  85. _splitpath(exename, drive, dir, fname, ext);
  86. if (drive[0] || dir[0]=='\\') {
  87. return loadable_exe(exename); /* absolute path, use directly */
  88. }
  89. /* Use the script's parent directory, which should be the Python home
  90. (This should only be used for bdist_wininst-installed scripts, because
  91. easy_install-ed scripts use the absolute path to python[w].exe
  92. */
  93. _splitpath(script, drive, dir, fname, ext);
  94. result = dir + strlen(dir) -1;
  95. if (*result == '\\') result--;
  96. while (*result != '\\' && result>=dir) *result-- = 0;
  97. _makepath(path, drive, dir, exename, NULL);
  98. return loadable_exe(path);
  99. }
  100. char **parse_argv(char *cmdline, int *argc)
  101. {
  102. /* Parse a command line in-place using MS C rules */
  103. char **result = calloc(strlen(cmdline), sizeof(char *));
  104. char *output = cmdline;
  105. char c;
  106. int nb = 0;
  107. int iq = 0;
  108. *argc = 0;
  109. result[0] = output;
  110. while (isspace(*cmdline)) cmdline++; /* skip leading spaces */
  111. do {
  112. c = *cmdline++;
  113. if (!c || (isspace(c) && !iq)) {
  114. while (nb) {*output++ = '\\'; nb--; }
  115. *output++ = 0;
  116. result[++*argc] = output;
  117. if (!c) return result;
  118. while (isspace(*cmdline)) cmdline++; /* skip leading spaces */
  119. if (!*cmdline) return result; /* avoid empty arg if trailing ws */
  120. continue;
  121. }
  122. if (c == '\\')
  123. ++nb; /* count \'s */
  124. else {
  125. if (c == '"') {
  126. if (!(nb & 1)) { iq = !iq; c = 0; } /* skip " unless odd # of \ */
  127. nb = nb >> 1; /* cut \'s in half */
  128. }
  129. while (nb) {*output++ = '\\'; nb--; }
  130. if (c) *output++ = c;
  131. }
  132. } while (1);
  133. }
  134. void pass_control_to_child(DWORD control_type) {
  135. /*
  136. * distribute-issue207
  137. * passes the control event to child process (Python)
  138. */
  139. if (!child_pid) {
  140. return;
  141. }
  142. GenerateConsoleCtrlEvent(child_pid,0);
  143. }
  144. BOOL control_handler(DWORD control_type) {
  145. /*
  146. * distribute-issue207
  147. * control event handler callback function
  148. */
  149. switch (control_type) {
  150. case CTRL_C_EVENT:
  151. pass_control_to_child(0);
  152. break;
  153. }
  154. return TRUE;
  155. }
  156. int create_and_wait_for_subprocess(char* command) {
  157. /*
  158. * distribute-issue207
  159. * launches child process (Python)
  160. */
  161. DWORD return_value = 0;
  162. LPSTR commandline = command;
  163. STARTUPINFOA s_info;
  164. PROCESS_INFORMATION p_info;
  165. ZeroMemory(&p_info, sizeof(p_info));
  166. ZeroMemory(&s_info, sizeof(s_info));
  167. s_info.cb = sizeof(STARTUPINFO);
  168. // set-up control handler callback funciotn
  169. SetConsoleCtrlHandler((PHANDLER_ROUTINE) control_handler, TRUE);
  170. if (!CreateProcessA(NULL, commandline, NULL, NULL, TRUE, 0, NULL, NULL, &s_info, &p_info)) {
  171. fprintf(stderr, "failed to create process.\n");
  172. return 0;
  173. }
  174. child_pid = p_info.dwProcessId;
  175. // wait for Python to exit
  176. WaitForSingleObject(p_info.hProcess, INFINITE);
  177. if (!GetExitCodeProcess(p_info.hProcess, &return_value)) {
  178. fprintf(stderr, "failed to get exit code from process.\n");
  179. return 0;
  180. }
  181. return return_value;
  182. }
  183. char* join_executable_and_args(char *executable, char **args, int argc)
  184. {
  185. /*
  186. * distribute-issue207
  187. * CreateProcess needs a long string of the executable and command-line arguments,
  188. * so we need to convert it from the args that was built
  189. */
  190. int len,counter;
  191. char* cmdline;
  192. len=strlen(executable)+2;
  193. for (counter=1; counter<argc; counter++) {
  194. len+=strlen(args[counter])+1;
  195. }
  196. cmdline = (char*)calloc(len, sizeof(char));
  197. sprintf(cmdline, "%s", executable);
  198. len=strlen(executable);
  199. for (counter=1; counter<argc; counter++) {
  200. sprintf(cmdline+len, " %s", args[counter]);
  201. len+=strlen(args[counter])+1;
  202. }
  203. return cmdline;
  204. }
  205. int run(int argc, char **argv, int is_gui) {
  206. char python[256]; /* python executable's filename*/
  207. char *pyopt; /* Python option */
  208. char script[256]; /* the script's filename */
  209. int scriptf; /* file descriptor for script file */
  210. char **newargs, **newargsp, **parsedargs; /* argument array for exec */
  211. char *ptr, *end; /* working pointers for string manipulation */
  212. char *cmdline;
  213. int i, parsedargc; /* loop counter */
  214. /* compute script name from our .exe name*/
  215. GetModuleFileNameA(NULL, script, sizeof(script));
  216. end = script + strlen(script);
  217. while( end>script && *end != '.')
  218. *end-- = '\0';
  219. *end-- = '\0';
  220. strcat(script, (GUI ? "-script.pyw" : "-script.py"));
  221. /* figure out the target python executable */
  222. scriptf = open(script, O_RDONLY);
  223. if (scriptf == -1) {
  224. return fail("Cannot open %s\n", script);
  225. }
  226. end = python + read(scriptf, python, sizeof(python));
  227. close(scriptf);
  228. ptr = python-1;
  229. while(++ptr < end && *ptr && *ptr!='\n' && *ptr!='\r') {;}
  230. *ptr-- = '\0';
  231. if (strncmp(python, "#!", 2)) {
  232. /* default to python.exe if no #! header */
  233. strcpy(python, "#!python.exe");
  234. }
  235. parsedargs = parse_argv(python+2, &parsedargc);
  236. /* Using spawnv() can fail strangely if you e.g. find the Cygwin
  237. Python, so we'll make sure Windows can find and load it */
  238. ptr = find_exe(parsedargs[0], script);
  239. if (!ptr) {
  240. return fail("Cannot find Python executable %s\n", parsedargs[0]);
  241. }
  242. /* printf("Python executable: %s\n", ptr); */
  243. /* Argument array needs to be
  244. parsedargc + argc, plus 1 for null sentinel */
  245. newargs = (char **)calloc(parsedargc + argc + 1, sizeof(char *));
  246. newargsp = newargs;
  247. *newargsp++ = quoted(ptr);
  248. for (i = 1; i<parsedargc; i++) *newargsp++ = quoted(parsedargs[i]);
  249. *newargsp++ = quoted(script);
  250. for (i = 1; i < argc; i++) *newargsp++ = quoted(argv[i]);
  251. *newargsp++ = NULL;
  252. /* printf("args 0: %s\nargs 1: %s\n", newargs[0], newargs[1]); */
  253. if (is_gui) {
  254. /* Use exec, we don't need to wait for the GUI to finish */
  255. execv(ptr, (const char * const *)(newargs));
  256. return fail("Could not exec %s", ptr); /* shouldn't get here! */
  257. }
  258. /*
  259. * distribute-issue207: using CreateProcessA instead of spawnv
  260. */
  261. cmdline = join_executable_and_args(ptr, newargs, parsedargc + argc);
  262. return create_and_wait_for_subprocess(cmdline);
  263. }
  264. int WINAPI WinMain(HINSTANCE hI, HINSTANCE hP, LPSTR lpCmd, int nShow) {
  265. return run(__argc, __argv, GUI);
  266. }
  267. int main(int argc, char** argv) {
  268. return run(argc, argv, GUI);
  269. }