Win32OperatingSystem.st
changeset 23927 3f82716744b9
parent 23848 b74dc3385473
child 23928 2c38127d6863
--- a/Win32OperatingSystem.st	Fri Mar 15 15:31:48 2019 +0100
+++ b/Win32OperatingSystem.st	Sat Mar 16 00:51:37 2019 +0100
@@ -358,6 +358,10 @@
 #  include <iphlpapi.h>
 # endif
 
+// not needed
+// #define PSAPI_VERSION 1
+// #include <psapi.h>
+
 # ifndef WINDOWSX_H_INCLUDED
 #  define WINDOWSX_H_INCLUDED
 #  include <windowsx.h>
@@ -3855,68 +3859,68 @@
 !
 
 exec:aCommandPath withArguments:argString environment:environment fileDescriptors:fdArray fork:doFork
-        newPgrp:newPgrp inDirectory:aDirectory
-        showWindow:showWindowBooleanOrNil
+	newPgrp:newPgrp inDirectory:aDirectory
+	showWindow:showWindowBooleanOrNil
 
     "Internal lowLevel entry for combined fork & exec for WIN32
 
      If fork is false (chain a command):
-         execute the OS command specified by the argument, aCommandPath, with
-         arguments in argArray (no arguments, if nil).
-         If successful, this method does not return and smalltalk is gone.
-         If not successful, it does return.
-         Normal use is with forkForCommand.
+	 execute the OS command specified by the argument, aCommandPath, with
+	 arguments in argArray (no arguments, if nil).
+	 If successful, this method does not return and smalltalk is gone.
+	 If not successful, it does return.
+	 Normal use is with forkForCommand.
 
      If fork is true (subprocess command execution):
-        fork a child to do the above.
-        The Win32ProcessHandle of the child process is returned; nil if the fork failed.
+	fork a child to do the above.
+	The Win32ProcessHandle of the child process is returned; nil if the fork failed.
 
      fdArray contains the filedescriptors, to be used for the child (if fork is true).
-        fdArray[1] = 15 -> use fd 15 as stdin.
-        If an element of the array is set to nil, the corresponding filedescriptor
-        will be closed for the child.
-        fdArray[0] == StdIn for child
-        fdArray[1] == StdOut for child
-        fdArray[2] == StdErr for child
+	fdArray[1] = 15 -> use fd 15 as stdin.
+	If an element of the array is set to nil, the corresponding filedescriptor
+	will be closed for the child.
+	fdArray[0] == StdIn for child
+	fdArray[1] == StdOut for child
+	fdArray[2] == StdErr for child
 
      NOTE that in WIN32 the fds are HANDLES.
 
      If newPgrp is true, the subprocess will be established in a new process group.
-        The processgroup will be equal to id.
-        newPgrp is not used on WIN32 and VMS systems.
+	The processgroup will be equal to id.
+	newPgrp is not used on WIN32 and VMS systems.
 
      showWindowOrBoolean may be:
-        true  - a window is shown on start of the command
-        false - the command window is hidden
-        nil   - the nCmdShown parameter of the commans's winmain function determins,
-                if a window is shown.
-        #default
-              - same as nil
+	true  - a window is shown on start of the command
+	false - the command window is hidden
+	nil   - the nCmdShown parameter of the commans's winmain function determins,
+		if a window is shown.
+	#default
+	      - same as nil
     "
 
     |dirPath handle|
 
     aDirectory notNil ifTrue:[
-        dirPath := aDirectory asFilename asAbsoluteFilename osNameForDirectory.
-        (dirPath endsWith:':') ifTrue:[
-            dirPath := dirPath , '\'.
-        ].
+	dirPath := aDirectory asFilename asAbsoluteFilename osNameForDirectory.
+	(dirPath endsWith:':') ifTrue:[
+	    dirPath := dirPath , '\'.
+	].
     ].
 
     handle := self
-        primExec:aCommandPath
-        commandLine:argString
-        environment:environment
-        fileDescriptors:fdArray
-        fork:doFork
-        newPgrp:newPgrp
-        inPath:dirPath
-        createFlags:nil
-        inheritHandles:true
-        showWindow:showWindowBooleanOrNil.
+	primExec:aCommandPath
+	commandLine:argString
+	environment:environment
+	fileDescriptors:fdArray
+	fork:doFork
+	newPgrp:newPgrp
+	inPath:dirPath
+	createFlags:nil
+	inheritHandles:true
+	showWindow:showWindowBooleanOrNil.
 
     handle notNil ifTrue:[
-        handle registerForFinalization.
+	handle registerForFinalization.
     ].
 
 "/ 'created ' print. cmdLine print. ' -> ' print. rslt printCR.
