-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjob.c
2160 lines (1866 loc) · 54.9 KB
/
job.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $NetBSD: job.c,v 1.466 2024/03/01 16:41:42 sjg Exp $ */
/*
* Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Adam de Boor.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Copyright (c) 1988, 1989 by Adam de Boor
* Copyright (c) 1989 by Berkeley Softworks
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Adam de Boor.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Create child processes and collect their output.
*
* Interface:
* Job_Init Called to initialize this module. In addition,
* the .BEGIN target is made, including all of its
* dependencies before this function returns.
* Hence, the makefiles must have been parsed
* before this function is called.
*
* Job_End Clean up any memory used.
*
* Job_Make Start the creation of the given target.
*
* Job_CatchChildren
* Check for and handle the termination of any
* children. This must be called reasonably
* frequently to keep the whole make going at
* a decent clip, since job table entries aren't
* removed until their process is caught this way.
*
* Job_ParseShell Given a special dependency line with target '.SHELL',
* define the shell that is used for the creation
* commands in jobs mode.
*
* Job_Finish Perform any final processing which needs doing.
* This includes the execution of any commands
* which have been/were attached to the .END
* target. It should only be called when the
* job table is empty.
*
* Job_AbortAll Abort all currently running jobs. Do not handle
* output or do anything for the jobs, just kill them.
* Should only be called in an emergency.
*
* Job_CheckCommands
* Verify that the commands for a target are
* ok. Provide them if necessary and possible.
*
* Job_Touch Update a target without really updating it.
*
* Job_Wait Wait for all currently-running jobs to finish.
*/
#include <process.h>
#include "make.h"
#include "dir.h"
#include "job.h"
#include "trace.h"
/* "@(#)job.c 8.2 (Berkeley) 3/19/94" */
/*
* A shell defines how the commands are run. All commands for a target are
* written into a single buffer, which is then given to the shell to execute
* the commands, using -c, from it. The commands are written to the buffer
* using a few templates for echo control and error control.
*
* The name of the shell is the basename for the shell, such as "cmd.exe"
* and "pwsh.exe".
*
* The error checking for individual commands is controlled using runChkTmpl.
*
* echoTmpl is a printf template for echoing the command, should echoing
* be on; runIgnTmpl is another printf template for executing the command
* while ignoring the return status. Finally runChkTmpl is a printf template
* for running the command and causing the shell to exit on error. If any of
* these strings are empty the command will be executed anyway as is, and if
* it causes an error, so be it. Any templates set up to echo the command will
* escape any meta characters in the command string to avoid unwanted shell code
* injection, the escaped command is safe to use in double quotes.
*
* metaChar and specialChar are used for escaping characters. metaChar is a
* char array with 128 elements where metaChar[c] would be 1 if c needed to
* be escaped and 0 otherwise. specialChar lists characters that need to be
* escaped in a special way, e.g a newline. All characters used in specialChar
* also need to be present in metaChar.
*/
typedef struct Shell {
const char *name; /* name of the shell */
/* template to run a command without error checking */
const char *runIgnTmpl;
/* template to run a command with error checking */
const char *runChkTmpl;
const char *echoTmpl; /* template to echo a command */
/*
* Arguments to be passed to the shell.
* This should end with the 'exec' flag, usually /c.
*/
const char *args;
/*
* Character used to execute multiple commands on one line,
* regardless of whether the last command failed or not.
*/
char separator;
char commentChar; /* character used by shell for comment lines */
char escapeChar; /* escape character used by shell */
/*
* Characters that need to be escaped in a special way.
* specialChar[0] is the character to be escaped, and the rest
* of the string is the escaped character. Multiple characters
* should be seperated by a nul character, the array ends with
* two trailing nuls.
* e.g "a!a\0b^b\0" means that 'a' can be escaped using '!a'
* and 'b' can be escaped using '^b'.
*/
char *specialChar;
/*
* An array used to determine characters are interpreted
* specially by the shell.
*
* When we predefine shells, this is initialized as
* a string of characters for convenience. Shell_Init turns
* this into a metaChar table.
*/
unsigned char *metaChar;
} Shell;
typedef struct CommandFlags {
/* Whether to echo the command before or instead of running it. */
bool echo;
/* Run the command even in -n or -N mode. */
bool always;
/*
* true if we turned error checking off before writing the command to
* the commands file and need to turn it back on
*/
bool ignerr;
} CommandFlags;
/*
* Write shell commands to a file.
*
* TODO: keep track of whether commands are echoed.
* TODO: keep track of whether error checking is active.
*/
typedef struct ShellWriter {
Buffer *b;
} ShellWriter;
/* error handling variables */
static int job_errors = 0; /* number of errors reported */
static enum { /* Why is the make aborting? */
ABORT_NONE,
ABORT_ERROR, /* Aborted because of an error */
ABORT_INTERRUPT, /* Aborted because it was interrupted */
ABORT_WAIT /* Waiting for jobs to finish */
} aborting = ABORT_NONE;
#define JOB_TOKENS "+EI+" /* Token to requeue for each abort state */
/* Tracks the number of tokens currently "out" to build jobs. */
int jobTokensRunning = 0;
typedef enum JobStartResult {
JOB_RUNNING, /* Job is running */
JOB_ERROR, /* Error in starting the job */
JOB_FINISHED /* The job is already finished */
} JobStartResult;
/*
* Descriptions for various shells.
*
* The build environment may set DEFSHELL_INDEX to one of
* DEFSHELL_INDEX_SH, DEFSHELL_INDEX_KSH, or DEFSHELL_INDEX_CSH, to
* select one of the predefined shells as the default shell.
*
* Alternatively, the build environment may set DEFSHELL_CUSTOM to the
* name or the full path of a sh-compatible shell, which will be used as
* the default shell.
*
* ".SHELL" lines in Makefiles can choose the default shell from the
* set defined here, or add additional shells.
*/
#ifdef DEFSHELL_CUSTOM
#define DEFSHELL_INDEX_CUSTOM 0
#endif /* !DEFSHELL_CUSTOM */
#ifndef DEFSHELL_INDEX
#define DEFSHELL_INDEX 0 /* DEFSHELL_INDEX_CUSTOM or DEFSHELL_INDEX_SH */
#endif /* !DEFSHELL_INDEX */
/*
* The maximum number of pointers that can
* be stored in shell_freeIt.
*
* This includes:
*
* shell itself
* ShellName
* ShellPath
* Shell.runIgnTmpl
* Shell.runChkTmpl
* Shell.echoTmpl
* Shell.specialChar
* Shell.metaChar
* Shell.args
*/
#define NSHELLDATA 9
static Shell shells[] = {
/* Command Prompt description.*/
{
"cmd.exe", /* .name */
"%s&", /* .runIgnTmpl */
"%s||exit&", /* .runChkTmpl */
"echo %s&", /* .echoTmpl */
"/c", /* .args */
'&', /* .separator */
'\0', /* .commentChar */
'^', /* .escapeChar */
"\n&echo:\0", /* .specialChar */
"\n%&<>^|" /* .metaChar */
},
/* Powershell description. */
{
"pwsh.exe", /* .name */
/*
* We set $lastexitcode to null if the command fails
* in order not to confuse runChkTmpl.
*/
"$(%s)||$($lastexitcode=$null);", /* .runIgnTmpl */
/*
* Powershell only sets $lastexitcode when
* and actual application is run, so it wont
* be set if a command is misspelt for example.
* In this case, we simply exit with 1.
*/
"$(%s)||$(if($lastexitcode-ne$null)"
"{exit $lastexitcode}exit 1);", /* .runChkTmpl */
"echo %s;", /* .echoTmpl */
"/c", /* .args */
';', /* .separator */
'#', /* .commentChar */
'`', /* .escapeChar */
"\"`\\\"\0\n`n\0", /* .specialChar */
"\n\"#$&'*();<>@`{|} " /* .metaChar */
}
};
/*
* This is the shell to which we pass all commands in the Makefile.
* It is set by the Job_ParseShell function.
*/
static Shell *shell = &shells[DEFSHELL_INDEX];
const char *shellPath = NULL; /* full pathname of executable image */
const char *shellName = NULL; /* last component of shellPath */
static void *shell_freeIt[NSHELLDATA]; /* Allocated memory for custom .SHELL */
static Job *job_table; /* The structures that describe them */
static Job *job_table_end; /* job_table + maxJobs */
static char *targPrefix = NULL; /* To identify a job change in the output. */
static Job tokenWaitJob; /* token wait pseudo-job */
static HANDLE job_mutex = NULL;
static void CollectOutput(Job *, bool);
static void MAKE_ATTR_DEAD JobInterrupt(bool);
static void
SwitchOutputTo(GNode *gn)
{
/* The node for which output was most recently produced. */
static GNode *lastNode = NULL;
if (gn == lastNode)
return;
lastNode = gn;
if (opts.maxJobs != 1 && targPrefix != NULL && targPrefix[0] != '\0')
(void)fprintf(stdout, "%s %s ---\n", targPrefix, gn->name);
}
void
Job_FlagsToString(const Job *job, char *buf, size_t bufsize)
{
snprintf(buf, bufsize, "%c%c%c",
job->ignerr ? 'i' : '-',
!job->echo ? 's' : '-',
job->special ? 'S' : '-');
}
static void
DumpJobs(const char *where)
{
Job *job;
char flags[4];
debug_printf("job table @ %s\n", where);
for (job = job_table; job < job_table_end; job++) {
Job_FlagsToString(job, flags, sizeof flags);
debug_printf("job %d, status %d, flags %s, pid %lu\n",
(int)(job - job_table), job->status, flags, job->pid);
}
}
/*
* Delete the target of a failed, interrupted, or otherwise
* unsuccessful job unless inhibited by .PRECIOUS.
*/
static void
JobDeleteTarget(GNode *gn)
{
const char *file;
if (gn->type & OP_JOIN)
return;
if (gn->type & OP_PHONY)
return;
if (GNode_IsPrecious(gn))
return;
if (opts.noExecute)
return;
file = GNode_Path(gn);
if (unlink_file(file) == 0)
Error("*** %s removed", file);
}
static void
JobCreatePipe(Job *job)
{
if (CreatePipe(&job->inPipe, &job->outPipe, NULL, PIPESZ) == 0)
Punt("failed to create pipe: %s", strerr(GetLastError()));
/*
* We mark the input side of the pipe non-blocking; we might lose the
* race for the token when a new one becomes available, so the read
* from the pipe should not block.
*/
if (SetNamedPipeHandleState(job->inPipe, &(DWORD){PIPE_NOWAIT}, NULL, NULL) == 0)
Punt("failed to set pipe handle state: %s", strerr(GetLastError()));
if (SetHandleInformation(job->outPipe, HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT) == 0)
Punt("failed to set pipe attributes: %s", strerr(GetLastError()));
}
/*
* Terminate all jobs, catching any output they
* may have produced, then exit.
*/
MAKE_ATTR_DEAD static void
JobPassSig_int(void)
{
/* Run .INTERRUPT target then exit */
JobInterrupt(true);
}
MAKE_ATTR_DEAD static void
JobPassSig_term(void)
{
/* Dont run .INTERRUPT target then exit */
JobInterrupt(false);
}
static Job *
JobFindHandle(HANDLE handle, JobStatus status, bool isJobs)
{
Job *job;
for (job = job_table; job < job_table_end; job++) {
if (job->status == status && job->handle == handle)
return job;
}
if (DEBUG(JOB) && isJobs)
DumpJobs("no handle");
return NULL;
}
/* Parse leading '@', '-' and '+', which control the exact execution mode. */
static void
ParseCommandFlags(char **pp, CommandFlags *out_cmdFlags)
{
char *p = *pp;
out_cmdFlags->echo = true;
out_cmdFlags->ignerr = false;
out_cmdFlags->always = false;
for (;;) {
if (*p == '@')
out_cmdFlags->echo = DEBUG(LOUD);
else if (*p == '-')
out_cmdFlags->ignerr = true;
else if (*p == '+')
out_cmdFlags->always = true;
else if (!ch_isspace(*p))
/* Ignore whitespace for compatibility with GNU make */
break;
p++;
}
pp_skip_whitespace(&p);
*pp = p;
}
/* Escape characters interpreted specially by the shell. */
static char *
EscapeShell(char *cmd)
{
size_t i;
LazyBuf esc;
if (shell->metaChar == NULL)
return cmd;
LazyBuf_Init(&esc, cmd);
for (i = 0; cmd[i] != '\0'; i++) {
if (ch_is_shell_meta(cmd[i], shell->metaChar)) {
const char *s;
if ((s = ch_is_shell_special(cmd[i], shell->specialChar))
!= NULL) {
LazyBuf_AddStr(&esc, s);
continue;
}
LazyBuf_Add(&esc, shell->escapeChar);
}
LazyBuf_Add(&esc, cmd[i]);
}
LazyBuf_Add(&esc, '\0');
return esc.data == NULL ? UNCONST(esc.expected) : esc.data;
}
static void
ShellWriter_WriteFmt(ShellWriter *wr, const char *fmt, const char *arg)
{
DEBUG1(JOB, fmt, arg);
char *str = _alloca((size_t)snprintf(NULL, 0, fmt, arg) + 1);
sprintf(str, fmt, arg);
Buf_AddStr(wr->b, str);
}
static void
ShellWriter_WriteLine(ShellWriter *wr, const char *line)
{
ShellWriter_WriteFmt(wr, "%s\n", line);
}
static void
ShellWriter_EchoCmd(ShellWriter *wr, const char *escCmd)
{
ShellWriter_WriteFmt(wr, shell->echoTmpl, escCmd);
}
/*
* The shell has no built-in error control, so emulate error control by
* enclosing each shell command in a template like "{ %s \n } || exit $?"
* (configurable per shell).
*/
static void
JobWriteSpecialsEchoCtl(Job *job, ShellWriter *wr, CommandFlags *inout_cmdFlags,
const char *escCmd, const char **inout_cmdTemplate)
{
/* XXX: Why is the whole job modified at this point? */
job->ignerr = true;
if (job->echo && inout_cmdFlags->echo) {
ShellWriter_EchoCmd(wr, escCmd);
/*
* Leave echoing off so the user doesn't see the commands
* for toggling the error checking.
*/
inout_cmdFlags->echo = false;
}
*inout_cmdTemplate = shell->runIgnTmpl;
/*
* The template runIgnTmpl already takes care of ignoring errors,
* so pretend error checking is still on.
* XXX: What effects does this have, and why is it necessary?
*/
inout_cmdFlags->ignerr = false;
}
static void
JobWriteSpecials(Job *job, ShellWriter *wr, const char *escCmd, bool run,
CommandFlags *inout_cmdFlags, const char **inout_cmdTemplate)
{
if (!run)
inout_cmdFlags->ignerr = false;
else if (shell->runIgnTmpl != NULL && shell->runIgnTmpl[0] != '\0') {
JobWriteSpecialsEchoCtl(job, wr, inout_cmdFlags, escCmd,
inout_cmdTemplate);
} else
inout_cmdFlags->ignerr = false;
}
/*
* Write a shell command to the job's commands file, to be run later.
*
* If the command starts with '@' and neither the -s nor the -n flag was
* given to make, stick a shell-specific echoOff command in the script.
*
* If the command starts with '-' and the shell has no error control (none
* of the predefined shells has that), ignore errors for the entire job.
*
* XXX: Why ignore errors for the entire job? This is even documented in the
* manual page, but without any rationale since there is no known rationale.
*
* XXX: The manual page says the '-' "affects the entire job", but that's not
* accurate. The '-' does not affect the commands before the '-'.
*
* If the command is just "...", skip all further commands of this job. These
* commands are attached to the .END node instead and will be run by
* Job_Finish after all other targets have been made.
*/
static void
JobWriteCommand(Job *job, ShellWriter *wr, StringListNode *ln, const char *ucmd)
{
bool run;
CommandFlags cmdFlags;
/* Template for writing a command to the shell file */
const char *cmdTemplate;
char *xcmd; /* The expanded command */
char *xcmdStart;
char *escCmd; /* xcmd escaped to be used in double quotes */
run = GNode_ShouldExecute(job->node);
xcmd = Var_SubstInTarget(ucmd, job->node);
/* TODO: handle errors */
xcmdStart = xcmd;
cmdTemplate = "%s\n";
ParseCommandFlags(&xcmd, &cmdFlags);
/* The '+' command flag overrides the -n or -N options. */
if (cmdFlags.always && !run) {
/*
* We're not actually executing anything...
* but this one needs to be - use compat mode just for it.
*/
(void)Compat_RunCommand(ucmd, job->node, ln);
free(xcmdStart);
return;
}
escCmd = EscapeShell(xcmd);
if (cmdFlags.ignerr) {
JobWriteSpecials(job, wr, escCmd, run, &cmdFlags, &cmdTemplate);
} else {
/*
* If errors are being checked and the shell doesn't have
* error control but does supply an runChkTmpl template, then
* set up commands to run through it.
*/
if (shell->runChkTmpl != NULL &&
shell->runChkTmpl[0] != '\0') {
if (job->echo && cmdFlags.echo) {
ShellWriter_EchoCmd(wr, escCmd);
cmdFlags.echo = false;
}
/*
* If it's a comment line or blank, avoid the possible
* syntax error generated by "{\n} || exit $?".
*/
cmdTemplate = escCmd[0] == shell->commentChar ||
escCmd[0] == '\0'
? shell->runIgnTmpl
: shell->runChkTmpl;
cmdFlags.ignerr = false;
}
}
ShellWriter_WriteFmt(wr, cmdTemplate, xcmd);
if (escCmd != xcmd)
free(escCmd);
free(xcmdStart);
}
/*
* Write all commands to the shell file that is later executed.
*
* The special command "..." stops writing and saves the remaining commands
* to be executed later, when the target '.END' is made.
*
* Return whether at least one command was written to the shell file.
*/
static bool
JobWriteCommands(Job *job)
{
StringListNode *ln;
bool seen = false;
ShellWriter wr;
wr.b = job->cmdBuffer;
for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
const char *cmd = ln->datum;
if (strcmp(cmd, "...") == 0) {
job->node->type |= OP_SAVE_CMDS;
job->tailCmds = ln->next;
break;
}
JobWriteCommand(job, &wr, ln, ln->datum);
seen = true;
}
/* Remove trailing separator. */
if (job->cmdBuffer->len > 0)
job->cmdBuffer->data[--job->cmdBuffer->len] = '\0';
DEBUG0(JOB, "\n");
return seen;
}
/*
* Save the delayed commands (those after '...'), to be executed later in
* the '.END' node, when everything else is done.
*/
static void
JobSaveCommands(Job *job)
{
StringListNode *ln;
for (ln = job->tailCmds; ln != NULL; ln = ln->next) {
const char *cmd = ln->datum;
char *expanded_cmd;
/*
* XXX: This Var_Subst is only intended to expand the dynamic
* variables such as .TARGET, .IMPSRC. It is not intended to
* expand the other variables as well; see deptgt-end.mk.
*/
expanded_cmd = Var_SubstInTarget(cmd, job->node);
/* TODO: handle errors */
Lst_Append(&Targ_GetEndNode()->commands, expanded_cmd);
Parse_RegisterCommand(expanded_cmd);
}
}
/* Called to close both input and output pipes when a job is finished. */
static void
JobClosePipes(Job *job)
{
CollectOutput(job, true);
CloseHandle(job->outPipe);
job->outPipe = NULL;
CloseHandle(job->inPipe);
job->inPipe = NULL;
}
static void
DebugFailedJob(const Job *job)
{
const StringListNode *ln;
if (!DEBUG(ERROR))
return;
debug_printf("\n");
debug_printf("*** Failed target: %s\n", job->node->name);
debug_printf("*** In directory: %s\n", curdir);
debug_printf("*** Failed commands:\n");
for (ln = job->node->commands.first; ln != NULL; ln = ln->next) {
const char *cmd = ln->datum;
debug_printf("\t%s\n", cmd);
if (strchr(cmd, '$') != NULL) {
char *xcmd = Var_Subst(cmd, job->node, VARE_EVAL);
debug_printf("\t=> %s\n", xcmd);
free(xcmd);
}
}
}
static void
JobFinishDoneExitedError(Job *job, DWORD *inout_status)
{
SwitchOutputTo(job->node);
#ifdef USE_META
if (useMeta) {
meta_job_error(job, job->node,
job->ignerr, *inout_status);
}
#endif
if (!shouldDieQuietly(job->node, -1)) {
DebugFailedJob(job);
(void)printf("*** [%s] Error code %ld%s\n",
job->node->name, *inout_status,
job->ignerr ? " (ignored)" : "");
}
if (job->ignerr)
*inout_status = 0;
else {
if (deleteOnError)
JobDeleteTarget(job->node);
PrintOnError(job->node, "\n");
}
}
static void
JobFinishDoneExited(Job *job, DWORD *inout_status)
{
DEBUG2(JOB, "Process %lu [%s] exited.\n", job->pid, job->node->name);
if (*inout_status != 0)
JobFinishDoneExitedError(job, inout_status);
else if (DEBUG(JOB)) {
SwitchOutputTo(job->node);
(void)printf("*** [%s] Completed successfully\n",
job->node->name);
}
(void)fflush(stdout);
}
/*
* Do final processing for the given job including updating parent nodes and
* starting new jobs as available/necessary.
*
* Deferred commands for the job are placed on the .END node.
*
* If there was a serious error (job_errors != 0; not an ignored one), no more
* jobs will be started.
*
* Input:
* job job to finish
* status sub-why job went away
*/
static void
JobFinish(Job *job, DWORD status)
{
bool return_job_token;
DEBUG3(JOB, "JobFinish: %lu [%s], status %lu\n",
job->pid, job->node->name, status);
JobClosePipes(job);
CloseHandle(job->handle);
if (job->cmdBuffer != NULL) {
Buf_Done(job->cmdBuffer);
free(job->cmdBuffer);
job->cmdBuffer = NULL;
}
JobFinishDoneExited(job, &status);
#ifdef USE_META
if (useMeta) {
int meta_status = meta_job_finish(job);
if (meta_status != 0 && status == 0)
status = meta_status;
}
#endif
return_job_token = false;
Trace_Log(JOBEND, job);
if (!job->special) {
if (status != 0 ||
(aborting == ABORT_ERROR) || aborting == ABORT_INTERRUPT)
return_job_token = true;
}
if (aborting != ABORT_ERROR && aborting != ABORT_INTERRUPT &&
status == 0) {
/*
* As long as we aren't aborting and the job didn't return a
* non-zero status that we shouldn't ignore, we call
* Make_Update to update the parents.
*/
JobSaveCommands(job);
job->node->made = MADE;
if (!job->special)
return_job_token = true;
Make_Update(job->node);
job->status = JOB_ST_FREE;
} else if (status != 0) {
job_errors++;
job->status = JOB_ST_FREE;
}
if (job_errors > 0 && !opts.keepgoing && aborting != ABORT_INTERRUPT) {
/* Prevent more jobs from getting started. */
aborting = ABORT_ERROR;
}
if (return_job_token)
Job_TokenReturn();
if (aborting == ABORT_ERROR && jobTokensRunning == 0)
Finish(job_errors);
}
static void
TouchRegular(GNode *gn)
{
const char *file = GNode_Path(gn);
ULARGE_INTEGER t;
FILETIME ft;
HANDLE fh;
/* convert our time_t value to a FILETIME value */
t.QuadPart = (now * 10000000LL) + 116444736000000000LL;
ft.dwLowDateTime = t.LowPart;
ft.dwHighDateTime = t.HighPart;
if ((fh = CreateFileA(file, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE ||
SetFileTime(fh, NULL, &ft, &ft) == 0) {
(void)fprintf(stderr, "*** couldn't touch %s: %s\n",
file, strerr(GetLastError()));
(void)fflush(stderr);
}
CloseHandle(fh);
}
/*
* Touch the given target. Called by JobStart when the -t flag was given.
*
* The modification date of the file is changed.
* If the file did not exist, it is created.
*/
void
Job_Touch(GNode *gn, bool echo)
{
if (gn->type &
(OP_JOIN | OP_USE | OP_USEBEFORE | OP_EXEC | OP_OPTIONAL |
OP_SPECIAL | OP_PHONY)) {
/*
* These are "virtual" targets and should not really be
* created.
*/
return;
}
if (echo || !GNode_ShouldExecute(gn)) {
(void)fprintf(stdout, "touch %s\n", gn->name);
(void)fflush(stdout);
}
if (!GNode_ShouldExecute(gn))
return;
if (gn->type & OP_ARCHV)
Arch_Touch(gn);
else if (gn->type & OP_LIB)
Arch_TouchLib(gn);
else
TouchRegular(gn);
}
/*
* Make sure the given node has all the commands it needs.
*
* The node will have commands from the .DEFAULT rule added to it if it
* needs them.
*
* Input:
* gn The target whose commands need verifying
* abortProc Function to abort with message
*
* Results:
* true if the commands list is/was ok.
*/
bool
Job_CheckCommands(GNode *gn, void (*abortProc)(const char *, ...))
{
if (GNode_IsTarget(gn))
return true;
if (!Lst_IsEmpty(&gn->commands))
return true;
if ((gn->type & OP_LIB) && !Lst_IsEmpty(&gn->children))
return true;
/*
* No commands. Look for .DEFAULT rule from which we might infer
* commands.
*/
if (defaultNode != NULL && !Lst_IsEmpty(&defaultNode->commands) &&
!(gn->type & OP_SPECIAL)) {
/*
* The traditional Make only looks for a .DEFAULT if the node
* was never the target of an operator, so that's what we do
* too.
*
* The .DEFAULT node acts like a transformation rule, in that
* gn also inherits any attributes or sources attached to
* .DEFAULT itself.
*/
Make_HandleUse(defaultNode, gn);
Var_Set(gn, IMPSRC, GNode_VarTarget(gn));
return true;
}
Dir_UpdateMTime(gn, false);
if (gn->mtime != 0 || (gn->type & OP_SPECIAL))
return true;
/*
* The node wasn't the target of an operator. We have no .DEFAULT
* rule to go on and the target doesn't already exist. There's
* nothing more we can do for this branch. If the -k flag wasn't
* given, we stop in our tracks, otherwise we just don't update
* this node's parents so they never get examined.
*/