-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNSProcessInfo.m
More file actions
1735 lines (1540 loc) · 46.3 KB
/
NSProcessInfo.m
File metadata and controls
1735 lines (1540 loc) · 46.3 KB
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
/** Implementation for NSProcessInfo for GNUStep
Copyright (C) 1995-2017 Free Software Foundation, Inc.
Written by: Georg Tuparev <Tuparev@EMBL-Heidelberg.de>
Heidelberg, Germany
Modified by: Richard Frith-Macdonald <rfm@gnu.org>
This file is part of the GNUstep Base Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110 USA.
<title>NSProcessInfo class reference</title>
$Date$ $Revision$
*/
/*************************************************************************
* File Name : NSProcessInfo.m
* Date : 06-aug-1995
*************************************************************************
* Notes :
* 1) The class functionality depends on the following UNIX functions and
* global variables: gethostname(), getpid(), and environ. For all system
* I had the opportunity to test them they are defined and have the same
* behavior. The same is true for the meaning of argv[0] (process name).
* 2) The global variable _gnu_sharedProcessInfoObject should NEVER be
* deallocate during the process runtime. Therefore I implemented a
* concrete NSProcessInfo subclass (_NSConcreteProcessInfo) with the only
* purpose to override the autorelease, retain, and release methods.
* To Do :
* 1) To test the class on more platforms;
* Bugs : Not known
* Last update: 07-aug-2002
* History : 06-aug-1995 - Birth and the first beta version (v. 0.5);
* 08-aug-1995 - V. 0.6 (tested on NS, SunOS, Solaris, OSF/1
* The use of the environ global var was changed to more
* conventional env[] (main function) so now the class could be
* used on SunOS and Solaris. [GT]
*************************************************************************
* Acknowledgments:
* - Adam Fedor, Andrew McCallum, and Paul Kunz for their help;
* - To the NEXTSTEP/GNUStep community
*************************************************************************/
#import "common.h"
#include <stdio.h>
#ifdef HAVE_WINDOWS_H
# include <windows.h>
#endif
#if defined(HAVE_SYS_SIGNAL_H)
# include <sys/signal.h>
#elif defined(HAVE_SIGNAL_H)
# include <signal.h>
#endif
#if defined(HAVE_SYS_FILE_H)
# include <sys/file.h>
#endif
#if defined(HAVE_SYS_FCNTL_H)
# include <sys/fcntl.h>
#elif defined(HAVE_FCNTL_H)
# include <fcntl.h>
#endif
#ifdef HAVE_SYS_UTSNAME_H
#include <sys/utsname.h>
#endif
#ifdef HAVE_KVM_ENV
#include <kvm.h>
#if defined(HAVE_SYS_FCNTL_H)
# include <sys/fcntl.h>
#elif defined(HAVE_FCNTL_H)
# include <fcntl.h>
#endif
#include <sys/param.h>
#endif /* HAVE_KVM_ENV */
#ifdef HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
#if HAVE_PROCFS_H
#define id _procfs_avoid_id_collision
#include <procfs.h>
#undef id
#endif
#if defined(__APPLE__) && !GS_FAKE_MAIN
#include <crt_externs.h>
#endif
#import "Foundation/NSArray.h"
#import "Foundation/NSSet.h"
#import "Foundation/NSCharacterSet.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSDate.h"
#import "Foundation/NSException.h"
#import "Foundation/NSFileManager.h"
#import "Foundation/NSProcessInfo.h"
#import "Foundation/NSAutoreleasePool.h"
#import "Foundation/NSHost.h"
#import "Foundation/NSLock.h"
#import "GNUstepBase/NSProcessInfo+GNUstepBase.h"
#import "GNUstepBase/NSString+GNUstepBase.h"
#import "GSPrivate.h"
/* This error message should be called only if the private main function
* was not executed successfully. This may happen ONLY if another library
* or kit defines its own main function (as gnustep-base does).
*/
#if GS_FAKE_MAIN
#define _GNU_MISSING_MAIN_FUNCTION_CALL "\nGNUSTEP Internal Error:\n\
The private GNUstep function to establish the argv and environment\n\
variables was not called.\n\
Perhaps your program failed to #include <Foundation/NSObject.h> or\n\
<Foundation/Foundation.h>?\n\
If that is not the problem, Please report the error to bug-gnustep@gnu.org.\n\n"
#else
#ifdef GS_PASS_ARGUMENTS
#define _GNU_MISSING_MAIN_FUNCTION_CALL "\nGNUSTEP Error:\n\
A call to NSProcessInfo +initializeWithArguments:... must be made\n\
as the first ObjC statment in main. This function is used to \n\
establish the argv and environment variables.\n"
#else
#define _GNU_MISSING_MAIN_FUNCTION_CALL "\nGNUSTEP Internal Error:\n\
The private GNUstep function to establish the argv and environment\n\
variables was not called.\n\
\n\
Mismatched library versions between GNUstep Foundation (base) and AppKit\n\
(gui) is most often the cause of this message. Please be sure you\n\
are using known compatible versions and not a mismatched set. Generally,\n\
we recommend you use versions of base and gui which were released together.\n\
\n\
For more detailed assistance, please report the error to bug-gnustep@gnu.org.\n\n"
#endif
#endif
@interface NSHost (NSProcessInfo)
+ (NSString*) _myHostName;
@end
/*************************************************************************
*** _NSConcreteProcessInfo
*************************************************************************/
@interface _NSConcreteProcessInfo: NSProcessInfo
- (id) autorelease;
- (void) release;
- (id) retain;
@end
@implementation _NSConcreteProcessInfo
- (id) autorelease
{
return self;
}
- (void) release
{
return;
}
- (id) retain
{
return self;
}
@end
/*************************************************************************
*** NSProcessInfo implementation
*************************************************************************/
/**
* Instances of this class encapsulate information on the current process.
* For example, you can get the arguments, environment variables, host name,
* or process name. There is only one instance per process, for obvious
* reasons, and it may be obtained through the +processInfo method.
*/
@implementation NSProcessInfo
/*************************************************************************
*** Static global vars
*************************************************************************/
// The lock to protect shared process resources.
static NSRecursiveLock *procLock = nil;
// The shared NSProcessInfo instance
static NSProcessInfo *_gnu_sharedProcessInfoObject = nil;
// Host name of the CPU executing the process
static NSString *_gnu_hostName = nil;
static char *_gnu_arg_zero = 0;
// Current process name
static NSString *_gnu_processName = nil;
// Array of NSStrings (argv[1] .. argv[argc-1])
static NSArray *_gnu_arguments = nil;
// Dictionary of environment vars and their values
static NSDictionary *_gnu_environment = nil;
// The operating system we are using.
static unsigned int _operatingSystem = 0;
static NSString *_operatingSystemName = nil;
static NSString *_operatingSystemVersion = nil;
// Flag to indicate that fallbackInitialisation was executed.
static BOOL fallbackInitialisation = NO;
static NSMutableSet *mySet = nil;
#ifdef __ANDROID__
static jobject _androidContext = NULL;
static NSString *_androidFilesDir = nil;
static NSString *_androidCacheDir = nil;
#endif
/*************************************************************************
*** Implementing the gnustep_base_user_main function
*************************************************************************/
static void
_gnu_process_args(int argc, char *argv[], char *env[])
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSString *arg0 = nil;
int i;
if (_gnu_arg_zero != 0)
{
free(_gnu_arg_zero);
}
if (argv != 0 && argv[0] != 0)
{
int len;
len = strlen(argv[0]) + 1;
_gnu_arg_zero = (char*)malloc(len);
memcpy(_gnu_arg_zero, argv[0], len);
arg0 = [[NSString alloc] initWithCString: _gnu_arg_zero];
}
else
{
#if defined(_WIN32)
unichar *buffer;
int buffer_size = 0;
int needed_size = 0;
int len;
const char *tmp;
while (needed_size == buffer_size)
{
buffer_size = buffer_size + 256;
buffer = (unichar*)malloc(buffer_size * sizeof(unichar));
needed_size = GetModuleFileNameW(NULL, buffer, buffer_size);
if (needed_size < buffer_size)
{
unsigned i;
for (i = 0; i < needed_size; i++)
{
if (buffer[i] == 0)
{
break;
}
}
arg0 = [[NSString alloc] initWithCharacters: buffer length: i];
}
else
{
free(buffer);
}
}
tmp = [arg0 cStringUsingEncoding: [NSString defaultCStringEncoding]];
len = strlen(tmp) + 1;
_gnu_arg_zero = (char*)malloc(len);
memcpy(_gnu_arg_zero, tmp, len);
#else
fprintf(stderr, "Error: for some reason, argv not properly set up "
"during GNUstep base initialization\n");
abort();
#endif
}
/* Getting the process name */
IF_NO_GC(RELEASE(_gnu_processName));
_gnu_processName = [arg0 lastPathComponent];
#if defined(_WIN32)
/* On windows we remove any .exe extension for consistency with app names
* under unix
*/
{
NSString *e = [_gnu_processName pathExtension];
if (e != nil && [e caseInsensitiveCompare: @"EXE"] == NSOrderedSame)
{
_gnu_processName = [_gnu_processName stringByDeletingPathExtension];
}
}
#endif
IF_NO_GC(RETAIN(_gnu_processName));
/* Copy the argument list */
#if defined(_WIN32)
{
unichar **argvw = CommandLineToArgvW(GetCommandLineW(), &argc);
NSString *str;
id obj_argv[argc];
int added = 1;
/* Copy the zero'th argument to the argument list */
obj_argv[0] = arg0;
if (mySet == nil) mySet = [NSMutableSet new];
for (i = 1; i < argc; i++)
{
str = [NSString stringWithCharacters: argvw[i] length: wcslen(argvw[i])];
if ([str hasPrefix: @"--GNU-Debug="])
{
[mySet addObject: [str substringFromIndex: 12]];
}
else
{
obj_argv[added++] = str;
}
}
IF_NO_GC(RELEASE(_gnu_arguments));
_gnu_arguments = [[NSArray alloc] initWithObjects: obj_argv count: added];
RELEASE(arg0);
}
#else
if (argv)
{
NSString *str;
id obj_argv[argc];
int added = 1;
NSStringEncoding enc = GSPrivateDefaultCStringEncoding();
/* Copy the zero'th argument to the argument list */
obj_argv[0] = arg0;
if (mySet == nil) mySet = [NSMutableSet new];
for (i = 1; i < argc; i++)
{
str = [NSString stringWithCString: argv[i] encoding: enc];
if ([str hasPrefix: @"--GNU-Debug="])
[mySet addObject: [str substringFromIndex: 12]];
else
obj_argv[added++] = str;
}
IF_NO_GC(RELEASE(_gnu_arguments));
_gnu_arguments = [[NSArray alloc] initWithObjects: obj_argv count: added];
RELEASE(arg0);
}
#endif
/* Copy the evironment list */
{
NSMutableArray *keys = [NSMutableArray new];
NSMutableArray *values = [NSMutableArray new];
NSStringEncoding enc = GSPrivateDefaultCStringEncoding();
#if defined(_WIN32)
if (fallbackInitialisation == NO)
{
unichar *base;
base = GetEnvironmentStringsW();
if (base != 0)
{
const unichar *wenvp = base;
while (*wenvp != 0)
{
const unichar *start = wenvp;
NSString *key;
NSString *val;
start = wenvp;
while (*wenvp != '=' && *wenvp != 0)
{
wenvp++;
}
if (*wenvp == '=')
{
key = [NSString stringWithCharacters: start
length: wenvp - start];
wenvp++;
start = wenvp;
}
else
{
break; // Bad format ... expected '='
}
while (*wenvp != 0)
{
wenvp++;
}
val = [NSString stringWithCharacters: start
length: wenvp - start];
wenvp++; // Skip past variable terminator
[keys addObject: key];
[values addObject: val];
}
FreeEnvironmentStringsW(base);
env = 0; // Suppress standard code.
}
}
#endif
if (env != 0)
{
i = 0;
while (env[i])
{
int len = strlen(env[i]);
char *cp = strchr(env[i], '=');
if (len && cp)
{
char buf[len+2];
memcpy(buf, env[i], len + 1);
cp = &buf[cp - env[i]];
*cp++ = '\0';
[keys addObject:
[NSString stringWithCString: buf encoding: enc]];
[values addObject:
[NSString stringWithCString: cp encoding: enc]];
}
i++;
}
}
IF_NO_GC(RELEASE(_gnu_environment));
_gnu_environment = [[NSDictionary alloc] initWithObjects: values
forKeys: keys];
IF_NO_GC(RELEASE(keys));
IF_NO_GC(RELEASE(values));
}
[arp drain];
}
#if !GS_FAKE_MAIN && ((defined(HAVE_PROCFS) || defined(HAVE_KVM_ENV) || defined(HAVE_PROCFS_PSINFO) || defined(__APPLE__)) && (defined(HAVE_LOAD_METHOD)))
/*
* We have to save program arguments and environment before main () is
* executed, because main () could modify their values before we get a
* chance to read them
*/
static int _gnu_noobjc_argc = 0;
static char **_gnu_noobjc_argv = NULL;
static char **_gnu_noobjc_env = NULL;
/*
* The +load method (an extension of the GNU compiler) is invoked
* before main and +initialize (for this class) is executed. This is
* guaranteed if +load contains only pure C code, as we have here. The
* code in here either uses libkvm if available, or else procfs.
*/
+ (void) load
{
#ifdef HAVE_KVM_ENV
/*
* Use the kvm library to open the kernel and read the environment and
* arguments. As we are not running as root we cannot open the memory
* device and thus we fake it using /dev/null. This is allowed under
* FreeBSD, but may fail on other operating systems which check the
* file type. The kvm calls used are those which are supposedly backward
* compatible with Solaris rather than being FreeBSD specific
*/
kvm_t *kptr = NULL;
struct kinfo_proc *proc_ptr = NULL;
int nprocs, i, count;
char **vectors;
/* open the kernel */
kptr = kvm_open(NULL, "/dev/null", NULL, O_RDONLY, "NSProcessInfo");
if (!kptr)
{
fprintf(stderr, "Error: Your system appears to provide libkvm, but the kernel open fails\n");
fprintf(stderr, "Try to reconfigure gnustep-base with --enable-fake-main. to work\n");
fprintf(stderr, "around this problem.");
abort();
}
/* find the process */
proc_ptr = kvm_getprocs(kptr, KERN_PROC_PID, getpid(), &nprocs);
if (!proc_ptr || (nprocs != 1))
{
fprintf(stderr, "Error: libkvm cannot find the current process\n");
abort();
}
/* get the environment vectors the normal way, since this always works.
On FreeBSD, the only other way is via /proc, and in later versions
/proc is not mounted. */
{
extern char **environ;
vectors = environ;
if (!vectors)
{
fprintf(stderr, "Error: for some reason, environ == NULL "
"during GNUstep base initialization\n"
"Please check the linking process\n");
abort();
}
}
/* copy the environment strings */
for (count = 0; vectors[count]; count++)
;
_gnu_noobjc_env = (char**)malloc(sizeof(char*) * (count + 1));
if (!_gnu_noobjc_env)
goto malloc_error;
for (i = 0; i < count; i++)
{
_gnu_noobjc_env[i] = (char *)strdup(vectors[i]);
if (!_gnu_noobjc_env[i])
goto malloc_error;
}
_gnu_noobjc_env[i] = NULL;
/* get the argument vectors */
vectors = kvm_getargv(kptr, proc_ptr, 0);
if (!vectors)
{
fprintf(stderr, "Error: libkvm does not return arguments for the current process\n");
fprintf(stderr, "this may be due to a bug (undocumented feature) in libkvm\n");
fprintf(stderr, "which fails to get arguments unless /proc is mounted.\n");
fprintf(stderr, "If so, you can mount the /proc filesystem or reconfigure/build\n");
fprintf(stderr, "gnustep-base with --enable-fake-main as a workaround, and\n");
fprintf(stderr, "should report the bug to the maintainer of libkvm on your operating system.\n");
abort();
}
/* copy the argument strings */
for (_gnu_noobjc_argc = 0; vectors[_gnu_noobjc_argc]; _gnu_noobjc_argc++)
;
_gnu_noobjc_argv
= (char**)malloc(sizeof(char*) * (_gnu_noobjc_argc + 1));
if (!_gnu_noobjc_argv)
goto malloc_error;
for (i = 0; i < _gnu_noobjc_argc; i++)
{
_gnu_noobjc_argv[i] = (char *)strdup(vectors[i]);
if (!_gnu_noobjc_argv[i])
goto malloc_error;
}
_gnu_noobjc_argv[i] = NULL;
return;
#elif defined(HAVE_PROCFS_PSINFO)
char *proc_file_name = NULL;
FILE *ifp;
psinfo_t pinfo;
char **vectors;
int i, count;
// Read commandline
proc_file_name = (char*)malloc(2048);
snprintf(proc_file_name, 2048, "/proc/%d/psinfo", (int)getpid());
ifp = fopen(proc_file_name, "r");
if (ifp == NULL)
{
fprintf(stderr, "Error: Failed to open the process info file:%s\n",
proc_file_name);
abort();
}
fread(&pinfo, sizeof(pinfo), 1, ifp);
fclose(ifp);
vectors = (char **)pinfo.pr_envp;
if (!vectors)
{
fprintf(stderr, "Error: for some reason, environ == NULL "
"during GNUstep base initialization\n"
"Please check the linking process\n");
abort();
}
/* copy the environment strings */
for (count = 0; vectors[count]; count++)
;
_gnu_noobjc_env = (char**)malloc(sizeof(char*) * (count + 1));
if (!_gnu_noobjc_env)
goto malloc_error;
for (i = 0; i < count; i++)
{
_gnu_noobjc_env[i] = (char *)strdup(vectors[i]);
if (!_gnu_noobjc_env[i])
goto malloc_error;
}
_gnu_noobjc_env[i] = NULL;
/* get the argument vectors */
vectors = (char **)pinfo.pr_argv;
if (!vectors)
{
fprintf(stderr, "Error: psinfo does not return arguments for the current process\n");
abort();
}
/* copy the argument strings */
for (_gnu_noobjc_argc = 0; vectors[_gnu_noobjc_argc]; _gnu_noobjc_argc++)
;
_gnu_noobjc_argv
= (char**)malloc(sizeof(char*) * (_gnu_noobjc_argc + 1));
if (!_gnu_noobjc_argv)
goto malloc_error;
for (i = 0; i < _gnu_noobjc_argc; i++)
{
_gnu_noobjc_argv[i] = (char *)strdup(vectors[i]);
if (!_gnu_noobjc_argv[i])
goto malloc_error;
}
_gnu_noobjc_argv[i] = NULL;
return;
#elif defined(__APPLE__)
/*
* Darwin/Mac OS X provides indirect access to command line arguments and
* the environment with functions defined in the C runtime system.
*/
int i, n;
int argc = *_NSGetArgc();
char **argv = *_NSGetArgv();
char **environ = *_NSGetEnviron();
/* copy environment */
n = 0;
while (environ[n] != NULL)
n++;
_gnu_noobjc_env = (char **)malloc(sizeof(char *) * (n + 1));
if (_gnu_noobjc_env == NULL)
goto malloc_error;
for (i = 0; i < n; i++)
{
_gnu_noobjc_env[i] = (char *)strdup(environ[i]);
if (_gnu_noobjc_env[i] == NULL)
goto malloc_error;
}
_gnu_noobjc_env[i] = NULL;
/* copy arguments */
_gnu_noobjc_argc = argc;
_gnu_noobjc_argv = (char **)malloc(sizeof(char *) * (argc + 1));
if (_gnu_noobjc_argv == NULL)
goto malloc_error;
for (i = 0; i < argc; i++)
{
_gnu_noobjc_argv[i] = (char *)strdup(argv[i]);
if (_gnu_noobjc_argv[i] == NULL)
goto malloc_error;
}
_gnu_noobjc_argv[i] = NULL;
return;
#else /* !HAVE_KVM_ENV (i.e. HAVE_PROCFS). */
/*
* Now we have the problem of reading program arguments and
* environment. We take the environment from extern char **environ, and
* the program arguments from the /proc filesystem.
*/
extern char **environ;
char *proc_file_name = NULL;
FILE *ifp;
int c;
int argument;
int length;
int position;
int env_terms;
BOOL stripTrailingNewline = NO;
#ifdef HAVE_PROGRAM_INVOCATION_NAME
extern char *program_invocation_name;
#endif /* HAVE_PROGRAM_INVOCATION_NAME */
// Read environment
/* NB: This should *never* happen if your compiler tools are
sane. But, if you are playing with them, you could break
them to the point you get here. :-) */
if (environ == NULL)
{
/* TODO: Try reading environment from /proc before aborting. */
fprintf(stderr, "Error: for some reason, environ == NULL "
"during GNUstep base initialization\n"
"Please check the linking process\n");
abort();
}
c = 0;
while (environ[c] != NULL)
c++;
env_terms = c;
_gnu_noobjc_env = (char**)malloc(sizeof(char*) * (env_terms + 1));
if (_gnu_noobjc_env == NULL)
goto malloc_error;
for (c = 0; c < env_terms; c++)
{
_gnu_noobjc_env[c] = (char *)strdup(environ[c]);
if (_gnu_noobjc_env[c] == NULL)
goto malloc_error;
}
_gnu_noobjc_env[c] = NULL;
// Read commandline
proc_file_name = (char *)malloc(2048);
snprintf(proc_file_name, 2048, "/proc/%d/cmdline", (int)getpid());
/*
* We read the /proc file thrice.
* First, to know how many arguments there are and allocate memory for them.
* Second, to know how long each argument is, and allocate memory accordingly.
* Third, to actually copy the arguments into memory.
*/
_gnu_noobjc_argc = 0;
#ifdef HAVE_STRERROR
errno = 0;
#endif /* HAVE_STRERROR */
ifp = fopen(proc_file_name, "r");
if (ifp == NULL)
goto proc_fs_error;
while (1)
{
c = getc(ifp);
if (c == 0)
_gnu_noobjc_argc++;
else if (c == EOF)
break;
}
#if (CMDLINE_TERMINATED == 0)
_gnu_noobjc_argc++;
#endif
fclose(ifp);
/*
* Now _gnu_noobcj_argc is the number of arguments;
* allocate memory accordingly.
*/
_gnu_noobjc_argv = (char **)malloc((sizeof(char *)) * (_gnu_noobjc_argc + 1));
if (_gnu_noobjc_argv == NULL)
goto malloc_error;
ifp = fopen(proc_file_name,"r");
//freopen(proc_file_name, "r", ifp);
if (ifp == NULL)
{
free(_gnu_noobjc_argv);
goto proc_fs_error;
}
argument = 0;
length = 0;
while (argument < _gnu_noobjc_argc)
{
c = getc(ifp);
length++;
if ((c == EOF) || (c == 0)) // End of a parameter
{
_gnu_noobjc_argv[argument]
= (char*)malloc((sizeof(char))*length);
if (_gnu_noobjc_argv[argument] == NULL)
goto malloc_error;
argument++;
length = 0;
if (c == EOF) // End of command line
{
_gnu_noobjc_argc = argument;
break;
}
}
}
fclose(ifp);
ifp = fopen(proc_file_name,"r");
//freopen(proc_file_name, "r", ifp);
if (ifp == NULL)
{
if (0 != _gnu_noobjc_argv)
{
for (c = 0; c < _gnu_noobjc_argc; c++)
{
free(_gnu_noobjc_argv[c]);
}
free(_gnu_noobjc_argv);
}
goto proc_fs_error;
}
argument = 0;
position = 0;
while (argument < _gnu_noobjc_argc)
{
c = getc(ifp);
if ((c == EOF) || (c == 0)) // End of a parameter
{
if (argument == 0 && position > 0
&& _gnu_noobjc_argv[argument][position-1] == '\n')
{
stripTrailingNewline = YES;
}
if (stripTrailingNewline == YES && position > 0
&& _gnu_noobjc_argv[argument][position-1] == '\n')
{
position--;
}
_gnu_noobjc_argv[argument][position] = '\0';
argument++;
if (c == EOF) // End of command line
break;
position = 0;
continue;
}
_gnu_noobjc_argv[argument][position] = c;
position++;
}
_gnu_noobjc_argv[argument] = NULL;
fclose(ifp);
free(proc_file_name);
return;
proc_fs_error:
#ifdef HAVE_STRERROR
/* Don't care about thread safety of strerror() here as this is only
* called in the initial thread and there shouldn't be any other
* threads at this point.
*/
fprintf(stderr, "Couldn't open file %s when starting gnustep-base; %s\n",
proc_file_name, strerror(errno));
#else /* !HAVE_FUNCTION_STRERROR */
fprintf(stderr, "Couldn't open file %s when starting gnustep-base.\n",
proc_file_name);
#endif /* HAVE_FUNCTION_STRERROR */
fprintf(stderr, "Your gnustep-base library is compiled for a kernel supporting the /proc filesystem, but it can't access it.\n");
fprintf(stderr, "You should recompile or change your kernel.\n");
free(proc_file_name);
#ifdef HAVE_PROGRAM_INVOCATION_NAME
fprintf(stderr, "We try to go on anyway; but the program will ignore any argument which were passed to it.\n");
_gnu_noobjc_argc = 1;
_gnu_noobjc_argv = malloc(sizeof(char *) * 2);
if (_gnu_noobjc_argv == NULL)
goto malloc_error;
_gnu_noobjc_argv[0] = strdup(program_invocation_name);
if (_gnu_noobjc_argv[0] == NULL)
goto malloc_error;
_gnu_noobjc_argv[1] = NULL;
return;
#else /* !HAVE_PROGRAM_INVOCATION_NAME */
/*
* There is really little sense in going on here, because NSBundle
* will anyway crash later if we just put something like "_Unknown_"
* as the program name.
*/
abort();
#endif /* HAVE_PROGRAM_INVOCATION_NAME */
#endif /* !HAVE_KVM_ENV (e.g. HAVE_PROCFS) */
malloc_error:
fprintf(stderr, "malloc() error when starting gnustep-base.\n");
fprintf(stderr, "Free some memory and then re-run the program.\n");
abort();
}
static void
_gnu_noobjc_free_vars(void)
{
char **p;
p = _gnu_noobjc_argv;
while (*p)
{
free(*p);
p++;
}
free(_gnu_noobjc_argv);
_gnu_noobjc_argv = 0;
p = _gnu_noobjc_env;
while (*p)
{
free(*p);
p++;
}
free(_gnu_noobjc_env);
_gnu_noobjc_env = 0;
}
+ (void) initialize
{
if (nil == procLock) procLock = [NSRecursiveLock new];
if (self == [NSProcessInfo class]
&& !_gnu_processName && !_gnu_arguments && !_gnu_environment)
{
if (_gnu_noobjc_argv == 0 || _gnu_noobjc_env == 0)
{
fprintf(stderr, _GNU_MISSING_MAIN_FUNCTION_CALL);
exit(1);
}
_gnu_process_args(_gnu_noobjc_argc, _gnu_noobjc_argv, _gnu_noobjc_env);
_gnu_noobjc_free_vars();
}
}
#else /*! HAVE_PROCFS !HAVE_LOAD_METHOD !HAVE_KVM_ENV */
#ifdef _WIN32
/* For WindowsAPI Library, we know the global variables (argc, etc) */
+ (void) initialize
{
if (nil == procLock) procLock = [NSRecursiveLock new];
if (self == [NSProcessInfo class]
&& !_gnu_processName && !_gnu_arguments && !_gnu_environment)
{
_gnu_process_args(__argc, __argv, _environ);
}
}
#elif defined(__BEOS__)
extern int __libc_argc;
extern char **__libc_argv;
+ (void) initialize
{
if (nil == procLock) procLock = [NSRecursiveLock new];
if (self == [NSProcessInfo class]
&& !_gnu_processName && !_gnu_arguments && !_gnu_environment)
{
_gnu_process_args(__libc_argc, __libc_argv, environ);
}
}
#else
+ (void) initialize
{
if (nil == procLock) procLock = [NSRecursiveLock new];
}
#ifndef GS_PASS_ARGUMENTS
#undef main
/* The gnustep_base_user_main function is declared 'weak' so that the linker
* should actually use the one compiled as the program's 'main' function.
* The internal version gets called only if the program does not implement
* the function (ie the prgram was compiled with the wrong version of
* GSConfig.h included/imported). The other possible reason for the internal
* function to be called would be a compiler/linker issue (eg 'weak' not
* supported).
*/
int gnustep_base_user_main () __attribute__((weak));
int gnustep_base_user_main (int argc, char *argv[], char *env[])
{
fprintf(stderr, "\nGNUSTEP Internal Error:\n"
"The GNUstep function to establish the argv and environment variables could\n"
"not find the main function of your program.\n"
"Perhaps your program failed to #include <Foundation/NSObject.h> or\n"
"<Foundation/Foundation.h> (or included/imported a different version of the\n"
"header from the one supplied with this copy of the gnustep-base library)?\n"
"If that is not the case, Please report the error to bug-gnustep@gnu.org.\n");
exit(1);
}
int main(int argc, char *argv[], char *env[])
{
#ifdef NeXT_RUNTIME
/* This memcpy has to be done before the first message is sent to any
constant string object. See Apple Radar 2870817 */
memcpy(&_NSConstantStringClassReference,
objc_getClass(STRINGIFY(NXConstantString)),
sizeof(_NSConstantStringClassReference));
#endif
#if defined(_WIN32)
WSADATA lpWSAData;
// Initialize Windows Sockets
if (WSAStartup(MAKEWORD(1,1), &lpWSAData))
{
printf("Could not startup Windows Sockets\n");
exit(1);
}
#endif /* _WIN32 */