/
UnixOSProcessPlugin.c
5102 lines (4345 loc) · 139 KB
/
UnixOSProcessPlugin.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
/* Automatically generated by
VMPluginCodeGenerator VMMaker.oscog-eem.2518 uuid: 33deb326-de86-45aa-be20-d64c10de4e70
from
UnixOSProcessPlugin VMConstruction-Plugins-OSProcessPlugin.oscog-dtl.66 uuid: a8a2bf10-e7b3-4963-90b3-d69a2bee77bb
*/
static char __buildInfo[] = "UnixOSProcessPlugin VMConstruction-Plugins-OSProcessPlugin.oscog-dtl.66 uuid: a8a2bf10-e7b3-4963-90b3-d69a2bee77bb " __DATE__ ;
/* D T Lewis - UnixOSProcessPlugin.c translated from class
UnixOSProcessPlugin of OSProcessPlugin version 4.6.4 Cog */
#include "config.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <errno.h>
#ifdef __OpenBSD__
# include <sys/signalvar.h>
#endif
/* Default EXPORT macro that does nothing (see comment in sq.h): */
#define EXPORT(returnType) returnType
/* Do not include the entire sq.h file but just those parts needed. */
#include "sqConfig.h" /* Configuration options */
#include "sqVirtualMachine.h" /* The virtual machine proxy definition */
#include "sqPlatformSpecific.h" /* Platform specific definitions */
#define true 1
#define false 0
#define null 0 /* using 'null' because nil is predefined in Think C */
#ifdef SQUEAK_BUILTIN_PLUGIN
# undef EXPORT
# define EXPORT(returnType) static returnType
#endif
#include "pharovm/imageAccess.h"
#include "pharovm/debug.h"
#include "FilePlugin.h"
#include "SocketPlugin.h"
#include "sqaio.h"
#include "sqMemoryAccess.h"
/*** Constants ***/
#define FILEHANDLETYPE FILE * /* the type of low level stream to be used in a struct SQFile */
#define PrimErrBadArgument 3
#define PrimErrBadNumArgs 5
#define PrimErrNoMemory 9
#define PrimErrNotFound 11
#define PrimErrUnsupported 7
#define SESSIONIDENTIFIERTYPE int
EXPORT(int) getProcessArgumentCount();
EXPORT(char**) getProcessArgumentVector();
EXPORT(char**) getProcessEnvironmentVector();
/*** Function Prototypes ***/
static sqInt argumentAtAsType(sqInt classIdentifier);
static void * callocWrappersize(sqInt count, sqInt objectSize);
static sqInt copyBytesFromtolength(void *charArray1, void *charArray2, sqInt len);
static sqInt createPipeForReaderwriter(FILEHANDLETYPE *readerIOStreamPtr, FILEHANDLETYPE *writerIOStreamPtr);
static char * cStringFromString(sqInt aString);
static sqInt cStringasCollection(const char *aCString, sqInt classIdentifier);
static sqInt descriptorTableSize(void);
static void dupToStdErr(sqInt anSQFileDataStructure);
static void dupToStdIn(sqInt anSQFileDataStructure);
static void dupToStdOut(sqInt anSQFileDataStructure);
static sqInt environmentAtAsType(sqInt classIdentifier);
static sqInt environmentAtSymbolAsType(sqInt classIdentifier);
static sqInt fileDescriptorFrom(sqInt aSQFileByteArray);
static FILEHANDLETYPE fileHandleFrom(sqInt sqFileStructByteArray);
static usqIntptr_t fileRecordSize(void);
static SQFile * fileValueOf(sqInt anSQFileRecord);
static char ** fixPointersInArrayOfStringswithOffsets(sqInt flattenedStrings, sqInt offsets);
static sqInt forkAndExecInDirectory(sqInt useSignalHandler);
EXPORT(pid_t) forkSqueak(sqInt useSignalHandler);
static void * forwardSignaltoSemaphoreAt(sqInt sigNum, sqInt semaphoreIndex);
EXPORT(sqInt) getCurrentWorkingDirectoryAsType(sqInt classIdentifier);
static char ** getEnvironmentVector(void);
EXPORT(const char*) getModuleName(void);
static sqInt getStdHandle(sqInt n);
static sqInt getThisSessionIdentifier(void);
static void * handleSignalFunctionAddress(void);
static void handleSignal(int sigNum);
EXPORT(sqInt) initialiseModule(void);
static sqInt initializeModuleForPlatform(void);
static sqInt isNonNullSQFile(sqInt objectPointer);
static sqInt isNullSQSocket(sqInt objectPointer);
static sqInt isSQFileObject(sqInt objectPointer);
static sqInt isSQSocketObject(sqInt objectPointer);
static sqInt isValidFileSession(sqInt objectPointer);
static sqInt isVmThread(void);
static sqInt makePipeForReaderwriter(FILEHANDLETYPE *readerIOStreamPtr, FILEHANDLETYPE *writerIOStreamPtr);
static sqInt maskForThisThreadAndResend(int sigNum);
static sqInt maskSignalForThisThread(int sigNum);
EXPORT(sqInt) moduleUnloaded(char *aModuleName);
static sqInt msg(char *s);
static sqInt needSigaltstack(void);
static sqInt newPthreadTypeByteArray(pthread_t aPthreadType);
static sqInt newSQFileByteArray(void);
static sqInt newSQSocketByteArray(void);
static void ** originalSignalHandlers(void);
static void * pointerFrom(sqInt aByteArray);
EXPORT(sqInt) primitiveArgumentAt(void);
EXPORT(sqInt) primitiveArgumentAtAsBytes(void);
EXPORT(sqInt) primitiveCanReceiveSignals(void);
EXPORT(sqInt) primitiveChdir(void);
EXPORT(sqInt) primitiveCreatePipe(void);
EXPORT(sqInt) primitiveCreatePipeWithSessionIdentifier(void);
EXPORT(sqInt) primitiveDup(sqInt fileDescriptor);
EXPORT(sqInt) primitiveDupTo(sqInt oldFileDescriptor, sqInt newFileDescriptor);
EXPORT(sqInt) primitiveEnvironmentAt(void);
EXPORT(sqInt) primitiveEnvironmentAtAsBytes(void);
EXPORT(sqInt) primitiveEnvironmentAtSymbol(void);
EXPORT(sqInt) primitiveEnvironmentAtSymbolAsBytes(void);
EXPORT(sqInt) primitiveErrorMessageAt(void);
EXPORT(sqInt) primitiveFileProtectionMask(void);
EXPORT(sqInt) primitiveFileStat(void);
EXPORT(sqInt) primitiveFixPointersInArrayOfStrings(void);
EXPORT(sqInt) primitiveForkAndExecInDirectory(void);
EXPORT(sqInt) primitiveForkExec(void);
EXPORT(sqInt) primitiveForkSqueak(void);
EXPORT(sqInt) primitiveForkSqueakWithoutSigHandler(void);
EXPORT(sqInt) primitiveForwardSignalToSemaphore(void);
EXPORT(sqInt) primitiveGetCurrentWorkingDirectory(void);
EXPORT(sqInt) primitiveGetCurrentWorkingDirectoryAsBytes(void);
EXPORT(sqInt) primitiveGetEGid(void);
EXPORT(sqInt) primitiveGetEUid(void);
EXPORT(sqInt) primitiveGetGid(void);
EXPORT(sqInt) primitiveGetPGid(void);
EXPORT(sqInt) primitiveGetPGrp(void);
EXPORT(sqInt) primitiveGetPid(void);
EXPORT(sqInt) primitiveGetPPid(void);
EXPORT(sqInt) primitiveGetSession(void);
EXPORT(sqInt) primitiveGetStdErrHandle(void);
EXPORT(sqInt) primitiveGetStdErrHandleWithSessionIdentifier(void);
EXPORT(sqInt) primitiveGetStdInHandle(void);
EXPORT(sqInt) primitiveGetStdInHandleWithSessionIdentifier(void);
EXPORT(sqInt) primitiveGetStdOutHandle(void);
EXPORT(sqInt) primitiveGetStdOutHandleWithSessionIdentifier(void);
EXPORT(sqInt) primitiveGetThreadID(void);
EXPORT(sqInt) primitiveGetUid(void);
EXPORT(sqInt) primitiveIsAtEndOfFile(void);
EXPORT(sqInt) primitiveKillOnExit(void);
EXPORT(sqInt) primitiveLockFileRegion(void);
EXPORT(sqInt) primitiveMakePipe(void);
EXPORT(sqInt) primitiveMakePipeWithSessionIdentifier(void);
EXPORT(sqInt) primitiveModuleName(void);
EXPORT(sqInt) primitiveNice(void);
EXPORT(sqInt) primitivePutEnv(void);
EXPORT(sqInt) primitiveRealpath(void);
EXPORT(sqInt) primitiveRealpathAsBytes(void);
EXPORT(sqInt) primitiveReapChildProcess(void);
EXPORT(sqInt) primitiveSemaIndexFor(void);
EXPORT(sqInt) primitiveSendSigabrtTo(void);
EXPORT(sqInt) primitiveSendSigalrmTo(void);
EXPORT(sqInt) primitiveSendSigchldTo(void);
EXPORT(sqInt) primitiveSendSigcontTo(void);
EXPORT(sqInt) primitiveSendSighupTo(void);
EXPORT(sqInt) primitiveSendSigintTo(void);
EXPORT(sqInt) primitiveSendSigkillTo(void);
EXPORT(sqInt) primitiveSendSigpipeTo(void);
EXPORT(sqInt) primitiveSendSigquitTo(void);
EXPORT(sqInt) primitiveSendSigstopTo(void);
EXPORT(sqInt) primitiveSendSigtermTo(void);
EXPORT(sqInt) primitiveSendSigusr1To(void);
EXPORT(sqInt) primitiveSendSigusr2To(void);
EXPORT(sqInt) primitiveSetPGid(void);
EXPORT(sqInt) primitiveSetPGrp(void);
EXPORT(sqInt) primitiveSetSemaIndex(void);
EXPORT(sqInt) primitiveSetSid(void);
EXPORT(sqInt) primitiveSigChldNumber(void);
EXPORT(sqInt) primitiveSigHupNumber(void);
EXPORT(sqInt) primitiveSigIntNumber(void);
EXPORT(sqInt) primitiveSigKillNumber(void);
EXPORT(sqInt) primitiveSigPipeNumber(void);
EXPORT(sqInt) primitiveSigQuitNumber(void);
EXPORT(sqInt) primitiveSigTermNumber(void);
EXPORT(sqInt) primitiveSigUsr1Number(void);
EXPORT(sqInt) primitiveSigUsr2Number(void);
EXPORT(sqInt) primitiveSizeOfInt(void);
EXPORT(sqInt) primitiveSizeOfPointer(void);
EXPORT(sqInt) primitiveSQFileFlush(void);
EXPORT(sqInt) primitiveSQFileFlushWithSessionIdentifier(void);
EXPORT(sqInt) primitiveSQFileSetBlocking(void);
EXPORT(sqInt) primitiveSQFileSetBlockingWithSessionIdentifier(void);
EXPORT(sqInt) primitiveSQFileSetNonBlocking(void);
EXPORT(sqInt) primitiveSQFileSetNonBlockingWithSessionIdentifier(void);
EXPORT(sqInt) primitiveSQFileSetUnbuffered(void);
EXPORT(sqInt) primitiveSQFileSetUnbufferedWithSessionIdentifier(void);
EXPORT(sqInt) primitiveTestEndOfFileFlag(void);
EXPORT(sqInt) primitiveTestLockableFileRegion(void);
EXPORT(sqInt) primitiveUnixFileClose(sqInt anIntegerFileNumber);
EXPORT(sqInt) primitiveUnixFileNumber(void);
EXPORT(sqInt) primitiveUnlockFileRegion(void);
EXPORT(sqInt) primitiveUnsetEnv(void);
EXPORT(sqInt) primitiveVersionString(void);
static sqInt realpathAsType(sqInt classIdentifier);
static void reapChildProcess(int sigNum);
static sqInt resendSignal(int sigNum);
static void restoreDefaultSignalHandlers(void);
static void sendSignalToPids(void);
static sqInt sendSignaltoPid(sqInt sig, sqInt pid);
static SESSIONIDENTIFIERTYPE sessionIdentifierFrom(sqInt aByteArray);
EXPORT(sqInt) setInterpreter(struct VirtualMachine *anInterpreter);
static void setSigChldHandler(void);
static void setSigIntDefaultHandler(void);
static void setSigIntIgnore(void);
static void * setSignalNumberhandler(sqInt signalNumber, void *signalHandlerAddress);
static void setSigPipeDefaultHandler(void);
static sqInt setSigPipeHandler(void);
static void setSigPipeIgnore(void);
EXPORT(sqInt) shutdownModule(void);
static sqInt sigAbrtNumber(void);
static sqInt sigAlrmNumber(void);
static sqInt sigChldNumber(void);
static sqInt sigContNumber(void);
static void * sigDefaultNumber(void);
static void * sigErrorNumber(void);
static void * sigHoldNumber(void);
static sqInt sigHupNumber(void);
static void * sigIgnoreNumber(void);
static sqInt sigIntNumber(void);
static sqInt sigKillNumber(void);
static sqInt signalArraySize(void);
static sqInt sigPipeNumber(void);
static sqInt sigQuitNumber(void);
static sqInt sigStopNumber(void);
static sqInt sigTermNumber(void);
static sqInt sigUsr1Number(void);
static sqInt sigUsr2Number(void);
static usqIntptr_t sizeOfInt(void);
static usqIntptr_t sizeOfPointer(void);
static sqInt sizeOfSession(void);
static int socketDescriptorFrom(sqInt sqSocketOop);
static usqIntptr_t socketRecordSize(void);
static SocketPtr socketValueOf(sqInt anSQSocketRecord);
static sqInt stringFromCString(const char *aCString);
static char * transientCStringFromString(sqInt aString);
static int unixFileNumber(FILEHANDLETYPE fileHandle);
static char * versionString(void);
/*** Variables ***/
#if !defined(SQUEAK_BUILTIN_PLUGIN)
static void * (*arrayValueOf)(sqInt oop);
static sqInt (*byteSizeOf)(sqInt oop);
static sqInt (*checkedIntegerValueOf)(sqInt intOop);
static sqInt (*classArray)(void);
static sqInt (*classByteArray)(void);
static sqInt (*classString)(void);
static sqInt (*failed)(void);
static sqInt (*falseObject)(void);
static void * (*firstIndexableField)(sqInt oop);
static sqInt (*getThisSessionID)(void);
static sqInt (*instantiateClassindexableSize)(sqInt classPointer, sqInt size);
static sqInt (*integerObjectOf)(sqInt value);
static sqInt (*integerValueOf)(sqInt oop);
static void * (*ioLoadFunctionFrom)(char *functionName, char *moduleName);
static sqInt (*isBytes)(sqInt oop);
static sqInt (*isIntegerObject)(sqInt objectPointer);
static sqInt (*methodArgumentCount)(void);
static sqInt (*methodReturnValue)(sqInt oop);
static sqInt (*nilObject)(void);
static sqInt (*pop)(sqInt nItems);
static sqInt (*popthenPush)(sqInt nItems, sqInt oop);
static sqInt (*popRemappableOop)(void);
static sqInt (*primitiveFail)(void);
static sqInt (*primitiveFailFor)(sqInt reasonCode);
static sqInt (*push)(sqInt object);
static sqInt (*pushInteger)(sqInt integerValue);
static sqInt (*pushRemappableOop)(sqInt oop);
static sqInt (*signalSemaphoreWithIndex)(sqInt semaIndex);
static sqInt (*sizeOfSTArrayFromCPrimitive)(void *cPtr);
static sqInt (*stObjectatput)(sqInt array, sqInt index, sqInt value);
static sqInt (*stSizeOf)(sqInt oop);
static sqInt (*stackIntegerValue)(sqInt offset);
static sqInt (*stackObjectValue)(sqInt offset);
static sqInt (*stackValue)(sqInt offset);
static sqInt (*trueObject)(void);
#else /* !defined(SQUEAK_BUILTIN_PLUGIN) */
extern void * arrayValueOf(sqInt oop);
extern sqInt byteSizeOf(sqInt oop);
extern sqInt checkedIntegerValueOf(sqInt intOop);
extern sqInt classArray(void);
extern sqInt classByteArray(void);
extern sqInt classString(void);
extern sqInt failed(void);
extern sqInt falseObject(void);
extern void * firstIndexableField(sqInt oop);
extern sqInt getThisSessionID(void);
extern sqInt instantiateClassindexableSize(sqInt classPointer, sqInt size);
extern sqInt integerObjectOf(sqInt value);
extern sqInt integerValueOf(sqInt oop);
extern void * ioLoadFunctionFrom(char *functionName, char *moduleName);
extern sqInt isBytes(sqInt oop);
#if !defined(isIntegerObject)
extern sqInt isIntegerObject(sqInt objectPointer);
#endif
extern sqInt methodArgumentCount(void);
extern sqInt methodReturnValue(sqInt oop);
extern sqInt nilObject(void);
extern sqInt pop(sqInt nItems);
extern sqInt popthenPush(sqInt nItems, sqInt oop);
extern sqInt popRemappableOop(void);
extern sqInt primitiveFail(void);
extern sqInt primitiveFailFor(sqInt reasonCode);
extern sqInt push(sqInt object);
extern sqInt pushInteger(sqInt integerValue);
extern sqInt pushRemappableOop(sqInt oop);
extern sqInt signalSemaphoreWithIndex(sqInt semaIndex);
extern sqInt sizeOfSTArrayFromCPrimitive(void *cPtr);
extern sqInt stObjectatput(sqInt array, sqInt index, sqInt value);
extern sqInt stSizeOf(sqInt oop);
extern sqInt stackIntegerValue(sqInt offset);
extern sqInt stackObjectValue(sqInt offset);
extern sqInt stackValue(sqInt offset);
extern sqInt trueObject(void);
extern
#endif
struct VirtualMachine* interpreterProxy;
static const char *moduleName =
#ifdef SQUEAK_BUILTIN_PLUGIN
"UnixOSProcessPlugin VMConstruction-Plugins-OSProcessPlugin.oscog-dtl.66 (i)"
#else
"UnixOSProcessPlugin VMConstruction-Plugins-OSProcessPlugin.oscog-dtl.66 (e)"
#endif
;
static void *originalSigHandlers[NSIG + 1];
static pid_t *pidArray = NULL;
static sqInt pidCount;
static unsigned char semaIndices[NSIG + 1];
static sqInt sigChldSemaIndex;
static int sigNumToSend = SIGTERM;
static sqInt useSignalStack;
static pthread_t vmThread;
/*** Macros ***/
#define sessionIdentifierFromSqFile(sqFile) (((SQFile *)(sqFile))->sessionID)
/* Answer a string containing the OS process argument at index (an Integer)
in the
argument list.
*/
/* UnixOSProcessPlugin>>#argumentAtAsType: */
static sqInt
argumentAtAsType(sqInt classIdentifier)
{
extern char **argVec;
sqInt index;
sqInt len;
sqInt newString;
sqInt s;
char *sPtr;
int argCnt = getProcessArgumentCount();
index = stackIntegerValue(0);
if ((index > argCnt) || (index < 1)) {
popthenPush(2, nilObject());
}
else {
sPtr = argVec[index - 1];
/* begin cString:asCollection: */
len = strlen(sPtr);
newString = instantiateClassindexableSize(classIdentifier, len);
strncpy(arrayValueOf(newString), sPtr, len);
s = newString;
popthenPush(2, s);
}
return 0;
}
/* Using malloc() and calloc() is something I would like to avoid, since it
is likely to cause problems some time in the future if somebody redesigns
object memory allocation. This wrapper just makes it easy to find senders
of calloc() in my code. -dtl */
/* OSProcessPlugin>>#callocWrapper:size: */
static void *
callocWrappersize(sqInt count, sqInt objectSize)
{
return calloc(count, objectSize);
}
/* self cCode: 'memcpy(charArray2, charArray1, len' */
/* OSProcessPlugin>>#copyBytesFrom:to:length: */
static sqInt
copyBytesFromtolength(void *charArray1, void *charArray2, sqInt len)
{
memcpy(charArray2, charArray1, len);
return 0;
}
/* Create a pipe and populate the readerIOStream and writerIOStream
variables. The SIGPIPE handler must have been set before creating the
pipe. Answer true for
success, else false.
*/
/* UnixOSProcessPlugin>>#createPipeForReader:writer: */
static sqInt
createPipeForReaderwriter(FILEHANDLETYPE *readerIOStreamPtr, FILEHANDLETYPE *writerIOStreamPtr)
{
int filedes[2];
if ((pipe(filedes)) == -1) {
/* Translates to a pipe() system call */
return 0;
}
else {
*writerIOStreamPtr= (FILE *) fdopen (filedes[1], "a");
*readerIOStreamPtr= (FILE *) fdopen (filedes[0], "r");
return 1;
}
}
/* Answer a new null-terminated C string copied from aString. The C string
is allocated from the C runtime heap. See transientCStringFromString for
a version which allocates from object memory.
Caution: This may invoke the garbage collector. */
/* OSProcessPlugin>>#cStringFromString: */
static char *
cStringFromString(sqInt aString)
{
char *cString;
sqInt len;
char *sPtr;
sPtr = arrayValueOf(aString);
len = sizeOfSTArrayFromCPrimitive(sPtr);
/* Space for a null terminated C string. */
cString = callocWrappersize(len + 1, 1);
strncpy (cString, sPtr, len);
return cString;
}
/* Answer a new collection, usually of type ByteArray or ByteString copied
from a null-terminated C string. Caution: This may invoke the garbage
collector.
*/
/* OSProcessPlugin>>#cString:asCollection: */
static sqInt
cStringasCollection(const char *aCString, sqInt classIdentifier)
{
sqInt len;
sqInt newString;
len = strlen(aCString);
newString = instantiateClassindexableSize(classIdentifier, len);
strncpy(arrayValueOf(newString), aCString, len);
return newString;
}
/* dtl:
Answer the size of the file descriptor table for a process. I am not sure
of the most portable
way to do this. If this implementation does not work on your Unix
platform, try changing
it to answer the value of FOPEN:=MAX, which will hopefully be defined in
stdio.h.
eem:
If we know that (e.g.) stdin is open we can use fd=dup(0);close(fd);fd
instead.
*/
/* UnixOSProcessPlugin>>#descriptorTableSize */
static sqInt
descriptorTableSize(void)
{
return getdtablesize();
}
/* Dup a file descriptor to allow it to be attached as the standard error
when we
exec() a new executable. This is Unix specific, in that it assumes that
file descriptor
0 is stdin, 1 is stdout, and 2 is stderr. The dup2() call is used to copy
the open file
descriptors into file descriptors 0, 1 and 2 so that the image which we
execute will
use them as stdin, stdout, and stderr.
*/
/* UnixOSProcessPlugin>>#dupToStdErr: */
static void
dupToStdErr(sqInt anSQFileDataStructure)
{
sqInt filenoToDup;
/* begin fileDescriptorFrom: */
if (!((((isBytes(anSQFileDataStructure))
&& ((byteSizeOf(anSQFileDataStructure)) == (sizeof(SQFile))))
&& ((getThisSessionID()) == (sessionIdentifierFromSqFile(arrayValueOf(anSQFileDataStructure)))))
&& (isNonNullSQFile(anSQFileDataStructure)))) {
filenoToDup = -1;
goto l1;
}
filenoToDup = fileno(fileHandleFrom(anSQFileDataStructure));
l1: /* end fileDescriptorFrom: */;
if (!(filenoToDup < 0)) {
if (!(filenoToDup == 2)) {
fflush(stderr);
dup2(filenoToDup, 2);
}
}
}
/* Dup a file descriptor to allow it to be attached as the standard input
when we
exec() a new executable. This is Unix specific, in that it assumes that
file descriptor
0 is stdin, 1 is stdout, and 2 is stderr. The dup2() call is used to copy
the open file
descriptors into file descriptors 0, 1 and 2 so that the image which we
execute will
use them as stdin, stdout, and stderr.
*/
/* UnixOSProcessPlugin>>#dupToStdIn: */
static void
dupToStdIn(sqInt anSQFileDataStructure)
{
sqInt filenoToDup;
/* begin fileDescriptorFrom: */
if (!((((isBytes(anSQFileDataStructure))
&& ((byteSizeOf(anSQFileDataStructure)) == (sizeof(SQFile))))
&& ((getThisSessionID()) == (sessionIdentifierFromSqFile(arrayValueOf(anSQFileDataStructure)))))
&& (isNonNullSQFile(anSQFileDataStructure)))) {
filenoToDup = -1;
goto l1;
}
filenoToDup = fileno(fileHandleFrom(anSQFileDataStructure));
l1: /* end fileDescriptorFrom: */;
if (!(filenoToDup < 0)) {
if (!(filenoToDup == 0)) {
fflush(stdin);
dup2(filenoToDup, 0);
rewind(stdin);
}
}
}
/* Dup a file descriptor to allow it to be attached as the standard output
when we
exec() a new executable. This is Unix specific, in that it assumes that
file descriptor
0 is stdin, 1 is stdout, and 2 is stderr. The dup2() call is used to copy
the open file
descriptors into file descriptors 0, 1 and 2 so that the image which we
execute will
use them as stdin, stdout, and stderr.
*/
/* UnixOSProcessPlugin>>#dupToStdOut: */
static void
dupToStdOut(sqInt anSQFileDataStructure)
{
sqInt filenoToDup;
/* begin fileDescriptorFrom: */
if (!((((isBytes(anSQFileDataStructure))
&& ((byteSizeOf(anSQFileDataStructure)) == (sizeof(SQFile))))
&& ((getThisSessionID()) == (sessionIdentifierFromSqFile(arrayValueOf(anSQFileDataStructure)))))
&& (isNonNullSQFile(anSQFileDataStructure)))) {
filenoToDup = -1;
goto l1;
}
filenoToDup = fileno(fileHandleFrom(anSQFileDataStructure));
l1: /* end fileDescriptorFrom: */;
if (!(filenoToDup < 0)) {
if (!(filenoToDup == 1)) {
fflush(stdout);
dup2(filenoToDup, 1);
}
}
}
/* Answer a string containing the OS process environment string at index (an
Integer) in the environment list. */
/* UnixOSProcessPlugin>>#environmentAtAsType: */
static sqInt
environmentAtAsType(sqInt classIdentifier)
{
sqInt envCnt;
sqInt index;
sqInt len;
sqInt newString;
char **p;
sqInt s;
char *sPtr;
/* Count number of environment variables. */
p = getEnvironmentVector();
if (p == null) {
return primitiveFail();
}
envCnt = 0;
while (*p++) envCnt++;
/* restore pointer */
p = getEnvironmentVector();
index = stackIntegerValue(0);
if ((index > envCnt) || (index < 1)) {
pop(2);
push(nilObject());
}
else {
sPtr = p[index - 1];
/* begin cString:asCollection: */
len = strlen(sPtr);
newString = instantiateClassindexableSize(classIdentifier, len);
strncpy(arrayValueOf(newString), sPtr, len);
s = newString;
pop(2);
push(s);
}
return 0;
}
/* Answer the value of an environment variable keyed by a Symbol. */
/* UnixOSProcessPlugin>>#environmentAtSymbolAsType: */
static sqInt
environmentAtSymbolAsType(sqInt classIdentifier)
{
char * getenvResult;
getenvResult = getenv(transientCStringFromString(stackObjectValue(0)));
if (getenvResult == 0) {
return primitiveFail();
}
else {
pop(2);
push(cStringasCollection(getenvResult, classIdentifier));
}
return 0;
}
/* Answer the OS file descriptor, an integer value, from a SQFile data
structure byte array, or answer -1 if unable to obtain the file descriptor
(probably due
to receiving an incorrect type of object as aFileHandle).
*/
/* return type should be int, but skip the declaration to permit inlining */
/* UnixOSProcessPlugin>>#fileDescriptorFrom: */
static sqInt
fileDescriptorFrom(sqInt aSQFileByteArray)
{
if (!((((isBytes(aSQFileByteArray))
&& ((byteSizeOf(aSQFileByteArray)) == (sizeof(SQFile))))
&& ((getThisSessionID()) == (sessionIdentifierFromSqFile(arrayValueOf(aSQFileByteArray)))))
&& (isNonNullSQFile(aSQFileByteArray)))) {
return -1;
}
return fileno(fileHandleFrom(aSQFileByteArray));
}
/* Answer a file handle from a SQFile structure. On most platforms, this
will be a (FILE *). On Win32, it is a HANDLE. */
/* OSProcessPlugin>>#fileHandleFrom: */
static FILEHANDLETYPE
fileHandleFrom(sqInt sqFileStructByteArray)
{
SQFile *sqFile;
sqFile = arrayValueOf(sqFileStructByteArray);
return sqFile->file;
}
/* Return the size of a Smalltalk file record in bytes. */
/* OSProcessPlugin>>#fileRecordSize */
static usqIntptr_t
fileRecordSize(void)
{
return sizeof(SQFile);
}
/* Return a pointer to the first byte of of the SQFile data structure file
record within
anSQFileRecord, which is expected to be a ByteArray of size
self>>fileRecordSize.
*/
/* OSProcessPlugin>>#fileValueOf: */
static SQFile *
fileValueOf(sqInt anSQFileRecord)
{
return arrayValueOf(anSQFileRecord);
}
/* The image constructs a flattened string of all the argument and/or
environment strings.
There is room at the beginning for the null-terminated array of pointers
to strings.
The rest of the string contains the null-terminated strings. */
/* Use the address offsets in offsetArray to fix up the pointers in
cStringArray. The result is a C array of pointers to char, used for argv
and env vectors.
*/
/* OSProcessPlugin>>#fixPointersInArrayOfStrings:withOffsets: */
static char **
fixPointersInArrayOfStringswithOffsets(sqInt flattenedStrings, sqInt offsets)
{
sqInt count;
sqInt idx;
sqInt *offsetArray;
char **ptr;
usqInt sz;
sqInt val;
count = stSizeOf(offsets);
offsetArray = firstIndexableField(offsets);
sz = ((usqInt)(byteSizeOf(flattenedStrings)));
if ((count * (sizeof(char *))) >= sz) {
primitiveFailFor(PrimErrBadArgument);
return 0;
}
ptr = ((char **) (arrayValueOf(flattenedStrings)));
idx = 0;
while (idx < count) {
val = integerValueOf(offsetArray[idx]);
if ((((usqInt)val)) >= sz) {
primitiveFailFor(PrimErrBadArgument);
return 0;
}
ptr[idx] = ((((char *) ptr)) + val);
idx += 1;
}
if ((ptr[idx]) != 0) {
primitiveFailFor(PrimErrBadArgument);
}
return (failed()
? 0
: ptr);
}
/* Fork a child OS process, and do an exec in the child. The parent continues
on in
Smalltalk, and this method answers the pid of the child which was created.
If useSignalHandler is true, set the signal handler for SIGCHLD.
Otherwise, assume
that death of child events are handled through some other mechanism.
In this implementation, memory for the argument and environment arrays is
allocated in the image prior to calling this primitive. This allows us to
avoid invoking the
garbage collector in this primitive (thereby moving the locations of
environment and argument memory), but comes at the cost of twiddling C
pointers here in the
primitive. An alternative to this whole mess is just to malloc the
environment and
argument vectors, but I think it is a good idea to avoid malloc as much as
possible so as not to limit future ObjectMemory implementations.
This primitive replaces #primitiveForkAndExec from earlier versions of the
plugin. The new name permits backward compatibility for an image running
on a VM
which does not yet have the updated plugin. This implementation uses a
different argument format on the stack, and differs functionally in that
the child now closes
all file descriptors (including sockets) not required (that is, everything
except stdin,
stdout, and stderr on descriptors 0, 1 and 2). This eliminates some flakey
behavior in child processes connected to Squeak by pipes, which failed to
exit at expected times
due to the old file descriptors remaining open. This is also cleaner in
that garbage
descriptors are not left hanging around the the child.
On entry, the stack contains:
0: workingDir, a null terminated string specifying the working directory
to use, or nil.
1: envOffsets, an array of integers for calculating environment string
address offsets.
2: envVecBuffer, a String buffer containing environment strings arranged
to look like char **.
3: argOffsets, an array of integers for calculating argument string
address offsets.
4: argVecBuffer, a String buffer containing argument strings arranged to
look like char **.
5: stdErr, a ByteArray handle.
6: stdOut, a ByteArray handle.
7: stdIn, a ByteArray handle.
8: executableFile, a null terminated string with the name of the file to
execute. 9: the sender
*/
/* UnixOSProcessPlugin>>#forkAndExecInDirectory: */
static sqInt
forkAndExecInDirectory(sqInt useSignalHandler)
{
sqInt argOffsets;
char **args;
sqInt argVecBuffer;
char **env;
sqInt envOffsets;
sqInt envVecBuffer;
sqInt executableFile;
sqInt fd;
sqInt fdLimiT;
struct itimerval intervalTimer;
pid_t pid;
char *progNamePtr;
char *pwdPtr;
struct itimerval saveIntervalTimer;
sqInt sigNum;
sqInt stdErr;
sqInt stdIn;
sqInt stdOut;
sqInt workingDir;
char **envVec = getProcessEnvironmentVector();
if ((methodArgumentCount()) != 9) {
return primitiveFailFor(PrimErrBadNumArgs);
}
if (useSignalHandler) {
setSigChldHandler();
}
workingDir = stackObjectValue(0);
envOffsets = stackObjectValue(1);
envVecBuffer = stackObjectValue(2);
argOffsets = stackObjectValue(3);
argVecBuffer = stackObjectValue(4);
stdErr = stackObjectValue(5);
stdOut = stackObjectValue(6);
stdIn = stackObjectValue(7);
executableFile = stackObjectValue(8);
if (failed()) {
return primitiveFailFor(PrimErrBadArgument);
}
intervalTimer.it_interval.tv_sec = 0;
intervalTimer.it_interval.tv_usec = 0;
intervalTimer.it_value.tv_sec = 0;
intervalTimer.it_value.tv_usec = 0;
setitimer (ITIMER_REAL, &intervalTimer, &saveIntervalTimer);
if (((pid = vfork())) != 0) {
/* Normal return to Smalltalk - this is the old parent process. */
/* Enable the timer again before resuming Smalltalk. */
setitimer (ITIMER_REAL, &saveIntervalTimer, 0L);
if (!(failed())) {
/* Pop 9 arguments plus receiver, push pid. */
pop(10);
pushInteger(pid);
}
return null;
}
if (workingDir != (nilObject())) {
pwdPtr = arrayValueOf(workingDir);
if ((failed())
|| (pwdPtr == 0)) {
primitiveFailFor(PrimErrBadArgument);
logError("bad workingDir parameter\n");
_exit(-1);
}
if ((chdir(pwdPtr)) != 0) {
primitiveFailFor(PrimErrNotFound);
logErrorFromErrno("chdir");
_exit(-1);
}
}
/* Dup the file handles to attach the new child process to the right streams
on descriptors 0, 1 and 2. */
progNamePtr = arrayValueOf(executableFile);
if (!(stdErr == (nilObject()))) {
dupToStdErr(stdErr);
}
if (!(stdOut == (nilObject()))) {
dupToStdOut(stdOut);
}
if (!(stdIn == (nilObject()))) {
dupToStdIn(stdIn);
}
for (fd = 3, fdLimiT = ((getdtablesize()) - 1); fd <= fdLimiT; fd += 1) {
close(fd);
}
if (envVecBuffer == (nilObject())) {
env = envVec;
}
else {
env = ((char **) (fixPointersInArrayOfStringswithOffsets(envVecBuffer, envOffsets)));
}
args = ((char **) (fixPointersInArrayOfStringswithOffsets(argVecBuffer, argOffsets)));
if ((env == 0)
|| (args == 0)) {
logErrorFromErrno("bad env or bad args");
_exit(-1);
}
/* begin restoreDefaultSignalHandlers */
if (!(semaIndices == null)) {
/* nil if in interpreter simulation */
sigNum = 1;
while (sigNum <= (signalArraySize())) {
if ((semaIndices[sigNum]) > 0) {
setSignalNumberhandler(sigNum, (originalSignalHandlers())[sigNum]);
}
sigNum += 1;
}
}
execve(progNamePtr, args, env);
logErrorFromErrno(progNamePtr);
_exit(-1);
return 0;
}
/* Fork a child process, and continue running squeak in the child process.
Answer the result of the fork() call, either the child pid or zero.
After calling fork(), two OS processes exist, one of which is the child of
the other. On
systems which implement copy-on-write memory management, and which support
the fork() system call, both processes will be running Smalltalk images,
and will be sharing
the same memory space. In the original OS process, the resulting value of
pid is the
process id of the child process (a non-zero integer). In the child
process, the value of
pid is zero.
The child recreates sufficient external resources to continue running.
This is done by
attaching to a new X session. The child is otherwise a copy of the parent
process, and
will continue executing the Smalltalk image at the same point as its
parent. The return
value of this primitive may be used by the two running Smalltalk images to
determine which is the parent and which is the child.
The child should not depend on using existing connections to external
resources. For
example, the child may lose its connections to stdin, stdout, and stderr
after its parent
exits.
The new child image does not start itself from the image in the file
system; rather it is
a clone of the parent image as it existed at the time of
primitiveForkSqueak. For this
reason, the parent and child should agree in advance as to whom is allowed
to save the
image to the file system, otherwise one Smalltalk may overwrite the image
of the other.
This is a simple call to fork(), rather than the more common idiom of
vfork() followed
by exec(). The vfork() call cannot be used here because it is designed to