wchar_t* _Py_wgetcwd(wchar_t *buf, size_t size) { #ifdef MS_WINDOWS int isize = (int)Py_MIN(size, INT_MAX); return _wgetcwd(buf, isize); #else char fname[MAXPATHLEN]; wchar_t *wname; size_t len; if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL) return NULL; wname = _Py_char2wchar(fname, &len); if (wname == NULL) return NULL; if (size <= len) { PyMem_RawFree(wname); return NULL; } wcsncpy(buf, wname, size); PyMem_RawFree(wname); return buf; #endif }
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+Py_ARRAY_LENGTH(possibleModules)-2; modName >= possibleModules; *modName--) CallModuleDllMain(*modName, DLL_PROCESS_DETACH); break; } } return ret; }
/* Called by a frozen .EXE only, so that built-in extension modules are cleaned up */ void PyWinFreeze_ExeTerm(void) { // Must go backwards char **modName; for (modName = possibleModules+Py_ARRAY_LENGTH(possibleModules)-2; modName >= possibleModules; *modName--) { /* printf("Terminating '%s'\n", *modName);*/ CallModuleDllMain(*modName, DLL_PROCESS_DETACH); } }
static int build_namelists (PyObject *module) { PyObject *labels; PyObject *names; PyObject *s; int num_controls; int i; num_controls = Py_ARRAY_LENGTH(control_labels); assert(num_controls == Py_ARRAY_LENGTH(control_names)); labels = PyList_New(num_controls); names = PyList_New(num_controls); if (labels == NULL || names == NULL) goto error2; for (i = 0; i < num_controls; i++) { s = PyUnicode_FromString(control_labels[i]); if (s == NULL) goto error2; PyList_SET_ITEM(labels, i, s); s = PyUnicode_FromString(control_names[i]); if (s == NULL) goto error2; PyList_SET_ITEM(names, i, s); } if (PyModule_AddObject(module, "control_labels", labels) == -1) goto error2; if (PyModule_AddObject(module, "control_names", names) == -1) goto error1; return 0; error2: Py_XDECREF(labels); error1: Py_XDECREF(names); return -1; }
static int test_initialize_pymain(void) { wchar_t *argv[] = {L"PYTHON", L"-c", L"import sys; print(f'Py_Main() after Py_Initialize: sys.argv={sys.argv}')", L"arg2"}; _testembed_Py_Initialize(); /* bpo-34008: Calling Py_Main() after Py_Initialize() must not crash */ Py_Main(Py_ARRAY_LENGTH(argv), argv); Py_Finalize(); return 0; }
int _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz) { char *cpath; char cbuf[MAXPATHLEN]; wchar_t *wbuf; int res; size_t r1; cpath = _Py_wchar2char(path, NULL); if (cpath == NULL) { errno = EINVAL; return -1; } res = (int)readlink(cpath, cbuf, Py_ARRAY_LENGTH(cbuf)); PyMem_Free(cpath); if (res == -1) return -1; if (res == Py_ARRAY_LENGTH(cbuf)) { errno = EINVAL; return -1; } cbuf[res] = '\0'; /* buf will be null terminated */ wbuf = _Py_char2wchar(cbuf, &r1); if (wbuf == NULL) { errno = EINVAL; return -1; } if (bufsiz <= r1) { PyMem_RawFree(wbuf); errno = EINVAL; return -1; } wcsncpy(buf, wbuf, bufsiz); PyMem_RawFree(wbuf); return (int)r1; }
wchar_t * Py_GetPythonHome(void) { wchar_t *home = default_home; if (home == NULL && !Py_IgnoreEnvironmentFlag) { char* chome = Py_GETENV("PYTHONHOME"); if (chome) { size_t size = Py_ARRAY_LENGTH(env_home); size_t r = mbstowcs(env_home, chome, size); if (r != (size_t)-1 && r < size) home = env_home; } } return home; }
static PyObject * partial_fastcall(partialobject *pto, PyObject **args, Py_ssize_t nargs, PyObject *kwargs) { PyObject *small_stack[_PY_FASTCALL_SMALL_STACK]; PyObject *ret; PyObject **stack, **stack_buf = NULL; Py_ssize_t nargs2, pto_nargs; pto_nargs = PyTuple_GET_SIZE(pto->args); nargs2 = pto_nargs + nargs; if (pto_nargs == 0) { stack = args; } else if (nargs == 0) { stack = &PyTuple_GET_ITEM(pto->args, 0); } else { if (nargs2 <= (Py_ssize_t)Py_ARRAY_LENGTH(small_stack)) { stack = small_stack; } else { stack_buf = PyMem_Malloc(nargs2 * sizeof(PyObject *)); if (stack_buf == NULL) { PyErr_NoMemory(); return NULL; } stack = stack_buf; } /* use borrowed references */ memcpy(stack, &PyTuple_GET_ITEM(pto->args, 0), pto_nargs * sizeof(PyObject*)); memcpy(&stack[pto_nargs], args, nargs * sizeof(PyObject*)); } ret = _PyObject_FastCallDict(pto->fn, stack, nargs2, kwargs); PyMem_Free(stack_buf); return ret; }
void _Py_DumpDecimal(int fd, unsigned long value) { /* maximum number of characters required for output of %lld or %p. We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits, plus 1 for the null byte. 53/22 is an upper bound for log10(256). */ char buffer[1 + (sizeof(unsigned long)*53-1) / 22 + 1]; char *ptr, *end; end = &buffer[Py_ARRAY_LENGTH(buffer) - 1]; ptr = end; *ptr = '\0'; do { --ptr; assert(ptr >= buffer); *ptr = '0' + (value % 10); value /= 10; } while (value); _Py_write_noraise(fd, ptr, end - ptr); }
static void dump_hexadecimal(int fd, unsigned long value, Py_ssize_t width) { char buffer[sizeof(unsigned long) * 2 + 1], *ptr, *end; const Py_ssize_t size = Py_ARRAY_LENGTH(buffer) - 1; if (width > size) width = size; end = &buffer[size]; ptr = end; *ptr = '\0'; do { --ptr; assert(ptr >= buffer); *ptr = Py_hexdigits[value & 15]; value >>= 4; } while ((end - ptr) < width || value); _Py_write_noraise(fd, ptr, end - ptr); }
Py_ssize_t PyUnicode_INDEX(const char *text, Py_ssize_t index) { PyObject *u; Py_ssize_t i; /* Prevent excessive micro allocations */ char buffer[256]; size_t buffer_size = Py_ARRAY_LENGTH(buffer); char *s = buffer; size_t l; /* Short-circuit */ if (index == 0) return 0; l = strlen(text); if (index > l) index = l; if (index >= buffer_size) { s = PyMem_RawMalloc(index+1); if (s == NULL) return -1; } strncpy(s, text, index); s[index] = '\0'; u = PyUnicode_DECODE(s); if (s != buffer) PyMem_RawFree(s); if (u == NULL) return -1; i = PyUnicode_GET_LENGTH(u); Py_DECREF(u); return i; }
static fault_handler_t faulthandler_handlers[] = { #ifdef SIGBUS {SIGBUS, 0, "Bus error", }, #endif #ifdef SIGILL {SIGILL, 0, "Illegal instruction", }, #endif {SIGFPE, 0, "Floating point exception", }, {SIGABRT, 0, "Aborted", }, /* define SIGSEGV at the end to make it the default choice if searching the handler fails in faulthandler_fatal_error() */ {SIGSEGV, 0, "Segmentation fault", } }; static const unsigned char faulthandler_nsignals = \ Py_ARRAY_LENGTH(faulthandler_handlers); #ifdef HAVE_SIGALTSTACK static stack_t stack; #endif /* Get the file descriptor of a file by calling its fileno() method and then call its flush() method. If file is NULL or Py_None, use sys.stderr as the new file. On success, return the new file and write the file descriptor into *p_fd. On error, return NULL. */ static PyObject*
static wchar_t * getpythonregpath(HKEY keyBase, int skipcore) { HKEY newKey = 0; DWORD dataSize = 0; DWORD numKeys = 0; LONG rc; wchar_t *retval = NULL; WCHAR *dataBuf = NULL; static const WCHAR keyPrefix[] = L"Software\\Python\\PythonCore\\"; static const WCHAR keySuffix[] = L"\\PythonPath"; size_t versionLen, keyBufLen; DWORD index; WCHAR *keyBuf = NULL; WCHAR *keyBufPtr; WCHAR **ppPaths = NULL; /* Tried to use sysget("winver") but here is too early :-( */ versionLen = strlen(PyWin_DLLVersionString); /* Space for all the chars, plus one \0 */ keyBufLen = sizeof(keyPrefix) + sizeof(WCHAR)*(versionLen-1) + sizeof(keySuffix); keyBuf = keyBufPtr = PyMem_RawMalloc(keyBufLen); if (keyBuf==NULL) goto done; memcpy_s(keyBufPtr, keyBufLen, keyPrefix, sizeof(keyPrefix)-sizeof(WCHAR)); keyBufPtr += Py_ARRAY_LENGTH(keyPrefix) - 1; mbstowcs(keyBufPtr, PyWin_DLLVersionString, versionLen); keyBufPtr += versionLen; /* NULL comes with this one! */ memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); /* Open the root Python key */ rc=RegOpenKeyExW(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 = PyMem_RawMalloc( sizeof(WCHAR *) * numKeys ); if (ppPaths==NULL) goto done; memset(ppPaths, 0, sizeof(WCHAR *) * numKeys); /* Loop over all subkeys, allocating a temp sub-buffer. */ for(index=0;index<numKeys;index++) { WCHAR keyBuf[MAX_PATH+1]; HKEY subKey = 0; DWORD reqdSize = MAX_PATH+1; /* Get the sub-key name */ DWORD rc = RegEnumKeyExW(newKey, index, keyBuf, &reqdSize, NULL, NULL, NULL, NULL ); if (rc!=ERROR_SUCCESS) goto done; /* Open the sub-key */ rc=RegOpenKeyExW(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 */ RegQueryValueExW(subKey, NULL, 0, NULL, NULL, &reqdSize); if (reqdSize) { ppPaths[index] = PyMem_RawMalloc(reqdSize); if (ppPaths[index]) { RegQueryValueExW(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 = PyMem_RawMalloc((dataSize+1) * sizeof(WCHAR)); if (dataBuf) { WCHAR *szCur = dataBuf; /* Copy our collected strings */ for (index=0;index<numKeys;index++) { if (index > 0) { *(szCur++) = L';'; dataSize--; } if (ppPaths[index]) { Py_ssize_t len = wcslen(ppPaths[index]); wcsncpy(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++) = L';'; dataSize--; } /* Now append the core path entries - this will include the NULL */ rc = RegQueryValueExW(newKey, NULL, 0, NULL, (LPBYTE)szCur, &dataSize); if (rc != ERROR_SUCCESS) { PyMem_RawFree(dataBuf); goto done; } } /* And set the result - caller must free */ retval = dataBuf; } done: /* Loop freeing my temp buffers */ if (ppPaths) { for(index=0; index<numKeys; index++) PyMem_RawFree(ppPaths[index]); PyMem_RawFree(ppPaths); } if (newKey) RegCloseKey(newKey); PyMem_RawFree(keyBuf); return retval; }
/* Compute argv[0] which will be prepended to sys.argv */ PyObject* _PyPathConfig_ComputeArgv0(int argc, wchar_t **argv) { wchar_t *argv0; wchar_t *p = NULL; Py_ssize_t n = 0; int have_script_arg = 0; int have_module_arg = 0; #ifdef HAVE_READLINK wchar_t link[MAXPATHLEN+1]; wchar_t argv0copy[2*MAXPATHLEN+1]; int nr = 0; #endif #if defined(HAVE_REALPATH) wchar_t fullpath[MAXPATHLEN]; #elif defined(MS_WINDOWS) wchar_t fullpath[MAX_PATH]; #endif argv0 = argv[0]; if (argc > 0 && argv0 != NULL) { have_module_arg = (wcscmp(argv0, L"-m") == 0); have_script_arg = !have_module_arg && (wcscmp(argv0, L"-c") != 0); } if (have_module_arg) { #if defined(HAVE_REALPATH) || defined(MS_WINDOWS) _Py_wgetcwd(fullpath, Py_ARRAY_LENGTH(fullpath)); argv0 = fullpath; n = wcslen(argv0); #else argv0 = L"."; n = 1; #endif } #ifdef HAVE_READLINK if (have_script_arg) nr = _Py_wreadlink(argv0, link, MAXPATHLEN); if (nr > 0) { /* It's a symlink */ link[nr] = '\0'; if (link[0] == SEP) argv0 = link; /* Link to absolute path */ else if (wcschr(link, SEP) == NULL) ; /* Link without path */ else { /* Must join(dirname(argv0), link) */ wchar_t *q = wcsrchr(argv0, SEP); if (q == NULL) argv0 = link; /* argv0 without path */ else { /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */ wcsncpy(argv0copy, argv0, MAXPATHLEN); q = wcsrchr(argv0copy, SEP); wcsncpy(q+1, link, MAXPATHLEN); q[MAXPATHLEN + 1] = L'\0'; argv0 = argv0copy; } } } #endif /* HAVE_READLINK */ #if SEP == '\\' /* Special case for Microsoft filename syntax */ if (have_script_arg) { wchar_t *q; #if defined(MS_WINDOWS) /* Replace the first element in argv with the full path. */ wchar_t *ptemp; if (GetFullPathNameW(argv0, Py_ARRAY_LENGTH(fullpath), fullpath, &ptemp)) { argv0 = fullpath; } #endif p = wcsrchr(argv0, SEP); /* Test for alternate separator */ q = wcsrchr(p ? p : argv0, '/'); if (q != NULL) p = q; if (p != NULL) { n = p + 1 - argv0; if (n > 1 && p[-1] != ':') n--; /* Drop trailing separator */ } } #else /* All other filename syntaxes */ if (have_script_arg) { #if defined(HAVE_REALPATH) if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) { argv0 = fullpath; } #endif p = wcsrchr(argv0, SEP); } if (p != NULL) { n = p + 1 - argv0; #if SEP == '/' /* Special case for Unix filename syntax */ if (n > 1) n--; /* Drop trailing separator */ #endif /* Unix */ } #endif /* All others */ return PyUnicode_FromWideChar(argv0, n); }
static int test_init_from_config(void) { /* Test _Py_InitializeFromConfig() */ _PyCoreConfig config = _PyCoreConfig_INIT; config.install_signal_handlers = 0; /* FIXME: test use_environment */ putenv("PYTHONHASHSEED=42"); config.use_hash_seed = 1; config.hash_seed = 123; putenv("PYTHONMALLOC=malloc"); config.allocator = "malloc_debug"; /* dev_mode=1 is tested in test_init_dev_mode() */ putenv("PYTHONFAULTHANDLER="); config.faulthandler = 1; putenv("PYTHONTRACEMALLOC=0"); config.tracemalloc = 2; putenv("PYTHONPROFILEIMPORTTIME=0"); config.import_time = 1; config.show_ref_count = 1; config.show_alloc_count = 1; /* FIXME: test dump_refs: bpo-34223 */ putenv("PYTHONMALLOCSTATS=0"); config.malloc_stats = 1; /* FIXME: test coerce_c_locale and coerce_c_locale_warn */ putenv("PYTHONUTF8=0"); Py_UTF8Mode = 0; config.utf8_mode = 1; putenv("PYTHONPYCACHEPREFIX=env_pycache_prefix"); config.pycache_prefix = L"conf_pycache_prefix"; Py_SetProgramName(L"./globalvar"); config.program_name = L"./conf_program_name"; static wchar_t* argv[2] = { L"-c", L"pass", }; config.argc = Py_ARRAY_LENGTH(argv); config.argv = argv; config.program = L"conf_program"; static wchar_t* xoptions[3] = { L"core_xoption1=3", L"core_xoption2=", L"core_xoption3", }; config.nxoption = Py_ARRAY_LENGTH(xoptions); config.xoptions = xoptions; static wchar_t* warnoptions[2] = { L"default", L"error::ResourceWarning", }; config.nwarnoption = Py_ARRAY_LENGTH(warnoptions); config.warnoptions = warnoptions; /* FIXME: test module_search_path_env */ /* FIXME: test home */ /* FIXME: test path config: module_search_path .. dll_path */ putenv("PYTHONVERBOSE=0"); Py_VerboseFlag = 0; config.verbose = 1; Py_NoSiteFlag = 0; config.site_import = 0; Py_BytesWarningFlag = 0; config.bytes_warning = 1; putenv("PYTHONINSPECT="); Py_InspectFlag = 0; config.inspect = 1; Py_InteractiveFlag = 0; config.interactive = 1; putenv("PYTHONOPTIMIZE=0"); Py_OptimizeFlag = 1; config.optimization_level = 2; /* FIXME: test parser_debug */ putenv("PYTHONDONTWRITEBYTECODE="); Py_DontWriteBytecodeFlag = 0; config.write_bytecode = 0; Py_QuietFlag = 0; config.quiet = 1; putenv("PYTHONUNBUFFERED="); Py_UnbufferedStdioFlag = 0; config.buffered_stdio = 0; putenv("PYTHONIOENCODING=cp424"); Py_SetStandardStreamEncoding("ascii", "ignore"); #ifdef MS_WINDOWS /* Py_SetStandardStreamEncoding() sets Py_LegacyWindowsStdioFlag to 1. Force it to 0 through the config. */ config.legacy_windows_stdio = 0; #endif config.stdio_encoding = "iso8859-1"; config.stdio_errors = "replace"; putenv("PYTHONNOUSERSITE="); Py_NoUserSiteDirectory = 0; config.user_site_directory = 0; config._check_hash_pycs_mode = "always"; Py_FrozenFlag = 0; config._frozen = 1; _PyInitError err = _Py_InitializeFromConfig(&config); /* Don't call _PyCoreConfig_Clear() since all strings are static */ if (_Py_INIT_FAILED(err)) { _Py_FatalInitError(err); } dump_config(); Py_Finalize(); return 0; }