-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
processes.c
2858 lines (2412 loc) · 71.6 KB
/
processes.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
/*
* processes.c: Process handles
*
* Author:
* Dick Porter (dick@ximian.com)
*
* (C) 2002-2011 Novell, Inc.
* Copyright 2011 Xamarin Inc
*/
#include <config.h>
#include <glib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <sched.h>
#include <sys/time.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#include <sys/time.h>
#include <fcntl.h>
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include <ctype.h>
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#ifdef HAVE_SYS_MKDEV_H
#include <sys/mkdev.h>
#endif
#ifdef HAVE_UTIME_H
#include <utime.h>
#endif
/* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
#ifdef __APPLE__
#include <TargetConditionals.h>
#include <sys/resource.h>
#ifdef HAVE_LIBPROC_H
/* proc_name */
#include <libproc.h>
#endif
#endif
#if defined(PLATFORM_MACOSX)
#define USE_OSX_LOADER
#endif
#if ( defined(__OpenBSD__) || defined(__FreeBSD__) ) && defined(HAVE_LINK_H)
#define USE_BSD_LOADER
#endif
#if defined(__HAIKU__)
#define USE_HAIKU_LOADER
#endif
#if defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER)
#include <sys/proc.h>
#include <sys/sysctl.h>
# if !defined(__OpenBSD__)
# include <sys/utsname.h>
# endif
# if defined(__FreeBSD__)
# include <sys/user.h> /* struct kinfo_proc */
# endif
#endif
#ifdef PLATFORM_SOLARIS
/* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
#if _FILE_OFFSET_BITS == 64
#undef _FILE_OFFSET_BITS
#include <procfs.h>
#define _FILE_OFFSET_BITS 64
#else
#include <procfs.h>
#endif
#endif
#ifdef __HAIKU__
#include <KernelKit.h>
#endif
#include <mono/io-layer/wapi.h>
#include <mono/io-layer/wapi-private.h>
#include <mono/io-layer/handles-private.h>
#include <mono/io-layer/process-private.h>
#include <mono/io-layer/threads.h>
#include <mono/io-layer/io-trace.h>
#include <mono/utils/strenc.h>
#include <mono/utils/mono-path.h>
#include <mono/io-layer/timefuncs-private.h>
#include <mono/utils/mono-time.h>
#include <mono/utils/mono-membar.h>
#include <mono/utils/mono-os-mutex.h>
#include <mono/utils/mono-signal-handler.h>
#include <mono/utils/mono-proclib.h>
#include <mono/utils/mono-once.h>
#include <mono/utils/mono-logger-internals.h>
/* The process' environment strings */
#if defined(__APPLE__)
#if defined (TARGET_OSX)
/* Apple defines this in crt_externs.h but doesn't provide that header for
* arm-apple-darwin9. We'll manually define the symbol on Apple as it does
* in fact exist on all implementations (so far)
*/
gchar ***_NSGetEnviron(void);
#define environ (*_NSGetEnviron())
#else
static char *mono_environ[1] = { NULL };
#define environ mono_environ
#endif /* defined (TARGET_OSX) */
#else
extern char **environ;
#endif
static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
static void process_close (gpointer handle, gpointer data);
static gboolean is_pid_valid (pid_t pid);
#if !(defined(USE_OSX_LOADER) || defined(USE_BSD_LOADER) || defined(USE_HAIKU_LOADER))
static FILE *
open_process_map (int pid, const char *mode);
#endif
struct _WapiHandleOps _wapi_process_ops = {
process_close, /* close_shared */
NULL, /* signal */
NULL, /* own */
NULL, /* is_owned */
process_wait, /* special_wait */
NULL /* prewait */
};
#if HAVE_SIGACTION
static struct sigaction previous_chld_sa;
#endif
static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
static void process_add_sigchld_handler (void);
/* The signal-safe logic to use mono_processes goes like this:
* - The list must be safe to traverse for the signal handler at all times.
* It's safe to: prepend an entry (which is a single store to 'mono_processes'),
* unlink an entry (assuming the unlinked entry isn't freed and doesn't
* change its 'next' pointer so that it can still be traversed).
* When cleaning up we first unlink an entry, then we verify that
* the read lock isn't locked. Then we can free the entry, since
* we know that nobody is using the old version of the list (including
* the unlinked entry).
* We also need to lock when adding and cleaning up so that those two
* operations don't mess with eachother. (This lock is not used in the
* signal handler)
*/
static struct MonoProcess *mono_processes = NULL;
static volatile gint32 mono_processes_cleaning_up = 0;
static mono_mutex_t mono_processes_mutex;
static void mono_processes_cleanup (void);
static gpointer current_process;
static char *cli_launcher;
static WapiHandle_process *
lookup_process_handle (gpointer handle)
{
WapiHandle_process *process_data;
gboolean ret;
ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
(gpointer *)&process_data);
if (!ret)
return NULL;
return process_data;
}
/* Check if a pid is valid - i.e. if a process exists with this pid. */
static gboolean
is_pid_valid (pid_t pid)
{
gboolean result = FALSE;
#if defined(HOST_WATCHOS)
result = TRUE; // TODO: Rewrite using sysctl
#elif defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__FreeBSD__)
if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
result = TRUE;
#elif defined(__HAIKU__)
team_info teamInfo;
if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
result = TRUE;
#else
char *dir = g_strdup_printf ("/proc/%d", pid);
if (!access (dir, F_OK))
result = TRUE;
g_free (dir);
#endif
return result;
}
static void
process_set_defaults (WapiHandle_process *process_handle)
{
/* These seem to be the defaults on w2k */
process_handle->min_working_set = 204800;
process_handle->max_working_set = 1413120;
_wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
}
static int
len16 (const gunichar2 *str)
{
int len = 0;
while (*str++ != 0)
len++;
return len;
}
static gunichar2 *
utf16_concat (const gunichar2 *first, ...)
{
va_list args;
int total = 0, i;
const gunichar2 *s;
gunichar2 *ret;
va_start (args, first);
total += len16 (first);
for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
total += len16 (s);
}
va_end (args);
ret = g_new (gunichar2, total + 1);
if (ret == NULL)
return NULL;
ret [total] = 0;
i = 0;
for (s = first; *s != 0; s++)
ret [i++] = *s;
va_start (args, first);
for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
const gunichar2 *p;
for (p = s; *p != 0; p++)
ret [i++] = *p;
}
va_end (args);
return ret;
}
static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
static const gunichar2 *utf16_space = utf16_space_bytes;
static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
static const gunichar2 *utf16_quote = utf16_quote_bytes;
#ifdef DEBUG_ENABLED
/* Useful in gdb */
void
print_utf16 (gunichar2 *str)
{
char *res;
res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
g_print ("%s\n", res);
g_free (res);
}
#endif
/* Implemented as just a wrapper around CreateProcess () */
gboolean
ShellExecuteEx (WapiShellExecuteInfo *sei)
{
gboolean ret;
WapiProcessInformation process_info;
gunichar2 *args;
if (sei == NULL) {
/* w2k just segfaults here, but we can do better than
* that
*/
SetLastError (ERROR_INVALID_PARAMETER);
return FALSE;
}
if (sei->lpFile == NULL)
/* w2k returns TRUE for this, for some reason. */
return TRUE;
/* Put both executable and parameters into the second argument
* to CreateProcess (), so it searches $PATH. The conversion
* into and back out of utf8 is because there is no
* g_strdup_printf () equivalent for gunichar2 :-(
*/
args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
if (args == NULL) {
SetLastError (ERROR_INVALID_DATA);
return FALSE;
}
ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
CREATE_UNICODE_ENVIRONMENT, NULL,
sei->lpDirectory, NULL, &process_info);
g_free (args);
if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
return ret;
if (!ret) {
static char *handler;
static gunichar2 *handler_utf16;
if (handler_utf16 == (gunichar2 *)-1)
return FALSE;
#ifdef PLATFORM_MACOSX
handler = g_strdup ("/usr/bin/open");
#else
/*
* On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
* if that fails, try to use gnome-open, then kfmclient
*/
handler = g_find_program_in_path ("xdg-open");
if (handler == NULL){
handler = g_find_program_in_path ("gnome-open");
if (handler == NULL){
handler = g_find_program_in_path ("kfmclient");
if (handler == NULL){
handler_utf16 = (gunichar2 *) -1;
return FALSE;
} else {
/* kfmclient needs exec argument */
char *old = handler;
handler = g_strconcat (old, " exec",
NULL);
g_free (old);
}
}
}
#endif
handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
g_free (handler);
/* Put quotes around the filename, in case it's a url
* that contains #'s (CreateProcess() calls
* g_shell_parse_argv(), which deliberately throws
* away anything after an unquoted #). Fixes bug
* 371567.
*/
args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
sei->lpFile, utf16_quote,
sei->lpParameters == NULL ? NULL : utf16_space,
sei->lpParameters, NULL);
if (args == NULL) {
SetLastError (ERROR_INVALID_DATA);
return FALSE;
}
ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
CREATE_UNICODE_ENVIRONMENT, NULL,
sei->lpDirectory, NULL, &process_info);
g_free (args);
if (!ret) {
if (GetLastError () != ERROR_OUTOFMEMORY)
SetLastError (ERROR_INVALID_DATA);
return FALSE;
}
/* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
CloseHandle (process_info.hProcess);
process_info.hProcess = NULL;
}
if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
sei->hProcess = process_info.hProcess;
else
CloseHandle (process_info.hProcess);
return ret;
}
static gboolean
is_managed_binary (const char *filename)
{
int original_errno = errno;
#if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
int file = open (filename, O_RDONLY | O_LARGEFILE);
#else
int file = open (filename, O_RDONLY);
#endif
off_t new_offset;
unsigned char buffer[8];
off_t file_size, optional_header_offset;
off_t pe_header_offset;
gboolean managed = FALSE;
int num_read;
guint32 first_word, second_word;
/* If we are unable to open the file, then we definitely
* can't say that it is managed. The child mono process
* probably wouldn't be able to open it anyway.
*/
if (file < 0) {
errno = original_errno;
return FALSE;
}
/* Retrieve the length of the file for future sanity checks. */
file_size = lseek (file, 0, SEEK_END);
lseek (file, 0, SEEK_SET);
/* We know we need to read a header field at offset 60. */
if (file_size < 64)
goto leave;
num_read = read (file, buffer, 2);
if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
goto leave;
new_offset = lseek (file, 60, SEEK_SET);
if (new_offset != 60)
goto leave;
num_read = read (file, buffer, 4);
if (num_read != 4)
goto leave;
pe_header_offset = buffer[0]
| (buffer[1] << 8)
| (buffer[2] << 16)
| (buffer[3] << 24);
if (pe_header_offset + 24 > file_size)
goto leave;
new_offset = lseek (file, pe_header_offset, SEEK_SET);
if (new_offset != pe_header_offset)
goto leave;
num_read = read (file, buffer, 4);
if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
goto leave;
/*
* Verify that the header we want in the optional header data
* is present in this binary.
*/
new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
if (new_offset != pe_header_offset + 20)
goto leave;
num_read = read (file, buffer, 2);
if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
goto leave;
/* Read the CLR header address and size fields. These will be
* zero if the binary is not managed.
*/
optional_header_offset = pe_header_offset + 24;
new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
if (new_offset != optional_header_offset + 208)
goto leave;
num_read = read (file, buffer, 8);
/* We are not concerned with endianness, only with
* whether it is zero or not.
*/
first_word = *(guint32 *)&buffer[0];
second_word = *(guint32 *)&buffer[4];
if ((num_read != 8) || (first_word == 0) || (second_word == 0))
goto leave;
managed = TRUE;
leave:
close (file);
errno = original_errno;
return managed;
}
gboolean
CreateProcessWithLogonW (const gunichar2 *username,
const gunichar2 *domain,
const gunichar2 *password,
const guint32 logonFlags,
const gunichar2 *appname,
const gunichar2 *cmdline,
guint32 create_flags,
gpointer env,
const gunichar2 *cwd,
WapiStartupInfo *startup,
WapiProcessInformation *process_info)
{
/* FIXME: use user information */
return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
}
static gboolean
is_readable_or_executable (const char *prog)
{
struct stat buf;
int a = access (prog, R_OK);
int b = access (prog, X_OK);
if (a != 0 && b != 0)
return FALSE;
if (stat (prog, &buf))
return FALSE;
if (S_ISREG (buf.st_mode))
return TRUE;
return FALSE;
}
static gboolean
is_executable (const char *prog)
{
struct stat buf;
if (access (prog, X_OK) != 0)
return FALSE;
if (stat (prog, &buf))
return FALSE;
if (S_ISREG (buf.st_mode))
return TRUE;
return FALSE;
}
static void
switch_dir_separators (char *path)
{
size_t i, pathLength = strlen(path);
/* Turn all the slashes round the right way, except for \' */
/* There are probably other characters that need to be excluded as well. */
for (i = 0; i < pathLength; i++) {
if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
path[i] = '/';
}
}
gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
gboolean inherit_handles, guint32 create_flags,
gpointer new_environ, const gunichar2 *cwd,
WapiStartupInfo *startup,
WapiProcessInformation *process_info)
{
#if defined (HAVE_FORK) && defined (HAVE_EXECVE)
char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
char *dir = NULL, **env_strings = NULL, **argv = NULL;
guint32 i, env_count = 0;
gboolean ret = FALSE;
gpointer handle = NULL;
WapiHandle_process process_handle = {0}, *process_handle_data;
GError *gerr = NULL;
int in_fd, out_fd, err_fd;
pid_t pid = 0;
int thr_ret;
int startup_pipe [2] = {-1, -1};
int dummy;
struct MonoProcess *mono_process;
gboolean fork_failed = FALSE;
mono_once (&process_sig_chld_once, process_add_sigchld_handler);
/* appname and cmdline specify the executable and its args:
*
* If appname is not NULL, it is the name of the executable.
* Otherwise the executable is the first token in cmdline.
*
* Executable searching:
*
* If appname is not NULL, it can specify the full path and
* file name, or else a partial name and the current directory
* will be used. There is no additional searching.
*
* If appname is NULL, the first whitespace-delimited token in
* cmdline is used. If the name does not contain a full
* directory path, the search sequence is:
*
* 1) The directory containing the current process
* 2) The current working directory
* 3) The windows system directory (Ignored)
* 4) The windows directory (Ignored)
* 5) $PATH
*
* Just to make things more interesting, tokens can contain
* white space if they are surrounded by quotation marks. I'm
* beginning to understand just why windows apps are generally
* so crap, with an API like this :-(
*/
if (appname != NULL) {
cmd = mono_unicode_to_external (appname);
if (cmd == NULL) {
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL",
__func__);
SetLastError (ERROR_PATH_NOT_FOUND);
goto free_strings;
}
switch_dir_separators(cmd);
}
if (cmdline != NULL) {
args = mono_unicode_to_external (cmdline);
if (args == NULL) {
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
SetLastError (ERROR_PATH_NOT_FOUND);
goto free_strings;
}
}
if (cwd != NULL) {
dir = mono_unicode_to_external (cwd);
if (dir == NULL) {
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: unicode conversion returned NULL", __func__);
SetLastError (ERROR_PATH_NOT_FOUND);
goto free_strings;
}
/* Turn all the slashes round the right way */
switch_dir_separators(dir);
}
/* We can't put off locating the executable any longer :-( */
if (cmd != NULL) {
char *unquoted;
if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
/* Strip off the drive letter. I can't
* believe that CP/M holdover is still
* visible...
*/
g_memmove (cmd, cmd+2, strlen (cmd)-2);
cmd[strlen (cmd)-2] = '\0';
}
unquoted = g_shell_unquote (cmd, NULL);
if (unquoted[0] == '/') {
/* Assume full path given */
prog = g_strdup (unquoted);
/* Executable existing ? */
if (!is_readable_or_executable (prog)) {
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
__func__, prog);
g_free (unquoted);
SetLastError (ERROR_FILE_NOT_FOUND);
goto free_strings;
}
} else {
/* Search for file named by cmd in the current
* directory
*/
char *curdir = g_get_current_dir ();
prog = g_strdup_printf ("%s/%s", curdir, unquoted);
g_free (curdir);
/* And make sure it's readable */
if (!is_readable_or_executable (prog)) {
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
__func__, prog);
g_free (unquoted);
SetLastError (ERROR_FILE_NOT_FOUND);
goto free_strings;
}
}
g_free (unquoted);
args_after_prog = args;
} else {
char *token = NULL;
char quote;
/* Dig out the first token from args, taking quotation
* marks into account
*/
/* First, strip off all leading whitespace */
args = g_strchug (args);
/* args_after_prog points to the contents of args
* after token has been set (otherwise argv[0] is
* duplicated)
*/
args_after_prog = args;
/* Assume the opening quote will always be the first
* character
*/
if (args[0] == '\"' || args [0] == '\'') {
quote = args [0];
for (i = 1; args[i] != '\0' && args[i] != quote; i++);
if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
/* We found the first token */
token = g_strndup (args+1, i-1);
args_after_prog = g_strchug (args + i + 1);
} else {
/* Quotation mark appeared in the
* middle of the token. Just give the
* whole first token, quotes and all,
* to exec.
*/
}
}
if (token == NULL) {
/* No quote mark, or malformed */
for (i = 0; args[i] != '\0'; i++) {
if (g_ascii_isspace (args[i])) {
token = g_strndup (args, i);
args_after_prog = args + i + 1;
break;
}
}
}
if (token == NULL && args[0] != '\0') {
/* Must be just one token in the string */
token = g_strdup (args);
args_after_prog = NULL;
}
if (token == NULL) {
/* Give up */
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find what to exec", __func__);
SetLastError (ERROR_PATH_NOT_FOUND);
goto free_strings;
}
/* Turn all the slashes round the right way. Only for
* the prg. name
*/
switch_dir_separators(token);
if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
/* Strip off the drive letter. I can't
* believe that CP/M holdover is still
* visible...
*/
g_memmove (token, token+2, strlen (token)-2);
token[strlen (token)-2] = '\0';
}
if (token[0] == '/') {
/* Assume full path given */
prog = g_strdup (token);
/* Executable existing ? */
if (!is_readable_or_executable (prog)) {
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s",
__func__, token);
g_free (token);
SetLastError (ERROR_FILE_NOT_FOUND);
goto free_strings;
}
} else {
char *curdir = g_get_current_dir ();
/* FIXME: Need to record the directory
* containing the current process, and check
* that for the new executable as the first
* place to look
*/
prog = g_strdup_printf ("%s/%s", curdir, token);
g_free (curdir);
/* I assume X_OK is the criterion to use,
* rather than F_OK
*
* X_OK is too strict *if* the target is a CLR binary
*/
if (!is_readable_or_executable (prog)) {
g_free (prog);
prog = g_find_program_in_path (token);
if (prog == NULL) {
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Couldn't find executable %s", __func__, token);
g_free (token);
SetLastError (ERROR_FILE_NOT_FOUND);
goto free_strings;
}
}
}
g_free (token);
}
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Exec prog [%s] args [%s]", __func__, prog,
args_after_prog);
/* Check for CLR binaries; if found, we will try to invoke
* them using the same mono binary that started us.
*/
if (is_managed_binary (prog)) {
gunichar2 *newapp = NULL, *newcmd;
gsize bytes_ignored;
if (cli_launcher)
newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
else
newapp = mono_unicode_from_external ("mono", &bytes_ignored);
if (newapp != NULL) {
if (appname != NULL) {
newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
appname, utf16_space,
cmdline, NULL);
} else {
newcmd = utf16_concat (utf16_quote, newapp, utf16_quote, utf16_space,
cmdline, NULL);
}
g_free ((gunichar2 *)newapp);
if (newcmd != NULL) {
ret = CreateProcess (NULL, newcmd,
process_attrs,
thread_attrs,
inherit_handles,
create_flags, new_environ,
cwd, startup,
process_info);
g_free ((gunichar2 *)newcmd);
goto free_strings;
}
}
} else {
if (!is_executable (prog)) {
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: Executable permisson not set on %s", __func__, prog);
SetLastError (ERROR_ACCESS_DENIED);
goto free_strings;
}
}
if (args_after_prog != NULL && *args_after_prog) {
char *qprog;
qprog = g_shell_quote (prog);
full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
g_free (qprog);
} else {
full_prog = g_shell_quote (prog);
}
ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
if (ret == FALSE) {
g_message ("CreateProcess: %s\n", gerr->message);
g_error_free (gerr);
gerr = NULL;
goto free_strings;
}
if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
in_fd = GPOINTER_TO_UINT (startup->hStdInput);
out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
err_fd = GPOINTER_TO_UINT (startup->hStdError);
} else {
in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
}
process_handle.proc_name = g_strdup (prog);
process_set_defaults (&process_handle);
handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
if (handle == _WAPI_HANDLE_INVALID) {
g_warning ("%s: error creating process handle", __func__);
ret = FALSE;
SetLastError (ERROR_OUTOFMEMORY);
goto free_strings;
}
/* new_environ is a block of NULL-terminated strings, which
* is itself NULL-terminated. Of course, passing an array of
* string pointers would have made things too easy :-(
*
* If new_environ is not NULL it specifies the entire set of
* environment variables in the new process. Otherwise the
* new process inherits the same environment.
*/
if (new_environ) {
gunichar2 *new_environp;
/* Count the number of strings */
for (new_environp = (gunichar2 *)new_environ; *new_environp;
new_environp++) {
env_count++;
while (*new_environp) {
new_environp++;
}
}
/* +2: one for the process handle value, and the last
* one is NULL
*/
env_strings = g_new0 (char *, env_count + 2);
/* Copy each environ string into 'strings' turning it
* into utf8 (or the requested encoding) at the same
* time
*/
env_count = 0;
for (new_environp = (gunichar2 *)new_environ; *new_environp;
new_environp++) {
env_strings[env_count] = mono_unicode_to_external (new_environp);
env_count++;
while (*new_environp) {
new_environp++;
}
}
} else {
for (i = 0; environ[i] != NULL; i++)
env_count++;
/* +2: one for the process handle value, and the last
* one is NULL
*/
env_strings = g_new0 (char *, env_count + 2);
/* Copy each environ string into 'strings' turning it
* into utf8 (or the requested encoding) at the same
* time
*/
env_count = 0;
for (i = 0; environ[i] != NULL; i++) {
env_strings[env_count] = g_strdup (environ[i]);
env_count++;
}
}
/* Create a pipe to make sure the child doesn't exit before
* we can add the process to the linked list of mono_processes */
if (pipe (startup_pipe) == -1) {
/* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
* This is just for a very hard to hit race condition in the first place */
startup_pipe [0] = startup_pipe [1] = -1;
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
}
thr_ret = _wapi_handle_lock_shared_handles ();
g_assert (thr_ret == 0);
pid = fork ();
if (pid == -1) {
/* Error */
SetLastError (ERROR_OUTOFMEMORY);
ret = FALSE;
fork_failed = TRUE;
goto cleanup;
} else if (pid == 0) {
/* Child */
if (startup_pipe [0] != -1) {
/* Wait until the parent has updated it's internal data */
ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
MONO_TRACE (G_LOG_LEVEL_DEBUG, MONO_TRACE_IO_LAYER, "%s: child: parent has completed its setup", __func__);
close (startup_pipe [0]);
close (startup_pipe [1]);
}
/* should we detach from the process group? */
/* Connect stdin, stdout and stderr */
dup2 (in_fd, 0);
dup2 (out_fd, 1);
dup2 (err_fd, 2);