@@ -5872,15 +5876,15 @@
     OBJ data;
 
     if (__isByteArrayLike(aByteArray) && __isStringLike(which)) {
-        // be careful: fileInfo points into aByteArray! 
-        // Beware of garbage collection after VerQueryValue()!
-        // We use a fixed max size of 1000 bytes here.
-        data = __BYTEARRAY_UNINITIALIZED_NEW_INT(1000);
-        if (VerQueryValue(__byteArrayVal(aByteArray), __stringVal(which), (LPVOID) &fileInfo, &uLen) == FALSE) {
-            RETURN (nil);
-        }
-        memcpy(__byteArrayVal(data), fileInfo, min(1000, uLen));
-        RETURN (data);
+	// be careful: fileInfo points into aByteArray!
+	// Beware of garbage collection after VerQueryValue()!
+	// We use a fixed max size of 1000 bytes here.
+	data = __BYTEARRAY_UNINITIALIZED_NEW_INT(1000);
+	if (VerQueryValue(__byteArrayVal(aByteArray), __stringVal(which), (LPVOID) &fileInfo, &uLen) == FALSE) {
+	    RETURN (nil);
+	}
+	memcpy(__byteArrayVal(data), fileInfo, min(1000, uLen));
+	RETURN (data);
     }
 badArgument: ;
 %}.
@@ -5888,8 +5892,8 @@
 
     "
       100000 timesRepeat:[
-           OperatingSystem getFileInfos:#('ProductVersion' 'CompanyName' 'FileDescription' 'FileVersion' 'ProductName') 
-                           fromFile:'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
+	   OperatingSystem getFileInfos:#('ProductVersion' 'CompanyName' 'FileDescription' 'FileVersion' 'ProductName')
+			   fromFile:'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
       ].
     "
 
@@ -6195,7 +6199,7 @@
 
     bytes := self getFileVersionInfoOf:(filename asFilename osName).
     bytes isEmptyOrNil ifTrue:[
-        ^ Dictionary new.
+	^ Dictionary new.
     ].
 
     self extractVersionValue:'\' from:bytes.
@@ -6203,13 +6207,13 @@
     lang := vfi unsignedInt16At:1.
     codePage := vfi unsignedInt16At:3.
     stringFileInfoBase := '\StringFileInfo\%1%2\'
-                               bindWith:(lang hexPrintString:4)
-                               with:(codePage hexPrintString:4).
+			       bindWith:(lang hexPrintString:4)
+			       with:(codePage hexPrintString:4).
     ^ Dictionary withKeys:infoKeys valueBlock:[:eachKey|
-            |sfi|            
-            sfi := self extractVersionValue:(stringFileInfoBase, eachKey) from:bytes.
-            sfi zeroByteStringAt:1 maximumSize:999
-         ].
+	    |sfi|
+	    sfi := self extractVersionValue:(stringFileInfoBase, eachKey) from:bytes.
+	    sfi zeroByteStringAt:1 maximumSize:999
+	 ].
 
     "
      self getFileInfos:#('ProductVersion' 'CompanyName' 'FileDescription' 'FileVersion' 'ProductName') fromFile:'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
