-
Notifications
You must be signed in to change notification settings - Fork 9
/
subprocess.jsm
1745 lines (1555 loc) · 57.2 KB
/
subprocess.jsm
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
// -*- coding: utf-8 -*-
// vim: et:ts=4:sw=4:sts=4:ft=javascript
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "MPL"); you may not use this file
* except in compliance with the MPL. You may obtain a copy of
* the MPL at http://www.mozilla.org/MPL/
*
* Software distributed under the MPL is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the MPL for the specific language governing
* rights and limitations under the MPL.
*
* The Original Code is subprocess.jsm.
*
* The Initial Developer of this code is Jan Gerber.
* Portions created by Jan Gerber <[email protected]>
* are Copyright (C) 2011 Jan Gerber.
* All Rights Reserved.
*
* Contributor(s):
* Patrick Brunschwig <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
* ***** END LICENSE BLOCK ***** */
/*
* Import into a JS component using
* 'Components.utils.import("resource://firefogg/subprocess.jsm");'
*
* This object allows to start a process, and read/write data to/from it
* using stdin/stdout/stderr streams.
* Usage example:
*
* var p = subprocess.call({
* command: '/bin/foo',
* arguments: ['-v', 'foo'],
* environment: [ "XYZ=abc", "MYVAR=def" ],
* charset: 'UTF-8',
* workdir: '/home/foo',
* //stdin: "some value to write to stdin\nfoobar",
* stdin: function(stdin) {
* stdin.write("some value to write to stdin\nfoobar");
* stdin.close();
* },
* stdout: function(data) {
* dump("got data on stdout:" + data + "\n");
* },
* stderr: function(data) {
* dump("got data on stderr:" + data + "\n");
* },
* done: function(result) {
* dump("process terminated with " + result.exitCode + "\n");
* },
* mergeStderr: false
* });
* p.wait(); // wait for the subprocess to terminate
* // this will block the main thread,
* // only do if you can wait that long
*
*
* Description of parameters:
* --------------------------
* Apart from <command>, all arguments are optional.
*
* command: either a |nsIFile| object pointing to an executable file or a
* String containing the platform-dependent path to an executable
* file.
*
* arguments: optional string array containing the arguments to the command.
*
* environment: optional string array containing environment variables to pass
* to the command. The array elements must have the form
* "VAR=data". Please note that if environment is defined, it
* replaces any existing environment variables for the subprocess.
*
* charset: Output is decoded with given charset and a string is returned.
* If charset is undefined, "UTF-8" is used as default.
* To get binary data, set this explicitly to null and the
* returned string is not decoded in any way.
*
* workdir: optional; String containing the platform-dependent path to a
* directory to become the current working directory of the subprocess.
*
* stdin: optional input data for the process to be passed on standard
* input. stdin can either be a string or a function.
* A |string| gets written to stdin and stdin gets closed;
* A |function| gets passed an object with write and close function.
* Please note that the write() function will return almost immediately;
* data is always written asynchronously on a separate thread.
*
* stdout: an optional function that can receive output data from the
* process. The stdout-function is called asynchronously; it can be
* called mutliple times during the execution of a process.
* At a minimum at each occurance of \n or \r.
* Please note that null-characters might need to be escaped
* with something like 'data.replace(/\0/g, "\\0");'.
*
* stderr: an optional function that can receive stderr data from the
* process. The stderr-function is called asynchronously; it can be
* called mutliple times during the execution of a process. Please
* note that null-characters might need to be escaped with
* something like 'data.replace(/\0/g, "\\0");'.
* (on windows it only gets called once right now)
*
* done: optional function that is called when the process has terminated.
* The exit code from the process available via result.exitCode. If
* stdout is not defined, then the output from stdout is available
* via result.stdout. stderr data is in result.stderr
*
* mergeStderr: optional boolean value. If true, stderr is merged with stdout;
* no data will be provided to stderr. Default is false.
*
* bufferedOutput: optional boolean value. If true, stderr and stdout are buffered
* and will only deliver data when a certain amount of output is
* available. Enabling the option will give you some performance
* benefits if your read a lot of data. Don't enable this if your
* application works in a conversation-like mode. Default is false.
*
*
* Description of object returned by subprocess.call(...)
* ------------------------------------------------------
* The object returned by subprocess.call offers a few methods that can be
* executed:
*
* wait(): waits for the subprocess to terminate. It is not required to use
* wait; done will be called in any case when the subprocess terminated.
*
* kill(hardKill): kill the subprocess. Any open pipes will be closed and
* done will be called.
* hardKill [ignored on Windows]:
* - false: signal the process terminate (SIGTERM)
* - true: kill the process (SIGKILL)
*
*
* Other methods in subprocess
* ---------------------------
*
* registerDebugHandler(functionRef): register a handler that is called to get
* debugging information
* registerLogHandler(functionRef): register a handler that is called to get error
* messages
*
* example:
* subprocess.registerLogHandler( function(s) { dump(s); } );
*/
'use strict';
Components.utils.import("resource://gre/modules/ctypes.jsm");
this.EXPORTED_SYMBOLS = ['subprocess'];
const Cc = Components.classes;
const Ci = Components.interfaces;
const NS_LOCAL_FILE = "@mozilla.org/file/local;1";
//Windows API definitions
if (ctypes.size_t.size == 8) {
var WinABI = ctypes.default_abi;
} else {
var WinABI = ctypes.winapi_abi;
}
const WORD = ctypes.uint16_t;
const DWORD = ctypes.uint32_t;
const LPDWORD = DWORD.ptr;
const UINT = ctypes.unsigned_int;
const BOOL = ctypes.bool;
const HANDLE = ctypes.size_t;
const HWND = HANDLE;
const HMODULE = HANDLE;
const WPARAM = ctypes.size_t;
const LPARAM = ctypes.size_t;
const LRESULT = ctypes.size_t;
const ULONG_PTR = ctypes.uintptr_t;
const PVOID = ctypes.voidptr_t;
const LPVOID = PVOID;
const LPCTSTR = ctypes.jschar.ptr;
const LPCWSTR = ctypes.jschar.ptr;
const LPTSTR = ctypes.jschar.ptr;
const LPSTR = ctypes.char.ptr;
const LPCSTR = ctypes.char.ptr;
const LPBYTE = ctypes.char.ptr;
const CREATE_NEW_CONSOLE = 0x00000010;
const CREATE_NO_WINDOW = 0x08000000;
const CREATE_UNICODE_ENVIRONMENT = 0x00000400;
const STARTF_USESHOWWINDOW = 0x00000001;
const STARTF_USESTDHANDLES = 0x00000100;
const SW_HIDE = 0;
const DUPLICATE_SAME_ACCESS = 0x00000002;
const STILL_ACTIVE = 259;
const INFINITE = DWORD(0xFFFFFFFF);
const WAIT_TIMEOUT = 0x00000102;
/*
typedef struct _SECURITY_ATTRIBUTES {
DWORD nLength;
LPVOID lpSecurityDescriptor;
BOOL bInheritHandle;
} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
*/
const SECURITY_ATTRIBUTES = new ctypes.StructType("SECURITY_ATTRIBUTES", [
{"nLength": DWORD},
{"lpSecurityDescriptor": LPVOID},
{"bInheritHandle": BOOL}
]);
/*
typedef struct _STARTUPINFO {
DWORD cb;
LPTSTR lpReserved;
LPTSTR lpDesktop;
LPTSTR lpTitle;
DWORD dwX;
DWORD dwY;
DWORD dwXSize;
DWORD dwYSize;
DWORD dwXCountChars;
DWORD dwYCountChars;
DWORD dwFillAttribute;
DWORD dwFlags;
WORD wShowWindow;
WORD cbReserved2;
LPBYTE lpReserved2;
HANDLE hStdInput;
HANDLE hStdOutput;
HANDLE hStdError;
} STARTUPINFO, *LPSTARTUPINFO;
*/
const STARTUPINFO = new ctypes.StructType("STARTUPINFO", [
{"cb": DWORD},
{"lpReserved": LPTSTR},
{"lpDesktop": LPTSTR},
{"lpTitle": LPTSTR},
{"dwX": DWORD},
{"dwY": DWORD},
{"dwXSize": DWORD},
{"dwYSize": DWORD},
{"dwXCountChars": DWORD},
{"dwYCountChars": DWORD},
{"dwFillAttribute": DWORD},
{"dwFlags": DWORD},
{"wShowWindow": WORD},
{"cbReserved2": WORD},
{"lpReserved2": LPBYTE},
{"hStdInput": HANDLE},
{"hStdOutput": HANDLE},
{"hStdError": HANDLE}
]);
/*
typedef struct _PROCESS_INFORMATION {
HANDLE hProcess;
HANDLE hThread;
DWORD dwProcessId;
DWORD dwThreadId;
} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;
*/
const PROCESS_INFORMATION = new ctypes.StructType("PROCESS_INFORMATION", [
{"hProcess": HANDLE},
{"hThread": HANDLE},
{"dwProcessId": DWORD},
{"dwThreadId": DWORD}
]);
/*
typedef struct _OVERLAPPED {
ULONG_PTR Internal;
ULONG_PTR InternalHigh;
union {
struct {
DWORD Offset;
DWORD OffsetHigh;
};
PVOID Pointer;
};
HANDLE hEvent;
} OVERLAPPED, *LPOVERLAPPED;
*/
const OVERLAPPED = new ctypes.StructType("OVERLAPPED");
//UNIX definitions
const pid_t = ctypes.int32_t;
const WNOHANG = 1;
const F_GETFD = 1;
const F_SETFL = 4;
const LIBNAME = 0;
const O_NONBLOCK = 1;
const RLIM_T = 2;
const RLIMIT_NOFILE = 3;
function getPlatformValue(valueType) {
if (! gXulRuntime)
gXulRuntime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
const platformDefaults = {
// Windows API:
'winnt': [ 'kernel32.dll' ],
// Unix API:
// library name O_NONBLOCK RLIM_T RLIMIT_NOFILE
'darwin': [ 'libc.dylib', 0x04 , ctypes.uint64_t , 8 ],
'linux': [ 'libc.so.6', 2024 , ctypes.unsigned_long, 7 ],
'freebsd': [ 'libc.so.7', 0x04 , ctypes.int64_t , 8 ],
'openbsd': [ 'libc.so.61.0', 0x04 , ctypes.int64_t , 8 ],
'sunos': [ 'libc.so', 0x80 , ctypes.unsigned_long, 5 ],
'android': [ 'libc.so', 2024 , ctypes.unsigned_long, 7 ]
};
return platformDefaults[gXulRuntime.OS.toLowerCase()][valueType];
}
var gDebugFunc = null,
gLogFunc = null,
gXulRuntime = null;
function LogError(s) {
if (gLogFunc)
gLogFunc(s);
else
dump(s);
}
function debugLog(s) {
if (gDebugFunc)
gDebugFunc(s);
}
function setTimeout(callback, timeout) {
var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.initWithCallback(callback, timeout, Ci.nsITimer.TYPE_ONE_SHOT);
};
function convertBytes(data, charset) {
var string = '';
charset = charset || 'UTF-8';
var unicodeConv = Cc["@mozilla.org/intl/scriptableunicodeconverter"]
.getService(Ci.nsIScriptableUnicodeConverter);
try {
unicodeConv.charset = charset;
string = unicodeConv.ConvertToUnicode(data);
} catch (ex) {
LogError("String conversion failed: "+ex.toString()+"\n");
string = '';
}
string += unicodeConv.Finish();
return string;
}
function getCommandStr(command) {
let commandStr = null;
if (typeof(command) == "string") {
let file = Cc[NS_LOCAL_FILE].createInstance(Ci.nsIFile);
file.initWithPath(command);
if (! (file.isExecutable() && file.isFile()))
throw("File '"+command+"' is not an executable file");
commandStr = command;
}
else {
if (! (command.isExecutable() && command.isFile()))
throw("File '"+command.path+"' is not an executable file");
commandStr = command.path;
}
return commandStr;
}
function getWorkDir(workdir) {
let workdirStr = null;
if (typeof(workdir) == "string") {
let file = Cc[NS_LOCAL_FILE].createInstance(Ci.nsIFile);
file.initWithPath(workdir);
if (! (file.isDirectory()))
throw("Directory '"+workdir+"' does not exist");
workdirStr = workdir;
}
else if (workdir) {
if (! workdir.isDirectory())
throw("Directory '"+workdir.path+"' does not exist");
workdirStr = workdir.path;
}
return workdirStr;
}
var subprocess = this.subprocess = {
call: function(options) {
options.mergeStderr = options.mergeStderr || false;
options.bufferedOutput = options.bufferedOutput || false;
options.workdir = options.workdir || null;
options.environment = options.environment || [];
if (options.arguments) {
var args = options.arguments;
options.arguments = [];
args.forEach(function(argument) {
options.arguments.push(argument);
});
} else {
options.arguments = [];
}
options.libc = getPlatformValue(LIBNAME);
if (gXulRuntime.OS.toLowerCase() == "android") {
return subprocess_android(options);
}
else if (gXulRuntime.OS.substring(0, 3) == "WIN") {
return subprocess_win32(options);
} else {
return subprocess_unix(options);
}
},
registerDebugHandler: function(func) {
gDebugFunc = func;
},
registerLogHandler: function(func) {
gLogFunc = func;
},
getPlatformValue: getPlatformValue
};
function subprocess_win32(options) {
var kernel32dll = ctypes.open(options.libc),
hChildProcess,
active = true,
done = false,
exitCode = -1,
child = {},
stdinWorker = null,
stdoutWorker = null,
stderrWorker = null,
pendingWriteCount = 0,
readers = 2,
stdinOpenState = 2,
error = '',
output = '';
// stdin pipe states
const OPEN = 2;
const CLOSEABLE = 1;
const CLOSED = 0;
//api declarations
/*
BOOL WINAPI CloseHandle(
__in HANDLE hObject
);
*/
var CloseHandle = kernel32dll.declare("CloseHandle",
WinABI,
BOOL,
HANDLE
);
/*
BOOL WINAPI CreateProcess(
__in_opt LPCTSTR lpApplicationName,
__inout_opt LPTSTR lpCommandLine,
__in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes,
__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
__in BOOL bInheritHandles,
__in DWORD dwCreationFlags,
__in_opt LPVOID lpEnvironment,
__in_opt LPCTSTR lpCurrentDirectory,
__in LPSTARTUPINFO lpStartupInfo,
__out LPPROCESS_INFORMATION lpProcessInformation
);
*/
var CreateProcessW = kernel32dll.declare("CreateProcessW",
WinABI,
BOOL,
LPCTSTR,
LPTSTR,
SECURITY_ATTRIBUTES.ptr,
SECURITY_ATTRIBUTES.ptr,
BOOL,
DWORD,
LPVOID,
LPCTSTR,
STARTUPINFO.ptr,
PROCESS_INFORMATION.ptr
);
// /*
// BOOL WINAPI ReadFile(
// __in HANDLE hFile,
// __out LPVOID ReadFileBuffer,
// __in DWORD nNumberOfBytesToRead,
// __out_opt LPDWORD lpNumberOfBytesRead,
// __inout_opt LPOVERLAPPED lpOverlapped
// );
// */
// var ReadFileBufferSize = 1024,
// ReadFileBuffer = ctypes.char.array(ReadFileBufferSize),
// ReadFile = kernel32dll.declare("ReadFile",
// WinABI,
// BOOL,
// HANDLE,
// ReadFileBuffer,
// DWORD,
// LPDWORD,
// OVERLAPPED.ptr
// );
//
// /*
// BOOL WINAPI PeekNamedPipe(
// __in HANDLE hNamedPipe,
// __out_opt LPVOID lpBuffer,
// __in DWORD nBufferSize,
// __out_opt LPDWORD lpBytesRead,
// __out_opt LPDWORD lpTotalBytesAvail,
// __out_opt LPDWORD lpBytesLeftThisMessage
// );
// */
// var PeekNamedPipe = kernel32dll.declare("PeekNamedPipe",
// WinABI,
// BOOL,
// HANDLE,
// ReadFileBuffer,
// DWORD,
// LPDWORD,
// LPDWORD,
// LPDWORD
// );
//
// /*
// BOOL WINAPI WriteFile(
// __in HANDLE hFile,
// __in LPCVOID lpBuffer,
// __in DWORD nNumberOfBytesToWrite,
// __out_opt LPDWORD lpNumberOfBytesWritten,
// __inout_opt LPOVERLAPPED lpOverlapped
// );
// */
// var WriteFile = kernel32dll.declare("WriteFile",
// WinABI,
// BOOL,
// HANDLE,
// ctypes.char.ptr,
// DWORD,
// LPDWORD,
// OVERLAPPED.ptr
// );
/*
BOOL WINAPI CreatePipe(
__out PHANDLE hReadPipe,
__out PHANDLE hWritePipe,
__in_opt LPSECURITY_ATTRIBUTES lpPipeAttributes,
__in DWORD nSize
);
*/
var CreatePipe = kernel32dll.declare("CreatePipe",
WinABI,
BOOL,
HANDLE.ptr,
HANDLE.ptr,
SECURITY_ATTRIBUTES.ptr,
DWORD
);
/*
HANDLE WINAPI GetCurrentProcess(void);
*/
var GetCurrentProcess = kernel32dll.declare("GetCurrentProcess",
WinABI,
HANDLE
);
/*
DWORD WINAPI GetLastError(void);
*/
var GetLastError = kernel32dll.declare("GetLastError",
WinABI,
DWORD
);
/*
BOOL WINAPI DuplicateHandle(
__in HANDLE hSourceProcessHandle,
__in HANDLE hSourceHandle,
__in HANDLE hTargetProcessHandle,
__out LPHANDLE lpTargetHandle,
__in DWORD dwDesiredAccess,
__in BOOL bInheritHandle,
__in DWORD dwOptions
);
*/
var DuplicateHandle = kernel32dll.declare("DuplicateHandle",
WinABI,
BOOL,
HANDLE,
HANDLE,
HANDLE,
HANDLE.ptr,
DWORD,
BOOL,
DWORD
);
/*
BOOL WINAPI GetExitCodeProcess(
__in HANDLE hProcess,
__out LPDWORD lpExitCode
);
*/
var GetExitCodeProcess = kernel32dll.declare("GetExitCodeProcess",
WinABI,
BOOL,
HANDLE,
LPDWORD
);
/*
DWORD WINAPI WaitForSingleObject(
__in HANDLE hHandle,
__in DWORD dwMilliseconds
);
*/
var WaitForSingleObject = kernel32dll.declare("WaitForSingleObject",
WinABI,
DWORD,
HANDLE,
DWORD
);
/*
BOOL WINAPI TerminateProcess(
__in HANDLE hProcess,
__in UINT uExitCode
);
*/
var TerminateProcess = kernel32dll.declare("TerminateProcess",
WinABI,
BOOL,
HANDLE,
UINT
);
//functions
function popen(command, workdir, args, environment, child) {
//escape arguments
args.unshift(command);
for (var i = 0; i < args.length; i++) {
if (typeof args[i] != "string") { args[i] = args[i].toString(); }
/* quote arguments with spaces */
if (args[i].match(/\s/)) {
args[i] = "\"" + args[i] + "\"";
}
/* If backslash is followed by a quote, double it */
args[i] = args[i].replace(/\\\"/g, "\\\\\"");
}
command = args.join(' ');
environment = environment || [];
if(environment.length) {
//An environment block consists of
//a null-terminated block of null-terminated strings.
//Using CREATE_UNICODE_ENVIRONMENT so needs to be jschar
environment = ctypes.jschar.array()(environment.join('\0') + '\0');
} else {
environment = null;
}
var hOutputReadTmp = new HANDLE(),
hOutputRead = new HANDLE(),
hOutputWrite = new HANDLE();
var hErrorRead = new HANDLE(),
hErrorReadTmp = new HANDLE(),
hErrorWrite = new HANDLE();
var hInputRead = new HANDLE(),
hInputWriteTmp = new HANDLE(),
hInputWrite = new HANDLE();
// Set up the security attributes struct.
var sa = new SECURITY_ATTRIBUTES();
sa.nLength = SECURITY_ATTRIBUTES.size;
sa.lpSecurityDescriptor = null;
sa.bInheritHandle = true;
// Create output pipe.
if(!CreatePipe(hOutputReadTmp.address(), hOutputWrite.address(), sa.address(), 0))
LogError('CreatePipe hOutputReadTmp failed');
// Create error pipe.
if(!CreatePipe(hErrorReadTmp.address(), hErrorWrite.address(), sa.address(), 0))
LogError('CreatePipe hErrorReadTmp failed');
// Create input pipe.
if (!CreatePipe(hInputRead.address(),hInputWriteTmp.address(),sa.address(), 0))
LogError("CreatePipe hInputRead failed");
// Create new output/error read handle and the input write handles. Set
// the Properties to FALSE. Otherwise, the child inherits the
// properties and, as a result, non-closeable handles to the pipes
// are created.
if (!DuplicateHandle(GetCurrentProcess(), hOutputReadTmp,
GetCurrentProcess(),
hOutputRead.address(), // Address of new handle.
0, false, // Make it uninheritable.
DUPLICATE_SAME_ACCESS))
LogError("DupliateHandle hOutputReadTmp failed");
if (!DuplicateHandle(GetCurrentProcess(), hErrorReadTmp,
GetCurrentProcess(),
hErrorRead.address(), // Address of new handle.
0, false, // Make it uninheritable.
DUPLICATE_SAME_ACCESS))
LogError("DupliateHandle hErrorReadTmp failed");
if (!DuplicateHandle(GetCurrentProcess(), hInputWriteTmp,
GetCurrentProcess(),
hInputWrite.address(), // Address of new handle.
0, false, // Make it uninheritable.
DUPLICATE_SAME_ACCESS))
LogError("DupliateHandle hInputWriteTmp failed");
// Close inheritable copies of the handles.
if (!CloseHandle(hOutputReadTmp)) LogError("CloseHandle hOutputReadTmp failed");
if (!CloseHandle(hErrorReadTmp)) LogError("CloseHandle hErrorReadTmp failed");
if (!CloseHandle(hInputWriteTmp)) LogError("CloseHandle failed");
var pi = new PROCESS_INFORMATION();
var si = new STARTUPINFO();
si.cb = STARTUPINFO.size;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = hInputRead;
si.hStdOutput = hOutputWrite;
si.hStdError = hErrorWrite;
// Launch the process
if(!CreateProcessW(null, // executable name
command, // command buffer
null, // process security attribute
null, // thread security attribute
true, // inherits system handles
CREATE_UNICODE_ENVIRONMENT|CREATE_NO_WINDOW, // process flags
environment, // envrionment block
workdir, // set as current directory
si.address(), // (in) startup information
pi.address() // (out) process information
))
throw("Fatal - Could not launch subprocess '"+command+"'");
// Close any unnecessary handles.
if (!CloseHandle(pi.hThread))
LogError("CloseHandle pi.hThread failed");
// Close pipe handles (do not continue to modify the parent).
// You need to make sure that no handles to the write end of the
// output pipe are maintained in this process or else the pipe will
// not close when the child process exits and the ReadFile will hang.
if (!CloseHandle(hInputRead)) LogError("CloseHandle hInputRead failed");
if (!CloseHandle(hOutputWrite)) LogError("CloseHandle hOutputWrite failed");
if (!CloseHandle(hErrorWrite)) LogError("CloseHandle hErrorWrite failed");
//return values
child.stdin = hInputWrite;
child.stdout = hOutputRead;
child.stderr = hErrorRead;
child.process = pi.hProcess;
return pi.hProcess;
}
/*
* createStdinWriter ()
*
* Create a ChromeWorker object for writing data to the subprocess' stdin
* pipe. The ChromeWorker object lives on a separate thread; this avoids
* internal deadlocks.
*/
function createStdinWriter() {
debugLog("Creating new stdin worker\n");
stdinWorker = new ChromeWorker("subprocess_worker_win.js");
stdinWorker.onmessage = function(event) {
switch(event.data) {
case "WriteOK":
pendingWriteCount--;
debugLog("got OK from stdinWorker - remaining count: "+pendingWriteCount+"\n");
break;
case "ClosedOK":
stdinOpenState = CLOSED;
debugLog("Stdin pipe closed\n");
break;
default:
debugLog("got msg from stdinWorker: "+event.data+"\n");
}
};
stdinWorker.onerror = function(error) {
pendingWriteCount--;
exitCode = -2;
LogError("got error from stdinWorker: "+error.message+"\n");
};
stdinWorker.postMessage({msg: "init", libc: options.libc});
}
/*
* writeStdin()
* @data: String containing the data to write
*
* Write data to the subprocess' stdin (equals to sending a request to the
* ChromeWorker object to write the data).
*/
function writeStdin(data) {
++pendingWriteCount;
debugLog("sending "+data.length+" bytes to stdinWorker\n");
var pipePtr = parseInt(ctypes.cast(child.stdin.address(), ctypes.uintptr_t).value);
stdinWorker.postMessage({
msg: 'write',
pipe: pipePtr,
data: data
});
}
/*
* closeStdinHandle()
*
* Close the stdin pipe, either directly or by requesting the ChromeWorker to
* close the pipe. The ChromeWorker will only close the pipe after the last write
* request process is done.
*/
function closeStdinHandle() {
debugLog("trying to close stdin\n");
if (stdinOpenState != OPEN) return;
stdinOpenState = CLOSEABLE;
if (stdinWorker) {
debugLog("sending close stdin to worker\n");
var pipePtr = parseInt(ctypes.cast(child.stdin.address(), ctypes.uintptr_t).value);
stdinWorker.postMessage({
msg: 'close',
pipe: pipePtr
});
}
else {
stdinOpenState = CLOSED;
debugLog("Closing Stdin\n");
CloseHandle(child.stdin) || LogError("CloseHandle hInputWrite failed");
}
}
/*
* createReader(pipe, name)
*
* @pipe: handle to the pipe
* @name: String containing the pipe name (stdout or stderr)
*
* Create a ChromeWorker object for reading data asynchronously from
* the pipe (i.e. on a separate thread), and passing the result back to
* the caller.
*/
function createReader(pipe, name, callbackFunc) {
var worker = new ChromeWorker("subprocess_worker_win.js");
worker.onmessage = function(event) {
switch(event.data.msg) {
case "data":
debugLog("got "+event.data.count+" bytes from "+name+"\n");
var data = '';
if (options.charset === null) {
data = event.data.data;
}
else
data = convertBytes(event.data.data, options.charset);
callbackFunc(data);
break;
case "done":
debugLog("Pipe "+name+" closed\n");
--readers;
if (readers == 0) cleanup();
break;
case "error":
exitCode = -2;
LogError("Got msg from "+name+": "+event.data.data+"\n");
break;
default:
debugLog("Got msg from "+name+": "+event.data.data+"\n");
}
};
worker.onerror = function(errorMsg) {
LogError("Got error from "+name+": "+errorMsg.message);
exitCode = -2;
};
var pipePtr = parseInt(ctypes.cast(pipe.address(), ctypes.uintptr_t).value);
worker.postMessage({
msg: 'read',
pipe: pipePtr,
libc: options.libc,
charset: options.charset === null ? "null" : options.charset,
bufferedOutput: options.bufferedOutput,
name: name
});
return worker;
}
/*
* readPipes()
*
* Open the pipes for reading from stdout and stderr
*/
function readPipes() {
stdoutWorker = createReader(child.stdout, "stdout", function (data) {
if(options.stdout) {
setTimeout(function() {
options.stdout(data);
}, 0);
} else {
output += data;
}
});
stderrWorker = createReader(child.stderr, "stderr", function (data) {
var output = options.mergeStderr ? 'stdout' : 'stderr';
if(options[output]) {
setTimeout(function() {
options[output](data);
}, 0);
} else {
error += data;
}
});
}
/*
* cleanup()
*
* close stdin if needed, get the exit code from the subprocess and invoke
* the caller's done() function.
*
* Note: because stdout() and stderr() are called using setTimeout, we need to
* do the same here in order to guarantee the message sequence.
*/
function cleanup() {
debugLog("Cleanup called\n");
if(active) {
active = false;
closeStdinHandle(); // should only be required in case of errors
var exit = new DWORD();
GetExitCodeProcess(child.process, exit.address());
if (exitCode > -2)
exitCode = exit.value;
if (stdinWorker)
stdinWorker.postMessage({msg: 'stop'});
setTimeout(function _done() {
if (options.done) {
try {
options.done({
exitCode: exitCode,
stdout: output,
stderr: error
});
}
catch (ex) {
// prevent from blocking if options.done() throws an error
done = true;
throw ex;
}