port 2P step 1: vendor CPython 2.7.18 as the mtpython static library

The embedded 40250 script layer needs its own interpreter on five platforms.
2.7 is end-of-life, so nothing can be fetched from the target SDKs and the
source is vendored (official 2.7.18 tarball, trimmed to 25MB; Lib/ stays for
step 3's python27.zip).

cpython-2.7.18/CMakeLists.txt builds one `mtpython` static library from exactly
the 133 objects the reference libpython2.7.a contains, off by default behind
-DMTGODOT_EMBED_PYTHON=ON. The source list and the built-in module table
(config/config.c, 39 entries) are shared; pyconfig.h is a probe result and is
not, so each platform keeps its own under config/<platform>/, regenerated by
tools/py_embed/gen_pyconfig.sh and checked against the shared table.

Three vendor patches, documented in docs/THIRD-PARTY.md: configure/configure.ac
learn arm64 on macOS, and posixmodule.c undefines the process-control calls it
hard-defines past pyconfig.h when building for iOS.

macOS (ctest python.embed: every builtin imports, codecs and pickle work off the
vendored Lib/), Android arm64 and iOS arm64 build. Linux needs a Linux host and
Windows needs a MinGW-vs-MSVC decision; both are noted for step 4.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-09-23 08:27:35 +09:00
co-authored by Claude Opus 5
parent a9b31dec67
commit 5fad769ee8
1018 changed files with 652582 additions and 19 deletions
+16
View File
@@ -0,0 +1,16 @@
/* Minimal main program -- everything is loaded from the library. */
#include "Python.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
int WINAPI WinMain(
HINSTANCE hInstance, /* handle to current instance */
HINSTANCE hPrevInstance, /* handle to previous instance */
LPSTR lpCmdLine, /* pointer to command line */
int nCmdShow /* show state of window */
)
{
return Py_Main(__argc, __argv);
}
File diff suppressed because it is too large Load Diff
+691
View File
@@ -0,0 +1,691 @@
/*
* support routines for subprocess module
*
* Currently, this extension module is only required when using the
* subprocess module on Windows, but in the future, stubs for other
* platforms might be added here as well.
*
* Copyright (c) 2004 by Fredrik Lundh <fredrik@pythonware.com>
* Copyright (c) 2004 by Secret Labs AB, http://www.pythonware.com
* Copyright (c) 2004 by Peter Astrand <astrand@lysator.liu.se>
*
* By obtaining, using, and/or copying this software and/or its
* associated documentation, you agree that you have read, understood,
* and will comply with the following terms and conditions:
*
* Permission to use, copy, modify, and distribute this software and
* its associated documentation for any purpose and without fee is
* hereby granted, provided that the above copyright notice appears in
* all copies, and that both that copyright notice and this permission
* notice appear in supporting documentation, and that the name of the
* authors not be used in advertising or publicity pertaining to
* distribution of the software without specific, written prior
* permission.
*
* THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/* Licensed to PSF under a Contributor Agreement. */
/* See http://www.python.org/2.4/license for licensing details. */
/* TODO: handle unicode command lines? */
/* TODO: handle unicode environment? */
#include "Python.h"
#define WINDOWS_LEAN_AND_MEAN
#include "windows.h"
/* -------------------------------------------------------------------- */
/* handle wrapper. note that this library uses integers when passing
handles to a function, and handle wrappers when returning handles.
the wrapper is used to provide Detach and Close methods */
typedef struct {
PyObject_HEAD
HANDLE handle;
} sp_handle_object;
staticforward PyTypeObject sp_handle_type;
static PyObject*
sp_handle_new(HANDLE handle)
{
sp_handle_object* self;
self = PyObject_NEW(sp_handle_object, &sp_handle_type);
if (self == NULL)
return NULL;
self->handle = handle;
return (PyObject*) self;
}
#if defined(MS_WIN32) && !defined(MS_WIN64)
#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"
#endif
static PyObject*
sp_handle_detach(sp_handle_object* self, PyObject* args)
{
HANDLE handle;
if (! PyArg_ParseTuple(args, ":Detach"))
return NULL;
handle = self->handle;
self->handle = INVALID_HANDLE_VALUE;
/* 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;
}
static void
sp_handle_dealloc(sp_handle_object* 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}
};
static PyObject*
sp_handle_getattr(sp_handle_object* self, char* 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);
}
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*/
};
/* -------------------------------------------------------------------- */
/* windows API functions */
PyDoc_STRVAR(GetStdHandle_doc,
"GetStdHandle(handle) -> integer\n\
\n\
Return a handle to the specified standard device\n\
(STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE).\n\
The integer associated with the handle object is returned.");
static PyObject *
sp_GetStdHandle(PyObject* self, PyObject* args)
{
HANDLE handle;
int std_handle;
if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle))
return NULL;
Py_BEGIN_ALLOW_THREADS
handle = GetStdHandle((DWORD) std_handle);
Py_END_ALLOW_THREADS
if (handle == INVALID_HANDLE_VALUE)
return PyErr_SetFromWindowsErr(GetLastError());
if (! handle) {
Py_INCREF(Py_None);
return Py_None;
}
/* note: returns integer, not handle object */
return HANDLE_TO_PYNUM(handle);
}
PyDoc_STRVAR(GetCurrentProcess_doc,
"GetCurrentProcess() -> handle\n\
\n\
Return a handle object for the current process.");
static PyObject *
sp_GetCurrentProcess(PyObject* self, PyObject* args)
{
if (! PyArg_ParseTuple(args, ":GetCurrentProcess"))
return NULL;
return sp_handle_new(GetCurrentProcess());
}
PyDoc_STRVAR(DuplicateHandle_doc,
"DuplicateHandle(source_proc_handle, source_handle,\n\
target_proc_handle, target_handle, access,\n\
inherit[, options]) -> handle\n\
\n\
Return a duplicate handle object.\n\
\n\
The duplicate handle refers to the same object as the original\n\
handle. Therefore, any changes to the object are reflected\n\
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);
}
PyDoc_STRVAR(CreatePipe_doc,
"CreatePipe(pipe_attrs, size) -> (read_handle, write_handle)\n\
\n\
Create an anonymous pipe, and return handles to the read and\n\
write ends of the pipe.\n\
\n\
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;
PyObject* pipe_attributes; /* ignored */
int size;
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
if (! result)
return PyErr_SetFromWindowsErr(GetLastError());
return Py_BuildValue(
"NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe));
}
/* helpers for createprocess */
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;
}
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;
}
static PyObject*
getenvironment(PyObject* environment)
{
int i, envsize;
PyObject* out = NULL;
PyObject* keys;
PyObject* values;
char* p;
/* convert environment dictionary to windows environment 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);
if (!keys) {
return NULL;
}
values = PyMapping_Values(environment);
if (!values) {
goto error;
}
out = PyString_FromStringAndSize(NULL, 2048);
if (! out)
goto error;
p = PyString_AS_STRING(out);
for (i = 0; i < envsize; i++) {
size_t 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);
if (strlen(PyString_AS_STRING(key)) != ksize ||
strlen(PyString_AS_STRING(value)) != vsize)
{
PyErr_SetString(PyExc_TypeError, "embedded null character");
goto error;
}
/* Search from index 1 because on Windows starting '=' is allowed for
defining hidden environment variables. */
if (ksize == 0 || strchr(PyString_AS_STRING(key) + 1, '=') != NULL) {
PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
goto error;
}
totalsize = (p - PyString_AS_STRING(out)) + ksize + 1 +
vsize + 1 + 1;
if (totalsize > (size_t)PyString_GET_SIZE(out)) {
size_t offset = p - PyString_AS_STRING(out);
if (_PyString_Resize(&out, totalsize + 1024))
goto exit;
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); */
exit:
Py_XDECREF(keys);
Py_XDECREF(values);
return out;
error:
Py_XDECREF(out);
Py_XDECREF(keys);
Py_XDECREF(values);
return NULL;
}
PyDoc_STRVAR(CreateProcess_doc,
"CreateProcess(app_name, cmd_line, proc_attrs, thread_attrs,\n\
inherit, flags, env_mapping, curdir,\n\
startup_info) -> (proc_handle, thread_handle,\n\
pid, tid)\n\
\n\
Create a new process and its primary thread. The return\n\
value is a tuple of the process handle, thread handle,\n\
process ID, and thread ID.\n\
\n\
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,
&current_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,
"TerminateProcess(handle, exit_code) -> None\n\
\n\
Terminate the specified process and all of its threads.");
static PyObject *
sp_TerminateProcess(PyObject* self, PyObject* args)
{
BOOL result;
HANDLE process;
int exit_code;
if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess",
&process, &exit_code))
return NULL;
result = TerminateProcess(process, exit_code);
if (! result)
return PyErr_SetFromWindowsErr(GetLastError());
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(GetExitCodeProcess_doc,
"GetExitCodeProcess(handle) -> Exit code\n\
\n\
Return the termination status of the specified process.");
static PyObject *
sp_GetExitCodeProcess(PyObject* self, PyObject* args)
{
DWORD exit_code;
BOOL result;
HANDLE process;
if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process))
return NULL;
result = GetExitCodeProcess(process, &exit_code);
if (! result)
return PyErr_SetFromWindowsErr(GetLastError());
return PyInt_FromLong(exit_code);
}
PyDoc_STRVAR(WaitForSingleObject_doc,
"WaitForSingleObject(handle, timeout) -> result\n\
\n\
Wait until the specified object is in the signaled state or\n\
the time-out interval elapses. The timeout value is specified\n\
in milliseconds.");
static PyObject *
sp_WaitForSingleObject(PyObject* self, PyObject* args)
{
DWORD result;
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
if (result == WAIT_FAILED)
return PyErr_SetFromWindowsErr(GetLastError());
return PyInt_FromLong((int) result);
}
PyDoc_STRVAR(GetVersion_doc,
"GetVersion() -> version\n\
\n\
Return the version number of the current operating system.");
static PyObject *
sp_GetVersion(PyObject* self, PyObject* args)
{
if (! PyArg_ParseTuple(args, ":GetVersion"))
return NULL;
return PyInt_FromLong((int) GetVersion());
}
PyDoc_STRVAR(GetModuleFileName_doc,
"GetModuleFileName(module) -> path\n\
\n\
Return the fully-qualified path for the file that contains\n\
the specified module. The module must have been loaded by the\n\
current process.\n\
\n\
The module parameter should be a handle to the loaded module\n\
whose path is being requested. If this parameter is 0, \n\
GetModuleFileName retrieves the path of the executable file\n\
of the current process.");
static PyObject *
sp_GetModuleFileName(PyObject* self, PyObject* args)
{
BOOL result;
HMODULE module;
TCHAR filename[MAX_PATH];
if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName",
&module))
return NULL;
result = GetModuleFileName(module, filename, MAX_PATH);
filename[MAX_PATH-1] = '\0';
if (! result)
return PyErr_SetFromWindowsErr(GetLastError());
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}
};
/* -------------------------------------------------------------------- */
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);
}
}
#if PY_VERSION_HEX >= 0x02030000
PyMODINIT_FUNC
#else
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);
defint(d, "STILL_ACTIVE", STILL_ACTIVE);
}
File diff suppressed because it is too large Load Diff
+170
View File
@@ -0,0 +1,170 @@
/* Module configuration */
/* This file contains the table of built-in modules.
See init_builtin() in import.c. */
#include "Python.h"
extern void initarray(void);
#ifndef MS_WINI64
extern void initaudioop(void);
#endif
extern void initbinascii(void);
extern void initcmath(void);
extern void initerrno(void);
extern void initfuture_builtins(void);
extern void initgc(void);
#ifndef MS_WINI64
extern void initimageop(void);
#endif
extern void initmath(void);
extern void init_md5(void);
extern void initnt(void);
extern void initoperator(void);
extern void initsignal(void);
extern void init_sha(void);
extern void init_sha256(void);
extern void init_sha512(void);
extern void initstrop(void);
extern void inittime(void);
extern void initthread(void);
extern void initcStringIO(void);
extern void initcPickle(void);
#ifdef WIN32
extern void initmsvcrt(void);
extern void init_locale(void);
#endif
extern void init_codecs(void);
extern void init_weakref(void);
extern void init_hotshot(void);
extern void initxxsubtype(void);
extern void initzipimport(void);
extern void init_random(void);
extern void inititertools(void);
extern void init_collections(void);
extern void init_heapq(void);
extern void init_bisect(void);
extern void init_symtable(void);
extern void initmmap(void);
extern void init_csv(void);
extern void init_sre(void);
extern void initparser(void);
extern void init_winreg(void);
extern void init_struct(void);
extern void initdatetime(void);
extern void init_functools(void);
extern void init_json(void);
extern void initzlib(void);
extern void init_multibytecodec(void);
extern void init_codecs_cn(void);
extern void init_codecs_hk(void);
extern void init_codecs_iso2022(void);
extern void init_codecs_jp(void);
extern void init_codecs_kr(void);
extern void init_codecs_tw(void);
extern void init_subprocess(void);
extern void init_lsprof(void);
extern void init_ast(void);
extern void init_io(void);
extern void _PyWarnings_Init(void);
/* tools/freeze/makeconfig.py marker for additional "extern" */
/* -- ADDMODULE MARKER 1 -- */
extern void PyMarshal_Init(void);
extern void initimp(void);
struct _inittab _PyImport_Inittab[] = {
{"array", initarray},
{"_ast", init_ast},
#ifdef MS_WINDOWS
#ifndef MS_WINI64
{"audioop", initaudioop},
#endif
#endif
{"binascii", initbinascii},
{"cmath", initcmath},
{"errno", initerrno},
{"future_builtins", initfuture_builtins},
{"gc", initgc},
#ifndef MS_WINI64
{"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},
#ifdef WITH_THREAD
{"thread", initthread},
#endif
{"cStringIO", initcStringIO},
{"cPickle", initcPickle},
#ifdef WIN32
{"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},
/* tools/freeze/makeconfig.py marker for additional "_inittab" entries */
/* -- ADDMODULE MARKER 2 -- */
/* This module "lives in" with marshal.c */
{"marshal", PyMarshal_Init},
/* 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},
{"_io", init_io},
/* Sentinel */
{0, 0}
};
+111
View File
@@ -0,0 +1,111 @@
/*
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
forgotten) from the programmer.
*/
#include "Python.h"
#include "windows.h"
#ifdef Py_ENABLE_SHARED
char dllVersionBuffer[16] = ""; // a private buffer
// Python Globals
HMODULE PyWin_DLLhModule = NULL;
const char *PyWin_DLLVersionString = dllVersionBuffer;
// Windows "Activation Context" work:
// Our .pyd extension modules are generally built without a manifest (ie,
// those included with Python and those built with a default distutils.
// This requires we perform some "activation context" magic when loading our
// extensions. In summary:
// * As our DLL loads we save the context being used.
// * Before loading our extensions we re-activate our saved context.
// * After extension load is complete we restore the old context.
// As an added complication, this magic only works on XP or later - we simply
// use the existence (or not) of the relevant function pointers from kernel32.
// See bug 4566 (http://python.org/sf/4566) for more details.
typedef BOOL (WINAPI * PFN_GETCURRENTACTCTX)(HANDLE *);
typedef BOOL (WINAPI * PFN_ACTIVATEACTCTX)(HANDLE, ULONG_PTR *);
typedef BOOL (WINAPI * PFN_DEACTIVATEACTCTX)(DWORD, ULONG_PTR);
typedef void (WINAPI * PFN_ADDREFACTCTX)(HANDLE);
typedef void (WINAPI * PFN_RELEASEACTCTX)(HANDLE);
// locals and function pointers for this activation context magic.
static HANDLE PyWin_DLLhActivationContext = NULL; // one day it might be public
static PFN_GETCURRENTACTCTX pfnGetCurrentActCtx = NULL;
static PFN_ACTIVATEACTCTX pfnActivateActCtx = NULL;
static PFN_DEACTIVATEACTCTX pfnDeactivateActCtx = NULL;
static PFN_ADDREFACTCTX pfnAddRefActCtx = NULL;
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");
}
}
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;
}
void _Py_DeactivateActCtx(ULONG_PTR cookie)
{
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)
{
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)) {
(*pfnAddRefActCtx)(PyWin_DLLhActivationContext);
}
else {
OutputDebugString("Python failed to load the default "
"activation context\n");
return FALSE;
}
break;
case DLL_PROCESS_DETACH:
if (pfnReleaseActCtx)
(*pfnReleaseActCtx)(PyWin_DLLhActivationContext);
break;
}
return TRUE;
}
#endif /* Py_ENABLE_SHARED */
+77
View File
@@ -0,0 +1,77 @@
In Win32, DLL's are "pre-linked" using a specified base address.
When the DLL is loaded, an attempt is made to place it at
that address. If that address is already in use, a new base address
is selected, and the DLL subject to fixups. Apparently, these
fixups are very slow, and significant performance gains can be
made by selecting a good base address.
This document is to allocate base addresses to core Python
and Python .PYD files, to give a better change of optimal performance.
This base address is passed to the linker using the /BASE
command line switch.
Python.exe/Pythonw.exe - 1d000000 - 1e000000 (-1)
Python.dll - 1e000000 - 1e100000 (-1)
Standard Extension Modules 1e100000 - 1e200000 ""
- _symtable 1e100000 - 1e110000 pyd removed in 2.4
- bsddb 1e180000 - 1e188000
- _tkinter 1e190000 - 1e1A0000
- parser 1e1A0000 - 1e1B0000 pyd removed in 2.4
- zlib 1e1B0000 - 1e1C0000
- winreg 1e1C0000 - 1e1D0000 pyd removed in 2.4
- _socket 1e1D0000 - 1e1E0000
- _sre 1e1E0000 - 1e1F0000 pyd removed in 2.4
- mmap 1e1F0000 - 1e1FFFFF pyd removed in 2.4
More standard extensions 1D100000 - 1e000000
- pyexpat 1D100000 - 1D110000
- select 1D110000 - 1D120000
- unicodedata 1D120000 - 1D160000
- winsound 1D160000 - 1D170000
- bZ2 1D170000 - 1D180000
- datetime 1D180000 - 1D190000 pyd removed in 2.4
- _csv 1D190000 - 1D1A0000 pyd removed in 2.4
- _ctypes 1D1A0000 - 1D1B0000
Other extension modules
- win32api 1e200000 - 1e220000
- win32ras 1e220000 - 1e230000
- win32lz 1e230000 - 1e240000
- timer 1e240000 - 1e250000
- mmapfile 1e250000 - 1e260000
- win32pipe 1e260000 - 1e270000
- avl 1e270000 - 1e270000
- dbhash 1e280000 - 1e290000
- win32net 1e290000 - 1e2A0000
- win32security 1e2A0000 - 1e2B0000
- win32print 1e2B0000 - 1e2c0000
- <unused> 1e2d0000 - 1e2e0000
- win32gui 1e2e0000 - 1e2f0000
- _imaging 1e2f0000 - 1e300000
- multiarray 1e300000 - 1e310000
- win32help 1e310000 - 1e320000
- win32clipboard 1e320000 - 1e330000
- win2kras 1e330000 - 1e340000
- pythoncom 1e340000 - 1e400000
- win32ui 1e400000 - 1e500000
- win32uiole 1e500000 - 1e600000
- pywintypes 1e600000 - 1e700000
- win32process 1e700000 - 1e800000
- odbc 1e710000 - 1e720000
- dbi 1e720000 - 1e730000
- win32file 1e730000 - 1e740000
- win32wnet 1e740000 - 1e750000
- win32com.shell 1e750000 - 1e760000
- win32com.internet 1e760000 - 1e770000
- win32com.exchange 1e770000 - 1e780000
- win32com.exchdapi 1e780000 - 1e790000
- win32com.axscript 1e790000 - 1e7a0000
- win32com.axdebug 1e7b0000 - 1e7c0000
- win32com.adsi 1e7f0000 - 1e800000
- win32event 1e810000 - 1e820000
- win32evtlog 1e820000 - 1e830000
- win32com.axcontrol 1e830000 - 1e840000
+6
View File
@@ -0,0 +1,6 @@
#include <windows.h>
int __stdcall
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
return 0;
}
+78
View File
@@ -0,0 +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;
}
}
+5
View File
@@ -0,0 +1,5 @@
errmap.h: generrmap.exe
.\generrmap.exe > errmap.h
genermap.exe: generrmap.c
cl generrmap.c
+134
View File
@@ -0,0 +1,134 @@
/* FreezeDLLMain.cpp
This is a DLLMain suitable for frozen applications/DLLs on
a Windows platform.
The general problem is that many Python extension modules may define
DLL main functions, but when statically linked together to form
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%"
(eg, DllMainpythoncom, or DllMainpywintypes)
* The frozen .EXE/.DLL links against this module, which provides
the single DllMain.
* This DllMain attempts to locate and call the DllMain for each
of the extension modules.
* This code also has hooks to "simulate" DllMain when used from
a frozen .EXE.
At this stage, there is a static table of "possibly embedded modules".
This should change to something better, but it will work OK for now.
Note that this scheme does not handle dependencies in the order
of DllMain calls - except it does call pywintypes first :-)
As an example of how an extension module with a DllMain should be
changed, here is a snippet from the pythoncom extension module.
// end of example code from pythoncom's DllMain.cpp
#ifndef BUILD_FREEZE
#define DLLMAIN DllMain
#define DLLMAIN_DECL
#else
#define DLLMAIN DllMainpythoncom
#define DLLMAIN_DECL __declspec(dllexport)
#endif
extern "C" DLLMAIN_DECL
BOOL WINAPI DLLMAIN(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
// end of example code from pythoncom's DllMain.cpp
***************************************************************************/
#include "windows.h"
static char *possibleModules[] = {
"pywintypes",
"pythoncom",
"win32ui",
NULL,
};
BOOL CallModuleDllMain(char *modName, DWORD dwReason);
/*
Called by a frozen .EXE only, so that built-in extension
modules are initialized correctly
*/
void PyWinFreeze_ExeInit(void)
{
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
*/
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);
}
}
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 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);
}
+20
View File
@@ -0,0 +1,20 @@
#include <stdio.h>
#include <errno.h>
/* Extract the mapping of Win32 error codes to errno */
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");
}
+714
View File
@@ -0,0 +1,714 @@
/* Return the initial module search path. */
/* Used by DOS, OS/2, Windows 3.1, Windows 95/98, Windows NT. */
/* ----------------------------------------------------------------
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
are actually fetched is different)
* Python always adds an empty entry at the start, which corresponds
to the current directory.
* If the PYTHONPATH env. var. exists, its entries are added next.
* We look in the registry for "application paths" - that is, sub-keys
under the main PythonPath registry key. These are added next (the
order of sub-key processing is undefined).
HKEY_CURRENT_USER is searched and added first.
HKEY_LOCAL_MACHINE is searched and added next.
(Note that all known installers only use HKLM, so HKCU is typically
empty)
* 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,
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,
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
used (eg. .\Lib;.\plat-win, etc)
The end result of all this is:
* When running python.exe, or any other .exe in the main Python directory
(either an installed version, or directly from the PCbuild directory),
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
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
always read.
* If Python can't find its home and there is no registry (eg, frozen
exe, some very strange installation setup) you get a path with
some default, but relative, paths.
---------------------------------------------------------------- */
#include "Python.h"
#include "osdefs.h"
#ifdef MS_WINDOWS
#include <windows.h>
#include <tchar.h>
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif /* HAVE_SYS_TYPES_H */
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif /* HAVE_SYS_STAT_H */
#include <string.h>
/* Search in some common locations for the associated Python libraries.
*
* Py_GetPath() tries to return a sensible Python module search path.
*
* The approach is an adaptation for Windows of the strategy used in
* ../Modules/getpath.c; it uses the Windows Registry as one of its
* information sources.
*/
#ifndef LANDMARK
#define LANDMARK "lib\\os.py"
#endif
static char prefix[MAXPATHLEN+1];
static char progpath[MAXPATHLEN+1];
static char dllpath[MAXPATHLEN+1];
static char *module_search_path = NULL;
static int
is_sep(char ch) /* determine if "ch" is a separator character */
{
#ifdef ALTSEP
return ch == SEP || ch == ALTSEP;
#else
return ch == SEP;
#endif
}
/* assumes 'dir' null terminated in bounds. Never writes
beyond existing terminator.
*/
static void
reduce(char *dir)
{
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;
}
/* Assumes 'filename' MAXPATHLEN+1 bytes long -
may extend 'filename' by one character.
*/
static int
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;
}
/* Add a path component, by appending stuff to buffer.
buffer must have at least MAXPATHLEN + 1 bytes allocated, and contain a
NUL-terminated string with no more than MAXPATHLEN characters (not counting
the trailing NUL). It's a fatal error if it contains a string longer than
that (callers must be careful!). If these requirements are met, it's
guaranteed that buffer will still be a NUL-terminated string with no more
than MAXPATHLEN characters at exit. If stuff is too long, only as much of
stuff as fits will be appended.
*/
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';
}
/* gotlandmark only called by search_for_prefix, which ensures
'prefix' is null terminated in bounds. join() ensures
'landmark' can not overflow prefix if too long.
*/
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;
}
/* 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;
}
#ifdef MS_WINDOWS
#ifdef Py_ENABLE_SHARED
/* a string loaded from the DLL at startup.*/
extern const char *PyWin_DLLVersionString;
/* Load a PYTHONPATH value from the registry.
Load from either HKEY_LOCAL_MACHINE or HKEY_CURRENT_USER.
Works in both Unicode and 8bit environments. Only uses the
Ex family of functions so it also works with Windows CE.
Returns NULL, or a pointer that should be freed.
XXX - this code is pretty strange, as it used to also
work on Win16, where the buffer sizes werent available
in advance. It could be simplied now Win16/Win32s is dead!
*/
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.
*/
#ifdef UNICODE
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;
#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;
}
#endif /* Py_ENABLE_SHARED */
#endif /* MS_WINDOWS */
static void
get_progpath(void)
{
extern char *Py_GetProgramName(void);
char *path = getenv("PATH");
char *prog = Py_GetProgramName();
#ifdef MS_WINDOWS
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...
*/
#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);
}
#else
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;
}
#else
/* 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;
#else
dllpath[0] = 0;
#endif
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.
*/
#ifdef ALTSEP
if (strchr(prog, SEP) || strchr(prog, ALTSEP))
#else
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';
}
static void
calculate_path(void)
{
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;
#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);
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;
#ifdef Py_ENABLE_SHARED
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;
#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;
#ifdef MS_WINDOWS
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;
}
#ifdef MS_WINDOWS
if (machinepath)
free(machinepath);
if (userpath)
free(userpath);
#endif /* MS_WINDOWS */
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');
}
}
#else
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--;
}
}
}
/* External interface */
char *
Py_GetPath(void)
{
if (!module_search_path)
calculate_path();
return module_search_path;
}
char *
Py_GetPrefix(void)
{
if (!module_search_path)
calculate_path();
return prefix;
}
char *
Py_GetExecPrefix(void)
{
return Py_GetPrefix();
}
char *
Py_GetProgramFullPath(void)
{
if (!module_search_path)
calculate_path();
return progpath;
}
+4
View File
@@ -0,0 +1,4 @@
101 ICON "py.ico"
102 ICON "pyc.ico"
103 ICON "pycon.ico"
+86
View File
@@ -0,0 +1,86 @@
/********************************************************************
import_nt.c
Win32 specific import code.
*/
#include "Python.h"
#include "osdefs.h"
#include <windows.h>
#include "importdl.h"
#include "malloc.h" /* for alloca */
/* a string loaded from the DLL at startup */
extern const char *PyWin_DLLVersionString;
FILE *PyWin_FindRegisteredModule(const char *moduleName,
struct filedescr **ppFileDesc,
char *pathBuf,
Py_ssize_t pathLen)
{
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";
#else
const char debugString[] = "";
#endif
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);
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;
}
@@ -0,0 +1,38 @@
#include <stdio.h>
#include "patchlevel.h"
/*
* This program prints out an include file containing fields required to build
* the version info resource of pythonxx.dll because the resource compiler
* cannot do the arithmetic.
*/
/*
* FIELD3 is the third field of the version number.
* This is what we'd like FIELD3 to be:
*
* #define FIELD3 (PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL)
*
* but that neither gives an error nor comes anywhere close to working.
*
* For 2.4a0,
* PY_MICRO_VERSION = 0
* PY_RELEASE_LEVEL = 'alpha' = 0xa
* PY_RELEASE_SERIAL = 0
*
* gives FIELD3 = 0*1000 + 10*10 + 0 = 100
*/
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;
}
+430
View File
@@ -0,0 +1,430 @@
/*********************************************************
msvcrtmodule.c
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...
This may only work on NT or 95...
Author: Mark Hammond and Guido van Rossum.
Maintenance: Guido van Rossum.
***********************************************************/
#include "Python.h"
#include "malloc.h"
#include <io.h>
#include <conio.h>
#include <sys/locking.h>
#ifdef _MSC_VER
#if _MSC_VER >= 1500 && _MSC_VER < 1600
#include <crtassem.h>
#endif
#endif
// Force the malloc heap to clean itself up, and free unused blocks
// back to the OS. (According to the docs, only works on NT.)
static PyObject *
msvcrt_heapmin(PyObject *self, PyObject *args)
{
if (!PyArg_ParseTuple(args, ":heapmin"))
return NULL;
if (_heapmin() != 0)
return PyErr_SetFromErrno(PyExc_IOError);
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(heapmin_doc,
"heapmin() -> None\n\
\n\
Force the malloc() heap to clean itself up and return unused blocks\n\
to the operating system. On failure, this raises IOError.");
// Perform locking operations on a C runtime file descriptor.
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;
}
PyDoc_STRVAR(locking_doc,
"locking(fd, mode, nbytes) -> None\n\
\n\
Lock part of a file based on file descriptor fd from the C runtime.\n\
Raises IOError on failure. The locked region of the file extends from\n\
the current file position for nbytes bytes, and may continue beyond\n\
the end of the file. mode must be one of the LK_* constants listed\n\
below. Multiple regions in a file may be locked at the same time, but\n\
may not overlap. Adjacent regions are not merged; they must be unlocked\n\
individually.");
// Set the file translation mode for a C runtime file descriptor.
static PyObject *
msvcrt_setmode(PyObject *self, PyObject *args)
{
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);
return PyInt_FromLong(flags);
}
PyDoc_STRVAR(setmode_doc,
"setmode(fd, mode) -> Previous mode\n\
\n\
Set the line-end translation mode for the file descriptor fd. To set\n\
it to text mode, flags should be os.O_TEXT; for binary, it should be\n\
os.O_BINARY.");
// Convert an OS file handle to a C runtime file descriptor.
static PyObject *
msvcrt_open_osfhandle(PyObject *self, PyObject *args)
{
long handle;
int flags;
int fd;
if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags))
return NULL;
fd = _open_osfhandle(handle, flags);
if (fd == -1)
return PyErr_SetFromErrno(PyExc_IOError);
return PyInt_FromLong(fd);
}
PyDoc_STRVAR(open_osfhandle_doc,
"open_osfhandle(handle, flags) -> file descriptor\n\
\n\
Create a C runtime file descriptor from the file handle handle. The\n\
flags parameter should be a bitwise OR of os.O_APPEND, os.O_RDONLY,\n\
and os.O_TEXT. The returned file descriptor may be used as a parameter\n\
to os.fdopen() to create a file object.");
// Convert a C runtime file descriptor to an OS file handle.
static PyObject *
msvcrt_get_osfhandle(PyObject *self, PyObject *args)
{
int fd;
Py_intptr_t handle;
if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd))
return NULL;
if (!_PyVerify_fd(fd))
return PyErr_SetFromErrno(PyExc_IOError);
handle = _get_osfhandle(fd);
if (handle == -1)
return PyErr_SetFromErrno(PyExc_IOError);
/* technically 'handle' is not a pointer, but an 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,
"get_osfhandle(fd) -> file handle\n\
\n\
Return the file handle for the file descriptor fd. Raises IOError\n\
if fd is not recognized.");
/* Console I/O */
static PyObject *
msvcrt_kbhit(PyObject *self, PyObject *args)
{
int ok;
if (!PyArg_ParseTuple(args, ":kbhit"))
return NULL;
ok = _kbhit();
return PyInt_FromLong(ok);
}
PyDoc_STRVAR(kbhit_doc,
"kbhit() -> bool\n\
\n\
Return true if a keypress is waiting to be read.");
static PyObject *
msvcrt_getch(PyObject *self, PyObject *args)
{
int ch;
char s[1];
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);
}
PyDoc_STRVAR(getch_doc,
"getch() -> key character\n\
\n\
Read a keypress and return the resulting character. Nothing is echoed to\n\
the console. This call will block if a keypress is not already\n\
available, but will not wait for Enter to be pressed. If the pressed key\n\
was a special function key, this will return '\\000' or '\\xe0'; the next\n\
call will return the keycode. The Control-C keypress cannot be read with\n\
this function.");
#ifdef _WCONIO_DEFINED
static PyObject *
msvcrt_getwch(PyObject *self, PyObject *args)
{
Py_UNICODE ch;
Py_UNICODE u[1];
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);
}
PyDoc_STRVAR(getwch_doc,
"getwch() -> Unicode key character\n\
\n\
Wide char variant of getch(), returning a Unicode value.");
#endif
static PyObject *
msvcrt_getche(PyObject *self, PyObject *args)
{
int ch;
char s[1];
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);
}
PyDoc_STRVAR(getche_doc,
"getche() -> key character\n\
\n\
Similar to getch(), but the keypress will be echoed if it represents\n\
a printable character.");
#ifdef _WCONIO_DEFINED
static PyObject *
msvcrt_getwche(PyObject *self, PyObject *args)
{
Py_UNICODE ch;
Py_UNICODE s[1];
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);
}
PyDoc_STRVAR(getwche_doc,
"getwche() -> Unicode key character\n\
\n\
Wide char variant of getche(), returning a Unicode value.");
#endif
static PyObject *
msvcrt_putch(PyObject *self, PyObject *args)
{
char ch;
if (!PyArg_ParseTuple(args, "c:putch", &ch))
return NULL;
_putch(ch);
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(putch_doc,
"putch(char) -> None\n\
\n\
Print the character char to the console without buffering.");
#ifdef _WCONIO_DEFINED
static PyObject *
msvcrt_putwch(PyObject *self, PyObject *args)
{
Py_UNICODE *ch;
int size;
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;
}
PyDoc_STRVAR(putwch_doc,
"putwch(unicode_char) -> None\n\
\n\
Wide char variant of putch(), accepting a Unicode value.");
#endif
static PyObject *
msvcrt_ungetch(PyObject *self, PyObject *args)
{
char ch;
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;
}
PyDoc_STRVAR(ungetch_doc,
"ungetch(char) -> None\n\
\n\
Cause the character char to be \"pushed back\" into the console buffer;\n\
it will be the next character read by getch() or getche().");
#ifdef _WCONIO_DEFINED
static PyObject *
msvcrt_ungetwch(PyObject *self, PyObject *args)
{
Py_UNICODE ch;
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;
}
PyDoc_STRVAR(ungetwch_doc,
"ungetwch(unicode_char) -> None\n\
\n\
Wide char variant of ungetch(), accepting a Unicode value.");
#endif
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);
}
}
/* 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},
#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},
#endif
{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 */
#ifdef _VC_ASSEMBLY_PUBLICKEYTOKEN
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;
#endif
#ifdef __LIBRARIES_ASSEMBLY_NAME_PREFIX
st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX",
__LIBRARIES_ASSEMBLY_NAME_PREFIX);
if (st < 0)return;
#endif
}
+770
View File
@@ -0,0 +1,770 @@
#ifndef Py_CONFIG_H
#define Py_CONFIG_H
/* pyconfig.h. NOT Generated automatically by configure.
This is a manually maintained version used for the Watcom,
Borland and Microsoft Visual C++ compilers. It is a
standard part of the Python distribution.
WINDOWS DEFINES:
The code specific to Windows should be wrapped around one of
the following #defines
MS_WIN64 - Code specific to the MS Win64 API
MS_WIN32 - Code specific to the MS Win32 (and Win64) API (obsolete, this covers all supported APIs)
MS_WINDOWS - Code specific to Windows, but all versions.
MS_WINCE - Code specific to Windows CE
Py_ENABLE_SHARED - Code if the Python core is built as a DLL.
Also note that neither "_M_IX86" or "_MSC_VER" should be used for
any purpose other than "Windows Intel x86 specific" and "Microsoft
compiler specific". Therefore, these should be very rare.
NOTE: The following symbols are deprecated:
NT, USE_DL_EXPORT, USE_DL_IMPORT, DL_EXPORT, DL_IMPORT
MS_CORE_DLL.
WIN32 is still required for the locale module.
*/
#ifdef _WIN32_WCE
#define MS_WINCE
#endif
/* Deprecated USE_DL_EXPORT macro - please use Py_BUILD_CORE */
#ifdef USE_DL_EXPORT
# define Py_BUILD_CORE
#endif /* USE_DL_EXPORT */
/* Visual Studio 2005 introduces deprecation warnings for
"insecure" and POSIX functions. The insecure functions should
be replaced by *_s versions (according to Microsoft); the
POSIX functions by _* versions (which, according to Microsoft,
would be ISO C conforming). Neither renaming is feasible, so
we just silence the warnings. */
#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE 1
#endif
#ifndef _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE 1
#endif
/* Windows CE does not have these */
#ifndef MS_WINCE
#define HAVE_IO_H
#define HAVE_SYS_UTIME_H
#define HAVE_TEMPNAM
#define HAVE_TMPFILE
#define HAVE_TMPNAM
#define HAVE_CLOCK
#define HAVE_STRERROR
#endif
#ifdef HAVE_IO_H
#include <io.h>
#endif
#define HAVE_HYPOT
#define HAVE_STRFTIME
#define DONT_HAVE_SIG_ALARM
#define DONT_HAVE_SIG_PAUSE
#define LONG_BIT 32
#define WORD_BIT 32
#define PREFIX ""
#define EXEC_PREFIX ""
#define MS_WIN32 /* only support win32 and greater. */
#define MS_WINDOWS
#ifndef PYTHONPATH
# define PYTHONPATH ".\\DLLs;.\\lib;.\\lib\\plat-win;.\\lib\\lib-tk"
#endif
#define NT_THREADS
#define WITH_THREAD
#ifndef NETSCAPE_PI
#define USE_SOCKET
#endif
/* CE6 doesn't have strdup() but _strdup(). Assume the same for earlier versions. */
#if defined(MS_WINCE)
# include <stdlib.h>
# define strdup _strdup
#endif
#ifdef MS_WINCE
/* Windows CE does not support environment variables */
#define getenv(v) (NULL)
#define environ (NULL)
#endif
/* Compiler specific defines */
/* ------------------------------------------------------------------------*/
/* Microsoft C defines _MSC_VER */
#ifdef _MSC_VER
/* We want COMPILER to expand to a string containing _MSC_VER's *value*.
* This is horridly tricky, because the stringization operator only works
* on macro arguments, and doesn't evaluate macros passed *as* arguments.
* Attempts simpler than the following appear doomed to produce "_MSC_VER"
* literally in the string.
*/
#define _Py_PASTE_VERSION(SUFFIX) \
("[MSC v." _Py_STRINGIZE(_MSC_VER) " " SUFFIX "]")
/* e.g., this produces, after compile-time string catenation,
* ("[MSC v.1200 32 bit (Intel)]")
*
* _Py_STRINGIZE(_MSC_VER) expands to
* _Py_STRINGIZE1((_MSC_VER)) expands to
* _Py_STRINGIZE2(_MSC_VER) but as this call is the result of token-pasting
* it's scanned again for macros and so further expands to (under MSVC 6)
* _Py_STRINGIZE2(1200) which then expands to
* "1200"
*/
#define _Py_STRINGIZE(X) _Py_STRINGIZE1((X))
#define _Py_STRINGIZE1(X) _Py_STRINGIZE2 ## X
#define _Py_STRINGIZE2(X) #X
/* MSVC defines _WINxx to differentiate the windows platform types
Note that for compatibility reasons _WIN32 is defined on Win32
*and* on Win64. For the same reasons, in Python, MS_WIN32 is
defined on Win32 *and* Win64. Win32 only code must therefore be
guarded as follows:
#if defined(MS_WIN32) && !defined(MS_WIN64)
Some modules are disabled on Itanium processors, therefore we
have MS_WINI64 set for those targets, otherwise MS_WINX64
*/
#ifdef _WIN64
#define MS_WIN64
#endif
/* set the COMPILER */
#ifdef MS_WIN64
#if defined(_M_IA64)
#define COMPILER _Py_PASTE_VERSION("64 bit (Itanium)")
#define MS_WINI64
#elif defined(_M_X64) || defined(_M_AMD64)
#ifdef __INTEL_COMPILER
#define COMPILER ("[ICC v." _Py_STRINGIZE(__INTEL_COMPILER) " 64 bit (amd64) with MSC v." _Py_STRINGIZE(_MSC_VER) " CRT]")
#else
#define COMPILER _Py_PASTE_VERSION("64 bit (AMD64)")
#endif /* __INTEL_COMPILER */
#define MS_WINX64
#else
#define COMPILER _Py_PASTE_VERSION("64 bit (Unknown)")
#endif
#endif /* MS_WIN64 */
/* set the version macros for the windows headers */
#ifdef MS_WINX64
/* 64 bit only runs on XP or greater */
#define Py_WINVER _WIN32_WINNT_WINXP
#define Py_NTDDI NTDDI_WINXP
#else
/* Python 2.6+ requires Windows 2000 or greater */
#ifdef _WIN32_WINNT_WIN2K
#define Py_WINVER _WIN32_WINNT_WIN2K
#else
#define Py_WINVER 0x0500
#endif
#define Py_NTDDI NTDDI_WIN2KSP4
#endif
/* We only set these values when building Python - we don't want to force
these values on extensions, as that will affect the prototypes and
structures exposed in the Windows headers. Even when building Python, we
allow a single source file to override this - they may need access to
structures etc so it can optionally use new Windows features if it
determines at runtime they are available.
*/
#if defined(Py_BUILD_CORE) || defined(Py_BUILD_CORE_MODULE)
#ifndef NTDDI_VERSION
#define NTDDI_VERSION Py_NTDDI
#endif
#ifndef WINVER
#define WINVER Py_WINVER
#endif
#ifndef _WIN32_WINNT
#define _WIN32_WINNT Py_WINVER
#endif
#endif
/* _W64 is not defined for VC6 or eVC4 */
#ifndef _W64
#define _W64
#endif
/* Define like size_t, omitting the "unsigned" */
#ifdef MS_WIN64
typedef __int64 ssize_t;
#else
typedef _W64 int ssize_t;
#endif
#define HAVE_SSIZE_T 1
#if defined(MS_WIN32) && !defined(MS_WIN64)
#ifdef _M_IX86
#ifdef __INTEL_COMPILER
#define COMPILER ("[ICC v." _Py_STRINGIZE(__INTEL_COMPILER) " 32 bit (Intel) with MSC v." _Py_STRINGIZE(_MSC_VER) " CRT]")
#else
#define COMPILER _Py_PASTE_VERSION("32 bit (Intel)")
#endif /* __INTEL_COMPILER */
#else
#define COMPILER _Py_PASTE_VERSION("32 bit (Unknown)")
#endif
#endif /* MS_WIN32 && !MS_WIN64 */
typedef int pid_t;
#include <float.h>
#define Py_IS_NAN _isnan
#define Py_IS_INFINITY(X) (!_finite(X) && !_isnan(X))
#define Py_IS_FINITE(X) _finite(X)
#define copysign _copysign
#endif /* _MSC_VER */
/* define some ANSI types that are not defined in earlier Win headers */
#if defined(_MSC_VER) && _MSC_VER >= 1200
/* This file only exists in VC 6.0 or higher */
#include <basetsd.h>
#endif
/* ------------------------------------------------------------------------*/
/* The Borland compiler defines __BORLANDC__ */
/* XXX These defines are likely incomplete, but should be easy to fix. */
#ifdef __BORLANDC__
#define COMPILER "[Borland]"
#ifdef _WIN32
/* tested with BCC 5.5 (__BORLANDC__ >= 0x0550)
*/
typedef int pid_t;
/* BCC55 seems to understand __declspec(dllimport), it is used in its
own header files (winnt.h, ...) - so we can do nothing and get the default*/
#undef HAVE_SYS_UTIME_H
#define HAVE_UTIME_H
#define HAVE_DIRENT_H
/* rename a few functions for the Borland compiler */
#include <io.h>
#define _chsize chsize
#define _setmode setmode
#else /* !_WIN32 */
#error "Only Win32 and later are supported"
#endif /* !_WIN32 */
#endif /* BORLANDC */
/* ------------------------------------------------------------------------*/
/* egcs/gnu-win32 defines __GNUC__ and _WIN32 */
#if defined(__GNUC__) && defined(_WIN32)
/* XXX These defines are likely incomplete, but should be easy to fix.
They should be complete enough to build extension modules. */
/* Suggested by Rene Liebscher <R.Liebscher@gmx.de> to avoid a GCC 2.91.*
bug that requires structure imports. More recent versions of the
compiler don't exhibit this bug.
*/
#if (__GNUC__==2) && (__GNUC_MINOR__<=91)
#warning "Please use an up-to-date version of gcc! (>2.91 recommended)"
#endif
#define COMPILER "[gcc]"
#define PY_LONG_LONG long long
#define PY_LLONG_MIN LLONG_MIN
#define PY_LLONG_MAX LLONG_MAX
#define PY_ULLONG_MAX ULLONG_MAX
#endif /* GNUC */
/* ------------------------------------------------------------------------*/
/* lcc-win32 defines __LCC__ */
#if defined(__LCC__)
/* XXX These defines are likely incomplete, but should be easy to fix.
They should be complete enough to build extension modules. */
#define COMPILER "[lcc-win32]"
typedef int pid_t;
/* __declspec() is supported here too - do nothing to get the defaults */
#endif /* LCC */
/* ------------------------------------------------------------------------*/
/* End of compilers - finish up */
#ifndef NO_STDIO_H
# include <stdio.h>
#endif
/* 64 bit ints are usually spelt __int64 unless compiler has overridden */
#define HAVE_LONG_LONG 1
#ifndef PY_LONG_LONG
# define PY_LONG_LONG __int64
# define PY_LLONG_MAX _I64_MAX
# define PY_LLONG_MIN _I64_MIN
# define PY_ULLONG_MAX _UI64_MAX
#endif
/* For Windows the Python core is in a DLL by default. Test
Py_NO_ENABLE_SHARED to find out. Also support MS_NO_COREDLL for b/w compat */
#if !defined(MS_NO_COREDLL) && !defined(Py_NO_ENABLE_SHARED)
# define Py_ENABLE_SHARED 1 /* standard symbol for shared library */
# define MS_COREDLL /* deprecated old symbol */
#endif /* !MS_NO_COREDLL && ... */
/* All windows compilers that use this header support __declspec */
#define HAVE_DECLSPEC_DLL
/* For an MSVC DLL, we can nominate the .lib files used by extensions */
#ifdef MS_COREDLL
# ifndef Py_BUILD_CORE /* not building the core - must be an ext */
# if defined(_MSC_VER)
/* So MSVC users need not specify the .lib file in
their Makefile (other compilers are generally
taken care of by distutils.) */
# ifdef _DEBUG
# pragma comment(lib,"python27_d.lib")
# else
# pragma comment(lib,"python27.lib")
# endif /* _DEBUG */
# endif /* _MSC_VER */
# endif /* Py_BUILD_CORE */
#endif /* MS_COREDLL */
#if defined(MS_WIN64)
/* maintain "win32" sys.platform for backward compatibility of Python code,
the Win64 API should be close enough to the Win32 API to make this
preferable */
# define PLATFORM "win32"
# define SIZEOF_VOID_P 8
# define SIZEOF_TIME_T 8
# define SIZEOF_OFF_T 4
# define SIZEOF_FPOS_T 8
# define SIZEOF_HKEY 8
# define SIZEOF_SIZE_T 8
/* configure.ac defines HAVE_LARGEFILE_SUPPORT iff HAVE_LONG_LONG,
sizeof(off_t) > sizeof(long), and sizeof(PY_LONG_LONG) >= sizeof(off_t).
On Win64 the second condition is not true, but if fpos_t replaces off_t
then this is true. The uses of HAVE_LARGEFILE_SUPPORT imply that Win64
should define this. */
# define HAVE_LARGEFILE_SUPPORT
#elif defined(MS_WIN32)
# define PLATFORM "win32"
# define HAVE_LARGEFILE_SUPPORT
# define SIZEOF_VOID_P 4
# define SIZEOF_OFF_T 4
# define SIZEOF_FPOS_T 8
# define SIZEOF_HKEY 4
# define SIZEOF_SIZE_T 4
/* MS VS2005 changes time_t to a 64-bit type on all platforms */
# if defined(_MSC_VER) && _MSC_VER >= 1400
# define SIZEOF_TIME_T 8
# else
# define SIZEOF_TIME_T 4
# endif
#endif
#ifdef _DEBUG
# define Py_DEBUG
#endif
#ifdef MS_WIN32
#define SIZEOF_SHORT 2
#define SIZEOF_INT 4
#define SIZEOF_LONG 4
#define SIZEOF_LONG_LONG 8
#define SIZEOF_DOUBLE 8
#define SIZEOF_FLOAT 4
/* VC 7.1 has them and VC 6.0 does not. VC 6.0 has a version number of 1200.
Microsoft eMbedded Visual C++ 4.0 has a version number of 1201 and doesn't
define these.
If some compiler does not provide them, modify the #if appropriately. */
#if defined(_MSC_VER)
#if _MSC_VER > 1300
#define HAVE_UINTPTR_T 1
#define HAVE_INTPTR_T 1
#else
/* VC6, VS 2002 and eVC4 don't support the C99 LL suffix for 64-bit integer literals */
#define Py_LL(x) x##I64
#endif /* _MSC_VER > 1200 */
#endif /* _MSC_VER */
#endif
/* define signed and unsigned exact-width 32-bit and 64-bit types, used in the
implementation of Python long integers. */
#ifndef PY_UINT32_T
#if SIZEOF_INT == 4
#define HAVE_UINT32_T 1
#define PY_UINT32_T unsigned int
#elif SIZEOF_LONG == 4
#define HAVE_UINT32_T 1
#define PY_UINT32_T unsigned long
#endif
#endif
#ifndef PY_UINT64_T
#if SIZEOF_LONG_LONG == 8
#define HAVE_UINT64_T 1
#define PY_UINT64_T unsigned PY_LONG_LONG
#endif
#endif
#ifndef PY_INT32_T
#if SIZEOF_INT == 4
#define HAVE_INT32_T 1
#define PY_INT32_T int
#elif SIZEOF_LONG == 4
#define HAVE_INT32_T 1
#define PY_INT32_T long
#endif
#endif
#ifndef PY_INT64_T
#if SIZEOF_LONG_LONG == 8
#define HAVE_INT64_T 1
#define PY_INT64_T PY_LONG_LONG
#endif
#endif
/* Fairly standard from here! */
/* Define to 1 if you have the `copysign' function. */
#define HAVE_COPYSIGN 1
/* Define to 1 if you have the `round' function. */
#if _MSC_VER >= 1800
#define HAVE_ROUND 1
#endif
/* Define to 1 if you have the `isinf' macro. */
#define HAVE_DECL_ISINF 1
/* Define to 1 if you have the `isnan' function. */
#define HAVE_DECL_ISNAN 1
/* Define if on AIX 3.
System headers sometimes define this.
We just want to avoid a redefinition error message. */
#ifndef _ALL_SOURCE
/* #undef _ALL_SOURCE */
#endif
/* Define to empty if the keyword does not work. */
/* #define const */
/* Define to 1 if you have the <conio.h> header file. */
#ifndef MS_WINCE
#define HAVE_CONIO_H 1
#endif
/* Define to 1 if you have the <direct.h> header file. */
#ifndef MS_WINCE
#define HAVE_DIRECT_H 1
#endif
/* Define if you have dirent.h. */
/* #define DIRENT 1 */
/* Define to the type of elements in the array set by `getgroups'.
Usually this is either `int' or `gid_t'. */
/* #undef GETGROUPS_T */
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef gid_t */
/* Define if your struct tm has tm_zone. */
/* #undef HAVE_TM_ZONE */
/* Define if you don't have tm_zone but do have the external array
tzname. */
#define HAVE_TZNAME
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef mode_t */
/* Define if you don't have dirent.h, but have ndir.h. */
/* #undef NDIR */
/* Define to `long' if <sys/types.h> doesn't define. */
/* #undef off_t */
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef pid_t */
/* Define if the system does not provide POSIX.1 features except
with this defined. */
/* #undef _POSIX_1_SOURCE */
/* Define if you need to in order for stat and other things to work. */
/* #undef _POSIX_SOURCE */
/* Define as the return type of signal handlers (int or void). */
#define RETSIGTYPE void
/* Define to `unsigned' if <sys/types.h> doesn't define. */
/* #undef size_t */
/* Define if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define if you don't have dirent.h, but have sys/dir.h. */
/* #undef SYSDIR */
/* Define if you don't have dirent.h, but have sys/ndir.h. */
/* #undef SYSNDIR */
/* Define if you can safely include both <sys/time.h> and <time.h>. */
/* #undef TIME_WITH_SYS_TIME */
/* Define if your <sys/time.h> declares struct tm. */
/* #define TM_IN_SYS_TIME 1 */
/* Define to `int' if <sys/types.h> doesn't define. */
/* #undef uid_t */
/* Define if the closedir function returns void instead of int. */
/* #undef VOID_CLOSEDIR */
/* Define if getpgrp() must be called as getpgrp(0)
and (consequently) setpgrp() as setpgrp(0, 0). */
/* #undef GETPGRP_HAVE_ARGS */
/* Define this if your time.h defines altzone */
/* #define HAVE_ALTZONE */
/* Define if you have the putenv function. */
#ifndef MS_WINCE
#define HAVE_PUTENV
#endif
/* Define if your compiler supports function prototypes */
#define HAVE_PROTOTYPES
/* Define if you can safely include both <sys/select.h> and <sys/time.h>
(which you can't on SCO ODT 3.0). */
/* #undef SYS_SELECT_WITH_SYS_TIME */
/* Define if you want documentation strings in extension modules */
#define WITH_DOC_STRINGS 1
/* Define if you want to compile in rudimentary thread support */
/* #undef WITH_THREAD */
/* Define if you want to use the GNU readline library */
/* #define WITH_READLINE 1 */
/* Define if you want to have a Unicode type. */
#define Py_USING_UNICODE
/* Define as the size of the unicode type. */
/* This is enough for unicodeobject.h to do the "right thing" on Windows. */
#define Py_UNICODE_SIZE 2
/* Use Python's own small-block memory-allocator. */
#define WITH_PYMALLOC 1
/* Define if you have clock. */
/* #define HAVE_CLOCK */
/* Define when any dynamic module loading is enabled */
#define HAVE_DYNAMIC_LOADING
/* Define if you have ftime. */
#ifndef MS_WINCE
#define HAVE_FTIME
#endif
/* Define if you have getpeername. */
#define HAVE_GETPEERNAME
/* Define if you have getpgrp. */
/* #undef HAVE_GETPGRP */
/* Define if you have getpid. */
#ifndef MS_WINCE
#define HAVE_GETPID
#endif
/* Define if you have gettimeofday. */
/* #undef HAVE_GETTIMEOFDAY */
/* Define if you have getwd. */
/* #undef HAVE_GETWD */
/* Define if you have lstat. */
/* #undef HAVE_LSTAT */
/* Define if you have the mktime function. */
#define HAVE_MKTIME
/* Define if you have nice. */
/* #undef HAVE_NICE */
/* Define if you have readlink. */
/* #undef HAVE_READLINK */
/* Define if you have select. */
/* #undef HAVE_SELECT */
/* Define if you have setpgid. */
/* #undef HAVE_SETPGID */
/* Define if you have setpgrp. */
/* #undef HAVE_SETPGRP */
/* Define if you have setsid. */
/* #undef HAVE_SETSID */
/* Define if you have setvbuf. */
#define HAVE_SETVBUF
/* Define if you have siginterrupt. */
/* #undef HAVE_SIGINTERRUPT */
/* Define if you have symlink. */
/* #undef HAVE_SYMLINK */
/* Define if you have tcgetpgrp. */
/* #undef HAVE_TCGETPGRP */
/* Define if you have tcsetpgrp. */
/* #undef HAVE_TCSETPGRP */
/* Define if you have times. */
/* #undef HAVE_TIMES */
/* Define if you have uname. */
/* #undef HAVE_UNAME */
/* Define if you have waitpid. */
/* #undef HAVE_WAITPID */
/* Define to 1 if you have the `wcscoll' function. */
#ifndef MS_WINCE
#define HAVE_WCSCOLL 1
#endif
/* Define if the zlib library has inflateCopy */
#define HAVE_ZLIB_COPY 1
/* Define if you have the <dlfcn.h> header file. */
/* #undef HAVE_DLFCN_H */
/* Define to 1 if you have the <errno.h> header file. */
#ifndef MS_WINCE
#define HAVE_ERRNO_H 1
#endif
/* Define if you have the <fcntl.h> header file. */
#ifndef MS_WINCE
#define HAVE_FCNTL_H 1
#endif
/* Define to 1 if you have the <process.h> header file. */
#ifndef MS_WINCE
#define HAVE_PROCESS_H 1
#endif
/* Define to 1 if you have the <signal.h> header file. */
#ifndef MS_WINCE
#define HAVE_SIGNAL_H 1
#endif
/* Define if you have the <stdarg.h> prototypes. */
#define HAVE_STDARG_PROTOTYPES
/* Define if you have the <stddef.h> header file. */
#define HAVE_STDDEF_H 1
/* Define if you have the <sys/audioio.h> header file. */
/* #undef HAVE_SYS_AUDIOIO_H */
/* Define if you have the <sys/param.h> header file. */
/* #define HAVE_SYS_PARAM_H 1 */
/* Define if you have the <sys/select.h> header file. */
/* #define HAVE_SYS_SELECT_H 1 */
/* Define to 1 if you have the <sys/stat.h> header file. */
#ifndef MS_WINCE
#define HAVE_SYS_STAT_H 1
#endif
/* Define if you have the <sys/time.h> header file. */
/* #define HAVE_SYS_TIME_H 1 */
/* Define if you have the <sys/times.h> header file. */
/* #define HAVE_SYS_TIMES_H 1 */
/* Define to 1 if you have the <sys/types.h> header file. */
#ifndef MS_WINCE
#define HAVE_SYS_TYPES_H 1
#endif
/* Define if you have the <sys/un.h> header file. */
/* #define HAVE_SYS_UN_H 1 */
/* Define if you have the <sys/utime.h> header file. */
/* #define HAVE_SYS_UTIME_H 1 */
/* Define if you have the <sys/utsname.h> header file. */
/* #define HAVE_SYS_UTSNAME_H 1 */
/* Define if you have the <thread.h> header file. */
/* #undef HAVE_THREAD_H */
/* Define if you have the <unistd.h> header file. */
/* #define HAVE_UNISTD_H 1 */
/* Define if you have the <utime.h> header file. */
/* #define HAVE_UTIME_H 1 */
/* Define if the compiler provides a wchar.h header file. */
#define HAVE_WCHAR_H 1
/* Define if you have the dl library (-ldl). */
/* #undef HAVE_LIBDL */
/* Define if you have the mpc library (-lmpc). */
/* #undef HAVE_LIBMPC */
/* Define if you have the nsl library (-lnsl). */
#define HAVE_LIBNSL 1
/* Define if you have the seq library (-lseq). */
/* #undef HAVE_LIBSEQ */
/* Define if you have the socket library (-lsocket). */
#define HAVE_LIBSOCKET 1
/* Define if you have the sun library (-lsun). */
/* #undef HAVE_LIBSUN */
/* Define if you have the termcap library (-ltermcap). */
/* #undef HAVE_LIBTERMCAP */
/* Define if you have the termlib library (-ltermlib). */
/* #undef HAVE_LIBTERMLIB */
/* Define if you have the thread library (-lthread). */
/* #undef HAVE_LIBTHREAD */
/* WinSock does not use a bitmask in select, and uses
socket handles greater than FD_SETSIZE */
#define Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
/* Define if C doubles are 64-bit IEEE 754 binary format, stored with the
least significant byte first */
#define DOUBLE_IS_LITTLE_ENDIAN_IEEE754 1
#endif /* !Py_CONFIG_H */
+5
View File
@@ -0,0 +1,5 @@
project : n:\python\python-1.5.1\pc\wat_os2\pyth_os2.exe n:\python\python-1.&
5.1\pc\wat_dos\pyth_dos.exe .SYMBOLIC
!include n:\python\python-1.5.1\pc\wat_os2\pyth_os2.mk1
!include n:\python\python-1.5.1\pc\wat_dos\pyth_dos.mk1
+1
View File
@@ -0,0 +1 @@
1 ICON DISCARDABLE "pycon.ico"
+74
View File
@@ -0,0 +1,74 @@
// Resource script for Python core DLL.
// Currently only holds version information.
//
#include "winver.h"
#define MS_WINDOWS
#include "modsupport.h"
#include "patchlevel.h"
#ifdef _DEBUG
# include "pythonnt_rc_d.h"
#else
# include "pythonnt_rc.h"
#endif
/* e.g., 2.1a2
* PY_VERSION comes from patchevel.h
*/
#define PYTHON_VERSION PY_VERSION "\0"
/* 64-bit version number as comma-separated list of 4 16-bit ints */
#if PY_MICRO_VERSION > 64
# error "PY_MICRO_VERSION > 64"
#endif
#if PY_RELEASE_LEVEL > 99
# error "PY_RELEASE_LEVEL > 99"
#endif
#if PY_RELEASE_SERIAL > 9
# error "PY_RELEASE_SERIAL > 9"
#endif
#define PYVERSION64 PY_MAJOR_VERSION, PY_MINOR_VERSION, FIELD3, PYTHON_API_VERSION
// String Tables
STRINGTABLE DISCARDABLE
BEGIN
1000, MS_DLL_ID
END
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION PYVERSION64
PRODUCTVERSION PYVERSION64
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x40004L
FILETYPE 0x1L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "000004b0"
BEGIN
VALUE "CompanyName", "Python Software Foundation\0"
VALUE "FileDescription", "Python Core\0"
VALUE "FileVersion", PYTHON_VERSION
VALUE "InternalName", "Python DLL\0"
VALUE "LegalCopyright", "Copyright © 2001-2017 Python Software Foundation. Copyright © 2000 BeOpen.com. Copyright © 1995-2001 CNRI. Copyright © 1991-1995 SMC.\0"
VALUE "OriginalFilename", PYTHON_DLL_NAME "\0"
VALUE "ProductName", "Python\0"
VALUE "ProductVersion", PYTHON_VERSION
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x0, 1200
END
END
+99
View File
@@ -0,0 +1,99 @@
Welcome to the "PC" subdirectory of the Python distribution
***********************************************************
This "PC" subdirectory contains complete project files to make
several older PC ports of Python, as well as all the PC-specific
Python source files. It should be located in the root of the
Python distribution, and there should be directories "Modules",
"Objects", "Python", etc. in the parent directory of this "PC"
subdirectory. Be sure to read the documentation in the Python
distribution.
Python requires library files such as string.py to be available in
one or more library directories. The search path of libraries is
set up when Python starts. To see the current Python library search
path, start Python and enter "import sys" and "print sys.path".
All PC ports use this scheme to try to set up a module search path:
1) The script location; the current directory without script.
2) The PYTHONPATH variable, if set.
3) For Win32 platforms (NT/95), paths specified in the Registry.
4) Default directories lib, lib/win, lib/test, lib/tkinter;
these are searched relative to the environment variable
PYTHONHOME, if set, or relative to the executable and its
ancestors, if a landmark file (Lib/string.py) is found ,
or the current directory (not useful).
5) The directory containing the executable.
The best installation strategy is to put the Python executable (and
DLL, for Win32 platforms) in some convenient directory such as
C:/python, and copy all library files and subdirectories (using XCOPY)
to C:/python/lib. Then you don't need to set PYTHONPATH. Otherwise,
set the environment variable PYTHONPATH to your Python search path.
For example,
set PYTHONPATH=.;d:\python\lib;d:\python\lib\win;d:\python\lib\dos-8x3
There are several add-in modules to build Python programs which use
the native Windows operating environment. The ports here just make
"QuickWin" and DOS Python versions which support a character-mode
(console) environment. Look in www.python.org for Tkinter, PythonWin,
WPY and wxPython.
To make a Python port, start the Integrated Development Environment
(IDE) of your compiler, and read in the native "project file"
(or makefile) provided. This will enable you to change any source
files or build settings so you can make custom builds.
pyconfig.h An important configuration file specific to PC's.
config.c The list of C modules to include in the Python PC
version. Manually edit this file to add or
remove Python modules.
testpy.py A Python test program. Run this to test your
Python port. It should produce copious output,
ending in a report on how many tests were OK, how many
failed, and how many were skipped. Don't worry about
skipped tests (these test unavailable optional features).
Additional files and subdirectories for 32-bit Windows
======================================================
python_nt.rc Resource compiler input for python15.dll.
dl_nt.c, import_nt.c
Additional sources used for 32-bit Windows features.
getpathp.c Default sys.path calculations (for all PC platforms).
dllbase_nt.txt A (manually maintained) list of base addresses for
various DLLs, to avoid run-time relocation.
Legacy support for older versions of Visual Studio
==================================================
The subdirectories VC6, VS7.1 and VS8.0 contain legacy support older
versions of Microsoft Visual Studio. See PCbuild/readme.txt.
EMX development tools for OS/2
==============================
See os2emx/readme.txt. This platform is maintained by Andrew MacIntyre.
IBM VisualAge C/C++ for OS/2
============================
See os2vacpp/readme.txt. This platform is supported by Jeff Rush.
NOTE: Support for os2vacpp may be dropped in the near future. Please move
to EMX.
Note for Windows 3.x and DOS users
==================================
Neither Windows 3.x nor DOS is supported any more. The last Python
version that supported these was Python 1.5.2; the support files were
present in Python 2.0 but weren't updated, and it is not our intention
to support these platforms for Python 2.x.
+32
View File
@@ -0,0 +1,32 @@
import sys
# This is a test module for Python. It looks in the standard
# places for various *.py files. If these are moved, you must
# change this module too.
try:
import os
except:
print """Could not import the standard "os" module.
Please check your PYTHONPATH environment variable."""
sys.exit(1)
try:
import symbol
except:
print """Could not import the standard "symbol" module. If this is
a PC, you should add the dos_8x3 directory to your PYTHONPATH."""
sys.exit(1)
import os
for dir in sys.path:
file = os.path.join(dir, "os.py")
if os.path.isfile(file):
test = os.path.join(dir, "test")
if os.path.isdir(test):
# Add the "test" directory to PYTHONPATH.
sys.path = sys.path + [test]
import regrtest # Standard Python tester.
regrtest.main()
+112
View File
@@ -0,0 +1,112 @@
/*
* w9xpopen.c
*
* Serves as an intermediate stub Win32 console application to
* avoid a hanging pipe when redirecting 16-bit console based
* programs (including MS-DOS console based programs and batch
* files) on Window 95 and Windows 98.
*
* This program is to be launched with redirected standard
* handles. It will launch the command line specified 16-bit
* console based application in the same console, forwarding
* its own redirected standard handles to the 16-bit child.
* AKA solution to the problem described in KB: Q150956.
*/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <stdlib.h> /* for malloc and its friends */
const char *usage =
"This program is used by Python's os.popen function\n"
"to work around a limitation in Windows 95/98. It is\n"
"not designed to be used as a stand-alone program.";
int main(int argc, char *argv[])
{
BOOL bRet;
STARTUPINFO si;
PROCESS_INFORMATION pi;
DWORD exit_code=0;
size_t cmdlen = 0;
int i;
char *cmdline, *cmdlinefill;
if (argc < 2) {
if (GetFileType(GetStdHandle(STD_INPUT_HANDLE))==FILE_TYPE_CHAR)
/* Attached to a console, and therefore not executed by Python
Display a message box for the inquisitive user
*/
MessageBox(NULL, usage, argv[0], MB_OK);
else {
/* Eeek - executed by Python, but args are screwed!
Write an error message to stdout so there is at
least some clue for the end user when it appears
in their output.
A message box would be hidden and blocks the app.
*/
fprintf(stdout, "Internal popen error - no args specified\n%s\n", usage);
}
return 1;
}
/* Build up the command-line from the args.
Args with a space are quoted, existing quotes are escaped.
To keep things simple calculating the buffer size, we assume
every character is a quote - ie, we allocate double what we need
in the worst case. As this is only double the command line passed
to us, there is a good chance this is reasonably small, so the total
allocation will almost always be < 512 bytes.
*/
for (i=1;i<argc;i++)
cmdlen += strlen(argv[i])*2 + 3; /* one space, maybe 2 quotes */
cmdline = cmdlinefill = (char *)malloc(cmdlen+1);
if (cmdline == NULL)
return -1;
for (i=1;i<argc;i++) {
const char *arglook;
int bQuote = strchr(argv[i], ' ') != NULL;
if (bQuote)
*cmdlinefill++ = '"';
/* escape quotes */
for (arglook=argv[i];*arglook;arglook++) {
if (*arglook=='"')
*cmdlinefill++ = '\\';
*cmdlinefill++ = *arglook;
}
if (bQuote)
*cmdlinefill++ = '"';
*cmdlinefill++ = ' ';
}
*cmdlinefill = '\0';
/* Make child process use this app's standard files. */
ZeroMemory(&si, sizeof si);
si.cb = sizeof si;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
bRet = CreateProcess(
NULL, cmdline,
NULL, NULL,
TRUE, 0,
NULL, NULL,
&si, &pi
);
free(cmdline);
if (bRet) {
if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_FAILED) {
GetExitCodeProcess(pi.hProcess, &exit_code);
}
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return exit_code;
}
return 1;
}
+191
View File
@@ -0,0 +1,191 @@
/* Author: Toby Dickenson <htrd90@zepler.org>
*
* Copyright (c) 1999 Toby Dickenson
*
* Permission to use this software in any way is granted without
* fee, provided that the copyright notice above appears in all
* copies. This software is provided "as is" without any warranty.
*/
/* Modified by Guido van Rossum */
/* Beep added by Mark Hammond */
/* Win9X Beep and platform identification added by Uncle Timmy */
/* Example:
import winsound
import time
# Play wav file
winsound.PlaySound('c:/windows/media/Chord.wav', winsound.SND_FILENAME)
# Play sound from control panel settings
winsound.PlaySound('SystemQuestion', winsound.SND_ALIAS)
# Play wav file from memory
data=open('c:/windows/media/Chimes.wav',"rb").read()
winsound.PlaySound(data, winsound.SND_MEMORY)
# Start playing the first bit of wav file asynchronously
winsound.PlaySound('c:/windows/media/Chord.wav',
winsound.SND_FILENAME|winsound.SND_ASYNC)
# But dont let it go for too long...
time.sleep(0.1)
# ...Before stopping it
winsound.PlaySound(None, 0)
*/
#include <Python.h>
#include <windows.h>
#include <mmsystem.h>
PyDoc_STRVAR(sound_playsound_doc,
"PlaySound(sound, flags) - a wrapper around the Windows PlaySound API\n"
"\n"
"The sound argument can be a filename, data, or None.\n"
"For flag values, ored together, see module documentation.");
PyDoc_STRVAR(sound_beep_doc,
"Beep(frequency, duration) - a wrapper around the Windows Beep API\n"
"\n"
"The frequency argument specifies frequency, in hertz, of the sound.\n"
"This parameter must be in the range 37 through 32,767.\n"
"The duration argument specifies the number of milliseconds.\n");
PyDoc_STRVAR(sound_msgbeep_doc,
"MessageBeep(x) - call Windows MessageBeep(x). x defaults to MB_OK.");
PyDoc_STRVAR(sound_module_doc,
"PlaySound(sound, flags) - play a sound\n"
"SND_FILENAME - sound is a wav file name\n"
"SND_ALIAS - sound is a registry sound association name\n"
"SND_LOOP - Play the sound repeatedly; must also specify SND_ASYNC\n"
"SND_MEMORY - sound is a memory image of a wav file\n"
"SND_PURGE - stop all instances of the specified sound\n"
"SND_ASYNC - PlaySound returns immediately\n"
"SND_NODEFAULT - Do not play a default beep if the sound can not be found\n"
"SND_NOSTOP - Do not interrupt any sounds currently playing\n" // Raising RuntimeError if needed
"SND_NOWAIT - Return immediately if the sound driver is busy\n" // Without any errors
"\n"
"Beep(frequency, duration) - Make a beep through the PC speaker.");
static PyObject *
sound_playsound(PyObject *s, PyObject *args)
{
const char *sound;
int flags;
int length;
int ok;
if (!PyArg_ParseTuple(args, "z#i:PlaySound", &sound, &length, &flags)) {
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;
}
Py_BEGIN_ALLOW_THREADS
ok = PlaySound(sound, NULL, flags);
Py_END_ALLOW_THREADS
if (!ok) {
PyErr_SetString(PyExc_RuntimeError, "Failed to play sound");
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
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;
}
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;
}
static struct PyMethodDef sound_methods[] =
{
{"PlaySound", sound_playsound, METH_VARARGS, sound_playsound_doc},
{"Beep", sound_beep, METH_VARARGS, sound_beep_doc},
{"MessageBeep", sound_msgbeep, METH_VARARGS, sound_msgbeep_doc},
{NULL, NULL}
};
static void
add_define(PyObject *dict, const char *key, long value)
{
PyObject *k = PyString_FromString(key);
PyObject *v = PyLong_FromLong(value);
if (v && k) {
PyDict_SetItem(dict, k, v);
}
Py_XDECREF(k);
Py_XDECREF(v);
}
#define ADD_DEFINE(tok) add_define(dict,#tok,tok)
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);
}