@@ -6359,30 +6363,30 @@
     //    GetSystemWow64DirectoryW(&fileTime);
     // can be called directly.
     {
-        typedef unsigned int (WINAPI *P_GetSystemWow64DirectoryW)(LPTSTR, unsigned int);
-        static P_GetSystemWow64DirectoryW pGetSystemWow64DirectoryW = NULL;
-        static int didCheck = 0;
-
-        if (pGetSystemWow64DirectoryW == NULL) {
-            if (!didCheck) {
-                pGetSystemWow64DirectoryW =
-                    (P_GetSystemWow64DirectoryW)
-                        GetProcAddress ( GetModuleHandle ("kernel32.dll"),
-                                         "GetSystemWow64DirectoryW");
-
-                didCheck = 1;
-            }
-        }
-
-        if (pGetSystemWow64DirectoryW != NULL) {
-            __rslt = (*pGetSystemWow64DirectoryW)(buffer, MAXPATHLEN);
-        }
+	typedef unsigned int (WINAPI *P_GetSystemWow64DirectoryW)(LPTSTR, unsigned int);
+	static P_GetSystemWow64DirectoryW pGetSystemWow64DirectoryW = NULL;
+	static int didCheck = 0;
+
+	if (pGetSystemWow64DirectoryW == NULL) {
+	    if (!didCheck) {
+		pGetSystemWow64DirectoryW =
+		    (P_GetSystemWow64DirectoryW)
+			GetProcAddress ( GetModuleHandle ("kernel32.dll"),
+					 "GetSystemWow64DirectoryW");
+
+		didCheck = 1;
+	    }
+	}
+
+	if (pGetSystemWow64DirectoryW != NULL) {
+	    __rslt = (*pGetSystemWow64DirectoryW)(buffer, MAXPATHLEN);
+	}
     }
 #else
     __rslt = GetSystemWow64DirectoryW(buffer, MAXPATHLEN);
 #endif
     if (__rslt != 0) {
-        rslt = __mkStringOrU16String_maxlen(buffer, MAXPATHLEN);
+	rslt = __mkStringOrU16String_maxlen(buffer, MAXPATHLEN);
     }
 %}.
     ^ rslt
@@ -7769,20 +7773,20 @@
 
 %{
     if (__isExternalAddressLike(processHandleOrPid) ) {
-        HANDLE hProcess = _HANDLEVal(processHandleOrPid);
-
-        if (hProcess != 0) {
-            TerminateProcess( hProcess, __intVal(exitCode) );
-        }
-        RETURN( self );
+	HANDLE hProcess = _HANDLEVal(processHandleOrPid);
+
+	if (hProcess != 0) {
+	    TerminateProcess( hProcess, __intVal(exitCode) );
+	}
+	RETURN( self );
     } else if( __isSmallInteger(processHandleOrPid) ) {
-        HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0, __smallIntegerVal(processHandleOrPid));
-
-        if( hProcess != 0 ) {
-            TerminateProcess( hProcess, __intVal(exitCode) );
-            CloseHandle(hProcess);
-        }
-        RETURN( self );
+	HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0, __smallIntegerVal(processHandleOrPid));
+
+	if( hProcess != 0 ) {
+	    TerminateProcess( hProcess, __intVal(exitCode) );
+	    CloseHandle(hProcess);
+	}
+	RETURN( self );
     }
 %}.
     self primitiveFailed:#invalidParameter.
@@ -8030,12 +8034,12 @@
     HANDLE __pid;
 
     if (!__isExternalAddressLike(pid) || (__pid = _HANDLEVal(pid)) == 0) {
-        RETURN(self);
-    }    
+	RETURN(self);
+    }
 
 #ifdef PROCESSDEBUGWIN32
     if (flag_PROCESSDEBUGWIN32) {
-        console_printf("Close ProcessHandle %x\n", __pid);
+	console_printf("Close ProcessHandle %x\n", __pid);
     }
 #endif
     CloseHandle(__pid);
@@ -9376,6 +9380,50 @@
     "
 !
 
+xx_getAllProcessIds
+    "not needed - use getAllProcesses.
+     returns a collection of processID,
+     of all processes in the system"
+
+%{
+#if 0
+    OBJ pidArray;
+    DWORD *processes;
+    DWORD cbNeeded, nProcesses;
+    int i, moreNeeded = 1;
+    // Get the list of process identifiers.
+    int nProcSpace = 512;
+
+    while (moreNeeded) {
+	processes = (DWORD*)malloc(nProcSpace*sizeof(DWORD));
+	if (! EnumProcesses( processes, (nProcSpace*sizeof(DWORD)), &cbNeeded ) ) {
+	    goto failed;
+	}
+	moreNeeded = (cbNeeded == (nProcSpace*sizeof(DWORD)));
+	if (moreNeeded) {
+	    // returned exactly the size I gave it; maybe there are more
+	    nProcSpace *= 2;
+	    free (processes);
+	}
+    }
+    // Calculate how many process identifiers were returned.
+    nProcesses = cbNeeded / sizeof(DWORD);
+    pidArray = __ARRAY_NEW_INT(nProcesses);
+    if (pidArray != nil) {
+	for (i=0; i<nProcesses; i++) {
+	    __ArrayInstPtr(pidArray)->a_element[i] = __mkSmallInteger(processes[i]);
+	}
+	RETURN ( pidArray );
+    }
+failed: ;
+#endif
+%}.
+    self primitiveFailed.
+!
+
+    "
+     OperatingSystem getProcessId
+    "
 getSystemID
     "if supported by the OS, return the systemID;
      a unique per machine identification.
