-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProcessWin32.c
2781 lines (2435 loc) · 86.2 KB
/
ProcessWin32.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
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing#kwsys for details. */
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Process.h)
#include KWSYS_HEADER(Encoding.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
# include "Encoding.h.in"
# include "Process.h.in"
#endif
/*
Implementation for Windows
On windows, a thread is created to wait for data on each pipe. The
threads are synchronized with the main thread to simulate the use of
a UNIX-style select system call.
*/
#ifdef _MSC_VER
# pragma warning(push, 1)
#endif
#include <windows.h> /* Windows API */
#if defined(_MSC_VER) && _MSC_VER >= 1800
# define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
#endif
#include <io.h> /* _unlink */
#include <stdio.h> /* snprintf */
#include <string.h> /* strlen, strdup */
#ifndef _MAX_FNAME
# define _MAX_FNAME 4096
#endif
#ifndef _MAX_PATH
# define _MAX_PATH 4096
#endif
#ifdef _MSC_VER
# pragma warning(pop)
# pragma warning(disable : 4514)
# pragma warning(disable : 4706)
#endif
/* There are pipes for the process pipeline's stdout and stderr. */
#define KWSYSPE_PIPE_COUNT 2
#define KWSYSPE_PIPE_STDOUT 0
#define KWSYSPE_PIPE_STDERR 1
/* The maximum amount to read from a pipe at a time. */
#define KWSYSPE_PIPE_BUFFER_SIZE 1024
/* Debug output macro. */
#if 0
# define KWSYSPE_DEBUG(x) \
((void*)cp == (void*)0x00226DE0 \
? (fprintf(stderr, "%d/%p/%d ", (int)GetCurrentProcessId(), cp, \
__LINE__), \
fprintf x, fflush(stderr), 1) \
: (1))
#else
# define KWSYSPE_DEBUG(x) (void)1
#endif
typedef LARGE_INTEGER kwsysProcessTime;
typedef struct kwsysProcessCreateInformation_s
{
/* Windows child startup control data. */
STARTUPINFOW StartupInfo;
/* Original handles before making inherited duplicates. */
HANDLE hStdInput;
HANDLE hStdOutput;
HANDLE hStdError;
} kwsysProcessCreateInformation;
typedef struct kwsysProcessPipeData_s kwsysProcessPipeData;
static DWORD WINAPI kwsysProcessPipeThreadRead(LPVOID ptd);
static void kwsysProcessPipeThreadReadPipe(kwsysProcess* cp,
kwsysProcessPipeData* td);
static DWORD WINAPI kwsysProcessPipeThreadWake(LPVOID ptd);
static void kwsysProcessPipeThreadWakePipe(kwsysProcess* cp,
kwsysProcessPipeData* td);
static int kwsysProcessInitialize(kwsysProcess* cp);
static DWORD kwsysProcessCreate(kwsysProcess* cp, int index,
kwsysProcessCreateInformation* si);
static void kwsysProcessDestroy(kwsysProcess* cp, int event);
static DWORD kwsysProcessSetupOutputPipeFile(PHANDLE handle, const char* name);
static void kwsysProcessSetupSharedPipe(DWORD nStdHandle, PHANDLE handle);
static void kwsysProcessSetupPipeNative(HANDLE native, PHANDLE handle);
static void kwsysProcessCleanupHandle(PHANDLE h);
static void kwsysProcessCleanup(kwsysProcess* cp, DWORD error);
static void kwsysProcessCleanErrorMessage(kwsysProcess* cp);
static int kwsysProcessGetTimeoutTime(kwsysProcess* cp, double* userTimeout,
kwsysProcessTime* timeoutTime);
static int kwsysProcessGetTimeoutLeft(kwsysProcessTime* timeoutTime,
double* userTimeout,
kwsysProcessTime* timeoutLength);
static kwsysProcessTime kwsysProcessTimeGetCurrent(void);
static DWORD kwsysProcessTimeToDWORD(kwsysProcessTime t);
static double kwsysProcessTimeToDouble(kwsysProcessTime t);
static kwsysProcessTime kwsysProcessTimeFromDouble(double d);
static int kwsysProcessTimeLess(kwsysProcessTime in1, kwsysProcessTime in2);
static kwsysProcessTime kwsysProcessTimeAdd(kwsysProcessTime in1,
kwsysProcessTime in2);
static kwsysProcessTime kwsysProcessTimeSubtract(kwsysProcessTime in1,
kwsysProcessTime in2);
static void kwsysProcessSetExitExceptionByIndex(kwsysProcess* cp, int code,
int idx);
static void kwsysProcessKillTree(int pid);
static void kwsysProcessDisablePipeThreads(kwsysProcess* cp);
static int kwsysProcessesInitialize(void);
static int kwsysTryEnterCreateProcessSection(void);
static void kwsysLeaveCreateProcessSection(void);
static int kwsysProcessesAdd(HANDLE hProcess, DWORD dwProcessId,
int newProcessGroup);
static void kwsysProcessesRemove(HANDLE hProcess);
static BOOL WINAPI kwsysCtrlHandler(DWORD dwCtrlType);
/* A structure containing synchronization data for each thread. */
typedef struct kwsysProcessPipeSync_s kwsysProcessPipeSync;
struct kwsysProcessPipeSync_s
{
/* Handle to the thread. */
HANDLE Thread;
/* Semaphore indicating to the thread that a process has started. */
HANDLE Ready;
/* Semaphore indicating to the thread that it should begin work. */
HANDLE Go;
/* Semaphore indicating thread has reset for another process. */
HANDLE Reset;
};
/* A structure containing data for each pipe's threads. */
struct kwsysProcessPipeData_s
{
/* ------------- Data managed per instance of kwsysProcess ------------- */
/* Synchronization data for reading thread. */
kwsysProcessPipeSync Reader;
/* Synchronization data for waking thread. */
kwsysProcessPipeSync Waker;
/* Index of this pipe. */
int Index;
/* The kwsysProcess instance owning this pipe. */
kwsysProcess* Process;
/* ------------- Data managed per call to Execute ------------- */
/* Buffer for data read in this pipe's thread. */
char DataBuffer[KWSYSPE_PIPE_BUFFER_SIZE];
/* The length of the data stored in the buffer. */
DWORD DataLength;
/* Whether the pipe has been closed. */
int Closed;
/* Handle for the read end of this pipe. */
HANDLE Read;
/* Handle for the write end of this pipe. */
HANDLE Write;
};
/* A structure containing results data for each process. */
typedef struct kwsysProcessResults_s kwsysProcessResults;
struct kwsysProcessResults_s
{
/* The status of the process. */
int State;
/* The exceptional behavior that terminated the process, if any. */
int ExitException;
/* The process exit code. */
DWORD ExitCode;
/* The process return code, if any. */
int ExitValue;
/* Description for the ExitException. */
char ExitExceptionString[KWSYSPE_PIPE_BUFFER_SIZE + 1];
};
/* Structure containing data used to implement the child's execution. */
struct kwsysProcess_s
{
/* ------------- Data managed per instance of kwsysProcess ------------- */
/* The status of the process structure. */
int State;
/* The command lines to execute. */
wchar_t** Commands;
int NumberOfCommands;
/* The exit code of each command. */
DWORD* CommandExitCodes;
/* The working directory for the child process. */
wchar_t* WorkingDirectory;
/* Whether to create the child as a detached process. */
int OptionDetach;
/* Whether the child was created as a detached process. */
int Detached;
/* Whether to hide the child process's window. */
int HideWindow;
/* Whether to treat command lines as verbatim. */
int Verbatim;
/* Whether to merge stdout/stderr of the child. */
int MergeOutput;
/* Whether to create the process in a new process group. */
int CreateProcessGroup;
/* Mutex to protect the shared index used by threads to report data. */
HANDLE SharedIndexMutex;
/* Semaphore used by threads to signal data ready. */
HANDLE Full;
/* Whether we are currently deleting this kwsysProcess instance. */
int Deleting;
/* Data specific to each pipe and its thread. */
kwsysProcessPipeData Pipe[KWSYSPE_PIPE_COUNT];
/* Name of files to which stdin and stdout pipes are attached. */
char* PipeFileSTDIN;
char* PipeFileSTDOUT;
char* PipeFileSTDERR;
/* Whether each pipe is shared with the parent process. */
int PipeSharedSTDIN;
int PipeSharedSTDOUT;
int PipeSharedSTDERR;
/* Native pipes provided by the user. */
HANDLE PipeNativeSTDIN[2];
HANDLE PipeNativeSTDOUT[2];
HANDLE PipeNativeSTDERR[2];
/* ------------- Data managed per call to Execute ------------- */
/* Index of last pipe to report data, if any. */
int CurrentIndex;
/* Index shared by threads to report data. */
int SharedIndex;
/* The timeout length. */
double Timeout;
/* Time at which the child started. */
kwsysProcessTime StartTime;
/* Time at which the child will timeout. Negative for no timeout. */
kwsysProcessTime TimeoutTime;
/* Flag for whether the process was killed. */
int Killed;
/* Flag for whether the timeout expired. */
int TimeoutExpired;
/* Flag for whether the process has terminated. */
int Terminated;
/* The number of pipes still open during execution and while waiting
for pipes to close after process termination. */
int PipesLeft;
/* Buffer for error messages. */
char ErrorMessage[KWSYSPE_PIPE_BUFFER_SIZE + 1];
/* process results. */
kwsysProcessResults* ProcessResults;
/* Windows process information data. */
PROCESS_INFORMATION* ProcessInformation;
/* Data and process termination events for which to wait. */
PHANDLE ProcessEvents;
int ProcessEventsLength;
/* Real working directory of our own process. */
DWORD RealWorkingDirectoryLength;
wchar_t* RealWorkingDirectory;
/* Own handles for the child's ends of the pipes in the parent process.
Used temporarily during process creation. */
HANDLE PipeChildStd[3];
};
kwsysProcess* kwsysProcess_New(void)
{
int i;
/* Process control structure. */
kwsysProcess* cp;
/* Windows version number data. */
OSVERSIONINFO osv;
/* Initialize list of processes before we get any farther. It's especially
important that the console Ctrl handler be added BEFORE starting the
first process. This prevents the risk of an orphaned process being
started by the main thread while the default Ctrl handler is in
progress. */
if (!kwsysProcessesInitialize()) {
return 0;
}
/* Allocate a process control structure. */
cp = (kwsysProcess*)malloc(sizeof(kwsysProcess));
if (!cp) {
/* Could not allocate memory for the control structure. */
return 0;
}
ZeroMemory(cp, sizeof(*cp));
/* Share stdin with the parent process by default. */
cp->PipeSharedSTDIN = 1;
/* Set initial status. */
cp->State = kwsysProcess_State_Starting;
/* Choose a method of running the child based on version of
windows. */
ZeroMemory(&osv, sizeof(osv));
osv.dwOSVersionInfoSize = sizeof(osv);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
# pragma warning(push)
# ifdef __INTEL_COMPILER
# pragma warning(disable : 1478)
# elif defined __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wdeprecated-declarations"
# else
# pragma warning(disable : 4996)
# endif
#endif
GetVersionEx(&osv);
#ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
# ifdef __clang__
# pragma clang diagnostic pop
# else
# pragma warning(pop)
# endif
#endif
if (osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
/* Win9x no longer supported. */
kwsysProcess_Delete(cp);
return 0;
}
/* Initially no thread owns the mutex. Initialize semaphore to 1. */
if (!(cp->SharedIndexMutex = CreateSemaphore(0, 1, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
}
/* Initially no data are available. Initialize semaphore to 0. */
if (!(cp->Full = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
}
/* Create the thread to read each pipe. */
for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
DWORD dummy = 0;
/* Assign the thread its index. */
cp->Pipe[i].Index = i;
/* Give the thread a pointer back to the kwsysProcess instance. */
cp->Pipe[i].Process = cp;
/* No process is yet running. Initialize semaphore to 0. */
if (!(cp->Pipe[i].Reader.Ready = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
}
/* The pipe is not yet reset. Initialize semaphore to 0. */
if (!(cp->Pipe[i].Reader.Reset = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
}
/* The thread's buffer is initially empty. Initialize semaphore to 1. */
if (!(cp->Pipe[i].Reader.Go = CreateSemaphore(0, 1, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
}
/* Create the reading thread. It will block immediately. The
thread will not make deeply nested calls, so we need only a
small stack. */
if (!(cp->Pipe[i].Reader.Thread = CreateThread(
0, 1024, kwsysProcessPipeThreadRead, &cp->Pipe[i], 0, &dummy))) {
kwsysProcess_Delete(cp);
return 0;
}
/* No process is yet running. Initialize semaphore to 0. */
if (!(cp->Pipe[i].Waker.Ready = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
}
/* The pipe is not yet reset. Initialize semaphore to 0. */
if (!(cp->Pipe[i].Waker.Reset = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
}
/* The waker should not wake immediately. Initialize semaphore to 0. */
if (!(cp->Pipe[i].Waker.Go = CreateSemaphore(0, 0, 1, 0))) {
kwsysProcess_Delete(cp);
return 0;
}
/* Create the waking thread. It will block immediately. The
thread will not make deeply nested calls, so we need only a
small stack. */
if (!(cp->Pipe[i].Waker.Thread = CreateThread(
0, 1024, kwsysProcessPipeThreadWake, &cp->Pipe[i], 0, &dummy))) {
kwsysProcess_Delete(cp);
return 0;
}
}
for (i = 0; i < 3; ++i) {
cp->PipeChildStd[i] = INVALID_HANDLE_VALUE;
}
return cp;
}
void kwsysProcess_Delete(kwsysProcess* cp)
{
int i;
/* Make sure we have an instance. */
if (!cp) {
return;
}
/* If the process is executing, wait for it to finish. */
if (cp->State == kwsysProcess_State_Executing) {
if (cp->Detached) {
kwsysProcess_Disown(cp);
} else {
kwsysProcess_WaitForExit(cp, 0);
}
}
/* We are deleting the kwsysProcess instance. */
cp->Deleting = 1;
/* Terminate each of the threads. */
for (i = 0; i < KWSYSPE_PIPE_COUNT; ++i) {
/* Terminate this reading thread. */
if (cp->Pipe[i].Reader.Thread) {
/* Signal the thread we are ready for it. It will terminate
immediately since Deleting is set. */
ReleaseSemaphore(cp->Pipe[i].Reader.Ready, 1, 0);
/* Wait for the thread to exit. */
WaitForSingleObject(cp->Pipe[i].Reader.Thread, INFINITE);
/* Close the handle to the thread. */
kwsysProcessCleanupHandle(&cp->Pipe[i].Reader.Thread);
}
/* Terminate this waking thread. */
if (cp->Pipe[i].Waker.Thread) {
/* Signal the thread we are ready for it. It will terminate
immediately since Deleting is set. */
ReleaseSemaphore(cp->Pipe[i].Waker.Ready, 1, 0);
/* Wait for the thread to exit. */
WaitForSingleObject(cp->Pipe[i].Waker.Thread, INFINITE);
/* Close the handle to the thread. */
kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Thread);
}
/* Cleanup the pipe's semaphores. */
kwsysProcessCleanupHandle(&cp->Pipe[i].Reader.Ready);
kwsysProcessCleanupHandle(&cp->Pipe[i].Reader.Go);
kwsysProcessCleanupHandle(&cp->Pipe[i].Reader.Reset);
kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Ready);
kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Go);
kwsysProcessCleanupHandle(&cp->Pipe[i].Waker.Reset);
}
/* Close the shared semaphores. */
kwsysProcessCleanupHandle(&cp->SharedIndexMutex);
kwsysProcessCleanupHandle(&cp->Full);
/* Free memory. */
kwsysProcess_SetCommand(cp, 0);
kwsysProcess_SetWorkingDirectory(cp, 0);
kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDIN, 0);
kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDOUT, 0);
kwsysProcess_SetPipeFile(cp, kwsysProcess_Pipe_STDERR, 0);
free(cp->CommandExitCodes);
free(cp->ProcessResults);
free(cp);
}
int kwsysProcess_SetCommand(kwsysProcess* cp, char const* const* command)
{
int i;
if (!cp) {
return 0;
}
for (i = 0; i < cp->NumberOfCommands; ++i) {
free(cp->Commands[i]);
}
cp->NumberOfCommands = 0;
if (cp->Commands) {
free(cp->Commands);
cp->Commands = 0;
}
if (command) {
return kwsysProcess_AddCommand(cp, command);
}
return 1;
}
int kwsysProcess_AddCommand(kwsysProcess* cp, char const* const* command)
{
int newNumberOfCommands;
wchar_t** newCommands;
/* Make sure we have a command to add. */
if (!cp || !command || !*command) {
return 0;
}
/* Allocate a new array for command pointers. */
newNumberOfCommands = cp->NumberOfCommands + 1;
if (!(newCommands =
(wchar_t**)malloc(sizeof(wchar_t*) * newNumberOfCommands))) {
/* Out of memory. */
return 0;
}
/* Copy any existing commands into the new array. */
{
int i;
for (i = 0; i < cp->NumberOfCommands; ++i) {
newCommands[i] = cp->Commands[i];
}
}
if (cp->Verbatim) {
/* Copy the verbatim command line into the buffer. */
newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(*command);
} else {
/* Encode the arguments so CommandLineToArgvW can decode
them from the command line string in the child. */
char buffer[32768]; /* CreateProcess max command-line length. */
char* end = buffer + sizeof(buffer);
char* out = buffer;
char const* const* a;
for (a = command; *a; ++a) {
int quote = !**a; /* Quote the empty string. */
int slashes = 0;
char const* c;
if (a != command && out != end) {
*out++ = ' ';
}
for (c = *a; !quote && *c; ++c) {
quote = (*c == ' ' || *c == '\t');
}
if (quote && out != end) {
*out++ = '"';
}
for (c = *a; *c; ++c) {
if (*c == '\\') {
++slashes;
} else {
if (*c == '"') {
// Add n+1 backslashes to total 2n+1 before internal '"'.
while (slashes-- >= 0 && out != end) {
*out++ = '\\';
}
}
slashes = 0;
}
if (out != end) {
*out++ = *c;
}
}
if (quote) {
// Add n backslashes to total 2n before ending '"'.
while (slashes-- > 0 && out != end) {
*out++ = '\\';
}
if (out != end) {
*out++ = '"';
}
}
}
if (out != end) {
*out = '\0';
newCommands[cp->NumberOfCommands] = kwsysEncoding_DupToWide(buffer);
} else {
newCommands[cp->NumberOfCommands] = 0;
}
}
if (!newCommands[cp->NumberOfCommands]) {
/* Out of memory or command line too long. */
free(newCommands);
return 0;
}
/* Save the new array of commands. */
free(cp->Commands);
cp->Commands = newCommands;
cp->NumberOfCommands = newNumberOfCommands;
return 1;
}
void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout)
{
if (!cp) {
return;
}
cp->Timeout = timeout;
if (cp->Timeout < 0) {
cp->Timeout = 0;
}
// Force recomputation of TimeoutTime.
cp->TimeoutTime.QuadPart = -1;
}
int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp, const char* dir)
{
if (!cp) {
return 0;
}
if (cp->WorkingDirectory) {
free(cp->WorkingDirectory);
cp->WorkingDirectory = 0;
}
if (dir && dir[0]) {
wchar_t* wdir = kwsysEncoding_DupToWide(dir);
/* We must convert the working directory to a full path. */
DWORD length = GetFullPathNameW(wdir, 0, 0, 0);
if (length > 0) {
wchar_t* work_dir = malloc(length * sizeof(wchar_t));
if (!work_dir) {
free(wdir);
return 0;
}
if (!GetFullPathNameW(wdir, length, work_dir, 0)) {
free(work_dir);
free(wdir);
return 0;
}
cp->WorkingDirectory = work_dir;
}
free(wdir);
}
return 1;
}
int kwsysProcess_SetPipeFile(kwsysProcess* cp, int pipe, const char* file)
{
char** pfile;
if (!cp) {
return 0;
}
switch (pipe) {
case kwsysProcess_Pipe_STDIN:
pfile = &cp->PipeFileSTDIN;
break;
case kwsysProcess_Pipe_STDOUT:
pfile = &cp->PipeFileSTDOUT;
break;
case kwsysProcess_Pipe_STDERR:
pfile = &cp->PipeFileSTDERR;
break;
default:
return 0;
}
if (*pfile) {
free(*pfile);
*pfile = 0;
}
if (file) {
*pfile = strdup(file);
if (!*pfile) {
return 0;
}
}
/* If we are redirecting the pipe, do not share it or use a native
pipe. */
if (*pfile) {
kwsysProcess_SetPipeNative(cp, pipe, 0);
kwsysProcess_SetPipeShared(cp, pipe, 0);
}
return 1;
}
void kwsysProcess_SetPipeShared(kwsysProcess* cp, int pipe, int shared)
{
if (!cp) {
return;
}
switch (pipe) {
case kwsysProcess_Pipe_STDIN:
cp->PipeSharedSTDIN = shared ? 1 : 0;
break;
case kwsysProcess_Pipe_STDOUT:
cp->PipeSharedSTDOUT = shared ? 1 : 0;
break;
case kwsysProcess_Pipe_STDERR:
cp->PipeSharedSTDERR = shared ? 1 : 0;
break;
default:
return;
}
/* If we are sharing the pipe, do not redirect it to a file or use a
native pipe. */
if (shared) {
kwsysProcess_SetPipeFile(cp, pipe, 0);
kwsysProcess_SetPipeNative(cp, pipe, 0);
}
}
void kwsysProcess_SetPipeNative(kwsysProcess* cp, int pipe, const HANDLE p[2])
{
HANDLE* pPipeNative = 0;
if (!cp) {
return;
}
switch (pipe) {
case kwsysProcess_Pipe_STDIN:
pPipeNative = cp->PipeNativeSTDIN;
break;
case kwsysProcess_Pipe_STDOUT:
pPipeNative = cp->PipeNativeSTDOUT;
break;
case kwsysProcess_Pipe_STDERR:
pPipeNative = cp->PipeNativeSTDERR;
break;
default:
return;
}
/* Copy the native pipe handles provided. */
if (p) {
pPipeNative[0] = p[0];
pPipeNative[1] = p[1];
} else {
pPipeNative[0] = 0;
pPipeNative[1] = 0;
}
/* If we are using a native pipe, do not share it or redirect it to
a file. */
if (p) {
kwsysProcess_SetPipeFile(cp, pipe, 0);
kwsysProcess_SetPipeShared(cp, pipe, 0);
}
}
int kwsysProcess_GetOption(kwsysProcess* cp, int optionId)
{
if (!cp) {
return 0;
}
switch (optionId) {
case kwsysProcess_Option_Detach:
return cp->OptionDetach;
case kwsysProcess_Option_HideWindow:
return cp->HideWindow;
case kwsysProcess_Option_MergeOutput:
return cp->MergeOutput;
case kwsysProcess_Option_Verbatim:
return cp->Verbatim;
case kwsysProcess_Option_CreateProcessGroup:
return cp->CreateProcessGroup;
default:
return 0;
}
}
void kwsysProcess_SetOption(kwsysProcess* cp, int optionId, int value)
{
if (!cp) {
return;
}
switch (optionId) {
case kwsysProcess_Option_Detach:
cp->OptionDetach = value;
break;
case kwsysProcess_Option_HideWindow:
cp->HideWindow = value;
break;
case kwsysProcess_Option_MergeOutput:
cp->MergeOutput = value;
break;
case kwsysProcess_Option_Verbatim:
cp->Verbatim = value;
break;
case kwsysProcess_Option_CreateProcessGroup:
cp->CreateProcessGroup = value;
break;
default:
break;
}
}
int kwsysProcess_GetState(kwsysProcess* cp)
{
return cp ? cp->State : kwsysProcess_State_Error;
}
int kwsysProcess_GetExitException(kwsysProcess* cp)
{
return (cp && cp->ProcessResults && (cp->NumberOfCommands > 0))
? cp->ProcessResults[cp->NumberOfCommands - 1].ExitException
: kwsysProcess_Exception_Other;
}
int kwsysProcess_GetExitValue(kwsysProcess* cp)
{
return (cp && cp->ProcessResults && (cp->NumberOfCommands > 0))
? cp->ProcessResults[cp->NumberOfCommands - 1].ExitValue
: -1;
}
int kwsysProcess_GetExitCode(kwsysProcess* cp)
{
return (cp && cp->ProcessResults && (cp->NumberOfCommands > 0))
? cp->ProcessResults[cp->NumberOfCommands - 1].ExitCode
: 0;
}
const char* kwsysProcess_GetErrorString(kwsysProcess* cp)
{
if (!cp) {
return "Process management structure could not be allocated";
} else if (cp->State == kwsysProcess_State_Error) {
return cp->ErrorMessage;
}
return "Success";
}
const char* kwsysProcess_GetExceptionString(kwsysProcess* cp)
{
if (!(cp && cp->ProcessResults && (cp->NumberOfCommands > 0))) {
return "GetExceptionString called with NULL process management structure";
} else if (cp->State == kwsysProcess_State_Exception) {
return cp->ProcessResults[cp->NumberOfCommands - 1].ExitExceptionString;
}
return "No exception";
}
/* the index should be in array bound. */
#define KWSYSPE_IDX_CHK(RET) \
if (!cp || idx >= cp->NumberOfCommands || idx < 0) { \
KWSYSPE_DEBUG((stderr, "array index out of bound\n")); \
return RET; \
}
int kwsysProcess_GetStateByIndex(kwsysProcess* cp, int idx)
{
KWSYSPE_IDX_CHK(kwsysProcess_State_Error)
return cp->ProcessResults[idx].State;
}
int kwsysProcess_GetExitExceptionByIndex(kwsysProcess* cp, int idx)
{
KWSYSPE_IDX_CHK(kwsysProcess_Exception_Other)
return cp->ProcessResults[idx].ExitException;
}
int kwsysProcess_GetExitValueByIndex(kwsysProcess* cp, int idx)
{
KWSYSPE_IDX_CHK(-1)
return cp->ProcessResults[idx].ExitValue;
}
int kwsysProcess_GetExitCodeByIndex(kwsysProcess* cp, int idx)
{
KWSYSPE_IDX_CHK(-1)
return cp->CommandExitCodes[idx];
}
const char* kwsysProcess_GetExceptionStringByIndex(kwsysProcess* cp, int idx)
{
KWSYSPE_IDX_CHK("GetExceptionString called with NULL process management "
"structure or index out of bound")
if (cp->ProcessResults[idx].State == kwsysProcess_StateByIndex_Exception) {
return cp->ProcessResults[idx].ExitExceptionString;
}
return "No exception";
}
#undef KWSYSPE_IDX_CHK
void kwsysProcess_Execute(kwsysProcess* cp)
{
int i;
/* Do not execute a second time. */
if (!cp || cp->State == kwsysProcess_State_Executing) {
return;
}
/* Make sure we have something to run. */
if (cp->NumberOfCommands < 1) {
strcpy(cp->ErrorMessage, "No command");
cp->State = kwsysProcess_State_Error;
return;
}
/* Initialize the control structure for a new process. */
if (!kwsysProcessInitialize(cp)) {
strcpy(cp->ErrorMessage, "Out of memory");
cp->State = kwsysProcess_State_Error;
return;
}
/* Save the real working directory of this process and change to
the working directory for the child processes. This is needed
to make pipe file paths evaluate correctly. */
if (cp->WorkingDirectory) {
if (!GetCurrentDirectoryW(cp->RealWorkingDirectoryLength,
cp->RealWorkingDirectory)) {
kwsysProcessCleanup(cp, GetLastError());
return;
}
if (!SetCurrentDirectoryW(cp->WorkingDirectory)) {
kwsysProcessCleanup(cp, GetLastError());
return;
}
}
/* Setup the stdin pipe for the first process. */
if (cp->PipeFileSTDIN) {
/* Create a handle to read a file for stdin. */
wchar_t* wstdin = kwsysEncoding_DupToWide(cp->PipeFileSTDIN);
DWORD error;
cp->PipeChildStd[0] =
CreateFileW(wstdin, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
OPEN_EXISTING, 0, 0);
error = GetLastError(); /* Check now in case free changes this. */
free(wstdin);
if (cp->PipeChildStd[0] == INVALID_HANDLE_VALUE) {
kwsysProcessCleanup(cp, error);
return;
}
} else if (cp->PipeSharedSTDIN) {
/* Share this process's stdin with the child. */
kwsysProcessSetupSharedPipe(STD_INPUT_HANDLE, &cp->PipeChildStd[0]);
} else if (cp->PipeNativeSTDIN[0]) {
/* Use the provided native pipe. */
kwsysProcessSetupPipeNative(cp->PipeNativeSTDIN[0], &cp->PipeChildStd[0]);
} else {
/* Explicitly give the child no stdin. */
cp->PipeChildStd[0] = INVALID_HANDLE_VALUE;
}
/* Create the output pipe for the last process.
We always create this so the pipe thread can run even if we
do not end up giving the write end to the child below. */
if (!CreatePipe(&cp->Pipe[KWSYSPE_PIPE_STDOUT].Read,
&cp->Pipe[KWSYSPE_PIPE_STDOUT].Write, 0, 0)) {