glob omits "." and ".."; removed built-in that will never be ported
[k8jam.git] / execnt.c
blobdb4854894c85843dfa64d9941ee281e54fd6cfa2
1 /*
2 * Copyright 1993, 1995 Christopher Seiwald.
4 * This file is part of Jam - see jam.c for Copyright information.
5 */
7 # include "jam.h"
8 # include "lists.h"
9 # include "execcmd.h"
10 # include <errno.h>
12 # ifdef USE_EXECNT
14 # define WIN32_LEAN_AND_MEAN
15 # include <windows.h> /* do the ugly deed */
16 # include <process.h>
18 # if !defined( __BORLANDC__ ) && !defined( OS_OS2 )
19 # define wait my_wait
20 static int my_wait( int *status );
21 # endif
24 * execnt.c - execute a shell command on Windows NT and Windows 95/98
26 * If $(JAMSHELL) is defined, uses that to formulate execvp()/spawnvp().
27 * The default is:
29 * /bin/sh -c % [ on UNIX/AmigaOS ]
30 * cmd.exe /c % [ on Windows NT ]
32 * Each word must be an individual element in a jam variable value.
34 * In $(JAMSHELL), % expands to the command string and ! expands to
35 * the slot number (starting at 1) for multiprocess (-j) invocations.
36 * If $(JAMSHELL) doesn't include a %, it is tacked on as the last
37 * argument.
39 * Don't just set JAMSHELL to /bin/sh or cmd.exe - it won't work!
41 * External routines:
42 * execcmd() - launch an async command execution
43 * execwait() - wait and drive at most one execution completion
45 * Internal routines:
46 * onintr() - bump intr to note command interruption
48 * 04/08/94 (seiwald) - Coherent/386 support added.
49 * 05/04/94 (seiwald) - async multiprocess interface
50 * 01/22/95 (seiwald) - $(JAMSHELL) support
51 * 06/02/97 (gsar) - full async multiprocess support for Win32
54 static int intr = 0;
55 static int cmdsrunning = 0;
56 static void (*istat)( int );
58 static int is_nt_351 = 0;
59 static int is_win95 = 1;
60 static int is_win95_defined = 0;
63 static struct
65 int pid; /* on win32, a real process handle */
66 void (*func)( void *closure, int status );
67 void *closure;
68 char *tempfile;
70 } cmdtab[ MAXJOBS ] = {{0}};
73 static void
74 set_is_win95( void )
76 OSVERSIONINFO os_info;
78 os_info.dwOSVersionInfoSize = sizeof(os_info);
79 os_info.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS;
80 GetVersionEx( &os_info );
82 is_win95 = (os_info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
83 is_win95_defined = 1;
85 /* now, test wether we're running Windows 3.51 */
86 /* this is later used to limit the system call command length */
87 if (os_info.dwPlatformId == VER_PLATFORM_WIN32_NT)
88 is_nt_351 = os_info.dwMajorVersion == 3;
92 static char**
93 string_to_args( const char* string, int* pcount )
95 int total = strlen( string );
96 int in_quote = 0, num_args;
97 char* line;
98 char* p;
99 char** arg;
100 char** args;
102 *pcount = 0;
104 /* do not copy trailing newlines, if any */
106 int i;
108 for ( i = total-1; i > 0; i-- )
110 if ( string[i] != '\n' && string[i] != '\r' )
111 break;
112 total --;
116 /* first of all, copy the input string */
117 line = (char*)malloc( total+2 );
118 if (!line)
119 return 0;
121 memcpy( line+1, string, total );
122 line[0] = 0;
123 line[total+1] = 0;
125 in_quote = 0;
126 for ( p = line+1; p[0]; p++ )
128 switch (p[0])
130 case '"':
131 in_quote = !in_quote;
132 break;
134 case ' ':
135 case '\t':
136 if (!in_quote)
137 p[0] = 0;
139 default:
144 /* now count the arguments.. */
145 for ( p = line; p < line+total+1; p++ )
146 if ( !p[0] && p[1] )
147 num_args++;
149 /* allocate the args array */
150 args = (char**)malloc( num_args*sizeof(char*)+2 );
151 if (!args)
153 free( line );
154 return 0;
157 arg = args+1;
158 for ( p = line; p < line+total+1; p++ )
159 if ( !p[0] && p[1] )
161 arg[0] = p+1;
162 arg++;
164 arg[0] = 0;
165 *pcount = num_args;
166 args[0] = line;
167 return args+1;
170 static void
171 free_args( char** args )
173 free( args[-1] );
174 free( args-1 );
178 /* process a "del" or "erase" command under Windows 95/98 */
179 static int
180 process_del( char* command )
182 char** arg;
183 char* p = command, *q;
184 int wildcard = 0, result = 0;
186 /* first of all, skip the command itself */
187 if ( p[0] == 'd' )
188 p += 3; /* assumes "del..;" */
189 else if ( p[0] == 'e' )
190 p += 5; /* assumes "erase.." */
191 else
192 return 1; /* invalid command */
194 /* process all targets independently */
195 for (;;)
197 /* skip leading spaces */
198 while ( *p && isspace(*p) )
199 p++;
201 /* exit if we encounter an end of string */
202 if (!*p)
203 return 0;
205 /* ignore toggles/flags */
206 if (*p == '/')
208 p++;
209 while ( *p && isalnum(*p) )
210 p++;
212 else
214 int in_quote = 0;
215 int wildcard = 0;
216 int go_on = 1;
218 q = p;
219 while (go_on)
221 switch (*p)
223 case '"':
224 in_quote = !in_quote;
225 break;
227 case '?':
228 case '*':
229 if (!in_quote)
230 wildcard = 1;
231 break;
233 case '\0':
234 if (in_quote)
235 return 1;
236 /* fall-through */
238 case ' ':
239 case '\t':
240 if (!in_quote)
242 int len = p - q;
243 int result;
244 char* line;
246 /* q..p-1 contains the delete argument */
247 if ( len <= 0 )
248 return 1;
250 line = (char*)malloc( len+4+1 );
251 if (!line)
252 return 1;
254 strncpy( line, "del ", 4 );
255 strncpy( line+4, q, len );
256 line[len+4] = '\0';
258 if ( wildcard )
259 result = system( line );
260 else
261 result = !DeleteFile( line+4 );
263 free( line );
264 if (result)
265 return 1;
267 go_on = 0;
270 default:
273 p++;
274 } /* while (go_on) */
281 * onintr() - bump intr to note command interruption
284 void
285 onintr( int disp )
287 intr++;
288 printf( "...interrupted\n" );
292 * execcmd() - launch an async command execution
295 void
296 execcmd(
297 char *string,
298 void (*func)( void *closure, int status ),
299 void *closure,
300 LIST *shell )
302 int pid;
303 int slot;
304 int max_line;
305 char *argv[ MAXARGC + 1 ]; /* +1 for NULL */
306 char *p;
308 if ( !is_win95_defined )
309 set_is_win95();
311 /* Find a slot in the running commands table for this one. */
312 if ( is_win95 )
314 /* only synchronous spans are supported on Windows 95/98 */
315 slot = 0;
317 else
319 for( slot = 0; slot < MAXJOBS; slot++ )
320 if( !cmdtab[ slot ].pid )
321 break;
323 if( slot == MAXJOBS )
325 printf( "no slots for child!\n" );
326 exit( EXITBAD );
329 if( !cmdtab[ slot ].tempfile )
331 char *tempdir;
333 if( !( tempdir = getenv( "TEMP" ) ) &&
334 !( tempdir = getenv( "TMP" ) ) )
335 tempdir = "\\temp";
337 cmdtab[ slot ].tempfile = malloc( strlen( tempdir ) + 14 );
339 sprintf( cmdtab[ slot ].tempfile, "%s\\jamtmp%02d.bat",
340 tempdir, slot );
343 /* Trim leading, ending white space */
345 while( isspace( *string ) )
346 ++string;
348 p = strchr( string, '\n' );
350 while( p && isspace( *p ) )
351 ++p;
353 /* on Windows NT 3.51, the maximul line length is 996 bytes !! */
354 /* while it's much bigger NT 4 and 2k */
355 max_line = is_nt_351 ? 996 : MAXLINE;
357 /* If multi line, or too long, or JAMSHELL is set, write to bat file. */
358 /* Otherwise, exec directly. */
359 /* Frankly, if it is a single long line I don't think the */
360 /* command interpreter will do any better -- it will fail. */
362 if( p && *p || strlen( string ) > max_line || shell )
364 FILE *f;
366 /* Write command to bat file. */
368 f = fopen( cmdtab[ slot ].tempfile, "w" );
369 fputs( string, f );
370 fclose( f );
372 string = cmdtab[ slot ].tempfile;
375 /* Forumulate argv */
376 /* If shell was defined, be prepared for % and ! subs. */
377 /* Otherwise, use stock /bin/sh (on unix) or cmd.exe (on NT). */
379 if( shell )
381 int i;
382 char jobno[4];
383 int gotpercent = 0;
385 sprintf( jobno, "%d", slot + 1 );
387 for( i = 0; shell && i < MAXARGC; i++, shell = list_next( shell ) )
389 switch( shell->string[0] )
391 case '%': argv[i] = string; gotpercent++; break;
392 case '!': argv[i] = jobno; break;
393 default: argv[i] = shell->string;
395 if( DEBUG_EXECCMD )
396 printf( "argv[%d] = '%s'\n", i, argv[i] );
399 if( !gotpercent )
400 argv[i++] = string;
402 argv[i] = 0;
404 else
406 /* don't worry, this is ignored on Win95/98, see later.. */
407 argv[0] = "cmd.exe";
408 argv[1] = "/Q/C"; /* anything more is non-portable */
409 argv[2] = string;
410 argv[3] = 0;
413 /* Catch interrupts whenever commands are running. */
415 if( !cmdsrunning++ )
416 istat = signal( SIGINT, onintr );
418 /* Start the command */
420 /* on Win95, we only do a synchronous call */
421 if ( is_win95 )
423 static const char* hard_coded[] =
425 "del", "erase", "copy", "mkdir", "rmdir", "cls", "dir",
426 "ren", "rename", "move", 0
429 const char** keyword;
430 int len, spawn = 1;
431 int result;
433 for ( keyword = hard_coded; keyword[0]; keyword++ )
435 len = strlen( keyword[0] );
436 if ( strnicmp( string, keyword[0], len ) == 0 &&
437 !isalnum(string[len]) )
439 /* this is one of the hard coded symbols, use 'system' to run */
440 /* them.. except for "del"/"erase" */
441 if ( keyword - hard_coded < 2 )
442 result = process_del( string );
443 else
444 result = system( string );
446 spawn = 0;
447 break;
451 if (spawn)
453 char** args;
454 int num_args;
456 /* convert the string into an array of arguments */
457 /* we need to take care of double quotes !! */
458 args = string_to_args( string, &num_args );
459 if ( args )
461 #if 0
462 char** arg;
463 fprintf( stderr, "%s: ", args[0] );
464 arg = args+1;
465 while ( arg[0] )
467 fprintf( stderr, " {%s}", arg[0] );
468 arg++;
470 fprintf( stderr, "\n" );
471 #endif
472 result = spawnvp( P_WAIT, args[0], args );
473 free_args( args );
475 else
476 result = 1;
478 func( closure, result ? EXEC_CMD_FAIL : EXEC_CMD_OK );
479 return;
482 /* the rest is for Windows NT only */
483 if( ( pid = spawnvp( P_NOWAIT, argv[0], argv ) ) == -1 )
485 perror( "spawn" );
486 exit( EXITBAD );
488 /* Save the operation for execwait() to find. */
490 cmdtab[ slot ].pid = pid;
491 cmdtab[ slot ].func = func;
492 cmdtab[ slot ].closure = closure;
494 /* Wait until we're under the limit of concurrent commands. */
495 /* Don't trust globs.jobs alone. */
497 while( cmdsrunning >= MAXJOBS || cmdsrunning >= globs.jobs )
498 if( !execwait() )
499 break;
503 * execwait() - wait and drive at most one execution completion
507 execwait()
509 int i;
510 int status, w;
511 int rstat;
513 /* Handle naive make1() which doesn't know if cmds are running. */
515 if( !cmdsrunning )
516 return 0;
518 if ( is_win95 )
519 return 0;
521 /* Pick up process pid and status */
523 while( ( w = wait( &status ) ) == -1 && errno == EINTR )
526 if( w == -1 )
528 printf( "child process(es) lost!\n" );
529 perror("wait");
530 exit( EXITBAD );
533 /* Find the process in the cmdtab. */
535 for( i = 0; i < MAXJOBS; i++ )
536 if( w == cmdtab[ i ].pid )
537 break;
539 if( i == MAXJOBS )
541 printf( "waif child found!\n" );
542 exit( EXITBAD );
545 /* Drive the completion */
547 if( !--cmdsrunning )
548 signal( SIGINT, istat );
550 if( intr )
551 rstat = EXEC_CMD_INTR;
552 else if( w == -1 || status != 0 )
553 rstat = EXEC_CMD_FAIL;
554 else
555 rstat = EXEC_CMD_OK;
557 cmdtab[ i ].pid = 0;
559 (*cmdtab[ i ].func)( cmdtab[ i ].closure, rstat );
561 return 1;
564 # if !defined( __BORLANDC__ )
566 static int
567 my_wait( int *status )
569 int i, num_active = 0;
570 DWORD exitcode, waitcode;
571 static HANDLE *active_handles = 0;
573 if (!active_handles)
574 active_handles = (HANDLE *)malloc(globs.jobs * sizeof(HANDLE) );
576 /* first see if any non-waited-for processes are dead,
577 * and return if so.
579 for ( i = 0; i < globs.jobs; i++ ) {
580 if ( cmdtab[i].pid ) {
581 if ( GetExitCodeProcess((HANDLE)cmdtab[i].pid, &exitcode) ) {
582 if ( exitcode == STILL_ACTIVE )
583 active_handles[num_active++] = (HANDLE)cmdtab[i].pid;
584 else {
585 CloseHandle((HANDLE)cmdtab[i].pid);
586 *status = (int)((exitcode & 0xff) << 8);
587 return cmdtab[i].pid;
590 else
591 goto FAILED;
595 /* if a child exists, wait for it to die */
596 if ( !num_active ) {
597 errno = ECHILD;
598 return -1;
600 waitcode = WaitForMultipleObjects( num_active,
601 active_handles,
602 FALSE,
603 INFINITE );
604 if ( waitcode != WAIT_FAILED ) {
605 if ( waitcode >= WAIT_ABANDONED_0
606 && waitcode < WAIT_ABANDONED_0 + num_active )
607 i = waitcode - WAIT_ABANDONED_0;
608 else
609 i = waitcode - WAIT_OBJECT_0;
610 if ( GetExitCodeProcess(active_handles[i], &exitcode) ) {
611 CloseHandle(active_handles[i]);
612 *status = (int)((exitcode & 0xff) << 8);
613 return (int)active_handles[i];
617 FAILED:
618 errno = GetLastError();
619 return -1;
623 # endif /* !__BORLANDC__ */
625 # endif /* USE_EXECNT */