@@ -10495,22 +10543,22 @@
 #define DM_OUT_DEFAULT      DM_UPDATE
 "
     nBytesNeeded := self
-           primDocumentProperties:nil
-           hPrinter:hPrinter
-           pDeviceName: deviceName
-           pDevModeOutput:nil
-           pDevModeInput:nil
-           fMode:0.
+	   primDocumentProperties:nil
+	   hPrinter:hPrinter
+	   pDeviceName: deviceName
+	   pDevModeOutput:nil
+	   pDevModeInput:nil
+	   fMode:0.
 
     devModeOutput := DevModeStructure new:(nBytesNeeded * 2 "never trust MS !!").
 
     rslt := self
-           primDocumentProperties:nil
-           hPrinter:hPrinter
-           pDeviceName: deviceName
-           pDevModeOutput:devModeOutput
-           pDevModeInput:pDevModeInputOrNil
-           fMode:4+2.
+	   primDocumentProperties:nil
+	   hPrinter:hPrinter
+	   pDeviceName: deviceName
+	   pDevModeOutput:devModeOutput
+	   pDevModeInput:pDevModeInputOrNil
+	   fMode:4+2.
 
     ^ devModeOutput
 
@@ -12283,33 +12331,33 @@
     char *name = (char *)0;
 
     if (firstCall) {
-        DWORD nameSize = sizeof(cachedName);
-
-        if (GetUserName(cachedName, &nameSize) == TRUE) {
-            name = cachedName;
-            firstCall = 0;
-        }
+	DWORD nameSize = sizeof(cachedName);
+
+	if (GetUserName(cachedName, &nameSize) == TRUE) {
+	    name = cachedName;
+	    firstCall = 0;
+	}
     } else {
-        name = cachedName;
+	name = cachedName;
     }
 
     /*
      * try a few common environment variables ...
      */
     if (! name || (name[0] == 0) ) {
-        name = getenv("LOGIN");
-        if (! name || (name[0] == 0) ) {
-            name = getenv("LOGNAME");
-            if (! name || (name[0] == 0) ) {
-                name = getenv("USER");
-            }
-        }
+	name = getenv("LOGIN");
+	if (! name || (name[0] == 0) ) {
+	    name = getenv("LOGNAME");
+	    if (! name || (name[0] == 0) ) {
+		name = getenv("USER");
+	    }
+	}
     }
     /*
      * nope - I really font know who you are.
      */
     if (! name || (name[0] == 0) ) {
-        name = "you";
+	name = "you";
     }
 
     RETURN ( __MKSTRING(name) );
@@ -14746,21 +14794,21 @@
     |index objectArray object debugBlock|
 
     debugBlock := [:obj|
-                      ^ 'obj:', obj , ' this:', self printString , ' idx:', self indexedName
-                  ].
+		      ^ 'obj:', obj , ' this:', self printString , ' idx:', self indexedName
+		  ].
 
     objectArray := self data objectArray.
     index := self indexedNameNumbered.
 
     index == 0 ifTrue:[
-        object := objectArray at:1 ifAbsent:[debugBlock value:(object at:#ObjectNameTitle)].
+	object := objectArray at:1 ifAbsent:[debugBlock value:(object at:#ObjectNameTitle)].
     ] ifFalse:[
-        object := objectArray detect:[:el| (el at:#ObjectNameTitleIndex) == index] 
-                              ifNone:[self error:'counter not found'].
-    ].
-
-    ^ (object at:#Counters) 
-         collect:[:el| {el at:#CounterNameTitle. el at:#CounterNameTitleIndex}].
+	object := objectArray detect:[:el| (el at:#ObjectNameTitleIndex) == index]
+			      ifNone:[self error:'counter not found'].
+    ].
+
+    ^ (object at:#Counters)
+	 collect:[:el| {el at:#CounterNameTitle. el at:#CounterNameTitleIndex}].
 
     "Modified: / 07-03-2019 / 16:29:51 / Stefan Vogel"
 ! !