diff options
Diffstat (limited to 'PC')
-rw-r--r-- | PC/VS7.1/make_buildinfo.c | 126 | ||||
-rw-r--r-- | PC/VS8.0/make_buildinfo.c | 128 | ||||
-rw-r--r-- | PC/_msi.c | 752 | ||||
-rw-r--r-- | PC/_subprocess.c | 748 | ||||
-rw-r--r-- | PC/_winreg.c | 2144 | ||||
-rw-r--r-- | PC/bdist_wininst/archive.h | 94 | ||||
-rw-r--r-- | PC/bdist_wininst/extract.c | 534 | ||||
-rw-r--r-- | PC/bdist_wininst/install.c | 4160 | ||||
-rw-r--r-- | PC/config.c | 144 | ||||
-rw-r--r-- | PC/dl_nt.c | 90 | ||||
-rw-r--r-- | PC/errmap.h | 148 | ||||
-rw-r--r-- | PC/frozen_dllmain.c | 116 | ||||
-rw-r--r-- | PC/generrmap.c | 24 | ||||
-rw-r--r-- | PC/getpathp.c | 952 | ||||
-rw-r--r-- | PC/import_nt.c | 122 | ||||
-rw-r--r-- | PC/make_versioninfo.c | 26 | ||||
-rwxr-xr-x | PC/msvcrtmodule.c | 358 | ||||
-rw-r--r-- | PC/os2emx/config.c | 130 | ||||
-rw-r--r-- | PC/os2emx/dlfcn.c | 286 | ||||
-rw-r--r-- | PC/os2emx/dllentry.c | 44 | ||||
-rw-r--r-- | PC/os2emx/getpathp.c | 480 | ||||
-rw-r--r-- | PC/os2emx/pythonpm.c | 144 | ||||
-rw-r--r-- | PC/os2vacpp/getpathp.c | 636 | ||||
-rw-r--r-- | PC/winsound.c | 122 |
24 files changed, 6254 insertions, 6254 deletions
diff --git a/PC/VS7.1/make_buildinfo.c b/PC/VS7.1/make_buildinfo.c index 27580bb..2aa2b66 100644 --- a/PC/VS7.1/make_buildinfo.c +++ b/PC/VS7.1/make_buildinfo.c @@ -21,72 +21,72 @@ int make_buildinfo2() { - struct _stat st; - HKEY hTortoise; - char command[500]; - DWORD type, size; - if (_stat(".svn", &st) < 0) - return 0; - /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ - if (_stat("no_subwcrev", &st) == 0) - return 0; - if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && - RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) - /* Tortoise not installed */ - return 0; - command[0] = '"'; /* quote the path to the executable */ - size = sizeof(command) - 1; - if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || - type != REG_SZ) - /* Registry corrupted */ - return 0; - strcat(command, "bin\\subwcrev.exe"); - if (_stat(command+1, &st) < 0) - /* subwcrev.exe not part of the release */ - return 0; - strcat(command, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); - puts(command); fflush(stdout); - if (system(command) < 0) - return 0; - return 1; + struct _stat st; + HKEY hTortoise; + char command[500]; + DWORD type, size; + if (_stat(".svn", &st) < 0) + return 0; + /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ + if (_stat("no_subwcrev", &st) == 0) + return 0; + if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && + RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) + /* Tortoise not installed */ + return 0; + command[0] = '"'; /* quote the path to the executable */ + size = sizeof(command) - 1; + if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || + type != REG_SZ) + /* Registry corrupted */ + return 0; + strcat(command, "bin\\subwcrev.exe"); + if (_stat(command+1, &st) < 0) + /* subwcrev.exe not part of the release */ + return 0; + strcat(command, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); + puts(command); fflush(stdout); + if (system(command) < 0) + return 0; + return 1; } int main(int argc, char*argv[]) { - char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; - int do_unlink, result; - if (argc != 2) { - fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); - return EXIT_FAILURE; - } - if (strcmp(argv[1], "Release") == 0) { - strcat(command, "-MD "); - } - else if (strcmp(argv[1], "Debug") == 0) { - strcat(command, "-D_DEBUG -MDd "); - } - else if (strcmp(argv[1], "ReleaseItanium") == 0) { - strcat(command, "-MD /USECL:MS_ITANIUM "); - } - else if (strcmp(argv[1], "ReleaseAMD64") == 0) { - strcat(command, "-MD "); - strcat(command, "-MD /USECL:MS_OPTERON "); - } - else { - fprintf(stderr, "unsupported configuration %s\n", argv[1]); - return EXIT_FAILURE; - } + char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; + int do_unlink, result; + if (argc != 2) { + fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); + return EXIT_FAILURE; + } + if (strcmp(argv[1], "Release") == 0) { + strcat(command, "-MD "); + } + else if (strcmp(argv[1], "Debug") == 0) { + strcat(command, "-D_DEBUG -MDd "); + } + else if (strcmp(argv[1], "ReleaseItanium") == 0) { + strcat(command, "-MD /USECL:MS_ITANIUM "); + } + else if (strcmp(argv[1], "ReleaseAMD64") == 0) { + strcat(command, "-MD "); + strcat(command, "-MD /USECL:MS_OPTERON "); + } + else { + fprintf(stderr, "unsupported configuration %s\n", argv[1]); + return EXIT_FAILURE; + } - if ((do_unlink = make_buildinfo2())) - strcat(command, "getbuildinfo2.c -DSUBWCREV "); - else - strcat(command, "..\\..\\Modules\\getbuildinfo.c"); - strcat(command, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); - puts(command); fflush(stdout); - result = system(command); - if (do_unlink) - unlink("getbuildinfo2.c"); - if (result < 0) - return EXIT_FAILURE; - return 0; + if ((do_unlink = make_buildinfo2())) + strcat(command, "getbuildinfo2.c -DSUBWCREV "); + else + strcat(command, "..\\..\\Modules\\getbuildinfo.c"); + strcat(command, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); + puts(command); fflush(stdout); + result = system(command); + if (do_unlink) + unlink("getbuildinfo2.c"); + if (result < 0) + return EXIT_FAILURE; + return 0; } diff --git a/PC/VS8.0/make_buildinfo.c b/PC/VS8.0/make_buildinfo.c index 133cfee..8cc3da2 100644 --- a/PC/VS8.0/make_buildinfo.c +++ b/PC/VS8.0/make_buildinfo.c @@ -23,72 +23,72 @@ int make_buildinfo2() { - struct _stat st; - HKEY hTortoise; - char command[CMD_SIZE+1]; - DWORD type, size; - if (_stat(".svn", &st) < 0) - return 0; - /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ - if (_stat("no_subwcrev", &st) == 0) - return 0; - if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && - RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) - /* Tortoise not installed */ - return 0; - command[0] = '"'; /* quote the path to the executable */ - size = sizeof(command) - 1; - if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || - type != REG_SZ) - /* Registry corrupted */ - return 0; - strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); - if (_stat(command+1, &st) < 0) - /* subwcrev.exe not part of the release */ - return 0; - strcat_s(command, CMD_SIZE, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); - puts(command); fflush(stdout); - if (system(command) < 0) - return 0; - return 1; + struct _stat st; + HKEY hTortoise; + char command[CMD_SIZE+1]; + DWORD type, size; + if (_stat(".svn", &st) < 0) + return 0; + /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */ + if (_stat("no_subwcrev", &st) == 0) + return 0; + if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS && + RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS) + /* Tortoise not installed */ + return 0; + command[0] = '"'; /* quote the path to the executable */ + size = sizeof(command) - 1; + if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS || + type != REG_SZ) + /* Registry corrupted */ + return 0; + strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe"); + if (_stat(command+1, &st) < 0) + /* subwcrev.exe not part of the release */ + return 0; + strcat_s(command, CMD_SIZE, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c"); + puts(command); fflush(stdout); + if (system(command) < 0) + return 0; + return 1; } int main(int argc, char*argv[]) { - char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; - int do_unlink, result; - if (argc != 2) { - fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); - return EXIT_FAILURE; - } - if (strcmp(argv[1], "Release") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - } - else if (strcmp(argv[1], "Debug") == 0) { - strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); - } - else if (strcmp(argv[1], "ReleaseItanium") == 0) { - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); - } - else if (strcmp(argv[1], "ReleaseAMD64") == 0) { - strcat_s(command, CMD_SIZE, "-MD "); - strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); - } - else { - fprintf(stderr, "unsupported configuration %s\n", argv[1]); - return EXIT_FAILURE; - } + char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL "; + int do_unlink, result; + if (argc != 2) { + fprintf(stderr, "make_buildinfo $(ConfigurationName)\n"); + return EXIT_FAILURE; + } + if (strcmp(argv[1], "Release") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + } + else if (strcmp(argv[1], "Debug") == 0) { + strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd "); + } + else if (strcmp(argv[1], "ReleaseItanium") == 0) { + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM "); + } + else if (strcmp(argv[1], "ReleaseAMD64") == 0) { + strcat_s(command, CMD_SIZE, "-MD "); + strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON "); + } + else { + fprintf(stderr, "unsupported configuration %s\n", argv[1]); + return EXIT_FAILURE; + } - if ((do_unlink = make_buildinfo2())) - strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); - else - strcat_s(command, CMD_SIZE, "..\\..\\Modules\\getbuildinfo.c"); - strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); - puts(command); fflush(stdout); - result = system(command); - if (do_unlink) - _unlink("getbuildinfo2.c"); - if (result < 0) - return EXIT_FAILURE; - return 0; -}
\ No newline at end of file + if ((do_unlink = make_buildinfo2())) + strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV "); + else + strcat_s(command, CMD_SIZE, "..\\..\\Modules\\getbuildinfo.c"); + strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC"); + puts(command); fflush(stdout); + result = system(command); + if (do_unlink) + _unlink("getbuildinfo2.c"); + if (result < 0) + return EXIT_FAILURE; + return 0; +} @@ -20,19 +20,19 @@ uuidcreate(PyObject* obj, PyObject*args) UUID result; char *cresult; PyObject *oresult; - + /* May return ok, local only, and no address. For local only, the documentation says we still get a uuid. For RPC_S_UUID_NO_ADDRESS, it's not clear whether we can use the result. */ if (UuidCreate(&result) == RPC_S_UUID_NO_ADDRESS) { - PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result"); - return NULL; + PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result"); + return NULL; } if (UuidToString(&result, &cresult) == RPC_S_OUT_OF_MEMORY) { - PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen"); - return NULL; + PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen"); + return NULL; } oresult = PyString_FromString(cresult); @@ -57,7 +57,7 @@ static FNFCIOPEN(cb_open) { int result = _open(pszFile, oflag, pmode); if (result == -1) - *err = errno; + *err = errno; return result; } @@ -65,7 +65,7 @@ static FNFCIREAD(cb_read) { UINT result = (UINT)_read(hf, memory, cb); if (result != cb) - *err = errno; + *err = errno; return result; } @@ -73,7 +73,7 @@ static FNFCIWRITE(cb_write) { UINT result = (UINT)_write(hf, memory, cb); if (result != cb) - *err = errno; + *err = errno; return result; } @@ -81,7 +81,7 @@ static FNFCICLOSE(cb_close) { int result = _close(hf); if (result != 0) - *err = errno; + *err = errno; return result; } @@ -89,7 +89,7 @@ static FNFCISEEK(cb_seek) { long result = (long)_lseek(hf, dist, seektype); if (result == -1) - *err = errno; + *err = errno; return result; } @@ -97,7 +97,7 @@ static FNFCIDELETE(cb_delete) { int result = remove(pszFile); if (result != 0) - *err = errno; + *err = errno; return result; } @@ -110,9 +110,9 @@ static FNFCIGETTEMPFILE(cb_gettempfile) { char *name = _tempnam("", "tmp"); if ((name != NULL) && ((int)strlen(name) < cbTempName)) { - strcpy(pszTempName, name); - free(name); - return TRUE; + strcpy(pszTempName, name); + free(name); + return TRUE; } if (name) free(name); @@ -122,10 +122,10 @@ static FNFCIGETTEMPFILE(cb_gettempfile) static FNFCISTATUS(cb_status) { if (pv) { - PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2); - if (result == NULL) - return -1; - Py_DECREF(result); + PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2); + if (result == NULL) + return -1; + Py_DECREF(result); } return 0; } @@ -133,18 +133,18 @@ static FNFCISTATUS(cb_status) static FNFCIGETNEXTCABINET(cb_getnextcabinet) { if (pv) { - PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab); - if (result == NULL) - return -1; - if (!PyString_Check(result)) { - PyErr_Format(PyExc_TypeError, - "Incorrect return type %s from getnextcabinet", - result->ob_type->tp_name); - Py_DECREF(result); - return FALSE; - } - strncpy(pccab->szCab, PyString_AsString(result), sizeof(pccab->szCab)); - return TRUE; + PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab); + if (result == NULL) + return -1; + if (!PyString_Check(result)) { + PyErr_Format(PyExc_TypeError, + "Incorrect return type %s from getnextcabinet", + result->ob_type->tp_name); + Py_DECREF(result); + return FALSE; + } + strncpy(pccab->szCab, PyString_AsString(result), sizeof(pccab->szCab)); + return TRUE; } return FALSE; } @@ -157,21 +157,21 @@ static FNFCIGETOPENINFO(cb_getopeninfo) /* Need Win32 handle to get time stamps */ handle = CreateFile(pszName, GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (handle == INVALID_HANDLE_VALUE) - return -1; + return -1; if (GetFileInformationByHandle(handle, &bhfi) == FALSE) { - CloseHandle(handle); - return -1; + CloseHandle(handle); + return -1; } FileTimeToLocalFileTime(&bhfi.ftLastWriteTime, &filetime); FileTimeToDosDateTime(&filetime, pdate, ptime); - *pattribs = (int)(bhfi.dwFileAttributes & - (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH)); + *pattribs = (int)(bhfi.dwFileAttributes & + (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH)); CloseHandle(handle); @@ -189,11 +189,11 @@ static PyObject* fcicreate(PyObject* obj, PyObject* args) if (!PyArg_ParseTuple(args, "sO:FCICreate", &cabname, &files)) - return NULL; + return NULL; if (!PyList_Check(files)) { - PyErr_SetString(PyExc_TypeError, "FCICreate expects a list"); - return NULL; + PyErr_SetString(PyExc_TypeError, "FCICreate expects a list"); + return NULL; } ccab.cb = INT_MAX; /* no need to split CAB into multiple media */ @@ -209,49 +209,49 @@ static PyObject* fcicreate(PyObject* obj, PyObject* args) ccab.szDisk[0] = '\0'; for (i = 0, p = cabname; *p; p = CharNext(p)) - if (*p == '\\' || *p == '/') - i = p - cabname + 1; + if (*p == '\\' || *p == '/') + i = p - cabname + 1; if (i >= sizeof(ccab.szCabPath) || - strlen(cabname+i) >= sizeof(ccab.szCab)) { - PyErr_SetString(PyExc_ValueError, "path name too long"); - return 0; + strlen(cabname+i) >= sizeof(ccab.szCab)) { + PyErr_SetString(PyExc_ValueError, "path name too long"); + return 0; } if (i > 0) { - memcpy(ccab.szCabPath, cabname, i); - ccab.szCabPath[i] = '\0'; - strcpy(ccab.szCab, cabname+i); + memcpy(ccab.szCabPath, cabname, i); + ccab.szCabPath[i] = '\0'; + strcpy(ccab.szCab, cabname+i); } else { - strcpy(ccab.szCabPath, ".\\"); - strcpy(ccab.szCab, cabname); + strcpy(ccab.szCabPath, ".\\"); + strcpy(ccab.szCab, cabname); } hfci = FCICreate(&erf, cb_fileplaced, cb_alloc, cb_free, - cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete, - cb_gettempfile, &ccab, NULL); + cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete, + cb_gettempfile, &ccab, NULL); if (hfci == NULL) { - PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper); - return NULL; + PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper); + return NULL; } for (i=0; i < PyList_GET_SIZE(files); i++) { - PyObject *item = PyList_GET_ITEM(files, i); - char *filename, *cabname; - if (!PyArg_ParseTuple(item, "ss", &filename, &cabname)) - goto err; - if (!FCIAddFile(hfci, filename, cabname, FALSE, - cb_getnextcabinet, cb_status, cb_getopeninfo, - tcompTYPE_MSZIP)) - goto err; + PyObject *item = PyList_GET_ITEM(files, i); + char *filename, *cabname; + if (!PyArg_ParseTuple(item, "ss", &filename, &cabname)) + goto err; + if (!FCIAddFile(hfci, filename, cabname, FALSE, + cb_getnextcabinet, cb_status, cb_getopeninfo, + tcompTYPE_MSZIP)) + goto err; } if (!FCIFlushCabinet(hfci, FALSE, cb_getnextcabinet, cb_status)) - goto err; + goto err; if (!FCIDestroy(hfci)) - goto err; + goto err; Py_INCREF(Py_None); return Py_None; @@ -266,7 +266,7 @@ typedef struct msiobj{ MSIHANDLE h; }msiobj; -static void +static void msiobj_dealloc(msiobj* msidb) { MsiCloseHandle(msidb->h); @@ -292,41 +292,41 @@ msierror(int status) MSIHANDLE err = MsiGetLastErrorRecord(); if (err == 0) { - switch(status) { - case ERROR_ACCESS_DENIED: - PyErr_SetString(MSIError, "access denied"); - return NULL; - case ERROR_FUNCTION_FAILED: - PyErr_SetString(MSIError, "function failed"); - return NULL; - case ERROR_INVALID_DATA: - PyErr_SetString(MSIError, "invalid data"); - return NULL; - case ERROR_INVALID_HANDLE: - PyErr_SetString(MSIError, "invalid handle"); - return NULL; - case ERROR_INVALID_STATE: - PyErr_SetString(MSIError, "invalid state"); - return NULL; - case ERROR_INVALID_PARAMETER: - PyErr_SetString(MSIError, "invalid parameter"); - return NULL; - default: - PyErr_Format(MSIError, "unknown error %x", status); - return NULL; - } + switch(status) { + case ERROR_ACCESS_DENIED: + PyErr_SetString(MSIError, "access denied"); + return NULL; + case ERROR_FUNCTION_FAILED: + PyErr_SetString(MSIError, "function failed"); + return NULL; + case ERROR_INVALID_DATA: + PyErr_SetString(MSIError, "invalid data"); + return NULL; + case ERROR_INVALID_HANDLE: + PyErr_SetString(MSIError, "invalid handle"); + return NULL; + case ERROR_INVALID_STATE: + PyErr_SetString(MSIError, "invalid state"); + return NULL; + case ERROR_INVALID_PARAMETER: + PyErr_SetString(MSIError, "invalid parameter"); + return NULL; + default: + PyErr_Format(MSIError, "unknown error %x", status); + return NULL; + } } code = MsiRecordGetInteger(err, 1); /* XXX code */ if (MsiFormatRecord(0, err, res, &size) == ERROR_MORE_DATA) { - res = malloc(size+1); - MsiFormatRecord(0, err, res, &size); - res[size]='\0'; + res = malloc(size+1); + MsiFormatRecord(0, err, res, &size); + res[size]='\0'; } MsiCloseHandle(err); PyErr_SetString(MSIError, res); if (res != buf) - free(res); + free(res); return NULL; } @@ -343,13 +343,13 @@ record_getinteger(msiobj* record, PyObject* args) { unsigned int field; int status; - + if (!PyArg_ParseTuple(args, "I:GetInteger", &field)) - return NULL; + return NULL; status = MsiRecordGetInteger(record->h, field); if (status == MSI_NULL_INTEGER){ - PyErr_SetString(MSIError, "could not convert record field to integer"); - return NULL; + PyErr_SetString(MSIError, "could not convert record field to integer"); + return NULL; } return PyInt_FromLong((long) status); } @@ -363,21 +363,21 @@ record_getstring(msiobj* record, PyObject* args) char *res = buf; DWORD size = sizeof(buf); PyObject* string; - + if (!PyArg_ParseTuple(args, "I:GetString", &field)) - return NULL; + return NULL; status = MsiRecordGetString(record->h, field, res, &size); if (status == ERROR_MORE_DATA) { - res = (char*) malloc(size + 1); - if (res == NULL) - return PyErr_NoMemory(); - status = MsiRecordGetString(record->h, field, res, &size); + res = (char*) malloc(size + 1); + if (res == NULL) + return PyErr_NoMemory(); + status = MsiRecordGetString(record->h, field, res, &size); } if (status != ERROR_SUCCESS) - return msierror((int) status); + return msierror((int) status); string = PyString_FromString(res); if (buf != res) - free(res); + free(res); return string; } @@ -386,7 +386,7 @@ record_cleardata(msiobj* record, PyObject *args) { int status = MsiRecordClearData(record->h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -400,10 +400,10 @@ record_setstring(msiobj* record, PyObject *args) char *data; if (!PyArg_ParseTuple(args, "is:SetString", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetString(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -417,10 +417,10 @@ record_setstream(msiobj* record, PyObject *args) char *data; if (!PyArg_ParseTuple(args, "is:SetStream", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetStream(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -434,10 +434,10 @@ record_setinteger(msiobj* record, PyObject *args) int data; if (!PyArg_ParseTuple(args, "ii:SetInteger", &field, &data)) - return NULL; + return NULL; if ((status = MsiRecordSetInteger(record->h, field, data)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -446,65 +446,65 @@ record_setinteger(msiobj* record, PyObject *args) static PyMethodDef record_methods[] = { - { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS, - PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")}, + { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS, + PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")}, { "GetInteger", (PyCFunction)record_getinteger, METH_VARARGS, PyDoc_STR("GetInteger(field) -> int\nWraps MsiRecordGetInteger")}, { "GetString", (PyCFunction)record_getstring, METH_VARARGS, PyDoc_STR("GetString(field) -> string\nWraps MsiRecordGetString")}, - { "SetString", (PyCFunction)record_setstring, METH_VARARGS, - PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")}, - { "SetStream", (PyCFunction)record_setstream, METH_VARARGS, - PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")}, - { "SetInteger", (PyCFunction)record_setinteger, METH_VARARGS, - PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")}, - { "ClearData", (PyCFunction)record_cleardata, METH_NOARGS, - PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")}, + { "SetString", (PyCFunction)record_setstring, METH_VARARGS, + PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")}, + { "SetStream", (PyCFunction)record_setstream, METH_VARARGS, + PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")}, + { "SetInteger", (PyCFunction)record_setinteger, METH_VARARGS, + PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")}, + { "ClearData", (PyCFunction)record_cleardata, METH_NOARGS, + PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")}, { NULL, NULL } }; static PyTypeObject record_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.Record", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - record_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.Record", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + record_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; static PyObject* @@ -513,8 +513,8 @@ record_new(MSIHANDLE h) msiobj *result = PyObject_NEW(struct msiobj, &record_Type); if (!result) { - MsiCloseHandle(h); - return NULL; + MsiCloseHandle(h); + return NULL; } result->h = h; @@ -537,27 +537,27 @@ summary_getproperty(msiobj* si, PyObject *args) DWORD ssize = sizeof(sval); if (!PyArg_ParseTuple(args, "i:GetProperty", &field)) - return NULL; + return NULL; - status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, - &fval, sval, &ssize); + status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, + &fval, sval, &ssize); if (status == ERROR_MORE_DATA) { - sval = malloc(ssize); - status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, - &fval, sval, &ssize); + sval = malloc(ssize); + status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival, + &fval, sval, &ssize); } switch(type) { - case VT_I2: case VT_I4: - return PyInt_FromLong(ival); - case VT_FILETIME: - PyErr_SetString(PyExc_NotImplementedError, "FILETIME result"); - return NULL; - case VT_LPSTR: - result = PyString_FromStringAndSize(sval, ssize); - if (sval != sbuf) - free(sval); - return result; + case VT_I2: case VT_I4: + return PyInt_FromLong(ival); + case VT_FILETIME: + PyErr_SetString(PyExc_NotImplementedError, "FILETIME result"); + return NULL; + case VT_LPSTR: + result = PyString_FromStringAndSize(sval, ssize); + if (sval != sbuf) + free(sval); + return result; } PyErr_Format(PyExc_NotImplementedError, "result of type %d", type); return NULL; @@ -571,7 +571,7 @@ summary_getpropertycount(msiobj* si, PyObject *args) status = MsiSummaryInfoGetPropertyCount(si->h, &result); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return PyInt_FromLong(result); } @@ -584,21 +584,21 @@ summary_setproperty(msiobj* si, PyObject *args) PyObject* data; if (!PyArg_ParseTuple(args, "iO:SetProperty", &field, &data)) - return NULL; + return NULL; if (PyString_Check(data)) { - status = MsiSummaryInfoSetProperty(si->h, field, VT_LPSTR, - 0, NULL, PyString_AsString(data)); + status = MsiSummaryInfoSetProperty(si->h, field, VT_LPSTR, + 0, NULL, PyString_AsString(data)); } else if (PyInt_Check(data)) { - status = MsiSummaryInfoSetProperty(si->h, field, VT_I4, - PyInt_AsLong(data), NULL, NULL); + status = MsiSummaryInfoSetProperty(si->h, field, VT_I4, + PyInt_AsLong(data), NULL, NULL); } else { - PyErr_SetString(PyExc_TypeError, "unsupported type"); - return NULL; + PyErr_SetString(PyExc_TypeError, "unsupported type"); + return NULL; } - + if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -612,65 +612,65 @@ summary_persist(msiobj* si, PyObject *args) status = MsiSummaryInfoPersist(si->h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; } static PyMethodDef summary_methods[] = { - { "GetProperty", (PyCFunction)summary_getproperty, METH_VARARGS, - PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")}, - { "GetPropertyCount", (PyCFunction)summary_getpropertycount, METH_NOARGS, - PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")}, - { "SetProperty", (PyCFunction)summary_setproperty, METH_VARARGS, - PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")}, - { "Persist", (PyCFunction)summary_persist, METH_NOARGS, - PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")}, + { "GetProperty", (PyCFunction)summary_getproperty, METH_VARARGS, + PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")}, + { "GetPropertyCount", (PyCFunction)summary_getpropertycount, METH_NOARGS, + PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")}, + { "SetProperty", (PyCFunction)summary_setproperty, METH_VARARGS, + PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")}, + { "Persist", (PyCFunction)summary_persist, METH_NOARGS, + PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")}, { NULL, NULL } }; static PyTypeObject summary_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.SummaryInformation", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - summary_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.SummaryInformation", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + summary_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /*************************** View objects **************/ @@ -683,19 +683,19 @@ view_execute(msiobj *view, PyObject*args) PyObject *oparams = Py_None; if (!PyArg_ParseTuple(args, "O:Execute", &oparams)) - return NULL; + return NULL; if (oparams != Py_None) { - if (oparams->ob_type != &record_Type) { - PyErr_SetString(PyExc_TypeError, "Execute argument must be a record"); - return NULL; - } - params = ((msiobj*)oparams)->h; + if (oparams->ob_type != &record_Type) { + PyErr_SetString(PyExc_TypeError, "Execute argument must be a record"); + return NULL; + } + params = ((msiobj*)oparams)->h; } status = MsiViewExecute(view->h, params); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -708,7 +708,7 @@ view_fetch(msiobj *view, PyObject*args) MSIHANDLE result; if ((status = MsiViewFetch(view->h, &result)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return record_new(result); } @@ -721,10 +721,10 @@ view_getcolumninfo(msiobj *view, PyObject *args) MSIHANDLE result; if (!PyArg_ParseTuple(args, "i:GetColumnInfo", &kind)) - return NULL; + return NULL; if ((status = MsiViewGetColumnInfo(view->h, kind, &result)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); return record_new(result); } @@ -737,15 +737,15 @@ view_modify(msiobj *view, PyObject *args) int status; if (!PyArg_ParseTuple(args, "iO:Modify", &kind, &data)) - return NULL; + return NULL; if (data->ob_type != &record_Type) { - PyErr_SetString(PyExc_TypeError, "Modify expects a record object"); - return NULL; + PyErr_SetString(PyExc_TypeError, "Modify expects a record object"); + return NULL; } if ((status = MsiViewModify(view->h, kind, ((msiobj*)data)->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -757,68 +757,68 @@ view_close(msiobj *view, PyObject*args) int status; if ((status = MsiViewClose(view->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; } static PyMethodDef view_methods[] = { - { "Execute", (PyCFunction)view_execute, METH_VARARGS, - PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")}, + { "Execute", (PyCFunction)view_execute, METH_VARARGS, + PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")}, { "GetColumnInfo", (PyCFunction)view_getcolumninfo, METH_VARARGS, - PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")}, + PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")}, { "Fetch", (PyCFunction)view_fetch, METH_NOARGS, - PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")}, + PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")}, { "Modify", (PyCFunction)view_modify, METH_VARARGS, - PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")}, + PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")}, { "Close", (PyCFunction)view_close, METH_NOARGS, - PyDoc_STR("Close() -> result\nWraps MsiViewClose")}, + PyDoc_STR("Close() -> result\nWraps MsiViewClose")}, { NULL, NULL } }; static PyTypeObject msiview_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.View", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - view_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.View", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + view_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; /*************************** Database objects **************/ @@ -832,15 +832,15 @@ msidb_openview(msiobj *msidb, PyObject *args) msiobj *result; if (!PyArg_ParseTuple(args, "s:OpenView", &sql)) - return NULL; + return NULL; if ((status = MsiDatabaseOpenView(msidb->h, sql, &hView)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); result = PyObject_NEW(struct msiobj, &msiview_Type); if (!result) { - MsiCloseHandle(hView); - return NULL; + MsiCloseHandle(hView); + return NULL; } result->h = hView; @@ -853,7 +853,7 @@ msidb_commit(msiobj *msidb, PyObject *args) int status; if ((status = MsiDatabaseCommit(msidb->h)) != ERROR_SUCCESS) - return msierror(status); + return msierror(status); Py_INCREF(Py_None); return Py_None; @@ -868,16 +868,16 @@ msidb_getsummaryinformation(msiobj *db, PyObject *args) msiobj *oresult; if (!PyArg_ParseTuple(args, "i:GetSummaryInformation", &count)) - return NULL; + return NULL; status = MsiGetSummaryInformation(db->h, NULL, count, &result); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); oresult = PyObject_NEW(struct msiobj, &summary_Type); if (!result) { - MsiCloseHandle(result); - return NULL; + MsiCloseHandle(result); + return NULL; } oresult->h = result; @@ -885,57 +885,57 @@ msidb_getsummaryinformation(msiobj *db, PyObject *args) } static PyMethodDef db_methods[] = { - { "OpenView", (PyCFunction)msidb_openview, METH_VARARGS, - PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")}, + { "OpenView", (PyCFunction)msidb_openview, METH_VARARGS, + PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")}, { "Commit", (PyCFunction)msidb_commit, METH_NOARGS, - PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")}, - { "GetSummaryInformation", (PyCFunction)msidb_getsummaryinformation, METH_VARARGS, - PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")}, + PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")}, + { "GetSummaryInformation", (PyCFunction)msidb_getsummaryinformation, METH_VARARGS, + PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")}, { NULL, NULL } }; static PyTypeObject msidb_Type = { - PyVarObject_HEAD_INIT(NULL, 0) - "_msi.Database", /*tp_name*/ - sizeof(msiobj), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - /* methods */ - (destructor)msiobj_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash*/ - 0, /*tp_call*/ - 0, /*tp_str*/ - PyObject_GenericGetAttr,/*tp_getattro*/ - PyObject_GenericSetAttr,/*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT, /*tp_flags*/ - 0, /*tp_doc*/ - 0, /*tp_traverse*/ - 0, /*tp_clear*/ - 0, /*tp_richcompare*/ - 0, /*tp_weaklistoffset*/ - 0, /*tp_iter*/ - 0, /*tp_iternext*/ - db_methods, /*tp_methods*/ - 0, /*tp_members*/ - 0, /*tp_getset*/ - 0, /*tp_base*/ - 0, /*tp_dict*/ - 0, /*tp_descr_get*/ - 0, /*tp_descr_set*/ - 0, /*tp_dictoffset*/ - 0, /*tp_init*/ - 0, /*tp_alloc*/ - 0, /*tp_new*/ - 0, /*tp_free*/ - 0, /*tp_is_gc*/ + PyVarObject_HEAD_INIT(NULL, 0) + "_msi.Database", /*tp_name*/ + sizeof(msiobj), /*tp_basicsize*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)msiobj_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + PyObject_GenericGetAttr,/*tp_getattro*/ + PyObject_GenericSetAttr,/*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + db_methods, /*tp_methods*/ + 0, /*tp_members*/ + 0, /*tp_getset*/ + 0, /*tp_base*/ + 0, /*tp_dict*/ + 0, /*tp_descr_get*/ + 0, /*tp_descr_set*/ + 0, /*tp_dictoffset*/ + 0, /*tp_init*/ + 0, /*tp_alloc*/ + 0, /*tp_new*/ + 0, /*tp_free*/ + 0, /*tp_is_gc*/ }; static PyObject* msiopendb(PyObject *obj, PyObject *args) @@ -945,18 +945,18 @@ static PyObject* msiopendb(PyObject *obj, PyObject *args) int persist; MSIHANDLE h; msiobj *result; - + if (!PyArg_ParseTuple(args, "si:MSIOpenDatabase", &path, &persist)) - return NULL; + return NULL; - status = MsiOpenDatabase(path, (LPCSTR)persist, &h); + status = MsiOpenDatabase(path, (LPCSTR)persist, &h); if (status != ERROR_SUCCESS) - return msierror(status); + return msierror(status); result = PyObject_NEW(struct msiobj, &msidb_Type); if (!result) { - MsiCloseHandle(h); - return NULL; + MsiCloseHandle(h); + return NULL; } result->h = h; return (PyObject*)result; @@ -969,26 +969,26 @@ createrecord(PyObject *o, PyObject *args) MSIHANDLE h; if (!PyArg_ParseTuple(args, "i:CreateRecord", &count)) - return NULL; - + return NULL; + h = MsiCreateRecord(count); if (h == 0) - return msierror(0); + return msierror(0); return record_new(h); } static PyMethodDef msi_methods[] = { - {"UuidCreate", (PyCFunction)uuidcreate, METH_NOARGS, - PyDoc_STR("UuidCreate() -> string")}, - {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS, - PyDoc_STR("fcicreate(cabname,files) -> None")}, - {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS, - PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")}, - {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS, - PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")}, - {NULL, NULL} /* sentinel */ + {"UuidCreate", (PyCFunction)uuidcreate, METH_NOARGS, + PyDoc_STR("UuidCreate() -> string")}, + {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS, + PyDoc_STR("fcicreate(cabname,files) -> None")}, + {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS, + PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")}, + {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS, + PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")}, + {NULL, NULL} /* sentinel */ }; static char msi_doc[] = "Documentation"; @@ -1000,7 +1000,7 @@ init_msi(void) m = Py_InitModule3("_msi", msi_methods, msi_doc); if (m == NULL) - return; + return; PyModule_AddIntConstant(m, "MSIDBOPEN_CREATEDIRECT", (int)MSIDBOPEN_CREATEDIRECT); PyModule_AddIntConstant(m, "MSIDBOPEN_CREATE", (int)MSIDBOPEN_CREATE); @@ -1046,6 +1046,6 @@ init_msi(void) MSIError = PyErr_NewException ("_msi.MSIError", NULL, NULL); if (!MSIError) - return; + return; PyModule_AddObject(m, "MSIError", MSIError); } diff --git a/PC/_subprocess.c b/PC/_subprocess.c index bbe75ff..6780382 100644 --- a/PC/_subprocess.c +++ b/PC/_subprocess.c @@ -49,8 +49,8 @@ the wrapper is used to provide Detach and Close methods */ typedef struct { - PyObject_HEAD - HANDLE handle; + PyObject_HEAD + HANDLE handle; } sp_handle_object; staticforward PyTypeObject sp_handle_type; @@ -58,97 +58,97 @@ staticforward PyTypeObject sp_handle_type; static PyObject* sp_handle_new(HANDLE handle) { - sp_handle_object* self; + sp_handle_object* self; - self = PyObject_NEW(sp_handle_object, &sp_handle_type); - if (self == NULL) - return NULL; + self = PyObject_NEW(sp_handle_object, &sp_handle_type); + if (self == NULL) + return NULL; - self->handle = handle; + self->handle = handle; - return (PyObject*) self; + return (PyObject*) self; } #if defined(MS_WIN32) && !defined(MS_WIN64) -#define HANDLE_TO_PYNUM(handle) PyInt_FromLong((long) handle) -#define PY_HANDLE_PARAM "l" +#define HANDLE_TO_PYNUM(handle) PyInt_FromLong((long) handle) +#define PY_HANDLE_PARAM "l" #else -#define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle) -#define PY_HANDLE_PARAM "L" +#define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle) +#define PY_HANDLE_PARAM "L" #endif static PyObject* sp_handle_detach(sp_handle_object* self, PyObject* args) { - HANDLE handle; + HANDLE handle; - if (! PyArg_ParseTuple(args, ":Detach")) - return NULL; + if (! PyArg_ParseTuple(args, ":Detach")) + return NULL; - handle = self->handle; + handle = self->handle; - self->handle = INVALID_HANDLE_VALUE; + self->handle = INVALID_HANDLE_VALUE; - /* note: return the current handle, as an integer */ - return HANDLE_TO_PYNUM(handle); + /* note: return the current handle, as an integer */ + return HANDLE_TO_PYNUM(handle); } static PyObject* sp_handle_close(sp_handle_object* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":Close")) - return NULL; - - if (self->handle != INVALID_HANDLE_VALUE) { - CloseHandle(self->handle); - self->handle = INVALID_HANDLE_VALUE; - } - Py_INCREF(Py_None); - return Py_None; + if (! PyArg_ParseTuple(args, ":Close")) + return NULL; + + if (self->handle != INVALID_HANDLE_VALUE) { + CloseHandle(self->handle); + self->handle = INVALID_HANDLE_VALUE; + } + Py_INCREF(Py_None); + return Py_None; } static void sp_handle_dealloc(sp_handle_object* self) { - if (self->handle != INVALID_HANDLE_VALUE) - CloseHandle(self->handle); - PyObject_FREE(self); + if (self->handle != INVALID_HANDLE_VALUE) + CloseHandle(self->handle); + PyObject_FREE(self); } static PyMethodDef sp_handle_methods[] = { - {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS}, - {"Close", (PyCFunction) sp_handle_close, METH_VARARGS}, - {NULL, NULL} + {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS}, + {"Close", (PyCFunction) sp_handle_close, METH_VARARGS}, + {NULL, NULL} }; static PyObject* sp_handle_getattr(sp_handle_object* self, char* name) { - return Py_FindMethod(sp_handle_methods, (PyObject*) self, name); + return Py_FindMethod(sp_handle_methods, (PyObject*) self, name); } static PyObject* sp_handle_as_int(sp_handle_object* self) { - return HANDLE_TO_PYNUM(self->handle); + return HANDLE_TO_PYNUM(self->handle); } static PyNumberMethods sp_handle_as_number; statichere PyTypeObject sp_handle_type = { - PyObject_HEAD_INIT(NULL) - 0, /*ob_size*/ - "_subprocess_handle", sizeof(sp_handle_object), 0, - (destructor) sp_handle_dealloc, /*tp_dealloc*/ - 0, /*tp_print*/ - (getattrfunc) sp_handle_getattr,/*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare*/ - 0, /*tp_repr*/ - &sp_handle_as_number, /*tp_as_number */ - 0, /*tp_as_sequence */ - 0, /*tp_as_mapping */ - 0 /*tp_hash*/ + PyObject_HEAD_INIT(NULL) + 0, /*ob_size*/ + "_subprocess_handle", sizeof(sp_handle_object), 0, + (destructor) sp_handle_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc) sp_handle_getattr,/*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + &sp_handle_as_number, /*tp_as_number */ + 0, /*tp_as_sequence */ + 0, /*tp_as_mapping */ + 0 /*tp_hash*/ }; /* -------------------------------------------------------------------- */ @@ -164,26 +164,26 @@ The integer associated with the handle object is returned."); static PyObject * sp_GetStdHandle(PyObject* self, PyObject* args) { - HANDLE handle; - int std_handle; + HANDLE handle; + int std_handle; - if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle)) - return NULL; + if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle)) + return NULL; - Py_BEGIN_ALLOW_THREADS - handle = GetStdHandle((DWORD) std_handle); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + handle = GetStdHandle((DWORD) std_handle); + Py_END_ALLOW_THREADS - if (handle == INVALID_HANDLE_VALUE) - return PyErr_SetFromWindowsErr(GetLastError()); + if (handle == INVALID_HANDLE_VALUE) + return PyErr_SetFromWindowsErr(GetLastError()); - if (! handle) { - Py_INCREF(Py_None); - return Py_None; - } + if (! handle) { + Py_INCREF(Py_None); + return Py_None; + } - /* note: returns integer, not handle object */ - return HANDLE_TO_PYNUM(handle); + /* note: returns integer, not handle object */ + return HANDLE_TO_PYNUM(handle); } PyDoc_STRVAR(GetCurrentProcess_doc, @@ -194,10 +194,10 @@ Return a handle object for the current process."); static PyObject * sp_GetCurrentProcess(PyObject* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":GetCurrentProcess")) - return NULL; + if (! PyArg_ParseTuple(args, ":GetCurrentProcess")) + return NULL; - return sp_handle_new(GetCurrentProcess()); + return sp_handle_new(GetCurrentProcess()); } PyDoc_STRVAR(DuplicateHandle_doc, @@ -214,43 +214,43 @@ through both handles."); static PyObject * sp_DuplicateHandle(PyObject* self, PyObject* args) { - HANDLE target_handle; - BOOL result; - - HANDLE source_process_handle; - HANDLE source_handle; - HANDLE target_process_handle; - int desired_access; - int inherit_handle; - int options = 0; - - if (! PyArg_ParseTuple(args, - PY_HANDLE_PARAM PY_HANDLE_PARAM PY_HANDLE_PARAM - "ii|i:DuplicateHandle", - &source_process_handle, - &source_handle, - &target_process_handle, - &desired_access, - &inherit_handle, - &options)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - result = DuplicateHandle( - source_process_handle, - source_handle, - target_process_handle, - &target_handle, - desired_access, - inherit_handle, - options - ); - Py_END_ALLOW_THREADS - - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); - - return sp_handle_new(target_handle); + HANDLE target_handle; + BOOL result; + + HANDLE source_process_handle; + HANDLE source_handle; + HANDLE target_process_handle; + int desired_access; + int inherit_handle; + int options = 0; + + if (! PyArg_ParseTuple(args, + PY_HANDLE_PARAM PY_HANDLE_PARAM PY_HANDLE_PARAM + "ii|i:DuplicateHandle", + &source_process_handle, + &source_handle, + &target_process_handle, + &desired_access, + &inherit_handle, + &options)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + result = DuplicateHandle( + source_process_handle, + source_handle, + target_process_handle, + &target_handle, + desired_access, + inherit_handle, + options + ); + Py_END_ALLOW_THREADS + + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); + + return sp_handle_new(target_handle); } PyDoc_STRVAR(CreatePipe_doc, @@ -264,25 +264,25 @@ pipe_attrs is ignored internally and can be None."); static PyObject * sp_CreatePipe(PyObject* self, PyObject* args) { - HANDLE read_pipe; - HANDLE write_pipe; - BOOL result; + HANDLE read_pipe; + HANDLE write_pipe; + BOOL result; - PyObject* pipe_attributes; /* ignored */ - int size; + PyObject* pipe_attributes; /* ignored */ + int size; - if (! PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size)) - return NULL; + if (! PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size)) + return NULL; - Py_BEGIN_ALLOW_THREADS - result = CreatePipe(&read_pipe, &write_pipe, NULL, size); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + result = CreatePipe(&read_pipe, &write_pipe, NULL, size); + Py_END_ALLOW_THREADS - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return Py_BuildValue( - "NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe)); + return Py_BuildValue( + "NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe)); } /* helpers for createprocess */ @@ -290,110 +290,110 @@ sp_CreatePipe(PyObject* self, PyObject* args) static int getint(PyObject* obj, char* name) { - PyObject* value; - int ret; - - value = PyObject_GetAttrString(obj, name); - if (! value) { - PyErr_Clear(); /* FIXME: propagate error? */ - return 0; - } - ret = (int) PyInt_AsLong(value); - Py_DECREF(value); - return ret; + PyObject* value; + int ret; + + value = PyObject_GetAttrString(obj, name); + if (! value) { + PyErr_Clear(); /* FIXME: propagate error? */ + return 0; + } + ret = (int) PyInt_AsLong(value); + Py_DECREF(value); + return ret; } static HANDLE gethandle(PyObject* obj, char* name) { - sp_handle_object* value; - HANDLE ret; - - value = (sp_handle_object*) PyObject_GetAttrString(obj, name); - if (! value) { - PyErr_Clear(); /* FIXME: propagate error? */ - return NULL; - } - if (value->ob_type != &sp_handle_type) - ret = NULL; - else - ret = value->handle; - Py_DECREF(value); - return ret; + sp_handle_object* value; + HANDLE ret; + + value = (sp_handle_object*) PyObject_GetAttrString(obj, name); + if (! value) { + PyErr_Clear(); /* FIXME: propagate error? */ + return NULL; + } + if (value->ob_type != &sp_handle_type) + ret = NULL; + else + ret = value->handle; + Py_DECREF(value); + return ret; } static PyObject* getenvironment(PyObject* environment) { - int i, envsize; - PyObject* out = NULL; - PyObject* keys; - PyObject* values; - char* p; - - /* convert environment dictionary to windows enviroment string */ - if (! PyMapping_Check(environment)) { - PyErr_SetString( - PyExc_TypeError, "environment must be dictionary or None"); - return NULL; - } - - envsize = PyMapping_Length(environment); - - keys = PyMapping_Keys(environment); - values = PyMapping_Values(environment); - if (!keys || !values) - goto error; - - out = PyString_FromStringAndSize(NULL, 2048); - if (! out) - goto error; - - p = PyString_AS_STRING(out); - - for (i = 0; i < envsize; i++) { - int ksize, vsize, totalsize; - PyObject* key = PyList_GET_ITEM(keys, i); - PyObject* value = PyList_GET_ITEM(values, i); - - if (! PyString_Check(key) || ! PyString_Check(value)) { - PyErr_SetString(PyExc_TypeError, - "environment can only contain strings"); - goto error; - } - ksize = PyString_GET_SIZE(key); - vsize = PyString_GET_SIZE(value); - totalsize = (p - PyString_AS_STRING(out)) + ksize + 1 + - vsize + 1 + 1; - if (totalsize > PyString_GET_SIZE(out)) { - int offset = p - PyString_AS_STRING(out); - _PyString_Resize(&out, totalsize + 1024); - p = PyString_AS_STRING(out) + offset; - } - memcpy(p, PyString_AS_STRING(key), ksize); - p += ksize; - *p++ = '='; - memcpy(p, PyString_AS_STRING(value), vsize); - p += vsize; - *p++ = '\0'; - } - - /* add trailing null byte */ - *p++ = '\0'; - _PyString_Resize(&out, p - PyString_AS_STRING(out)); - - /* PyObject_Print(out, stdout, 0); */ - - Py_XDECREF(keys); - Py_XDECREF(values); - - return out; + int i, envsize; + PyObject* out = NULL; + PyObject* keys; + PyObject* values; + char* p; + + /* convert environment dictionary to windows enviroment string */ + if (! PyMapping_Check(environment)) { + PyErr_SetString( + PyExc_TypeError, "environment must be dictionary or None"); + return NULL; + } + + envsize = PyMapping_Length(environment); + + keys = PyMapping_Keys(environment); + values = PyMapping_Values(environment); + if (!keys || !values) + goto error; + + out = PyString_FromStringAndSize(NULL, 2048); + if (! out) + goto error; + + p = PyString_AS_STRING(out); + + for (i = 0; i < envsize; i++) { + int ksize, vsize, totalsize; + PyObject* key = PyList_GET_ITEM(keys, i); + PyObject* value = PyList_GET_ITEM(values, i); + + if (! PyString_Check(key) || ! PyString_Check(value)) { + PyErr_SetString(PyExc_TypeError, + "environment can only contain strings"); + goto error; + } + ksize = PyString_GET_SIZE(key); + vsize = PyString_GET_SIZE(value); + totalsize = (p - PyString_AS_STRING(out)) + ksize + 1 + + vsize + 1 + 1; + if (totalsize > PyString_GET_SIZE(out)) { + int offset = p - PyString_AS_STRING(out); + _PyString_Resize(&out, totalsize + 1024); + p = PyString_AS_STRING(out) + offset; + } + memcpy(p, PyString_AS_STRING(key), ksize); + p += ksize; + *p++ = '='; + memcpy(p, PyString_AS_STRING(value), vsize); + p += vsize; + *p++ = '\0'; + } + + /* add trailing null byte */ + *p++ = '\0'; + _PyString_Resize(&out, p - PyString_AS_STRING(out)); + + /* PyObject_Print(out, stdout, 0); */ + + Py_XDECREF(keys); + Py_XDECREF(values); + + return out; error: - Py_XDECREF(out); - Py_XDECREF(keys); - Py_XDECREF(values); - return NULL; + Py_XDECREF(out); + Py_XDECREF(keys); + Py_XDECREF(values); + return NULL; } PyDoc_STRVAR(CreateProcess_doc, @@ -411,77 +411,77 @@ proc_attrs and thread_attrs are ignored internally and can be None."); static PyObject * sp_CreateProcess(PyObject* self, PyObject* args) { - BOOL result; - PROCESS_INFORMATION pi; - STARTUPINFO si; - PyObject* environment; - - char* application_name; - char* command_line; - PyObject* process_attributes; /* ignored */ - PyObject* thread_attributes; /* ignored */ - int inherit_handles; - int creation_flags; - PyObject* env_mapping; - char* current_directory; - PyObject* startup_info; - - if (! PyArg_ParseTuple(args, "zzOOiiOzO:CreateProcess", - &application_name, - &command_line, - &process_attributes, - &thread_attributes, - &inherit_handles, - &creation_flags, - &env_mapping, - ¤t_directory, - &startup_info)) - return NULL; - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - /* note: we only support a small subset of all SI attributes */ - si.dwFlags = getint(startup_info, "dwFlags"); - si.wShowWindow = getint(startup_info, "wShowWindow"); - si.hStdInput = gethandle(startup_info, "hStdInput"); - si.hStdOutput = gethandle(startup_info, "hStdOutput"); - si.hStdError = gethandle(startup_info, "hStdError"); - - if (PyErr_Occurred()) - return NULL; - - if (env_mapping == Py_None) - environment = NULL; - else { - environment = getenvironment(env_mapping); - if (! environment) - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - result = CreateProcess(application_name, - command_line, - NULL, - NULL, - inherit_handles, - creation_flags, - environment ? PyString_AS_STRING(environment) : NULL, - current_directory, - &si, - &pi); - Py_END_ALLOW_THREADS - - Py_XDECREF(environment); - - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); - - return Py_BuildValue("NNii", - sp_handle_new(pi.hProcess), - sp_handle_new(pi.hThread), - pi.dwProcessId, - pi.dwThreadId); + BOOL result; + PROCESS_INFORMATION pi; + STARTUPINFO si; + PyObject* environment; + + char* application_name; + char* command_line; + PyObject* process_attributes; /* ignored */ + PyObject* thread_attributes; /* ignored */ + int inherit_handles; + int creation_flags; + PyObject* env_mapping; + char* current_directory; + PyObject* startup_info; + + if (! PyArg_ParseTuple(args, "zzOOiiOzO:CreateProcess", + &application_name, + &command_line, + &process_attributes, + &thread_attributes, + &inherit_handles, + &creation_flags, + &env_mapping, + ¤t_directory, + &startup_info)) + return NULL; + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + + /* note: we only support a small subset of all SI attributes */ + si.dwFlags = getint(startup_info, "dwFlags"); + si.wShowWindow = getint(startup_info, "wShowWindow"); + si.hStdInput = gethandle(startup_info, "hStdInput"); + si.hStdOutput = gethandle(startup_info, "hStdOutput"); + si.hStdError = gethandle(startup_info, "hStdError"); + + if (PyErr_Occurred()) + return NULL; + + if (env_mapping == Py_None) + environment = NULL; + else { + environment = getenvironment(env_mapping); + if (! environment) + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + result = CreateProcess(application_name, + command_line, + NULL, + NULL, + inherit_handles, + creation_flags, + environment ? PyString_AS_STRING(environment) : NULL, + current_directory, + &si, + &pi); + Py_END_ALLOW_THREADS + + Py_XDECREF(environment); + + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); + + return Py_BuildValue("NNii", + sp_handle_new(pi.hProcess), + sp_handle_new(pi.hThread), + pi.dwProcessId, + pi.dwThreadId); } PyDoc_STRVAR(TerminateProcess_doc, @@ -492,21 +492,21 @@ Terminate the specified process and all of its threads."); static PyObject * sp_TerminateProcess(PyObject* self, PyObject* args) { - BOOL result; + BOOL result; - HANDLE process; - int exit_code; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess", - &process, &exit_code)) - return NULL; + HANDLE process; + int exit_code; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess", + &process, &exit_code)) + return NULL; - result = TerminateProcess(process, exit_code); + result = TerminateProcess(process, exit_code); - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(GetExitCodeProcess_doc, @@ -517,19 +517,19 @@ Return the termination status of the specified process."); static PyObject * sp_GetExitCodeProcess(PyObject* self, PyObject* args) { - DWORD exit_code; - BOOL result; + DWORD exit_code; + BOOL result; - HANDLE process; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process)) - return NULL; + HANDLE process; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process)) + return NULL; - result = GetExitCodeProcess(process, &exit_code); + result = GetExitCodeProcess(process, &exit_code); - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyInt_FromLong(exit_code); + return PyInt_FromLong(exit_code); } PyDoc_STRVAR(WaitForSingleObject_doc, @@ -542,23 +542,23 @@ in milliseconds."); static PyObject * sp_WaitForSingleObject(PyObject* self, PyObject* args) { - DWORD result; + DWORD result; - HANDLE handle; - int milliseconds; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:WaitForSingleObject", - &handle, - &milliseconds)) - return NULL; + HANDLE handle; + int milliseconds; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:WaitForSingleObject", + &handle, + &milliseconds)) + return NULL; - Py_BEGIN_ALLOW_THREADS - result = WaitForSingleObject(handle, (DWORD) milliseconds); - Py_END_ALLOW_THREADS + Py_BEGIN_ALLOW_THREADS + result = WaitForSingleObject(handle, (DWORD) milliseconds); + Py_END_ALLOW_THREADS - if (result == WAIT_FAILED) - return PyErr_SetFromWindowsErr(GetLastError()); + if (result == WAIT_FAILED) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyInt_FromLong((int) result); + return PyInt_FromLong((int) result); } PyDoc_STRVAR(GetVersion_doc, @@ -569,10 +569,10 @@ Return the version number of the current operating system."); static PyObject * sp_GetVersion(PyObject* self, PyObject* args) { - if (! PyArg_ParseTuple(args, ":GetVersion")) - return NULL; + if (! PyArg_ParseTuple(args, ":GetVersion")) + return NULL; - return PyInt_FromLong((int) GetVersion()); + return PyInt_FromLong((int) GetVersion()); } PyDoc_STRVAR(GetModuleFileName_doc, @@ -590,41 +590,41 @@ of the current process."); static PyObject * sp_GetModuleFileName(PyObject* self, PyObject* args) { - BOOL result; - HMODULE module; - TCHAR filename[MAX_PATH]; + BOOL result; + HMODULE module; + TCHAR filename[MAX_PATH]; - if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName", - &module)) - return NULL; + if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName", + &module)) + return NULL; - result = GetModuleFileName(module, filename, MAX_PATH); - filename[MAX_PATH-1] = '\0'; + result = GetModuleFileName(module, filename, MAX_PATH); + filename[MAX_PATH-1] = '\0'; - if (! result) - return PyErr_SetFromWindowsErr(GetLastError()); + if (! result) + return PyErr_SetFromWindowsErr(GetLastError()); - return PyString_FromString(filename); + return PyString_FromString(filename); } static PyMethodDef sp_functions[] = { - {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc}, - {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS, - GetCurrentProcess_doc}, - {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS, - DuplicateHandle_doc}, - {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc}, - {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc}, - {"TerminateProcess", sp_TerminateProcess, METH_VARARGS, - TerminateProcess_doc}, - {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS, - GetExitCodeProcess_doc}, - {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS, - WaitForSingleObject_doc}, - {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc}, - {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS, - GetModuleFileName_doc}, - {NULL, NULL} + {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc}, + {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS, + GetCurrentProcess_doc}, + {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS, + DuplicateHandle_doc}, + {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc}, + {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc}, + {"TerminateProcess", sp_TerminateProcess, METH_VARARGS, + TerminateProcess_doc}, + {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS, + GetExitCodeProcess_doc}, + {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS, + WaitForSingleObject_doc}, + {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc}, + {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS, + GetModuleFileName_doc}, + {NULL, NULL} }; /* -------------------------------------------------------------------- */ @@ -632,11 +632,11 @@ static PyMethodDef sp_functions[] = { static void defint(PyObject* d, const char* name, int value) { - PyObject* v = PyInt_FromLong((long) value); - if (v) { - PyDict_SetItemString(d, (char*) name, v); - Py_DECREF(v); - } + PyObject* v = PyInt_FromLong((long) value); + if (v) { + PyDict_SetItemString(d, (char*) name, v); + Py_DECREF(v); + } } #if PY_VERSION_HEX >= 0x02030000 @@ -646,28 +646,28 @@ DL_EXPORT(void) #endif init_subprocess() { - PyObject *d; - PyObject *m; - - /* patch up object descriptors */ - sp_handle_type.ob_type = &PyType_Type; - sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int; - - m = Py_InitModule("_subprocess", sp_functions); - if (m == NULL) - return; - d = PyModule_GetDict(m); - - /* constants */ - defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE); - defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE); - defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE); - defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS); - defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES); - defint(d, "STARTF_USESHOWWINDOW", STARTF_USESHOWWINDOW); - defint(d, "SW_HIDE", SW_HIDE); - defint(d, "INFINITE", INFINITE); - defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0); - defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE); - defint(d, "CREATE_NEW_PROCESS_GROUP", CREATE_NEW_PROCESS_GROUP); + PyObject *d; + PyObject *m; + + /* patch up object descriptors */ + sp_handle_type.ob_type = &PyType_Type; + sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int; + + m = Py_InitModule("_subprocess", sp_functions); + if (m == NULL) + return; + d = PyModule_GetDict(m); + + /* constants */ + defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE); + defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE); + defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE); + defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS); + defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES); + defint(d, "STARTF_USESHOWWINDOW", STARTF_USESHOWWINDOW); + defint(d, "SW_HIDE", SW_HIDE); + defint(d, "INFINITE", INFINITE); + defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0); + defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE); + defint(d, "CREATE_NEW_PROCESS_GROUP", CREATE_NEW_PROCESS_GROUP); } diff --git a/PC/_winreg.c b/PC/_winreg.c index 57fe22b..6872603 100644 --- a/PC/_winreg.c +++ b/PC/_winreg.c @@ -4,7 +4,7 @@ Windows Registry access module for Python. * Simple registry access written by Mark Hammond in win32api - module circa 1995. + module circa 1995. * Bill Tutt expanded the support significantly not long after. * Numerous other people have submitted patches since then. * Ripped from win32api module 03-Feb-2000 by Mark Hammond, and @@ -29,7 +29,7 @@ static char errNotAHandle[] = "Object is not a handle"; want to lose this info... */ #define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \ - PyErr_SetFromWindowsErr(rc) + PyErr_SetFromWindowsErr(rc) /* Forward declares */ @@ -384,8 +384,8 @@ PyDoc_STRVAR(PyHKEY_Detach_doc, ************************************************************************/ typedef struct { - PyObject_VAR_HEAD - HKEY hkey; + PyObject_VAR_HEAD + HKEY hkey; } PyHKEYObject; #define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type) @@ -395,46 +395,46 @@ static char *failMsg = "bad operand type"; static PyObject * PyHKEY_unaryFailureFunc(PyObject *ob) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static PyObject * PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static PyObject * PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3) { - PyErr_SetString(PyExc_TypeError, failMsg); - return NULL; + PyErr_SetString(PyExc_TypeError, failMsg); + return NULL; } static void PyHKEY_deallocFunc(PyObject *ob) { - /* Can not call PyHKEY_Close, as the ob->tp_type - has already been cleared, thus causing the type - check to fail! - */ - PyHKEYObject *obkey = (PyHKEYObject *)ob; - if (obkey->hkey) - RegCloseKey((HKEY)obkey->hkey); - PyObject_DEL(ob); + /* Can not call PyHKEY_Close, as the ob->tp_type + has already been cleared, thus causing the type + check to fail! + */ + PyHKEYObject *obkey = (PyHKEYObject *)ob; + if (obkey->hkey) + RegCloseKey((HKEY)obkey->hkey); + PyObject_DEL(ob); } static int PyHKEY_nonzeroFunc(PyObject *ob) { - return ((PyHKEYObject *)ob)->hkey != 0; + return ((PyHKEYObject *)ob)->hkey != 0; } static PyObject * PyHKEY_intFunc(PyObject *ob) { - PyHKEYObject *pyhkey = (PyHKEYObject *)ob; - return PyLong_FromVoidPtr(pyhkey->hkey); + PyHKEYObject *pyhkey = (PyHKEYObject *)ob; + return PyLong_FromVoidPtr(pyhkey->hkey); } static int @@ -442,7 +442,7 @@ PyHKEY_printFunc(PyObject *ob, FILE *fp, int flags) { PyHKEYObject *pyhkey = (PyHKEYObject *)ob; fprintf(fp, "<PyHKEY at %p (%p)>", - ob, pyhkey->hkey); + ob, pyhkey->hkey); return 0; } @@ -456,47 +456,47 @@ PyHKEY_strFunc(PyObject *ob) static int PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2) { - PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1; - PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2; - return pyhkey1 == pyhkey2 ? 0 : - (pyhkey1 < pyhkey2 ? -1 : 1); + PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1; + PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2; + return pyhkey1 == pyhkey2 ? 0 : + (pyhkey1 < pyhkey2 ? -1 : 1); } static long PyHKEY_hashFunc(PyObject *ob) { - /* Just use the address. - XXX - should we use the handle value? - */ - return _Py_HashPointer(ob); + /* Just use the address. + XXX - should we use the handle value? + */ + return _Py_HashPointer(ob); } static PyNumberMethods PyHKEY_NumberMethods = { - PyHKEY_binaryFailureFunc, /* nb_add */ - PyHKEY_binaryFailureFunc, /* nb_subtract */ - PyHKEY_binaryFailureFunc, /* nb_multiply */ - PyHKEY_binaryFailureFunc, /* nb_divide */ - PyHKEY_binaryFailureFunc, /* nb_remainder */ - PyHKEY_binaryFailureFunc, /* nb_divmod */ - PyHKEY_ternaryFailureFunc, /* nb_power */ - PyHKEY_unaryFailureFunc, /* nb_negative */ - PyHKEY_unaryFailureFunc, /* nb_positive */ - PyHKEY_unaryFailureFunc, /* nb_absolute */ - PyHKEY_nonzeroFunc, /* nb_nonzero */ - PyHKEY_unaryFailureFunc, /* nb_invert */ - PyHKEY_binaryFailureFunc, /* nb_lshift */ - PyHKEY_binaryFailureFunc, /* nb_rshift */ - PyHKEY_binaryFailureFunc, /* nb_and */ - PyHKEY_binaryFailureFunc, /* nb_xor */ - PyHKEY_binaryFailureFunc, /* nb_or */ - 0, /* nb_coerce (allowed to be zero) */ - PyHKEY_intFunc, /* nb_int */ - PyHKEY_unaryFailureFunc, /* nb_long */ - PyHKEY_unaryFailureFunc, /* nb_float */ - PyHKEY_unaryFailureFunc, /* nb_oct */ - PyHKEY_unaryFailureFunc, /* nb_hex */ + PyHKEY_binaryFailureFunc, /* nb_add */ + PyHKEY_binaryFailureFunc, /* nb_subtract */ + PyHKEY_binaryFailureFunc, /* nb_multiply */ + PyHKEY_binaryFailureFunc, /* nb_divide */ + PyHKEY_binaryFailureFunc, /* nb_remainder */ + PyHKEY_binaryFailureFunc, /* nb_divmod */ + PyHKEY_ternaryFailureFunc, /* nb_power */ + PyHKEY_unaryFailureFunc, /* nb_negative */ + PyHKEY_unaryFailureFunc, /* nb_positive */ + PyHKEY_unaryFailureFunc, /* nb_absolute */ + PyHKEY_nonzeroFunc, /* nb_nonzero */ + PyHKEY_unaryFailureFunc, /* nb_invert */ + PyHKEY_binaryFailureFunc, /* nb_lshift */ + PyHKEY_binaryFailureFunc, /* nb_rshift */ + PyHKEY_binaryFailureFunc, /* nb_and */ + PyHKEY_binaryFailureFunc, /* nb_xor */ + PyHKEY_binaryFailureFunc, /* nb_or */ + 0, /* nb_coerce (allowed to be zero) */ + PyHKEY_intFunc, /* nb_int */ + PyHKEY_unaryFailureFunc, /* nb_long */ + PyHKEY_unaryFailureFunc, /* nb_float */ + PyHKEY_unaryFailureFunc, /* nb_oct */ + PyHKEY_unaryFailureFunc, /* nb_hex */ }; static PyObject *PyHKEY_CloseMethod(PyObject *self, PyObject *args); @@ -505,50 +505,50 @@ static PyObject *PyHKEY_Enter(PyObject *self); static PyObject *PyHKEY_Exit(PyObject *self, PyObject *args); static struct PyMethodDef PyHKEY_methods[] = { - {"Close", PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc}, - {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc}, - {"__enter__", (PyCFunction)PyHKEY_Enter, METH_NOARGS, NULL}, - {"__exit__", PyHKEY_Exit, METH_VARARGS, NULL}, - {NULL} + {"Close", PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc}, + {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc}, + {"__enter__", (PyCFunction)PyHKEY_Enter, METH_NOARGS, NULL}, + {"__exit__", PyHKEY_Exit, METH_VARARGS, NULL}, + {NULL} }; static PyMemberDef PyHKEY_memberlist[] = { - {"handle", T_PYSSIZET, offsetof(PyHKEYObject, hkey), READONLY}, - {NULL} /* Sentinel */ + {"handle", T_PYSSIZET, offsetof(PyHKEYObject, hkey), READONLY}, + {NULL} /* Sentinel */ }; /* The type itself */ PyTypeObject PyHKEY_Type = { - PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */ - "PyHKEY", - sizeof(PyHKEYObject), - 0, - PyHKEY_deallocFunc, /* tp_dealloc */ - PyHKEY_printFunc, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - PyHKEY_compareFunc, /* tp_compare */ - 0, /* tp_repr */ - &PyHKEY_NumberMethods, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - PyHKEY_hashFunc, /* tp_hash */ - 0, /* tp_call */ - PyHKEY_strFunc, /* tp_str */ - 0, /* tp_getattro */ - 0, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT, /* tp_flags */ - PyHKEY_doc, /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - PyHKEY_methods, /* tp_methods */ - PyHKEY_memberlist, /* tp_members */ + PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */ + "PyHKEY", + sizeof(PyHKEYObject), + 0, + PyHKEY_deallocFunc, /* tp_dealloc */ + PyHKEY_printFunc, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + PyHKEY_compareFunc, /* tp_compare */ + 0, /* tp_repr */ + &PyHKEY_NumberMethods, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + PyHKEY_hashFunc, /* tp_hash */ + 0, /* tp_call */ + PyHKEY_strFunc, /* tp_str */ + 0, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT, /* tp_flags */ + PyHKEY_doc, /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + PyHKEY_methods, /* tp_methods */ + PyHKEY_memberlist, /* tp_members */ }; /************************************************************************ @@ -559,39 +559,39 @@ PyTypeObject PyHKEY_Type = static PyObject * PyHKEY_CloseMethod(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":Close")) - return NULL; - if (!PyHKEY_Close(self)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + if (!PyArg_ParseTuple(args, ":Close")) + return NULL; + if (!PyHKEY_Close(self)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyHKEY_DetachMethod(PyObject *self, PyObject *args) { - void* ret; - PyHKEYObject *pThis = (PyHKEYObject *)self; - if (!PyArg_ParseTuple(args, ":Detach")) - return NULL; - ret = (void*)pThis->hkey; - pThis->hkey = 0; - return PyLong_FromVoidPtr(ret); + void* ret; + PyHKEYObject *pThis = (PyHKEYObject *)self; + if (!PyArg_ParseTuple(args, ":Detach")) + return NULL; + ret = (void*)pThis->hkey; + pThis->hkey = 0; + return PyLong_FromVoidPtr(ret); } static PyObject * PyHKEY_Enter(PyObject *self) { - Py_XINCREF(self); - return self; + Py_XINCREF(self); + return self; } static PyObject * PyHKEY_Exit(PyObject *self, PyObject *args) { - if (!PyHKEY_Close(self)) - return NULL; - Py_RETURN_NONE; + if (!PyHKEY_Close(self)) + return NULL; + Py_RETURN_NONE; } @@ -601,74 +601,74 @@ PyHKEY_Exit(PyObject *self, PyObject *args) PyObject * PyHKEY_New(HKEY hInit) { - PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type); - if (key) - key->hkey = hInit; - return (PyObject *)key; + PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type); + if (key) + key->hkey = hInit; + return (PyObject *)key; } BOOL PyHKEY_Close(PyObject *ob_handle) { - LONG rc; - PyHKEYObject *key; - - if (!PyHKEY_Check(ob_handle)) { - PyErr_SetString(PyExc_TypeError, "bad operand type"); - return FALSE; - } - key = (PyHKEYObject *)ob_handle; - rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS; - key->hkey = 0; - if (rc != ERROR_SUCCESS) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - return rc == ERROR_SUCCESS; + LONG rc; + PyHKEYObject *key; + + if (!PyHKEY_Check(ob_handle)) { + PyErr_SetString(PyExc_TypeError, "bad operand type"); + return FALSE; + } + key = (PyHKEYObject *)ob_handle; + rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS; + key->hkey = 0; + if (rc != ERROR_SUCCESS) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + return rc == ERROR_SUCCESS; } BOOL PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK) { - if (ob == Py_None) { - if (!bNoneOK) { - PyErr_SetString( - PyExc_TypeError, - "None is not a valid HKEY in this context"); - return FALSE; - } - *pHANDLE = (HKEY)0; - } - else if (PyHKEY_Check(ob)) { - PyHKEYObject *pH = (PyHKEYObject *)ob; - *pHANDLE = pH->hkey; - } - else if (PyInt_Check(ob) || PyLong_Check(ob)) { - /* We also support integers */ - PyErr_Clear(); - *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob); - if (PyErr_Occurred()) - return FALSE; - } - else { - PyErr_SetString( - PyExc_TypeError, - "The object is not a PyHKEY object"); - return FALSE; - } - return TRUE; + if (ob == Py_None) { + if (!bNoneOK) { + PyErr_SetString( + PyExc_TypeError, + "None is not a valid HKEY in this context"); + return FALSE; + } + *pHANDLE = (HKEY)0; + } + else if (PyHKEY_Check(ob)) { + PyHKEYObject *pH = (PyHKEYObject *)ob; + *pHANDLE = pH->hkey; + } + else if (PyInt_Check(ob) || PyLong_Check(ob)) { + /* We also support integers */ + PyErr_Clear(); + *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob); + if (PyErr_Occurred()) + return FALSE; + } + else { + PyErr_SetString( + PyExc_TypeError, + "The object is not a PyHKEY object"); + return FALSE; + } + return TRUE; } PyObject * PyHKEY_FromHKEY(HKEY h) { - PyHKEYObject *op; - - /* Inline PyObject_New */ - op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject)); - if (op == NULL) - return PyErr_NoMemory(); - PyObject_INIT(op, &PyHKEY_Type); - op->hkey = h; - return (PyObject *)op; + PyHKEYObject *op; + + /* Inline PyObject_New */ + op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject)); + if (op == NULL) + return PyErr_NoMemory(); + PyObject_INIT(op, &PyHKEY_Type); + op->hkey = h; + return (PyObject *)op; } @@ -678,32 +678,32 @@ PyHKEY_FromHKEY(HKEY h) BOOL PyWinObject_CloseHKEY(PyObject *obHandle) { - BOOL ok; - if (PyHKEY_Check(obHandle)) { - ok = PyHKEY_Close(obHandle); - } + BOOL ok; + if (PyHKEY_Check(obHandle)) { + ok = PyHKEY_Close(obHandle); + } #if SIZEOF_LONG >= SIZEOF_HKEY - else if (PyInt_Check(obHandle)) { - long rc = RegCloseKey((HKEY)PyInt_AsLong(obHandle)); - ok = (rc == ERROR_SUCCESS); - if (!ok) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - } + else if (PyInt_Check(obHandle)) { + long rc = RegCloseKey((HKEY)PyInt_AsLong(obHandle)); + ok = (rc == ERROR_SUCCESS); + if (!ok) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + } #else - else if (PyLong_Check(obHandle)) { - long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle)); - ok = (rc == ERROR_SUCCESS); - if (!ok) - PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); - } + else if (PyLong_Check(obHandle)) { + long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle)); + ok = (rc == ERROR_SUCCESS); + if (!ok) + PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey"); + } #endif - else { - PyErr_SetString( - PyExc_TypeError, - "A handle must be a HKEY object or an integer"); - return FALSE; - } - return ok; + else { + PyErr_SetString( + PyExc_TypeError, + "A handle must be a HKEY object or an integer"); + return FALSE; + } + return ok; } @@ -720,29 +720,29 @@ PyWinObject_CloseHKEY(PyObject *obHandle) static void fixupMultiSZ(char **str, char *data, int len) { - char *P; - int i; - char *Q; - - Q = data + len; - for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) { - str[i] = P; - for(; *P != '\0'; P++) - ; - } + char *P; + int i; + char *Q; + + Q = data + len; + for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) { + str[i] = P; + for(; *P != '\0'; P++) + ; + } } static int countStrings(char *data, int len) { - int strings; - char *P; - char *Q = data + len; - - for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++) - for (; P < Q && *P != '\0'; P++) - ; - return strings; + int strings; + char *P; + char *Q = data + len; + + for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++) + for (; P < Q && *P != '\0'; P++) + ; + return strings; } /* Convert PyObject into Registry data. @@ -750,244 +750,244 @@ countStrings(char *data, int len) static BOOL Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize) { - Py_ssize_t i,j; - switch (typ) { - case REG_DWORD: - if (value != Py_None && !PyInt_Check(value)) - return FALSE; - *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - *retDataSize = sizeof(DWORD); - if (value == Py_None) { - DWORD zero = 0; - memcpy(*retDataBuf, &zero, sizeof(DWORD)); - } - else - memcpy(*retDataBuf, - &PyInt_AS_LONG((PyIntObject *)value), - sizeof(DWORD)); - break; - case REG_SZ: - case REG_EXPAND_SZ: - { - int need_decref = 0; - if (value == Py_None) - *retDataSize = 1; - else { - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString( - value, - "mbcs", - NULL); - if (value==NULL) - return FALSE; - need_decref = 1; - } - if (!PyString_Check(value)) - return FALSE; - *retDataSize = 1 + strlen( - PyString_AS_STRING( - (PyStringObject *)value)); - } - *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - if (value == Py_None) - strcpy((char *)*retDataBuf, ""); - else - strcpy((char *)*retDataBuf, - PyString_AS_STRING( - (PyStringObject *)value)); - if (need_decref) - Py_DECREF(value); - break; - } - case REG_MULTI_SZ: - { - DWORD size = 0; - char *P; - PyObject **obs = NULL; - - if (value == Py_None) - i = 0; - else { - if (!PyList_Check(value)) - return FALSE; - i = PyList_Size(value); - } - obs = malloc(sizeof(PyObject *) * i); - memset(obs, 0, sizeof(PyObject *) * i); - for (j = 0; j < i; j++) - { - PyObject *t; - t = PyList_GET_ITEM( - (PyListObject *)value,j); - if (PyString_Check(t)) { - obs[j] = t; - Py_INCREF(t); - } else if (PyUnicode_Check(t)) { - obs[j] = PyUnicode_AsEncodedString( - t, - "mbcs", - NULL); - if (obs[j]==NULL) - goto reg_multi_fail; - } else - goto reg_multi_fail; - size += 1 + strlen( - PyString_AS_STRING( - (PyStringObject *)obs[j])); - } - - *retDataSize = size + 1; - *retDataBuf = (BYTE *)PyMem_NEW(char, - *retDataSize); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - goto reg_multi_fail; - } - P = (char *)*retDataBuf; - - for (j = 0; j < i; j++) - { - PyObject *t; - t = obs[j]; - strcpy(P, - PyString_AS_STRING( - (PyStringObject *)t)); - P += 1 + strlen( - PyString_AS_STRING( - (PyStringObject *)t)); - Py_DECREF(obs[j]); - } - /* And doubly-terminate the list... */ - *P = '\0'; - free(obs); - break; - reg_multi_fail: - if (obs) { - for (j = 0; j < i; j++) - Py_XDECREF(obs[j]); - - free(obs); - } - return FALSE; - } - case REG_BINARY: - /* ALSO handle ALL unknown data types here. Even if we can't - support it natively, we should handle the bits. */ - default: - if (value == Py_None) - *retDataSize = 0; - else { - void *src_buf; - PyBufferProcs *pb = value->ob_type->tp_as_buffer; - if (pb==NULL) { - PyErr_Format(PyExc_TypeError, - "Objects of type '%s' can not " - "be used as binary registry values", - value->ob_type->tp_name); - return FALSE; - } - *retDataSize = (*pb->bf_getreadbuffer)(value, 0, &src_buf); - *retDataBuf = (BYTE *)PyMem_NEW(char, - *retDataSize); - if (*retDataBuf==NULL){ - PyErr_NoMemory(); - return FALSE; - } - memcpy(*retDataBuf, src_buf, *retDataSize); - } - break; - } - return TRUE; + Py_ssize_t i,j; + switch (typ) { + case REG_DWORD: + if (value != Py_None && !PyInt_Check(value)) + return FALSE; + *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + *retDataSize = sizeof(DWORD); + if (value == Py_None) { + DWORD zero = 0; + memcpy(*retDataBuf, &zero, sizeof(DWORD)); + } + else + memcpy(*retDataBuf, + &PyInt_AS_LONG((PyIntObject *)value), + sizeof(DWORD)); + break; + case REG_SZ: + case REG_EXPAND_SZ: + { + int need_decref = 0; + if (value == Py_None) + *retDataSize = 1; + else { + if (PyUnicode_Check(value)) { + value = PyUnicode_AsEncodedString( + value, + "mbcs", + NULL); + if (value==NULL) + return FALSE; + need_decref = 1; + } + if (!PyString_Check(value)) + return FALSE; + *retDataSize = 1 + strlen( + PyString_AS_STRING( + (PyStringObject *)value)); + } + *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + if (value == Py_None) + strcpy((char *)*retDataBuf, ""); + else + strcpy((char *)*retDataBuf, + PyString_AS_STRING( + (PyStringObject *)value)); + if (need_decref) + Py_DECREF(value); + break; + } + case REG_MULTI_SZ: + { + DWORD size = 0; + char *P; + PyObject **obs = NULL; + + if (value == Py_None) + i = 0; + else { + if (!PyList_Check(value)) + return FALSE; + i = PyList_Size(value); + } + obs = malloc(sizeof(PyObject *) * i); + memset(obs, 0, sizeof(PyObject *) * i); + for (j = 0; j < i; j++) + { + PyObject *t; + t = PyList_GET_ITEM( + (PyListObject *)value,j); + if (PyString_Check(t)) { + obs[j] = t; + Py_INCREF(t); + } else if (PyUnicode_Check(t)) { + obs[j] = PyUnicode_AsEncodedString( + t, + "mbcs", + NULL); + if (obs[j]==NULL) + goto reg_multi_fail; + } else + goto reg_multi_fail; + size += 1 + strlen( + PyString_AS_STRING( + (PyStringObject *)obs[j])); + } + + *retDataSize = size + 1; + *retDataBuf = (BYTE *)PyMem_NEW(char, + *retDataSize); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + goto reg_multi_fail; + } + P = (char *)*retDataBuf; + + for (j = 0; j < i; j++) + { + PyObject *t; + t = obs[j]; + strcpy(P, + PyString_AS_STRING( + (PyStringObject *)t)); + P += 1 + strlen( + PyString_AS_STRING( + (PyStringObject *)t)); + Py_DECREF(obs[j]); + } + /* And doubly-terminate the list... */ + *P = '\0'; + free(obs); + break; + reg_multi_fail: + if (obs) { + for (j = 0; j < i; j++) + Py_XDECREF(obs[j]); + + free(obs); + } + return FALSE; + } + case REG_BINARY: + /* ALSO handle ALL unknown data types here. Even if we can't + support it natively, we should handle the bits. */ + default: + if (value == Py_None) + *retDataSize = 0; + else { + void *src_buf; + PyBufferProcs *pb = value->ob_type->tp_as_buffer; + if (pb==NULL) { + PyErr_Format(PyExc_TypeError, + "Objects of type '%s' can not " + "be used as binary registry values", + value->ob_type->tp_name); + return FALSE; + } + *retDataSize = (*pb->bf_getreadbuffer)(value, 0, &src_buf); + *retDataBuf = (BYTE *)PyMem_NEW(char, + *retDataSize); + if (*retDataBuf==NULL){ + PyErr_NoMemory(); + return FALSE; + } + memcpy(*retDataBuf, src_buf, *retDataSize); + } + break; + } + return TRUE; } /* Convert Registry data into PyObject*/ static PyObject * Reg2Py(char *retDataBuf, DWORD retDataSize, DWORD typ) { - PyObject *obData; - - switch (typ) { - case REG_DWORD: - if (retDataSize == 0) - obData = Py_BuildValue("i", 0); - else - obData = Py_BuildValue("i", - *(int *)retDataBuf); - break; - case REG_SZ: - case REG_EXPAND_SZ: - /* retDataBuf may or may not have a trailing NULL in - the buffer. */ - if (retDataSize && retDataBuf[retDataSize-1] == '\0') - --retDataSize; - if (retDataSize ==0) - retDataBuf = ""; - obData = PyUnicode_DecodeMBCS(retDataBuf, - retDataSize, - NULL); - break; - case REG_MULTI_SZ: - if (retDataSize == 0) - obData = PyList_New(0); - else - { - int index = 0; - int s = countStrings(retDataBuf, retDataSize); - char **str = (char **)malloc(sizeof(char *)*s); - if (str == NULL) - return PyErr_NoMemory(); - - fixupMultiSZ(str, retDataBuf, retDataSize); - obData = PyList_New(s); - if (obData == NULL) - return NULL; - for (index = 0; index < s; index++) - { - size_t len = _mbstrlen(str[index]); - if (len > INT_MAX) { - PyErr_SetString(PyExc_OverflowError, - "registry string is too long for a Python string"); - Py_DECREF(obData); - return NULL; - } - PyList_SetItem(obData, - index, - PyUnicode_DecodeMBCS( - (const char *)str[index], - (int)len, - NULL) - ); - } - free(str); - - break; - } - case REG_BINARY: - /* ALSO handle ALL unknown data types here. Even if we can't - support it natively, we should handle the bits. */ - default: - if (retDataSize == 0) { - Py_INCREF(Py_None); - obData = Py_None; - } - else - obData = Py_BuildValue("s#", - (char *)retDataBuf, - retDataSize); - break; - } - if (obData == NULL) - return NULL; - else - return obData; + PyObject *obData; + + switch (typ) { + case REG_DWORD: + if (retDataSize == 0) + obData = Py_BuildValue("i", 0); + else + obData = Py_BuildValue("i", + *(int *)retDataBuf); + break; + case REG_SZ: + case REG_EXPAND_SZ: + /* retDataBuf may or may not have a trailing NULL in + the buffer. */ + if (retDataSize && retDataBuf[retDataSize-1] == '\0') + --retDataSize; + if (retDataSize ==0) + retDataBuf = ""; + obData = PyUnicode_DecodeMBCS(retDataBuf, + retDataSize, + NULL); + break; + case REG_MULTI_SZ: + if (retDataSize == 0) + obData = PyList_New(0); + else + { + int index = 0; + int s = countStrings(retDataBuf, retDataSize); + char **str = (char **)malloc(sizeof(char *)*s); + if (str == NULL) + return PyErr_NoMemory(); + + fixupMultiSZ(str, retDataBuf, retDataSize); + obData = PyList_New(s); + if (obData == NULL) + return NULL; + for (index = 0; index < s; index++) + { + size_t len = _mbstrlen(str[index]); + if (len > INT_MAX) { + PyErr_SetString(PyExc_OverflowError, + "registry string is too long for a Python string"); + Py_DECREF(obData); + return NULL; + } + PyList_SetItem(obData, + index, + PyUnicode_DecodeMBCS( + (const char *)str[index], + (int)len, + NULL) + ); + } + free(str); + + break; + } + case REG_BINARY: + /* ALSO handle ALL unknown data types here. Even if we can't + support it natively, we should handle the bits. */ + default: + if (retDataSize == 0) { + Py_INCREF(Py_None); + obData = Py_None; + } + else + obData = Py_BuildValue("s#", + (char *)retDataBuf, + retDataSize); + break; + } + if (obData == NULL) + return NULL; + else + return obData; } /* The Python methods */ @@ -995,344 +995,344 @@ Reg2Py(char *retDataBuf, DWORD retDataSize, DWORD typ) static PyObject * PyCloseKey(PyObject *self, PyObject *args) { - PyObject *obKey; - if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey)) - return NULL; - if (!PyHKEY_Close(obKey)) - return NULL; - Py_INCREF(Py_None); - return Py_None; + PyObject *obKey; + if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey)) + return NULL; + if (!PyHKEY_Close(obKey)) + return NULL; + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyConnectRegistry(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - char *szCompName = NULL; - HKEY retKey; - long rc; - if (!PyArg_ParseTuple(args, "zO:ConnectRegistry", &szCompName, &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegConnectRegistry(szCompName, hKey, &retKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "ConnectRegistry"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + char *szCompName = NULL; + HKEY retKey; + long rc; + if (!PyArg_ParseTuple(args, "zO:ConnectRegistry", &szCompName, &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegConnectRegistry(szCompName, hKey, &retKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "ConnectRegistry"); + return PyHKEY_FromHKEY(retKey); } static PyObject * PyCreateKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - char *subKey; - HKEY retKey; - long rc; - if (!PyArg_ParseTuple(args, "Oz:CreateKey", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - rc = RegCreateKey(hKey, subKey, &retKey); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + char *subKey; + HKEY retKey; + long rc; + if (!PyArg_ParseTuple(args, "Oz:CreateKey", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + rc = RegCreateKey(hKey, subKey, &retKey); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey"); + return PyHKEY_FromHKEY(retKey); } static PyObject * PyCreateKeyEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - char *subKey; - HKEY retKey; - int res = 0; - REGSAM sam = KEY_WRITE; - long rc; - if (!PyArg_ParseTuple(args, "Oz|ii:CreateKeyEx", &obKey, &subKey, - &res, &sam)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - rc = RegCreateKeyEx(hKey, subKey, res, NULL, (DWORD)NULL, - sam, NULL, &retKey, NULL); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + char *subKey; + HKEY retKey; + int res = 0; + REGSAM sam = KEY_WRITE; + long rc; + if (!PyArg_ParseTuple(args, "Oz|ii:CreateKeyEx", &obKey, &subKey, + &res, &sam)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + rc = RegCreateKeyEx(hKey, subKey, res, NULL, (DWORD)NULL, + sam, NULL, &retKey, NULL); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx"); + return PyHKEY_FromHKEY(retKey); } static PyObject * PyDeleteKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - char *subKey; - long rc; - if (!PyArg_ParseTuple(args, "Os:DeleteKey", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - rc = RegDeleteKey(hKey, subKey ); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + char *subKey; + long rc; + if (!PyArg_ParseTuple(args, "Os:DeleteKey", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + rc = RegDeleteKey(hKey, subKey ); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyDeleteKeyEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RDKEFunc)(HKEY, const char*, REGSAM, int); - RDKEFunc pfn = NULL; - char *subKey; - long rc; - int res = 0; - REGSAM sam = KEY_WOW64_64KEY; - - if (!PyArg_ParseTuple(args, "Os|ii:DeleteKeyEx", - &obKey, &subKey, &sam, &res)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically. */ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RDKEFunc)GetProcAddress(hMod, - "RegDeleteKeyExA"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey, subKey, sam, res); - Py_END_ALLOW_THREADS - - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RDKEFunc)(HKEY, const char*, REGSAM, int); + RDKEFunc pfn = NULL; + char *subKey; + long rc; + int res = 0; + REGSAM sam = KEY_WOW64_64KEY; + + if (!PyArg_ParseTuple(args, "Os|ii:DeleteKeyEx", + &obKey, &subKey, &sam, &res)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically. */ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RDKEFunc)GetProcAddress(hMod, + "RegDeleteKeyExA"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey, subKey, sam, res); + Py_END_ALLOW_THREADS + + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyDeleteValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - char *subKey; - long rc; - if (!PyArg_ParseTuple(args, "Oz:DeleteValue", &obKey, &subKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegDeleteValue(hKey, subKey); - Py_END_ALLOW_THREADS - if (rc !=ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegDeleteValue"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + char *subKey; + long rc; + if (!PyArg_ParseTuple(args, "Oz:DeleteValue", &obKey, &subKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegDeleteValue(hKey, subKey); + Py_END_ALLOW_THREADS + if (rc !=ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegDeleteValue"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyEnumKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - int index; - long rc; - PyObject *retStr; - char tmpbuf[256]; /* max key name length is 255 */ - DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ - - if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rc = RegEnumKeyEx(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx"); - - retStr = PyString_FromStringAndSize(tmpbuf, len); - return retStr; /* can be NULL */ + HKEY hKey; + PyObject *obKey; + int index; + long rc; + PyObject *retStr; + char tmpbuf[256]; /* max key name length is 255 */ + DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ + + if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rc = RegEnumKeyEx(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx"); + + retStr = PyString_FromStringAndSize(tmpbuf, len); + return retStr; /* can be NULL */ } static PyObject * PyEnumValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - int index; - long rc; - char *retValueBuf; - char *retDataBuf; - DWORD retValueSize; - DWORD retDataSize; - DWORD typ; - PyObject *obData; - PyObject *retVal; - - if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - if ((rc = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL, - NULL, - &retValueSize, &retDataSize, NULL, NULL)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryInfoKey"); - ++retValueSize; /* include null terminators */ - ++retDataSize; - retValueBuf = (char *)PyMem_Malloc(retValueSize); - if (retValueBuf == NULL) - return PyErr_NoMemory(); - retDataBuf = (char *)PyMem_Malloc(retDataSize); - if (retDataBuf == NULL) { - PyMem_Free(retValueBuf); - return PyErr_NoMemory(); - } - - Py_BEGIN_ALLOW_THREADS - rc = RegEnumValue(hKey, - index, - retValueBuf, - &retValueSize, - NULL, - &typ, - (BYTE *)retDataBuf, - &retDataSize); - Py_END_ALLOW_THREADS - - if (rc != ERROR_SUCCESS) { - retVal = PyErr_SetFromWindowsErrWithFunction(rc, - "PyRegEnumValue"); - goto fail; - } - obData = Reg2Py(retDataBuf, retDataSize, typ); - if (obData == NULL) { - retVal = NULL; - goto fail; - } - retVal = Py_BuildValue("sOi", retValueBuf, obData, typ); - Py_DECREF(obData); + HKEY hKey; + PyObject *obKey; + int index; + long rc; + char *retValueBuf; + char *retDataBuf; + DWORD retValueSize; + DWORD retDataSize; + DWORD typ; + PyObject *obData; + PyObject *retVal; + + if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + if ((rc = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL, + NULL, + &retValueSize, &retDataSize, NULL, NULL)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryInfoKey"); + ++retValueSize; /* include null terminators */ + ++retDataSize; + retValueBuf = (char *)PyMem_Malloc(retValueSize); + if (retValueBuf == NULL) + return PyErr_NoMemory(); + retDataBuf = (char *)PyMem_Malloc(retDataSize); + if (retDataBuf == NULL) { + PyMem_Free(retValueBuf); + return PyErr_NoMemory(); + } + + Py_BEGIN_ALLOW_THREADS + rc = RegEnumValue(hKey, + index, + retValueBuf, + &retValueSize, + NULL, + &typ, + (BYTE *)retDataBuf, + &retDataSize); + Py_END_ALLOW_THREADS + + if (rc != ERROR_SUCCESS) { + retVal = PyErr_SetFromWindowsErrWithFunction(rc, + "PyRegEnumValue"); + goto fail; + } + obData = Reg2Py(retDataBuf, retDataSize, typ); + if (obData == NULL) { + retVal = NULL; + goto fail; + } + retVal = Py_BuildValue("sOi", retValueBuf, obData, typ); + Py_DECREF(obData); fail: - PyMem_Free(retValueBuf); - PyMem_Free(retDataBuf); - return retVal; + PyMem_Free(retValueBuf); + PyMem_Free(retDataBuf); + return retVal; } static PyObject * PyExpandEnvironmentStrings(PyObject *self, PyObject *args) { - Py_UNICODE *retValue = NULL; - Py_UNICODE *src; - DWORD retValueSize; - DWORD rc; - PyObject *o; - - if (!PyArg_ParseTuple(args, "u:ExpandEnvironmentStrings", &src)) - return NULL; - - retValueSize = ExpandEnvironmentStringsW(src, retValue, 0); - if (retValueSize == 0) { - return PyErr_SetFromWindowsErrWithFunction(retValueSize, - "ExpandEnvironmentStrings"); - } - retValue = (Py_UNICODE *)PyMem_Malloc(retValueSize * sizeof(Py_UNICODE)); - if (retValue == NULL) { - return PyErr_NoMemory(); - } - - rc = ExpandEnvironmentStringsW(src, retValue, retValueSize); - if (rc == 0) { - PyMem_Free(retValue); - return PyErr_SetFromWindowsErrWithFunction(retValueSize, - "ExpandEnvironmentStrings"); - } - o = PyUnicode_FromUnicode(retValue, wcslen(retValue)); - PyMem_Free(retValue); - return o; + Py_UNICODE *retValue = NULL; + Py_UNICODE *src; + DWORD retValueSize; + DWORD rc; + PyObject *o; + + if (!PyArg_ParseTuple(args, "u:ExpandEnvironmentStrings", &src)) + return NULL; + + retValueSize = ExpandEnvironmentStringsW(src, retValue, 0); + if (retValueSize == 0) { + return PyErr_SetFromWindowsErrWithFunction(retValueSize, + "ExpandEnvironmentStrings"); + } + retValue = (Py_UNICODE *)PyMem_Malloc(retValueSize * sizeof(Py_UNICODE)); + if (retValue == NULL) { + return PyErr_NoMemory(); + } + + rc = ExpandEnvironmentStringsW(src, retValue, retValueSize); + if (rc == 0) { + PyMem_Free(retValue); + return PyErr_SetFromWindowsErrWithFunction(retValueSize, + "ExpandEnvironmentStrings"); + } + o = PyUnicode_FromUnicode(retValue, wcslen(retValue)); + PyMem_Free(retValue); + return o; } static PyObject * PyFlushKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - long rc; - if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegFlushKey(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + long rc; + if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegFlushKey(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyLoadKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - char *subKey; - char *fileName; - - long rc; - if (!PyArg_ParseTuple(args, "Oss:LoadKey", &obKey, &subKey, &fileName)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - Py_BEGIN_ALLOW_THREADS - rc = RegLoadKey(hKey, subKey, fileName ); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + char *subKey; + char *fileName; + + long rc; + if (!PyArg_ParseTuple(args, "Oss:LoadKey", &obKey, &subKey, &fileName)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + Py_BEGIN_ALLOW_THREADS + rc = RegLoadKey(hKey, subKey, fileName ); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyOpenKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - - char *subKey; - int res = 0; - HKEY retKey; - long rc; - REGSAM sam = KEY_READ; - if (!PyArg_ParseTuple(args, "Oz|ii:OpenKey", &obKey, &subKey, - &res, &sam)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - rc = RegOpenKeyEx(hKey, subKey, res, sam, &retKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx"); - return PyHKEY_FromHKEY(retKey); + HKEY hKey; + PyObject *obKey; + + char *subKey; + int res = 0; + HKEY retKey; + long rc; + REGSAM sam = KEY_READ; + if (!PyArg_ParseTuple(args, "Oz|ii:OpenKey", &obKey, &subKey, + &res, &sam)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + rc = RegOpenKeyEx(hKey, subKey, res, sam, &retKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx"); + return PyHKEY_FromHKEY(retKey); } @@ -1348,18 +1348,18 @@ PyQueryInfoKey(PyObject *self, PyObject *args) PyObject *l; PyObject *ret; if (!PyArg_ParseTuple(args, "O:QueryInfoKey", &obKey)) - return NULL; + return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; + return NULL; if ((rc = RegQueryInfoKey(hKey, NULL, NULL, 0, &nSubKeys, NULL, NULL, - &nValues, NULL, NULL, NULL, &ft)) + &nValues, NULL, NULL, NULL, &ft)) != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey"); + return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey"); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; l = PyLong_FromLongLong(li.QuadPart); if (l == NULL) - return NULL; + return NULL; ret = Py_BuildValue("iiO", nSubKeys, nValues, l); Py_DECREF(l); return ret; @@ -1368,338 +1368,338 @@ PyQueryInfoKey(PyObject *self, PyObject *args) static PyObject * PyQueryValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - char *subKey; - long rc; - PyObject *retStr; - char *retBuf; - long bufSize = 0; - - if (!PyArg_ParseTuple(args, "Oz:QueryValue", &obKey, &subKey)) - return NULL; - - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if ((rc = RegQueryValue(hKey, subKey, NULL, &bufSize)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValue"); - retStr = PyString_FromStringAndSize(NULL, bufSize); - if (retStr == NULL) - return NULL; - retBuf = PyString_AS_STRING(retStr); - if ((rc = RegQueryValue(hKey, subKey, retBuf, &bufSize)) - != ERROR_SUCCESS) { - Py_DECREF(retStr); - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValue"); - } - _PyString_Resize(&retStr, strlen(retBuf)); - return retStr; + HKEY hKey; + PyObject *obKey; + char *subKey; + long rc; + PyObject *retStr; + char *retBuf; + long bufSize = 0; + + if (!PyArg_ParseTuple(args, "Oz:QueryValue", &obKey, &subKey)) + return NULL; + + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if ((rc = RegQueryValue(hKey, subKey, NULL, &bufSize)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValue"); + retStr = PyString_FromStringAndSize(NULL, bufSize); + if (retStr == NULL) + return NULL; + retBuf = PyString_AS_STRING(retStr); + if ((rc = RegQueryValue(hKey, subKey, retBuf, &bufSize)) + != ERROR_SUCCESS) { + Py_DECREF(retStr); + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValue"); + } + _PyString_Resize(&retStr, strlen(retBuf)); + return retStr; } static PyObject * PyQueryValueEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - char *valueName; - - long rc; - char *retBuf; - DWORD bufSize = 0; - DWORD typ; - PyObject *obData; - PyObject *result; - - if (!PyArg_ParseTuple(args, "Oz:QueryValueEx", &obKey, &valueName)) - return NULL; - - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if ((rc = RegQueryValueEx(hKey, valueName, - NULL, NULL, NULL, - &bufSize)) - != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValueEx"); - retBuf = (char *)PyMem_Malloc(bufSize); - if (retBuf == NULL) - return PyErr_NoMemory(); - if ((rc = RegQueryValueEx(hKey, valueName, NULL, - &typ, (BYTE *)retBuf, &bufSize)) - != ERROR_SUCCESS) { - PyMem_Free(retBuf); - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryValueEx"); - } - obData = Reg2Py(retBuf, bufSize, typ); - PyMem_Free((void *)retBuf); - if (obData == NULL) - return NULL; - result = Py_BuildValue("Oi", obData, typ); - Py_DECREF(obData); - return result; + HKEY hKey; + PyObject *obKey; + char *valueName; + + long rc; + char *retBuf; + DWORD bufSize = 0; + DWORD typ; + PyObject *obData; + PyObject *result; + + if (!PyArg_ParseTuple(args, "Oz:QueryValueEx", &obKey, &valueName)) + return NULL; + + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if ((rc = RegQueryValueEx(hKey, valueName, + NULL, NULL, NULL, + &bufSize)) + != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValueEx"); + retBuf = (char *)PyMem_Malloc(bufSize); + if (retBuf == NULL) + return PyErr_NoMemory(); + if ((rc = RegQueryValueEx(hKey, valueName, NULL, + &typ, (BYTE *)retBuf, &bufSize)) + != ERROR_SUCCESS) { + PyMem_Free(retBuf); + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryValueEx"); + } + obData = Reg2Py(retBuf, bufSize, typ); + PyMem_Free((void *)retBuf); + if (obData == NULL) + return NULL; + result = Py_BuildValue("Oi", obData, typ); + Py_DECREF(obData); + return result; } static PyObject * PySaveKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - char *fileName; - LPSECURITY_ATTRIBUTES pSA = NULL; - - long rc; - if (!PyArg_ParseTuple(args, "Os:SaveKey", &obKey, &fileName)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; + HKEY hKey; + PyObject *obKey; + char *fileName; + LPSECURITY_ATTRIBUTES pSA = NULL; + + long rc; + if (!PyArg_ParseTuple(args, "Os:SaveKey", &obKey, &fileName)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; /* One day we may get security into the core? - if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE)) - return NULL; + if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE)) + return NULL; */ - Py_BEGIN_ALLOW_THREADS - rc = RegSaveKey(hKey, fileName, pSA ); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey"); - Py_INCREF(Py_None); - return Py_None; + Py_BEGIN_ALLOW_THREADS + rc = RegSaveKey(hKey, fileName, pSA ); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PySetValue(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - char *subKey; - char *str; - DWORD typ; - DWORD len; - long rc; - PyObject *obStrVal; - PyObject *obSubKey; - if (!PyArg_ParseTuple(args, "OOiO:SetValue", - &obKey, - &obSubKey, - &typ, - &obStrVal)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if (typ != REG_SZ) { - PyErr_SetString(PyExc_TypeError, - "Type must be _winreg.REG_SZ"); - return NULL; - } - /* XXX - need Unicode support */ - str = PyString_AsString(obStrVal); - if (str == NULL) - return NULL; - len = PyString_Size(obStrVal); - if (obSubKey == Py_None) - subKey = NULL; - else { - subKey = PyString_AsString(obSubKey); - if (subKey == NULL) - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = RegSetValue(hKey, subKey, REG_SZ, str, len+1); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + char *subKey; + char *str; + DWORD typ; + DWORD len; + long rc; + PyObject *obStrVal; + PyObject *obSubKey; + if (!PyArg_ParseTuple(args, "OOiO:SetValue", + &obKey, + &obSubKey, + &typ, + &obStrVal)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if (typ != REG_SZ) { + PyErr_SetString(PyExc_TypeError, + "Type must be _winreg.REG_SZ"); + return NULL; + } + /* XXX - need Unicode support */ + str = PyString_AsString(obStrVal); + if (str == NULL) + return NULL; + len = PyString_Size(obStrVal); + if (obSubKey == Py_None) + subKey = NULL; + else { + subKey = PyString_AsString(obSubKey); + if (subKey == NULL) + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = RegSetValue(hKey, subKey, REG_SZ, str, len+1); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PySetValueEx(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - char *valueName; - PyObject *obRes; - PyObject *value; - BYTE *data; - DWORD len; - DWORD typ; - - LONG rc; - - if (!PyArg_ParseTuple(args, "OzOiO:SetValueEx", - &obKey, - &valueName, - &obRes, - &typ, - &value)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - if (!Py2Reg(value, typ, &data, &len)) - { - if (!PyErr_Occurred()) - PyErr_SetString(PyExc_ValueError, - "Could not convert the data to the specified type."); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = RegSetValueEx(hKey, valueName, 0, typ, data, len); - Py_END_ALLOW_THREADS - PyMem_DEL(data); - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegSetValueEx"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + char *valueName; + PyObject *obRes; + PyObject *value; + BYTE *data; + DWORD len; + DWORD typ; + + LONG rc; + + if (!PyArg_ParseTuple(args, "OzOiO:SetValueEx", + &obKey, + &valueName, + &obRes, + &typ, + &value)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + if (!Py2Reg(value, typ, &data, &len)) + { + if (!PyErr_Occurred()) + PyErr_SetString(PyExc_ValueError, + "Could not convert the data to the specified type."); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = RegSetValueEx(hKey, valueName, 0, typ, data, len); + Py_END_ALLOW_THREADS + PyMem_DEL(data); + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegSetValueEx"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyDisableReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RDRKFunc)(HKEY); - RDRKFunc pfn = NULL; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically. */ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RDRKFunc)GetProcAddress(hMod, - "RegDisableReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegDisableReflectionKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RDRKFunc)(HKEY); + RDRKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically. */ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RDRKFunc)GetProcAddress(hMod, + "RegDisableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegDisableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyEnableReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RERKFunc)(HKEY); - RERKFunc pfn = NULL; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically. */ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RERKFunc)GetProcAddress(hMod, - "RegEnableReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegEnableReflectionKey"); - Py_INCREF(Py_None); - return Py_None; + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RERKFunc)(HKEY); + RERKFunc pfn = NULL; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically. */ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RERKFunc)GetProcAddress(hMod, + "RegEnableReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegEnableReflectionKey"); + Py_INCREF(Py_None); + return Py_None; } static PyObject * PyQueryReflectionKey(PyObject *self, PyObject *args) { - HKEY hKey; - PyObject *obKey; - HMODULE hMod; - typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *); - RQRKFunc pfn = NULL; - BOOL result; - LONG rc; - - if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey)) - return NULL; - if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) - return NULL; - - /* Only available on 64bit platforms, so we must load it - dynamically. */ - hMod = GetModuleHandle("advapi32.dll"); - if (hMod) - pfn = (RQRKFunc)GetProcAddress(hMod, - "RegQueryReflectionKey"); - if (!pfn) { - PyErr_SetString(PyExc_NotImplementedError, - "not implemented on this platform"); - return NULL; - } - Py_BEGIN_ALLOW_THREADS - rc = (*pfn)(hKey, &result); - Py_END_ALLOW_THREADS - if (rc != ERROR_SUCCESS) - return PyErr_SetFromWindowsErrWithFunction(rc, - "RegQueryReflectionKey"); - return PyBool_FromLong(result); + HKEY hKey; + PyObject *obKey; + HMODULE hMod; + typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *); + RQRKFunc pfn = NULL; + BOOL result; + LONG rc; + + if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey)) + return NULL; + if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) + return NULL; + + /* Only available on 64bit platforms, so we must load it + dynamically. */ + hMod = GetModuleHandle("advapi32.dll"); + if (hMod) + pfn = (RQRKFunc)GetProcAddress(hMod, + "RegQueryReflectionKey"); + if (!pfn) { + PyErr_SetString(PyExc_NotImplementedError, + "not implemented on this platform"); + return NULL; + } + Py_BEGIN_ALLOW_THREADS + rc = (*pfn)(hKey, &result); + Py_END_ALLOW_THREADS + if (rc != ERROR_SUCCESS) + return PyErr_SetFromWindowsErrWithFunction(rc, + "RegQueryReflectionKey"); + return PyBool_FromLong(result); } static struct PyMethodDef winreg_methods[] = { - {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc}, - {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc}, - {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc}, - {"CreateKeyEx", PyCreateKeyEx, METH_VARARGS, CreateKeyEx_doc}, - {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc}, - {"DeleteKeyEx", PyDeleteKeyEx, METH_VARARGS, DeleteKeyEx_doc}, - {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc}, - {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc}, - {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc}, - {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc}, - {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc}, - {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS, - ExpandEnvironmentStrings_doc }, - {"FlushKey", PyFlushKey, METH_VARARGS, FlushKey_doc}, - {"LoadKey", PyLoadKey, METH_VARARGS, LoadKey_doc}, - {"OpenKey", PyOpenKey, METH_VARARGS, OpenKey_doc}, - {"OpenKeyEx", PyOpenKey, METH_VARARGS, OpenKeyEx_doc}, - {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc}, - {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc}, - {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc}, - {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc}, - {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc}, - {"SetValue", PySetValue, METH_VARARGS, SetValue_doc}, - {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc}, - NULL, + {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc}, + {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc}, + {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc}, + {"CreateKeyEx", PyCreateKeyEx, METH_VARARGS, CreateKeyEx_doc}, + {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc}, + {"DeleteKeyEx", PyDeleteKeyEx, METH_VARARGS, DeleteKeyEx_doc}, + {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc}, + {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc}, + {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc}, + {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc}, + {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc}, + {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS, + ExpandEnvironmentStrings_doc }, + {"FlushKey", PyFlushKey, METH_VARARGS, FlushKey_doc}, + {"LoadKey", PyLoadKey, METH_VARARGS, LoadKey_doc}, + {"OpenKey", PyOpenKey, METH_VARARGS, OpenKey_doc}, + {"OpenKeyEx", PyOpenKey, METH_VARARGS, OpenKeyEx_doc}, + {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc}, + {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc}, + {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc}, + {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc}, + {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc}, + {"SetValue", PySetValue, METH_VARARGS, SetValue_doc}, + {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc}, + NULL, }; static void insint(PyObject * d, char * name, long value) { - PyObject *v = PyInt_FromLong(value); - if (!v || PyDict_SetItemString(d, name, v)) - PyErr_Clear(); - Py_XDECREF(v); + PyObject *v = PyInt_FromLong(value); + if (!v || PyDict_SetItemString(d, name, v)) + PyErr_Clear(); + Py_XDECREF(v); } #define ADD_INT(val) insint(d, #val, val) @@ -1707,89 +1707,89 @@ insint(PyObject * d, char * name, long value) static void inskey(PyObject * d, char * name, HKEY key) { - PyObject *v = PyLong_FromVoidPtr(key); - if (!v || PyDict_SetItemString(d, name, v)) - PyErr_Clear(); - Py_XDECREF(v); + PyObject *v = PyLong_FromVoidPtr(key); + if (!v || PyDict_SetItemString(d, name, v)) + PyErr_Clear(); + Py_XDECREF(v); } #define ADD_KEY(val) inskey(d, #val, val) PyMODINIT_FUNC init_winreg(void) { - PyObject *m, *d; - m = Py_InitModule3("_winreg", winreg_methods, module_doc); - if (m == NULL) - return; - d = PyModule_GetDict(m); - if (PyType_Ready(&PyHKEY_Type) < 0) - return; - PyHKEY_Type.tp_doc = PyHKEY_doc; - Py_INCREF(&PyHKEY_Type); - if (PyDict_SetItemString(d, "HKEYType", - (PyObject *)&PyHKEY_Type) != 0) - return; - Py_INCREF(PyExc_WindowsError); - if (PyDict_SetItemString(d, "error", - PyExc_WindowsError) != 0) - return; - - /* Add the relevant constants */ - ADD_KEY(HKEY_CLASSES_ROOT); - ADD_KEY(HKEY_CURRENT_USER); - ADD_KEY(HKEY_LOCAL_MACHINE); - ADD_KEY(HKEY_USERS); - ADD_KEY(HKEY_PERFORMANCE_DATA); + PyObject *m, *d; + m = Py_InitModule3("_winreg", winreg_methods, module_doc); + if (m == NULL) + return; + d = PyModule_GetDict(m); + if (PyType_Ready(&PyHKEY_Type) < 0) + return; + PyHKEY_Type.tp_doc = PyHKEY_doc; + Py_INCREF(&PyHKEY_Type); + if (PyDict_SetItemString(d, "HKEYType", + (PyObject *)&PyHKEY_Type) != 0) + return; + Py_INCREF(PyExc_WindowsError); + if (PyDict_SetItemString(d, "error", + PyExc_WindowsError) != 0) + return; + + /* Add the relevant constants */ + ADD_KEY(HKEY_CLASSES_ROOT); + ADD_KEY(HKEY_CURRENT_USER); + ADD_KEY(HKEY_LOCAL_MACHINE); + ADD_KEY(HKEY_USERS); + ADD_KEY(HKEY_PERFORMANCE_DATA); #ifdef HKEY_CURRENT_CONFIG - ADD_KEY(HKEY_CURRENT_CONFIG); + ADD_KEY(HKEY_CURRENT_CONFIG); #endif #ifdef HKEY_DYN_DATA - ADD_KEY(HKEY_DYN_DATA); + ADD_KEY(HKEY_DYN_DATA); #endif - ADD_INT(KEY_QUERY_VALUE); - ADD_INT(KEY_SET_VALUE); - ADD_INT(KEY_CREATE_SUB_KEY); - ADD_INT(KEY_ENUMERATE_SUB_KEYS); - ADD_INT(KEY_NOTIFY); - ADD_INT(KEY_CREATE_LINK); - ADD_INT(KEY_READ); - ADD_INT(KEY_WRITE); - ADD_INT(KEY_EXECUTE); - ADD_INT(KEY_ALL_ACCESS); + ADD_INT(KEY_QUERY_VALUE); + ADD_INT(KEY_SET_VALUE); + ADD_INT(KEY_CREATE_SUB_KEY); + ADD_INT(KEY_ENUMERATE_SUB_KEYS); + ADD_INT(KEY_NOTIFY); + ADD_INT(KEY_CREATE_LINK); + ADD_INT(KEY_READ); + ADD_INT(KEY_WRITE); + ADD_INT(KEY_EXECUTE); + ADD_INT(KEY_ALL_ACCESS); #ifdef KEY_WOW64_64KEY - ADD_INT(KEY_WOW64_64KEY); + ADD_INT(KEY_WOW64_64KEY); #endif #ifdef KEY_WOW64_32KEY - ADD_INT(KEY_WOW64_32KEY); + ADD_INT(KEY_WOW64_32KEY); #endif - ADD_INT(REG_OPTION_RESERVED); - ADD_INT(REG_OPTION_NON_VOLATILE); - ADD_INT(REG_OPTION_VOLATILE); - ADD_INT(REG_OPTION_CREATE_LINK); - ADD_INT(REG_OPTION_BACKUP_RESTORE); - ADD_INT(REG_OPTION_OPEN_LINK); - ADD_INT(REG_LEGAL_OPTION); - ADD_INT(REG_CREATED_NEW_KEY); - ADD_INT(REG_OPENED_EXISTING_KEY); - ADD_INT(REG_WHOLE_HIVE_VOLATILE); - ADD_INT(REG_REFRESH_HIVE); - ADD_INT(REG_NO_LAZY_FLUSH); - ADD_INT(REG_NOTIFY_CHANGE_NAME); - ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES); - ADD_INT(REG_NOTIFY_CHANGE_LAST_SET); - ADD_INT(REG_NOTIFY_CHANGE_SECURITY); - ADD_INT(REG_LEGAL_CHANGE_FILTER); - ADD_INT(REG_NONE); - ADD_INT(REG_SZ); - ADD_INT(REG_EXPAND_SZ); - ADD_INT(REG_BINARY); - ADD_INT(REG_DWORD); - ADD_INT(REG_DWORD_LITTLE_ENDIAN); - ADD_INT(REG_DWORD_BIG_ENDIAN); - ADD_INT(REG_LINK); - ADD_INT(REG_MULTI_SZ); - ADD_INT(REG_RESOURCE_LIST); - ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR); - ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST); + ADD_INT(REG_OPTION_RESERVED); + ADD_INT(REG_OPTION_NON_VOLATILE); + ADD_INT(REG_OPTION_VOLATILE); + ADD_INT(REG_OPTION_CREATE_LINK); + ADD_INT(REG_OPTION_BACKUP_RESTORE); + ADD_INT(REG_OPTION_OPEN_LINK); + ADD_INT(REG_LEGAL_OPTION); + ADD_INT(REG_CREATED_NEW_KEY); + ADD_INT(REG_OPENED_EXISTING_KEY); + ADD_INT(REG_WHOLE_HIVE_VOLATILE); + ADD_INT(REG_REFRESH_HIVE); + ADD_INT(REG_NO_LAZY_FLUSH); + ADD_INT(REG_NOTIFY_CHANGE_NAME); + ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES); + ADD_INT(REG_NOTIFY_CHANGE_LAST_SET); + ADD_INT(REG_NOTIFY_CHANGE_SECURITY); + ADD_INT(REG_LEGAL_CHANGE_FILTER); + ADD_INT(REG_NONE); + ADD_INT(REG_SZ); + ADD_INT(REG_EXPAND_SZ); + ADD_INT(REG_BINARY); + ADD_INT(REG_DWORD); + ADD_INT(REG_DWORD_LITTLE_ENDIAN); + ADD_INT(REG_DWORD_BIG_ENDIAN); + ADD_INT(REG_LINK); + ADD_INT(REG_MULTI_SZ); + ADD_INT(REG_RESOURCE_LIST); + ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR); + ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST); } diff --git a/PC/bdist_wininst/archive.h b/PC/bdist_wininst/archive.h index 35d2fd6..31a7805 100644 --- a/PC/bdist_wininst/archive.h +++ b/PC/bdist_wininst/archive.h @@ -14,55 +14,55 @@ */ struct eof_cdir { - long tag; /* must be 0x06054b50 */ - short disknum; - short firstdisk; - short nTotalCDirThis; - short nTotalCDir; - long nBytesCDir; - long ofsCDir; - short commentlen; + long tag; /* must be 0x06054b50 */ + short disknum; + short firstdisk; + short nTotalCDirThis; + short nTotalCDir; + long nBytesCDir; + long ofsCDir; + short commentlen; }; struct cdir { - long tag; /* must be 0x02014b50 */ - short version_made; - short version_extract; - short gp_bitflag; - short comp_method; - short last_mod_file_time; - short last_mod_file_date; - long crc32; - long comp_size; - long uncomp_size; - short fname_length; - short extra_length; - short comment_length; - short disknum_start; - short int_file_attr; - long ext_file_attr; - long ofs_local_header; + long tag; /* must be 0x02014b50 */ + short version_made; + short version_extract; + short gp_bitflag; + short comp_method; + short last_mod_file_time; + short last_mod_file_date; + long crc32; + long comp_size; + long uncomp_size; + short fname_length; + short extra_length; + short comment_length; + short disknum_start; + short int_file_attr; + long ext_file_attr; + long ofs_local_header; }; struct fhdr { - long tag; /* must be 0x04034b50 */ - short version_needed; - short flags; - short method; - short last_mod_file_time; - short last_mod_file_date; - long crc32; - long comp_size; - long uncomp_size; - short fname_length; - short extra_length; + long tag; /* must be 0x04034b50 */ + short version_needed; + short flags; + short method; + short last_mod_file_time; + short last_mod_file_date; + long crc32; + long comp_size; + long uncomp_size; + short fname_length; + short extra_length; }; struct meta_data_hdr { - int tag; - int uncomp_size; - int bitmap_size; + int tag; + int uncomp_size; + int bitmap_size; }; #pragma pack() @@ -70,29 +70,29 @@ struct meta_data_hdr { /* installation scheme */ typedef struct tagSCHEME { - char *name; - char *prefix; + char *name; + char *prefix; } SCHEME; typedef int (*NOTIFYPROC)(int code, LPSTR text, ...); extern BOOL extract_file(char *dst, char *src, int method, int comp_size, - int uncomp_size, NOTIFYPROC notify); + int uncomp_size, NOTIFYPROC notify); extern BOOL unzip_archive(SCHEME *scheme, char *dirname, char *data, - DWORD size, NOTIFYPROC notify); + DWORD size, NOTIFYPROC notify); extern char * map_new_file(DWORD flags, char *filename, char - *pathname_part, int size, - WORD wFatDate, WORD wFatTime, - NOTIFYPROC callback); + *pathname_part, int size, + WORD wFatDate, WORD wFatTime, + NOTIFYPROC callback); extern BOOL ensure_directory (char *pathname, char *new_part, - NOTIFYPROC callback); + NOTIFYPROC callback); /* codes for NOITIFYPROC */ #define DIR_CREATED 1 diff --git a/PC/bdist_wininst/extract.c b/PC/bdist_wininst/extract.c index b495e1c..fc2d2b9 100644 --- a/PC/bdist_wininst/extract.c +++ b/PC/bdist_wininst/extract.c @@ -19,181 +19,181 @@ /* Convert unix-path to dos-path */ static void normpath(char *path) { - while (path && *path) { - if (*path == '/') - *path = '\\'; - ++path; - } + while (path && *path) { + if (*path == '/') + *path = '\\'; + ++path; + } } BOOL ensure_directory(char *pathname, char *new_part, NOTIFYPROC notify) { - while (new_part && *new_part && (new_part = strchr(new_part, '\\'))) { - DWORD attr; - *new_part = '\0'; - attr = GetFileAttributes(pathname); - if (attr == -1) { - /* nothing found */ - if (!CreateDirectory(pathname, NULL) && notify) - notify(SYSTEM_ERROR, - "CreateDirectory (%s)", pathname); - else - notify(DIR_CREATED, pathname); - } - if (attr & FILE_ATTRIBUTE_DIRECTORY) { - ; - } else { - SetLastError(183); - if (notify) - notify(SYSTEM_ERROR, - "CreateDirectory (%s)", pathname); - } - *new_part = '\\'; - ++new_part; - } - return TRUE; + while (new_part && *new_part && (new_part = strchr(new_part, '\\'))) { + DWORD attr; + *new_part = '\0'; + attr = GetFileAttributes(pathname); + if (attr == -1) { + /* nothing found */ + if (!CreateDirectory(pathname, NULL) && notify) + notify(SYSTEM_ERROR, + "CreateDirectory (%s)", pathname); + else + notify(DIR_CREATED, pathname); + } + if (attr & FILE_ATTRIBUTE_DIRECTORY) { + ; + } else { + SetLastError(183); + if (notify) + notify(SYSTEM_ERROR, + "CreateDirectory (%s)", pathname); + } + *new_part = '\\'; + ++new_part; + } + return TRUE; } /* XXX Should better explicitely specify * uncomp_size and file_times instead of pfhdr! */ char *map_new_file(DWORD flags, char *filename, - char *pathname_part, int size, - WORD wFatDate, WORD wFatTime, - NOTIFYPROC notify) + char *pathname_part, int size, + WORD wFatDate, WORD wFatTime, + NOTIFYPROC notify) { - HANDLE hFile, hFileMapping; - char *dst; - FILETIME ft; + HANDLE hFile, hFileMapping; + char *dst; + FILETIME ft; try_again: - if (!flags) - flags = CREATE_NEW; - hFile = CreateFile(filename, - GENERIC_WRITE | GENERIC_READ, - 0, NULL, - flags, - FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) { - DWORD x = GetLastError(); - switch (x) { - case ERROR_FILE_EXISTS: - if (notify && notify(CAN_OVERWRITE, filename)) - hFile = CreateFile(filename, - GENERIC_WRITE|GENERIC_READ, - 0, NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - else { - if (notify) - notify(FILE_OVERWRITTEN, filename); - return NULL; - } - break; - case ERROR_PATH_NOT_FOUND: - if (ensure_directory(filename, pathname_part, notify)) - goto try_again; - else - return FALSE; - break; - default: - SetLastError(x); - break; - } - } - if (hFile == INVALID_HANDLE_VALUE) { - if (notify) - notify (SYSTEM_ERROR, "CreateFile (%s)", filename); - return NULL; - } - - if (notify) - notify(FILE_CREATED, filename); - - DosDateTimeToFileTime(wFatDate, wFatTime, &ft); - SetFileTime(hFile, &ft, &ft, &ft); - - - if (size == 0) { - /* We cannot map a zero-length file (Also it makes - no sense */ - CloseHandle(hFile); - return NULL; - } - - hFileMapping = CreateFileMapping(hFile, - NULL, PAGE_READWRITE, 0, size, NULL); - - CloseHandle(hFile); - - if (hFileMapping == INVALID_HANDLE_VALUE) { - if (notify) - notify(SYSTEM_ERROR, - "CreateFileMapping (%s)", filename); - return NULL; - } - - dst = MapViewOfFile(hFileMapping, - FILE_MAP_WRITE, 0, 0, 0); - - CloseHandle(hFileMapping); - - if (!dst) { - if (notify) - notify(SYSTEM_ERROR, "MapViewOfFile (%s)", filename); - return NULL; - } - return dst; + if (!flags) + flags = CREATE_NEW; + hFile = CreateFile(filename, + GENERIC_WRITE | GENERIC_READ, + 0, NULL, + flags, + FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) { + DWORD x = GetLastError(); + switch (x) { + case ERROR_FILE_EXISTS: + if (notify && notify(CAN_OVERWRITE, filename)) + hFile = CreateFile(filename, + GENERIC_WRITE|GENERIC_READ, + 0, NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + NULL); + else { + if (notify) + notify(FILE_OVERWRITTEN, filename); + return NULL; + } + break; + case ERROR_PATH_NOT_FOUND: + if (ensure_directory(filename, pathname_part, notify)) + goto try_again; + else + return FALSE; + break; + default: + SetLastError(x); + break; + } + } + if (hFile == INVALID_HANDLE_VALUE) { + if (notify) + notify (SYSTEM_ERROR, "CreateFile (%s)", filename); + return NULL; + } + + if (notify) + notify(FILE_CREATED, filename); + + DosDateTimeToFileTime(wFatDate, wFatTime, &ft); + SetFileTime(hFile, &ft, &ft, &ft); + + + if (size == 0) { + /* We cannot map a zero-length file (Also it makes + no sense */ + CloseHandle(hFile); + return NULL; + } + + hFileMapping = CreateFileMapping(hFile, + NULL, PAGE_READWRITE, 0, size, NULL); + + CloseHandle(hFile); + + if (hFileMapping == INVALID_HANDLE_VALUE) { + if (notify) + notify(SYSTEM_ERROR, + "CreateFileMapping (%s)", filename); + return NULL; + } + + dst = MapViewOfFile(hFileMapping, + FILE_MAP_WRITE, 0, 0, 0); + + CloseHandle(hFileMapping); + + if (!dst) { + if (notify) + notify(SYSTEM_ERROR, "MapViewOfFile (%s)", filename); + return NULL; + } + return dst; } BOOL extract_file(char *dst, char *src, int method, int comp_size, - int uncomp_size, NOTIFYPROC notify) + int uncomp_size, NOTIFYPROC notify) { - z_stream zstream; - int result; + z_stream zstream; + int result; - if (method == Z_DEFLATED) { - int x; - memset(&zstream, 0, sizeof(zstream)); - zstream.next_in = src; - zstream.avail_in = comp_size+1; - zstream.next_out = dst; - zstream.avail_out = uncomp_size; + if (method == Z_DEFLATED) { + int x; + memset(&zstream, 0, sizeof(zstream)); + zstream.next_in = src; + zstream.avail_in = comp_size+1; + zstream.next_out = dst; + zstream.avail_out = uncomp_size; /* Apparently an undocumented feature of zlib: Set windowsize to negative values to supress the gzip header and be compatible with zip! */ - result = TRUE; - if (Z_OK != (x = inflateInit2(&zstream, -15))) { - if (notify) - notify(ZLIB_ERROR, - "inflateInit2 returns %d", x); - result = FALSE; - goto cleanup; - } - if (Z_STREAM_END != (x = inflate(&zstream, Z_FINISH))) { - if (notify) - notify(ZLIB_ERROR, - "inflate returns %d", x); - result = FALSE; - } - cleanup: - if (Z_OK != (x = inflateEnd(&zstream))) { - if (notify) - notify (ZLIB_ERROR, - "inflateEnd returns %d", x); - result = FALSE; - } - } else if (method == 0) { - memcpy(dst, src, uncomp_size); - result = TRUE; - } else - result = FALSE; - UnmapViewOfFile(dst); - return result; + result = TRUE; + if (Z_OK != (x = inflateInit2(&zstream, -15))) { + if (notify) + notify(ZLIB_ERROR, + "inflateInit2 returns %d", x); + result = FALSE; + goto cleanup; + } + if (Z_STREAM_END != (x = inflate(&zstream, Z_FINISH))) { + if (notify) + notify(ZLIB_ERROR, + "inflate returns %d", x); + result = FALSE; + } + cleanup: + if (Z_OK != (x = inflateEnd(&zstream))) { + if (notify) + notify (ZLIB_ERROR, + "inflateEnd returns %d", x); + result = FALSE; + } + } else if (method == 0) { + memcpy(dst, src, uncomp_size); + result = TRUE; + } else + result = FALSE; + UnmapViewOfFile(dst); + return result; } /* Open a zip-compatible archive and extract all files @@ -201,121 +201,121 @@ extract_file(char *dst, char *src, int method, int comp_size, */ BOOL unzip_archive(SCHEME *scheme, char *dirname, char *data, DWORD size, - NOTIFYPROC notify) + NOTIFYPROC notify) { - int n; - char pathname[MAX_PATH]; - char *new_part; - - /* read the end of central directory record */ - struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof - (struct eof_cdir)]; - - int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - - pe->ofsCDir; - - /* set position to start of central directory */ - int pos = arc_start + pe->ofsCDir; - - /* make sure this is a zip file */ - if (pe->tag != 0x06054b50) - return FALSE; - - /* Loop through the central directory, reading all entries */ - for (n = 0; n < pe->nTotalCDir; ++n) { - int i; - char *fname; - char *pcomp; - char *dst; - struct cdir *pcdir; - struct fhdr *pfhdr; - - pcdir = (struct cdir *)&data[pos]; - pfhdr = (struct fhdr *)&data[pcdir->ofs_local_header + - arc_start]; - - if (pcdir->tag != 0x02014b50) - return FALSE; - if (pfhdr->tag != 0x04034b50) - return FALSE; - pos += sizeof(struct cdir); - fname = (char *)&data[pos]; /* This is not null terminated! */ - pos += pcdir->fname_length + pcdir->extra_length + - pcdir->comment_length; - - pcomp = &data[pcdir->ofs_local_header - + sizeof(struct fhdr) - + arc_start - + pfhdr->fname_length - + pfhdr->extra_length]; - - /* dirname is the Python home directory (prefix) */ - strcpy(pathname, dirname); - if (pathname[strlen(pathname)-1] != '\\') - strcat(pathname, "\\"); - new_part = &pathname[lstrlen(pathname)]; - /* we must now match the first part of the pathname - * in the archive to a component in the installation - * scheme (PURELIB, PLATLIB, HEADERS, SCRIPTS, or DATA) - * and replace this part by the one in the scheme to use - */ - for (i = 0; scheme[i].name; ++i) { - if (0 == strnicmp(scheme[i].name, fname, - strlen(scheme[i].name))) { - char *rest; - int len; - - /* length of the replaced part */ - int namelen = strlen(scheme[i].name); - - strcat(pathname, scheme[i].prefix); - - rest = fname + namelen; - len = pfhdr->fname_length - namelen; - - if ((pathname[strlen(pathname)-1] != '\\') - && (pathname[strlen(pathname)-1] != '/')) - strcat(pathname, "\\"); - /* Now that pathname ends with a separator, - * we must make sure rest does not start with - * an additional one. - */ - if ((rest[0] == '\\') || (rest[0] == '/')) { - ++rest; - --len; - } - - strncat(pathname, rest, len); - goto Done; - } - } - /* no prefix to replace found, go unchanged */ - strncat(pathname, fname, pfhdr->fname_length); - Done: - normpath(pathname); - if (pathname[strlen(pathname)-1] != '\\') { - /* - * The local file header (pfhdr) does not always - * contain the compressed and uncompressed sizes of - * the data depending on bit 3 of the flags field. So - * it seems better to use the data from the central - * directory (pcdir). - */ - dst = map_new_file(0, pathname, new_part, - pcdir->uncomp_size, - pcdir->last_mod_file_date, - pcdir->last_mod_file_time, notify); - if (dst) { - if (!extract_file(dst, pcomp, pfhdr->method, - pcdir->comp_size, - pcdir->uncomp_size, - notify)) - return FALSE; - } /* else ??? */ - } - if (notify) - notify(NUM_FILES, new_part, (int)pe->nTotalCDir, - (int)n+1); - } - return TRUE; + int n; + char pathname[MAX_PATH]; + char *new_part; + + /* read the end of central directory record */ + struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof + (struct eof_cdir)]; + + int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - + pe->ofsCDir; + + /* set position to start of central directory */ + int pos = arc_start + pe->ofsCDir; + + /* make sure this is a zip file */ + if (pe->tag != 0x06054b50) + return FALSE; + + /* Loop through the central directory, reading all entries */ + for (n = 0; n < pe->nTotalCDir; ++n) { + int i; + char *fname; + char *pcomp; + char *dst; + struct cdir *pcdir; + struct fhdr *pfhdr; + + pcdir = (struct cdir *)&data[pos]; + pfhdr = (struct fhdr *)&data[pcdir->ofs_local_header + + arc_start]; + + if (pcdir->tag != 0x02014b50) + return FALSE; + if (pfhdr->tag != 0x04034b50) + return FALSE; + pos += sizeof(struct cdir); + fname = (char *)&data[pos]; /* This is not null terminated! */ + pos += pcdir->fname_length + pcdir->extra_length + + pcdir->comment_length; + + pcomp = &data[pcdir->ofs_local_header + + sizeof(struct fhdr) + + arc_start + + pfhdr->fname_length + + pfhdr->extra_length]; + + /* dirname is the Python home directory (prefix) */ + strcpy(pathname, dirname); + if (pathname[strlen(pathname)-1] != '\\') + strcat(pathname, "\\"); + new_part = &pathname[lstrlen(pathname)]; + /* we must now match the first part of the pathname + * in the archive to a component in the installation + * scheme (PURELIB, PLATLIB, HEADERS, SCRIPTS, or DATA) + * and replace this part by the one in the scheme to use + */ + for (i = 0; scheme[i].name; ++i) { + if (0 == strnicmp(scheme[i].name, fname, + strlen(scheme[i].name))) { + char *rest; + int len; + + /* length of the replaced part */ + int namelen = strlen(scheme[i].name); + + strcat(pathname, scheme[i].prefix); + + rest = fname + namelen; + len = pfhdr->fname_length - namelen; + + if ((pathname[strlen(pathname)-1] != '\\') + && (pathname[strlen(pathname)-1] != '/')) + strcat(pathname, "\\"); + /* Now that pathname ends with a separator, + * we must make sure rest does not start with + * an additional one. + */ + if ((rest[0] == '\\') || (rest[0] == '/')) { + ++rest; + --len; + } + + strncat(pathname, rest, len); + goto Done; + } + } + /* no prefix to replace found, go unchanged */ + strncat(pathname, fname, pfhdr->fname_length); + Done: + normpath(pathname); + if (pathname[strlen(pathname)-1] != '\\') { + /* + * The local file header (pfhdr) does not always + * contain the compressed and uncompressed sizes of + * the data depending on bit 3 of the flags field. So + * it seems better to use the data from the central + * directory (pcdir). + */ + dst = map_new_file(0, pathname, new_part, + pcdir->uncomp_size, + pcdir->last_mod_file_date, + pcdir->last_mod_file_time, notify); + if (dst) { + if (!extract_file(dst, pcomp, pfhdr->method, + pcdir->comp_size, + pcdir->uncomp_size, + notify)) + return FALSE; + } /* else ??? */ + } + if (notify) + notify(NUM_FILES, new_part, (int)pe->nTotalCDir, + (int)n+1); + } + return TRUE; } diff --git a/PC/bdist_wininst/install.c b/PC/bdist_wininst/install.c index ae8d0db..d5472ef 100644 --- a/PC/bdist_wininst/install.c +++ b/PC/bdist_wininst/install.c @@ -20,21 +20,21 @@ * * At runtime, the exefile has appended: * - compressed setup-data in ini-format, containing the following sections: - * [metadata] - * author=Greg Ward - * author_email=gward@python.net - * description=Python Distribution Utilities - * licence=Python - * name=Distutils - * url=http://www.python.org/sigs/distutils-sig/ - * version=0.9pre + * [metadata] + * author=Greg Ward + * author_email=gward@python.net + * description=Python Distribution Utilities + * licence=Python + * name=Distutils + * url=http://www.python.org/sigs/distutils-sig/ + * version=0.9pre * - * [Setup] - * info= text to be displayed in the edit-box - * title= to be displayed by this program - * target_version = if present, python version required - * pyc_compile = if 0, do not compile py to pyc - * pyo_compile = if 0, do not compile py to pyo + * [Setup] + * info= text to be displayed in the edit-box + * title= to be displayed by this program + * target_version = if present, python version required + * pyc_compile = if 0, do not compile py to pyc + * pyo_compile = if 0, do not compile py to pyo * * - a struct meta_data_hdr, describing the above * - a zip-file, containing the modules to be installed. @@ -118,28 +118,28 @@ char modulename[MAX_PATH]; HWND hwndMain; HWND hDialog; -char *ini_file; /* Full pathname of ini-file */ +char *ini_file; /* Full pathname of ini-file */ /* From ini-file */ -char info[4096]; /* [Setup] info= */ -char title[80]; /* [Setup] title=, contains package name - including version: "Distutils-1.0.1" */ -char target_version[10]; /* [Setup] target_version=, required python - version or empty string */ -char build_info[80]; /* [Setup] build_info=, distutils version - and build date */ - -char meta_name[80]; /* package name without version like - 'Distutils' */ +char info[4096]; /* [Setup] info= */ +char title[80]; /* [Setup] title=, contains package name + including version: "Distutils-1.0.1" */ +char target_version[10]; /* [Setup] target_version=, required python + version or empty string */ +char build_info[80]; /* [Setup] build_info=, distutils version + and build date */ + +char meta_name[80]; /* package name without version like + 'Distutils' */ char install_script[MAX_PATH]; char *pre_install_script; /* run before we install a single file */ char user_access_control[10]; // one of 'auto', 'force', otherwise none. -int py_major, py_minor; /* Python version selected for installation */ +int py_major, py_minor; /* Python version selected for installation */ -char *arc_data; /* memory mapped archive */ -DWORD arc_size; /* number of bytes in archive */ -int exe_size; /* number of bytes for exe-file portion */ +char *arc_data; /* memory mapped archive */ +DWORD arc_size; /* number of bytes in archive */ +int exe_size; /* number of bytes for exe-file portion */ char python_dir[MAX_PATH]; char pythondll[MAX_PATH]; BOOL pyc_compile, pyo_compile; @@ -147,7 +147,7 @@ BOOL pyc_compile, pyo_compile; the permissions of the current user. */ HKEY hkey_root = (HKEY)-1; -BOOL success; /* Installation successfull? */ +BOOL success; /* Installation successfull? */ char *failure_reason = NULL; HANDLE hBitmap; @@ -165,128 +165,128 @@ static BOOL notify(int code, char *fmt, ...); /* Note: If scheme.prefix is nonempty, it must end with a '\'! */ /* Note: purelib must be the FIRST entry! */ SCHEME old_scheme[] = { - { "PURELIB", "" }, - { "PLATLIB", "" }, - { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ - { "SCRIPTS", "Scripts\\" }, - { "DATA", "" }, - { NULL, NULL }, + { "PURELIB", "" }, + { "PLATLIB", "" }, + { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ + { "SCRIPTS", "Scripts\\" }, + { "DATA", "" }, + { NULL, NULL }, }; SCHEME new_scheme[] = { - { "PURELIB", "Lib\\site-packages\\" }, - { "PLATLIB", "Lib\\site-packages\\" }, - { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ - { "SCRIPTS", "Scripts\\" }, - { "DATA", "" }, - { NULL, NULL }, + { "PURELIB", "Lib\\site-packages\\" }, + { "PLATLIB", "Lib\\site-packages\\" }, + { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */ + { "SCRIPTS", "Scripts\\" }, + { "DATA", "" }, + { NULL, NULL }, }; static void unescape(char *dst, char *src, unsigned size) { - char *eon; - char ch; - - while (src && *src && (size > 2)) { - if (*src == '\\') { - switch (*++src) { - case 'n': - ++src; - *dst++ = '\r'; - *dst++ = '\n'; - size -= 2; - break; - case 'r': - ++src; - *dst++ = '\r'; - --size; - break; - case '0': case '1': case '2': case '3': - ch = (char)strtol(src, &eon, 8); - if (ch == '\n') { - *dst++ = '\r'; - --size; - } - *dst++ = ch; - --size; - src = eon; - } - } else { - *dst++ = *src++; - --size; - } - } - *dst = '\0'; + char *eon; + char ch; + + while (src && *src && (size > 2)) { + if (*src == '\\') { + switch (*++src) { + case 'n': + ++src; + *dst++ = '\r'; + *dst++ = '\n'; + size -= 2; + break; + case 'r': + ++src; + *dst++ = '\r'; + --size; + break; + case '0': case '1': case '2': case '3': + ch = (char)strtol(src, &eon, 8); + if (ch == '\n') { + *dst++ = '\r'; + --size; + } + *dst++ = ch; + --size; + src = eon; + } + } else { + *dst++ = *src++; + --size; + } + } + *dst = '\0'; } static struct tagFile { - char *path; - struct tagFile *next; + char *path; + struct tagFile *next; } *file_list = NULL; static void set_failure_reason(char *reason) { if (failure_reason) - free(failure_reason); + free(failure_reason); failure_reason = strdup(reason); success = FALSE; } static char *get_failure_reason() { if (!failure_reason) - return "Installation failed."; + return "Installation failed."; return failure_reason; } static void add_to_filelist(char *path) { - struct tagFile *p; - p = (struct tagFile *)malloc(sizeof(struct tagFile)); - p->path = strdup(path); - p->next = file_list; - file_list = p; + struct tagFile *p; + p = (struct tagFile *)malloc(sizeof(struct tagFile)); + p->path = strdup(path); + p->next = file_list; + file_list = p; } static int do_compile_files(int (__cdecl * PyRun_SimpleString)(char *), - int optimize) + int optimize) { - struct tagFile *p; - int total, n; - char Buffer[MAX_PATH + 64]; - int errors = 0; - - total = 0; - p = file_list; - while (p) { - ++total; - p = p->next; - } - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETRANGE, 0, - MAKELPARAM(0, total)); - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, 0, 0); - - n = 0; - p = file_list; - while (p) { - ++n; - wsprintf(Buffer, - "import py_compile; py_compile.compile (r'%s')", - p->path); - if (PyRun_SimpleString(Buffer)) { - ++errors; - } - /* We send the notification even if the files could not - * be created so that the uninstaller will remove them - * in case they are created later. - */ - wsprintf(Buffer, "%s%c", p->path, optimize ? 'o' : 'c'); - notify(FILE_CREATED, Buffer); - - SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, n, 0); - SetDlgItemText(hDialog, IDC_INFO, p->path); - p = p->next; - } - return errors; + struct tagFile *p; + int total, n; + char Buffer[MAX_PATH + 64]; + int errors = 0; + + total = 0; + p = file_list; + while (p) { + ++total; + p = p->next; + } + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETRANGE, 0, + MAKELPARAM(0, total)); + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, 0, 0); + + n = 0; + p = file_list; + while (p) { + ++n; + wsprintf(Buffer, + "import py_compile; py_compile.compile (r'%s')", + p->path); + if (PyRun_SimpleString(Buffer)) { + ++errors; + } + /* We send the notification even if the files could not + * be created so that the uninstaller will remove them + * in case they are created later. + */ + wsprintf(Buffer, "%s%c", p->path, optimize ? 'o' : 'c'); + notify(FILE_CREATED, Buffer); + + SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, n, 0); + SetDlgItemText(hDialog, IDC_INFO, p->path); + p = p->next; + } + return errors; } #define DECLPROC(dll, result, name, args)\ @@ -306,47 +306,47 @@ typedef void PyObject; */ static int compile_filelist(HINSTANCE hPython, BOOL optimize_flag) { - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, void, Py_SetProgramName, (char *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, PyObject *, PySys_GetObject, (char *)); - DECLVAR(hPython, int, Py_OptimizeFlag); + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, void, Py_SetProgramName, (char *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, PyObject *, PySys_GetObject, (char *)); + DECLVAR(hPython, int, Py_OptimizeFlag); - int errors = 0; - struct tagFile *p = file_list; + int errors = 0; + struct tagFile *p = file_list; - if (!p) - return 0; + if (!p) + return 0; - if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize) - return -1; + if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize) + return -1; - if (!PyRun_SimpleString || !PySys_GetObject || !Py_OptimizeFlag) - return -1; + if (!PyRun_SimpleString || !PySys_GetObject || !Py_OptimizeFlag) + return -1; - *Py_OptimizeFlag = optimize_flag ? 1 : 0; - Py_SetProgramName(modulename); - Py_Initialize(); + *Py_OptimizeFlag = optimize_flag ? 1 : 0; + Py_SetProgramName(modulename); + Py_Initialize(); - errors += do_compile_files(PyRun_SimpleString, optimize_flag); - Py_Finalize(); + errors += do_compile_files(PyRun_SimpleString, optimize_flag); + Py_Finalize(); - return errors; + return errors; } typedef PyObject *(*PyCFunction)(PyObject *, PyObject *); struct PyMethodDef { - char *ml_name; - PyCFunction ml_meth; - int ml_flags; - char *ml_doc; + char *ml_name; + PyCFunction ml_meth; + int ml_flags; + char *ml_doc; }; typedef struct PyMethodDef PyMethodDef; // XXX - all of these are potentially fragile! We load and unload -// the Python DLL multiple times - so storing functions pointers +// the Python DLL multiple times - so storing functions pointers // is dangerous (although things *look* OK at present) // Better might be to roll prepare_script_environment() into // LoadPythonDll(), and create a new UnloadPythonDLL() which also @@ -363,249 +363,249 @@ PyObject *(*g_PyErr_Format)(PyObject *, char *, ...); #define DEF_CSIDL(name) { name, #name } struct { - int nFolder; - char *name; + int nFolder; + char *name; } csidl_names[] = { - /* Startup menu for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_STARTMENU), - /* Startup menu. */ - DEF_CSIDL(CSIDL_STARTMENU), + /* Startup menu for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_STARTMENU), + /* Startup menu. */ + DEF_CSIDL(CSIDL_STARTMENU), /* DEF_CSIDL(CSIDL_COMMON_APPDATA), */ /* DEF_CSIDL(CSIDL_LOCAL_APPDATA), */ - /* Repository for application-specific data. - Needs Internet Explorer 4.0 */ - DEF_CSIDL(CSIDL_APPDATA), - - /* The desktop for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_DESKTOPDIRECTORY), - /* The desktop. */ - DEF_CSIDL(CSIDL_DESKTOPDIRECTORY), - - /* Startup folder for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_STARTUP), - /* Startup folder. */ - DEF_CSIDL(CSIDL_STARTUP), - - /* Programs item in the start menu for all users. - NT only */ - DEF_CSIDL(CSIDL_COMMON_PROGRAMS), - /* Program item in the user's start menu. */ - DEF_CSIDL(CSIDL_PROGRAMS), + /* Repository for application-specific data. + Needs Internet Explorer 4.0 */ + DEF_CSIDL(CSIDL_APPDATA), + + /* The desktop for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_DESKTOPDIRECTORY), + /* The desktop. */ + DEF_CSIDL(CSIDL_DESKTOPDIRECTORY), + + /* Startup folder for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_STARTUP), + /* Startup folder. */ + DEF_CSIDL(CSIDL_STARTUP), + + /* Programs item in the start menu for all users. + NT only */ + DEF_CSIDL(CSIDL_COMMON_PROGRAMS), + /* Program item in the user's start menu. */ + DEF_CSIDL(CSIDL_PROGRAMS), /* DEF_CSIDL(CSIDL_PROGRAM_FILES_COMMON), */ /* DEF_CSIDL(CSIDL_PROGRAM_FILES), */ - /* Virtual folder containing fonts. */ - DEF_CSIDL(CSIDL_FONTS), + /* Virtual folder containing fonts. */ + DEF_CSIDL(CSIDL_FONTS), }; #define DIM(a) (sizeof(a) / sizeof((a)[0])) static PyObject *FileCreated(PyObject *self, PyObject *args) { - char *path; - if (!g_PyArg_ParseTuple(args, "s", &path)) - return NULL; - notify(FILE_CREATED, path); - return g_Py_BuildValue(""); + char *path; + if (!g_PyArg_ParseTuple(args, "s", &path)) + return NULL; + notify(FILE_CREATED, path); + return g_Py_BuildValue(""); } static PyObject *DirectoryCreated(PyObject *self, PyObject *args) { - char *path; - if (!g_PyArg_ParseTuple(args, "s", &path)) - return NULL; - notify(DIR_CREATED, path); - return g_Py_BuildValue(""); + char *path; + if (!g_PyArg_ParseTuple(args, "s", &path)) + return NULL; + notify(DIR_CREATED, path); + return g_Py_BuildValue(""); } static PyObject *GetSpecialFolderPath(PyObject *self, PyObject *args) { - char *name; - char lpszPath[MAX_PATH]; - int i; - static HRESULT (WINAPI *My_SHGetSpecialFolderPath)(HWND hwnd, - LPTSTR lpszPath, - int nFolder, - BOOL fCreate); - - if (!My_SHGetSpecialFolderPath) { - HINSTANCE hLib = LoadLibrary("shell32.dll"); - if (!hLib) { - g_PyErr_Format(g_PyExc_OSError, - "function not available"); - return NULL; - } - My_SHGetSpecialFolderPath = (BOOL (WINAPI *)(HWND, LPTSTR, - int, BOOL)) - GetProcAddress(hLib, - "SHGetSpecialFolderPathA"); - } - - if (!g_PyArg_ParseTuple(args, "s", &name)) - return NULL; - - if (!My_SHGetSpecialFolderPath) { - g_PyErr_Format(g_PyExc_OSError, "function not available"); - return NULL; - } - - for (i = 0; i < DIM(csidl_names); ++i) { - if (0 == strcmpi(csidl_names[i].name, name)) { - int nFolder; - nFolder = csidl_names[i].nFolder; - if (My_SHGetSpecialFolderPath(NULL, lpszPath, - nFolder, 0)) - return g_Py_BuildValue("s", lpszPath); - else { - g_PyErr_Format(g_PyExc_OSError, - "no such folder (%s)", name); - return NULL; - } - - } - }; - g_PyErr_Format(g_PyExc_ValueError, "unknown CSIDL (%s)", name); - return NULL; + char *name; + char lpszPath[MAX_PATH]; + int i; + static HRESULT (WINAPI *My_SHGetSpecialFolderPath)(HWND hwnd, + LPTSTR lpszPath, + int nFolder, + BOOL fCreate); + + if (!My_SHGetSpecialFolderPath) { + HINSTANCE hLib = LoadLibrary("shell32.dll"); + if (!hLib) { + g_PyErr_Format(g_PyExc_OSError, + "function not available"); + return NULL; + } + My_SHGetSpecialFolderPath = (BOOL (WINAPI *)(HWND, LPTSTR, + int, BOOL)) + GetProcAddress(hLib, + "SHGetSpecialFolderPathA"); + } + + if (!g_PyArg_ParseTuple(args, "s", &name)) + return NULL; + + if (!My_SHGetSpecialFolderPath) { + g_PyErr_Format(g_PyExc_OSError, "function not available"); + return NULL; + } + + for (i = 0; i < DIM(csidl_names); ++i) { + if (0 == strcmpi(csidl_names[i].name, name)) { + int nFolder; + nFolder = csidl_names[i].nFolder; + if (My_SHGetSpecialFolderPath(NULL, lpszPath, + nFolder, 0)) + return g_Py_BuildValue("s", lpszPath); + else { + g_PyErr_Format(g_PyExc_OSError, + "no such folder (%s)", name); + return NULL; + } + + } + }; + g_PyErr_Format(g_PyExc_ValueError, "unknown CSIDL (%s)", name); + return NULL; } static PyObject *CreateShortcut(PyObject *self, PyObject *args) { - char *path; /* path and filename */ - char *description; - char *filename; - - char *arguments = NULL; - char *iconpath = NULL; - int iconindex = 0; - char *workdir = NULL; - - WCHAR wszFilename[MAX_PATH]; - - IShellLink *ps1 = NULL; - IPersistFile *pPf = NULL; - - HRESULT hr; - - hr = CoInitialize(NULL); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "CoInitialize failed, error 0x%x", hr); - goto error; - } - - if (!g_PyArg_ParseTuple(args, "sss|sssi", - &path, &description, &filename, - &arguments, &workdir, &iconpath, &iconindex)) - return NULL; - - hr = CoCreateInstance(&CLSID_ShellLink, - NULL, - CLSCTX_INPROC_SERVER, - &IID_IShellLink, - &ps1); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "CoCreateInstance failed, error 0x%x", hr); - goto error; - } - - hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile, - (void **)&pPf); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "QueryInterface(IPersistFile) error 0x%x", hr); - goto error; - } - - - hr = ps1->lpVtbl->SetPath(ps1, path); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetPath() failed, error 0x%x", hr); - goto error; - } - - hr = ps1->lpVtbl->SetDescription(ps1, description); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetDescription() failed, error 0x%x", hr); - goto error; - } - - if (arguments) { - hr = ps1->lpVtbl->SetArguments(ps1, arguments); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetArguments() error 0x%x", hr); - goto error; - } - } - - if (iconpath) { - hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetIconLocation() error 0x%x", hr); - goto error; - } - } - - if (workdir) { - hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "SetWorkingDirectory() error 0x%x", hr); - goto error; - } - } - - MultiByteToWideChar(CP_ACP, 0, - filename, -1, - wszFilename, MAX_PATH); - - hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE); - if (FAILED(hr)) { - g_PyErr_Format(g_PyExc_OSError, - "Failed to create shortcut '%s' - error 0x%x", filename, hr); - goto error; - } - - pPf->lpVtbl->Release(pPf); - ps1->lpVtbl->Release(ps1); - CoUninitialize(); - return g_Py_BuildValue(""); - + char *path; /* path and filename */ + char *description; + char *filename; + + char *arguments = NULL; + char *iconpath = NULL; + int iconindex = 0; + char *workdir = NULL; + + WCHAR wszFilename[MAX_PATH]; + + IShellLink *ps1 = NULL; + IPersistFile *pPf = NULL; + + HRESULT hr; + + hr = CoInitialize(NULL); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "CoInitialize failed, error 0x%x", hr); + goto error; + } + + if (!g_PyArg_ParseTuple(args, "sss|sssi", + &path, &description, &filename, + &arguments, &workdir, &iconpath, &iconindex)) + return NULL; + + hr = CoCreateInstance(&CLSID_ShellLink, + NULL, + CLSCTX_INPROC_SERVER, + &IID_IShellLink, + &ps1); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "CoCreateInstance failed, error 0x%x", hr); + goto error; + } + + hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile, + (void **)&pPf); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "QueryInterface(IPersistFile) error 0x%x", hr); + goto error; + } + + + hr = ps1->lpVtbl->SetPath(ps1, path); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetPath() failed, error 0x%x", hr); + goto error; + } + + hr = ps1->lpVtbl->SetDescription(ps1, description); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetDescription() failed, error 0x%x", hr); + goto error; + } + + if (arguments) { + hr = ps1->lpVtbl->SetArguments(ps1, arguments); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetArguments() error 0x%x", hr); + goto error; + } + } + + if (iconpath) { + hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetIconLocation() error 0x%x", hr); + goto error; + } + } + + if (workdir) { + hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "SetWorkingDirectory() error 0x%x", hr); + goto error; + } + } + + MultiByteToWideChar(CP_ACP, 0, + filename, -1, + wszFilename, MAX_PATH); + + hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE); + if (FAILED(hr)) { + g_PyErr_Format(g_PyExc_OSError, + "Failed to create shortcut '%s' - error 0x%x", filename, hr); + goto error; + } + + pPf->lpVtbl->Release(pPf); + ps1->lpVtbl->Release(ps1); + CoUninitialize(); + return g_Py_BuildValue(""); + error: - if (pPf) - pPf->lpVtbl->Release(pPf); + if (pPf) + pPf->lpVtbl->Release(pPf); - if (ps1) - ps1->lpVtbl->Release(ps1); + if (ps1) + ps1->lpVtbl->Release(ps1); - CoUninitialize(); + CoUninitialize(); - return NULL; + return NULL; } static PyObject *PyMessageBox(PyObject *self, PyObject *args) { - int rc; - char *text, *caption; - int flags; - if (!g_PyArg_ParseTuple(args, "ssi", &text, &caption, &flags)) - return NULL; - rc = MessageBox(GetFocus(), text, caption, flags); - return g_Py_BuildValue("i", rc); + int rc; + char *text, *caption; + int flags; + if (!g_PyArg_ParseTuple(args, "ssi", &text, &caption, &flags)) + return NULL; + rc = MessageBox(GetFocus(), text, caption, flags); + return g_Py_BuildValue("i", rc); } static PyObject *GetRootHKey(PyObject *self) { - return g_PyLong_FromVoidPtr(hkey_root); + return g_PyLong_FromVoidPtr(hkey_root); } #define METH_VARARGS 0x0001 @@ -613,74 +613,74 @@ static PyObject *GetRootHKey(PyObject *self) typedef PyObject *(*PyCFunction)(PyObject *, PyObject *); PyMethodDef meth[] = { - {"create_shortcut", CreateShortcut, METH_VARARGS, NULL}, - {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL}, - {"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL}, - {"file_created", FileCreated, METH_VARARGS, NULL}, - {"directory_created", DirectoryCreated, METH_VARARGS, NULL}, - {"message_box", PyMessageBox, METH_VARARGS, NULL}, + {"create_shortcut", CreateShortcut, METH_VARARGS, NULL}, + {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL}, + {"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL}, + {"file_created", FileCreated, METH_VARARGS, NULL}, + {"directory_created", DirectoryCreated, METH_VARARGS, NULL}, + {"message_box", PyMessageBox, METH_VARARGS, NULL}, }; static HINSTANCE LoadPythonDll(char *fname) { - char fullpath[_MAX_PATH]; - LONG size = sizeof(fullpath); - char subkey_name[80]; - char buffer[260 + 12]; - HINSTANCE h; - - /* make sure PYTHONHOME is set, to that sys.path is initialized correctly */ - wsprintf(buffer, "PYTHONHOME=%s", python_dir); - _putenv(buffer); - h = LoadLibrary(fname); - if (h) - return h; - wsprintf(subkey_name, - "SOFTWARE\\Python\\PythonCore\\%d.%d\\InstallPath", - py_major, py_minor); - if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER, subkey_name, - fullpath, &size) && - ERROR_SUCCESS != RegQueryValue(HKEY_LOCAL_MACHINE, subkey_name, - fullpath, &size)) - return NULL; - strcat(fullpath, "\\"); - strcat(fullpath, fname); - return LoadLibrary(fullpath); + char fullpath[_MAX_PATH]; + LONG size = sizeof(fullpath); + char subkey_name[80]; + char buffer[260 + 12]; + HINSTANCE h; + + /* make sure PYTHONHOME is set, to that sys.path is initialized correctly */ + wsprintf(buffer, "PYTHONHOME=%s", python_dir); + _putenv(buffer); + h = LoadLibrary(fname); + if (h) + return h; + wsprintf(subkey_name, + "SOFTWARE\\Python\\PythonCore\\%d.%d\\InstallPath", + py_major, py_minor); + if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER, subkey_name, + fullpath, &size) && + ERROR_SUCCESS != RegQueryValue(HKEY_LOCAL_MACHINE, subkey_name, + fullpath, &size)) + return NULL; + strcat(fullpath, "\\"); + strcat(fullpath, fname); + return LoadLibrary(fullpath); } static int prepare_script_environment(HINSTANCE hPython) { - PyObject *mod; - DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *)); - DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *)); - DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *)); - DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *)); - DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); - DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); - DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); - DECLPROC(hPython, PyObject *, PyLong_FromVoidPtr, (void *)); - if (!PyImport_ImportModule || !PyObject_GetAttrString || - !PyObject_SetAttrString || !PyCFunction_New) - return 1; - if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - mod = PyImport_ImportModule("__builtin__"); - if (mod) { - int i; - g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError"); - g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError"); - for (i = 0; i < DIM(meth); ++i) { - PyObject_SetAttrString(mod, meth[i].ml_name, - PyCFunction_New(&meth[i], NULL)); - } - } - g_Py_BuildValue = Py_BuildValue; - g_PyArg_ParseTuple = PyArg_ParseTuple; - g_PyErr_Format = PyErr_Format; - g_PyLong_FromVoidPtr = PyLong_FromVoidPtr; - - return 0; + PyObject *mod; + DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *)); + DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *)); + DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *)); + DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *)); + DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); + DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); + DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); + DECLPROC(hPython, PyObject *, PyLong_FromVoidPtr, (void *)); + if (!PyImport_ImportModule || !PyObject_GetAttrString || + !PyObject_SetAttrString || !PyCFunction_New) + return 1; + if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + mod = PyImport_ImportModule("__builtin__"); + if (mod) { + int i; + g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError"); + g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError"); + for (i = 0; i < DIM(meth); ++i) { + PyObject_SetAttrString(mod, meth[i].ml_name, + PyCFunction_New(&meth[i], NULL)); + } + } + g_Py_BuildValue = Py_BuildValue; + g_PyArg_ParseTuple = PyArg_ParseTuple; + g_PyErr_Format = PyErr_Format; + g_PyLong_FromVoidPtr = PyLong_FromVoidPtr; + + return 0; } /* @@ -696,473 +696,473 @@ static int prepare_script_environment(HINSTANCE hPython) static int do_run_installscript(HINSTANCE hPython, char *pathname, int argc, char **argv) { - int fh, result; - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, int, PySys_SetArgv, (int, char **)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); - DECLPROC(hPython, PyObject *, PyCFunction_New, - (PyMethodDef *, PyObject *)); - DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); - DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); - - if (!Py_Initialize || !PySys_SetArgv - || !PyRun_SimpleString || !Py_Finalize) - return 1; - - if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format) - return 1; - - if (pathname == NULL || pathname[0] == '\0') - return 2; - - fh = open(pathname, _O_RDONLY); - if (-1 == fh) { - fprintf(stderr, "Could not open postinstall-script %s\n", - pathname); - return 3; - } - - SetDlgItemText(hDialog, IDC_INFO, "Running Script..."); - - Py_Initialize(); - - prepare_script_environment(hPython); - PySys_SetArgv(argc, argv); - result = 3; - { - struct _stat statbuf; - if(0 == _fstat(fh, &statbuf)) { - char *script = alloca(statbuf.st_size + 5); - int n = read(fh, script, statbuf.st_size); - if (n > 0) { - script[n] = '\n'; - script[n+1] = 0; - result = PyRun_SimpleString(script); - } - } - } - Py_Finalize(); - - close(fh); - return result; + int fh, result; + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, int, PySys_SetArgv, (int, char **)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...)); + DECLPROC(hPython, PyObject *, PyCFunction_New, + (PyMethodDef *, PyObject *)); + DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...)); + DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *)); + + if (!Py_Initialize || !PySys_SetArgv + || !PyRun_SimpleString || !Py_Finalize) + return 1; + + if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format) + return 1; + + if (pathname == NULL || pathname[0] == '\0') + return 2; + + fh = open(pathname, _O_RDONLY); + if (-1 == fh) { + fprintf(stderr, "Could not open postinstall-script %s\n", + pathname); + return 3; + } + + SetDlgItemText(hDialog, IDC_INFO, "Running Script..."); + + Py_Initialize(); + + prepare_script_environment(hPython); + PySys_SetArgv(argc, argv); + result = 3; + { + struct _stat statbuf; + if(0 == _fstat(fh, &statbuf)) { + char *script = alloca(statbuf.st_size + 5); + int n = read(fh, script, statbuf.st_size); + if (n > 0) { + script[n] = '\n'; + script[n+1] = 0; + result = PyRun_SimpleString(script); + } + } + } + Py_Finalize(); + + close(fh); + return result; } static int run_installscript(char *pathname, int argc, char **argv, char **pOutput) { - HINSTANCE hPython; - int result = 1; - int out_buf_size; - HANDLE redirected, old_stderr, old_stdout; - char *tempname; - - *pOutput = NULL; - - tempname = tempnam(NULL, NULL); - // We use a static CRT while the Python version we load uses - // the CRT from one of various possibile DLLs. As a result we - // need to redirect the standard handles using the API rather - // than the CRT. - redirected = CreateFile( - tempname, - GENERIC_WRITE | GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, - NULL); - old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - old_stderr = GetStdHandle(STD_ERROR_HANDLE); - SetStdHandle(STD_OUTPUT_HANDLE, redirected); - SetStdHandle(STD_ERROR_HANDLE, redirected); - - hPython = LoadPythonDll(pythondll); - if (hPython) { - result = do_run_installscript(hPython, pathname, argc, argv); - FreeLibrary(hPython); - } else { - fprintf(stderr, "*** Could not load Python ***"); - } - SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); - SetStdHandle(STD_ERROR_HANDLE, old_stderr); - out_buf_size = min(GetFileSize(redirected, NULL), 4096); - *pOutput = malloc(out_buf_size+1); - if (*pOutput) { - DWORD nread = 0; - SetFilePointer(redirected, 0, 0, FILE_BEGIN); - ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL); - (*pOutput)[nread] = '\0'; - } - CloseHandle(redirected); - DeleteFile(tempname); - return result; + HINSTANCE hPython; + int result = 1; + int out_buf_size; + HANDLE redirected, old_stderr, old_stdout; + char *tempname; + + *pOutput = NULL; + + tempname = tempnam(NULL, NULL); + // We use a static CRT while the Python version we load uses + // the CRT from one of various possibile DLLs. As a result we + // need to redirect the standard handles using the API rather + // than the CRT. + redirected = CreateFile( + tempname, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_READ, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, + NULL); + old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); + old_stderr = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_OUTPUT_HANDLE, redirected); + SetStdHandle(STD_ERROR_HANDLE, redirected); + + hPython = LoadPythonDll(pythondll); + if (hPython) { + result = do_run_installscript(hPython, pathname, argc, argv); + FreeLibrary(hPython); + } else { + fprintf(stderr, "*** Could not load Python ***"); + } + SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); + SetStdHandle(STD_ERROR_HANDLE, old_stderr); + out_buf_size = min(GetFileSize(redirected, NULL), 4096); + *pOutput = malloc(out_buf_size+1); + if (*pOutput) { + DWORD nread = 0; + SetFilePointer(redirected, 0, 0, FILE_BEGIN); + ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL); + (*pOutput)[nread] = '\0'; + } + CloseHandle(redirected); + DeleteFile(tempname); + return result; } static int do_run_simple_script(HINSTANCE hPython, char *script) { - int rc; - DECLPROC(hPython, void, Py_Initialize, (void)); - DECLPROC(hPython, void, Py_SetProgramName, (char *)); - DECLPROC(hPython, void, Py_Finalize, (void)); - DECLPROC(hPython, int, PyRun_SimpleString, (char *)); - DECLPROC(hPython, void, PyErr_Print, (void)); - - if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize || - !PyRun_SimpleString || !PyErr_Print) - return -1; - - Py_SetProgramName(modulename); - Py_Initialize(); - prepare_script_environment(hPython); - rc = PyRun_SimpleString(script); - if (rc) - PyErr_Print(); - Py_Finalize(); - return rc; + int rc; + DECLPROC(hPython, void, Py_Initialize, (void)); + DECLPROC(hPython, void, Py_SetProgramName, (char *)); + DECLPROC(hPython, void, Py_Finalize, (void)); + DECLPROC(hPython, int, PyRun_SimpleString, (char *)); + DECLPROC(hPython, void, PyErr_Print, (void)); + + if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize || + !PyRun_SimpleString || !PyErr_Print) + return -1; + + Py_SetProgramName(modulename); + Py_Initialize(); + prepare_script_environment(hPython); + rc = PyRun_SimpleString(script); + if (rc) + PyErr_Print(); + Py_Finalize(); + return rc; } static int run_simple_script(char *script) { - int rc; - HINSTANCE hPython; - char *tempname = tempnam(NULL, NULL); - // Redirect output using win32 API - see comments above... - HANDLE redirected = CreateFile( - tempname, - GENERIC_WRITE | GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, - NULL); - HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); - HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE); - SetStdHandle(STD_OUTPUT_HANDLE, redirected); - SetStdHandle(STD_ERROR_HANDLE, redirected); - - hPython = LoadPythonDll(pythondll); - if (!hPython) { - char reason[128]; - wsprintf(reason, "Can't load Python for pre-install script (%d)", GetLastError()); - set_failure_reason(reason); - return -1; - } - rc = do_run_simple_script(hPython, script); - FreeLibrary(hPython); - SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); - SetStdHandle(STD_ERROR_HANDLE, old_stderr); - /* We only care about the output when we fail. If the script works - OK, then we discard it - */ - if (rc) { - int err_buf_size; - char *err_buf; - const char *prefix = "Running the pre-installation script failed\r\n"; - int prefix_len = strlen(prefix); - err_buf_size = GetFileSize(redirected, NULL); - if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway... - err_buf_size = 4096; - err_buf = malloc(prefix_len + err_buf_size + 1); - if (err_buf) { - DWORD n = 0; - strcpy(err_buf, prefix); - SetFilePointer(redirected, 0, 0, FILE_BEGIN); - ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL); - err_buf[prefix_len+n] = '\0'; - set_failure_reason(err_buf); - free(err_buf); - } else { - set_failure_reason("Out of memory!"); - } - } - CloseHandle(redirected); - DeleteFile(tempname); - return rc; + int rc; + HINSTANCE hPython; + char *tempname = tempnam(NULL, NULL); + // Redirect output using win32 API - see comments above... + HANDLE redirected = CreateFile( + tempname, + GENERIC_WRITE | GENERIC_READ, + FILE_SHARE_READ, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH, + NULL); + HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE); + HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_OUTPUT_HANDLE, redirected); + SetStdHandle(STD_ERROR_HANDLE, redirected); + + hPython = LoadPythonDll(pythondll); + if (!hPython) { + char reason[128]; + wsprintf(reason, "Can't load Python for pre-install script (%d)", GetLastError()); + set_failure_reason(reason); + return -1; + } + rc = do_run_simple_script(hPython, script); + FreeLibrary(hPython); + SetStdHandle(STD_OUTPUT_HANDLE, old_stdout); + SetStdHandle(STD_ERROR_HANDLE, old_stderr); + /* We only care about the output when we fail. If the script works + OK, then we discard it + */ + if (rc) { + int err_buf_size; + char *err_buf; + const char *prefix = "Running the pre-installation script failed\r\n"; + int prefix_len = strlen(prefix); + err_buf_size = GetFileSize(redirected, NULL); + if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway... + err_buf_size = 4096; + err_buf = malloc(prefix_len + err_buf_size + 1); + if (err_buf) { + DWORD n = 0; + strcpy(err_buf, prefix); + SetFilePointer(redirected, 0, 0, FILE_BEGIN); + ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL); + err_buf[prefix_len+n] = '\0'; + set_failure_reason(err_buf); + free(err_buf); + } else { + set_failure_reason("Out of memory!"); + } + } + CloseHandle(redirected); + DeleteFile(tempname); + return rc; } static BOOL SystemError(int error, char *msg) { - char Buffer[1024]; - int n; - - if (error) { - LPVOID lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - error, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPSTR)&lpMsgBuf, - 0, - NULL - ); - strncpy(Buffer, lpMsgBuf, sizeof(Buffer)); - LocalFree(lpMsgBuf); - } else - Buffer[0] = '\0'; - n = lstrlen(Buffer); - _snprintf(Buffer+n, sizeof(Buffer)-n, msg); - MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP); - return FALSE; + char Buffer[1024]; + int n; + + if (error) { + LPVOID lpMsgBuf; + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPSTR)&lpMsgBuf, + 0, + NULL + ); + strncpy(Buffer, lpMsgBuf, sizeof(Buffer)); + LocalFree(lpMsgBuf); + } else + Buffer[0] = '\0'; + n = lstrlen(Buffer); + _snprintf(Buffer+n, sizeof(Buffer)-n, msg); + MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP); + return FALSE; } static BOOL notify (int code, char *fmt, ...) { - char Buffer[1024]; - va_list marker; - BOOL result = TRUE; - int a, b; - char *cp; + char Buffer[1024]; + va_list marker; + BOOL result = TRUE; + int a, b; + char *cp; - va_start(marker, fmt); - _vsnprintf(Buffer, sizeof(Buffer), fmt, marker); + va_start(marker, fmt); + _vsnprintf(Buffer, sizeof(Buffer), fmt, marker); - switch (code) { + switch (code) { /* Questions */ - case CAN_OVERWRITE: - break; + case CAN_OVERWRITE: + break; /* Information notification */ - case DIR_CREATED: - if (logfile) - fprintf(logfile, "100 Made Dir: %s\n", fmt); - break; - - case FILE_CREATED: - if (logfile) - fprintf(logfile, "200 File Copy: %s\n", fmt); - goto add_to_filelist_label; - break; - - case FILE_OVERWRITTEN: - if (logfile) - fprintf(logfile, "200 File Overwrite: %s\n", fmt); - add_to_filelist_label: - if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py"))) - add_to_filelist(fmt); - break; + case DIR_CREATED: + if (logfile) + fprintf(logfile, "100 Made Dir: %s\n", fmt); + break; + + case FILE_CREATED: + if (logfile) + fprintf(logfile, "200 File Copy: %s\n", fmt); + goto add_to_filelist_label; + break; + + case FILE_OVERWRITTEN: + if (logfile) + fprintf(logfile, "200 File Overwrite: %s\n", fmt); + add_to_filelist_label: + if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py"))) + add_to_filelist(fmt); + break; /* Error Messages */ - case ZLIB_ERROR: - MessageBox(GetFocus(), Buffer, "Error", - MB_OK | MB_ICONWARNING); - break; - - case SYSTEM_ERROR: - SystemError(GetLastError(), Buffer); - break; - - case NUM_FILES: - a = va_arg(marker, int); - b = va_arg(marker, int); - SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a)); - SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt); - } - va_end(marker); - - return result; + case ZLIB_ERROR: + MessageBox(GetFocus(), Buffer, "Error", + MB_OK | MB_ICONWARNING); + break; + + case SYSTEM_ERROR: + SystemError(GetLastError(), Buffer); + break; + + case NUM_FILES: + a = va_arg(marker, int); + b = va_arg(marker, int); + SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a)); + SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt); + } + va_end(marker); + + return result; } static char *MapExistingFile(char *pathname, DWORD *psize) { - HANDLE hFile, hFileMapping; - DWORD nSizeLow, nSizeHigh; - char *data; - - hFile = CreateFile(pathname, - GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile == INVALID_HANDLE_VALUE) - return NULL; - nSizeLow = GetFileSize(hFile, &nSizeHigh); - hFileMapping = CreateFileMapping(hFile, - NULL, PAGE_READONLY, 0, 0, NULL); - CloseHandle(hFile); - - if (hFileMapping == INVALID_HANDLE_VALUE) - return NULL; - - data = MapViewOfFile(hFileMapping, - FILE_MAP_READ, 0, 0, 0); - - CloseHandle(hFileMapping); - *psize = nSizeLow; - return data; + HANDLE hFile, hFileMapping; + DWORD nSizeLow, nSizeHigh; + char *data; + + hFile = CreateFile(pathname, + GENERIC_READ, FILE_SHARE_READ, NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, NULL); + if (hFile == INVALID_HANDLE_VALUE) + return NULL; + nSizeLow = GetFileSize(hFile, &nSizeHigh); + hFileMapping = CreateFileMapping(hFile, + NULL, PAGE_READONLY, 0, 0, NULL); + CloseHandle(hFile); + + if (hFileMapping == INVALID_HANDLE_VALUE) + return NULL; + + data = MapViewOfFile(hFileMapping, + FILE_MAP_READ, 0, 0, 0); + + CloseHandle(hFileMapping); + *psize = nSizeLow; + return data; } static void create_bitmap(HWND hwnd) { - BITMAPFILEHEADER *bfh; - BITMAPINFO *bi; - HDC hdc; + BITMAPFILEHEADER *bfh; + BITMAPINFO *bi; + HDC hdc; - if (!bitmap_bytes) - return; + if (!bitmap_bytes) + return; - if (hBitmap) - return; + if (hBitmap) + return; - hdc = GetDC(hwnd); + hdc = GetDC(hwnd); - bfh = (BITMAPFILEHEADER *)bitmap_bytes; - bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER)); + bfh = (BITMAPFILEHEADER *)bitmap_bytes; + bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER)); - hBitmap = CreateDIBitmap(hdc, - &bi->bmiHeader, - CBM_INIT, - bitmap_bytes + bfh->bfOffBits, - bi, - DIB_RGB_COLORS); - ReleaseDC(hwnd, hdc); + hBitmap = CreateDIBitmap(hdc, + &bi->bmiHeader, + CBM_INIT, + bitmap_bytes + bfh->bfOffBits, + bi, + DIB_RGB_COLORS); + ReleaseDC(hwnd, hdc); } /* Extract everything we need to begin the installation. Currently this is the INI filename with install data, and the raw pre-install script */ static BOOL ExtractInstallData(char *data, DWORD size, int *pexe_size, - char **out_ini_file, char **out_preinstall_script) + char **out_ini_file, char **out_preinstall_script) { - /* read the end of central directory record */ - struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof - (struct eof_cdir)]; - - int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - - pe->ofsCDir; - - int ofs = arc_start - sizeof (struct meta_data_hdr); - - /* read meta_data info */ - struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs]; - char *src, *dst; - char *ini_file; - char tempdir[MAX_PATH]; - - /* ensure that if we fail, we don't have garbage out pointers */ - *out_ini_file = *out_preinstall_script = NULL; - - if (pe->tag != 0x06054b50) { - return FALSE; - } - - if (pmd->tag != 0x1234567B) { - return SystemError(0, - "Invalid cfgdata magic number (see bdist_wininst.py)"); - } - if (ofs < 0) { - return FALSE; - } - - if (pmd->bitmap_size) { - /* Store pointer to bitmap bytes */ - bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size; - } - - *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size; - - src = ((char *)pmd) - pmd->uncomp_size; - ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */ - if (!ini_file) - return FALSE; - if (!GetTempPath(sizeof(tempdir), tempdir) - || !GetTempFileName(tempdir, "~du", 0, ini_file)) { - SystemError(GetLastError(), - "Could not create temporary file"); - return FALSE; - } - - dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size, - 0, 0, NULL/*notify*/); - if (!dst) - return FALSE; - /* Up to the first \0 is the INI file data. */ - strncpy(dst, src, pmd->uncomp_size); - src += strlen(dst) + 1; - /* Up to next \0 is the pre-install script */ - *out_preinstall_script = strdup(src); - *out_ini_file = ini_file; - UnmapViewOfFile(dst); - return TRUE; + /* read the end of central directory record */ + struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof + (struct eof_cdir)]; + + int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir - + pe->ofsCDir; + + int ofs = arc_start - sizeof (struct meta_data_hdr); + + /* read meta_data info */ + struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs]; + char *src, *dst; + char *ini_file; + char tempdir[MAX_PATH]; + + /* ensure that if we fail, we don't have garbage out pointers */ + *out_ini_file = *out_preinstall_script = NULL; + + if (pe->tag != 0x06054b50) { + return FALSE; + } + + if (pmd->tag != 0x1234567B) { + return SystemError(0, + "Invalid cfgdata magic number (see bdist_wininst.py)"); + } + if (ofs < 0) { + return FALSE; + } + + if (pmd->bitmap_size) { + /* Store pointer to bitmap bytes */ + bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size; + } + + *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size; + + src = ((char *)pmd) - pmd->uncomp_size; + ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */ + if (!ini_file) + return FALSE; + if (!GetTempPath(sizeof(tempdir), tempdir) + || !GetTempFileName(tempdir, "~du", 0, ini_file)) { + SystemError(GetLastError(), + "Could not create temporary file"); + return FALSE; + } + + dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size, + 0, 0, NULL/*notify*/); + if (!dst) + return FALSE; + /* Up to the first \0 is the INI file data. */ + strncpy(dst, src, pmd->uncomp_size); + src += strlen(dst) + 1; + /* Up to next \0 is the pre-install script */ + *out_preinstall_script = strdup(src); + *out_ini_file = ini_file; + UnmapViewOfFile(dst); + return TRUE; } static void PumpMessages(void) { - MSG msg; - while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - TranslateMessage(&msg); - DispatchMessage(&msg); - } + MSG msg; + while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } } LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - HDC hdc; - HFONT hFont; - int h; - PAINTSTRUCT ps; - switch (msg) { - case WM_PAINT: - hdc = BeginPaint(hwnd, &ps); - h = GetSystemMetrics(SM_CYSCREEN) / 10; - hFont = CreateFont(h, 0, 0, 0, 700, TRUE, - 0, 0, 0, 0, 0, 0, 0, "Times Roman"); - hFont = SelectObject(hdc, hFont); - SetBkMode(hdc, TRANSPARENT); - TextOut(hdc, 15, 15, title, strlen(title)); - SetTextColor(hdc, RGB(255, 255, 255)); - TextOut(hdc, 10, 10, title, strlen(title)); - DeleteObject(SelectObject(hdc, hFont)); - EndPaint(hwnd, &ps); - return 0; - } - return DefWindowProc(hwnd, msg, wParam, lParam); + HDC hdc; + HFONT hFont; + int h; + PAINTSTRUCT ps; + switch (msg) { + case WM_PAINT: + hdc = BeginPaint(hwnd, &ps); + h = GetSystemMetrics(SM_CYSCREEN) / 10; + hFont = CreateFont(h, 0, 0, 0, 700, TRUE, + 0, 0, 0, 0, 0, 0, 0, "Times Roman"); + hFont = SelectObject(hdc, hFont); + SetBkMode(hdc, TRANSPARENT); + TextOut(hdc, 15, 15, title, strlen(title)); + SetTextColor(hdc, RGB(255, 255, 255)); + TextOut(hdc, 10, 10, title, strlen(title)); + DeleteObject(SelectObject(hdc, hFont)); + EndPaint(hwnd, &ps); + return 0; + } + return DefWindowProc(hwnd, msg, wParam, lParam); } static HWND CreateBackground(char *title) { - WNDCLASS wc; - HWND hwnd; - char buffer[4096]; - - wc.style = CS_VREDRAW | CS_HREDRAW; - wc.lpfnWndProc = WindowProc; - wc.cbWndExtra = 0; - wc.cbClsExtra = 0; - wc.hInstance = GetModuleHandle(NULL); - wc.hIcon = NULL; - wc.hCursor = LoadCursor(NULL, IDC_ARROW); - wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128)); - wc.lpszMenuName = NULL; - wc.lpszClassName = "SetupWindowClass"; - - if (!RegisterClass(&wc)) - MessageBox(hwndMain, - "Could not register window class", - "Setup.exe", MB_OK); - - wsprintf(buffer, "Setup %s", title); - hwnd = CreateWindow("SetupWindowClass", - buffer, - 0, - 0, 0, - GetSystemMetrics(SM_CXFULLSCREEN), - GetSystemMetrics(SM_CYFULLSCREEN), - NULL, - NULL, - GetModuleHandle(NULL), - NULL); - ShowWindow(hwnd, SW_SHOWMAXIMIZED); - UpdateWindow(hwnd); - return hwnd; + WNDCLASS wc; + HWND hwnd; + char buffer[4096]; + + wc.style = CS_VREDRAW | CS_HREDRAW; + wc.lpfnWndProc = WindowProc; + wc.cbWndExtra = 0; + wc.cbClsExtra = 0; + wc.hInstance = GetModuleHandle(NULL); + wc.hIcon = NULL; + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128)); + wc.lpszMenuName = NULL; + wc.lpszClassName = "SetupWindowClass"; + + if (!RegisterClass(&wc)) + MessageBox(hwndMain, + "Could not register window class", + "Setup.exe", MB_OK); + + wsprintf(buffer, "Setup %s", title); + hwnd = CreateWindow("SetupWindowClass", + buffer, + 0, + 0, 0, + GetSystemMetrics(SM_CXFULLSCREEN), + GetSystemMetrics(SM_CYFULLSCREEN), + NULL, + NULL, + GetModuleHandle(NULL), + NULL); + ShowWindow(hwnd, SW_SHOWMAXIMIZED); + UpdateWindow(hwnd); + return hwnd; } /* @@ -1170,16 +1170,16 @@ static HWND CreateBackground(char *title) */ static void CenterWindow(HWND hwnd) { - RECT rc; - int w, h; - - GetWindowRect(hwnd, &rc); - w = GetSystemMetrics(SM_CXSCREEN); - h = GetSystemMetrics(SM_CYSCREEN); - MoveWindow(hwnd, - (w - (rc.right-rc.left))/2, - (h - (rc.bottom-rc.top))/2, - rc.right-rc.left, rc.bottom-rc.top, FALSE); + RECT rc; + int w, h; + + GetWindowRect(hwnd, &rc); + w = GetSystemMetrics(SM_CXSCREEN); + h = GetSystemMetrics(SM_CYSCREEN); + MoveWindow(hwnd, + (w - (rc.right-rc.left))/2, + (h - (rc.bottom-rc.top))/2, + rc.right-rc.left, rc.bottom-rc.top, FALSE); } #include <prsht.h> @@ -1187,45 +1187,45 @@ static void CenterWindow(HWND hwnd) BOOL CALLBACK IntroDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; - char Buffer[4096]; - - switch (msg) { - case WM_INITDIALOG: - create_bitmap(hwnd); - if(hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - CenterWindow(GetParent(hwnd)); - wsprintf(Buffer, - "This Wizard will install %s on your computer. " - "Click Next to continue " - "or Cancel to exit the Setup Wizard.", - meta_name); - SetDlgItemText(hwnd, IDC_TITLE, Buffer); - SetDlgItemText(hwnd, IDC_INTRO_TEXT, info); - SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info); - return FALSE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: - PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT); - break; - - case PSN_WIZNEXT: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return FALSE; + LPNMHDR lpnm; + char Buffer[4096]; + + switch (msg) { + case WM_INITDIALOG: + create_bitmap(hwnd); + if(hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + CenterWindow(GetParent(hwnd)); + wsprintf(Buffer, + "This Wizard will install %s on your computer. " + "Click Next to continue " + "or Cancel to exit the Setup Wizard.", + meta_name); + SetDlgItemText(hwnd, IDC_TITLE, Buffer); + SetDlgItemText(hwnd, IDC_INTRO_TEXT, info); + SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info); + return FALSE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: + PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT); + break; + + case PSN_WIZNEXT: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return FALSE; } #ifdef USE_OTHER_PYTHON_VERSIONS @@ -1237,133 +1237,133 @@ int bound_image_major; int bound_image_minor; static BOOL __stdcall StatusRoutine(IMAGEHLP_STATUS_REASON reason, - PSTR ImageName, - PSTR DllName, - ULONG Va, - ULONG Parameter) + PSTR ImageName, + PSTR DllName, + ULONG Va, + ULONG Parameter) { - char fname[_MAX_PATH]; - int int_version; - - switch(reason) { - case BindOutOfMemory: - case BindRvaToVaFailed: - case BindNoRoomInImage: - case BindImportProcedureFailed: - break; - - case BindImportProcedure: - case BindForwarder: - case BindForwarderNOT: - case BindImageModified: - case BindExpandFileHeaders: - case BindImageComplete: - case BindSymbolsNotUpdated: - case BindMismatchedSymbols: - case BindImportModuleFailed: - break; - - case BindImportModule: - if (1 == sscanf(DllName, "python%d", &int_version)) { - SearchPath(NULL, DllName, NULL, sizeof(fname), - fname, NULL); - strcpy(bound_image_dll, fname); - bound_image_major = int_version / 10; - bound_image_minor = int_version % 10; - OutputDebugString("BOUND "); - OutputDebugString(fname); - OutputDebugString("\n"); - } - break; - } - return TRUE; + char fname[_MAX_PATH]; + int int_version; + + switch(reason) { + case BindOutOfMemory: + case BindRvaToVaFailed: + case BindNoRoomInImage: + case BindImportProcedureFailed: + break; + + case BindImportProcedure: + case BindForwarder: + case BindForwarderNOT: + case BindImageModified: + case BindExpandFileHeaders: + case BindImageComplete: + case BindSymbolsNotUpdated: + case BindMismatchedSymbols: + case BindImportModuleFailed: + break; + + case BindImportModule: + if (1 == sscanf(DllName, "python%d", &int_version)) { + SearchPath(NULL, DllName, NULL, sizeof(fname), + fname, NULL); + strcpy(bound_image_dll, fname); + bound_image_major = int_version / 10; + bound_image_minor = int_version % 10; + OutputDebugString("BOUND "); + OutputDebugString(fname); + OutputDebugString("\n"); + } + break; + } + return TRUE; } /* */ static LPSTR get_sys_prefix(LPSTR exe, LPSTR dll) { - void (__cdecl * Py_Initialize)(void); - void (__cdecl * Py_SetProgramName)(char *); - void (__cdecl * Py_Finalize)(void); - void* (__cdecl * PySys_GetObject)(char *); - void (__cdecl * PySys_SetArgv)(int, char **); - char* (__cdecl * Py_GetPrefix)(void); - char* (__cdecl * Py_GetPath)(void); - HINSTANCE hPython; - LPSTR prefix = NULL; - int (__cdecl * PyRun_SimpleString)(char *); - - { - char Buffer[256]; - wsprintf(Buffer, "PYTHONHOME=%s", exe); - *strrchr(Buffer, '\\') = '\0'; -// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK); - _putenv(Buffer); - _putenv("PYTHONPATH="); - } - - hPython = LoadLibrary(dll); - if (!hPython) - return NULL; - Py_Initialize = (void (*)(void))GetProcAddress - (hPython,"Py_Initialize"); - - PySys_SetArgv = (void (*)(int, char **))GetProcAddress - (hPython,"PySys_SetArgv"); - - PyRun_SimpleString = (int (*)(char *))GetProcAddress - (hPython,"PyRun_SimpleString"); - - Py_SetProgramName = (void (*)(char *))GetProcAddress - (hPython,"Py_SetProgramName"); - - PySys_GetObject = (void* (*)(char *))GetProcAddress - (hPython,"PySys_GetObject"); - - Py_GetPrefix = (char * (*)(void))GetProcAddress - (hPython,"Py_GetPrefix"); - - Py_GetPath = (char * (*)(void))GetProcAddress - (hPython,"Py_GetPath"); - - Py_Finalize = (void (*)(void))GetProcAddress(hPython, - "Py_Finalize"); - Py_SetProgramName(exe); - Py_Initialize(); - PySys_SetArgv(1, &exe); - - MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK); - MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK); - - Py_Finalize(); - FreeLibrary(hPython); - - return prefix; + void (__cdecl * Py_Initialize)(void); + void (__cdecl * Py_SetProgramName)(char *); + void (__cdecl * Py_Finalize)(void); + void* (__cdecl * PySys_GetObject)(char *); + void (__cdecl * PySys_SetArgv)(int, char **); + char* (__cdecl * Py_GetPrefix)(void); + char* (__cdecl * Py_GetPath)(void); + HINSTANCE hPython; + LPSTR prefix = NULL; + int (__cdecl * PyRun_SimpleString)(char *); + + { + char Buffer[256]; + wsprintf(Buffer, "PYTHONHOME=%s", exe); + *strrchr(Buffer, '\\') = '\0'; +// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK); + _putenv(Buffer); + _putenv("PYTHONPATH="); + } + + hPython = LoadLibrary(dll); + if (!hPython) + return NULL; + Py_Initialize = (void (*)(void))GetProcAddress + (hPython,"Py_Initialize"); + + PySys_SetArgv = (void (*)(int, char **))GetProcAddress + (hPython,"PySys_SetArgv"); + + PyRun_SimpleString = (int (*)(char *))GetProcAddress + (hPython,"PyRun_SimpleString"); + + Py_SetProgramName = (void (*)(char *))GetProcAddress + (hPython,"Py_SetProgramName"); + + PySys_GetObject = (void* (*)(char *))GetProcAddress + (hPython,"PySys_GetObject"); + + Py_GetPrefix = (char * (*)(void))GetProcAddress + (hPython,"Py_GetPrefix"); + + Py_GetPath = (char * (*)(void))GetProcAddress + (hPython,"Py_GetPath"); + + Py_Finalize = (void (*)(void))GetProcAddress(hPython, + "Py_Finalize"); + Py_SetProgramName(exe); + Py_Initialize(); + PySys_SetArgv(1, &exe); + + MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK); + MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK); + + Py_Finalize(); + FreeLibrary(hPython); + + return prefix; } static BOOL CheckPythonExe(LPSTR pathname, LPSTR version, int *pmajor, int *pminor) { - bound_image_dll[0] = '\0'; - if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES, - pathname, - NULL, - NULL, - StatusRoutine)) - return SystemError(0, "Could not bind image"); - if (bound_image_dll[0] == '\0') - return SystemError(0, "Does not seem to be a python executable"); - *pmajor = bound_image_major; - *pminor = bound_image_minor; - if (version && *version) { - char core_version[12]; - wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor); - if (strcmp(version, core_version)) - return SystemError(0, "Wrong Python version"); - } - get_sys_prefix(pathname, bound_image_dll); - return TRUE; + bound_image_dll[0] = '\0'; + if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES, + pathname, + NULL, + NULL, + StatusRoutine)) + return SystemError(0, "Could not bind image"); + if (bound_image_dll[0] == '\0') + return SystemError(0, "Does not seem to be a python executable"); + *pmajor = bound_image_major; + *pminor = bound_image_minor; + if (version && *version) { + char core_version[12]; + wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor); + if (strcmp(version, core_version)) + return SystemError(0, "Wrong Python version"); + } + get_sys_prefix(pathname, bound_image_dll); + return TRUE; } /* @@ -1372,48 +1372,48 @@ CheckPythonExe(LPSTR pathname, LPSTR version, int *pmajor, int *pminor) */ static BOOL GetOtherPythonVersion(HWND hwnd, LPSTR version) { - char vers_name[_MAX_PATH + 80]; - DWORD itemindex; - OPENFILENAME of; - char pathname[_MAX_PATH]; - DWORD result; - - strcpy(pathname, "python.exe"); - - memset(&of, 0, sizeof(of)); - of.lStructSize = sizeof(OPENFILENAME); - of.hwndOwner = GetParent(hwnd); - of.hInstance = NULL; - of.lpstrFilter = "python.exe\0python.exe\0"; - of.lpstrCustomFilter = NULL; - of.nMaxCustFilter = 0; - of.nFilterIndex = 1; - of.lpstrFile = pathname; - of.nMaxFile = sizeof(pathname); - of.lpstrFileTitle = NULL; - of.nMaxFileTitle = 0; - of.lpstrInitialDir = NULL; - of.lpstrTitle = "Python executable"; - of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST; - of.lpstrDefExt = "exe"; - - result = GetOpenFileName(&of); - if (result) { - int major, minor; - if (!CheckPythonExe(pathname, version, &major, &minor)) { - return FALSE; - } - *strrchr(pathname, '\\') = '\0'; - wsprintf(vers_name, "Python Version %d.%d in %s", - major, minor, pathname); - itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1, - (LPARAM)(LPSTR)vers_name); - SendMessage(hwnd, LB_SETCURSEL, itemindex, 0); - SendMessage(hwnd, LB_SETITEMDATA, itemindex, - (LPARAM)(LPSTR)strdup(pathname)); - return TRUE; - } - return FALSE; + char vers_name[_MAX_PATH + 80]; + DWORD itemindex; + OPENFILENAME of; + char pathname[_MAX_PATH]; + DWORD result; + + strcpy(pathname, "python.exe"); + + memset(&of, 0, sizeof(of)); + of.lStructSize = sizeof(OPENFILENAME); + of.hwndOwner = GetParent(hwnd); + of.hInstance = NULL; + of.lpstrFilter = "python.exe\0python.exe\0"; + of.lpstrCustomFilter = NULL; + of.nMaxCustFilter = 0; + of.nFilterIndex = 1; + of.lpstrFile = pathname; + of.nMaxFile = sizeof(pathname); + of.lpstrFileTitle = NULL; + of.nMaxFileTitle = 0; + of.lpstrInitialDir = NULL; + of.lpstrTitle = "Python executable"; + of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST; + of.lpstrDefExt = "exe"; + + result = GetOpenFileName(&of); + if (result) { + int major, minor; + if (!CheckPythonExe(pathname, version, &major, &minor)) { + return FALSE; + } + *strrchr(pathname, '\\') = '\0'; + wsprintf(vers_name, "Python Version %d.%d in %s", + major, minor, pathname); + itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1, + (LPARAM)(LPSTR)vers_name); + SendMessage(hwnd, LB_SETCURSEL, itemindex, 0); + SendMessage(hwnd, LB_SETITEMDATA, itemindex, + (LPARAM)(LPSTR)strdup(pathname)); + return TRUE; + } + return FALSE; } #endif /* USE_OTHER_PYTHON_VERSIONS */ @@ -1430,71 +1430,71 @@ typedef struct _InstalledVersionInfo { */ static BOOL GetPythonVersions(HWND hwnd, HKEY hkRoot, LPSTR version) { - DWORD index = 0; - char core_version[80]; - HKEY hKey; - BOOL result = TRUE; - DWORD bufsize; - - if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot, - "Software\\Python\\PythonCore", - 0, KEY_READ, &hKey)) - return FALSE; - bufsize = sizeof(core_version); - while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index, - core_version, &bufsize, NULL, - NULL, NULL, NULL)) { - char subkey_name[80], vers_name[80]; - int itemindex; - DWORD value_size; - HKEY hk; - - bufsize = sizeof(core_version); - ++index; - if (version && *version && strcmp(version, core_version)) - continue; - - wsprintf(vers_name, "Python Version %s (found in registry)", - core_version); - wsprintf(subkey_name, - "Software\\Python\\PythonCore\\%s\\InstallPath", - core_version); - if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) { - InstalledVersionInfo *ivi = - (InstalledVersionInfo *)malloc(sizeof(InstalledVersionInfo)); - value_size = sizeof(ivi->prefix); - if (ivi && - ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL, - ivi->prefix, &value_size)) { - itemindex = SendMessage(hwnd, LB_ADDSTRING, 0, - (LPARAM)(LPSTR)vers_name); - ivi->hkey = hkRoot; - SendMessage(hwnd, LB_SETITEMDATA, itemindex, - (LPARAM)(LPSTR)ivi); - } - RegCloseKey(hk); - } - } - RegCloseKey(hKey); - return result; + DWORD index = 0; + char core_version[80]; + HKEY hKey; + BOOL result = TRUE; + DWORD bufsize; + + if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot, + "Software\\Python\\PythonCore", + 0, KEY_READ, &hKey)) + return FALSE; + bufsize = sizeof(core_version); + while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index, + core_version, &bufsize, NULL, + NULL, NULL, NULL)) { + char subkey_name[80], vers_name[80]; + int itemindex; + DWORD value_size; + HKEY hk; + + bufsize = sizeof(core_version); + ++index; + if (version && *version && strcmp(version, core_version)) + continue; + + wsprintf(vers_name, "Python Version %s (found in registry)", + core_version); + wsprintf(subkey_name, + "Software\\Python\\PythonCore\\%s\\InstallPath", + core_version); + if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) { + InstalledVersionInfo *ivi = + (InstalledVersionInfo *)malloc(sizeof(InstalledVersionInfo)); + value_size = sizeof(ivi->prefix); + if (ivi && + ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL, + ivi->prefix, &value_size)) { + itemindex = SendMessage(hwnd, LB_ADDSTRING, 0, + (LPARAM)(LPSTR)vers_name); + ivi->hkey = hkRoot; + SendMessage(hwnd, LB_SETITEMDATA, itemindex, + (LPARAM)(LPSTR)ivi); + } + RegCloseKey(hk); + } + } + RegCloseKey(hKey); + return result; } /* Determine if the current user can write to HKEY_LOCAL_MACHINE */ BOOL HasLocalMachinePrivs() { - HKEY hKey; - DWORD result; - static char KeyName[] = - "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; - - result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, - KeyName, - 0, - KEY_CREATE_SUB_KEY, - &hKey); - if (result==0) - RegCloseKey(hKey); - return result==0; + HKEY hKey; + DWORD result; + static char KeyName[] = + "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; + + result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, + KeyName, + 0, + KEY_CREATE_SUB_KEY, + &hKey); + if (result==0) + RegCloseKey(hKey); + return result==0; } // Check the root registry key to use - either HKLM or HKCU. @@ -1507,86 +1507,86 @@ BOOL HasLocalMachinePrivs() // We assume hkey_root is already set to where Python itself is installed. void CheckRootKey(HWND hwnd) { - if (hkey_root==HKEY_CURRENT_USER) { - ; // as above, always install ourself in HKCU too. - } else if (hkey_root==HKEY_LOCAL_MACHINE) { - // Python in HKLM, but we may or may not have permissions there. - // Open the uninstall key with 'create' permissions - if this fails, - // we don't have permission. - if (!HasLocalMachinePrivs()) - hkey_root = HKEY_CURRENT_USER; - } else { - MessageBox(hwnd, "Don't know Python's installation type", - "Strange", MB_OK | MB_ICONSTOP); - /* Default to wherever they can, but preferring HKLM */ - hkey_root = HasLocalMachinePrivs() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; - } + if (hkey_root==HKEY_CURRENT_USER) { + ; // as above, always install ourself in HKCU too. + } else if (hkey_root==HKEY_LOCAL_MACHINE) { + // Python in HKLM, but we may or may not have permissions there. + // Open the uninstall key with 'create' permissions - if this fails, + // we don't have permission. + if (!HasLocalMachinePrivs()) + hkey_root = HKEY_CURRENT_USER; + } else { + MessageBox(hwnd, "Don't know Python's installation type", + "Strange", MB_OK | MB_ICONSTOP); + /* Default to wherever they can, but preferring HKLM */ + hkey_root = HasLocalMachinePrivs() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; + } } /* Return the installation scheme depending on Python version number */ SCHEME *GetScheme(int major, int minor) { - if (major > 2) - return new_scheme; - else if((major == 2) && (minor >= 2)) - return new_scheme; - return old_scheme; + if (major > 2) + return new_scheme; + else if((major == 2) && (minor >= 2)) + return new_scheme; + return old_scheme; } BOOL CALLBACK SelectPythonDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; - - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), - HKEY_LOCAL_MACHINE, target_version); - GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), - HKEY_CURRENT_USER, target_version); - { /* select the last entry which is the highest python - version found */ - int count; - count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCOUNT, 0, 0); - if (count && count != LB_ERR) - SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL, - count-1, 0); - - /* If a specific Python version is required, - * display a prominent notice showing this fact. - */ - if (target_version && target_version[0]) { - char buffer[4096]; - wsprintf(buffer, - "Python %s is required for this package. " - "Select installation to use:", - target_version); - SetDlgItemText(hwnd, IDC_TITLE, buffer); - } - - if (count == 0) { - char Buffer[4096]; - char *msg; - if (target_version && target_version[0]) { - wsprintf(Buffer, - "Python version %s required, which was not found" - " in the registry.", target_version); - msg = Buffer; - } else - msg = "No Python installation found in the registry."; - MessageBox(hwnd, msg, "Cannot install", - MB_OK | MB_ICONSTOP); - } - } - goto UpdateInstallDir; - break; - - case WM_COMMAND: - switch (LOWORD(wParam)) { + LPNMHDR lpnm; + + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), + HKEY_LOCAL_MACHINE, target_version); + GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST), + HKEY_CURRENT_USER, target_version); + { /* select the last entry which is the highest python + version found */ + int count; + count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCOUNT, 0, 0); + if (count && count != LB_ERR) + SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL, + count-1, 0); + + /* If a specific Python version is required, + * display a prominent notice showing this fact. + */ + if (target_version && target_version[0]) { + char buffer[4096]; + wsprintf(buffer, + "Python %s is required for this package. " + "Select installation to use:", + target_version); + SetDlgItemText(hwnd, IDC_TITLE, buffer); + } + + if (count == 0) { + char Buffer[4096]; + char *msg; + if (target_version && target_version[0]) { + wsprintf(Buffer, + "Python version %s required, which was not found" + " in the registry.", target_version); + msg = Buffer; + } else + msg = "No Python installation found in the registry."; + MessageBox(hwnd, msg, "Cannot install", + MB_OK | MB_ICONSTOP); + } + } + goto UpdateInstallDir; + break; + + case WM_COMMAND: + switch (LOWORD(wParam)) { /* case IDC_OTHERPYTHON: if (GetOtherPythonVersion(GetDlgItem(hwnd, IDC_VERSIONS_LIST), @@ -1594,307 +1594,307 @@ SelectPythonDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) goto UpdateInstallDir; break; */ - case IDC_VERSIONS_LIST: - switch (HIWORD(wParam)) { - int id; - case LBN_SELCHANGE: - UpdateInstallDir: - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCURSEL, 0, 0); - if (id == LB_ERR) { - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK); - SetDlgItemText(hwnd, IDC_PATH, ""); - SetDlgItemText(hwnd, IDC_INSTALL_PATH, ""); - strcpy(python_dir, ""); - strcpy(pythondll, ""); - } else { - char *pbuf; - int result; - InstalledVersionInfo *ivi; - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - /* Get the python directory */ - ivi = (InstalledVersionInfo *) - SendDlgItemMessage(hwnd, - IDC_VERSIONS_LIST, - LB_GETITEMDATA, - id, - 0); - hkey_root = ivi->hkey; - strcpy(python_dir, ivi->prefix); - SetDlgItemText(hwnd, IDC_PATH, python_dir); - /* retrieve the python version and pythondll to use */ - result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETTEXTLEN, (WPARAM)id, 0); - pbuf = (char *)malloc(result + 1); - if (pbuf) { - /* guess the name of the python-dll */ - SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETTEXT, (WPARAM)id, - (LPARAM)pbuf); - result = sscanf(pbuf, "Python Version %d.%d", - &py_major, &py_minor); - if (result == 2) { + case IDC_VERSIONS_LIST: + switch (HIWORD(wParam)) { + int id; + case LBN_SELCHANGE: + UpdateInstallDir: + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCURSEL, 0, 0); + if (id == LB_ERR) { + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK); + SetDlgItemText(hwnd, IDC_PATH, ""); + SetDlgItemText(hwnd, IDC_INSTALL_PATH, ""); + strcpy(python_dir, ""); + strcpy(pythondll, ""); + } else { + char *pbuf; + int result; + InstalledVersionInfo *ivi; + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + /* Get the python directory */ + ivi = (InstalledVersionInfo *) + SendDlgItemMessage(hwnd, + IDC_VERSIONS_LIST, + LB_GETITEMDATA, + id, + 0); + hkey_root = ivi->hkey; + strcpy(python_dir, ivi->prefix); + SetDlgItemText(hwnd, IDC_PATH, python_dir); + /* retrieve the python version and pythondll to use */ + result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETTEXTLEN, (WPARAM)id, 0); + pbuf = (char *)malloc(result + 1); + if (pbuf) { + /* guess the name of the python-dll */ + SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETTEXT, (WPARAM)id, + (LPARAM)pbuf); + result = sscanf(pbuf, "Python Version %d.%d", + &py_major, &py_minor); + if (result == 2) { #ifdef _DEBUG - wsprintf(pythondll, "python%d%d_d.dll", - py_major, py_minor); + wsprintf(pythondll, "python%d%d_d.dll", + py_major, py_minor); #else - wsprintf(pythondll, "python%d%d.dll", - py_major, py_minor); + wsprintf(pythondll, "python%d%d.dll", + py_major, py_minor); #endif - } - free(pbuf); - } else - strcpy(pythondll, ""); - /* retrieve the scheme for this version */ - { - char install_path[_MAX_PATH]; - SCHEME *scheme = GetScheme(py_major, py_minor); - strcpy(install_path, python_dir); - if (install_path[strlen(install_path)-1] != '\\') - strcat(install_path, "\\"); - strcat(install_path, scheme[0].prefix); - SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path); - } - } - } - break; - } - return 0; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - int id; - case PSN_SETACTIVE: - id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, - LB_GETCURSEL, 0, 0); - if (id == LB_ERR) - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK); - else - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - break; - - case PSN_WIZNEXT: - break; - - case PSN_WIZFINISH: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + } + free(pbuf); + } else + strcpy(pythondll, ""); + /* retrieve the scheme for this version */ + { + char install_path[_MAX_PATH]; + SCHEME *scheme = GetScheme(py_major, py_minor); + strcpy(install_path, python_dir); + if (install_path[strlen(install_path)-1] != '\\') + strcat(install_path, "\\"); + strcat(install_path, scheme[0].prefix); + SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path); + } + } + } + break; + } + return 0; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + int id; + case PSN_SETACTIVE: + id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, + LB_GETCURSEL, 0, 0); + if (id == LB_ERR) + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK); + else + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + break; + + case PSN_WIZNEXT: + break; + + case PSN_WIZFINISH: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } static BOOL OpenLogfile(char *dir) { - char buffer[_MAX_PATH+1]; - time_t ltime; - struct tm *now; - long result; - HKEY hKey, hSubkey; - char subkey_name[256]; - static char KeyName[] = - "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; - const char *root_name = (hkey_root==HKEY_LOCAL_MACHINE ? - "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER"); - DWORD disposition; - - /* Use Create, as the Uninstall subkey may not exist under HKCU. - Use CreateKeyEx, so we can specify a SAM specifying write access - */ - result = RegCreateKeyEx(hkey_root, - KeyName, - 0, /* reserved */ - NULL, /* class */ - 0, /* options */ - KEY_CREATE_SUB_KEY, /* sam */ - NULL, /* security */ - &hKey, /* result key */ - NULL); /* disposition */ - if (result != ERROR_SUCCESS) { - if (result == ERROR_ACCESS_DENIED) { - /* This should no longer be able to happen - we have already - checked if they have permissions in HKLM, and all users - should have write access to HKCU. - */ - MessageBox(GetFocus(), - "You do not seem to have sufficient access rights\n" - "on this machine to install this software", - NULL, - MB_OK | MB_ICONSTOP); - return FALSE; - } else { - MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK); - } - } - - sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name); - logfile = fopen(buffer, "a"); - time(<ime); - now = localtime(<ime); - strftime(buffer, sizeof(buffer), - "*** Installation started %Y/%m/%d %H:%M ***\n", - localtime(<ime)); - fprintf(logfile, buffer); - fprintf(logfile, "Source: %s\n", modulename); - - /* Root key must be first entry processed by uninstaller. */ - fprintf(logfile, "999 Root Key: %s\n", root_name); - - sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor); - - result = RegCreateKeyEx(hKey, subkey_name, - 0, NULL, 0, - KEY_WRITE, - NULL, - &hSubkey, - &disposition); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK); - - RegCloseKey(hKey); - - if (disposition == REG_CREATED_NEW_KEY) - fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name); - - sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title); - - result = RegSetValueEx(hSubkey, "DisplayName", - 0, - REG_SZ, - buffer, - strlen(buffer)+1); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); - - fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", - KeyName, subkey_name, "DisplayName", buffer); - - { - FILE *fp; - sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name); - fp = fopen(buffer, "wb"); - fwrite(arc_data, exe_size, 1, fp); - fclose(fp); - - sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"", - dir, meta_name, dir, meta_name); - - result = RegSetValueEx(hSubkey, "UninstallString", - 0, - REG_SZ, - buffer, - strlen(buffer)+1); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); - - fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", - KeyName, subkey_name, "UninstallString", buffer); - } - return TRUE; + char buffer[_MAX_PATH+1]; + time_t ltime; + struct tm *now; + long result; + HKEY hKey, hSubkey; + char subkey_name[256]; + static char KeyName[] = + "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; + const char *root_name = (hkey_root==HKEY_LOCAL_MACHINE ? + "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER"); + DWORD disposition; + + /* Use Create, as the Uninstall subkey may not exist under HKCU. + Use CreateKeyEx, so we can specify a SAM specifying write access + */ + result = RegCreateKeyEx(hkey_root, + KeyName, + 0, /* reserved */ + NULL, /* class */ + 0, /* options */ + KEY_CREATE_SUB_KEY, /* sam */ + NULL, /* security */ + &hKey, /* result key */ + NULL); /* disposition */ + if (result != ERROR_SUCCESS) { + if (result == ERROR_ACCESS_DENIED) { + /* This should no longer be able to happen - we have already + checked if they have permissions in HKLM, and all users + should have write access to HKCU. + */ + MessageBox(GetFocus(), + "You do not seem to have sufficient access rights\n" + "on this machine to install this software", + NULL, + MB_OK | MB_ICONSTOP); + return FALSE; + } else { + MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK); + } + } + + sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name); + logfile = fopen(buffer, "a"); + time(<ime); + now = localtime(<ime); + strftime(buffer, sizeof(buffer), + "*** Installation started %Y/%m/%d %H:%M ***\n", + localtime(<ime)); + fprintf(logfile, buffer); + fprintf(logfile, "Source: %s\n", modulename); + + /* Root key must be first entry processed by uninstaller. */ + fprintf(logfile, "999 Root Key: %s\n", root_name); + + sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor); + + result = RegCreateKeyEx(hKey, subkey_name, + 0, NULL, 0, + KEY_WRITE, + NULL, + &hSubkey, + &disposition); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK); + + RegCloseKey(hKey); + + if (disposition == REG_CREATED_NEW_KEY) + fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name); + + sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title); + + result = RegSetValueEx(hSubkey, "DisplayName", + 0, + REG_SZ, + buffer, + strlen(buffer)+1); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); + + fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", + KeyName, subkey_name, "DisplayName", buffer); + + { + FILE *fp; + sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name); + fp = fopen(buffer, "wb"); + fwrite(arc_data, exe_size, 1, fp); + fclose(fp); + + sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"", + dir, meta_name, dir, meta_name); + + result = RegSetValueEx(hSubkey, "UninstallString", + 0, + REG_SZ, + buffer, + strlen(buffer)+1); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK); + + fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n", + KeyName, subkey_name, "UninstallString", buffer); + } + return TRUE; } static void CloseLogfile(void) { - char buffer[_MAX_PATH+1]; - time_t ltime; - struct tm *now; - - time(<ime); - now = localtime(<ime); - strftime(buffer, sizeof(buffer), - "*** Installation finished %Y/%m/%d %H:%M ***\n", - localtime(<ime)); - fprintf(logfile, buffer); - if (logfile) - fclose(logfile); + char buffer[_MAX_PATH+1]; + time_t ltime; + struct tm *now; + + time(<ime); + now = localtime(<ime); + strftime(buffer, sizeof(buffer), + "*** Installation finished %Y/%m/%d %H:%M ***\n", + localtime(<ime)); + fprintf(logfile, buffer); + if (logfile) + fclose(logfile); } BOOL CALLBACK InstallFilesDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; - char Buffer[4096]; - SCHEME *scheme; - - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - wsprintf(Buffer, - "Click Next to begin the installation of %s. " - "If you want to review or change any of your " - " installation settings, click Back. " - "Click Cancel to exit the wizard.", - meta_name); - SetDlgItemText(hwnd, IDC_TITLE, Buffer); - SetDlgItemText(hwnd, IDC_INFO, "Ready to install"); - break; - - case WM_NUMFILES: - SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam); - PumpMessages(); - return TRUE; - - case WM_NEXTFILE: - SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam, - 0); - SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam); - PumpMessages(); - return TRUE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: - PropSheet_SetWizButtons(GetParent(hwnd), - PSWIZB_BACK | PSWIZB_NEXT); - break; - - case PSN_WIZFINISH: - break; - - case PSN_WIZNEXT: - /* Handle a Next button click here */ - hDialog = hwnd; - success = TRUE; - - /* Disable the buttons while we work. Sending CANCELTOCLOSE has - the effect of disabling the cancel button, which is a) as we - do everything synchronously we can't cancel, and b) the next - step is 'finished', when it is too late to cancel anyway. - The next step being 'Finished' means we also don't need to - restore the button state back */ - PropSheet_SetWizButtons(GetParent(hwnd), 0); - SendMessage(GetParent(hwnd), PSM_CANCELTOCLOSE, 0, 0); - /* Make sure the installation directory name ends in a */ - /* backslash */ - if (python_dir[strlen(python_dir)-1] != '\\') - strcat(python_dir, "\\"); - /* Strip the trailing backslash again */ - python_dir[strlen(python_dir)-1] = '\0'; - - CheckRootKey(hwnd); - - if (!OpenLogfile(python_dir)) - break; + LPNMHDR lpnm; + char Buffer[4096]; + SCHEME *scheme; + + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + wsprintf(Buffer, + "Click Next to begin the installation of %s. " + "If you want to review or change any of your " + " installation settings, click Back. " + "Click Cancel to exit the wizard.", + meta_name); + SetDlgItemText(hwnd, IDC_TITLE, Buffer); + SetDlgItemText(hwnd, IDC_INFO, "Ready to install"); + break; + + case WM_NUMFILES: + SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam); + PumpMessages(); + return TRUE; + + case WM_NEXTFILE: + SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam, + 0); + SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam); + PumpMessages(); + return TRUE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: + PropSheet_SetWizButtons(GetParent(hwnd), + PSWIZB_BACK | PSWIZB_NEXT); + break; + + case PSN_WIZFINISH: + break; + + case PSN_WIZNEXT: + /* Handle a Next button click here */ + hDialog = hwnd; + success = TRUE; + + /* Disable the buttons while we work. Sending CANCELTOCLOSE has + the effect of disabling the cancel button, which is a) as we + do everything synchronously we can't cancel, and b) the next + step is 'finished', when it is too late to cancel anyway. + The next step being 'Finished' means we also don't need to + restore the button state back */ + PropSheet_SetWizButtons(GetParent(hwnd), 0); + SendMessage(GetParent(hwnd), PSM_CANCELTOCLOSE, 0, 0); + /* Make sure the installation directory name ends in a */ + /* backslash */ + if (python_dir[strlen(python_dir)-1] != '\\') + strcat(python_dir, "\\"); + /* Strip the trailing backslash again */ + python_dir[strlen(python_dir)-1] = '\0'; + + CheckRootKey(hwnd); + + if (!OpenLogfile(python_dir)) + break; /* * The scheme we have to use depends on the Python version... @@ -1915,202 +1915,202 @@ InstallFilesDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) 'data' : '$base', } */ - scheme = GetScheme(py_major, py_minor); - /* Run the pre-install script. */ - if (pre_install_script && *pre_install_script) { - SetDlgItemText (hwnd, IDC_TITLE, - "Running pre-installation script"); - run_simple_script(pre_install_script); - } - if (!success) { - break; - } - /* Extract all files from the archive */ - SetDlgItemText(hwnd, IDC_TITLE, "Installing files..."); - if (!unzip_archive (scheme, - python_dir, arc_data, - arc_size, notify)) - set_failure_reason("Failed to unzip installation files"); - /* Compile the py-files */ - if (success && pyc_compile) { - int errors; - HINSTANCE hPython; - SetDlgItemText(hwnd, IDC_TITLE, - "Compiling files to .pyc..."); - - SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); - hPython = LoadPythonDll(pythondll); - if (hPython) { - errors = compile_filelist(hPython, FALSE); - FreeLibrary(hPython); - } - /* Compilation errors are intentionally ignored: - * Python2.0 contains a bug which will result - * in sys.path containing garbage under certain - * circumstances, and an error message will only - * confuse the user. - */ - } - if (success && pyo_compile) { - int errors; - HINSTANCE hPython; - SetDlgItemText(hwnd, IDC_TITLE, - "Compiling files to .pyo..."); - - SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); - hPython = LoadPythonDll(pythondll); - if (hPython) { - errors = compile_filelist(hPython, TRUE); - FreeLibrary(hPython); - } - /* Errors ignored: see above */ - } - - - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + scheme = GetScheme(py_major, py_minor); + /* Run the pre-install script. */ + if (pre_install_script && *pre_install_script) { + SetDlgItemText (hwnd, IDC_TITLE, + "Running pre-installation script"); + run_simple_script(pre_install_script); + } + if (!success) { + break; + } + /* Extract all files from the archive */ + SetDlgItemText(hwnd, IDC_TITLE, "Installing files..."); + if (!unzip_archive (scheme, + python_dir, arc_data, + arc_size, notify)) + set_failure_reason("Failed to unzip installation files"); + /* Compile the py-files */ + if (success && pyc_compile) { + int errors; + HINSTANCE hPython; + SetDlgItemText(hwnd, IDC_TITLE, + "Compiling files to .pyc..."); + + SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); + hPython = LoadPythonDll(pythondll); + if (hPython) { + errors = compile_filelist(hPython, FALSE); + FreeLibrary(hPython); + } + /* Compilation errors are intentionally ignored: + * Python2.0 contains a bug which will result + * in sys.path containing garbage under certain + * circumstances, and an error message will only + * confuse the user. + */ + } + if (success && pyo_compile) { + int errors; + HINSTANCE hPython; + SetDlgItemText(hwnd, IDC_TITLE, + "Compiling files to .pyo..."); + + SetDlgItemText(hDialog, IDC_INFO, "Loading python..."); + hPython = LoadPythonDll(pythondll); + if (hPython) { + errors = compile_filelist(hPython, TRUE); + FreeLibrary(hPython); + } + /* Errors ignored: see above */ + } + + + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } BOOL CALLBACK FinishedDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { - LPNMHDR lpnm; - - switch (msg) { - case WM_INITDIALOG: - if (hBitmap) - SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, - IMAGE_BITMAP, (LPARAM)hBitmap); - if (!success) - SetDlgItemText(hwnd, IDC_INFO, get_failure_reason()); - - /* async delay: will show the dialog box completely before - the install_script is started */ - PostMessage(hwnd, WM_USER, 0, 0L); - return TRUE; - - case WM_USER: - - if (success && install_script && install_script[0]) { - char fname[MAX_PATH]; - char *buffer; - HCURSOR hCursor; - int result; - - char *argv[3] = {NULL, "-install", NULL}; - - SetDlgItemText(hwnd, IDC_TITLE, - "Please wait while running postinstall script..."); - strcpy(fname, python_dir); - strcat(fname, "\\Scripts\\"); - strcat(fname, install_script); - - if (logfile) - fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname); - - hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT)); - - argv[0] = fname; - - result = run_installscript(fname, 2, argv, &buffer); - if (0 != result) { - fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result); - } - if (buffer) - SetDlgItemText(hwnd, IDC_INFO, buffer); - SetDlgItemText(hwnd, IDC_TITLE, - "Postinstall script finished.\n" - "Click the Finish button to exit the Setup wizard."); - - free(buffer); - SetCursor(hCursor); - CloseLogfile(); - } - - return TRUE; - - case WM_NOTIFY: - lpnm = (LPNMHDR) lParam; - - switch (lpnm->code) { - case PSN_SETACTIVE: /* Enable the Finish button */ - PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH); - break; - - case PSN_WIZNEXT: - break; - - case PSN_WIZFINISH: - break; - - case PSN_RESET: - break; - - default: - break; - } - } - return 0; + LPNMHDR lpnm; + + switch (msg) { + case WM_INITDIALOG: + if (hBitmap) + SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE, + IMAGE_BITMAP, (LPARAM)hBitmap); + if (!success) + SetDlgItemText(hwnd, IDC_INFO, get_failure_reason()); + + /* async delay: will show the dialog box completely before + the install_script is started */ + PostMessage(hwnd, WM_USER, 0, 0L); + return TRUE; + + case WM_USER: + + if (success && install_script && install_script[0]) { + char fname[MAX_PATH]; + char *buffer; + HCURSOR hCursor; + int result; + + char *argv[3] = {NULL, "-install", NULL}; + + SetDlgItemText(hwnd, IDC_TITLE, + "Please wait while running postinstall script..."); + strcpy(fname, python_dir); + strcat(fname, "\\Scripts\\"); + strcat(fname, install_script); + + if (logfile) + fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname); + + hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT)); + + argv[0] = fname; + + result = run_installscript(fname, 2, argv, &buffer); + if (0 != result) { + fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result); + } + if (buffer) + SetDlgItemText(hwnd, IDC_INFO, buffer); + SetDlgItemText(hwnd, IDC_TITLE, + "Postinstall script finished.\n" + "Click the Finish button to exit the Setup wizard."); + + free(buffer); + SetCursor(hCursor); + CloseLogfile(); + } + + return TRUE; + + case WM_NOTIFY: + lpnm = (LPNMHDR) lParam; + + switch (lpnm->code) { + case PSN_SETACTIVE: /* Enable the Finish button */ + PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH); + break; + + case PSN_WIZNEXT: + break; + + case PSN_WIZFINISH: + break; + + case PSN_RESET: + break; + + default: + break; + } + } + return 0; } void RunWizard(HWND hwnd) { - PROPSHEETPAGE psp = {0}; - HPROPSHEETPAGE ahpsp[4] = {0}; - PROPSHEETHEADER psh = {0}; - - /* Display module information */ - psp.dwSize = sizeof(psp); - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.hInstance = GetModuleHandle (NULL); - psp.lParam = 0; - psp.pfnDlgProc = IntroDlgProc; - psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO); - - ahpsp[0] = CreatePropertySheetPage(&psp); - - /* Select python version to use */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON); - psp.pfnDlgProc = SelectPythonDlgProc; - - ahpsp[1] = CreatePropertySheetPage(&psp); - - /* Install the files */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES); - psp.pfnDlgProc = InstallFilesDlgProc; - - ahpsp[2] = CreatePropertySheetPage(&psp); - - /* Show success or failure */ - psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; - psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED); - psp.pfnDlgProc = FinishedDlgProc; - - ahpsp[3] = CreatePropertySheetPage(&psp); - - /* Create the property sheet */ - psh.dwSize = sizeof(psh); - psh.hInstance = GetModuleHandle(NULL); - psh.hwndParent = hwnd; - psh.phpage = ahpsp; - psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/; - psh.pszbmWatermark = NULL; - psh.pszbmHeader = NULL; - psh.nStartPage = 0; - psh.nPages = 4; - - PropertySheet(&psh); + PROPSHEETPAGE psp = {0}; + HPROPSHEETPAGE ahpsp[4] = {0}; + PROPSHEETHEADER psh = {0}; + + /* Display module information */ + psp.dwSize = sizeof(psp); + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.hInstance = GetModuleHandle (NULL); + psp.lParam = 0; + psp.pfnDlgProc = IntroDlgProc; + psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO); + + ahpsp[0] = CreatePropertySheetPage(&psp); + + /* Select python version to use */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON); + psp.pfnDlgProc = SelectPythonDlgProc; + + ahpsp[1] = CreatePropertySheetPage(&psp); + + /* Install the files */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES); + psp.pfnDlgProc = InstallFilesDlgProc; + + ahpsp[2] = CreatePropertySheetPage(&psp); + + /* Show success or failure */ + psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER; + psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED); + psp.pfnDlgProc = FinishedDlgProc; + + ahpsp[3] = CreatePropertySheetPage(&psp); + + /* Create the property sheet */ + psh.dwSize = sizeof(psh); + psh.hInstance = GetModuleHandle(NULL); + psh.hwndParent = hwnd; + psh.phpage = ahpsp; + psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/; + psh.pszbmWatermark = NULL; + psh.pszbmHeader = NULL; + psh.nStartPage = 0; + psh.nPages = 4; + + PropertySheet(&psh); } // subtly different from HasLocalMachinePrivs(), in that after executing @@ -2118,16 +2118,16 @@ void RunWizard(HWND hwnd) // such implication for HasLocalMachinePrivs BOOL MyIsUserAnAdmin() { - typedef BOOL (WINAPI *PFNIsUserAnAdmin)(); - static PFNIsUserAnAdmin pfnIsUserAnAdmin = NULL; - HMODULE shell32; - // This function isn't guaranteed to be available (and it can't hurt - // to leave the library loaded) - if (0 == (shell32=LoadLibrary("shell32.dll"))) - return FALSE; - if (0 == (pfnIsUserAnAdmin=(PFNIsUserAnAdmin)GetProcAddress(shell32, "IsUserAnAdmin"))) - return FALSE; - return (*pfnIsUserAnAdmin)(); + typedef BOOL (WINAPI *PFNIsUserAnAdmin)(); + static PFNIsUserAnAdmin pfnIsUserAnAdmin = NULL; + HMODULE shell32; + // This function isn't guaranteed to be available (and it can't hurt + // to leave the library loaded) + if (0 == (shell32=LoadLibrary("shell32.dll"))) + return FALSE; + if (0 == (pfnIsUserAnAdmin=(PFNIsUserAnAdmin)GetProcAddress(shell32, "IsUserAnAdmin"))) + return FALSE; + return (*pfnIsUserAnAdmin)(); } // Some magic for Vista's UAC. If there is a target_version, and @@ -2139,38 +2139,38 @@ BOOL MyIsUserAnAdmin() // Returns TRUE if we should spawn an elevated child BOOL NeedAutoUAC() { - HKEY hk; - char key_name[80]; - // no Python version info == we can't know yet. - if (target_version[0] == '\0') - return FALSE; - // see how python is current installed - wsprintf(key_name, - "Software\\Python\\PythonCore\\%s\\InstallPath", - target_version); - if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, - key_name, 0, KEY_READ, &hk)) - return FALSE; - RegCloseKey(hk); - // Python is installed in HKLM - we must elevate. - return TRUE; + HKEY hk; + char key_name[80]; + // no Python version info == we can't know yet. + if (target_version[0] == '\0') + return FALSE; + // see how python is current installed + wsprintf(key_name, + "Software\\Python\\PythonCore\\%s\\InstallPath", + target_version); + if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, + key_name, 0, KEY_READ, &hk)) + return FALSE; + RegCloseKey(hk); + // Python is installed in HKLM - we must elevate. + return TRUE; } // Returns TRUE if the platform supports UAC. BOOL PlatformSupportsUAC() { - // Note that win2k does seem to support ShellExecute with 'runas', - // but does *not* support IsUserAnAdmin - so we just pretend things - // only work on XP and later. - BOOL bIsWindowsXPorLater; - OSVERSIONINFO winverinfo; - winverinfo.dwOSVersionInfoSize = sizeof(winverinfo); - if (!GetVersionEx(&winverinfo)) - return FALSE; // something bad has gone wrong - bIsWindowsXPorLater = + // Note that win2k does seem to support ShellExecute with 'runas', + // but does *not* support IsUserAnAdmin - so we just pretend things + // only work on XP and later. + BOOL bIsWindowsXPorLater; + OSVERSIONINFO winverinfo; + winverinfo.dwOSVersionInfoSize = sizeof(winverinfo); + if (!GetVersionEx(&winverinfo)) + return FALSE; // something bad has gone wrong + bIsWindowsXPorLater = ( (winverinfo.dwMajorVersion > 5) || ( (winverinfo.dwMajorVersion == 5) && (winverinfo.dwMinorVersion >= 1) )); - return bIsWindowsXPorLater; + return bIsWindowsXPorLater; } // Spawn ourself as an elevated application. On failure, a message is @@ -2178,97 +2178,97 @@ BOOL PlatformSupportsUAC() // on error. void SpawnUAC() { - // interesting failure scenario that has been seen: initial executable - // runs from a network drive - but once elevated, that network share - // isn't seen, and ShellExecute fails with SE_ERR_ACCESSDENIED. - int ret = (int)ShellExecute(0, "runas", modulename, "", NULL, - SW_SHOWNORMAL); - if (ret <= 32) { - char msg[128]; - wsprintf(msg, "Failed to start elevated process (ShellExecute returned %d)", ret); - MessageBox(0, msg, "Setup", MB_OK | MB_ICONERROR); - } + // interesting failure scenario that has been seen: initial executable + // runs from a network drive - but once elevated, that network share + // isn't seen, and ShellExecute fails with SE_ERR_ACCESSDENIED. + int ret = (int)ShellExecute(0, "runas", modulename, "", NULL, + SW_SHOWNORMAL); + if (ret <= 32) { + char msg[128]; + wsprintf(msg, "Failed to start elevated process (ShellExecute returned %d)", ret); + MessageBox(0, msg, "Setup", MB_OK | MB_ICONERROR); + } } int DoInstall(void) { - char ini_buffer[4096]; - - /* Read installation information */ - GetPrivateProfileString("Setup", "title", "", ini_buffer, - sizeof(ini_buffer), ini_file); - unescape(title, ini_buffer, sizeof(title)); - - GetPrivateProfileString("Setup", "info", "", ini_buffer, - sizeof(ini_buffer), ini_file); - unescape(info, ini_buffer, sizeof(info)); - - GetPrivateProfileString("Setup", "build_info", "", build_info, - sizeof(build_info), ini_file); - - pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1, - ini_file); - pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1, - ini_file); - - GetPrivateProfileString("Setup", "target_version", "", - target_version, sizeof(target_version), - ini_file); - - GetPrivateProfileString("metadata", "name", "", - meta_name, sizeof(meta_name), - ini_file); - - GetPrivateProfileString("Setup", "install_script", "", - install_script, sizeof(install_script), - ini_file); - - GetPrivateProfileString("Setup", "user_access_control", "", - user_access_control, sizeof(user_access_control), ini_file); - - // See if we need to do the Vista UAC magic. - if (strcmp(user_access_control, "force")==0) { - if (PlatformSupportsUAC() && !MyIsUserAnAdmin()) { - SpawnUAC(); - return 0; - } - // already admin - keep going - } else if (strcmp(user_access_control, "auto")==0) { - // Check if it looks like we need UAC control, based - // on how Python itself was installed. - if (PlatformSupportsUAC() && !MyIsUserAnAdmin() && NeedAutoUAC()) { - SpawnUAC(); - return 0; - } - } else { - // display a warning about unknown values - only the developer - // of the extension will see it (until they fix it!) - if (user_access_control[0] && strcmp(user_access_control, "none") != 0) { - MessageBox(GetFocus(), "Bad user_access_control value", "oops", MB_OK); - // nothing to do. - } - } - - hwndMain = CreateBackground(title); - - RunWizard(hwndMain); - - /* Clean up */ - UnmapViewOfFile(arc_data); - if (ini_file) - DeleteFile(ini_file); - - if (hBitmap) - DeleteObject(hBitmap); - - return 0; + char ini_buffer[4096]; + + /* Read installation information */ + GetPrivateProfileString("Setup", "title", "", ini_buffer, + sizeof(ini_buffer), ini_file); + unescape(title, ini_buffer, sizeof(title)); + + GetPrivateProfileString("Setup", "info", "", ini_buffer, + sizeof(ini_buffer), ini_file); + unescape(info, ini_buffer, sizeof(info)); + + GetPrivateProfileString("Setup", "build_info", "", build_info, + sizeof(build_info), ini_file); + + pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1, + ini_file); + pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1, + ini_file); + + GetPrivateProfileString("Setup", "target_version", "", + target_version, sizeof(target_version), + ini_file); + + GetPrivateProfileString("metadata", "name", "", + meta_name, sizeof(meta_name), + ini_file); + + GetPrivateProfileString("Setup", "install_script", "", + install_script, sizeof(install_script), + ini_file); + + GetPrivateProfileString("Setup", "user_access_control", "", + user_access_control, sizeof(user_access_control), ini_file); + + // See if we need to do the Vista UAC magic. + if (strcmp(user_access_control, "force")==0) { + if (PlatformSupportsUAC() && !MyIsUserAnAdmin()) { + SpawnUAC(); + return 0; + } + // already admin - keep going + } else if (strcmp(user_access_control, "auto")==0) { + // Check if it looks like we need UAC control, based + // on how Python itself was installed. + if (PlatformSupportsUAC() && !MyIsUserAnAdmin() && NeedAutoUAC()) { + SpawnUAC(); + return 0; + } + } else { + // display a warning about unknown values - only the developer + // of the extension will see it (until they fix it!) + if (user_access_control[0] && strcmp(user_access_control, "none") != 0) { + MessageBox(GetFocus(), "Bad user_access_control value", "oops", MB_OK); + // nothing to do. + } + } + + hwndMain = CreateBackground(title); + + RunWizard(hwndMain); + + /* Clean up */ + UnmapViewOfFile(arc_data); + if (ini_file) + DeleteFile(ini_file); + + if (hBitmap) + DeleteObject(hBitmap); + + return 0; } /*********************** uninstall section ******************************/ static int compare(const void *p1, const void *p2) { - return strcmp(*(char **)p2, *(char **)p1); + return strcmp(*(char **)p2, *(char **)p1); } /* @@ -2282,379 +2282,379 @@ static int compare(const void *p1, const void *p2) */ void remove_exe(void) { - char exename[_MAX_PATH]; - char batname[_MAX_PATH]; - FILE *fp; - STARTUPINFO si; - PROCESS_INFORMATION pi; - - GetModuleFileName(NULL, exename, sizeof(exename)); - sprintf(batname, "%s.bat", exename); - fp = fopen(batname, "w"); - fprintf(fp, ":Repeat\n"); - fprintf(fp, "del \"%s\"\n", exename); - fprintf(fp, "if exist \"%s\" goto Repeat\n", exename); - fprintf(fp, "del \"%s\"\n", batname); - fclose(fp); - - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - si.dwFlags = STARTF_USESHOWWINDOW; - si.wShowWindow = SW_HIDE; - if (CreateProcess(NULL, - batname, - NULL, - NULL, - FALSE, - CREATE_SUSPENDED | IDLE_PRIORITY_CLASS, - NULL, - "\\", - &si, - &pi)) { - SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE); - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); - SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); - CloseHandle(pi.hProcess); - ResumeThread(pi.hThread); - CloseHandle(pi.hThread); - } + char exename[_MAX_PATH]; + char batname[_MAX_PATH]; + FILE *fp; + STARTUPINFO si; + PROCESS_INFORMATION pi; + + GetModuleFileName(NULL, exename, sizeof(exename)); + sprintf(batname, "%s.bat", exename); + fp = fopen(batname, "w"); + fprintf(fp, ":Repeat\n"); + fprintf(fp, "del \"%s\"\n", exename); + fprintf(fp, "if exist \"%s\" goto Repeat\n", exename); + fprintf(fp, "del \"%s\"\n", batname); + fclose(fp); + + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); + si.dwFlags = STARTF_USESHOWWINDOW; + si.wShowWindow = SW_HIDE; + if (CreateProcess(NULL, + batname, + NULL, + NULL, + FALSE, + CREATE_SUSPENDED | IDLE_PRIORITY_CLASS, + NULL, + "\\", + &si, + &pi)) { + SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE); + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); + SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); + CloseHandle(pi.hProcess); + ResumeThread(pi.hThread); + CloseHandle(pi.hThread); + } } void DeleteRegistryKey(char *string) { - char *keyname; - char *subkeyname; - char *delim; - HKEY hKey; - long result; - char *line; - - line = strdup(string); /* so we can change it */ - - keyname = strchr(line, '['); - if (!keyname) - return; - ++keyname; - - subkeyname = strchr(keyname, ']'); - if (!subkeyname) - return; - *subkeyname++='\0'; - delim = strchr(subkeyname, '\n'); - if (delim) - *delim = '\0'; - - result = RegOpenKeyEx(hkey_root, - keyname, - 0, - KEY_WRITE, - &hKey); - - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), string, "Could not open key", MB_OK); - else { - result = RegDeleteKey(hKey, subkeyname); - if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) - MessageBox(GetFocus(), string, "Could not delete key", MB_OK); - RegCloseKey(hKey); - } - free(line); + char *keyname; + char *subkeyname; + char *delim; + HKEY hKey; + long result; + char *line; + + line = strdup(string); /* so we can change it */ + + keyname = strchr(line, '['); + if (!keyname) + return; + ++keyname; + + subkeyname = strchr(keyname, ']'); + if (!subkeyname) + return; + *subkeyname++='\0'; + delim = strchr(subkeyname, '\n'); + if (delim) + *delim = '\0'; + + result = RegOpenKeyEx(hkey_root, + keyname, + 0, + KEY_WRITE, + &hKey); + + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), string, "Could not open key", MB_OK); + else { + result = RegDeleteKey(hKey, subkeyname); + if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) + MessageBox(GetFocus(), string, "Could not delete key", MB_OK); + RegCloseKey(hKey); + } + free(line); } void DeleteRegistryValue(char *string) { - char *keyname; - char *valuename; - char *value; - HKEY hKey; - long result; - char *line; + char *keyname; + char *valuename; + char *value; + HKEY hKey; + long result; + char *line; - line = strdup(string); /* so we can change it */ + line = strdup(string); /* so we can change it */ /* Format is 'Reg DB Value: [key]name=value' */ - keyname = strchr(line, '['); - if (!keyname) - return; - ++keyname; - valuename = strchr(keyname, ']'); - if (!valuename) - return; - *valuename++ = '\0'; - value = strchr(valuename, '='); - if (!value) - return; - - *value++ = '\0'; - - result = RegOpenKeyEx(hkey_root, - keyname, - 0, - KEY_WRITE, - &hKey); - if (result != ERROR_SUCCESS) - MessageBox(GetFocus(), string, "Could not open key", MB_OK); - else { - result = RegDeleteValue(hKey, valuename); - if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) - MessageBox(GetFocus(), string, "Could not delete value", MB_OK); - RegCloseKey(hKey); - } - free(line); + keyname = strchr(line, '['); + if (!keyname) + return; + ++keyname; + valuename = strchr(keyname, ']'); + if (!valuename) + return; + *valuename++ = '\0'; + value = strchr(valuename, '='); + if (!value) + return; + + *value++ = '\0'; + + result = RegOpenKeyEx(hkey_root, + keyname, + 0, + KEY_WRITE, + &hKey); + if (result != ERROR_SUCCESS) + MessageBox(GetFocus(), string, "Could not open key", MB_OK); + else { + result = RegDeleteValue(hKey, valuename); + if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) + MessageBox(GetFocus(), string, "Could not delete value", MB_OK); + RegCloseKey(hKey); + } + free(line); } BOOL MyDeleteFile(char *line) { - char *pathname = strchr(line, ':'); - if (!pathname) - return FALSE; - ++pathname; - while (isspace(*pathname)) - ++pathname; - return DeleteFile(pathname); + char *pathname = strchr(line, ':'); + if (!pathname) + return FALSE; + ++pathname; + while (isspace(*pathname)) + ++pathname; + return DeleteFile(pathname); } BOOL MyRemoveDirectory(char *line) { - char *pathname = strchr(line, ':'); - if (!pathname) - return FALSE; - ++pathname; - while (isspace(*pathname)) - ++pathname; - return RemoveDirectory(pathname); + char *pathname = strchr(line, ':'); + if (!pathname) + return FALSE; + ++pathname; + while (isspace(*pathname)) + ++pathname; + return RemoveDirectory(pathname); } BOOL Run_RemoveScript(char *line) { - char *dllname; - char *scriptname; - static char lastscript[MAX_PATH]; + char *dllname; + char *scriptname; + static char lastscript[MAX_PATH]; /* Format is 'Run Scripts: [pythondll]scriptname' */ /* XXX Currently, pythondll carries no path!!! */ - dllname = strchr(line, '['); - if (!dllname) - return FALSE; - ++dllname; - scriptname = strchr(dllname, ']'); - if (!scriptname) - return FALSE; - *scriptname++ = '\0'; - /* this function may be called more than one time with the same - script, only run it one time */ - if (strcmp(lastscript, scriptname)) { - char *argv[3] = {NULL, "-remove", NULL}; - char *buffer = NULL; - - argv[0] = scriptname; - - if (0 != run_installscript(scriptname, 2, argv, &buffer)) - fprintf(stderr, "*** Could not run installation script ***"); - - if (buffer && buffer[0]) - MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK); - free(buffer); - - strcpy(lastscript, scriptname); - } - return TRUE; + dllname = strchr(line, '['); + if (!dllname) + return FALSE; + ++dllname; + scriptname = strchr(dllname, ']'); + if (!scriptname) + return FALSE; + *scriptname++ = '\0'; + /* this function may be called more than one time with the same + script, only run it one time */ + if (strcmp(lastscript, scriptname)) { + char *argv[3] = {NULL, "-remove", NULL}; + char *buffer = NULL; + + argv[0] = scriptname; + + if (0 != run_installscript(scriptname, 2, argv, &buffer)) + fprintf(stderr, "*** Could not run installation script ***"); + + if (buffer && buffer[0]) + MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK); + free(buffer); + + strcpy(lastscript, scriptname); + } + return TRUE; } int DoUninstall(int argc, char **argv) { - FILE *logfile; - char buffer[4096]; - int nLines = 0; - int i; - char *cp; - int nFiles = 0; - int nDirs = 0; - int nErrors = 0; - char **lines; - int lines_buffer_size = 10; - - if (argc != 3) { - MessageBox(NULL, - "Wrong number of args", - NULL, - MB_OK); - return 1; /* Error */ - } - if (strcmp(argv[1], "-u")) { - MessageBox(NULL, - "2. arg is not -u", - NULL, - MB_OK); - return 1; /* Error */ - } - - logfile = fopen(argv[2], "r"); - if (!logfile) { - MessageBox(NULL, - "could not open logfile", - NULL, - MB_OK); - return 1; /* Error */ - } - - lines = (char **)malloc(sizeof(char *) * lines_buffer_size); - if (!lines) - return SystemError(0, "Out of memory"); - - /* Read the whole logfile, realloacting the buffer */ - while (fgets(buffer, sizeof(buffer), logfile)) { - int len = strlen(buffer); - /* remove trailing white space */ - while (isspace(buffer[len-1])) - len -= 1; - buffer[len] = '\0'; - lines[nLines++] = strdup(buffer); - if (nLines >= lines_buffer_size) { - lines_buffer_size += 10; - lines = (char **)realloc(lines, - sizeof(char *) * lines_buffer_size); - if (!lines) - return SystemError(0, "Out of memory"); - } - } - fclose(logfile); - - /* Sort all the lines, so that highest 3-digit codes are first */ - qsort(&lines[0], nLines, sizeof(char *), - compare); - - if (IDYES != MessageBox(NULL, - "Are you sure you want to remove\n" - "this package from your computer?", - "Please confirm", - MB_YESNO | MB_ICONQUESTION)) - return 0; - - hkey_root = HKEY_LOCAL_MACHINE; - cp = ""; - for (i = 0; i < nLines; ++i) { - /* Ignore duplicate lines */ - if (strcmp(cp, lines[i])) { - int ign; - cp = lines[i]; - /* Parse the lines */ - if (2 == sscanf(cp, "%d Root Key: %s", &ign, &buffer)) { - if (strcmp(buffer, "HKEY_CURRENT_USER")==0) - hkey_root = HKEY_CURRENT_USER; - else { - // HKLM - check they have permissions. - if (!HasLocalMachinePrivs()) { - MessageBox(GetFocus(), - "You do not seem to have sufficient access rights\n" - "on this machine to uninstall this software", - NULL, - MB_OK | MB_ICONSTOP); - return 1; /* Error */ - } - } - } else if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) { - if (MyRemoveDirectory(cp)) - ++nDirs; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) { - if (MyDeleteFile(cp)) - ++nFiles; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) { - if (MyDeleteFile(cp)) - ++nFiles; - else { - int code = GetLastError(); - if (code != 2 && code != 3) { /* file or path not found */ - ++nErrors; - } - } - } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) { - DeleteRegistryKey(cp); - } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) { - DeleteRegistryValue(cp); - } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) { - Run_RemoveScript(cp); - } - } - } - - if (DeleteFile(argv[2])) { - ++nFiles; - } else { - ++nErrors; - SystemError(GetLastError(), argv[2]); - } - if (nErrors) - wsprintf(buffer, - "%d files and %d directories removed\n" - "%d files or directories could not be removed", - nFiles, nDirs, nErrors); - else - wsprintf(buffer, "%d files and %d directories removed", - nFiles, nDirs); - MessageBox(NULL, buffer, "Uninstall Finished!", - MB_OK | MB_ICONINFORMATION); - remove_exe(); - return 0; + FILE *logfile; + char buffer[4096]; + int nLines = 0; + int i; + char *cp; + int nFiles = 0; + int nDirs = 0; + int nErrors = 0; + char **lines; + int lines_buffer_size = 10; + + if (argc != 3) { + MessageBox(NULL, + "Wrong number of args", + NULL, + MB_OK); + return 1; /* Error */ + } + if (strcmp(argv[1], "-u")) { + MessageBox(NULL, + "2. arg is not -u", + NULL, + MB_OK); + return 1; /* Error */ + } + + logfile = fopen(argv[2], "r"); + if (!logfile) { + MessageBox(NULL, + "could not open logfile", + NULL, + MB_OK); + return 1; /* Error */ + } + + lines = (char **)malloc(sizeof(char *) * lines_buffer_size); + if (!lines) + return SystemError(0, "Out of memory"); + + /* Read the whole logfile, realloacting the buffer */ + while (fgets(buffer, sizeof(buffer), logfile)) { + int len = strlen(buffer); + /* remove trailing white space */ + while (isspace(buffer[len-1])) + len -= 1; + buffer[len] = '\0'; + lines[nLines++] = strdup(buffer); + if (nLines >= lines_buffer_size) { + lines_buffer_size += 10; + lines = (char **)realloc(lines, + sizeof(char *) * lines_buffer_size); + if (!lines) + return SystemError(0, "Out of memory"); + } + } + fclose(logfile); + + /* Sort all the lines, so that highest 3-digit codes are first */ + qsort(&lines[0], nLines, sizeof(char *), + compare); + + if (IDYES != MessageBox(NULL, + "Are you sure you want to remove\n" + "this package from your computer?", + "Please confirm", + MB_YESNO | MB_ICONQUESTION)) + return 0; + + hkey_root = HKEY_LOCAL_MACHINE; + cp = ""; + for (i = 0; i < nLines; ++i) { + /* Ignore duplicate lines */ + if (strcmp(cp, lines[i])) { + int ign; + cp = lines[i]; + /* Parse the lines */ + if (2 == sscanf(cp, "%d Root Key: %s", &ign, &buffer)) { + if (strcmp(buffer, "HKEY_CURRENT_USER")==0) + hkey_root = HKEY_CURRENT_USER; + else { + // HKLM - check they have permissions. + if (!HasLocalMachinePrivs()) { + MessageBox(GetFocus(), + "You do not seem to have sufficient access rights\n" + "on this machine to uninstall this software", + NULL, + MB_OK | MB_ICONSTOP); + return 1; /* Error */ + } + } + } else if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) { + if (MyRemoveDirectory(cp)) + ++nDirs; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) { + if (MyDeleteFile(cp)) + ++nFiles; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) { + if (MyDeleteFile(cp)) + ++nFiles; + else { + int code = GetLastError(); + if (code != 2 && code != 3) { /* file or path not found */ + ++nErrors; + } + } + } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) { + DeleteRegistryKey(cp); + } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) { + DeleteRegistryValue(cp); + } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) { + Run_RemoveScript(cp); + } + } + } + + if (DeleteFile(argv[2])) { + ++nFiles; + } else { + ++nErrors; + SystemError(GetLastError(), argv[2]); + } + if (nErrors) + wsprintf(buffer, + "%d files and %d directories removed\n" + "%d files or directories could not be removed", + nFiles, nDirs, nErrors); + else + wsprintf(buffer, "%d files and %d directories removed", + nFiles, nDirs); + MessageBox(NULL, buffer, "Uninstall Finished!", + MB_OK | MB_ICONINFORMATION); + remove_exe(); + return 0; } int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, - LPSTR lpszCmdLine, INT nCmdShow) + LPSTR lpszCmdLine, INT nCmdShow) { - extern int __argc; - extern char **__argv; - char *basename; - - GetModuleFileName(NULL, modulename, sizeof(modulename)); - - /* Map the executable file to memory */ - arc_data = MapExistingFile(modulename, &arc_size); - if (!arc_data) { - SystemError(GetLastError(), "Could not open archive"); - return 1; - } - - /* OK. So this program can act as installer (self-extracting - * zip-file, or as uninstaller when started with '-u logfile' - * command line flags. - * - * The installer is usually started without command line flags, - * and the uninstaller is usually started with the '-u logfile' - * flag. What to do if some innocent user double-clicks the - * exe-file? - * The following implements a defensive strategy... - */ - - /* Try to extract the configuration data into a temporary file */ - if (ExtractInstallData(arc_data, arc_size, &exe_size, - &ini_file, &pre_install_script)) - return DoInstall(); - - if (!ini_file && __argc > 1) { - return DoUninstall(__argc, __argv); - } - - - basename = strrchr(modulename, '\\'); - if (basename) - ++basename; - - /* Last guess about the purpose of this program */ - if (basename && (0 == strncmp(basename, "Remove", 6))) - SystemError(0, "This program is normally started by windows"); - else - SystemError(0, "Setup program invalid or damaged"); - return 1; + extern int __argc; + extern char **__argv; + char *basename; + + GetModuleFileName(NULL, modulename, sizeof(modulename)); + + /* Map the executable file to memory */ + arc_data = MapExistingFile(modulename, &arc_size); + if (!arc_data) { + SystemError(GetLastError(), "Could not open archive"); + return 1; + } + + /* OK. So this program can act as installer (self-extracting + * zip-file, or as uninstaller when started with '-u logfile' + * command line flags. + * + * The installer is usually started without command line flags, + * and the uninstaller is usually started with the '-u logfile' + * flag. What to do if some innocent user double-clicks the + * exe-file? + * The following implements a defensive strategy... + */ + + /* Try to extract the configuration data into a temporary file */ + if (ExtractInstallData(arc_data, arc_size, &exe_size, + &ini_file, &pre_install_script)) + return DoInstall(); + + if (!ini_file && __argc > 1) { + return DoUninstall(__argc, __argv); + } + + + basename = strrchr(modulename, '\\'); + if (basename) + ++basename; + + /* Last guess about the purpose of this program */ + if (basename && (0 == strncmp(basename, "Remove", 6))) + SystemError(0, "This program is normally started by windows"); + else + SystemError(0, "Setup program invalid or damaged"); + return 1; } diff --git a/PC/config.c b/PC/config.c index 41f0573..35c6608 100644 --- a/PC/config.c +++ b/PC/config.c @@ -77,94 +77,94 @@ extern void initimp(void); struct _inittab _PyImport_Inittab[] = { - {"array", initarray}, - {"_ast", init_ast}, + {"array", initarray}, + {"_ast", init_ast}, #ifdef MS_WINDOWS #ifndef MS_WINI64 - {"audioop", initaudioop}, + {"audioop", initaudioop}, #endif #endif - {"binascii", initbinascii}, - {"cmath", initcmath}, - {"errno", initerrno}, - {"future_builtins", initfuture_builtins}, - {"gc", initgc}, + {"binascii", initbinascii}, + {"cmath", initcmath}, + {"errno", initerrno}, + {"future_builtins", initfuture_builtins}, + {"gc", initgc}, #ifndef MS_WINI64 - {"imageop", initimageop}, + {"imageop", initimageop}, #endif - {"math", initmath}, - {"_md5", init_md5}, - {"nt", initnt}, /* Use the NT os functions, not posix */ - {"operator", initoperator}, - {"signal", initsignal}, - {"_sha", init_sha}, - {"_sha256", init_sha256}, - {"_sha512", init_sha512}, - {"strop", initstrop}, - {"time", inittime}, + {"math", initmath}, + {"_md5", init_md5}, + {"nt", initnt}, /* Use the NT os functions, not posix */ + {"operator", initoperator}, + {"signal", initsignal}, + {"_sha", init_sha}, + {"_sha256", init_sha256}, + {"_sha512", init_sha512}, + {"strop", initstrop}, + {"time", inittime}, #ifdef WITH_THREAD - {"thread", initthread}, + {"thread", initthread}, #endif - {"cStringIO", initcStringIO}, - {"cPickle", initcPickle}, + {"cStringIO", initcStringIO}, + {"cPickle", initcPickle}, #ifdef WIN32 - {"msvcrt", initmsvcrt}, - {"_locale", init_locale}, + {"msvcrt", initmsvcrt}, + {"_locale", init_locale}, #endif - /* XXX Should _subprocess go in a WIN32 block? not WIN64? */ - {"_subprocess", init_subprocess}, - - {"_codecs", init_codecs}, - {"_weakref", init_weakref}, - {"_hotshot", init_hotshot}, - {"_random", init_random}, - {"_bisect", init_bisect}, - {"_heapq", init_heapq}, - {"_lsprof", init_lsprof}, - {"itertools", inititertools}, - {"_collections", init_collections}, - {"_symtable", init_symtable}, - {"mmap", initmmap}, - {"_csv", init_csv}, - {"_sre", init_sre}, - {"parser", initparser}, - {"_winreg", init_winreg}, - {"_struct", init_struct}, - {"datetime", initdatetime}, - {"_functools", init_functools}, - {"_json", init_json}, - - {"xxsubtype", initxxsubtype}, - {"zipimport", initzipimport}, - {"zlib", initzlib}, - - /* CJK codecs */ - {"_multibytecodec", init_multibytecodec}, - {"_codecs_cn", init_codecs_cn}, - {"_codecs_hk", init_codecs_hk}, - {"_codecs_iso2022", init_codecs_iso2022}, - {"_codecs_jp", init_codecs_jp}, - {"_codecs_kr", init_codecs_kr}, - {"_codecs_tw", init_codecs_tw}, + /* XXX Should _subprocess go in a WIN32 block? not WIN64? */ + {"_subprocess", init_subprocess}, + + {"_codecs", init_codecs}, + {"_weakref", init_weakref}, + {"_hotshot", init_hotshot}, + {"_random", init_random}, + {"_bisect", init_bisect}, + {"_heapq", init_heapq}, + {"_lsprof", init_lsprof}, + {"itertools", inititertools}, + {"_collections", init_collections}, + {"_symtable", init_symtable}, + {"mmap", initmmap}, + {"_csv", init_csv}, + {"_sre", init_sre}, + {"parser", initparser}, + {"_winreg", init_winreg}, + {"_struct", init_struct}, + {"datetime", initdatetime}, + {"_functools", init_functools}, + {"_json", init_json}, + + {"xxsubtype", initxxsubtype}, + {"zipimport", initzipimport}, + {"zlib", initzlib}, + + /* CJK codecs */ + {"_multibytecodec", init_multibytecodec}, + {"_codecs_cn", init_codecs_cn}, + {"_codecs_hk", init_codecs_hk}, + {"_codecs_iso2022", init_codecs_iso2022}, + {"_codecs_jp", init_codecs_jp}, + {"_codecs_kr", init_codecs_kr}, + {"_codecs_tw", init_codecs_tw}, /* tools/freeze/makeconfig.py marker for additional "_inittab" entries */ /* -- ADDMODULE MARKER 2 -- */ - /* This module "lives in" with marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module "lives in" with marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives it with import.c */ - {"imp", initimp}, + /* This lives it with import.c */ + {"imp", initimp}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"__builtin__", NULL}, - {"sys", NULL}, - {"exceptions", NULL}, - {"_warnings", _PyWarnings_Init}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"__builtin__", NULL}, + {"sys", NULL}, + {"exceptions", NULL}, + {"_warnings", _PyWarnings_Init}, - {"_io", init_io}, + {"_io", init_io}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; @@ -3,7 +3,7 @@ Entry point for the Windows NT DLL. About the only reason for having this, is so initall() can automatically -be called, removing that burden (and possible source of frustration if +be called, removing that burden (and possible source of frustration if forgotten) from the programmer. */ @@ -46,61 +46,61 @@ static PFN_RELEASEACTCTX pfnReleaseActCtx = NULL; void _LoadActCtxPointers() { - HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll"); - if (hKernel32) - pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx"); - // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest. - if (pfnGetCurrentActCtx) { - pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx"); - pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx"); - pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx"); - pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx"); - } + HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll"); + if (hKernel32) + pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx"); + // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest. + if (pfnGetCurrentActCtx) { + pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx"); + pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx"); + pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx"); + pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx"); + } } ULONG_PTR _Py_ActivateActCtx() { - ULONG_PTR ret = 0; - if (PyWin_DLLhActivationContext && pfnActivateActCtx) - if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) { - OutputDebugString("Python failed to activate the activation context before loading a DLL\n"); - ret = 0; // no promise the failing function didn't change it! - } - return ret; + ULONG_PTR ret = 0; + if (PyWin_DLLhActivationContext && pfnActivateActCtx) + if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) { + OutputDebugString("Python failed to activate the activation context before loading a DLL\n"); + ret = 0; // no promise the failing function didn't change it! + } + return ret; } void _Py_DeactivateActCtx(ULONG_PTR cookie) { - if (cookie && pfnDeactivateActCtx) - if (!(*pfnDeactivateActCtx)(0, cookie)) - OutputDebugString("Python failed to de-activate the activation context\n"); + if (cookie && pfnDeactivateActCtx) + if (!(*pfnDeactivateActCtx)(0, cookie)) + OutputDebugString("Python failed to de-activate the activation context\n"); } -BOOL WINAPI DllMain (HANDLE hInst, - ULONG ul_reason_for_call, - LPVOID lpReserved) +BOOL WINAPI DllMain (HANDLE hInst, + ULONG ul_reason_for_call, + LPVOID lpReserved) { - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - PyWin_DLLhModule = hInst; - // 1000 is a magic number I picked out of the air. Could do with a #define, I spose... - LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer)); - - // and capture our activation context for use when loading extensions. - _LoadActCtxPointers(); - if (pfnGetCurrentActCtx && pfnAddRefActCtx) - if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext)) - if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext)) - OutputDebugString("Python failed to load the default activation context\n"); - break; - - case DLL_PROCESS_DETACH: - if (pfnReleaseActCtx) - (*pfnReleaseActCtx)(PyWin_DLLhActivationContext); - break; - } - return TRUE; + switch (ul_reason_for_call) + { + case DLL_PROCESS_ATTACH: + PyWin_DLLhModule = hInst; + // 1000 is a magic number I picked out of the air. Could do with a #define, I spose... + LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer)); + + // and capture our activation context for use when loading extensions. + _LoadActCtxPointers(); + if (pfnGetCurrentActCtx && pfnAddRefActCtx) + if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext)) + if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext)) + OutputDebugString("Python failed to load the default activation context\n"); + break; + + case DLL_PROCESS_DETACH: + if (pfnReleaseActCtx) + (*pfnReleaseActCtx)(PyWin_DLLhActivationContext); + break; + } + return TRUE; } #endif /* Py_ENABLE_SHARED */ diff --git a/PC/errmap.h b/PC/errmap.h index 59aeea1..d225aa4 100644 --- a/PC/errmap.h +++ b/PC/errmap.h @@ -1,78 +1,78 @@ /* Generated file. Do not edit. */ int winerror_to_errno(int winerror) { - switch(winerror) { - case 2: return 2; - case 3: return 2; - case 4: return 24; - case 5: return 13; - case 6: return 9; - case 7: return 12; - case 8: return 12; - case 9: return 12; - case 10: return 7; - case 11: return 8; - case 15: return 2; - case 16: return 13; - case 17: return 18; - case 18: return 2; - case 19: return 13; - case 20: return 13; - case 21: return 13; - case 22: return 13; - case 23: return 13; - case 24: return 13; - case 25: return 13; - case 26: return 13; - case 27: return 13; - case 28: return 13; - case 29: return 13; - case 30: return 13; - case 31: return 13; - case 32: return 13; - case 33: return 13; - case 34: return 13; - case 35: return 13; - case 36: return 13; - case 53: return 2; - case 65: return 13; - case 67: return 2; - case 80: return 17; - case 82: return 13; - case 83: return 13; - case 89: return 11; - case 108: return 13; - case 109: return 32; - case 112: return 28; - case 114: return 9; - case 128: return 10; - case 129: return 10; - case 130: return 9; - case 132: return 13; - case 145: return 41; - case 158: return 13; - case 161: return 2; - case 164: return 11; - case 167: return 13; - case 183: return 17; - case 188: return 8; - case 189: return 8; - case 190: return 8; - case 191: return 8; - case 192: return 8; - case 193: return 8; - case 194: return 8; - case 195: return 8; - case 196: return 8; - case 197: return 8; - case 198: return 8; - case 199: return 8; - case 200: return 8; - case 201: return 8; - case 202: return 8; - case 206: return 2; - case 215: return 11; - case 1816: return 12; - default: return EINVAL; - } + switch(winerror) { + case 2: return 2; + case 3: return 2; + case 4: return 24; + case 5: return 13; + case 6: return 9; + case 7: return 12; + case 8: return 12; + case 9: return 12; + case 10: return 7; + case 11: return 8; + case 15: return 2; + case 16: return 13; + case 17: return 18; + case 18: return 2; + case 19: return 13; + case 20: return 13; + case 21: return 13; + case 22: return 13; + case 23: return 13; + case 24: return 13; + case 25: return 13; + case 26: return 13; + case 27: return 13; + case 28: return 13; + case 29: return 13; + case 30: return 13; + case 31: return 13; + case 32: return 13; + case 33: return 13; + case 34: return 13; + case 35: return 13; + case 36: return 13; + case 53: return 2; + case 65: return 13; + case 67: return 2; + case 80: return 17; + case 82: return 13; + case 83: return 13; + case 89: return 11; + case 108: return 13; + case 109: return 32; + case 112: return 28; + case 114: return 9; + case 128: return 10; + case 129: return 10; + case 130: return 9; + case 132: return 13; + case 145: return 41; + case 158: return 13; + case 161: return 2; + case 164: return 11; + case 167: return 13; + case 183: return 17; + case 188: return 8; + case 189: return 8; + case 190: return 8; + case 191: return 8; + case 192: return 8; + case 193: return 8; + case 194: return 8; + case 195: return 8; + case 196: return 8; + case 197: return 8; + case 198: return 8; + case 199: return 8; + case 200: return 8; + case 201: return 8; + case 202: return 8; + case 206: return 2; + case 215: return 11; + case 1816: return 12; + default: return EINVAL; + } } diff --git a/PC/frozen_dllmain.c b/PC/frozen_dllmain.c index fbb4713..a8cc885 100644 --- a/PC/frozen_dllmain.c +++ b/PC/frozen_dllmain.c @@ -9,7 +9,7 @@ a frozen application, this DLLMain symbol exists multiple times. The solution is: * Each module checks for a frozen build, and if so, defines its DLLMain - function as "__declspec(dllexport) DllMain%module%" + function as "__declspec(dllexport) DllMain%module%" (eg, DllMainpythoncom, or DllMainpywintypes) * The frozen .EXE/.DLL links against this module, which provides @@ -47,10 +47,10 @@ changed, here is a snippet from the pythoncom extension module. #include "windows.h" static char *possibleModules[] = { - "pywintypes", - "pythoncom", - "win32ui", - NULL, + "pywintypes", + "pythoncom", + "win32ui", + NULL, }; BOOL CallModuleDllMain(char *modName, DWORD dwReason); @@ -62,73 +62,73 @@ BOOL CallModuleDllMain(char *modName, DWORD dwReason); */ void PyWinFreeze_ExeInit(void) { - char **modName; - for (modName = possibleModules;*modName;*modName++) { -/* printf("Initialising '%s'\n", *modName); */ - CallModuleDllMain(*modName, DLL_PROCESS_ATTACH); - } + char **modName; + for (modName = possibleModules;*modName;*modName++) { +/* printf("Initialising '%s'\n", *modName); */ + CallModuleDllMain(*modName, DLL_PROCESS_ATTACH); + } } /* Called by a frozen .EXE only, so that built-in extension - modules are cleaned up + modules are cleaned up */ void PyWinFreeze_ExeTerm(void) { - // Must go backwards - char **modName; - for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; - modName >= possibleModules; - *modName--) { -/* printf("Terminating '%s'\n", *modName);*/ - CallModuleDllMain(*modName, DLL_PROCESS_DETACH); - } + // Must go backwards + char **modName; + for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; + modName >= possibleModules; + *modName--) { +/* printf("Terminating '%s'\n", *modName);*/ + CallModuleDllMain(*modName, DLL_PROCESS_DETACH); + } } BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { - BOOL ret = TRUE; - switch (dwReason) { - case DLL_PROCESS_ATTACH: - { - char **modName; - for (modName = possibleModules;*modName;*modName++) { - BOOL ok = CallModuleDllMain(*modName, dwReason); - if (!ok) - ret = FALSE; - } - break; - } - case DLL_PROCESS_DETACH: - { - // Must go backwards - char **modName; - for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; - modName >= possibleModules; - *modName--) - CallModuleDllMain(*modName, DLL_PROCESS_DETACH); - break; - } - } - return ret; + BOOL ret = TRUE; + switch (dwReason) { + case DLL_PROCESS_ATTACH: + { + char **modName; + for (modName = possibleModules;*modName;*modName++) { + BOOL ok = CallModuleDllMain(*modName, dwReason); + if (!ok) + ret = FALSE; + } + break; + } + case DLL_PROCESS_DETACH: + { + // Must go backwards + char **modName; + for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2; + modName >= possibleModules; + *modName--) + CallModuleDllMain(*modName, DLL_PROCESS_DETACH); + break; + } + } + return ret; } BOOL CallModuleDllMain(char *modName, DWORD dwReason) { - BOOL (WINAPI * pfndllmain)(HINSTANCE, DWORD, LPVOID); - - char funcName[255]; - HMODULE hmod = GetModuleHandle(NULL); - strcpy(funcName, "_DllMain"); - strcat(funcName, modName); - strcat(funcName, "@12"); // stdcall convention. - pfndllmain = (BOOL (WINAPI *)(HINSTANCE, DWORD, LPVOID))GetProcAddress(hmod, funcName); - if (pfndllmain==NULL) { - /* No function by that name exported - then that module does - not appear in our frozen program - return OK - */ - return TRUE; - } - return (*pfndllmain)(hmod, dwReason, NULL); + BOOL (WINAPI * pfndllmain)(HINSTANCE, DWORD, LPVOID); + + char funcName[255]; + HMODULE hmod = GetModuleHandle(NULL); + strcpy(funcName, "_DllMain"); + strcat(funcName, modName); + strcat(funcName, "@12"); // stdcall convention. + pfndllmain = (BOOL (WINAPI *)(HINSTANCE, DWORD, LPVOID))GetProcAddress(hmod, funcName); + if (pfndllmain==NULL) { + /* No function by that name exported - then that module does + not appear in our frozen program - return OK + */ + return TRUE; + } + return (*pfndllmain)(hmod, dwReason, NULL); } diff --git a/PC/generrmap.c b/PC/generrmap.c index 2b25063..bf1081b 100644 --- a/PC/generrmap.c +++ b/PC/generrmap.c @@ -5,16 +5,16 @@ int main() { - int i; - printf("/* Generated file. Do not edit. */\n"); - printf("int winerror_to_errno(int winerror)\n"); - printf("{\n\tswitch(winerror) {\n"); - for(i=1; i < 65000; i++) { - _dosmaperr(i); - if (errno == EINVAL) - continue; - printf("\t\tcase %d: return %d;\n", i, errno); - } - printf("\t\tdefault: return EINVAL;\n"); - printf("\t}\n}\n"); + int i; + printf("/* Generated file. Do not edit. */\n"); + printf("int winerror_to_errno(int winerror)\n"); + printf("{\n\tswitch(winerror) {\n"); + for(i=1; i < 65000; i++) { + _dosmaperr(i); + if (errno == EINVAL) + continue; + printf("\t\tcase %d: return %d;\n", i, errno); + } + printf("\t\tdefault: return EINVAL;\n"); + printf("\t}\n}\n"); } diff --git a/PC/getpathp.c b/PC/getpathp.c index 78f4465..461f9fc 100644 --- a/PC/getpathp.c +++ b/PC/getpathp.c @@ -4,8 +4,8 @@ /* ---------------------------------------------------------------- PATH RULES FOR WINDOWS: - This describes how sys.path is formed on Windows. It describes the - functionality, not the implementation (ie, the order in which these + This describes how sys.path is formed on Windows. It describes the + functionality, not the implementation (ie, the order in which these are actually fetched is different) * Python always adds an empty entry at the start, which corresponds @@ -24,15 +24,15 @@ * We attempt to locate the "Python Home" - if the PYTHONHOME env var is set, we believe it. Otherwise, we use the path of our host .EXE's to try and locate our "landmark" (lib\\os.py) and deduce our home. - - If we DO have a Python Home: The relevant sub-directories (Lib, + - If we DO have a Python Home: The relevant sub-directories (Lib, plat-win, lib-tk, etc) are based on the Python Home - If we DO NOT have a Python Home, the core Python Path is - loaded from the registry. This is the main PythonPath key, + loaded from the registry. This is the main PythonPath key, and both HKLM and HKCU are combined to form the path) * Iff - we can not locate the Python Home, have not had a PYTHONPATH specified, and can't locate any Registry entries (ie, we have _nothing_ - we can assume is a good path), a default path with relative entries is + we can assume is a good path), a default path with relative entries is used (eg. .\Lib;.\plat-win, etc) @@ -42,9 +42,9 @@ the core path is deduced, and the core paths in the registry are ignored. Other "application paths" in the registry are always read. - * When Python is hosted in another exe (different directory, embedded via + * When Python is hosted in another exe (different directory, embedded via COM, etc), the Python Home will not be deduced, so the core path from - the registry is used. Other "application paths" in the registry are + the registry is used. Other "application paths" in the registry are always read. * If Python can't find its home and there is no registry (eg, frozen @@ -92,12 +92,12 @@ static char *module_search_path = NULL; static int -is_sep(char ch) /* determine if "ch" is a separator character */ +is_sep(char ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -107,36 +107,36 @@ is_sep(char ch) /* determine if "ch" is a separator character */ static void reduce(char *dir) { - size_t i = strlen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + size_t i = strlen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(char *filename) { - struct stat buf; - return stat(filename, &buf) == 0; + struct stat buf; + return stat(filename, &buf) == 0; } -/* Assumes 'filename' MAXPATHLEN+1 bytes long - +/* Assumes 'filename' MAXPATHLEN+1 bytes long - may extend 'filename' by one character. */ static int -ismodule(char *filename) /* Is module -- check for .pyc/.pyo too */ +ismodule(char *filename) /* Is module -- check for .pyc/.pyo too */ { - if (exists(filename)) - return 1; - - /* Check for the compiled version of prefix. */ - if (strlen(filename) < MAXPATHLEN) { - strcat(filename, Py_OptimizeFlag ? "o" : "c"); - if (exists(filename)) - return 1; - } - return 0; + if (exists(filename)) + return 1; + + /* Check for the compiled version of prefix. */ + if (strlen(filename) < MAXPATHLEN) { + strcat(filename, Py_OptimizeFlag ? "o" : "c"); + if (exists(filename)) + return 1; + } + return 0; } /* Add a path component, by appending stuff to buffer. @@ -151,21 +151,21 @@ ismodule(char *filename) /* Is module -- check for .pyc/.pyo too */ static void join(char *buffer, char *stuff) { - size_t n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = strlen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = strlen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + size_t n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = strlen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = strlen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + strncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } /* gotlandmark only called by search_for_prefix, which ensures @@ -175,29 +175,29 @@ join(char *buffer, char *stuff) static int gotlandmark(char *landmark) { - int ok; - Py_ssize_t n; - - n = strlen(prefix); - join(prefix, landmark); - ok = ismodule(prefix); - prefix[n] = '\0'; - return ok; + int ok; + Py_ssize_t n; + + n = strlen(prefix); + join(prefix, landmark); + ok = ismodule(prefix); + prefix[n] = '\0'; + return ok; } -/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. +/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. assumption provided by only caller, calculate_path() */ static int search_for_prefix(char *argv0_path, char *landmark) { - /* Search from argv0_path, until landmark is found */ - strcpy(prefix, argv0_path); - do { - if (gotlandmark(landmark)) - return 1; - reduce(prefix); - } while (prefix[0]); - return 0; + /* Search from argv0_path, until landmark is found */ + strcpy(prefix, argv0_path); + do { + if (gotlandmark(landmark)) + return 1; + reduce(prefix); + } while (prefix[0]); + return 0; } #ifdef MS_WINDOWS @@ -223,146 +223,146 @@ extern const char *PyWin_DLLVersionString; static char * getpythonregpath(HKEY keyBase, int skipcore) { - HKEY newKey = 0; - DWORD dataSize = 0; - DWORD numKeys = 0; - LONG rc; - char *retval = NULL; - TCHAR *dataBuf = NULL; - static const TCHAR keyPrefix[] = _T("Software\\Python\\PythonCore\\"); - static const TCHAR keySuffix[] = _T("\\PythonPath"); - size_t versionLen; - DWORD index; - TCHAR *keyBuf = NULL; - TCHAR *keyBufPtr; - TCHAR **ppPaths = NULL; - - /* Tried to use sysget("winver") but here is too early :-( */ - versionLen = _tcslen(PyWin_DLLVersionString); - /* Space for all the chars, plus one \0 */ - keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + - sizeof(TCHAR)*(versionLen-1) + - sizeof(keySuffix)); - if (keyBuf==NULL) goto done; - - memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(TCHAR)); - keyBufPtr += sizeof(keyPrefix)/sizeof(TCHAR) - 1; - memcpy(keyBufPtr, PyWin_DLLVersionString, versionLen * sizeof(TCHAR)); - keyBufPtr += versionLen; - /* NULL comes with this one! */ - memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); - /* Open the root Python key */ - rc=RegOpenKeyEx(keyBase, - keyBuf, /* subkey */ - 0, /* reserved */ - KEY_READ, - &newKey); - if (rc!=ERROR_SUCCESS) goto done; - /* Find out how big our core buffer is, and how many subkeys we have */ - rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, - NULL, NULL, &dataSize, NULL, NULL); - if (rc!=ERROR_SUCCESS) goto done; - if (skipcore) dataSize = 0; /* Only count core ones if we want them! */ - /* Allocate a temp array of char buffers, so we only need to loop - reading the registry once - */ - ppPaths = malloc( sizeof(TCHAR *) * numKeys ); - if (ppPaths==NULL) goto done; - memset(ppPaths, 0, sizeof(TCHAR *) * numKeys); - /* Loop over all subkeys, allocating a temp sub-buffer. */ - for(index=0;index<numKeys;index++) { - TCHAR keyBuf[MAX_PATH+1]; - HKEY subKey = 0; - DWORD reqdSize = MAX_PATH+1; - /* Get the sub-key name */ - DWORD rc = RegEnumKeyEx(newKey, index, keyBuf, &reqdSize, - NULL, NULL, NULL, NULL ); - if (rc!=ERROR_SUCCESS) goto done; - /* Open the sub-key */ - rc=RegOpenKeyEx(newKey, - keyBuf, /* subkey */ - 0, /* reserved */ - KEY_READ, - &subKey); - if (rc!=ERROR_SUCCESS) goto done; - /* Find the value of the buffer size, malloc, then read it */ - RegQueryValueEx(subKey, NULL, 0, NULL, NULL, &reqdSize); - if (reqdSize) { - ppPaths[index] = malloc(reqdSize); - if (ppPaths[index]) { - RegQueryValueEx(subKey, NULL, 0, NULL, - (LPBYTE)ppPaths[index], - &reqdSize); - dataSize += reqdSize + 1; /* 1 for the ";" */ - } - } - RegCloseKey(subKey); - } - - /* return null if no path to return */ - if (dataSize == 0) goto done; - - /* original datasize from RegQueryInfo doesn't include the \0 */ - dataBuf = malloc((dataSize+1) * sizeof(TCHAR)); - if (dataBuf) { - TCHAR *szCur = dataBuf; - DWORD reqdSize = dataSize; - /* Copy our collected strings */ - for (index=0;index<numKeys;index++) { - if (index > 0) { - *(szCur++) = _T(';'); - dataSize--; - } - if (ppPaths[index]) { - Py_ssize_t len = _tcslen(ppPaths[index]); - _tcsncpy(szCur, ppPaths[index], len); - szCur += len; - assert(dataSize > (DWORD)len); - dataSize -= (DWORD)len; - } - } - if (skipcore) - *szCur = '\0'; - else { - /* If we have no values, we dont need a ';' */ - if (numKeys) { - *(szCur++) = _T(';'); - dataSize--; - } - /* Now append the core path entries - - this will include the NULL - */ - rc = RegQueryValueEx(newKey, NULL, 0, NULL, - (LPBYTE)szCur, &dataSize); - } - /* And set the result - caller must free - If MBCS, it is fine as is. If Unicode, allocate new - buffer and convert. - */ + HKEY newKey = 0; + DWORD dataSize = 0; + DWORD numKeys = 0; + LONG rc; + char *retval = NULL; + TCHAR *dataBuf = NULL; + static const TCHAR keyPrefix[] = _T("Software\\Python\\PythonCore\\"); + static const TCHAR keySuffix[] = _T("\\PythonPath"); + size_t versionLen; + DWORD index; + TCHAR *keyBuf = NULL; + TCHAR *keyBufPtr; + TCHAR **ppPaths = NULL; + + /* Tried to use sysget("winver") but here is too early :-( */ + versionLen = _tcslen(PyWin_DLLVersionString); + /* Space for all the chars, plus one \0 */ + keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + + sizeof(TCHAR)*(versionLen-1) + + sizeof(keySuffix)); + if (keyBuf==NULL) goto done; + + memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(TCHAR)); + keyBufPtr += sizeof(keyPrefix)/sizeof(TCHAR) - 1; + memcpy(keyBufPtr, PyWin_DLLVersionString, versionLen * sizeof(TCHAR)); + keyBufPtr += versionLen; + /* NULL comes with this one! */ + memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); + /* Open the root Python key */ + rc=RegOpenKeyEx(keyBase, + keyBuf, /* subkey */ + 0, /* reserved */ + KEY_READ, + &newKey); + if (rc!=ERROR_SUCCESS) goto done; + /* Find out how big our core buffer is, and how many subkeys we have */ + rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, + NULL, NULL, &dataSize, NULL, NULL); + if (rc!=ERROR_SUCCESS) goto done; + if (skipcore) dataSize = 0; /* Only count core ones if we want them! */ + /* Allocate a temp array of char buffers, so we only need to loop + reading the registry once + */ + ppPaths = malloc( sizeof(TCHAR *) * numKeys ); + if (ppPaths==NULL) goto done; + memset(ppPaths, 0, sizeof(TCHAR *) * numKeys); + /* Loop over all subkeys, allocating a temp sub-buffer. */ + for(index=0;index<numKeys;index++) { + TCHAR keyBuf[MAX_PATH+1]; + HKEY subKey = 0; + DWORD reqdSize = MAX_PATH+1; + /* Get the sub-key name */ + DWORD rc = RegEnumKeyEx(newKey, index, keyBuf, &reqdSize, + NULL, NULL, NULL, NULL ); + if (rc!=ERROR_SUCCESS) goto done; + /* Open the sub-key */ + rc=RegOpenKeyEx(newKey, + keyBuf, /* subkey */ + 0, /* reserved */ + KEY_READ, + &subKey); + if (rc!=ERROR_SUCCESS) goto done; + /* Find the value of the buffer size, malloc, then read it */ + RegQueryValueEx(subKey, NULL, 0, NULL, NULL, &reqdSize); + if (reqdSize) { + ppPaths[index] = malloc(reqdSize); + if (ppPaths[index]) { + RegQueryValueEx(subKey, NULL, 0, NULL, + (LPBYTE)ppPaths[index], + &reqdSize); + dataSize += reqdSize + 1; /* 1 for the ";" */ + } + } + RegCloseKey(subKey); + } + + /* return null if no path to return */ + if (dataSize == 0) goto done; + + /* original datasize from RegQueryInfo doesn't include the \0 */ + dataBuf = malloc((dataSize+1) * sizeof(TCHAR)); + if (dataBuf) { + TCHAR *szCur = dataBuf; + DWORD reqdSize = dataSize; + /* Copy our collected strings */ + for (index=0;index<numKeys;index++) { + if (index > 0) { + *(szCur++) = _T(';'); + dataSize--; + } + if (ppPaths[index]) { + Py_ssize_t len = _tcslen(ppPaths[index]); + _tcsncpy(szCur, ppPaths[index], len); + szCur += len; + assert(dataSize > (DWORD)len); + dataSize -= (DWORD)len; + } + } + if (skipcore) + *szCur = '\0'; + else { + /* If we have no values, we dont need a ';' */ + if (numKeys) { + *(szCur++) = _T(';'); + dataSize--; + } + /* Now append the core path entries - + this will include the NULL + */ + rc = RegQueryValueEx(newKey, NULL, 0, NULL, + (LPBYTE)szCur, &dataSize); + } + /* And set the result - caller must free + If MBCS, it is fine as is. If Unicode, allocate new + buffer and convert. + */ #ifdef UNICODE - retval = (char *)malloc(reqdSize+1); - if (retval) - WideCharToMultiByte(CP_ACP, 0, - dataBuf, -1, /* source */ - retval, reqdSize+1, /* dest */ - NULL, NULL); - free(dataBuf); + retval = (char *)malloc(reqdSize+1); + if (retval) + WideCharToMultiByte(CP_ACP, 0, + dataBuf, -1, /* source */ + retval, reqdSize+1, /* dest */ + NULL, NULL); + free(dataBuf); #else - retval = dataBuf; + retval = dataBuf; #endif - } + } done: - /* Loop freeing my temp buffers */ - if (ppPaths) { - for(index=0;index<numKeys;index++) - if (ppPaths[index]) free(ppPaths[index]); - free(ppPaths); - } - if (newKey) - RegCloseKey(newKey); - if (keyBuf) - free(keyBuf); - return retval; + /* Loop freeing my temp buffers */ + if (ppPaths) { + for(index=0;index<numKeys;index++) + if (ppPaths[index]) free(ppPaths[index]); + free(ppPaths); + } + if (newKey) + RegCloseKey(newKey); + if (keyBuf) + free(keyBuf); + return retval; } #endif /* Py_ENABLE_SHARED */ #endif /* MS_WINDOWS */ @@ -370,314 +370,314 @@ done: static void get_progpath(void) { - extern char *Py_GetProgramName(void); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); + extern char *Py_GetProgramName(void); + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); #ifdef MS_WINDOWS - extern HANDLE PyWin_DLLhModule; + extern HANDLE PyWin_DLLhModule; #ifdef UNICODE - WCHAR wprogpath[MAXPATHLEN+1]; - /* Windows documents that GetModuleFileName() will "truncate", - but makes no mention of the null terminator. Play it safe. - PLUS Windows itself defines MAX_PATH as the same, but anyway... - */ + WCHAR wprogpath[MAXPATHLEN+1]; + /* Windows documents that GetModuleFileName() will "truncate", + but makes no mention of the null terminator. Play it safe. + PLUS Windows itself defines MAX_PATH as the same, but anyway... + */ #ifdef Py_ENABLE_SHARED - wprogpath[MAXPATHLEN]=_T('\0'); - if (PyWin_DLLhModule && - GetModuleFileName(PyWin_DLLhModule, wprogpath, MAXPATHLEN)) { - WideCharToMultiByte(CP_ACP, 0, - wprogpath, -1, - dllpath, MAXPATHLEN+1, - NULL, NULL); - } + wprogpath[MAXPATHLEN]=_T('\0'); + if (PyWin_DLLhModule && + GetModuleFileName(PyWin_DLLhModule, wprogpath, MAXPATHLEN)) { + WideCharToMultiByte(CP_ACP, 0, + wprogpath, -1, + dllpath, MAXPATHLEN+1, + NULL, NULL); + } #else - dllpath[0] = 0; + dllpath[0] = 0; #endif - wprogpath[MAXPATHLEN]=_T('\0'); - if (GetModuleFileName(NULL, wprogpath, MAXPATHLEN)) { - WideCharToMultiByte(CP_ACP, 0, - wprogpath, -1, - progpath, MAXPATHLEN+1, - NULL, NULL); - return; - } + wprogpath[MAXPATHLEN]=_T('\0'); + if (GetModuleFileName(NULL, wprogpath, MAXPATHLEN)) { + WideCharToMultiByte(CP_ACP, 0, + wprogpath, -1, + progpath, MAXPATHLEN+1, + NULL, NULL); + return; + } #else - /* static init of progpath ensures final char remains \0 */ + /* static init of progpath ensures final char remains \0 */ #ifdef Py_ENABLE_SHARED - if (PyWin_DLLhModule) - if (!GetModuleFileName(PyWin_DLLhModule, dllpath, MAXPATHLEN)) - dllpath[0] = 0; + if (PyWin_DLLhModule) + if (!GetModuleFileName(PyWin_DLLhModule, dllpath, MAXPATHLEN)) + dllpath[0] = 0; #else - dllpath[0] = 0; + dllpath[0] = 0; #endif - if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) - return; + if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) + return; #endif #endif - if (prog == NULL || *prog == '\0') - prog = "python"; - - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ + if (prog == NULL || *prog == '\0') + prog = "python"; + + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ #ifdef ALTSEP - if (strchr(prog, SEP) || strchr(prog, ALTSEP)) + if (strchr(prog, SEP) || strchr(prog, ALTSEP)) #else - if (strchr(prog, SEP)) + if (strchr(prog, SEP)) #endif - strncpy(progpath, prog, MAXPATHLEN); - else if (path) { - while (1) { - char *delim = strchr(path, DELIM); - - if (delim) { - size_t len = delim - path; - /* ensure we can't overwrite buffer */ - len = min(MAXPATHLEN,len); - strncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - strncpy(progpath, path, MAXPATHLEN); - - /* join() is safe for MAXPATHLEN+1 size buffer */ - join(progpath, prog); - if (exists(progpath)) - break; - - if (!delim) { - progpath[0] = '\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; + strncpy(progpath, prog, MAXPATHLEN); + else if (path) { + while (1) { + char *delim = strchr(path, DELIM); + + if (delim) { + size_t len = delim - path; + /* ensure we can't overwrite buffer */ + len = min(MAXPATHLEN,len); + strncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + strncpy(progpath, path, MAXPATHLEN); + + /* join() is safe for MAXPATHLEN+1 size buffer */ + join(progpath, prog); + if (exists(progpath)) + break; + + if (!delim) { + progpath[0] = '\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; } static void calculate_path(void) { - char argv0_path[MAXPATHLEN+1]; - char *buf; - size_t bufsz; - char *pythonhome = Py_GetPythonHome(); - char *envpath = Py_GETENV("PYTHONPATH"); + char argv0_path[MAXPATHLEN+1]; + char *buf; + size_t bufsz; + char *pythonhome = Py_GetPythonHome(); + char *envpath = Py_GETENV("PYTHONPATH"); #ifdef MS_WINDOWS - int skiphome, skipdefault; - char *machinepath = NULL; - char *userpath = NULL; - char zip_path[MAXPATHLEN+1]; - size_t len; + int skiphome, skipdefault; + char *machinepath = NULL; + char *userpath = NULL; + char zip_path[MAXPATHLEN+1]; + size_t len; #endif - get_progpath(); - /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ - strcpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else - strncpy(prefix, pythonhome, MAXPATHLEN); + get_progpath(); + /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ + strcpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else + strncpy(prefix, pythonhome, MAXPATHLEN); - if (envpath && *envpath == '\0') - envpath = NULL; + if (envpath && *envpath == '\0') + envpath = NULL; #ifdef MS_WINDOWS - /* Calculate zip archive path */ - if (dllpath[0]) /* use name of python DLL */ - strncpy(zip_path, dllpath, MAXPATHLEN); - else /* use name of executable program */ - strncpy(zip_path, progpath, MAXPATHLEN); - zip_path[MAXPATHLEN] = '\0'; - len = strlen(zip_path); - if (len > 4) { - zip_path[len-3] = 'z'; /* change ending to "zip" */ - zip_path[len-2] = 'i'; - zip_path[len-1] = 'p'; - } - else { - zip_path[0] = 0; - } - - skiphome = pythonhome==NULL ? 0 : 1; + /* Calculate zip archive path */ + if (dllpath[0]) /* use name of python DLL */ + strncpy(zip_path, dllpath, MAXPATHLEN); + else /* use name of executable program */ + strncpy(zip_path, progpath, MAXPATHLEN); + zip_path[MAXPATHLEN] = '\0'; + len = strlen(zip_path); + if (len > 4) { + zip_path[len-3] = 'z'; /* change ending to "zip" */ + zip_path[len-2] = 'i'; + zip_path[len-1] = 'p'; + } + else { + zip_path[0] = 0; + } + + skiphome = pythonhome==NULL ? 0 : 1; #ifdef Py_ENABLE_SHARED - machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome); - userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome); + machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome); + userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome); #endif - /* We only use the default relative PYTHONPATH if we havent - anything better to use! */ - skipdefault = envpath!=NULL || pythonhome!=NULL || \ - machinepath!=NULL || userpath!=NULL; + /* We only use the default relative PYTHONPATH if we havent + anything better to use! */ + skipdefault = envpath!=NULL || pythonhome!=NULL || \ + machinepath!=NULL || userpath!=NULL; #endif - /* We need to construct a path from the following parts. - (1) the PYTHONPATH environment variable, if set; - (2) for Win32, the zip archive file path; - (3) for Win32, the machinepath and userpath, if set; - (4) the PYTHONPATH config macro, with the leading "." - of each component replaced with pythonhome, if set; - (5) the directory containing the executable (argv0_path). - The length calculation calculates #4 first. - Extra rules: - - If PYTHONHOME is set (in any way) item (3) is ignored. - - If registry values are used, (4) and (5) are ignored. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - char *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= strlen(pythonhome); - } - else - bufsz = 0; - bufsz += strlen(PYTHONPATH) + 1; - bufsz += strlen(argv0_path) + 1; + /* We need to construct a path from the following parts. + (1) the PYTHONPATH environment variable, if set; + (2) for Win32, the zip archive file path; + (3) for Win32, the machinepath and userpath, if set; + (4) the PYTHONPATH config macro, with the leading "." + of each component replaced with pythonhome, if set; + (5) the directory containing the executable (argv0_path). + The length calculation calculates #4 first. + Extra rules: + - If PYTHONHOME is set (in any way) item (3) is ignored. + - If registry values are used, (4) and (5) are ignored. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + char *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= strlen(pythonhome); + } + else + bufsz = 0; + bufsz += strlen(PYTHONPATH) + 1; + bufsz += strlen(argv0_path) + 1; #ifdef MS_WINDOWS - if (userpath) - bufsz += strlen(userpath) + 1; - if (machinepath) - bufsz += strlen(machinepath) + 1; - bufsz += strlen(zip_path) + 1; + if (userpath) + bufsz += strlen(userpath) + 1; + if (machinepath) + bufsz += strlen(machinepath) + 1; + bufsz += strlen(zip_path) + 1; #endif - if (envpath != NULL) - bufsz += strlen(envpath) + 1; - - module_search_path = buf = malloc(bufsz); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using default static path.\n"); - module_search_path = PYTHONPATH; - } + if (envpath != NULL) + bufsz += strlen(envpath) + 1; + + module_search_path = buf = malloc(bufsz); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using default static path.\n"); + module_search_path = PYTHONPATH; + } #ifdef MS_WINDOWS - if (machinepath) - free(machinepath); - if (userpath) - free(userpath); + if (machinepath) + free(machinepath); + if (userpath) + free(userpath); #endif /* MS_WINDOWS */ - return; - } - - if (envpath) { - strcpy(buf, envpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } + return; + } + + if (envpath) { + strcpy(buf, envpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } #ifdef MS_WINDOWS - if (zip_path[0]) { - strcpy(buf, zip_path); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - if (userpath) { - strcpy(buf, userpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - free(userpath); - } - if (machinepath) { - strcpy(buf, machinepath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - free(machinepath); - } - if (pythonhome == NULL) { - if (!skipdefault) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); - } - } + if (zip_path[0]) { + strcpy(buf, zip_path); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + if (userpath) { + strcpy(buf, userpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + free(userpath); + } + if (machinepath) { + strcpy(buf, machinepath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + free(machinepath); + } + if (pythonhome == NULL) { + if (!skipdefault) { + strcpy(buf, PYTHONPATH); + buf = strchr(buf, '\0'); + } + } #else - if (pythonhome == NULL) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); - } + if (pythonhome == NULL) { + strcpy(buf, PYTHONPATH); + buf = strchr(buf, '\0'); + } #endif /* MS_WINDOWS */ - else { - char *p = PYTHONPATH; - char *q; - size_t n; - for (;;) { - q = strchr(p, DELIM); - if (q == NULL) - n = strlen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - strcpy(buf, pythonhome); - buf = strchr(buf, '\0'); - p++; - n--; - } - strncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - strcpy(buf, argv0_path); - buf = strchr(buf, '\0'); - } - *buf = '\0'; - /* Now to pull one last hack/trick. If sys.prefix is - empty, then try and find it somewhere on the paths - we calculated. We scan backwards, as our general policy - is that Python core directories are at the *end* of - sys.path. We assume that our "lib" directory is - on the path, and that our 'prefix' directory is - the parent of that. - */ - if (*prefix=='\0') { - char lookBuf[MAXPATHLEN+1]; - char *look = buf - 1; /* 'buf' is at the end of the buffer */ - while (1) { - Py_ssize_t nchars; - char *lookEnd = look; - /* 'look' will end up one character before the - start of the path in question - even if this - is one character before the start of the buffer - */ - while (look >= module_search_path && *look != DELIM) - look--; - nchars = lookEnd-look; - strncpy(lookBuf, look+1, nchars); - lookBuf[nchars] = '\0'; - /* Up one level to the parent */ - reduce(lookBuf); - if (search_for_prefix(lookBuf, LANDMARK)) { - break; - } - /* If we are out of paths to search - give up */ - if (look < module_search_path) - break; - look--; - } - } + else { + char *p = PYTHONPATH; + char *q; + size_t n; + for (;;) { + q = strchr(p, DELIM); + if (q == NULL) + n = strlen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + strcpy(buf, pythonhome); + buf = strchr(buf, '\0'); + p++; + n--; + } + strncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + strcpy(buf, argv0_path); + buf = strchr(buf, '\0'); + } + *buf = '\0'; + /* Now to pull one last hack/trick. If sys.prefix is + empty, then try and find it somewhere on the paths + we calculated. We scan backwards, as our general policy + is that Python core directories are at the *end* of + sys.path. We assume that our "lib" directory is + on the path, and that our 'prefix' directory is + the parent of that. + */ + if (*prefix=='\0') { + char lookBuf[MAXPATHLEN+1]; + char *look = buf - 1; /* 'buf' is at the end of the buffer */ + while (1) { + Py_ssize_t nchars; + char *lookEnd = look; + /* 'look' will end up one character before the + start of the path in question - even if this + is one character before the start of the buffer + */ + while (look >= module_search_path && *look != DELIM) + look--; + nchars = lookEnd-look; + strncpy(lookBuf, look+1, nchars); + lookBuf[nchars] = '\0'; + /* Up one level to the parent */ + reduce(lookBuf); + if (search_for_prefix(lookBuf, LANDMARK)) { + break; + } + /* If we are out of paths to search - give up */ + if (look < module_search_path) + break; + look--; + } + } } @@ -686,29 +686,29 @@ calculate_path(void) char * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); - return module_search_path; + if (!module_search_path) + calculate_path(); + return module_search_path; } char * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); - return prefix; + if (!module_search_path) + calculate_path(); + return prefix; } char * Py_GetExecPrefix(void) { - return Py_GetPrefix(); + return Py_GetPrefix(); } char * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); - return progpath; + if (!module_search_path) + calculate_path(); + return progpath; } diff --git a/PC/import_nt.c b/PC/import_nt.c index e7d152a..196a774 100644 --- a/PC/import_nt.c +++ b/PC/import_nt.c @@ -1,6 +1,6 @@ /******************************************************************** - import_nt.c + import_nt.c Win32 specific import code. @@ -16,71 +16,71 @@ extern const char *PyWin_DLLVersionString; FILE *PyWin_FindRegisteredModule(const char *moduleName, - struct filedescr **ppFileDesc, - char *pathBuf, - Py_ssize_t pathLen) + struct filedescr **ppFileDesc, + char *pathBuf, + Py_ssize_t pathLen) { - char *moduleKey; - const char keyPrefix[] = "Software\\Python\\PythonCore\\"; - const char keySuffix[] = "\\Modules\\"; + char *moduleKey; + const char keyPrefix[] = "Software\\Python\\PythonCore\\"; + const char keySuffix[] = "\\Modules\\"; #ifdef _DEBUG - /* In debugging builds, we _must_ have the debug version - * registered. - */ - const char debugString[] = "\\Debug"; + /* In debugging builds, we _must_ have the debug version + * registered. + */ + const char debugString[] = "\\Debug"; #else - const char debugString[] = ""; + const char debugString[] = ""; #endif - struct filedescr *fdp = NULL; - FILE *fp; - HKEY keyBase = HKEY_CURRENT_USER; - int modNameSize; - long regStat; + struct filedescr *fdp = NULL; + FILE *fp; + HKEY keyBase = HKEY_CURRENT_USER; + int modNameSize; + long regStat; - /* Calculate the size for the sprintf buffer. - * Get the size of the chars only, plus 1 NULL. - */ - size_t bufSize = sizeof(keyPrefix)-1 + - strlen(PyWin_DLLVersionString) + - sizeof(keySuffix) + - strlen(moduleName) + - sizeof(debugString) - 1; - /* alloca == no free required, but memory only local to fn, - * also no heap fragmentation! - */ - moduleKey = alloca(bufSize); - PyOS_snprintf(moduleKey, bufSize, - "Software\\Python\\PythonCore\\%s\\Modules\\%s%s", - PyWin_DLLVersionString, moduleName, debugString); + /* Calculate the size for the sprintf buffer. + * Get the size of the chars only, plus 1 NULL. + */ + size_t bufSize = sizeof(keyPrefix)-1 + + strlen(PyWin_DLLVersionString) + + sizeof(keySuffix) + + strlen(moduleName) + + sizeof(debugString) - 1; + /* alloca == no free required, but memory only local to fn, + * also no heap fragmentation! + */ + moduleKey = alloca(bufSize); + PyOS_snprintf(moduleKey, bufSize, + "Software\\Python\\PythonCore\\%s\\Modules\\%s%s", + PyWin_DLLVersionString, moduleName, debugString); - assert(pathLen < INT_MAX); - modNameSize = (int)pathLen; - regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize); - if (regStat != ERROR_SUCCESS) { - /* No user setting - lookup in machine settings */ - keyBase = HKEY_LOCAL_MACHINE; - /* be anal - failure may have reset size param */ - modNameSize = (int)pathLen; - regStat = RegQueryValue(keyBase, moduleKey, - pathBuf, &modNameSize); + assert(pathLen < INT_MAX); + modNameSize = (int)pathLen; + regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize); + if (regStat != ERROR_SUCCESS) { + /* No user setting - lookup in machine settings */ + keyBase = HKEY_LOCAL_MACHINE; + /* be anal - failure may have reset size param */ + modNameSize = (int)pathLen; + regStat = RegQueryValue(keyBase, moduleKey, + pathBuf, &modNameSize); - if (regStat != ERROR_SUCCESS) - return NULL; - } - /* use the file extension to locate the type entry. */ - for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { - size_t extLen = strlen(fdp->suffix); - assert(modNameSize >= 0); /* else cast to size_t is wrong */ - if ((size_t)modNameSize > extLen && - strnicmp(pathBuf + ((size_t)modNameSize-extLen-1), - fdp->suffix, - extLen) == 0) - break; - } - if (fdp->suffix == NULL) - return NULL; - fp = fopen(pathBuf, fdp->mode); - if (fp != NULL) - *ppFileDesc = fdp; - return fp; + if (regStat != ERROR_SUCCESS) + return NULL; + } + /* use the file extension to locate the type entry. */ + for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) { + size_t extLen = strlen(fdp->suffix); + assert(modNameSize >= 0); /* else cast to size_t is wrong */ + if ((size_t)modNameSize > extLen && + strnicmp(pathBuf + ((size_t)modNameSize-extLen-1), + fdp->suffix, + extLen) == 0) + break; + } + if (fdp->suffix == NULL) + return NULL; + fp = fopen(pathBuf, fdp->mode); + if (fp != NULL) + *ppFileDesc = fdp; + return fp; } diff --git a/PC/make_versioninfo.c b/PC/make_versioninfo.c index b9f9b88..e969671 100644 --- a/PC/make_versioninfo.c +++ b/PC/make_versioninfo.c @@ -22,17 +22,17 @@ */ int main(int argc, char **argv) { - printf("/* This file created by make_versioninfo.exe */\n"); - printf("#define FIELD3 %d\n", - PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL); - printf("#define MS_DLL_ID \"%d.%d\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#ifndef _DEBUG\n"); - printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#else\n"); - printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n", - PY_MAJOR_VERSION, PY_MINOR_VERSION); - printf("#endif\n"); - return 0; + printf("/* This file created by make_versioninfo.exe */\n"); + printf("#define FIELD3 %d\n", + PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL); + printf("#define MS_DLL_ID \"%d.%d\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#ifndef _DEBUG\n"); + printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#else\n"); + printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n", + PY_MAJOR_VERSION, PY_MINOR_VERSION); + printf("#endif\n"); + return 0; } diff --git a/PC/msvcrtmodule.c b/PC/msvcrtmodule.c index 9764a02..68b7d24 100755 --- a/PC/msvcrtmodule.c +++ b/PC/msvcrtmodule.c @@ -1,18 +1,18 @@ /********************************************************* - msvcrtmodule.c + msvcrtmodule.c - A Python interface to the Microsoft Visual C Runtime - Library, providing access to those non-portable, but - still useful routines. + A Python interface to the Microsoft Visual C Runtime + Library, providing access to those non-portable, but + still useful routines. - Only ever compiled with an MS compiler, so no attempt - has been made to avoid MS language extensions, etc... + Only ever compiled with an MS compiler, so no attempt + has been made to avoid MS language extensions, etc... - This may only work on NT or 95... + This may only work on NT or 95... - Author: Mark Hammond and Guido van Rossum. - Maintenance: Guido van Rossum. + Author: Mark Hammond and Guido van Rossum. + Maintenance: Guido van Rossum. ***********************************************************/ @@ -33,14 +33,14 @@ static PyObject * msvcrt_heapmin(PyObject *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":heapmin")) - return NULL; + if (!PyArg_ParseTuple(args, ":heapmin")) + return NULL; - if (_heapmin() != 0) - return PyErr_SetFromErrno(PyExc_IOError); + if (_heapmin() != 0) + return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(heapmin_doc, @@ -53,22 +53,22 @@ to the operating system. On failure, this raises IOError."); static PyObject * msvcrt_locking(PyObject *self, PyObject *args) { - int fd; - int mode; - long nbytes; - int err; - - if (!PyArg_ParseTuple(args, "iil:locking", &fd, &mode, &nbytes)) - return NULL; - - Py_BEGIN_ALLOW_THREADS - err = _locking(fd, mode, nbytes); - Py_END_ALLOW_THREADS - if (err != 0) - return PyErr_SetFromErrno(PyExc_IOError); - - Py_INCREF(Py_None); - return Py_None; + int fd; + int mode; + long nbytes; + int err; + + if (!PyArg_ParseTuple(args, "iil:locking", &fd, &mode, &nbytes)) + return NULL; + + Py_BEGIN_ALLOW_THREADS + err = _locking(fd, mode, nbytes); + Py_END_ALLOW_THREADS + if (err != 0) + return PyErr_SetFromErrno(PyExc_IOError); + + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(locking_doc, @@ -86,16 +86,16 @@ individually."); static PyObject * msvcrt_setmode(PyObject *self, PyObject *args) { - int fd; - int flags; - if (!PyArg_ParseTuple(args,"ii:setmode", &fd, &flags)) - return NULL; + int fd; + int flags; + if (!PyArg_ParseTuple(args,"ii:setmode", &fd, &flags)) + return NULL; - flags = _setmode(fd, flags); - if (flags == -1) - return PyErr_SetFromErrno(PyExc_IOError); + flags = _setmode(fd, flags); + if (flags == -1) + return PyErr_SetFromErrno(PyExc_IOError); - return PyInt_FromLong(flags); + return PyInt_FromLong(flags); } PyDoc_STRVAR(setmode_doc, @@ -109,18 +109,18 @@ os.O_BINARY."); static PyObject * msvcrt_open_osfhandle(PyObject *self, PyObject *args) { - long handle; - int flags; - int fd; + long handle; + int flags; + int fd; - if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags)) - return NULL; + if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags)) + return NULL; - fd = _open_osfhandle(handle, flags); - if (fd == -1) - return PyErr_SetFromErrno(PyExc_IOError); + fd = _open_osfhandle(handle, flags); + if (fd == -1) + return PyErr_SetFromErrno(PyExc_IOError); - return PyInt_FromLong(fd); + return PyInt_FromLong(fd); } PyDoc_STRVAR(open_osfhandle_doc, @@ -135,20 +135,20 @@ to os.fdopen() to create a file object."); static PyObject * msvcrt_get_osfhandle(PyObject *self, PyObject *args) { - int fd; - Py_intptr_t handle; + int fd; + Py_intptr_t handle; - if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd)) - return NULL; + if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd)) + return NULL; - handle = _get_osfhandle(fd); - if (handle == -1) - return PyErr_SetFromErrno(PyExc_IOError); + handle = _get_osfhandle(fd); + if (handle == -1) + return PyErr_SetFromErrno(PyExc_IOError); - /* technically 'handle' is not a pointer, but a integer as - large as a pointer, Python's *VoidPtr interface is the - most appropriate here */ - return PyLong_FromVoidPtr((void*)handle); + /* technically 'handle' is not a pointer, but a integer as + large as a pointer, Python's *VoidPtr interface is the + most appropriate here */ + return PyLong_FromVoidPtr((void*)handle); } PyDoc_STRVAR(get_osfhandle_doc, @@ -162,13 +162,13 @@ if fd is not recognized."); static PyObject * msvcrt_kbhit(PyObject *self, PyObject *args) { - int ok; + int ok; - if (!PyArg_ParseTuple(args, ":kbhit")) - return NULL; + if (!PyArg_ParseTuple(args, ":kbhit")) + return NULL; - ok = _kbhit(); - return PyInt_FromLong(ok); + ok = _kbhit(); + return PyInt_FromLong(ok); } PyDoc_STRVAR(kbhit_doc, @@ -179,17 +179,17 @@ Return true if a keypress is waiting to be read."); static PyObject * msvcrt_getch(PyObject *self, PyObject *args) { - int ch; - char s[1]; + int ch; + char s[1]; - if (!PyArg_ParseTuple(args, ":getch")) - return NULL; + if (!PyArg_ParseTuple(args, ":getch")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getch(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyString_FromStringAndSize(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getch(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyString_FromStringAndSize(s, 1); } PyDoc_STRVAR(getch_doc, @@ -206,17 +206,17 @@ this function."); static PyObject * msvcrt_getwch(PyObject *self, PyObject *args) { - Py_UNICODE ch; - Py_UNICODE u[1]; + Py_UNICODE ch; + Py_UNICODE u[1]; - if (!PyArg_ParseTuple(args, ":getwch")) - return NULL; + if (!PyArg_ParseTuple(args, ":getwch")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getwch(); - Py_END_ALLOW_THREADS - u[0] = ch; - return PyUnicode_FromUnicode(u, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getwch(); + Py_END_ALLOW_THREADS + u[0] = ch; + return PyUnicode_FromUnicode(u, 1); } PyDoc_STRVAR(getwch_doc, @@ -228,17 +228,17 @@ Wide char variant of getch(), returning a Unicode value."); static PyObject * msvcrt_getche(PyObject *self, PyObject *args) { - int ch; - char s[1]; + int ch; + char s[1]; - if (!PyArg_ParseTuple(args, ":getche")) - return NULL; + if (!PyArg_ParseTuple(args, ":getche")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getche(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyString_FromStringAndSize(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getche(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyString_FromStringAndSize(s, 1); } PyDoc_STRVAR(getche_doc, @@ -251,17 +251,17 @@ a printable character."); static PyObject * msvcrt_getwche(PyObject *self, PyObject *args) { - Py_UNICODE ch; - Py_UNICODE s[1]; + Py_UNICODE ch; + Py_UNICODE s[1]; - if (!PyArg_ParseTuple(args, ":getwche")) - return NULL; + if (!PyArg_ParseTuple(args, ":getwche")) + return NULL; - Py_BEGIN_ALLOW_THREADS - ch = _getwche(); - Py_END_ALLOW_THREADS - s[0] = ch; - return PyUnicode_FromUnicode(s, 1); + Py_BEGIN_ALLOW_THREADS + ch = _getwche(); + Py_END_ALLOW_THREADS + s[0] = ch; + return PyUnicode_FromUnicode(s, 1); } PyDoc_STRVAR(getwche_doc, @@ -273,14 +273,14 @@ Wide char variant of getche(), returning a Unicode value."); static PyObject * msvcrt_putch(PyObject *self, PyObject *args) { - char ch; + char ch; - if (!PyArg_ParseTuple(args, "c:putch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "c:putch", &ch)) + return NULL; - _putch(ch); - Py_INCREF(Py_None); - return Py_None; + _putch(ch); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(putch_doc, @@ -292,19 +292,19 @@ Print the character char to the console without buffering."); static PyObject * msvcrt_putwch(PyObject *self, PyObject *args) { - Py_UNICODE *ch; - int size; + Py_UNICODE *ch; + int size; - if (!PyArg_ParseTuple(args, "u#:putwch", &ch, &size)) - return NULL; + if (!PyArg_ParseTuple(args, "u#:putwch", &ch, &size)) + return NULL; - if (size == 0) { - PyErr_SetString(PyExc_ValueError, - "Expected unicode string of length 1"); - return NULL; - } - _putwch(*ch); - Py_RETURN_NONE; + if (size == 0) { + PyErr_SetString(PyExc_ValueError, + "Expected unicode string of length 1"); + return NULL; + } + _putwch(*ch); + Py_RETURN_NONE; } @@ -317,15 +317,15 @@ Wide char variant of putch(), accepting a Unicode value."); static PyObject * msvcrt_ungetch(PyObject *self, PyObject *args) { - char ch; + char ch; - if (!PyArg_ParseTuple(args, "c:ungetch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "c:ungetch", &ch)) + return NULL; - if (_ungetch(ch) == EOF) - return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + if (_ungetch(ch) == EOF) + return PyErr_SetFromErrno(PyExc_IOError); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(ungetch_doc, @@ -338,15 +338,15 @@ it will be the next character read by getch() or getche()."); static PyObject * msvcrt_ungetwch(PyObject *self, PyObject *args) { - Py_UNICODE ch; + Py_UNICODE ch; - if (!PyArg_ParseTuple(args, "u:ungetwch", &ch)) - return NULL; + if (!PyArg_ParseTuple(args, "u:ungetwch", &ch)) + return NULL; - if (_ungetch(ch) == EOF) - return PyErr_SetFromErrno(PyExc_IOError); - Py_INCREF(Py_None); - return Py_None; + if (_ungetch(ch) == EOF) + return PyErr_SetFromErrno(PyExc_IOError); + Py_INCREF(Py_None); + return Py_None; } PyDoc_STRVAR(ungetwch_doc, @@ -358,70 +358,70 @@ Wide char variant of ungetch(), accepting a Unicode value."); static void insertint(PyObject *d, char *name, int value) { - PyObject *v = PyInt_FromLong((long) value); - if (v == NULL) { - /* Don't bother reporting this error */ - PyErr_Clear(); - } - else { - PyDict_SetItemString(d, name, v); - Py_DECREF(v); - } + PyObject *v = PyInt_FromLong((long) value); + if (v == NULL) { + /* Don't bother reporting this error */ + PyErr_Clear(); + } + else { + PyDict_SetItemString(d, name, v); + Py_DECREF(v); + } } /* List of functions exported by this module */ static struct PyMethodDef msvcrt_functions[] = { - {"heapmin", msvcrt_heapmin, METH_VARARGS, heapmin_doc}, - {"locking", msvcrt_locking, METH_VARARGS, locking_doc}, - {"setmode", msvcrt_setmode, METH_VARARGS, setmode_doc}, - {"open_osfhandle", msvcrt_open_osfhandle, METH_VARARGS, open_osfhandle_doc}, - {"get_osfhandle", msvcrt_get_osfhandle, METH_VARARGS, get_osfhandle_doc}, - {"kbhit", msvcrt_kbhit, METH_VARARGS, kbhit_doc}, - {"getch", msvcrt_getch, METH_VARARGS, getch_doc}, - {"getche", msvcrt_getche, METH_VARARGS, getche_doc}, - {"putch", msvcrt_putch, METH_VARARGS, putch_doc}, - {"ungetch", msvcrt_ungetch, METH_VARARGS, ungetch_doc}, + {"heapmin", msvcrt_heapmin, METH_VARARGS, heapmin_doc}, + {"locking", msvcrt_locking, METH_VARARGS, locking_doc}, + {"setmode", msvcrt_setmode, METH_VARARGS, setmode_doc}, + {"open_osfhandle", msvcrt_open_osfhandle, METH_VARARGS, open_osfhandle_doc}, + {"get_osfhandle", msvcrt_get_osfhandle, METH_VARARGS, get_osfhandle_doc}, + {"kbhit", msvcrt_kbhit, METH_VARARGS, kbhit_doc}, + {"getch", msvcrt_getch, METH_VARARGS, getch_doc}, + {"getche", msvcrt_getche, METH_VARARGS, getche_doc}, + {"putch", msvcrt_putch, METH_VARARGS, putch_doc}, + {"ungetch", msvcrt_ungetch, METH_VARARGS, ungetch_doc}, #ifdef _WCONIO_DEFINED - {"getwch", msvcrt_getwch, METH_VARARGS, getwch_doc}, - {"getwche", msvcrt_getwche, METH_VARARGS, getwche_doc}, - {"putwch", msvcrt_putwch, METH_VARARGS, putwch_doc}, - {"ungetwch", msvcrt_ungetwch, METH_VARARGS, ungetwch_doc}, + {"getwch", msvcrt_getwch, METH_VARARGS, getwch_doc}, + {"getwche", msvcrt_getwche, METH_VARARGS, getwche_doc}, + {"putwch", msvcrt_putwch, METH_VARARGS, putwch_doc}, + {"ungetwch", msvcrt_ungetwch, METH_VARARGS, ungetwch_doc}, #endif - {NULL, NULL} + {NULL, NULL} }; PyMODINIT_FUNC initmsvcrt(void) { - int st; - PyObject *d; - PyObject *m = Py_InitModule("msvcrt", msvcrt_functions); - if (m == NULL) - return; - d = PyModule_GetDict(m); - - /* constants for the locking() function's mode argument */ - insertint(d, "LK_LOCK", _LK_LOCK); - insertint(d, "LK_NBLCK", _LK_NBLCK); - insertint(d, "LK_NBRLCK", _LK_NBRLCK); - insertint(d, "LK_RLCK", _LK_RLCK); - insertint(d, "LK_UNLCK", _LK_UNLCK); - - /* constants for the crt versions */ + int st; + PyObject *d; + PyObject *m = Py_InitModule("msvcrt", msvcrt_functions); + if (m == NULL) + return; + d = PyModule_GetDict(m); + + /* constants for the locking() function's mode argument */ + insertint(d, "LK_LOCK", _LK_LOCK); + insertint(d, "LK_NBLCK", _LK_NBLCK); + insertint(d, "LK_NBRLCK", _LK_NBRLCK); + insertint(d, "LK_RLCK", _LK_RLCK); + insertint(d, "LK_UNLCK", _LK_UNLCK); + + /* constants for the crt versions */ #ifdef _VC_ASSEMBLY_PUBLICKEYTOKEN - st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN", - _VC_ASSEMBLY_PUBLICKEYTOKEN); - if (st < 0)return; + st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN", + _VC_ASSEMBLY_PUBLICKEYTOKEN); + if (st < 0)return; #endif #ifdef _CRT_ASSEMBLY_VERSION - st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION", - _CRT_ASSEMBLY_VERSION); - if (st < 0)return; + st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION", + _CRT_ASSEMBLY_VERSION); + if (st < 0)return; #endif #ifdef __LIBRARIES_ASSEMBLY_NAME_PREFIX - st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX", - __LIBRARIES_ASSEMBLY_NAME_PREFIX); - if (st < 0)return; + st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX", + __LIBRARIES_ASSEMBLY_NAME_PREFIX); + if (st < 0)return; #endif } diff --git a/PC/os2emx/config.c b/PC/os2emx/config.c index 408381c..cbab25c 100644 --- a/PC/os2emx/config.c +++ b/PC/os2emx/config.c @@ -102,81 +102,81 @@ extern void initgc(); struct _inittab _PyImport_Inittab[] = { - {"os2", initos2}, - {"signal", initsignal}, + {"os2", initos2}, + {"signal", initsignal}, #ifdef WITH_THREAD - {"thread", initthread}, + {"thread", initthread}, #endif - {"_codecs", init_codecs}, - {"_csv", init_csv}, - {"_locale", init_locale}, - {"_random", init_random}, - {"_sre", init_sre}, - {"_symtable", init_symtable}, - {"_weakref", init_weakref}, - {"array", initarray}, - {"binascii", initbinascii}, - {"cPickle", initcPickle}, - {"cStringIO", initcStringIO}, - {"_collections", init_collections}, - {"cmath", initcmath}, - {"datetime", initdatetime}, - {"dl", initdl}, - {"errno", initerrno}, - {"fcntl", initfcntl}, - {"_fileio", init_fileio}, - {"_functools", init_functools}, - {"_heapq", init_heapq}, - {"imageop", initimageop}, - {"itertools", inititertools}, - {"math", initmath}, - {"_md5", init_md5}, - {"operator", initoperator}, - {"_sha", init_sha}, - {"_sha256", init_sha256}, - {"_sha512", init_sha512}, - {"strop", initstrop}, - {"_struct", init_struct}, - {"termios", inittermios}, - {"time", inittime}, - {"timing", inittiming}, - {"xxsubtype", initxxsubtype}, - {"zipimport", initzipimport}, + {"_codecs", init_codecs}, + {"_csv", init_csv}, + {"_locale", init_locale}, + {"_random", init_random}, + {"_sre", init_sre}, + {"_symtable", init_symtable}, + {"_weakref", init_weakref}, + {"array", initarray}, + {"binascii", initbinascii}, + {"cPickle", initcPickle}, + {"cStringIO", initcStringIO}, + {"_collections", init_collections}, + {"cmath", initcmath}, + {"datetime", initdatetime}, + {"dl", initdl}, + {"errno", initerrno}, + {"fcntl", initfcntl}, + {"_fileio", init_fileio}, + {"_functools", init_functools}, + {"_heapq", init_heapq}, + {"imageop", initimageop}, + {"itertools", inititertools}, + {"math", initmath}, + {"_md5", init_md5}, + {"operator", initoperator}, + {"_sha", init_sha}, + {"_sha256", init_sha256}, + {"_sha512", init_sha512}, + {"strop", initstrop}, + {"_struct", init_struct}, + {"termios", inittermios}, + {"time", inittime}, + {"timing", inittiming}, + {"xxsubtype", initxxsubtype}, + {"zipimport", initzipimport}, #if !HAVE_DYNAMIC_LOADING - {"_curses", init_curses}, - {"_curses_panel", init_curses_panel}, - {"_hotshot", init_hotshot}, - {"_testcapi", init_testcapi}, - {"bsddb185", initbsddb185}, - {"bz2", initbz2}, - {"fpectl", initfpectl}, - {"fpetest", initfpetest}, - {"parser", initparser}, - {"pwd", initpwd}, - {"unicodedata", initunicodedata}, - {"zlib", initzlib}, + {"_curses", init_curses}, + {"_curses_panel", init_curses_panel}, + {"_hotshot", init_hotshot}, + {"_testcapi", init_testcapi}, + {"bsddb185", initbsddb185}, + {"bz2", initbz2}, + {"fpectl", initfpectl}, + {"fpetest", initfpetest}, + {"parser", initparser}, + {"pwd", initpwd}, + {"unicodedata", initunicodedata}, + {"zlib", initzlib}, #ifdef USE_SOCKET - {"_socket", init_socket}, - {"select", initselect}, + {"_socket", init_socket}, + {"select", initselect}, #endif #endif /* -- ADDMODULE MARKER 2 -- */ - /* This module "lives in" with marshal.c */ - {"marshal", PyMarshal_Init}, + /* This module "lives in" with marshal.c */ + {"marshal", PyMarshal_Init}, - /* This lives it with import.c */ - {"imp", initimp}, + /* This lives it with import.c */ + {"imp", initimp}, - /* These entries are here for sys.builtin_module_names */ - {"__main__", NULL}, - {"__builtin__", NULL}, - {"sys", NULL}, - {"exceptions", NULL}, + /* These entries are here for sys.builtin_module_names */ + {"__main__", NULL}, + {"__builtin__", NULL}, + {"sys", NULL}, + {"exceptions", NULL}, - /* This lives in gcmodule.c */ - {"gc", initgc}, + /* This lives in gcmodule.c */ + {"gc", initgc}, - /* Sentinel */ - {0, 0} + /* Sentinel */ + {0, 0} }; diff --git a/PC/os2emx/dlfcn.c b/PC/os2emx/dlfcn.c index 9e88d5e..47c046c 100644 --- a/PC/os2emx/dlfcn.c +++ b/PC/os2emx/dlfcn.c @@ -46,178 +46,178 @@ PERFORMANCE OF THIS SOFTWARE. #include <malloc.h> typedef struct _track_rec { - char *name; - HMODULE handle; - void *id; - struct _track_rec *next; + char *name; + HMODULE handle; + void *id; + struct _track_rec *next; } tDLLchain, *DLLchain; -static DLLchain dlload = NULL; /* A simple chained list of DLL names */ -static char dlerr [256]; /* last error text string */ +static DLLchain dlload = NULL; /* A simple chained list of DLL names */ +static char dlerr [256]; /* last error text string */ static void *last_id; static DLLchain find_id(void *id) { - DLLchain tmp; + DLLchain tmp; - for (tmp = dlload; tmp; tmp = tmp->next) - if (id == tmp->id) - return tmp; + for (tmp = dlload; tmp; tmp = tmp->next) + if (id == tmp->id) + return tmp; - return NULL; + return NULL; } /* load a dynamic-link library and return handle */ void *dlopen(char *filename, int flags) { - HMODULE hm; - DLLchain tmp; - char err[256]; - char *errtxt; - int rc = 0, set_chain = 0; - - for (tmp = dlload; tmp; tmp = tmp->next) - if (strnicmp(tmp->name, filename, 999) == 0) - break; - - if (!tmp) - { - tmp = (DLLchain) malloc(sizeof(tDLLchain)); - if (!tmp) - goto nomem; - tmp->name = strdup(filename); - tmp->next = dlload; - set_chain = 1; - } - - switch (rc = DosLoadModule((PSZ)&err, sizeof(err), filename, &hm)) - { - case NO_ERROR: - tmp->handle = hm; - if (set_chain) - { - do - last_id++; - while ((last_id == 0) || (find_id(last_id))); - tmp->id = last_id; - dlload = tmp; - } - return tmp->id; - case ERROR_FILE_NOT_FOUND: - case ERROR_PATH_NOT_FOUND: - errtxt = "module `%s' not found"; - break; - case ERROR_TOO_MANY_OPEN_FILES: - case ERROR_NOT_ENOUGH_MEMORY: - case ERROR_SHARING_BUFFER_EXCEEDED: + HMODULE hm; + DLLchain tmp; + char err[256]; + char *errtxt; + int rc = 0, set_chain = 0; + + for (tmp = dlload; tmp; tmp = tmp->next) + if (strnicmp(tmp->name, filename, 999) == 0) + break; + + if (!tmp) + { + tmp = (DLLchain) malloc(sizeof(tDLLchain)); + if (!tmp) + goto nomem; + tmp->name = strdup(filename); + tmp->next = dlload; + set_chain = 1; + } + + switch (rc = DosLoadModule((PSZ)&err, sizeof(err), filename, &hm)) + { + case NO_ERROR: + tmp->handle = hm; + if (set_chain) + { + do + last_id++; + while ((last_id == 0) || (find_id(last_id))); + tmp->id = last_id; + dlload = tmp; + } + return tmp->id; + case ERROR_FILE_NOT_FOUND: + case ERROR_PATH_NOT_FOUND: + errtxt = "module `%s' not found"; + break; + case ERROR_TOO_MANY_OPEN_FILES: + case ERROR_NOT_ENOUGH_MEMORY: + case ERROR_SHARING_BUFFER_EXCEEDED: nomem: - errtxt = "out of system resources"; - break; - case ERROR_ACCESS_DENIED: - errtxt = "access denied"; - break; - case ERROR_BAD_FORMAT: - case ERROR_INVALID_SEGMENT_NUMBER: - case ERROR_INVALID_ORDINAL: - case ERROR_INVALID_MODULETYPE: - case ERROR_INVALID_EXE_SIGNATURE: - case ERROR_EXE_MARKED_INVALID: - case ERROR_ITERATED_DATA_EXCEEDS_64K: - case ERROR_INVALID_MINALLOCSIZE: - case ERROR_INVALID_SEGDPL: - case ERROR_AUTODATASEG_EXCEEDS_64K: - case ERROR_RELOCSRC_CHAIN_EXCEEDS_SEGLIMIT: - errtxt = "invalid module format"; - break; - case ERROR_INVALID_NAME: - errtxt = "filename doesn't match module name"; - break; - case ERROR_SHARING_VIOLATION: - case ERROR_LOCK_VIOLATION: - errtxt = "sharing violation"; - break; - case ERROR_INIT_ROUTINE_FAILED: - errtxt = "module initialization failed"; - break; - default: - errtxt = "cause `%s', error code = %d"; - break; - } - snprintf(dlerr, sizeof(dlerr), errtxt, &err, rc); - if (tmp) - { - if (tmp->name) - free(tmp->name); - free(tmp); - } - return 0; + errtxt = "out of system resources"; + break; + case ERROR_ACCESS_DENIED: + errtxt = "access denied"; + break; + case ERROR_BAD_FORMAT: + case ERROR_INVALID_SEGMENT_NUMBER: + case ERROR_INVALID_ORDINAL: + case ERROR_INVALID_MODULETYPE: + case ERROR_INVALID_EXE_SIGNATURE: + case ERROR_EXE_MARKED_INVALID: + case ERROR_ITERATED_DATA_EXCEEDS_64K: + case ERROR_INVALID_MINALLOCSIZE: + case ERROR_INVALID_SEGDPL: + case ERROR_AUTODATASEG_EXCEEDS_64K: + case ERROR_RELOCSRC_CHAIN_EXCEEDS_SEGLIMIT: + errtxt = "invalid module format"; + break; + case ERROR_INVALID_NAME: + errtxt = "filename doesn't match module name"; + break; + case ERROR_SHARING_VIOLATION: + case ERROR_LOCK_VIOLATION: + errtxt = "sharing violation"; + break; + case ERROR_INIT_ROUTINE_FAILED: + errtxt = "module initialization failed"; + break; + default: + errtxt = "cause `%s', error code = %d"; + break; + } + snprintf(dlerr, sizeof(dlerr), errtxt, &err, rc); + if (tmp) + { + if (tmp->name) + free(tmp->name); + free(tmp); + } + return 0; } /* return a pointer to the `symbol' in DLL */ void *dlsym(void *handle, char *symbol) { - int rc = 0; - PFN addr; - char *errtxt; - int symord = 0; - DLLchain tmp = find_id(handle); - - if (!tmp) - goto inv_handle; - - if (*symbol == '#') - symord = atoi(symbol + 1); - - switch (rc = DosQueryProcAddr(tmp->handle, symord, symbol, &addr)) - { - case NO_ERROR: - return (void *)addr; - case ERROR_INVALID_HANDLE: + int rc = 0; + PFN addr; + char *errtxt; + int symord = 0; + DLLchain tmp = find_id(handle); + + if (!tmp) + goto inv_handle; + + if (*symbol == '#') + symord = atoi(symbol + 1); + + switch (rc = DosQueryProcAddr(tmp->handle, symord, symbol, &addr)) + { + case NO_ERROR: + return (void *)addr; + case ERROR_INVALID_HANDLE: inv_handle: - errtxt = "invalid module handle"; - break; - case ERROR_PROC_NOT_FOUND: - case ERROR_INVALID_NAME: - errtxt = "no symbol `%s' in module"; - break; - default: - errtxt = "symbol `%s', error code = %d"; - break; - } - snprintf(dlerr, sizeof(dlerr), errtxt, symbol, rc); - return NULL; + errtxt = "invalid module handle"; + break; + case ERROR_PROC_NOT_FOUND: + case ERROR_INVALID_NAME: + errtxt = "no symbol `%s' in module"; + break; + default: + errtxt = "symbol `%s', error code = %d"; + break; + } + snprintf(dlerr, sizeof(dlerr), errtxt, symbol, rc); + return NULL; } /* free dynamicaly-linked library */ int dlclose(void *handle) { - int rc; - DLLchain tmp = find_id(handle); - - if (!tmp) - goto inv_handle; - - switch (rc = DosFreeModule(tmp->handle)) - { - case NO_ERROR: - free(tmp->name); - dlload = tmp->next; - free(tmp); - return 0; - case ERROR_INVALID_HANDLE: + int rc; + DLLchain tmp = find_id(handle); + + if (!tmp) + goto inv_handle; + + switch (rc = DosFreeModule(tmp->handle)) + { + case NO_ERROR: + free(tmp->name); + dlload = tmp->next; + free(tmp); + return 0; + case ERROR_INVALID_HANDLE: inv_handle: - strcpy(dlerr, "invalid module handle"); - return -1; - case ERROR_INVALID_ACCESS: - strcpy(dlerr, "access denied"); - return -1; - default: - return -1; - } + strcpy(dlerr, "invalid module handle"); + return -1; + case ERROR_INVALID_ACCESS: + strcpy(dlerr, "access denied"); + return -1; + default: + return -1; + } } /* return a string describing last occurred dl error */ char *dlerror() { - return dlerr; + return dlerr; } diff --git a/PC/os2emx/dllentry.c b/PC/os2emx/dllentry.c index dbf9c98..9ccca1c 100644 --- a/PC/os2emx/dllentry.c +++ b/PC/os2emx/dllentry.c @@ -4,7 +4,7 @@ #define NULL 0 -#define REF(s) extern void s(); void *____ref_##s = &s; +#define REF(s) extern void s(); void *____ref_##s = &s; /* Make references to imported symbols to pull them from static library */ REF(Py_Main); @@ -18,25 +18,25 @@ extern void __ctordtorTerm(void); unsigned long _DLL_InitTerm(unsigned long mod_handle, unsigned long flag) { - switch (flag) - { - case 0: - if (_CRT_init()) - return 0; - __ctordtorInit(); - - /* Ignore fatal signals */ - signal(SIGSEGV, SIG_IGN); - signal(SIGFPE, SIG_IGN); - - return 1; - - case 1: - __ctordtorTerm(); - _CRT_term(); - return 1; - - default: - return 0; - } + switch (flag) + { + case 0: + if (_CRT_init()) + return 0; + __ctordtorInit(); + + /* Ignore fatal signals */ + signal(SIGSEGV, SIG_IGN); + signal(SIGFPE, SIG_IGN); + + return 1; + + case 1: + __ctordtorTerm(); + _CRT_term(); + return 1; + + default: + return 0; + } } diff --git a/PC/os2emx/getpathp.c b/PC/os2emx/getpathp.c index 5839eab..4faa505 100644 --- a/PC/os2emx/getpathp.c +++ b/PC/os2emx/getpathp.c @@ -4,8 +4,8 @@ /* ---------------------------------------------------------------- PATH RULES FOR OS/2+EMX: - This describes how sys.path is formed on OS/2+EMX. It describes the - functionality, not the implementation (ie, the order in which these + This describes how sys.path is formed on OS/2+EMX. It describes the + functionality, not the implementation (ie, the order in which these are actually fetched is different) * Python always adds an empty entry at the start, which corresponds @@ -16,10 +16,10 @@ * We attempt to locate the "Python Home" - if the PYTHONHOME env var is set, we believe it. Otherwise, we use the path of our host .EXE's to try and locate our "landmark" (lib\\os.py) and deduce our home. - - If we DO have a Python Home: The relevant sub-directories (Lib, + - If we DO have a Python Home: The relevant sub-directories (Lib, plat-win, lib-tk, etc) are based on the Python Home - If we DO NOT have a Python Home, the core Python Path is - loaded from the registry. This is the main PythonPath key, + loaded from the registry. This is the main PythonPath key, and both HKLM and HKCU are combined to form the path) * Iff - we can not locate the Python Home, and have not had a PYTHONPATH @@ -32,9 +32,9 @@ (either an installed version, or directly from the PCbuild directory), the core path is deduced. - * When Python is hosted in another exe (different directory, embedded via + * When Python is hosted in another exe (different directory, embedded via COM, etc), the Python Home will not be deduced, so the core path from - the registry is used. Other "application paths "in the registry are + the registry is used. Other "application paths "in the registry are always read. * If Python can't find its home and there is no registry (eg, frozen @@ -85,12 +85,12 @@ static char *module_search_path = NULL; static int -is_sep(char ch) /* determine if "ch" is a separator character */ +is_sep(char ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -100,36 +100,36 @@ is_sep(char ch) /* determine if "ch" is a separator character */ static void reduce(char *dir) { - size_t i = strlen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + size_t i = strlen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(char *filename) { - struct stat buf; - return stat(filename, &buf) == 0; + struct stat buf; + return stat(filename, &buf) == 0; } /* Is module (check for .pyc/.pyo too) - * Assumes 'filename' MAXPATHLEN+1 bytes long - + * Assumes 'filename' MAXPATHLEN+1 bytes long - * may extend 'filename' by one character. */ static int ismodule(char *filename) { - if (exists(filename)) - return 1; - - /* Check for the compiled version of prefix. */ - if (strlen(filename) < MAXPATHLEN) { - strcat(filename, Py_OptimizeFlag ? "o" : "c"); - if (exists(filename)) - return 1; - } - return 0; + if (exists(filename)) + return 1; + + /* Check for the compiled version of prefix. */ + if (strlen(filename) < MAXPATHLEN) { + strcat(filename, Py_OptimizeFlag ? "o" : "c"); + if (exists(filename)) + return 1; + } + return 0; } /* Add a path component, by appending stuff to buffer. @@ -145,21 +145,21 @@ ismodule(char *filename) static void join(char *buffer, char *stuff) { - size_t n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = strlen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = strlen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + size_t n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = strlen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = strlen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + strncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } /* gotlandmark only called by search_for_prefix, which ensures @@ -169,219 +169,219 @@ join(char *buffer, char *stuff) static int gotlandmark(char *landmark) { - int n, ok; + int n, ok; - n = strlen(prefix); - join(prefix, landmark); - ok = ismodule(prefix); - prefix[n] = '\0'; - return ok; + n = strlen(prefix); + join(prefix, landmark); + ok = ismodule(prefix); + prefix[n] = '\0'; + return ok; } -/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. +/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd. * assumption provided by only caller, calculate_path() */ static int search_for_prefix(char *argv0_path, char *landmark) { - /* Search from argv0_path, until landmark is found */ - strcpy(prefix, argv0_path); - do { - if (gotlandmark(landmark)) - return 1; - reduce(prefix); - } while (prefix[0]); - return 0; + /* Search from argv0_path, until landmark is found */ + strcpy(prefix, argv0_path); + do { + if (gotlandmark(landmark)) + return 1; + reduce(prefix); + } while (prefix[0]); + return 0; } static void get_progpath(void) { - extern char *Py_GetProgramName(void); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); - - PPIB pib; - if ((DosGetInfoBlocks(NULL, &pib) == 0) && - (DosQueryModuleName(pib->pib_hmte, sizeof(progpath), progpath) == 0)) - return; - - if (prog == NULL || *prog == '\0') - prog = "python"; - - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ + extern char *Py_GetProgramName(void); + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); + + PPIB pib; + if ((DosGetInfoBlocks(NULL, &pib) == 0) && + (DosQueryModuleName(pib->pib_hmte, sizeof(progpath), progpath) == 0)) + return; + + if (prog == NULL || *prog == '\0') + prog = "python"; + + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ #ifdef ALTSEP - if (strchr(prog, SEP) || strchr(prog, ALTSEP)) + if (strchr(prog, SEP) || strchr(prog, ALTSEP)) #else - if (strchr(prog, SEP)) + if (strchr(prog, SEP)) #endif - strncpy(progpath, prog, MAXPATHLEN); - else if (path) { - while (1) { - char *delim = strchr(path, DELIM); - - if (delim) { - size_t len = delim - path; - /* ensure we can't overwrite buffer */ + strncpy(progpath, prog, MAXPATHLEN); + else if (path) { + while (1) { + char *delim = strchr(path, DELIM); + + if (delim) { + size_t len = delim - path; + /* ensure we can't overwrite buffer */ #if !defined(PYCC_GCC) - len = min(MAXPATHLEN,len); + len = min(MAXPATHLEN,len); #else - len = MAXPATHLEN < len ? MAXPATHLEN : len; + len = MAXPATHLEN < len ? MAXPATHLEN : len; #endif - strncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - strncpy(progpath, path, MAXPATHLEN); - - /* join() is safe for MAXPATHLEN+1 size buffer */ - join(progpath, prog); - if (exists(progpath)) - break; - - if (!delim) { - progpath[0] = '\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; + strncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + strncpy(progpath, path, MAXPATHLEN); + + /* join() is safe for MAXPATHLEN+1 size buffer */ + join(progpath, prog); + if (exists(progpath)) + break; + + if (!delim) { + progpath[0] = '\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; } static void calculate_path(void) { - char argv0_path[MAXPATHLEN+1]; - char *buf; - size_t bufsz; - char *pythonhome = Py_GetPythonHome(); - char *envpath = getenv("PYTHONPATH"); - char zip_path[MAXPATHLEN+1]; - size_t len; - - get_progpath(); - /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ - strcpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else - strncpy(prefix, pythonhome, MAXPATHLEN); - - if (envpath && *envpath == '\0') - envpath = NULL; - - /* Calculate zip archive path */ - strncpy(zip_path, progpath, MAXPATHLEN); - zip_path[MAXPATHLEN] = '\0'; - len = strlen(zip_path); - if (len > 4) { - zip_path[len-3] = 'z'; /* change ending to "zip" */ - zip_path[len-2] = 'i'; - zip_path[len-1] = 'p'; - } - else { - zip_path[0] = 0; - } - - /* We need to construct a path from the following parts. - * (1) the PYTHONPATH environment variable, if set; - * (2) the zip archive file path; - * (3) the PYTHONPATH config macro, with the leading "." - * of each component replaced with pythonhome, if set; - * (4) the directory containing the executable (argv0_path). - * The length calculation calculates #3 first. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - char *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= strlen(pythonhome); - } - else - bufsz = 0; - bufsz += strlen(PYTHONPATH) + 1; - bufsz += strlen(argv0_path) + 1; - bufsz += strlen(zip_path) + 1; - if (envpath != NULL) - bufsz += strlen(envpath) + 1; - - module_search_path = buf = malloc(bufsz); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using default static path.\n"); - module_search_path = PYTHONPATH; - } - return; - } - - if (envpath) { - strcpy(buf, envpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - if (zip_path[0]) { - strcpy(buf, zip_path); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - - if (pythonhome == NULL) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); - } - else { - char *p = PYTHONPATH; - char *q; - size_t n; - for (;;) { - q = strchr(p, DELIM); - if (q == NULL) - n = strlen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - strcpy(buf, pythonhome); - buf = strchr(buf, '\0'); - p++; - n--; - } - strncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - strcpy(buf, argv0_path); - buf = strchr(buf, '\0'); - } - *buf = '\0'; + char argv0_path[MAXPATHLEN+1]; + char *buf; + size_t bufsz; + char *pythonhome = Py_GetPythonHome(); + char *envpath = getenv("PYTHONPATH"); + char zip_path[MAXPATHLEN+1]; + size_t len; + + get_progpath(); + /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */ + strcpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else + strncpy(prefix, pythonhome, MAXPATHLEN); + + if (envpath && *envpath == '\0') + envpath = NULL; + + /* Calculate zip archive path */ + strncpy(zip_path, progpath, MAXPATHLEN); + zip_path[MAXPATHLEN] = '\0'; + len = strlen(zip_path); + if (len > 4) { + zip_path[len-3] = 'z'; /* change ending to "zip" */ + zip_path[len-2] = 'i'; + zip_path[len-1] = 'p'; + } + else { + zip_path[0] = 0; + } + + /* We need to construct a path from the following parts. + * (1) the PYTHONPATH environment variable, if set; + * (2) the zip archive file path; + * (3) the PYTHONPATH config macro, with the leading "." + * of each component replaced with pythonhome, if set; + * (4) the directory containing the executable (argv0_path). + * The length calculation calculates #3 first. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + char *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= strlen(pythonhome); + } + else + bufsz = 0; + bufsz += strlen(PYTHONPATH) + 1; + bufsz += strlen(argv0_path) + 1; + bufsz += strlen(zip_path) + 1; + if (envpath != NULL) + bufsz += strlen(envpath) + 1; + + module_search_path = buf = malloc(bufsz); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using default static path.\n"); + module_search_path = PYTHONPATH; + } + return; + } + + if (envpath) { + strcpy(buf, envpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + if (zip_path[0]) { + strcpy(buf, zip_path); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + + if (pythonhome == NULL) { + strcpy(buf, PYTHONPATH); + buf = strchr(buf, '\0'); + } + else { + char *p = PYTHONPATH; + char *q; + size_t n; + for (;;) { + q = strchr(p, DELIM); + if (q == NULL) + n = strlen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + strcpy(buf, pythonhome); + buf = strchr(buf, '\0'); + p++; + n--; + } + strncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + strcpy(buf, argv0_path); + buf = strchr(buf, '\0'); + } + *buf = '\0'; } @@ -390,29 +390,29 @@ calculate_path(void) char * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); - return module_search_path; + if (!module_search_path) + calculate_path(); + return module_search_path; } char * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); - return prefix; + if (!module_search_path) + calculate_path(); + return prefix; } char * Py_GetExecPrefix(void) { - return Py_GetPrefix(); + return Py_GetPrefix(); } char * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); - return progpath; + if (!module_search_path) + calculate_path(); + return progpath; } diff --git a/PC/os2emx/pythonpm.c b/PC/os2emx/pythonpm.c index 5accbbd..ba47f4b 100644 --- a/PC/os2emx/pythonpm.c +++ b/PC/os2emx/pythonpm.c @@ -27,10 +27,10 @@ /* use structure to pass command line to Python thread */ typedef struct { - int argc; - char **argv; - HWND Frame; - int running; + int argc; + char **argv; + HWND Frame; + int running; } arglist; /* make this a global to simplify access. @@ -45,80 +45,80 @@ void PythonThread(void *); int main(int argc, char **argv) { - ULONG FrameFlags = FCF_TITLEBAR | - FCF_SYSMENU | - FCF_SIZEBORDER | - FCF_HIDEBUTTON | - FCF_SHELLPOSITION | - FCF_TASKLIST; - HAB hab; - HMQ hmq; - HWND Client; - QMSG qmsg; - arglist args; - int python_tid; - - /* init PM and create message queue */ - hab = WinInitialize(0); - hmq = WinCreateMsgQueue(hab, 0); - - /* create a (hidden) Window to house the window procedure */ - args.Frame = WinCreateStdWindow(HWND_DESKTOP, - 0, - &FrameFlags, - NULL, - "PythonPM", - 0L, - 0, - 0, - &Client); - - /* run Python interpreter in a thread */ - args.argc = argc; - args.argv = argv; - args.running = 0; - if (-1 == (python_tid = _beginthread(PythonThread, NULL, 1024 * 1024, &args))) - { - /* couldn't start thread */ - WinAlarm(HWND_DESKTOP, WA_ERROR); - PythonRC = 1; - } - else - { - /* process PM messages, until Python exits */ - while (WinGetMsg(hab, &qmsg, NULLHANDLE, 0, 0)) - WinDispatchMsg(hab, &qmsg); - if (args.running > 0) - DosKillThread(python_tid); - } - - /* destroy window, shutdown message queue and PM */ - WinDestroyWindow(args.Frame); - WinDestroyMsgQueue(hmq); - WinTerminate(hab); - - return PythonRC; + ULONG FrameFlags = FCF_TITLEBAR | + FCF_SYSMENU | + FCF_SIZEBORDER | + FCF_HIDEBUTTON | + FCF_SHELLPOSITION | + FCF_TASKLIST; + HAB hab; + HMQ hmq; + HWND Client; + QMSG qmsg; + arglist args; + int python_tid; + + /* init PM and create message queue */ + hab = WinInitialize(0); + hmq = WinCreateMsgQueue(hab, 0); + + /* create a (hidden) Window to house the window procedure */ + args.Frame = WinCreateStdWindow(HWND_DESKTOP, + 0, + &FrameFlags, + NULL, + "PythonPM", + 0L, + 0, + 0, + &Client); + + /* run Python interpreter in a thread */ + args.argc = argc; + args.argv = argv; + args.running = 0; + if (-1 == (python_tid = _beginthread(PythonThread, NULL, 1024 * 1024, &args))) + { + /* couldn't start thread */ + WinAlarm(HWND_DESKTOP, WA_ERROR); + PythonRC = 1; + } + else + { + /* process PM messages, until Python exits */ + while (WinGetMsg(hab, &qmsg, NULLHANDLE, 0, 0)) + WinDispatchMsg(hab, &qmsg); + if (args.running > 0) + DosKillThread(python_tid); + } + + /* destroy window, shutdown message queue and PM */ + WinDestroyWindow(args.Frame); + WinDestroyMsgQueue(hmq); + WinTerminate(hab); + + return PythonRC; } void PythonThread(void *argl) { - HAB hab; - arglist *args; + HAB hab; + arglist *args; - /* PM initialisation */ - hab = WinInitialize(0); + /* PM initialisation */ + hab = WinInitialize(0); - /* start Python */ - args = (arglist *)argl; - args->running = 1; - PythonRC = Py_Main(args->argc, args->argv); + /* start Python */ + args = (arglist *)argl; + args->running = 1; + PythonRC = Py_Main(args->argc, args->argv); - /* enter a critical section and send the termination message */ - DosEnterCritSec(); - args->running = 0; - WinPostMsg(args->Frame, WM_QUIT, NULL, NULL); + /* enter a critical section and send the termination message */ + DosEnterCritSec(); + args->running = 0; + WinPostMsg(args->Frame, WM_QUIT, NULL, NULL); - /* shutdown PM and terminate thread */ - WinTerminate(hab); - _endthread(); + /* shutdown PM and terminate thread */ + WinTerminate(hab); + _endthread(); } diff --git a/PC/os2vacpp/getpathp.c b/PC/os2vacpp/getpathp.c index 607f2a1..5bc2827 100644 --- a/PC/os2vacpp/getpathp.c +++ b/PC/os2vacpp/getpathp.c @@ -55,12 +55,12 @@ static char *module_search_path = NULL; static int -is_sep(char ch) /* determine if "ch" is a separator character */ +is_sep(char ch) /* determine if "ch" is a separator character */ { #ifdef ALTSEP - return ch == SEP || ch == ALTSEP; + return ch == SEP || ch == ALTSEP; #else - return ch == SEP; + return ch == SEP; #endif } @@ -68,18 +68,18 @@ is_sep(char ch) /* determine if "ch" is a separator character */ static void reduce(char *dir) { - int i = strlen(dir); - while (i > 0 && !is_sep(dir[i])) - --i; - dir[i] = '\0'; + int i = strlen(dir); + while (i > 0 && !is_sep(dir[i])) + --i; + dir[i] = '\0'; } - + static int exists(char *filename) { - struct stat buf; - return stat(filename, &buf) == 0; + struct stat buf; + return stat(filename, &buf) == 0; } @@ -95,42 +95,42 @@ exists(char *filename) static void join(char *buffer, char *stuff) { - int n, k; - if (is_sep(stuff[0])) - n = 0; - else { - n = strlen(buffer); - if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) - buffer[n++] = SEP; - } - if (n > MAXPATHLEN) - Py_FatalError("buffer overflow in getpathp.c's joinpath()"); - k = strlen(stuff); - if (n + k > MAXPATHLEN) - k = MAXPATHLEN - n; - strncpy(buffer+n, stuff, k); - buffer[n+k] = '\0'; + int n, k; + if (is_sep(stuff[0])) + n = 0; + else { + n = strlen(buffer); + if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN) + buffer[n++] = SEP; + } + if (n > MAXPATHLEN) + Py_FatalError("buffer overflow in getpathp.c's joinpath()"); + k = strlen(stuff); + if (n + k > MAXPATHLEN) + k = MAXPATHLEN - n; + strncpy(buffer+n, stuff, k); + buffer[n+k] = '\0'; } static int search_for_prefix(char *argv0_path, char *landmark) { - int n; - - /* Search from argv0_path, until root is found */ - strcpy(prefix, argv0_path); - do { - n = strlen(prefix); - join(prefix, landmark); - if (exists(prefix)) { - prefix[n] = '\0'; - return 1; - } - prefix[n] = '\0'; - reduce(prefix); - } while (prefix[0]); - return 0; + int n; + + /* Search from argv0_path, until root is found */ + strcpy(prefix, argv0_path); + do { + n = strlen(prefix); + join(prefix, landmark); + if (exists(prefix)) { + prefix[n] = '\0'; + return 1; + } + prefix[n] = '\0'; + reduce(prefix); + } while (prefix[0]); + return 0; } #ifdef MS_WIN32 @@ -147,299 +147,299 @@ extern const char *PyWin_DLLVersionString; // a string loaded from the DLL at st static char * getpythonregpath(HKEY keyBase, BOOL bWin32s) { - HKEY newKey = 0; - DWORD nameSize = 0; - DWORD dataSize = 0; - DWORD numEntries = 0; - LONG rc; - char *retval = NULL; - char *dataBuf; - const char keyPrefix[] = "Software\\Python\\PythonCore\\"; - const char keySuffix[] = "\\PythonPath"; - int versionLen; - char *keyBuf; - - // Tried to use sysget("winver") but here is too early :-( - versionLen = strlen(PyWin_DLLVersionString); - // alloca == no free required, but memory only local to fn. - // also no heap fragmentation! Am I being silly? - keyBuf = alloca(sizeof(keyPrefix)-1 + versionLen + sizeof(keySuffix)); // chars only, plus 1 NULL. - // lots of constants here for the compiler to optimize away :-) - memcpy(keyBuf, keyPrefix, sizeof(keyPrefix)-1); - memcpy(keyBuf+sizeof(keyPrefix)-1, PyWin_DLLVersionString, versionLen); - memcpy(keyBuf+sizeof(keyPrefix)-1+versionLen, keySuffix, sizeof(keySuffix)); // NULL comes with this one! - - rc=RegOpenKey(keyBase, - keyBuf, - &newKey); - if (rc==ERROR_SUCCESS) { - RegQueryInfoKey(newKey, NULL, NULL, NULL, NULL, NULL, NULL, - &numEntries, &nameSize, &dataSize, NULL, NULL); - } - if (bWin32s && numEntries==0 && dataSize==0) { - /* must hardcode for Win32s */ - numEntries = 1; - dataSize = 511; - } - if (numEntries) { - /* Loop over all subkeys. */ - /* Win32s doesnt know how many subkeys, so we do - it twice */ - char keyBuf[MAX_PATH+1]; - int index = 0; - int off = 0; - for(index=0;;index++) { - long reqdSize = 0; - DWORD rc = RegEnumKey(newKey, - index, keyBuf, MAX_PATH+1); - if (rc) break; - rc = RegQueryValue(newKey, keyBuf, NULL, &reqdSize); - if (rc) break; - if (bWin32s && reqdSize==0) reqdSize = 512; - dataSize += reqdSize + 1; /* 1 for the ";" */ - } - dataBuf = malloc(dataSize+1); - if (dataBuf==NULL) - return NULL; /* pretty serious? Raise error? */ - /* Now loop over, grabbing the paths. - Subkeys before main library */ - for(index=0;;index++) { - int adjust; - long reqdSize = dataSize; - DWORD rc = RegEnumKey(newKey, - index, keyBuf,MAX_PATH+1); - if (rc) break; - rc = RegQueryValue(newKey, - keyBuf, dataBuf+off, &reqdSize); - if (rc) break; - if (reqdSize>1) { - /* If Nothing, or only '\0' copied. */ - adjust = strlen(dataBuf+off); - dataSize -= adjust; - off += adjust; - dataBuf[off++] = ';'; - dataBuf[off] = '\0'; - dataSize--; - } - } - /* Additionally, win32s doesnt work as expected, so - the specific strlen() is required for 3.1. */ - rc = RegQueryValue(newKey, "", dataBuf+off, &dataSize); - if (rc==ERROR_SUCCESS) { - if (strlen(dataBuf)==0) - free(dataBuf); - else - retval = dataBuf; /* caller will free */ - } - else - free(dataBuf); - } - - if (newKey) - RegCloseKey(newKey); - return retval; + HKEY newKey = 0; + DWORD nameSize = 0; + DWORD dataSize = 0; + DWORD numEntries = 0; + LONG rc; + char *retval = NULL; + char *dataBuf; + const char keyPrefix[] = "Software\\Python\\PythonCore\\"; + const char keySuffix[] = "\\PythonPath"; + int versionLen; + char *keyBuf; + + // Tried to use sysget("winver") but here is too early :-( + versionLen = strlen(PyWin_DLLVersionString); + // alloca == no free required, but memory only local to fn. + // also no heap fragmentation! Am I being silly? + keyBuf = alloca(sizeof(keyPrefix)-1 + versionLen + sizeof(keySuffix)); // chars only, plus 1 NULL. + // lots of constants here for the compiler to optimize away :-) + memcpy(keyBuf, keyPrefix, sizeof(keyPrefix)-1); + memcpy(keyBuf+sizeof(keyPrefix)-1, PyWin_DLLVersionString, versionLen); + memcpy(keyBuf+sizeof(keyPrefix)-1+versionLen, keySuffix, sizeof(keySuffix)); // NULL comes with this one! + + rc=RegOpenKey(keyBase, + keyBuf, + &newKey); + if (rc==ERROR_SUCCESS) { + RegQueryInfoKey(newKey, NULL, NULL, NULL, NULL, NULL, NULL, + &numEntries, &nameSize, &dataSize, NULL, NULL); + } + if (bWin32s && numEntries==0 && dataSize==0) { + /* must hardcode for Win32s */ + numEntries = 1; + dataSize = 511; + } + if (numEntries) { + /* Loop over all subkeys. */ + /* Win32s doesnt know how many subkeys, so we do + it twice */ + char keyBuf[MAX_PATH+1]; + int index = 0; + int off = 0; + for(index=0;;index++) { + long reqdSize = 0; + DWORD rc = RegEnumKey(newKey, + index, keyBuf, MAX_PATH+1); + if (rc) break; + rc = RegQueryValue(newKey, keyBuf, NULL, &reqdSize); + if (rc) break; + if (bWin32s && reqdSize==0) reqdSize = 512; + dataSize += reqdSize + 1; /* 1 for the ";" */ + } + dataBuf = malloc(dataSize+1); + if (dataBuf==NULL) + return NULL; /* pretty serious? Raise error? */ + /* Now loop over, grabbing the paths. + Subkeys before main library */ + for(index=0;;index++) { + int adjust; + long reqdSize = dataSize; + DWORD rc = RegEnumKey(newKey, + index, keyBuf,MAX_PATH+1); + if (rc) break; + rc = RegQueryValue(newKey, + keyBuf, dataBuf+off, &reqdSize); + if (rc) break; + if (reqdSize>1) { + /* If Nothing, or only '\0' copied. */ + adjust = strlen(dataBuf+off); + dataSize -= adjust; + off += adjust; + dataBuf[off++] = ';'; + dataBuf[off] = '\0'; + dataSize--; + } + } + /* Additionally, win32s doesnt work as expected, so + the specific strlen() is required for 3.1. */ + rc = RegQueryValue(newKey, "", dataBuf+off, &dataSize); + if (rc==ERROR_SUCCESS) { + if (strlen(dataBuf)==0) + free(dataBuf); + else + retval = dataBuf; /* caller will free */ + } + else + free(dataBuf); + } + + if (newKey) + RegCloseKey(newKey); + return retval; } #endif /* MS_WIN32 */ static void get_progpath(void) { - extern char *Py_GetProgramName(void); - char *path = getenv("PATH"); - char *prog = Py_GetProgramName(); + extern char *Py_GetProgramName(void); + char *path = getenv("PATH"); + char *prog = Py_GetProgramName(); #ifdef MS_WIN32 - if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) - return; + if (GetModuleFileName(NULL, progpath, MAXPATHLEN)) + return; #endif - if (prog == NULL || *prog == '\0') - prog = "python"; - - /* If there is no slash in the argv0 path, then we have to - * assume python is on the user's $PATH, since there's no - * other way to find a directory to start the search from. If - * $PATH isn't exported, you lose. - */ + if (prog == NULL || *prog == '\0') + prog = "python"; + + /* If there is no slash in the argv0 path, then we have to + * assume python is on the user's $PATH, since there's no + * other way to find a directory to start the search from. If + * $PATH isn't exported, you lose. + */ #ifdef ALTSEP - if (strchr(prog, SEP) || strchr(prog, ALTSEP)) + if (strchr(prog, SEP) || strchr(prog, ALTSEP)) #else - if (strchr(prog, SEP)) + if (strchr(prog, SEP)) #endif - strcpy(progpath, prog); - else if (path) { - while (1) { - char *delim = strchr(path, DELIM); - - if (delim) { - int len = delim - path; - strncpy(progpath, path, len); - *(progpath + len) = '\0'; - } - else - strcpy(progpath, path); - - join(progpath, prog); - if (exists(progpath)) - break; - - if (!delim) { - progpath[0] = '\0'; - break; - } - path = delim + 1; - } - } - else - progpath[0] = '\0'; + strcpy(progpath, prog); + else if (path) { + while (1) { + char *delim = strchr(path, DELIM); + + if (delim) { + int len = delim - path; + strncpy(progpath, path, len); + *(progpath + len) = '\0'; + } + else + strcpy(progpath, path); + + join(progpath, prog); + if (exists(progpath)) + break; + + if (!delim) { + progpath[0] = '\0'; + break; + } + path = delim + 1; + } + } + else + progpath[0] = '\0'; } static void calculate_path(void) { - char argv0_path[MAXPATHLEN+1]; - char *buf; - int bufsz; - char *pythonhome = Py_GetPythonHome(); - char *envpath = Py_GETENV("PYTHONPATH"); + char argv0_path[MAXPATHLEN+1]; + char *buf; + int bufsz; + char *pythonhome = Py_GetPythonHome(); + char *envpath = Py_GETENV("PYTHONPATH"); #ifdef MS_WIN32 - char *machinepath, *userpath; - - /* Are we running under Windows 3.1(1) Win32s? */ - if (PyWin_IsWin32s()) { - /* Only CLASSES_ROOT is supported */ - machinepath = getpythonregpath(HKEY_CLASSES_ROOT, TRUE); - userpath = NULL; - } else { - machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, FALSE); - userpath = getpythonregpath(HKEY_CURRENT_USER, FALSE); - } + char *machinepath, *userpath; + + /* Are we running under Windows 3.1(1) Win32s? */ + if (PyWin_IsWin32s()) { + /* Only CLASSES_ROOT is supported */ + machinepath = getpythonregpath(HKEY_CLASSES_ROOT, TRUE); + userpath = NULL; + } else { + machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, FALSE); + userpath = getpythonregpath(HKEY_CURRENT_USER, FALSE); + } #endif - get_progpath(); - strcpy(argv0_path, progpath); - reduce(argv0_path); - if (pythonhome == NULL || *pythonhome == '\0') { - if (search_for_prefix(argv0_path, LANDMARK)) - pythonhome = prefix; - else - pythonhome = NULL; - } - else { - char *delim; - - strcpy(prefix, pythonhome); - - /* Extract Any Optional Trailing EXEC_PREFIX */ - /* e.g. PYTHONHOME=<prefix>:<exec_prefix> */ - delim = strchr(prefix, DELIM); - if (delim) { - *delim = '\0'; - strcpy(exec_prefix, delim+1); - } else - strcpy(exec_prefix, EXEC_PREFIX); + get_progpath(); + strcpy(argv0_path, progpath); + reduce(argv0_path); + if (pythonhome == NULL || *pythonhome == '\0') { + if (search_for_prefix(argv0_path, LANDMARK)) + pythonhome = prefix; + else + pythonhome = NULL; + } + else { + char *delim; + + strcpy(prefix, pythonhome); + + /* Extract Any Optional Trailing EXEC_PREFIX */ + /* e.g. PYTHONHOME=<prefix>:<exec_prefix> */ + delim = strchr(prefix, DELIM); + if (delim) { + *delim = '\0'; + strcpy(exec_prefix, delim+1); + } else + strcpy(exec_prefix, EXEC_PREFIX); } - if (envpath && *envpath == '\0') - envpath = NULL; - - /* We need to construct a path from the following parts: - (1) the PYTHONPATH environment variable, if set; - (2) for Win32, the machinepath and userpath, if set; - (3) the PYTHONPATH config macro, with the leading "." - of each component replaced with pythonhome, if set; - (4) the directory containing the executable (argv0_path). - The length calculation calculates #3 first. - */ - - /* Calculate size of return buffer */ - if (pythonhome != NULL) { - char *p; - bufsz = 1; - for (p = PYTHONPATH; *p; p++) { - if (*p == DELIM) - bufsz++; /* number of DELIM plus one */ - } - bufsz *= strlen(pythonhome); - } - else - bufsz = 0; - bufsz += strlen(PYTHONPATH) + 1; - if (envpath != NULL) - bufsz += strlen(envpath) + 1; - bufsz += strlen(argv0_path) + 1; + if (envpath && *envpath == '\0') + envpath = NULL; + + /* We need to construct a path from the following parts: + (1) the PYTHONPATH environment variable, if set; + (2) for Win32, the machinepath and userpath, if set; + (3) the PYTHONPATH config macro, with the leading "." + of each component replaced with pythonhome, if set; + (4) the directory containing the executable (argv0_path). + The length calculation calculates #3 first. + */ + + /* Calculate size of return buffer */ + if (pythonhome != NULL) { + char *p; + bufsz = 1; + for (p = PYTHONPATH; *p; p++) { + if (*p == DELIM) + bufsz++; /* number of DELIM plus one */ + } + bufsz *= strlen(pythonhome); + } + else + bufsz = 0; + bufsz += strlen(PYTHONPATH) + 1; + if (envpath != NULL) + bufsz += strlen(envpath) + 1; + bufsz += strlen(argv0_path) + 1; #ifdef MS_WIN32 - if (machinepath) - bufsz += strlen(machinepath) + 1; - if (userpath) - bufsz += strlen(userpath) + 1; + if (machinepath) + bufsz += strlen(machinepath) + 1; + if (userpath) + bufsz += strlen(userpath) + 1; #endif - module_search_path = buf = malloc(bufsz); - if (buf == NULL) { - /* We can't exit, so print a warning and limp along */ - fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); - if (envpath) { - fprintf(stderr, "Using default static $PYTHONPATH.\n"); - module_search_path = envpath; - } - else { - fprintf(stderr, "Using environment $PYTHONPATH.\n"); - module_search_path = PYTHONPATH; - } - return; - } - - if (envpath) { - strcpy(buf, envpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } + module_search_path = buf = malloc(bufsz); + if (buf == NULL) { + /* We can't exit, so print a warning and limp along */ + fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n"); + if (envpath) { + fprintf(stderr, "Using default static $PYTHONPATH.\n"); + module_search_path = envpath; + } + else { + fprintf(stderr, "Using environment $PYTHONPATH.\n"); + module_search_path = PYTHONPATH; + } + return; + } + + if (envpath) { + strcpy(buf, envpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } #ifdef MS_WIN32 - if (machinepath) { - strcpy(buf, machinepath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } - if (userpath) { - strcpy(buf, userpath); - buf = strchr(buf, '\0'); - *buf++ = DELIM; - } + if (machinepath) { + strcpy(buf, machinepath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } + if (userpath) { + strcpy(buf, userpath); + buf = strchr(buf, '\0'); + *buf++ = DELIM; + } #endif - if (pythonhome == NULL) { - strcpy(buf, PYTHONPATH); - buf = strchr(buf, '\0'); - } - else { - char *p = PYTHONPATH; - char *q; - int n; - for (;;) { - q = strchr(p, DELIM); - if (q == NULL) - n = strlen(p); - else - n = q-p; - if (p[0] == '.' && is_sep(p[1])) { - strcpy(buf, pythonhome); - buf = strchr(buf, '\0'); - p++; - n--; - } - strncpy(buf, p, n); - buf += n; - if (q == NULL) - break; - *buf++ = DELIM; - p = q+1; - } - } - if (argv0_path) { - *buf++ = DELIM; - strcpy(buf, argv0_path); - buf = strchr(buf, '\0'); - } - *buf = '\0'; + if (pythonhome == NULL) { + strcpy(buf, PYTHONPATH); + buf = strchr(buf, '\0'); + } + else { + char *p = PYTHONPATH; + char *q; + int n; + for (;;) { + q = strchr(p, DELIM); + if (q == NULL) + n = strlen(p); + else + n = q-p; + if (p[0] == '.' && is_sep(p[1])) { + strcpy(buf, pythonhome); + buf = strchr(buf, '\0'); + p++; + n--; + } + strncpy(buf, p, n); + buf += n; + if (q == NULL) + break; + *buf++ = DELIM; + p = q+1; + } + } + if (argv0_path) { + *buf++ = DELIM; + strcpy(buf, argv0_path); + buf = strchr(buf, '\0'); + } + *buf = '\0'; } @@ -448,35 +448,35 @@ calculate_path(void) char * Py_GetPath(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return module_search_path; + return module_search_path; } char * Py_GetPrefix(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return prefix; + return prefix; } char * Py_GetExecPrefix(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return exec_prefix; + return exec_prefix; } char * Py_GetProgramFullPath(void) { - if (!module_search_path) - calculate_path(); + if (!module_search_path) + calculate_path(); - return progpath; + return progpath; } diff --git a/PC/winsound.c b/PC/winsound.c index e6ff226..05305d2 100644 --- a/PC/winsound.c +++ b/PC/winsound.c @@ -78,14 +78,14 @@ sound_playsound(PyObject *s, PyObject *args) int ok; if(!PyArg_ParseTuple(args,"z#i:PlaySound",&sound,&length,&flags)) { - return NULL; + return NULL; } if(flags&SND_ASYNC && flags &SND_MEMORY) { - /* Sidestep reference counting headache; unfortunately this also - prevent SND_LOOP from memory. */ - PyErr_SetString(PyExc_RuntimeError,"Cannot play asynchronously from memory"); - return NULL; + /* Sidestep reference counting headache; unfortunately this also + prevent SND_LOOP from memory. */ + PyErr_SetString(PyExc_RuntimeError,"Cannot play asynchronously from memory"); + return NULL; } Py_BEGIN_ALLOW_THREADS @@ -93,8 +93,8 @@ sound_playsound(PyObject *s, PyObject *args) Py_END_ALLOW_THREADS if(!ok) { - PyErr_SetString(PyExc_RuntimeError,"Failed to play sound"); - return NULL; + PyErr_SetString(PyExc_RuntimeError,"Failed to play sound"); + return NULL; } Py_INCREF(Py_None); @@ -104,40 +104,40 @@ sound_playsound(PyObject *s, PyObject *args) static PyObject * sound_beep(PyObject *self, PyObject *args) { - int freq; - int dur; - BOOL ok; - - if (!PyArg_ParseTuple(args, "ii:Beep", &freq, &dur)) - return NULL; - - if (freq < 37 || freq > 32767) { - PyErr_SetString(PyExc_ValueError, - "frequency must be in 37 thru 32767"); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - ok = Beep(freq, dur); - Py_END_ALLOW_THREADS - if (!ok) { - PyErr_SetString(PyExc_RuntimeError,"Failed to beep"); - return NULL; - } - - Py_INCREF(Py_None); - return Py_None; + int freq; + int dur; + BOOL ok; + + if (!PyArg_ParseTuple(args, "ii:Beep", &freq, &dur)) + return NULL; + + if (freq < 37 || freq > 32767) { + PyErr_SetString(PyExc_ValueError, + "frequency must be in 37 thru 32767"); + return NULL; + } + + Py_BEGIN_ALLOW_THREADS + ok = Beep(freq, dur); + Py_END_ALLOW_THREADS + if (!ok) { + PyErr_SetString(PyExc_RuntimeError,"Failed to beep"); + return NULL; + } + + Py_INCREF(Py_None); + return Py_None; } static PyObject * sound_msgbeep(PyObject *self, PyObject *args) { - int x = MB_OK; - if (!PyArg_ParseTuple(args, "|i:MessageBeep", &x)) - return NULL; - MessageBeep(x); - Py_INCREF(Py_None); - return Py_None; + int x = MB_OK; + if (!PyArg_ParseTuple(args, "|i:MessageBeep", &x)) + return NULL; + MessageBeep(x); + Py_INCREF(Py_None); + return Py_None; } static struct PyMethodDef sound_methods[] = @@ -155,7 +155,7 @@ add_define(PyObject *dict, const char *key, long value) PyObject *v=PyLong_FromLong(value); if(v&&k) { - PyDict_SetItem(dict,k,v); + PyDict_SetItem(dict,k,v); } Py_XDECREF(k); Py_XDECREF(v); @@ -166,28 +166,28 @@ add_define(PyObject *dict, const char *key, long value) PyMODINIT_FUNC initwinsound(void) { - PyObject *dict; - PyObject *module = Py_InitModule3("winsound", - sound_methods, - sound_module_doc); - if (module == NULL) - return; - dict = PyModule_GetDict(module); - - ADD_DEFINE(SND_ASYNC); - ADD_DEFINE(SND_NODEFAULT); - ADD_DEFINE(SND_NOSTOP); - ADD_DEFINE(SND_NOWAIT); - ADD_DEFINE(SND_ALIAS); - ADD_DEFINE(SND_FILENAME); - ADD_DEFINE(SND_MEMORY); - ADD_DEFINE(SND_PURGE); - ADD_DEFINE(SND_LOOP); - ADD_DEFINE(SND_APPLICATION); - - ADD_DEFINE(MB_OK); - ADD_DEFINE(MB_ICONASTERISK); - ADD_DEFINE(MB_ICONEXCLAMATION); - ADD_DEFINE(MB_ICONHAND); - ADD_DEFINE(MB_ICONQUESTION); + PyObject *dict; + PyObject *module = Py_InitModule3("winsound", + sound_methods, + sound_module_doc); + if (module == NULL) + return; + dict = PyModule_GetDict(module); + + ADD_DEFINE(SND_ASYNC); + ADD_DEFINE(SND_NODEFAULT); + ADD_DEFINE(SND_NOSTOP); + ADD_DEFINE(SND_NOWAIT); + ADD_DEFINE(SND_ALIAS); + ADD_DEFINE(SND_FILENAME); + ADD_DEFINE(SND_MEMORY); + ADD_DEFINE(SND_PURGE); + ADD_DEFINE(SND_LOOP); + ADD_DEFINE(SND_APPLICATION); + + ADD_DEFINE(MB_OK); + ADD_DEFINE(MB_ICONASTERISK); + ADD_DEFINE(MB_ICONEXCLAMATION); + ADD_DEFINE(MB_ICONHAND); + ADD_DEFINE(MB_ICONQUESTION); } |