-
Notifications
You must be signed in to change notification settings - Fork 0
/
System2.h
1072 lines (894 loc) · 39.9 KB
/
System2.h
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
#ifndef SYSTEM2_H
#define SYSTEM2_H
//============================================================
//Declaration
//============================================================
/*
If you do not want to use header only due to system header leakage
1. Define SYSTEM2_DECLARATION_ONLY 1 before you include this header
2. Add System2.c to your project or
define SYSTEM2_IMPLEMENTATION_ONLY 1 and include this header in a c file
*/
#if SYSTEM2_DECLARATION_ONLY
//We need system types defined if we don't want to include system headers
#if defined(__unix__) || defined(__APPLE__)
typedef int pid_t;
#endif
#if defined(_WIN32)
typedef void* HANDLE;
#endif
#else
//Includes all the required system headers
#if defined(__unix__) || defined(__APPLE__)
#include <unistd.h>
#include <stdio.h>
#endif
#if defined(_WIN32)
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <windows.h>
#endif
#endif
#if SYSTEM2_DECLARATION_ONLY || SYSTEM2_IMPLEMENTATION_ONLY
//We don't need any inline prefix if we are having declaration and implementation separated
#define SYSTEM2_FUNC_PREFIX
#else
#define SYSTEM2_FUNC_PREFIX static inline
#endif
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
typedef struct
{
bool RedirectInput; //Redirect input with pipe?
bool RedirectOutput; //Redirect output with pipe?
const char* RunDirectory; //The directory to run the command in?
#if defined(__unix__) || defined(__APPLE__)
int ParentToChildPipes[2];
int ChildToParentPipes[2];
pid_t ChildProcessID;
#endif
#if defined(_WIN32)
bool DisableEscapes; //Disable automatic escaping?
HANDLE ParentToChildPipes[2];
HANDLE ChildToParentPipes[2];
HANDLE ChildProcessHandle;
#endif
} System2CommandInfo;
typedef enum
{
SYSTEM2_FD_READ = 0,
SYSTEM2_FD_WRITE = 1
} SYSTEM2_PIPE_FILE_DESCRIPTORS;
typedef enum
{
SYSTEM2_RESULT_COMMAND_TERMINATED = 3,
SYSTEM2_RESULT_COMMAND_NOT_FINISHED = 2,
SYSTEM2_RESULT_READ_NOT_FINISHED = 1,
SYSTEM2_RESULT_SUCCESS = 0,
SYSTEM2_RESULT_PIPE_CREATE_FAILED = -1,
SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED = -2,
SYSTEM2_RESULT_CREATE_CHILD_PROCESS_FAILED = -3,
SYSTEM2_RESULT_READ_FAILED = -4,
SYSTEM2_RESULT_WRITE_FAILED = -5,
SYSTEM2_RESULT_COMMAND_WAIT_SYNC_FAILED = -6,
SYSTEM2_RESULT_COMMAND_WAIT_ASYNC_FAILED = -7,
SYSTEM2_RESULT_UNSUPPORTED_PLATFORM = -8,
SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED = -9
} SYSTEM2_RESULT;
/*
Runs the command in system shell just like the `system()` funcion with the given settings
passed with `inOutCommandInfo`.
This uses
`sh -c command` for POSIX and
`cmd /s /v /c command` for Windows
Could return the follow result:
- SYSTEM2_RESULT_SUCCESS
- SYSTEM2_RESULT_PIPE_CREATE_FAILED
- SYSTEM2_RESULT_CREATE_CHILD_PROCESS_FAILED
- SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED
- SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED
*/
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2Run( const char* command,
System2CommandInfo* inOutCommandInfo);
/*
Runs the executable (which can search in PATH env variable) with the given arguments and settings
passed with inOutCommandInfo.
On Windows, automatic escaping can be removed by setting the `DisableEscape` in `inOutCommandInfo`
Could return the follow result:
- SYSTEM2_RESULT_SUCCESS
- SYSTEM2_RESULT_PIPE_CREATE_FAILED
- SYSTEM2_RESULT_CREATE_CHILD_PROCESS_FAILED
- SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED
- SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED
*/
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2RunSubprocess(const char* executable,
const char* const* args,
int argsCount,
System2CommandInfo* inOutCommandInfo);
/*
Reads the output (stdout and stderr) from the command.
Output string is **NOT** null terminated.
If SYSTEM2_RESULT_READ_NOT_FINISHED is returned,
this function can be called again until SYSTEM2_RESULT_SUCCESS to retrieve the rest of the output.
outBytesRead determines how many bytes have been read for **this** function call
Could return the follow result:
- SYSTEM2_RESULT_SUCCESS
- SYSTEM2_RESULT_READ_NOT_FINISHED
- SYSTEM2_RESULT_READ_FAILED
*/
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2ReadFromOutput( const System2CommandInfo* info,
char* outputBuffer,
uint32_t outputBufferSize,
uint32_t* outBytesRead);
/*
Write the input (stdin) to the command.
Could return the follow result:
- SYSTEM2_RESULT_SUCCESS
- SYSTEM2_RESULT_WRITE_FAILED
*/
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2WriteToInput( const System2CommandInfo* info,
const char* inputBuffer,
const uint32_t inputBufferSize);
//TODO: Might want to add this to have this ability to close input pipe manually
//SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2CloseInput(System2CommandInfo* info);
/*
Gets the return code if the command has finished.
Otherwise, this will return SYSTEM2_RESULT_COMMAND_NOT_FINISHED immediately.
Could return the follow result:
- SYSTEM2_RESULT_SUCCESS
- SYSTEM2_RESULT_COMMAND_NOT_FINISHED
- SYSTEM2_RESULT_COMMAND_TERMINATED
- SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED
- SYSTEM2_RESULT_COMMAND_WAIT_ASYNC_FAILED
*/
SYSTEM2_FUNC_PREFIX
SYSTEM2_RESULT System2GetCommandReturnValueAsync( const System2CommandInfo* info,
int* outReturnCode);
/*
Wait for the command to finish and gets the return code
Could return the follow result:
- SYSTEM2_RESULT_SUCCESS
- SYSTEM2_RESULT_COMMAND_TERMINATED
- SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED
- SYSTEM2_RESULT_COMMAND_WAIT_SYNC_FAILED
*/
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2GetCommandReturnValueSync(const System2CommandInfo* info,
int* outReturnCode);
//============================================================
//Implementation
//============================================================
#if !SYSTEM2_DECLARATION_ONLY
#include <stdlib.h>
#include <stdbool.h>
#if defined(__unix__) || defined(__APPLE__)
#include <sys/wait.h>
SYSTEM2_FUNC_PREFIX
SYSTEM2_RESULT System2RunSubprocessPosix( const char* executable,
const char* const* args,
int argsCount,
System2CommandInfo* inOutCommandInfo)
{
int result = pipe(inOutCommandInfo->ParentToChildPipes);
if(result != 0)
return SYSTEM2_RESULT_PIPE_CREATE_FAILED;
result = pipe(inOutCommandInfo->ChildToParentPipes);
if(result != 0)
return SYSTEM2_RESULT_PIPE_CREATE_FAILED;
const char** nullTerminatedArgs = (const char**)malloc(sizeof(char**) * (argsCount + 1));
if(nullTerminatedArgs == NULL)
return SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED;
for(int i = 0; i < argsCount; ++i)
nullTerminatedArgs[i] = args[i];
nullTerminatedArgs[argsCount] = NULL;
pid_t pid = fork();
if(pid < 0)
{
free(nullTerminatedArgs);
return SYSTEM2_RESULT_CREATE_CHILD_PROCESS_FAILED;
}
//Child
else if(pid == 0)
{
if(close(inOutCommandInfo->ParentToChildPipes[SYSTEM2_FD_WRITE]) != 0)
_exit(2);
if(close(inOutCommandInfo->ChildToParentPipes[SYSTEM2_FD_READ]) != 0)
_exit(3);
if(inOutCommandInfo->RunDirectory != NULL)
{
if(chdir(inOutCommandInfo->RunDirectory) != 0)
_exit(4);
}
if(inOutCommandInfo->RedirectInput)
{
result = dup2(inOutCommandInfo->ParentToChildPipes[SYSTEM2_FD_READ], STDIN_FILENO);
if(result == -1)
_exit(5);
}
if(inOutCommandInfo->RedirectOutput)
{
result = dup2(inOutCommandInfo->ChildToParentPipes[SYSTEM2_FD_WRITE], STDOUT_FILENO);
if(result == -1)
_exit(6);
result = dup2(inOutCommandInfo->ChildToParentPipes[SYSTEM2_FD_WRITE], STDERR_FILENO);
if(result == -1)
_exit(7);
}
//TODO: Send the errno back to the host and display the error
if(execvp(executable, (char**)nullTerminatedArgs) == -1)
_exit(52);
//Should never be reached
_exit(8);
}
//Parent
else
{
free(nullTerminatedArgs);
if(close(inOutCommandInfo->ParentToChildPipes[SYSTEM2_FD_READ]) != 0)
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
if(close(inOutCommandInfo->ChildToParentPipes[SYSTEM2_FD_WRITE]) != 0)
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
inOutCommandInfo->ChildProcessID = pid;
}
return SYSTEM2_RESULT_SUCCESS;
}
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2RunPosix( const char* command,
System2CommandInfo* inOutCommandInfo)
{
const char* args[] = { "/bin/sh", "-c", command };
return System2RunSubprocessPosix("/bin/sh", args, 3, inOutCommandInfo);
}
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2ReadFromOutputPosix( const System2CommandInfo* info,
char* outputBuffer,
uint32_t outputBufferSize,
uint32_t* outBytesRead)
{
uint32_t readResult;
*outBytesRead = 0;
while (true)
{
readResult = read( info->ChildToParentPipes[SYSTEM2_FD_READ],
outputBuffer,
outputBufferSize - *outBytesRead);
if(readResult == 0)
break;
if(readResult == -1)
return SYSTEM2_RESULT_READ_FAILED;
outputBuffer += readResult;
*outBytesRead += readResult;
if(outputBufferSize - *outBytesRead == 0)
return SYSTEM2_RESULT_READ_NOT_FINISHED;
}
return SYSTEM2_RESULT_SUCCESS;
}
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2WriteToInputPosix(const System2CommandInfo* info,
const char* inputBuffer,
const uint32_t inputBufferSize)
{
uint32_t currentWriteLengthLeft = inputBufferSize;
while(true)
{
uint32_t writeResult = write( info->ParentToChildPipes[SYSTEM2_FD_WRITE],
inputBuffer,
inputBufferSize);
if(writeResult == -1)
return SYSTEM2_RESULT_WRITE_FAILED;
inputBuffer += writeResult;
currentWriteLengthLeft -= writeResult;
if(currentWriteLengthLeft == 0)
break;
}
return SYSTEM2_RESULT_SUCCESS;
}
SYSTEM2_FUNC_PREFIX
SYSTEM2_RESULT System2GetCommandReturnValueAsyncPosix( const System2CommandInfo* info,
int* outReturnCode)
{
int status;
pid_t pidResult = waitpid(info->ChildProcessID, &status, WNOHANG);
if(pidResult == 0)
return SYSTEM2_RESULT_COMMAND_NOT_FINISHED;
else if(pidResult == -1)
return SYSTEM2_RESULT_COMMAND_WAIT_ASYNC_FAILED;
if(close(info->ChildToParentPipes[SYSTEM2_FD_READ]) != 0)
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
if(close(info->ParentToChildPipes[SYSTEM2_FD_WRITE]) != 0)
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
if(!WIFEXITED(status))
{
*outReturnCode = -1;
return SYSTEM2_RESULT_COMMAND_TERMINATED;
}
*outReturnCode = WEXITSTATUS(status);
return SYSTEM2_RESULT_SUCCESS;
}
SYSTEM2_FUNC_PREFIX
SYSTEM2_RESULT System2GetCommandReturnValueSyncPosix( const System2CommandInfo* info,
int* outReturnCode)
{
int status;
pid_t pidResult = waitpid(info->ChildProcessID, &status, 0);
if(pidResult == -1)
return SYSTEM2_RESULT_COMMAND_WAIT_SYNC_FAILED;
if(close(info->ChildToParentPipes[SYSTEM2_FD_READ]) != 0)
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
if(close(info->ParentToChildPipes[SYSTEM2_FD_WRITE]) != 0)
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
if(!WIFEXITED(status))
{
*outReturnCode = -1;
return SYSTEM2_RESULT_COMMAND_TERMINATED;
}
*outReturnCode = WEXITSTATUS(status);
return SYSTEM2_RESULT_SUCCESS;
}
#endif
#if defined(_WIN32)
#include <strsafe.h>
SYSTEM2_FUNC_PREFIX void PrintError(LPCTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code
LPVOID lpMsgBuf;
DWORD dw = GetLastError();
FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0,
NULL );
// Display the error message and exit the process
printf("Error %d: %s\n", dw, (char*)lpMsgBuf);
LocalFree(lpMsgBuf);
}
//https://learn.microsoft.com/en-gb/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way
SYSTEM2_FUNC_PREFIX int ConstructCommandLineWindows(const char* const* args,
size_t argsCount,
bool disableEscape,
int resultSize,
char* outResult)
{
size_t currentIndex = 0;
if(argsCount == 0)
{
if(outResult != NULL)
{
if(resultSize < 1)
return -1;
else
{
outResult[0] = '\0';
return 1;
}
}
else
return 1;
}
for(size_t i = 0; i < argsCount; ++i)
{
size_t currentArgLength = strlen(args[i]);
if( currentArgLength != 0 &&
strchr(args[i], ' ') == NULL &&
strchr(args[i], '\t') == NULL &&
strchr(args[i], '\n') == NULL &&
strchr(args[i], '\v') == NULL &&
strchr(args[i], '"') == NULL)
{
if(outResult != NULL)
{
strcpy(&outResult[currentIndex], args[i]);
currentIndex += currentArgLength;
//Bound check
if(currentIndex >= resultSize)
return -1;
if(i != argsCount - 1)
outResult[currentIndex++] = ' ';
else
outResult[currentIndex++] = '\0';
}
else
{
currentIndex += currentArgLength;
++currentIndex;
}
}
else
{
if(outResult != NULL)
{
//Bound check
if(currentIndex >= resultSize)
return -1;
outResult[currentIndex++] = '"';
}
else
++currentIndex;
for(int j = 0; j < currentArgLength; ++j)
{
int numberBackslashes = 0;
if(!disableEscape)
{
for(; j < currentArgLength && args[i][j] == '\\'; ++j)
++numberBackslashes;
}
if(j == currentArgLength && !disableEscape)
{
// Escape all backslashes, but let the terminating
// double quotation mark we add below be interpreted
// as a metacharacter.
if(outResult != NULL)
{
//Bound check
if(currentIndex + numberBackslashes * 2 >= resultSize)
return -1;
for(int k = 0; k < numberBackslashes * 2; ++k)
outResult[currentIndex++] = '\\';
}
else
{
for(int k = 0; k < numberBackslashes * 2; ++k)
++currentIndex;
}
}
else if(args[i][j] == '"' && !disableEscape)
{
// Escape all backslashes and the following
// double quotation mark.
if(outResult != NULL)
{
//Bound check
if(currentIndex + numberBackslashes * 2 + 1 + 1 >= resultSize)
return -1;
for(int k = 0; k < numberBackslashes * 2 + 1; ++k)
outResult[currentIndex++] = '\\';
outResult[currentIndex++] = '"';
}
else
{
for(int k = 0; k < numberBackslashes * 2 + 1; ++k)
++currentIndex;
++currentIndex;
}
}
else
{
if(outResult != NULL)
{
//Bound check
if(currentIndex + numberBackslashes + 1 >= resultSize)
return -1;
// Backslashes aren't special here.
for(int k = 0; k < numberBackslashes; ++k)
outResult[currentIndex++] = '\\';
outResult[currentIndex++] = args[i][j];
}
else
{
for(int k = 0; k < numberBackslashes; ++k)
++currentIndex;
++currentIndex;
}
}
}
if(outResult != NULL)
{
//Bound check
if(currentIndex + 2 > resultSize)
return -1;
outResult[currentIndex++] = '"';
if(i != argsCount - 1)
outResult[currentIndex++] = ' ';
else
outResult[currentIndex++] = '\0';
}
else
currentIndex += 2;
}
}
return (int)currentIndex;
}
SYSTEM2_FUNC_PREFIX
SYSTEM2_RESULT System2RunSubprocessWindows( const char* executable,
const char* const* args,
int argsCount,
System2CommandInfo* inOutCommandInfo)
{
// Set the write handle to the pipe for STDOUT to be inherited.
if(inOutCommandInfo->RedirectOutput)
{
// Create a pipe for the child process's STDOUT.
if(!CreatePipe( &inOutCommandInfo->ChildToParentPipes[SYSTEM2_FD_READ],
&inOutCommandInfo->ChildToParentPipes[SYSTEM2_FD_WRITE],
NULL,
0))
{
return SYSTEM2_RESULT_PIPE_CREATE_FAILED;
}
if(!SetHandleInformation( inOutCommandInfo->ChildToParentPipes[SYSTEM2_FD_WRITE],
HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT))
{
return SYSTEM2_RESULT_PIPE_CREATE_FAILED;
}
}
// Create a pipe for the child process's STDIN.
if(!CreatePipe( &inOutCommandInfo->ParentToChildPipes[SYSTEM2_FD_READ],
&inOutCommandInfo->ParentToChildPipes[SYSTEM2_FD_WRITE],
NULL,
0))
{
return SYSTEM2_RESULT_PIPE_CREATE_FAILED;
}
// Set the read handle to the pipe for STDIN to be inherited.
if(!SetHandleInformation( inOutCommandInfo->ParentToChildPipes[SYSTEM2_FD_READ],
HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT))
{
return SYSTEM2_RESULT_PIPE_CREATE_FAILED;
}
PROCESS_INFORMATION processInfo;
STARTUPINFOW startupInfo;
BOOL success = FALSE;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory( &processInfo, sizeof(PROCESS_INFORMATION) );
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
ZeroMemory(&startupInfo, sizeof(STARTUPINFOW));
startupInfo.cb = sizeof(STARTUPINFOW);
startupInfo.dwFlags |= STARTF_USESTDHANDLES;
if(inOutCommandInfo->RedirectInput)
startupInfo.hStdInput = inOutCommandInfo->ParentToChildPipes[SYSTEM2_FD_READ];
else
startupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);;
if(inOutCommandInfo->RedirectOutput)
{
startupInfo.hStdError = inOutCommandInfo->ChildToParentPipes[SYSTEM2_FD_WRITE];
startupInfo.hStdOutput = inOutCommandInfo->ChildToParentPipes[SYSTEM2_FD_WRITE];
}
else
{
startupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
startupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
}
//Join and escape each argument together, then run it
{
//Calculating final command count
int finalCommandSize = 0;
const char** concatedArgs = (const char**)malloc(sizeof(char*) * (argsCount + 1));
concatedArgs[0] = executable;
for(int i = 0; i < argsCount; ++i)
concatedArgs[i + 1] = args[i];
finalCommandSize = ConstructCommandLineWindows( concatedArgs,
argsCount + 1,
inOutCommandInfo->DisableEscapes,
0,
NULL);
if(finalCommandSize < 0)
{
free(concatedArgs);
return SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED;
}
char* commandCopy = (char*)malloc(finalCommandSize);
if(commandCopy == NULL)
{
free(concatedArgs);
return SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED;
}
int wroteSize = ConstructCommandLineWindows(concatedArgs,
argsCount + 1,
inOutCommandInfo->DisableEscapes,
finalCommandSize,
commandCopy);
free((void*)concatedArgs);
if(wroteSize != finalCommandSize)
{
printf( "wroteSize and finalCommandSize mismatch, %d, %d\n",
wroteSize,
finalCommandSize);
return SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED;
}
//Construct final command
wchar_t* commandCopyWide = NULL;
//Convert final command to wide chars
{
int wideCommandSize = MultiByteToWideChar(CP_UTF8, 0, commandCopy, -1, NULL, 0);
if(wideCommandSize <= 0)
{
free(commandCopy);
return SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED;
}
commandCopyWide = (wchar_t*)malloc(wideCommandSize * sizeof(wchar_t));
if(commandCopyWide == NULL)
{
free(commandCopy);
return SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED;
}
wideCommandSize = MultiByteToWideChar(CP_UTF8,
0,
commandCopy,
-1,
commandCopyWide,
wideCommandSize);
if(wideCommandSize <= 0)
{
free(commandCopy);
free(commandCopyWide);
return SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED;
}
}
//Convert working directory to wide chars
wchar_t* workingDirectoryWide = NULL;
if(inOutCommandInfo->RunDirectory != NULL)
{
int wideWorkingWideDirSize = MultiByteToWideChar( CP_UTF8,
0,
inOutCommandInfo->RunDirectory,
-1,
NULL,
0);
if(wideWorkingWideDirSize <= 0)
{
free(commandCopy);
free(commandCopyWide);
return SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED;
}
workingDirectoryWide = (wchar_t*)malloc(wideWorkingWideDirSize * sizeof(wchar_t));
if(workingDirectoryWide == NULL)
{
free(commandCopy);
free(commandCopyWide);
return SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED;
}
wideWorkingWideDirSize = MultiByteToWideChar( CP_UTF8,
0,
inOutCommandInfo->RunDirectory,
-1,
workingDirectoryWide,
wideWorkingWideDirSize);
if(wideWorkingWideDirSize <= 0)
{
free(commandCopy);
free(commandCopyWide);
free(workingDirectoryWide);
return SYSTEM2_RESULT_COMMAND_CONSTRUCT_FAILED;
}
}
success = CreateProcessW( NULL,
commandCopyWide, // command line
//L"PrintArgs.exe a\\\\b d\"e f\"g h",
NULL, // process securitye attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
CREATE_UNICODE_ENVIRONMENT, // creation flags
NULL, // use parent's environment
workingDirectoryWide, // use parent's current directory
&startupInfo, // STARTUPINFO pointer
&processInfo); // receives PROCESS_INFORMATION
free(commandCopy);
free(commandCopyWide);
if(workingDirectoryWide != NULL)
free(workingDirectoryWide);
}
// If an error occurs, exit the application.
if(!success)
{
PrintError("CreateProcessW");
return SYSTEM2_RESULT_CREATE_CHILD_PROCESS_FAILED;
}
else
{
// Close handles to the child process and its primary thread.
// Some applications might keep these handles to monitor the status
// of the child process, for example.
inOutCommandInfo->ChildProcessHandle = processInfo.hProcess;
// Close handles to the stdin and stdout pipes no longer needed by the child process.
// If they are not explicitly closed, there is no way to recognize that the child process has ended.
if(inOutCommandInfo->RedirectInput)
{
if(!CloseHandle(processInfo.hThread))
return SYSTEM2_RESULT_CREATE_CHILD_PROCESS_FAILED;
}
if(inOutCommandInfo->RedirectOutput)
{
if(!CloseHandle(inOutCommandInfo->ChildToParentPipes[SYSTEM2_FD_WRITE]))
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
}
if(!CloseHandle(inOutCommandInfo->ParentToChildPipes[SYSTEM2_FD_READ]))
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
return SYSTEM2_RESULT_SUCCESS;
}
}
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2RunWindows( const char* command,
System2CommandInfo* outCommandInfo)
{
const char* args[] = {"/s", "/v", "/c", command};
outCommandInfo->DisableEscapes = true;
return System2RunSubprocessWindows( "cmd",
args,
sizeof(args) / sizeof(char*),
outCommandInfo);
}
//TODO: Use peeknamedpipe to get number of bytes available before reading it
// so that it doesn't block
//https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-peeknamedpipe
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2ReadFromOutputWindows(const System2CommandInfo* info,
char* outputBuffer,
uint32_t outputBufferSize,
uint32_t* outBytesRead)
{
DWORD readResult;
BOOL bSuccess;
*outBytesRead = 0;
while (true)
{
bSuccess = ReadFile(info->ChildToParentPipes[SYSTEM2_FD_READ],
outputBuffer,
outputBufferSize - *outBytesRead,
&readResult,
NULL);
if (readResult == 0)
break;
if(!bSuccess)
return SYSTEM2_RESULT_READ_FAILED;
outputBuffer += readResult;
*outBytesRead += readResult;
if(outputBufferSize - *outBytesRead == 0)
return SYSTEM2_RESULT_READ_NOT_FINISHED;
}
//if(GetLastError() == ERROR_BROKEN_PIPE)
// return SYSTEM2_RESULT_SUCCESS;
//return SYSTEM2_RESULT_READ_FAILED;
return SYSTEM2_RESULT_SUCCESS;
}
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2WriteToInputWindows( const System2CommandInfo* info,
const char* inputBuffer,
const uint32_t inputBufferSize)
{
DWORD currentWriteLengthLeft = inputBufferSize;
BOOL bSuccess;
while (true)
{
DWORD writeResult;
bSuccess = WriteFile( info->ParentToChildPipes[SYSTEM2_FD_WRITE],
inputBuffer,
currentWriteLengthLeft,
&writeResult,
NULL);
if (!bSuccess)
return SYSTEM2_RESULT_WRITE_FAILED;
inputBuffer += writeResult;
currentWriteLengthLeft -= writeResult;
if (currentWriteLengthLeft == 0)
break;
}
return SYSTEM2_RESULT_SUCCESS;
}
SYSTEM2_FUNC_PREFIX
SYSTEM2_RESULT System2GetCommandReturnValueAsyncWindows(const System2CommandInfo* info,
int* outReturnCode)
{
DWORD exitCode;
if(!GetExitCodeProcess(info->ChildProcessHandle, &exitCode))
return SYSTEM2_RESULT_COMMAND_WAIT_ASYNC_FAILED;
if(info->RedirectOutput)
{
if(!CloseHandle(info->ChildToParentPipes[SYSTEM2_FD_READ]))
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
}
if(info->RedirectInput)
{
if(!CloseHandle(info->ParentToChildPipes[SYSTEM2_FD_WRITE]))
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
}
CloseHandle(info->ChildProcessHandle);
*outReturnCode = exitCode;
return SYSTEM2_RESULT_SUCCESS;
}
SYSTEM2_FUNC_PREFIX
SYSTEM2_RESULT System2GetCommandReturnValueSyncWindows( const System2CommandInfo* info,
int* outReturnCode)
{
if(WaitForSingleObject(info->ChildProcessHandle, INFINITE) != 0)
return SYSTEM2_RESULT_COMMAND_WAIT_SYNC_FAILED;
if(info->RedirectOutput)
{
if(!CloseHandle(info->ChildToParentPipes[SYSTEM2_FD_READ]))
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
}
if(info->RedirectInput)
{
if(!CloseHandle(info->ParentToChildPipes[SYSTEM2_FD_WRITE]))
return SYSTEM2_RESULT_PIPE_FD_CLOSE_FAILED;
}
DWORD exitCode;
if(!GetExitCodeProcess(info->ChildProcessHandle, &exitCode))
{
*outReturnCode = -1;
CloseHandle(info->ChildProcessHandle);
return SYSTEM2_RESULT_COMMAND_TERMINATED;
}
CloseHandle(info->ChildProcessHandle);
*outReturnCode = exitCode;
return SYSTEM2_RESULT_SUCCESS;
}
#endif
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2Run( const char* command,
System2CommandInfo* inOutCommandInfo)
{
#if defined(__unix__) || defined(__APPLE__)
return System2RunPosix(command, inOutCommandInfo);
#elif defined(_WIN32)
return System2RunWindows(command, inOutCommandInfo);
#else
return SYSTEM2_RESULT_UNSUPPORTED_PLATFORM;
#endif
}
SYSTEM2_FUNC_PREFIX SYSTEM2_RESULT System2RunSubprocess(const char* executable,
const char* const* args,