Recorded merge of revisions 81029 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/trunk

........
  r81029 | antoine.pitrou | 2010-05-09 16:46:46 +0200 (dim., 09 mai 2010) | 3 lines

  Untabify C files. Will watch buildbots.
........
This commit is contained in:
Antoine Pitrou 2010-05-09 15:52:27 +00:00
parent bd25030019
commit f95a1b3c53
248 changed files with 113361 additions and 113361 deletions

View file

@ -6,44 +6,44 @@ PyObject* PyInit_xyzzy(void); /* Forward */
main(int argc, char **argv)
{
/* Ignore passed-in argc/argv. If desired, conversion
should use mbstowcs to convert them. */
wchar_t *args[] = {L"embed", L"hello", 0};
/* Ignore passed-in argc/argv. If desired, conversion
should use mbstowcs to convert them. */
wchar_t *args[] = {L"embed", L"hello", 0};
/* Pass argv[0] to the Python interpreter */
Py_SetProgramName(args[0]);
/* Pass argv[0] to the Python interpreter */
Py_SetProgramName(args[0]);
/* Add a static module */
PyImport_AppendInittab("xyzzy", PyInit_xyzzy);
/* Add a static module */
PyImport_AppendInittab("xyzzy", PyInit_xyzzy);
/* Initialize the Python interpreter. Required. */
Py_Initialize();
/* Initialize the Python interpreter. Required. */
Py_Initialize();
/* Define sys.argv. It is up to the application if you
want this; you can also let it undefined (since the Python
code is generally not a main program it has no business
touching sys.argv...) */
PySys_SetArgv(2, args);
/* Define sys.argv. It is up to the application if you
want this; you can also let it undefined (since the Python
code is generally not a main program it has no business
touching sys.argv...) */
PySys_SetArgv(2, args);
/* Do some application specific code */
printf("Hello, brave new world\n\n");
/* Do some application specific code */
printf("Hello, brave new world\n\n");
/* Execute some Python statements (in module __main__) */
PyRun_SimpleString("import sys\n");
PyRun_SimpleString("print(sys.builtin_module_names)\n");
PyRun_SimpleString("print(sys.modules.keys())\n");
PyRun_SimpleString("print(sys.executable)\n");
PyRun_SimpleString("print(sys.argv)\n");
/* Execute some Python statements (in module __main__) */
PyRun_SimpleString("import sys\n");
PyRun_SimpleString("print(sys.builtin_module_names)\n");
PyRun_SimpleString("print(sys.modules.keys())\n");
PyRun_SimpleString("print(sys.executable)\n");
PyRun_SimpleString("print(sys.argv)\n");
/* Note that you can call any public function of the Python
interpreter here, e.g. call_object(). */
/* Note that you can call any public function of the Python
interpreter here, e.g. call_object(). */
/* Some more application specific code */
printf("\nGoodbye, cruel world\n");
/* Some more application specific code */
printf("\nGoodbye, cruel world\n");
/* Exit, cleaning up the interpreter */
Py_Exit(0);
/*NOTREACHED*/
/* Exit, cleaning up the interpreter */
Py_Exit(0);
/*NOTREACHED*/
}
/* A static module */
@ -52,29 +52,29 @@ main(int argc, char **argv)
static PyObject *
xyzzy_foo(PyObject *self, PyObject* args)
{
return PyLong_FromLong(42L);
return PyLong_FromLong(42L);
}
static PyMethodDef xyzzy_methods[] = {
{"foo", xyzzy_foo, METH_NOARGS,
"Return the meaning of everything."},
{NULL, NULL} /* sentinel */
{"foo", xyzzy_foo, METH_NOARGS,
"Return the meaning of everything."},
{NULL, NULL} /* sentinel */
};
static struct PyModuleDef xyzzymodule = {
{}, /* m_base */
"xyzzy", /* m_name */
0, /* m_doc */
0, /* m_size */
xyzzy_methods, /* m_methods */
0, /* m_reload */
0, /* m_traverse */
0, /* m_clear */
0, /* m_free */
{}, /* m_base */
"xyzzy", /* m_name */
0, /* m_doc */
0, /* m_size */
xyzzy_methods, /* m_methods */
0, /* m_reload */
0, /* m_traverse */
0, /* m_clear */
0, /* m_free */
};
PyObject*
PyInit_xyzzy(void)
{
return PyModule_Create(&xyzzymodule);
return PyModule_Create(&xyzzymodule);
}

View file

@ -6,28 +6,28 @@
main(int argc, char **argv)
{
int count = -1;
char *command;
int count = -1;
char *command;
if (argc < 2 || argc > 3) {
fprintf(stderr, "usage: loop <python-command> [count]\n");
exit(2);
}
command = argv[1];
if (argc < 2 || argc > 3) {
fprintf(stderr, "usage: loop <python-command> [count]\n");
exit(2);
}
command = argv[1];
if (argc == 3) {
count = atoi(argv[2]);
}
if (argc == 3) {
count = atoi(argv[2]);
}
Py_SetProgramName(argv[0]);
Py_SetProgramName(argv[0]);
/* uncomment this if you don't want to load site.py */
/* Py_NoSiteFlag = 1; */
/* uncomment this if you don't want to load site.py */
/* Py_NoSiteFlag = 1; */
while (count == -1 || --count >= 0 ) {
Py_Initialize();
PyRun_SimpleString(command);
Py_Finalize();
}
return 0;
while (count == -1 || --count >= 0 ) {
Py_Initialize();
PyRun_SimpleString(command);
Py_Finalize();
}
return 0;
}

View file

@ -34,8 +34,8 @@ extern int Py_VerboseFlag;
#endif
struct workorder {
int conn;
struct sockaddr_in addr;
int conn;
struct sockaddr_in addr;
};
/* Forward */
@ -55,40 +55,40 @@ static PyThreadState *gtstate;
main(int argc, char **argv)
{
int port = PORT;
int c;
int port = PORT;
int c;
if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0')
progname = argv[0];
if (argc > 0 && argv[0] != NULL && argv[0][0] != '\0')
progname = argv[0];
while ((c = getopt(argc, argv, "v")) != EOF) {
switch (c) {
case 'v':
Py_VerboseFlag++;
break;
default:
usage();
}
}
while ((c = getopt(argc, argv, "v")) != EOF) {
switch (c) {
case 'v':
Py_VerboseFlag++;
break;
default:
usage();
}
}
if (optind < argc) {
if (optind+1 < argc) {
oprogname();
fprintf(stderr, "too many arguments\n");
usage();
}
port = atoi(argv[optind]);
if (port <= 0) {
fprintf(stderr, "bad port (%s)\n", argv[optind]);
usage();
}
}
if (optind < argc) {
if (optind+1 < argc) {
oprogname();
fprintf(stderr, "too many arguments\n");
usage();
}
port = atoi(argv[optind]);
if (port <= 0) {
fprintf(stderr, "bad port (%s)\n", argv[optind]);
usage();
}
}
main_thread(port);
main_thread(port);
fprintf(stderr, "Bye.\n");
fprintf(stderr, "Bye.\n");
exit(0);
exit(0);
}
static char usage_line[] = "usage: %s [port]\n";
@ -96,120 +96,120 @@ static char usage_line[] = "usage: %s [port]\n";
static void
usage(void)
{
fprintf(stderr, usage_line, progname);
exit(2);
fprintf(stderr, usage_line, progname);
exit(2);
}
static void
main_thread(int port)
{
int sock, conn, size, i;
struct sockaddr_in addr, clientaddr;
int sock, conn, size, i;
struct sockaddr_in addr, clientaddr;
sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0) {
oprogname();
perror("can't create socket");
exit(1);
}
sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0) {
oprogname();
perror("can't create socket");
exit(1);
}
#ifdef SO_REUSEADDR
i = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i);
i = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &i, sizeof i);
#endif
memset((char *)&addr, '\0', sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = 0L;
if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) {
oprogname();
perror("can't bind socket to address");
exit(1);
}
memset((char *)&addr, '\0', sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = 0L;
if (bind(sock, (struct sockaddr *)&addr, sizeof addr) < 0) {
oprogname();
perror("can't bind socket to address");
exit(1);
}
if (listen(sock, 5) < 0) {
oprogname();
perror("can't listen on socket");
exit(1);
}
if (listen(sock, 5) < 0) {
oprogname();
perror("can't listen on socket");
exit(1);
}
fprintf(stderr, "Listening on port %d...\n", port);
fprintf(stderr, "Listening on port %d...\n", port);
for (i = 0; ; i++) {
size = sizeof clientaddr;
memset((char *) &clientaddr, '\0', size);
conn = accept(sock, (struct sockaddr *) &clientaddr, &size);
if (conn < 0) {
oprogname();
perror("can't accept connection from socket");
exit(1);
}
for (i = 0; ; i++) {
size = sizeof clientaddr;
memset((char *) &clientaddr, '\0', size);
conn = accept(sock, (struct sockaddr *) &clientaddr, &size);
if (conn < 0) {
oprogname();
perror("can't accept connection from socket");
exit(1);
}
size = sizeof addr;
memset((char *) &addr, '\0', size);
if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) {
oprogname();
perror("can't get socket name of connection");
exit(1);
}
if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) {
oprogname();
perror("connection from non-local host refused");
fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n",
ntohl(addr.sin_addr.s_addr),
ntohl(clientaddr.sin_addr.s_addr));
close(conn);
continue;
}
if (i == 4) {
close(conn);
break;
}
create_thread(conn, &clientaddr);
}
size = sizeof addr;
memset((char *) &addr, '\0', size);
if (getsockname(conn, (struct sockaddr *)&addr, &size) < 0) {
oprogname();
perror("can't get socket name of connection");
exit(1);
}
if (clientaddr.sin_addr.s_addr != addr.sin_addr.s_addr) {
oprogname();
perror("connection from non-local host refused");
fprintf(stderr, "(addr=%lx, clientaddr=%lx)\n",
ntohl(addr.sin_addr.s_addr),
ntohl(clientaddr.sin_addr.s_addr));
close(conn);
continue;
}
if (i == 4) {
close(conn);
break;
}
create_thread(conn, &clientaddr);
}
close(sock);
close(sock);
if (gtstate) {
PyEval_AcquireThread(gtstate);
gtstate = NULL;
Py_Finalize();
/* And a second time, just because we can. */
Py_Finalize(); /* This should be harmless. */
}
exit(0);
if (gtstate) {
PyEval_AcquireThread(gtstate);
gtstate = NULL;
Py_Finalize();
/* And a second time, just because we can. */
Py_Finalize(); /* This should be harmless. */
}
exit(0);
}
static void
create_thread(int conn, struct sockaddr_in *addr)
{
struct workorder *work;
pthread_t tdata;
struct workorder *work;
pthread_t tdata;
work = malloc(sizeof(struct workorder));
if (work == NULL) {
oprogname();
fprintf(stderr, "out of memory for thread.\n");
close(conn);
return;
}
work->conn = conn;
work->addr = *addr;
work = malloc(sizeof(struct workorder));
if (work == NULL) {
oprogname();
fprintf(stderr, "out of memory for thread.\n");
close(conn);
return;
}
work->conn = conn;
work->addr = *addr;
init_python();
init_python();
if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) {
oprogname();
perror("can't create new thread");
close(conn);
return;
}
if (pthread_create(&tdata, NULL, (void *)service_thread, work) < 0) {
oprogname();
perror("can't create new thread");
close(conn);
return;
}
if (pthread_detach(tdata) < 0) {
oprogname();
perror("can't detach from thread");
}
if (pthread_detach(tdata) < 0) {
oprogname();
perror("can't detach from thread");
}
}
static PyThreadState *the_tstate;
@ -219,152 +219,152 @@ static PyObject *the_builtins;
static void
init_python(void)
{
if (gtstate)
return;
Py_Initialize(); /* Initialize the interpreter */
PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */
gtstate = PyEval_SaveThread(); /* Release the thread state */
if (gtstate)
return;
Py_Initialize(); /* Initialize the interpreter */
PyEval_InitThreads(); /* Create (and acquire) the interpreter lock */
gtstate = PyEval_SaveThread(); /* Release the thread state */
}
static void *
service_thread(struct workorder *work)
{
FILE *input, *output;
FILE *input, *output;
fprintf(stderr, "Start thread for connection %d.\n", work->conn);
fprintf(stderr, "Start thread for connection %d.\n", work->conn);
ps();
ps();
input = fdopen(work->conn, "r");
if (input == NULL) {
oprogname();
perror("can't create input stream");
goto done;
}
input = fdopen(work->conn, "r");
if (input == NULL) {
oprogname();
perror("can't create input stream");
goto done;
}
output = fdopen(work->conn, "w");
if (output == NULL) {
oprogname();
perror("can't create output stream");
fclose(input);
goto done;
}
output = fdopen(work->conn, "w");
if (output == NULL) {
oprogname();
perror("can't create output stream");
fclose(input);
goto done;
}
setvbuf(input, NULL, _IONBF, 0);
setvbuf(output, NULL, _IONBF, 0);
setvbuf(input, NULL, _IONBF, 0);
setvbuf(output, NULL, _IONBF, 0);
run_interpreter(input, output);
run_interpreter(input, output);
fclose(input);
fclose(output);
fclose(input);
fclose(output);
done:
fprintf(stderr, "End thread for connection %d.\n", work->conn);
close(work->conn);
free(work);
fprintf(stderr, "End thread for connection %d.\n", work->conn);
close(work->conn);
free(work);
}
static void
oprogname(void)
{
int save = errno;
fprintf(stderr, "%s: ", progname);
errno = save;
int save = errno;
fprintf(stderr, "%s: ", progname);
errno = save;
}
static void
run_interpreter(FILE *input, FILE *output)
{
PyThreadState *tstate;
PyObject *new_stdin, *new_stdout;
PyObject *mainmod, *globals;
char buffer[1000];
char *p, *q;
int n, end;
PyThreadState *tstate;
PyObject *new_stdin, *new_stdout;
PyObject *mainmod, *globals;
char buffer[1000];
char *p, *q;
int n, end;
PyEval_AcquireLock();
tstate = Py_NewInterpreter();
if (tstate == NULL) {
fprintf(output, "Sorry -- can't create an interpreter\n");
return;
}
PyEval_AcquireLock();
tstate = Py_NewInterpreter();
if (tstate == NULL) {
fprintf(output, "Sorry -- can't create an interpreter\n");
return;
}
mainmod = PyImport_AddModule("__main__");
globals = PyModule_GetDict(mainmod);
Py_INCREF(globals);
mainmod = PyImport_AddModule("__main__");
globals = PyModule_GetDict(mainmod);
Py_INCREF(globals);
new_stdin = PyFile_FromFile(input, "<socket-in>", "r", NULL);
new_stdout = PyFile_FromFile(output, "<socket-out>", "w", NULL);
new_stdin = PyFile_FromFile(input, "<socket-in>", "r", NULL);
new_stdout = PyFile_FromFile(output, "<socket-out>", "w", NULL);
PySys_SetObject("stdin", new_stdin);
PySys_SetObject("stdout", new_stdout);
PySys_SetObject("stderr", new_stdout);
PySys_SetObject("stdin", new_stdin);
PySys_SetObject("stdout", new_stdout);
PySys_SetObject("stderr", new_stdout);
for (n = 1; !PyErr_Occurred(); n++) {
Py_BEGIN_ALLOW_THREADS
fprintf(output, "%d> ", n);
p = fgets(buffer, sizeof buffer, input);
Py_END_ALLOW_THREADS
for (n = 1; !PyErr_Occurred(); n++) {
Py_BEGIN_ALLOW_THREADS
fprintf(output, "%d> ", n);
p = fgets(buffer, sizeof buffer, input);
Py_END_ALLOW_THREADS
if (p == NULL)
break;
if (p[0] == '\377' && p[1] == '\354')
break;
if (p == NULL)
break;
if (p[0] == '\377' && p[1] == '\354')
break;
q = strrchr(p, '\r');
if (q && q[1] == '\n' && q[2] == '\0') {
*q++ = '\n';
*q++ = '\0';
}
q = strrchr(p, '\r');
if (q && q[1] == '\n' && q[2] == '\0') {
*q++ = '\n';
*q++ = '\0';
}
while (*p && isspace(*p))
p++;
if (p[0] == '#' || p[0] == '\0')
continue;
while (*p && isspace(*p))
p++;
if (p[0] == '#' || p[0] == '\0')
continue;
end = run_command(buffer, globals);
if (end < 0)
PyErr_Print();
end = run_command(buffer, globals);
if (end < 0)
PyErr_Print();
if (end)
break;
}
if (end)
break;
}
Py_XDECREF(globals);
Py_XDECREF(new_stdin);
Py_XDECREF(new_stdout);
Py_XDECREF(globals);
Py_XDECREF(new_stdin);
Py_XDECREF(new_stdout);
Py_EndInterpreter(tstate);
PyEval_ReleaseLock();
Py_EndInterpreter(tstate);
PyEval_ReleaseLock();
fprintf(output, "Goodbye!\n");
fprintf(output, "Goodbye!\n");
}
static int
run_command(char *buffer, PyObject *globals)
{
PyObject *m, *d, *v;
fprintf(stderr, "run_command: %s", buffer);
if (strchr(buffer, '\n') == NULL)
fprintf(stderr, "\n");
v = PyRun_String(buffer, Py_single_input, globals, globals);
if (v == NULL) {
if (PyErr_Occurred() == PyExc_SystemExit) {
PyErr_Clear();
return 1;
}
PyErr_Print();
return 0;
}
Py_DECREF(v);
return 0;
PyObject *m, *d, *v;
fprintf(stderr, "run_command: %s", buffer);
if (strchr(buffer, '\n') == NULL)
fprintf(stderr, "\n");
v = PyRun_String(buffer, Py_single_input, globals, globals);
if (v == NULL) {
if (PyErr_Occurred() == PyExc_SystemExit) {
PyErr_Clear();
return 1;
}
PyErr_Print();
return 0;
}
Py_DECREF(v);
return 0;
}
static void
ps(void)
{
char buffer[100];
PyOS_snprintf(buffer, sizeof(buffer),
"ps -l -p %d </dev/null | sed 1d\n", getpid());
system(buffer);
char buffer[100];
PyOS_snprintf(buffer, sizeof(buffer),
"ps -l -p %d </dev/null | sed 1d\n", getpid());
system(buffer);
}

File diff suppressed because it is too large Load diff

View file

@ -8,11 +8,11 @@ extern "C" {
/* Interface to random parts in ceval.c */
PyAPI_FUNC(PyObject *) PyEval_CallObjectWithKeywords(
PyObject *, PyObject *, PyObject *);
PyObject *, PyObject *, PyObject *);
/* Inline this */
#define PyEval_CallObject(func,arg) \
PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
PyAPI_FUNC(PyObject *) PyEval_CallFunction(PyObject *obj,
const char *format, ...);
@ -45,7 +45,7 @@ PyAPI_FUNC(int) Py_MakePendingCalls(void);
exceeds the current recursion limit. It raises a RuntimeError, and sets
the "overflowed" flag in the thread state structure. This flag
temporarily *disables* the normal protection; this allows cleanup code
to potentially outgrow the recursion limit while processing the
to potentially outgrow the recursion limit while processing the
RuntimeError.
* "last chance" anti-recursion protection is triggered when the recursion
level exceeds "current recursion limit + 50". By construction, this
@ -67,12 +67,12 @@ PyAPI_FUNC(void) Py_SetRecursionLimit(int);
PyAPI_FUNC(int) Py_GetRecursionLimit(void);
#define Py_EnterRecursiveCall(where) \
(_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \
_Py_CheckRecursiveCall(where))
#define Py_LeaveRecursiveCall() \
(_Py_MakeRecCheck(PyThreadState_GET()->recursion_depth) && \
_Py_CheckRecursiveCall(where))
#define Py_LeaveRecursiveCall() \
do{ if(_Py_MakeEndRecCheck(PyThreadState_GET()->recursion_depth)) \
PyThreadState_GET()->overflowed = 0; \
} while(0)
PyThreadState_GET()->overflowed = 0; \
} while(0)
PyAPI_FUNC(int) _Py_CheckRecursiveCall(char *where);
PyAPI_DATA(int) _Py_CheckRecursionLimit;
@ -83,15 +83,15 @@ PyAPI_DATA(int) _Py_CheckRecursionLimit;
of _Py_CheckRecursionLimit for _Py_MakeEndRecCheck() to function properly.
*/
# define _Py_MakeRecCheck(x) \
(++(x) > (_Py_CheckRecursionLimit += PyThreadState_GET()->overflowed - 1))
(++(x) > (_Py_CheckRecursionLimit += PyThreadState_GET()->overflowed - 1))
#else
# define _Py_MakeRecCheck(x) (++(x) > _Py_CheckRecursionLimit)
#endif
#define _Py_MakeEndRecCheck(x) \
(--(x) < ((_Py_CheckRecursionLimit > 100) \
? (_Py_CheckRecursionLimit - 50) \
: (3 * (_Py_CheckRecursionLimit >> 2))))
(--(x) < ((_Py_CheckRecursionLimit > 100) \
? (_Py_CheckRecursionLimit - 50) \
: (3 * (_Py_CheckRecursionLimit >> 2))))
#define Py_ALLOW_RECURSION \
do { unsigned char _old = PyThreadState_GET()->recursion_critical;\
@ -114,31 +114,31 @@ PyAPI_FUNC(PyObject *) PyEval_EvalFrameEx(struct _frame *f, int exc);
that lasts a long time and doesn't touch Python data) can allow other
threads to run as follows:
...preparations here...
Py_BEGIN_ALLOW_THREADS
...blocking system call here...
Py_END_ALLOW_THREADS
...interpret result here...
...preparations here...
Py_BEGIN_ALLOW_THREADS
...blocking system call here...
Py_END_ALLOW_THREADS
...interpret result here...
The Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS pair expands to a
{}-surrounded block.
To leave the block in the middle (e.g., with return), you must insert
a line containing Py_BLOCK_THREADS before the return, e.g.
if (...premature_exit...) {
Py_BLOCK_THREADS
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
if (...premature_exit...) {
Py_BLOCK_THREADS
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
An alternative is:
Py_BLOCK_THREADS
if (...premature_exit...) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
Py_UNBLOCK_THREADS
Py_BLOCK_THREADS
if (...premature_exit...) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
Py_UNBLOCK_THREADS
For convenience, that the value of 'errno' is restored across
Py_END_ALLOW_THREADS and Py_BLOCK_THREADS.
@ -170,12 +170,12 @@ PyAPI_FUNC(void) _PyEval_SetSwitchInterval(unsigned long microseconds);
PyAPI_FUNC(unsigned long) _PyEval_GetSwitchInterval(void);
#define Py_BEGIN_ALLOW_THREADS { \
PyThreadState *_save; \
_save = PyEval_SaveThread();
#define Py_BLOCK_THREADS PyEval_RestoreThread(_save);
#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread();
#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \
}
PyThreadState *_save; \
_save = PyEval_SaveThread();
#define Py_BLOCK_THREADS PyEval_RestoreThread(_save);
#define Py_UNBLOCK_THREADS _save = PyEval_SaveThread();
#define Py_END_ALLOW_THREADS PyEval_RestoreThread(_save); \
}
#else /* !WITH_THREAD */

View file

@ -11,13 +11,13 @@ extern "C" {
* big-endian, unless otherwise noted:
*
* byte offset
* 0 year 2 bytes, 1-9999
* 2 month 1 byte, 1-12
* 3 day 1 byte, 1-31
* 4 hour 1 byte, 0-23
* 5 minute 1 byte, 0-59
* 6 second 1 byte, 0-59
* 7 usecond 3 bytes, 0-999999
* 0 year 2 bytes, 1-9999
* 2 month 1 byte, 1-12
* 3 day 1 byte, 1-31
* 4 hour 1 byte, 0-23
* 5 minute 1 byte, 0-59
* 6 second 1 byte, 0-59
* 7 usecond 3 bytes, 0-999999
* 10
*/
@ -33,26 +33,26 @@ extern "C" {
typedef struct
{
PyObject_HEAD
long hashcode; /* -1 when unknown */
int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */
int seconds; /* 0 <= seconds < 24*3600 is invariant */
int microseconds; /* 0 <= microseconds < 1000000 is invariant */
PyObject_HEAD
long hashcode; /* -1 when unknown */
int days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */
int seconds; /* 0 <= seconds < 24*3600 is invariant */
int microseconds; /* 0 <= microseconds < 1000000 is invariant */
} PyDateTime_Delta;
typedef struct
{
PyObject_HEAD /* a pure abstract base clase */
PyObject_HEAD /* a pure abstract base clase */
} PyDateTime_TZInfo;
/* The datetime and time types have hashcodes, and an optional tzinfo member,
* present if and only if hastzinfo is true.
*/
#define _PyTZINFO_HEAD \
PyObject_HEAD \
long hashcode; \
char hastzinfo; /* boolean flag */
#define _PyTZINFO_HEAD \
PyObject_HEAD \
long hashcode; \
char hastzinfo; /* boolean flag */
/* No _PyDateTime_BaseTZInfo is allocated; it's just to have something
* convenient to cast to, when getting at the hastzinfo member of objects
@ -60,7 +60,7 @@ typedef struct
*/
typedef struct
{
_PyTZINFO_HEAD
_PyTZINFO_HEAD
} _PyDateTime_BaseTZInfo;
/* All time objects are of PyDateTime_TimeType, but that can be allocated
@ -69,20 +69,20 @@ typedef struct
* internal struct used to allocate the right amount of space for the
* "without" case.
*/
#define _PyDateTime_TIMEHEAD \
_PyTZINFO_HEAD \
unsigned char data[_PyDateTime_TIME_DATASIZE];
#define _PyDateTime_TIMEHEAD \
_PyTZINFO_HEAD \
unsigned char data[_PyDateTime_TIME_DATASIZE];
typedef struct
{
_PyDateTime_TIMEHEAD
} _PyDateTime_BaseTime; /* hastzinfo false */
_PyDateTime_TIMEHEAD
} _PyDateTime_BaseTime; /* hastzinfo false */
typedef struct
{
_PyDateTime_TIMEHEAD
PyObject *tzinfo;
} PyDateTime_Time; /* hastzinfo true */
_PyDateTime_TIMEHEAD
PyObject *tzinfo;
} PyDateTime_Time; /* hastzinfo true */
/* All datetime objects are of PyDateTime_DateTimeType, but that can be
@ -92,48 +92,48 @@ typedef struct
*/
typedef struct
{
_PyTZINFO_HEAD
unsigned char data[_PyDateTime_DATE_DATASIZE];
_PyTZINFO_HEAD
unsigned char data[_PyDateTime_DATE_DATASIZE];
} PyDateTime_Date;
#define _PyDateTime_DATETIMEHEAD \
_PyTZINFO_HEAD \
unsigned char data[_PyDateTime_DATETIME_DATASIZE];
#define _PyDateTime_DATETIMEHEAD \
_PyTZINFO_HEAD \
unsigned char data[_PyDateTime_DATETIME_DATASIZE];
typedef struct
{
_PyDateTime_DATETIMEHEAD
} _PyDateTime_BaseDateTime; /* hastzinfo false */
_PyDateTime_DATETIMEHEAD
} _PyDateTime_BaseDateTime; /* hastzinfo false */
typedef struct
{
_PyDateTime_DATETIMEHEAD
PyObject *tzinfo;
} PyDateTime_DateTime; /* hastzinfo true */
_PyDateTime_DATETIMEHEAD
PyObject *tzinfo;
} PyDateTime_DateTime; /* hastzinfo true */
/* Apply for date and datetime instances. */
#define PyDateTime_GET_YEAR(o) ((((PyDateTime_Date*)o)->data[0] << 8) | \
((PyDateTime_Date*)o)->data[1])
((PyDateTime_Date*)o)->data[1])
#define PyDateTime_GET_MONTH(o) (((PyDateTime_Date*)o)->data[2])
#define PyDateTime_GET_DAY(o) (((PyDateTime_Date*)o)->data[3])
#define PyDateTime_DATE_GET_HOUR(o) (((PyDateTime_DateTime*)o)->data[4])
#define PyDateTime_DATE_GET_MINUTE(o) (((PyDateTime_DateTime*)o)->data[5])
#define PyDateTime_DATE_GET_SECOND(o) (((PyDateTime_DateTime*)o)->data[6])
#define PyDateTime_DATE_GET_MICROSECOND(o) \
((((PyDateTime_DateTime*)o)->data[7] << 16) | \
(((PyDateTime_DateTime*)o)->data[8] << 8) | \
((PyDateTime_DateTime*)o)->data[9])
#define PyDateTime_DATE_GET_MICROSECOND(o) \
((((PyDateTime_DateTime*)o)->data[7] << 16) | \
(((PyDateTime_DateTime*)o)->data[8] << 8) | \
((PyDateTime_DateTime*)o)->data[9])
/* Apply for time instances. */
#define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0])
#define PyDateTime_TIME_GET_MINUTE(o) (((PyDateTime_Time*)o)->data[1])
#define PyDateTime_TIME_GET_SECOND(o) (((PyDateTime_Time*)o)->data[2])
#define PyDateTime_TIME_GET_MICROSECOND(o) \
((((PyDateTime_Time*)o)->data[3] << 16) | \
(((PyDateTime_Time*)o)->data[4] << 8) | \
((PyDateTime_Time*)o)->data[5])
#define PyDateTime_TIME_GET_MICROSECOND(o) \
((((PyDateTime_Time*)o)->data[3] << 16) | \
(((PyDateTime_Time*)o)->data[4] << 8) | \
((PyDateTime_Time*)o)->data[5])
/* Define structure for C API. */
@ -148,7 +148,7 @@ typedef struct {
/* constructors */
PyObject *(*Date_FromDate)(int, int, int, PyTypeObject*);
PyObject *(*DateTime_FromDateAndTime)(int, int, int, int, int, int, int,
PyObject*, PyTypeObject*);
PyObject*, PyTypeObject*);
PyObject *(*Time_FromTime)(int, int, int, int, PyObject*, PyTypeObject*);
PyObject *(*Delta_FromDelta)(int, int, int, int, PyTypeObject*);
@ -185,7 +185,7 @@ typedef struct {
static PyDateTime_CAPI *PyDateTimeAPI = NULL;
#define PyDateTime_IMPORT \
PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0)
PyDateTimeAPI = (PyDateTime_CAPI *)PyCapsule_Import(PyDateTime_CAPSULE_NAME, 0)
/* Macros for type checking when not building the Python core. */
#define PyDate_Check(op) PyObject_TypeCheck(op, PyDateTimeAPI->DateType)
@ -205,30 +205,30 @@ static PyDateTime_CAPI *PyDateTimeAPI = NULL;
/* Macros for accessing constructors in a simplified fashion. */
#define PyDate_FromDate(year, month, day) \
PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType)
PyDateTimeAPI->Date_FromDate(year, month, day, PyDateTimeAPI->DateType)
#define PyDateTime_FromDateAndTime(year, month, day, hour, min, sec, usec) \
PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \
min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType)
PyDateTimeAPI->DateTime_FromDateAndTime(year, month, day, hour, \
min, sec, usec, Py_None, PyDateTimeAPI->DateTimeType)
#define PyTime_FromTime(hour, minute, second, usecond) \
PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \
Py_None, PyDateTimeAPI->TimeType)
PyDateTimeAPI->Time_FromTime(hour, minute, second, usecond, \
Py_None, PyDateTimeAPI->TimeType)
#define PyDelta_FromDSU(days, seconds, useconds) \
PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \
PyDateTimeAPI->DeltaType)
PyDateTimeAPI->Delta_FromDelta(days, seconds, useconds, 1, \
PyDateTimeAPI->DeltaType)
/* Macros supporting the DB API. */
#define PyDateTime_FromTimestamp(args) \
PyDateTimeAPI->DateTime_FromTimestamp( \
(PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL)
PyDateTimeAPI->DateTime_FromTimestamp( \
(PyObject*) (PyDateTimeAPI->DateTimeType), args, NULL)
#define PyDate_FromTimestamp(args) \
PyDateTimeAPI->Date_FromTimestamp( \
(PyObject*) (PyDateTimeAPI->DateType), args)
PyDateTimeAPI->Date_FromTimestamp( \
(PyObject*) (PyDateTimeAPI->DateType), args)
#endif /* Py_BUILD_CORE */
#endif /* Py_BUILD_CORE */
#ifdef __cplusplus
}

View file

@ -9,27 +9,27 @@ typedef PyObject *(*getter)(PyObject *, void *);
typedef int (*setter)(PyObject *, PyObject *, void *);
typedef struct PyGetSetDef {
char *name;
getter get;
setter set;
char *doc;
void *closure;
char *name;
getter get;
setter set;
char *doc;
void *closure;
} PyGetSetDef;
typedef PyObject *(*wrapperfunc)(PyObject *self, PyObject *args,
void *wrapped);
void *wrapped);
typedef PyObject *(*wrapperfunc_kwds)(PyObject *self, PyObject *args,
void *wrapped, PyObject *kwds);
void *wrapped, PyObject *kwds);
struct wrapperbase {
char *name;
int offset;
void *function;
wrapperfunc wrapper;
char *doc;
int flags;
PyObject *name_strobj;
char *name;
int offset;
void *function;
wrapperfunc wrapper;
char *doc;
int flags;
PyObject *name_strobj;
};
/* Flags for above struct */
@ -38,9 +38,9 @@ struct wrapperbase {
/* Various kinds of descriptor objects */
typedef struct {
PyObject_HEAD
PyTypeObject *d_type;
PyObject *d_name;
PyObject_HEAD
PyTypeObject *d_type;
PyObject *d_name;
} PyDescrObject;
#define PyDescr_COMMON PyDescrObject d_common
@ -49,24 +49,24 @@ typedef struct {
#define PyDescr_NAME(x) (((PyDescrObject *)(x))->d_name)
typedef struct {
PyDescr_COMMON;
PyMethodDef *d_method;
PyDescr_COMMON;
PyMethodDef *d_method;
} PyMethodDescrObject;
typedef struct {
PyDescr_COMMON;
struct PyMemberDef *d_member;
PyDescr_COMMON;
struct PyMemberDef *d_member;
} PyMemberDescrObject;
typedef struct {
PyDescr_COMMON;
PyGetSetDef *d_getset;
PyDescr_COMMON;
PyGetSetDef *d_getset;
} PyGetSetDescrObject;
typedef struct {
PyDescr_COMMON;
struct wrapperbase *d_base;
void *d_wrapped; /* This can be any function pointer */
PyDescr_COMMON;
struct wrapperbase *d_base;
void *d_wrapped; /* This can be any function pointer */
} PyWrapperDescrObject;
PyAPI_DATA(PyTypeObject) PyClassMethodDescr_Type;
@ -79,11 +79,11 @@ PyAPI_DATA(PyTypeObject) PyDictProxy_Type;
PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *);
PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *);
PyAPI_FUNC(PyObject *) PyDescr_NewMember(PyTypeObject *,
struct PyMemberDef *);
struct PyMemberDef *);
PyAPI_FUNC(PyObject *) PyDescr_NewGetSet(PyTypeObject *,
struct PyGetSetDef *);
struct PyGetSetDef *);
PyAPI_FUNC(PyObject *) PyDescr_NewWrapper(PyTypeObject *,
struct wrapperbase *, void *);
struct wrapperbase *, void *);
#define PyDescr_IsData(d) (Py_TYPE(d)->tp_descr_set != NULL)
PyAPI_FUNC(PyObject *) PyDictProxy_New(PyObject *);

View file

@ -48,13 +48,13 @@ meaning otherwise.
#define PyDict_MINSIZE 8
typedef struct {
/* Cached hash code of me_key. Note that hash codes are C longs.
* We have to use Py_ssize_t instead because dict_popitem() abuses
* me_hash to hold a search finger.
*/
Py_ssize_t me_hash;
PyObject *me_key;
PyObject *me_value;
/* Cached hash code of me_key. Note that hash codes are C longs.
* We have to use Py_ssize_t instead because dict_popitem() abuses
* me_hash to hold a search finger.
*/
Py_ssize_t me_hash;
PyObject *me_key;
PyObject *me_value;
} PyDictEntry;
/*
@ -68,24 +68,24 @@ it's two-thirds full.
*/
typedef struct _dictobject PyDictObject;
struct _dictobject {
PyObject_HEAD
Py_ssize_t ma_fill; /* # Active + # Dummy */
Py_ssize_t ma_used; /* # Active */
PyObject_HEAD
Py_ssize_t ma_fill; /* # Active + # Dummy */
Py_ssize_t ma_used; /* # Active */
/* The table contains ma_mask + 1 slots, and that's a power of 2.
* We store the mask instead of the size because the mask is more
* frequently needed.
*/
Py_ssize_t ma_mask;
/* The table contains ma_mask + 1 slots, and that's a power of 2.
* We store the mask instead of the size because the mask is more
* frequently needed.
*/
Py_ssize_t ma_mask;
/* ma_table points to ma_smalltable for small tables, else to
* additional malloc'ed memory. ma_table is never NULL! This rule
* saves repeated runtime null-tests in the workhorse getitem and
* setitem calls.
*/
PyDictEntry *ma_table;
PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, long hash);
PyDictEntry ma_smalltable[PyDict_MINSIZE];
/* ma_table points to ma_smalltable for small tables, else to
* additional malloc'ed memory. ma_table is never NULL! This rule
* saves repeated runtime null-tests in the workhorse getitem and
* setitem calls.
*/
PyDictEntry *ma_table;
PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, long hash);
PyDictEntry ma_smalltable[PyDict_MINSIZE];
};
PyAPI_DATA(PyTypeObject) PyDict_Type;
@ -104,7 +104,7 @@ PyAPI_DATA(PyTypeObject) PyDictValues_Type;
#define PyDictValues_Check(op) (Py_TYPE(op) == &PyDictValues_Type)
/* This excludes Values, since they are not sets. */
# define PyDictViewSet_Check(op) \
(PyDictKeys_Check(op) || PyDictItems_Check(op))
(PyDictKeys_Check(op) || PyDictItems_Check(op))
PyAPI_FUNC(PyObject *) PyDict_New(void);
@ -114,9 +114,9 @@ PyAPI_FUNC(int) PyDict_SetItem(PyObject *mp, PyObject *key, PyObject *item);
PyAPI_FUNC(int) PyDict_DelItem(PyObject *mp, PyObject *key);
PyAPI_FUNC(void) PyDict_Clear(PyObject *mp);
PyAPI_FUNC(int) PyDict_Next(
PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value);
PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value);
PyAPI_FUNC(int) _PyDict_Next(
PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash);
PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash);
PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp);
PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp);
PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp);
@ -137,8 +137,8 @@ PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other);
dict.update(other) is equivalent to PyDict_Merge(dict, other, 1).
*/
PyAPI_FUNC(int) PyDict_Merge(PyObject *mp,
PyObject *other,
int override);
PyObject *other,
int override);
/* PyDict_MergeFromSeq2 updates/merges from an iterable object producing
iterable objects of length 2. If override is true, the last occurrence
@ -146,8 +146,8 @@ PyAPI_FUNC(int) PyDict_Merge(PyObject *mp,
is equivalent to dict={}; PyDict_MergeFromSeq(dict, seq2, 1).
*/
PyAPI_FUNC(int) PyDict_MergeFromSeq2(PyObject *d,
PyObject *seq2,
int override);
PyObject *seq2,
int override);
PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key);
PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item);

View file

@ -63,9 +63,9 @@ whose size is determined when the object is allocated.
#ifdef Py_TRACE_REFS
/* Define pointers to support a doubly-linked list of all live heap objects. */
#define _PyObject_HEAD_EXTRA \
struct _object *_ob_next; \
struct _object *_ob_prev;
#define _PyObject_HEAD_EXTRA \
struct _object *_ob_next; \
struct _object *_ob_prev;
#define _PyObject_EXTRA_INIT 0, 0,
@ -75,14 +75,14 @@ whose size is determined when the object is allocated.
#endif
/* PyObject_HEAD defines the initial segment of every PyObject. */
#define PyObject_HEAD PyObject ob_base;
#define PyObject_HEAD PyObject ob_base;
#define PyObject_HEAD_INIT(type) \
{ _PyObject_EXTRA_INIT \
1, type },
#define PyObject_HEAD_INIT(type) \
{ _PyObject_EXTRA_INIT \
1, type },
#define PyVarObject_HEAD_INIT(type, size) \
{ PyObject_HEAD_INIT(type) size },
#define PyVarObject_HEAD_INIT(type, size) \
{ PyObject_HEAD_INIT(type) size },
/* PyObject_VAR_HEAD defines the initial segment of all variable-size
* container objects. These end with a declaration of an array with 1
@ -99,19 +99,19 @@ whose size is determined when the object is allocated.
* in addition, be cast to PyVarObject*.
*/
typedef struct _object {
_PyObject_HEAD_EXTRA
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
_PyObject_HEAD_EXTRA
Py_ssize_t ob_refcnt;
struct _typeobject *ob_type;
} PyObject;
typedef struct {
PyObject ob_base;
Py_ssize_t ob_size; /* Number of items in variable part */
PyObject ob_base;
Py_ssize_t ob_size; /* Number of items in variable part */
} PyVarObject;
#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
/*
Type objects contain a string containing the type name (to help somewhat
@ -142,26 +142,26 @@ typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
/* buffer interface */
typedef struct bufferinfo {
void *buf;
PyObject *obj; /* owned reference */
Py_ssize_t len;
Py_ssize_t itemsize; /* This is Py_ssize_t so it can be
pointed to by strides in simple case.*/
int readonly;
int ndim;
char *format;
Py_ssize_t *shape;
Py_ssize_t *strides;
Py_ssize_t *suboffsets;
Py_ssize_t smalltable[2]; /* static store for shape and strides of
mono-dimensional buffers. */
void *internal;
void *buf;
PyObject *obj; /* owned reference */
Py_ssize_t len;
Py_ssize_t itemsize; /* This is Py_ssize_t so it can be
pointed to by strides in simple case.*/
int readonly;
int ndim;
char *format;
Py_ssize_t *shape;
Py_ssize_t *strides;
Py_ssize_t *suboffsets;
Py_ssize_t smalltable[2]; /* static store for shape and strides of
mono-dimensional buffers. */
void *internal;
} Py_buffer;
typedef int (*getbufferproc)(PyObject *, Py_buffer *, int);
typedef void (*releasebufferproc)(PyObject *, Py_buffer *);
/* Flags for getting buffers */
/* Flags for getting buffers */
#define PyBUF_SIMPLE 0
#define PyBUF_WRITABLE 0x0001
/* we used to include an E, backwards compatible alias */
@ -198,67 +198,67 @@ typedef int (*visitproc)(PyObject *, void *);
typedef int (*traverseproc)(PyObject *, visitproc, void *);
typedef struct {
/* Number implementations must check *both*
arguments for proper type and implement the necessary conversions
in the slot functions themselves. */
/* Number implementations must check *both*
arguments for proper type and implement the necessary conversions
in the slot functions themselves. */
binaryfunc nb_add;
binaryfunc nb_subtract;
binaryfunc nb_multiply;
binaryfunc nb_remainder;
binaryfunc nb_divmod;
ternaryfunc nb_power;
unaryfunc nb_negative;
unaryfunc nb_positive;
unaryfunc nb_absolute;
inquiry nb_bool;
unaryfunc nb_invert;
binaryfunc nb_lshift;
binaryfunc nb_rshift;
binaryfunc nb_and;
binaryfunc nb_xor;
binaryfunc nb_or;
unaryfunc nb_int;
void *nb_reserved; /* the slot formerly known as nb_long */
unaryfunc nb_float;
binaryfunc nb_add;
binaryfunc nb_subtract;
binaryfunc nb_multiply;
binaryfunc nb_remainder;
binaryfunc nb_divmod;
ternaryfunc nb_power;
unaryfunc nb_negative;
unaryfunc nb_positive;
unaryfunc nb_absolute;
inquiry nb_bool;
unaryfunc nb_invert;
binaryfunc nb_lshift;
binaryfunc nb_rshift;
binaryfunc nb_and;
binaryfunc nb_xor;
binaryfunc nb_or;
unaryfunc nb_int;
void *nb_reserved; /* the slot formerly known as nb_long */
unaryfunc nb_float;
binaryfunc nb_inplace_add;
binaryfunc nb_inplace_subtract;
binaryfunc nb_inplace_multiply;
binaryfunc nb_inplace_remainder;
ternaryfunc nb_inplace_power;
binaryfunc nb_inplace_lshift;
binaryfunc nb_inplace_rshift;
binaryfunc nb_inplace_and;
binaryfunc nb_inplace_xor;
binaryfunc nb_inplace_or;
binaryfunc nb_inplace_add;
binaryfunc nb_inplace_subtract;
binaryfunc nb_inplace_multiply;
binaryfunc nb_inplace_remainder;
ternaryfunc nb_inplace_power;
binaryfunc nb_inplace_lshift;
binaryfunc nb_inplace_rshift;
binaryfunc nb_inplace_and;
binaryfunc nb_inplace_xor;
binaryfunc nb_inplace_or;
binaryfunc nb_floor_divide;
binaryfunc nb_true_divide;
binaryfunc nb_inplace_floor_divide;
binaryfunc nb_inplace_true_divide;
binaryfunc nb_floor_divide;
binaryfunc nb_true_divide;
binaryfunc nb_inplace_floor_divide;
binaryfunc nb_inplace_true_divide;
unaryfunc nb_index;
unaryfunc nb_index;
} PyNumberMethods;
typedef struct {
lenfunc sq_length;
binaryfunc sq_concat;
ssizeargfunc sq_repeat;
ssizeargfunc sq_item;
void *was_sq_slice;
ssizeobjargproc sq_ass_item;
void *was_sq_ass_slice;
objobjproc sq_contains;
lenfunc sq_length;
binaryfunc sq_concat;
ssizeargfunc sq_repeat;
ssizeargfunc sq_item;
void *was_sq_slice;
ssizeobjargproc sq_ass_item;
void *was_sq_ass_slice;
objobjproc sq_contains;
binaryfunc sq_inplace_concat;
ssizeargfunc sq_inplace_repeat;
binaryfunc sq_inplace_concat;
ssizeargfunc sq_inplace_repeat;
} PySequenceMethods;
typedef struct {
lenfunc mp_length;
binaryfunc mp_subscript;
objobjargproc mp_ass_subscript;
lenfunc mp_length;
binaryfunc mp_subscript;
objobjargproc mp_ass_subscript;
} PyMappingMethods;
@ -286,109 +286,109 @@ typedef PyObject *(*newfunc)(struct _typeobject *, PyObject *, PyObject *);
typedef PyObject *(*allocfunc)(struct _typeobject *, Py_ssize_t);
typedef struct _typeobject {
PyObject_VAR_HEAD
const char *tp_name; /* For printing, in format "<module>.<name>" */
Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
PyObject_VAR_HEAD
const char *tp_name; /* For printing, in format "<module>.<name>" */
Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
/* Methods to implement standard operations */
/* Methods to implement standard operations */
destructor tp_dealloc;
printfunc tp_print;
getattrfunc tp_getattr;
setattrfunc tp_setattr;
void *tp_reserved; /* formerly known as tp_compare */
reprfunc tp_repr;
destructor tp_dealloc;
printfunc tp_print;
getattrfunc tp_getattr;
setattrfunc tp_setattr;
void *tp_reserved; /* formerly known as tp_compare */
reprfunc tp_repr;
/* Method suites for standard classes */
/* Method suites for standard classes */
PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;
PyNumberMethods *tp_as_number;
PySequenceMethods *tp_as_sequence;
PyMappingMethods *tp_as_mapping;
/* More standard operations (here for binary compatibility) */
/* More standard operations (here for binary compatibility) */
hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;
hashfunc tp_hash;
ternaryfunc tp_call;
reprfunc tp_str;
getattrofunc tp_getattro;
setattrofunc tp_setattro;
/* Functions to access object as input/output buffer */
PyBufferProcs *tp_as_buffer;
/* Functions to access object as input/output buffer */
PyBufferProcs *tp_as_buffer;
/* Flags to define presence of optional/expanded features */
long tp_flags;
/* Flags to define presence of optional/expanded features */
long tp_flags;
const char *tp_doc; /* Documentation string */
const char *tp_doc; /* Documentation string */
/* Assigned meaning in release 2.0 */
/* call function for all accessible objects */
traverseproc tp_traverse;
/* Assigned meaning in release 2.0 */
/* call function for all accessible objects */
traverseproc tp_traverse;
/* delete references to contained objects */
inquiry tp_clear;
/* delete references to contained objects */
inquiry tp_clear;
/* Assigned meaning in release 2.1 */
/* rich comparisons */
richcmpfunc tp_richcompare;
/* Assigned meaning in release 2.1 */
/* rich comparisons */
richcmpfunc tp_richcompare;
/* weak reference enabler */
Py_ssize_t tp_weaklistoffset;
/* weak reference enabler */
Py_ssize_t tp_weaklistoffset;
/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
/* Iterators */
getiterfunc tp_iter;
iternextfunc tp_iternext;
/* Attribute descriptor and subclassing stuff */
struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
struct _typeobject *tp_base;
PyObject *tp_dict;
descrgetfunc tp_descr_get;
descrsetfunc tp_descr_set;
Py_ssize_t tp_dictoffset;
initproc tp_init;
allocfunc tp_alloc;
newfunc tp_new;
freefunc tp_free; /* Low-level free-memory routine */
inquiry tp_is_gc; /* For PyObject_IS_GC */
PyObject *tp_bases;
PyObject *tp_mro; /* method resolution order */
PyObject *tp_cache;
PyObject *tp_subclasses;
PyObject *tp_weaklist;
destructor tp_del;
/* Attribute descriptor and subclassing stuff */
struct PyMethodDef *tp_methods;
struct PyMemberDef *tp_members;
struct PyGetSetDef *tp_getset;
struct _typeobject *tp_base;
PyObject *tp_dict;
descrgetfunc tp_descr_get;
descrsetfunc tp_descr_set;
Py_ssize_t tp_dictoffset;
initproc tp_init;
allocfunc tp_alloc;
newfunc tp_new;
freefunc tp_free; /* Low-level free-memory routine */
inquiry tp_is_gc; /* For PyObject_IS_GC */
PyObject *tp_bases;
PyObject *tp_mro; /* method resolution order */
PyObject *tp_cache;
PyObject *tp_subclasses;
PyObject *tp_weaklist;
destructor tp_del;
/* Type attribute cache version tag. Added in version 2.6 */
unsigned int tp_version_tag;
/* Type attribute cache version tag. Added in version 2.6 */
unsigned int tp_version_tag;
#ifdef COUNT_ALLOCS
/* these must be last and never explicitly initialized */
Py_ssize_t tp_allocs;
Py_ssize_t tp_frees;
Py_ssize_t tp_maxalloc;
struct _typeobject *tp_prev;
struct _typeobject *tp_next;
/* these must be last and never explicitly initialized */
Py_ssize_t tp_allocs;
Py_ssize_t tp_frees;
Py_ssize_t tp_maxalloc;
struct _typeobject *tp_prev;
struct _typeobject *tp_next;
#endif
} PyTypeObject;
/* The *real* layout of a type object when allocated on the heap */
typedef struct _heaptypeobject {
/* Note: there's a dependency on the order of these members
in slotptr() in typeobject.c . */
PyTypeObject ht_type;
PyNumberMethods as_number;
PyMappingMethods as_mapping;
PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
so that the mapping wins when both
the mapping and the sequence define
a given operator (e.g. __getitem__).
see add_operators() in typeobject.c . */
PyBufferProcs as_buffer;
PyObject *ht_name, *ht_slots;
/* here are optional user slots, followed by the members. */
/* Note: there's a dependency on the order of these members
in slotptr() in typeobject.c . */
PyTypeObject ht_type;
PyNumberMethods as_number;
PyMappingMethods as_mapping;
PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
so that the mapping wins when both
the mapping and the sequence define
a given operator (e.g. __getitem__).
see add_operators() in typeobject.c . */
PyBufferProcs as_buffer;
PyObject *ht_name, *ht_slots;
/* here are optional user slots, followed by the members. */
} PyHeapTypeObject;
/* access macro to the members which are floating "behind" the object */
@ -399,20 +399,20 @@ typedef struct _heaptypeobject {
/* Generic type check */
PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
#define PyObject_TypeCheck(ob, tp) \
(Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp)))
(Py_TYPE(ob) == (tp) || PyType_IsSubtype(Py_TYPE(ob), (tp)))
PyAPI_DATA(PyTypeObject) PyType_Type; /* built-in 'type' */
PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
#define PyType_Check(op) \
PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS)
PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS)
#define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type)
PyAPI_FUNC(int) PyType_Ready(PyTypeObject *);
PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
PyObject *, PyObject *);
PyObject *, PyObject *);
PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *);
PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, char *, PyObject **);
PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
@ -439,7 +439,7 @@ PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *);
PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *,
PyObject *, PyObject *);
PyObject *, PyObject *);
PyAPI_FUNC(long) PyObject_Hash(PyObject *);
PyAPI_FUNC(long) PyObject_HashNotImplemented(PyObject *);
PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);
@ -469,7 +469,7 @@ PyAPI_FUNC(long) _Py_HashPointer(void*);
#define PyObject_REPR(obj) _PyUnicode_AsString(PyObject_Repr(obj))
/* Flag bits for printing: */
#define Py_PRINT_RAW 1 /* No string quotes etc. */
#define Py_PRINT_RAW 1 /* No string quotes etc. */
/*
`Type flags (tp_flags)
@ -524,20 +524,20 @@ given type object has a specified feature.
#define Py_TPFLAGS_IS_ABSTRACT (1L<<20)
/* These flags are used to determine if a type is a subclass. */
#define Py_TPFLAGS_INT_SUBCLASS (1L<<23)
#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24)
#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25)
#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26)
#define Py_TPFLAGS_BYTES_SUBCLASS (1L<<27)
#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28)
#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29)
#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30)
#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31)
#define Py_TPFLAGS_INT_SUBCLASS (1L<<23)
#define Py_TPFLAGS_LONG_SUBCLASS (1L<<24)
#define Py_TPFLAGS_LIST_SUBCLASS (1L<<25)
#define Py_TPFLAGS_TUPLE_SUBCLASS (1L<<26)
#define Py_TPFLAGS_BYTES_SUBCLASS (1L<<27)
#define Py_TPFLAGS_UNICODE_SUBCLASS (1L<<28)
#define Py_TPFLAGS_DICT_SUBCLASS (1L<<29)
#define Py_TPFLAGS_BASE_EXC_SUBCLASS (1L<<30)
#define Py_TPFLAGS_TYPE_SUBCLASS (1L<<31)
#define Py_TPFLAGS_DEFAULT ( \
Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
Py_TPFLAGS_HAVE_VERSION_TAG | \
0)
Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \
Py_TPFLAGS_HAVE_VERSION_TAG | \
0)
#define PyType_HasFeature(t,f) (((t)->tp_flags & (f)) != 0)
#define PyType_FastSubclass(t,f) PyType_HasFeature(t,f)
@ -589,32 +589,32 @@ environment the global variable trick is not safe.)
#ifdef Py_REF_DEBUG
PyAPI_DATA(Py_ssize_t) _Py_RefTotal;
PyAPI_FUNC(void) _Py_NegativeRefcount(const char *fname,
int lineno, PyObject *op);
int lineno, PyObject *op);
PyAPI_FUNC(PyObject *) _PyDict_Dummy(void);
PyAPI_FUNC(PyObject *) _PySet_Dummy(void);
PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void);
#define _Py_INC_REFTOTAL _Py_RefTotal++
#define _Py_DEC_REFTOTAL _Py_RefTotal--
#define _Py_REF_DEBUG_COMMA ,
#define _Py_CHECK_REFCNT(OP) \
{ if (((PyObject*)OP)->ob_refcnt < 0) \
_Py_NegativeRefcount(__FILE__, __LINE__, \
(PyObject *)(OP)); \
#define _Py_INC_REFTOTAL _Py_RefTotal++
#define _Py_DEC_REFTOTAL _Py_RefTotal--
#define _Py_REF_DEBUG_COMMA ,
#define _Py_CHECK_REFCNT(OP) \
{ if (((PyObject*)OP)->ob_refcnt < 0) \
_Py_NegativeRefcount(__FILE__, __LINE__, \
(PyObject *)(OP)); \
}
#else
#define _Py_INC_REFTOTAL
#define _Py_DEC_REFTOTAL
#define _Py_REF_DEBUG_COMMA
#define _Py_CHECK_REFCNT(OP) /* a semicolon */;
#define _Py_CHECK_REFCNT(OP) /* a semicolon */;
#endif /* Py_REF_DEBUG */
#ifdef COUNT_ALLOCS
PyAPI_FUNC(void) inc_count(PyTypeObject *);
PyAPI_FUNC(void) dec_count(PyTypeObject *);
#define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP))
#define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP))
#define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees--
#define _Py_COUNT_ALLOCS_COMMA ,
#define _Py_INC_TPALLOCS(OP) inc_count(Py_TYPE(OP))
#define _Py_INC_TPFREES(OP) dec_count(Py_TYPE(OP))
#define _Py_DEC_TPFREES(OP) Py_TYPE(OP)->tp_frees--
#define _Py_COUNT_ALLOCS_COMMA ,
#else
#define _Py_INC_TPALLOCS(OP)
#define _Py_INC_TPFREES(OP)
@ -635,30 +635,30 @@ PyAPI_FUNC(void) _Py_AddToAllObjects(PyObject *, int force);
/* Without Py_TRACE_REFS, there's little enough to do that we expand code
* inline.
*/
#define _Py_NewReference(op) ( \
_Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \
_Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
Py_REFCNT(op) = 1)
#define _Py_NewReference(op) ( \
_Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \
_Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
Py_REFCNT(op) = 1)
#define _Py_ForgetReference(op) _Py_INC_TPFREES(op)
#define _Py_Dealloc(op) ( \
_Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \
(*Py_TYPE(op)->tp_dealloc)((PyObject *)(op)))
#define _Py_Dealloc(op) ( \
_Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA \
(*Py_TYPE(op)->tp_dealloc)((PyObject *)(op)))
#endif /* !Py_TRACE_REFS */
#define Py_INCREF(op) ( \
_Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
((PyObject*)(op))->ob_refcnt++)
#define Py_INCREF(op) ( \
_Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
((PyObject*)(op))->ob_refcnt++)
#define Py_DECREF(op) \
do { \
if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \
--((PyObject*)(op))->ob_refcnt != 0) \
_Py_CHECK_REFCNT(op) \
else \
_Py_Dealloc((PyObject *)(op)); \
} while (0)
#define Py_DECREF(op) \
do { \
if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \
--((PyObject*)(op))->ob_refcnt != 0) \
_Py_CHECK_REFCNT(op) \
else \
_Py_Dealloc((PyObject *)(op)); \
} while (0)
/* Safely decref `op` and set `op` to NULL, especially useful in tp_clear
* and tp_dealloc implementatons.
@ -694,14 +694,14 @@ PyAPI_FUNC(void) _Py_AddToAllObjects(PyObject *, int force);
* Python integers aren't currently weakly referencable. Best practice is
* to use Py_CLEAR() even if you can't think of a reason for why you need to.
*/
#define Py_CLEAR(op) \
do { \
if (op) { \
PyObject *_py_tmp = (PyObject *)(op); \
(op) = NULL; \
Py_DECREF(_py_tmp); \
} \
} while (0)
#define Py_CLEAR(op) \
do { \
if (op) { \
PyObject *_py_tmp = (PyObject *)(op); \
(op) = NULL; \
Py_DECREF(_py_tmp); \
} \
} while (0)
/* Macros to use in case the object pointer may be NULL: */
#define Py_XINCREF(op) do { if ((op) == NULL) ; else Py_INCREF(op); } while (0)
@ -813,13 +813,13 @@ bracketing the body of its tp_dealloc function with a pair of macros:
static void
mytype_dealloc(mytype *p)
{
... declarations go here ...
... declarations go here ...
PyObject_GC_UnTrack(p); // must untrack first
Py_TRASHCAN_SAFE_BEGIN(p)
... The body of the deallocator goes here, including all calls ...
... to Py_DECREF on contained objects. ...
Py_TRASHCAN_SAFE_END(p)
PyObject_GC_UnTrack(p); // must untrack first
Py_TRASHCAN_SAFE_BEGIN(p)
... The body of the deallocator goes here, including all calls ...
... to Py_DECREF on contained objects. ...
Py_TRASHCAN_SAFE_END(p)
}
CAUTION: Never return from the middle of the body! If the body needs to
@ -849,16 +849,16 @@ PyAPI_DATA(PyObject *) _PyTrash_delete_later;
#define PyTrash_UNWIND_LEVEL 50
#define Py_TRASHCAN_SAFE_BEGIN(op) \
if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \
++_PyTrash_delete_nesting;
/* The body of the deallocator is here. */
if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \
++_PyTrash_delete_nesting;
/* The body of the deallocator is here. */
#define Py_TRASHCAN_SAFE_END(op) \
--_PyTrash_delete_nesting; \
if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \
_PyTrash_destroy_chain(); \
} \
else \
_PyTrash_deposit_object((PyObject*)op);
--_PyTrash_delete_nesting; \
if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \
_PyTrash_destroy_chain(); \
} \
else \
_PyTrash_deposit_object((PyObject*)op);
#ifdef __cplusplus
}

View file

@ -101,7 +101,7 @@ PyAPI_FUNC(void) PyObject_Free(void *);
/* Macros */
#ifdef WITH_PYMALLOC
#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */
#ifdef PYMALLOC_DEBUG /* WITH_PYMALLOC && PYMALLOC_DEBUG */
PyAPI_FUNC(void *) _PyObject_DebugMalloc(size_t nbytes);
PyAPI_FUNC(void *) _PyObject_DebugRealloc(void *p, size_t nbytes);
PyAPI_FUNC(void) _PyObject_DebugFree(void *p);
@ -115,28 +115,28 @@ PyAPI_FUNC(void) _PyObject_DebugCheckAddressApi(char api, const void *p);
PyAPI_FUNC(void *) _PyMem_DebugMalloc(size_t nbytes);
PyAPI_FUNC(void *) _PyMem_DebugRealloc(void *p, size_t nbytes);
PyAPI_FUNC(void) _PyMem_DebugFree(void *p);
#define PyObject_MALLOC _PyObject_DebugMalloc
#define PyObject_Malloc _PyObject_DebugMalloc
#define PyObject_REALLOC _PyObject_DebugRealloc
#define PyObject_Realloc _PyObject_DebugRealloc
#define PyObject_FREE _PyObject_DebugFree
#define PyObject_Free _PyObject_DebugFree
#define PyObject_MALLOC _PyObject_DebugMalloc
#define PyObject_Malloc _PyObject_DebugMalloc
#define PyObject_REALLOC _PyObject_DebugRealloc
#define PyObject_Realloc _PyObject_DebugRealloc
#define PyObject_FREE _PyObject_DebugFree
#define PyObject_Free _PyObject_DebugFree
#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */
#define PyObject_MALLOC PyObject_Malloc
#define PyObject_REALLOC PyObject_Realloc
#define PyObject_FREE PyObject_Free
#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */
#define PyObject_MALLOC PyObject_Malloc
#define PyObject_REALLOC PyObject_Realloc
#define PyObject_FREE PyObject_Free
#endif
#else /* ! WITH_PYMALLOC */
#define PyObject_MALLOC PyMem_MALLOC
#define PyObject_REALLOC PyMem_REALLOC
#define PyObject_FREE PyMem_FREE
#else /* ! WITH_PYMALLOC */
#define PyObject_MALLOC PyMem_MALLOC
#define PyObject_REALLOC PyMem_REALLOC
#define PyObject_FREE PyMem_FREE
#endif /* WITH_PYMALLOC */
#endif /* WITH_PYMALLOC */
#define PyObject_Del PyObject_Free
#define PyObject_DEL PyObject_FREE
#define PyObject_Del PyObject_Free
#define PyObject_DEL PyObject_FREE
/*
* Generic object allocator interface
@ -151,16 +151,16 @@ PyAPI_FUNC(PyObject *) _PyObject_New(PyTypeObject *);
PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
#define PyObject_New(type, typeobj) \
( (type *) _PyObject_New(typeobj) )
( (type *) _PyObject_New(typeobj) )
#define PyObject_NewVar(type, typeobj, n) \
( (type *) _PyObject_NewVar((typeobj), (n)) )
( (type *) _PyObject_NewVar((typeobj), (n)) )
/* Macros trading binary compatibility for speed. See also pymem.h.
Note that these macros expect non-NULL object pointers.*/
#define PyObject_INIT(op, typeobj) \
( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) )
( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) )
#define PyObject_INIT_VAR(op, typeobj, size) \
( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) )
( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) )
#define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize )
@ -178,17 +178,17 @@ PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
# error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2"
#endif
#define _PyObject_VAR_SIZE(typeobj, nitems) \
(size_t) \
( ( (typeobj)->tp_basicsize + \
(nitems)*(typeobj)->tp_itemsize + \
(SIZEOF_VOID_P - 1) \
) & ~(SIZEOF_VOID_P - 1) \
)
#define _PyObject_VAR_SIZE(typeobj, nitems) \
(size_t) \
( ( (typeobj)->tp_basicsize + \
(nitems)*(typeobj)->tp_itemsize + \
(SIZEOF_VOID_P - 1) \
) & ~(SIZEOF_VOID_P - 1) \
)
#define PyObject_NEW(type, typeobj) \
( (type *) PyObject_Init( \
(PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) )
(PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) )
#define PyObject_NEW_VAR(type, typeobj, n) \
( (type *) PyObject_InitVar( \
@ -200,7 +200,7 @@ PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
distinction between two steps (at least):
1) the actual allocation of the object storage;
2) the initialization of the Python specific fields
in this storage with PyObject_{Init, InitVar}.
in this storage with PyObject_{Init, InitVar}.
PyObject *
YourObject_New(...)
@ -209,7 +209,7 @@ PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct));
if (op == NULL)
return PyErr_NoMemory();
return PyErr_NoMemory();
PyObject_Init(op, &YourTypeStruct);
@ -236,44 +236,44 @@ PyAPI_FUNC(Py_ssize_t) PyGC_Collect(void);
/* Test if an object has a GC head */
#define PyObject_IS_GC(o) (PyType_IS_GC(Py_TYPE(o)) && \
(Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o)))
(Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o)))
PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t);
#define PyObject_GC_Resize(type, op, n) \
( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) )
( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) )
/* for source compatibility with 2.2 */
#define _PyObject_GC_Del PyObject_GC_Del
/* GC information is stored BEFORE the object structure. */
typedef union _gc_head {
struct {
union _gc_head *gc_next;
union _gc_head *gc_prev;
Py_ssize_t gc_refs;
} gc;
long double dummy; /* force worst-case alignment */
struct {
union _gc_head *gc_next;
union _gc_head *gc_prev;
Py_ssize_t gc_refs;
} gc;
long double dummy; /* force worst-case alignment */
} PyGC_Head;
extern PyGC_Head *_PyGC_generation0;
#define _Py_AS_GC(o) ((PyGC_Head *)(o)-1)
#define _PyGC_REFS_UNTRACKED (-2)
#define _PyGC_REFS_REACHABLE (-3)
#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4)
#define _PyGC_REFS_UNTRACKED (-2)
#define _PyGC_REFS_REACHABLE (-3)
#define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4)
/* Tell the GC to track this object. NB: While the object is tracked the
* collector it must be safe to call the ob_traverse method. */
#define _PyObject_GC_TRACK(o) do { \
PyGC_Head *g = _Py_AS_GC(o); \
if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \
Py_FatalError("GC object already tracked"); \
g->gc.gc_refs = _PyGC_REFS_REACHABLE; \
g->gc.gc_next = _PyGC_generation0; \
g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \
g->gc.gc_prev->gc.gc_next = g; \
_PyGC_generation0->gc.gc_prev = g; \
PyGC_Head *g = _Py_AS_GC(o); \
if (g->gc.gc_refs != _PyGC_REFS_UNTRACKED) \
Py_FatalError("GC object already tracked"); \
g->gc.gc_refs = _PyGC_REFS_REACHABLE; \
g->gc.gc_next = _PyGC_generation0; \
g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \
g->gc.gc_prev->gc.gc_next = g; \
_PyGC_generation0->gc.gc_prev = g; \
} while (0);
/* Tell the GC to stop tracking this object.
@ -281,23 +281,23 @@ extern PyGC_Head *_PyGC_generation0;
* way to provoke memory errors if calling code is confused.
*/
#define _PyObject_GC_UNTRACK(o) do { \
PyGC_Head *g = _Py_AS_GC(o); \
assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \
g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \
g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \
g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \
g->gc.gc_next = NULL; \
PyGC_Head *g = _Py_AS_GC(o); \
assert(g->gc.gc_refs != _PyGC_REFS_UNTRACKED); \
g->gc.gc_refs = _PyGC_REFS_UNTRACKED; \
g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \
g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \
g->gc.gc_next = NULL; \
} while (0);
/* True if the object is currently tracked by the GC. */
#define _PyObject_GC_IS_TRACKED(o) \
((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED)
((_Py_AS_GC(o))->gc.gc_refs != _PyGC_REFS_UNTRACKED)
/* True if the object may be tracked by the GC in the future, or already is.
This can be useful to implement some optimizations. */
#define _PyObject_GC_MAY_BE_TRACKED(obj) \
(PyObject_IS_GC(obj) && \
(!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj)))
(PyObject_IS_GC(obj) && \
(!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj)))
PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t);
@ -308,9 +308,9 @@ PyAPI_FUNC(void) PyObject_GC_UnTrack(void *);
PyAPI_FUNC(void) PyObject_GC_Del(void *);
#define PyObject_GC_New(type, typeobj) \
( (type *) _PyObject_GC_New(typeobj) )
( (type *) _PyObject_GC_New(typeobj) )
#define PyObject_GC_NewVar(type, typeobj, n) \
( (type *) _PyObject_GC_NewVar((typeobj), (n)) )
( (type *) _PyObject_GC_NewVar((typeobj), (n)) )
/* Utility macro to help write tp_traverse functions.
@ -318,14 +318,14 @@ PyAPI_FUNC(void) PyObject_GC_Del(void *);
* "visit" and "arg". This is intended to keep tp_traverse functions
* looking as much alike as possible.
*/
#define Py_VISIT(op) \
do { \
if (op) { \
int vret = visit((PyObject *)(op), arg); \
if (vret) \
return vret; \
} \
} while (0)
#define Py_VISIT(op) \
do { \
if (op) { \
int vret = visit((PyObject *)(op), arg); \
if (vret) \
return vret; \
} \
} while (0)
/* This is here for the sake of backwards compatibility. Extensions that
* use the old GC API will still compile but the objects will not be
@ -341,7 +341,7 @@ PyAPI_FUNC(void) PyObject_GC_Del(void *);
#define PyType_SUPPORTS_WEAKREFS(t) ((t)->tp_weaklistoffset > 0)
#define PyObject_GET_WEAKREFS_LISTPTR(o) \
((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset))
((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset))
#ifdef __cplusplus
}

View file

@ -8,8 +8,8 @@ extern "C" {
/* PyException_HEAD defines the initial segment of every exception class. */
#define PyException_HEAD PyObject_HEAD PyObject *dict;\
PyObject *args; PyObject *traceback;\
PyObject *context; PyObject *cause;
PyObject *args; PyObject *traceback;\
PyObject *context; PyObject *cause;
typedef struct {
PyException_HEAD
@ -92,15 +92,15 @@ PyAPI_FUNC(void) PyException_SetContext(PyObject *, PyObject *);
/* */
#define PyExceptionClass_Check(x) \
(PyType_Check((x)) && \
PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS))
#define PyExceptionClass_Check(x) \
(PyType_Check((x)) && \
PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS))
#define PyExceptionInstance_Check(x) \
PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS)
#define PyExceptionInstance_Check(x) \
PyType_FastSubclass((x)->ob_type, Py_TPFLAGS_BASE_EXC_SUBCLASS)
#define PyExceptionClass_Name(x) \
((char *)(((PyTypeObject*)(x))->tp_name))
((char *)(((PyTypeObject*)(x))->tp_name))
#define PyExceptionInstance_Class(x) ((PyObject*)((x)->ob_type))
@ -175,30 +175,30 @@ PyAPI_FUNC(int) PyErr_BadArgument(void);
PyAPI_FUNC(PyObject *) PyErr_NoMemory(void);
PyAPI_FUNC(PyObject *) PyErr_SetFromErrno(PyObject *);
PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilenameObject(
PyObject *, PyObject *);
PyObject *, PyObject *);
PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithFilename(
PyObject *, const char *);
PyObject *, const char *);
#ifdef MS_WINDOWS
PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithUnicodeFilename(
PyObject *, const Py_UNICODE *);
PyObject *, const Py_UNICODE *);
#endif /* MS_WINDOWS */
PyAPI_FUNC(PyObject *) PyErr_Format(PyObject *, const char *, ...);
#ifdef MS_WINDOWS
PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilenameObject(
int, const char *);
int, const char *);
PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename(
int, const char *);
int, const char *);
PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithUnicodeFilename(
int, const Py_UNICODE *);
int, const Py_UNICODE *);
PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErr(int);
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObject(
PyObject *,int, PyObject *);
PyObject *,int, PyObject *);
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilename(
PyObject *,int, const char *);
PyObject *,int, const char *);
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithUnicodeFilename(
PyObject *,int, const Py_UNICODE *);
PyObject *,int, const Py_UNICODE *);
PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int);
#endif /* MS_WINDOWS */
@ -211,9 +211,9 @@ PyAPI_FUNC(void) _PyErr_BadInternalCall(const char *filename, int lineno);
/* Function to create a new exception */
PyAPI_FUNC(PyObject *) PyErr_NewException(
const char *name, PyObject *base, PyObject *dict);
const char *name, PyObject *base, PyObject *dict);
PyAPI_FUNC(PyObject *) PyErr_NewExceptionWithDoc(
const char *name, const char *doc, PyObject *base, PyObject *dict);
const char *name, const char *doc, PyObject *base, PyObject *dict);
PyAPI_FUNC(void) PyErr_WriteUnraisable(PyObject *);
/* In sigcheck.c or signalmodule.c */
@ -232,15 +232,15 @@ PyAPI_FUNC(PyObject *) PyErr_ProgramText(const char *, int);
/* create a UnicodeDecodeError object */
PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_Create(
const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
/* create a UnicodeEncodeError object */
PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_Create(
const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
/* create a UnicodeTranslateError object */
PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_Create(
const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
/* get the encoding attribute */
PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetEncoding(PyObject *);
@ -283,11 +283,11 @@ PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_GetReason(PyObject *);
/* assign a new value to the reason attribute
return 0 on success, -1 on failure */
PyAPI_FUNC(int) PyUnicodeEncodeError_SetReason(
PyObject *, const char *);
PyObject *, const char *);
PyAPI_FUNC(int) PyUnicodeDecodeError_SetReason(
PyObject *, const char *);
PyObject *, const char *);
PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason(
PyObject *, const char *);
PyObject *, const char *);
/* These APIs aren't really part of the error implementation, but
@ -306,9 +306,9 @@ PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason(
#include <stdarg.h>
PyAPI_FUNC(int) PyOS_snprintf(char *str, size_t size, const char *format, ...)
Py_GCC_ATTRIBUTE((format(printf, 3, 4)));
Py_GCC_ATTRIBUTE((format(printf, 3, 4)));
PyAPI_FUNC(int) PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
Py_GCC_ATTRIBUTE((format(printf, 3, 0)));
Py_GCC_ATTRIBUTE((format(printf, 3, 0)));
#ifdef __cplusplus
}

View file

@ -4,7 +4,7 @@
* This file moves some of the autoconf magic to compile-time
* when building on MacOSX. This is needed for building 4-way
* universal binaries and for 64-bit universal binaries because
* the values redefined below aren't configure-time constant but
* the values redefined below aren't configure-time constant but
* only compile-time constant in these scenarios.
*/
@ -36,40 +36,40 @@
# undef SIZEOF_LONG
# ifdef __LP64__
# define SIZEOF__BOOL 1
# define SIZEOF__BOOL 1
# define SIZEOF_LONG 8
# define SIZEOF_PTHREAD_T 8
# define SIZEOF_SIZE_T 8
# define SIZEOF_TIME_T 8
# define SIZEOF_VOID_P 8
# define SIZEOF_UINTPTR_T 8
# define SIZEOF_PTHREAD_T 8
# define SIZEOF__BOOL 1
# define SIZEOF__BOOL 1
# define SIZEOF_LONG 8
# define SIZEOF_PTHREAD_T 8
# define SIZEOF_SIZE_T 8
# define SIZEOF_TIME_T 8
# define SIZEOF_VOID_P 8
# define SIZEOF_UINTPTR_T 8
# define SIZEOF_PTHREAD_T 8
# else
# ifdef __ppc__
# define SIZEOF__BOOL 4
# define SIZEOF__BOOL 4
# else
# define SIZEOF__BOOL 1
# define SIZEOF__BOOL 1
# endif
# define SIZEOF_LONG 4
# define SIZEOF_PTHREAD_T 4
# define SIZEOF_SIZE_T 4
# define SIZEOF_TIME_T 4
# define SIZEOF_VOID_P 4
# define SIZEOF_UINTPTR_T 4
# define SIZEOF_PTHREAD_T 4
# define SIZEOF_LONG 4
# define SIZEOF_PTHREAD_T 4
# define SIZEOF_SIZE_T 4
# define SIZEOF_TIME_T 4
# define SIZEOF_VOID_P 4
# define SIZEOF_UINTPTR_T 4
# define SIZEOF_PTHREAD_T 4
# endif
# if defined(__LP64__)
/* MacOSX 10.4 (the first release to suppport 64-bit code
* at all) only supports 64-bit in the UNIX layer.
* Therefore surpress the toolbox-glue in 64-bit mode.
*/
/* MacOSX 10.4 (the first release to suppport 64-bit code
* at all) only supports 64-bit in the UNIX layer.
* Therefore surpress the toolbox-glue in 64-bit mode.
*/
/* In 64-bit mode setpgrp always has no argments, in 32-bit
* mode that depends on the compilation environment
*/
# undef SETPGRP_HAVE_ARG
/* In 64-bit mode setpgrp always has no argments, in 32-bit
* mode that depends on the compilation environment
*/
# undef SETPGRP_HAVE_ARG
# endif
@ -84,17 +84,17 @@
# define HAVE_GCC_ASM_FOR_X87
#endif
/*
* The definition in pyconfig.h is only valid on the OS release
* where configure ran on and not necessarily for all systems where
* the executable can be used on.
*
* Specifically: OSX 10.4 has limited supported for '%zd', while
* 10.5 has full support for '%zd'. A binary built on 10.5 won't
* work properly on 10.4 unless we surpress the definition
* of PY_FORMAT_SIZE_T
*/
#undef PY_FORMAT_SIZE_T
/*
* The definition in pyconfig.h is only valid on the OS release
* where configure ran on and not necessarily for all systems where
* the executable can be used on.
*
* Specifically: OSX 10.4 has limited supported for '%zd', while
* 10.5 has full support for '%zd'. A binary built on 10.5 won't
* work properly on 10.4 unless we surpress the definition
* of PY_FORMAT_SIZE_T
*/
#undef PY_FORMAT_SIZE_T
#endif /* defined(_APPLE__) */

View file

@ -132,20 +132,20 @@ Used in: PY_LONG_LONG
* integral type.
*/
#ifdef HAVE_UINTPTR_T
typedef uintptr_t Py_uintptr_t;
typedef intptr_t Py_intptr_t;
typedef uintptr_t Py_uintptr_t;
typedef intptr_t Py_intptr_t;
#elif SIZEOF_VOID_P <= SIZEOF_INT
typedef unsigned int Py_uintptr_t;
typedef int Py_intptr_t;
typedef unsigned int Py_uintptr_t;
typedef int Py_intptr_t;
#elif SIZEOF_VOID_P <= SIZEOF_LONG
typedef unsigned long Py_uintptr_t;
typedef long Py_intptr_t;
typedef unsigned long Py_uintptr_t;
typedef long Py_intptr_t;
#elif defined(HAVE_LONG_LONG) && (SIZEOF_VOID_P <= SIZEOF_LONG_LONG)
typedef unsigned PY_LONG_LONG Py_uintptr_t;
typedef PY_LONG_LONG Py_intptr_t;
typedef unsigned PY_LONG_LONG Py_uintptr_t;
typedef PY_LONG_LONG Py_intptr_t;
#else
# error "Python needs a typedef for Py_uintptr_t in pyport.h."
@ -156,9 +156,9 @@ typedef PY_LONG_LONG Py_intptr_t;
* unsigned integral type). See PEP 353 for details.
*/
#ifdef HAVE_SSIZE_T
typedef ssize_t Py_ssize_t;
typedef ssize_t Py_ssize_t;
#elif SIZEOF_VOID_P == SIZEOF_SIZE_T
typedef Py_intptr_t Py_ssize_t;
typedef Py_intptr_t Py_ssize_t;
#else
# error "Python needs a typedef for Py_ssize_t in pyport.h."
#endif
@ -166,7 +166,7 @@ typedef Py_intptr_t Py_ssize_t;
/* Largest possible value of size_t.
SIZE_MAX is part of C99, so it might be defined on some
platforms. If it is not defined, (size_t)-1 is a portable
definition for C89, due to the way signed->unsigned
definition for C89, due to the way signed->unsigned
conversion is defined. */
#ifdef SIZE_MAX
#define PY_SIZE_MAX SIZE_MAX
@ -259,7 +259,7 @@ typedef Py_intptr_t Py_ssize_t;
/* enable more aggressive optimization for visual studio */
#pragma optimize("agtw", on)
#endif
/* ignore warnings if the compiler decides not to inline a function */
/* ignore warnings if the compiler decides not to inline a function */
#pragma warning(disable: 4710)
/* fastest possible local call under MSVC */
#define Py_LOCAL(type) static type __fastcall
@ -279,16 +279,16 @@ typedef Py_intptr_t Py_ssize_t;
*/
#if defined(_MSC_VER)
#define Py_MEMCPY(target, source, length) do { \
size_t i_, n_ = (length); \
char *t_ = (void*) (target); \
const char *s_ = (void*) (source); \
if (n_ >= 16) \
memcpy(t_, s_, n_); \
else \
for (i_ = 0; i_ < n_; i_++) \
t_[i_] = s_[i_]; \
} while (0)
#define Py_MEMCPY(target, source, length) do { \
size_t i_, n_ = (length); \
char *t_ = (void*) (target); \
const char *s_ = (void*) (source); \
if (n_ >= 16) \
memcpy(t_, s_, n_); \
else \
for (i_ = 0; i_ < n_; i_++) \
t_[i_] = s_[i_]; \
} while (0)
#else
#define Py_MEMCPY memcpy
#endif
@ -403,7 +403,7 @@ extern "C" {
*/
#ifdef SIGNED_RIGHT_SHIFT_ZERO_FILLS
#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) \
((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J))
((I) < 0 ? -1-((-1-(I)) >> (J)) : (I) >> (J))
#else
#define Py_ARITHMETIC_RIGHT_SHIFT(TYPE, I, J) ((I) >> (J))
#endif
@ -423,7 +423,7 @@ extern "C" {
*/
#ifdef Py_DEBUG
#define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) \
(assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE))
(assert((WIDE)(NARROW)(VALUE) == (VALUE)), (NARROW)(VALUE))
#else
#define Py_SAFE_DOWNCAST(VALUE, WIDE, NARROW) (NARROW)(VALUE)
#endif
@ -443,13 +443,13 @@ extern "C" {
#define _Py_SET_EDOM_FOR_NAN(X) ;
#endif
#define Py_SET_ERRNO_ON_MATH_ERROR(X) \
do { \
if (errno == 0) { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
errno = ERANGE; \
else _Py_SET_EDOM_FOR_NAN(X) \
} \
} while(0)
do { \
if (errno == 0) { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
errno = ERANGE; \
else _Py_SET_EDOM_FOR_NAN(X) \
} \
} while(0)
/* Py_SET_ERANGE_ON_OVERFLOW(x)
* An alias of Py_SET_ERRNO_ON_MATH_ERROR for backward-compatibility.
@ -470,26 +470,26 @@ extern "C" {
* This isn't reliable. See Py_OVERFLOWED comments.
* X and Y may be evaluated more than once.
*/
#define Py_ADJUST_ERANGE1(X) \
do { \
if (errno == 0) { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
errno = ERANGE; \
} \
else if (errno == ERANGE && (X) == 0.0) \
errno = 0; \
} while(0)
#define Py_ADJUST_ERANGE1(X) \
do { \
if (errno == 0) { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL) \
errno = ERANGE; \
} \
else if (errno == ERANGE && (X) == 0.0) \
errno = 0; \
} while(0)
#define Py_ADJUST_ERANGE2(X, Y) \
do { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \
(Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \
if (errno == 0) \
errno = ERANGE; \
} \
else if (errno == ERANGE) \
errno = 0; \
} while(0)
#define Py_ADJUST_ERANGE2(X, Y) \
do { \
if ((X) == Py_HUGE_VAL || (X) == -Py_HUGE_VAL || \
(Y) == Py_HUGE_VAL || (Y) == -Py_HUGE_VAL) { \
if (errno == 0) \
errno = ERANGE; \
} \
else if (errno == ERANGE) \
errno = 0; \
} while(0)
/* The functions _Py_dg_strtod and _Py_dg_dtoa in Python/dtoa.c (which are
* required to support the short float repr introduced in Python 3.1) require
@ -518,18 +518,18 @@ extern "C" {
#ifdef HAVE_GCC_ASM_FOR_X87
#define HAVE_PY_SET_53BIT_PRECISION 1
/* _Py_get/set_387controlword functions are defined in Python/pymath.c */
#define _Py_SET_53BIT_PRECISION_HEADER \
unsigned short old_387controlword, new_387controlword
#define _Py_SET_53BIT_PRECISION_START \
do { \
old_387controlword = _Py_get_387controlword(); \
new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \
if (new_387controlword != old_387controlword) \
_Py_set_387controlword(new_387controlword); \
} while (0)
#define _Py_SET_53BIT_PRECISION_END \
if (new_387controlword != old_387controlword) \
_Py_set_387controlword(old_387controlword)
#define _Py_SET_53BIT_PRECISION_HEADER \
unsigned short old_387controlword, new_387controlword
#define _Py_SET_53BIT_PRECISION_START \
do { \
old_387controlword = _Py_get_387controlword(); \
new_387controlword = (old_387controlword & ~0x0f00) | 0x0200; \
if (new_387controlword != old_387controlword) \
_Py_set_387controlword(new_387controlword); \
} while (0)
#define _Py_SET_53BIT_PRECISION_END \
if (new_387controlword != old_387controlword) \
_Py_set_387controlword(old_387controlword)
#endif
/* default definitions are empty */
@ -573,7 +573,7 @@ extern "C" {
* extern int x() Py_DEPRECATED(2.5);
*/
#if defined(__GNUC__) && ((__GNUC__ >= 4) || \
(__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))
(__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))
#define Py_DEPRECATED(VERSION_UNUSED) __attribute__((__deprecated__))
#else
#define Py_DEPRECATED(VERSION_UNUSED)
@ -593,7 +593,7 @@ extern int gethostname(char *, int);
#endif
#ifdef HAVE__GETPTY
#include <sys/types.h> /* we need to import mode_t */
#include <sys/types.h> /* we need to import mode_t */
extern char * _getpty(int *, int, mode_t, int);
#endif
@ -674,54 +674,54 @@ extern pid_t forkpty(int *, char *, struct termios *, struct winsize *);
linkage handling and it uses __declspec().
*/
#if defined(__CYGWIN__)
# define HAVE_DECLSPEC_DLL
# define HAVE_DECLSPEC_DLL
#endif
/* only get special linkage if built as shared or platform is Cygwin */
#if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__)
# if defined(HAVE_DECLSPEC_DLL)
# ifdef Py_BUILD_CORE
# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE
# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE
/* module init functions inside the core need no external linkage */
/* except for Cygwin to handle embedding */
# if defined(__CYGWIN__)
# define PyMODINIT_FUNC __declspec(dllexport) PyObject*
# else /* __CYGWIN__ */
# define PyMODINIT_FUNC PyObject*
# endif /* __CYGWIN__ */
# else /* Py_BUILD_CORE */
/* Building an extension module, or an embedded situation */
/* public Python functions and data are imported */
/* Under Cygwin, auto-import functions to prevent compilation */
/* failures similar to http://python.org/doc/FAQ.html#3.24 */
# if !defined(__CYGWIN__)
# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE
# endif /* !__CYGWIN__ */
# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE
/* module init functions outside the core must be exported */
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" __declspec(dllexport) PyObject*
# else /* __cplusplus */
# define PyMODINIT_FUNC __declspec(dllexport) PyObject*
# endif /* __cplusplus */
# endif /* Py_BUILD_CORE */
# endif /* HAVE_DECLSPEC */
# if defined(HAVE_DECLSPEC_DLL)
# ifdef Py_BUILD_CORE
# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE
# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE
/* module init functions inside the core need no external linkage */
/* except for Cygwin to handle embedding */
# if defined(__CYGWIN__)
# define PyMODINIT_FUNC __declspec(dllexport) PyObject*
# else /* __CYGWIN__ */
# define PyMODINIT_FUNC PyObject*
# endif /* __CYGWIN__ */
# else /* Py_BUILD_CORE */
/* Building an extension module, or an embedded situation */
/* public Python functions and data are imported */
/* Under Cygwin, auto-import functions to prevent compilation */
/* failures similar to http://python.org/doc/FAQ.html#3.24 */
# if !defined(__CYGWIN__)
# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE
# endif /* !__CYGWIN__ */
# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE
/* module init functions outside the core must be exported */
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" __declspec(dllexport) PyObject*
# else /* __cplusplus */
# define PyMODINIT_FUNC __declspec(dllexport) PyObject*
# endif /* __cplusplus */
# endif /* Py_BUILD_CORE */
# endif /* HAVE_DECLSPEC */
#endif /* Py_ENABLE_SHARED */
/* If no external linkage macros defined by now, create defaults */
#ifndef PyAPI_FUNC
# define PyAPI_FUNC(RTYPE) RTYPE
# define PyAPI_FUNC(RTYPE) RTYPE
#endif
#ifndef PyAPI_DATA
# define PyAPI_DATA(RTYPE) extern RTYPE
# define PyAPI_DATA(RTYPE) extern RTYPE
#endif
#ifndef PyMODINIT_FUNC
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" PyObject*
# else /* __cplusplus */
# define PyMODINIT_FUNC PyObject*
# endif /* __cplusplus */
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" PyObject*
# else /* __cplusplus */
# define PyMODINIT_FUNC PyObject*
# endif /* __cplusplus */
#endif
/* limits.h constants that may be missing */

View file

@ -17,7 +17,7 @@ extern "C" {
#define PyCF_IGNORE_COOKIE 0x0800
typedef struct {
int cf_flags; /* bitmask of CO_xxx flags relevant to future */
int cf_flags; /* bitmask of CO_xxx flags relevant to future */
} PyCompilerFlags;
PyAPI_FUNC(void) Py_SetProgramName(wchar_t *);
@ -40,33 +40,33 @@ PyAPI_FUNC(int) PyRun_SimpleFileExFlags(FILE *, const char *, int, PyCompilerFla
PyAPI_FUNC(int) PyRun_InteractiveOneFlags(FILE *, const char *, PyCompilerFlags *);
PyAPI_FUNC(int) PyRun_InteractiveLoopFlags(FILE *, const char *, PyCompilerFlags *);
PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *,
int, PyCompilerFlags *flags,
PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *,
int, PyCompilerFlags *flags,
PyArena *);
PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *,
const char*, int,
char *, char *,
PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *,
const char*, int,
char *, char *,
PyCompilerFlags *, int *,
PyArena *);
#define PyParser_SimpleParseString(S, B) \
PyParser_SimpleParseStringFlags(S, B, 0)
PyParser_SimpleParseStringFlags(S, B, 0)
#define PyParser_SimpleParseFile(FP, S, B) \
PyParser_SimpleParseFileFlags(FP, S, B, 0)
PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int,
int);
PyParser_SimpleParseFileFlags(FP, S, B, 0)
PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int,
int);
PyAPI_FUNC(struct _node *) PyParser_SimpleParseFileFlags(FILE *, const char *,
int, int);
int, int);
PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *,
PyObject *, PyCompilerFlags *);
PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *,
PyObject *, PyCompilerFlags *);
PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int,
PyObject *, PyObject *, int,
PyCompilerFlags *);
PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int,
PyObject *, PyObject *, int,
PyCompilerFlags *);
#define Py_CompileString(str, p, s) Py_CompileStringFlags(str, p, s, NULL)
PyAPI_FUNC(PyObject *) Py_CompileStringFlags(const char *, const char *, int,
PyCompilerFlags *);
PyCompilerFlags *);
PyAPI_FUNC(struct symtable *) Py_SymtableString(const char *, const char *, int);
PyAPI_FUNC(void) PyErr_Print(void);
@ -93,20 +93,20 @@ PyAPI_FUNC(int) Py_Main(int argc, wchar_t **argv);
#define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL)
#define PyRun_AnyFile(fp, name) PyRun_AnyFileExFlags(fp, name, 0, NULL)
#define PyRun_AnyFileEx(fp, name, closeit) \
PyRun_AnyFileExFlags(fp, name, closeit, NULL)
PyRun_AnyFileExFlags(fp, name, closeit, NULL)
#define PyRun_AnyFileFlags(fp, name, flags) \
PyRun_AnyFileExFlags(fp, name, 0, flags)
PyRun_AnyFileExFlags(fp, name, 0, flags)
#define PyRun_SimpleString(s) PyRun_SimpleStringFlags(s, NULL)
#define PyRun_SimpleFile(f, p) PyRun_SimpleFileExFlags(f, p, 0, NULL)
#define PyRun_SimpleFileEx(f, p, c) PyRun_SimpleFileExFlags(f, p, c, NULL)
#define PyRun_InteractiveOne(f, p) PyRun_InteractiveOneFlags(f, p, NULL)
#define PyRun_InteractiveLoop(f, p) PyRun_InteractiveLoopFlags(f, p, NULL)
#define PyRun_File(fp, p, s, g, l) \
PyRun_FileExFlags(fp, p, s, g, l, 0, NULL)
PyRun_FileExFlags(fp, p, s, g, l, 0, NULL)
#define PyRun_FileEx(fp, p, s, g, l, c) \
PyRun_FileExFlags(fp, p, s, g, l, c, NULL)
PyRun_FileExFlags(fp, p, s, g, l, c, NULL)
#define PyRun_FileFlags(fp, p, s, g, l, flags) \
PyRun_FileExFlags(fp, p, s, g, l, 0, flags)
PyRun_FileExFlags(fp, p, s, g, l, 0, flags)
/* In getpath.c */
PyAPI_FUNC(wchar_t *) Py_GetProgramFullPath(void);

View file

@ -22,8 +22,8 @@ no meaning otherwise.
#define PySet_MINSIZE 8
typedef struct {
long hash; /* cached hash code for the entry key */
PyObject *key;
long hash; /* cached hash code for the entry key */
PyObject *key;
} setentry;
@ -33,27 +33,27 @@ This data structure is shared by set and frozenset objects.
typedef struct _setobject PySetObject;
struct _setobject {
PyObject_HEAD
PyObject_HEAD
Py_ssize_t fill; /* # Active + # Dummy */
Py_ssize_t used; /* # Active */
Py_ssize_t fill; /* # Active + # Dummy */
Py_ssize_t used; /* # Active */
/* The table contains mask + 1 slots, and that's a power of 2.
* We store the mask instead of the size because the mask is more
* frequently needed.
*/
Py_ssize_t mask;
/* The table contains mask + 1 slots, and that's a power of 2.
* We store the mask instead of the size because the mask is more
* frequently needed.
*/
Py_ssize_t mask;
/* table points to smalltable for small tables, else to
* additional malloc'ed memory. table is never NULL! This rule
* saves repeated runtime null-tests.
*/
setentry *table;
setentry *(*lookup)(PySetObject *so, PyObject *key, long hash);
setentry smalltable[PySet_MINSIZE];
/* table points to smalltable for small tables, else to
* additional malloc'ed memory. table is never NULL! This rule
* saves repeated runtime null-tests.
*/
setentry *table;
setentry *(*lookup)(PySetObject *so, PyObject *key, long hash);
setentry smalltable[PySet_MINSIZE];
long hash; /* only used by frozenset objects */
PyObject *weakreflist; /* List of weak references */
long hash; /* only used by frozenset objects */
PyObject *weakreflist; /* List of weak references */
};
PyAPI_DATA(PyTypeObject) PySet_Type;
@ -69,17 +69,17 @@ PyAPI_DATA(PyTypeObject) PySetIter_Type;
#define PyFrozenSet_CheckExact(ob) (Py_TYPE(ob) == &PyFrozenSet_Type)
#define PyAnySet_CheckExact(ob) \
(Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type)
(Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type)
#define PyAnySet_Check(ob) \
(Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \
PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
(Py_TYPE(ob) == &PySet_Type || Py_TYPE(ob) == &PyFrozenSet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PySet_Type) || \
PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
#define PySet_Check(ob) \
(Py_TYPE(ob) == &PySet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PySet_Type))
(Py_TYPE(ob) == &PySet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PySet_Type))
#define PyFrozenSet_Check(ob) \
(Py_TYPE(ob) == &PyFrozenSet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
(Py_TYPE(ob) == &PyFrozenSet_Type || \
PyType_IsSubtype(Py_TYPE(ob), &PyFrozenSet_Type))
PyAPI_FUNC(PyObject *) PySet_New(PyObject *);
PyAPI_FUNC(PyObject *) PyFrozenSet_New(PyObject *);

View file

@ -8,35 +8,35 @@ extern "C" {
#endif
typedef struct PyStructSequence_Field {
char *name;
char *doc;
char *name;
char *doc;
} PyStructSequence_Field;
typedef struct PyStructSequence_Desc {
char *name;
char *doc;
struct PyStructSequence_Field *fields;
int n_in_sequence;
char *name;
char *doc;
struct PyStructSequence_Field *fields;
int n_in_sequence;
} PyStructSequence_Desc;
extern char* PyStructSequence_UnnamedField;
PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type,
PyStructSequence_Desc *desc);
PyStructSequence_Desc *desc);
PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type);
typedef struct {
PyObject_VAR_HEAD
PyObject *ob_item[1];
PyObject_VAR_HEAD
PyObject *ob_item[1];
} PyStructSequence;
/* Macro, *only* to be used to fill in brand new objects */
#define PyStructSequence_SET_ITEM(op, i, v) \
(((PyStructSequence *)(op))->ob_item[i] = v)
(((PyStructSequence *)(op))->ob_item[i] = v)
#define PyStructSequence_GET_ITEM(op, i) \
(((PyStructSequence *)(op))->ob_item[i])
(((PyStructSequence *)(op))->ob_item[i])
#ifdef __cplusplus

View file

@ -15,40 +15,40 @@ typedef enum _block_type { FunctionBlock, ClassBlock, ModuleBlock }
struct _symtable_entry;
struct symtable {
const char *st_filename; /* name of file being compiled */
struct _symtable_entry *st_cur; /* current symbol table entry */
struct _symtable_entry *st_top; /* symbol table entry for module */
PyObject *st_blocks; /* dict: map AST node addresses
* to symbol table entries */
PyObject *st_stack; /* list: stack of namespace info */
PyObject *st_global; /* borrowed ref to st_top->st_symbols */
int st_nblocks; /* number of blocks used */
PyObject *st_private; /* name of current class or NULL */
PyFutureFeatures *st_future; /* module's future features */
const char *st_filename; /* name of file being compiled */
struct _symtable_entry *st_cur; /* current symbol table entry */
struct _symtable_entry *st_top; /* symbol table entry for module */
PyObject *st_blocks; /* dict: map AST node addresses
* to symbol table entries */
PyObject *st_stack; /* list: stack of namespace info */
PyObject *st_global; /* borrowed ref to st_top->st_symbols */
int st_nblocks; /* number of blocks used */
PyObject *st_private; /* name of current class or NULL */
PyFutureFeatures *st_future; /* module's future features */
};
typedef struct _symtable_entry {
PyObject_HEAD
PyObject *ste_id; /* int: key in ste_table->st_blocks */
PyObject *ste_symbols; /* dict: variable names to flags */
PyObject *ste_name; /* string: name of current block */
PyObject *ste_varnames; /* list of variable names */
PyObject *ste_children; /* list of child blocks */
_Py_block_ty ste_type; /* module, class, or function */
int ste_unoptimized; /* false if namespace is optimized */
int ste_nested; /* true if block is nested */
unsigned ste_free : 1; /* true if block has free variables */
unsigned ste_child_free : 1; /* true if a child block has free vars,
including free refs to globals */
unsigned ste_generator : 1; /* true if namespace is a generator */
unsigned ste_varargs : 1; /* true if block has varargs */
unsigned ste_varkeywords : 1; /* true if block has varkeywords */
unsigned ste_returns_value : 1; /* true if namespace uses return with
an argument */
int ste_lineno; /* first line of block */
int ste_opt_lineno; /* lineno of last exec or import * */
int ste_tmpname; /* counter for listcomp temp vars */
struct symtable *ste_table;
PyObject_HEAD
PyObject *ste_id; /* int: key in ste_table->st_blocks */
PyObject *ste_symbols; /* dict: variable names to flags */
PyObject *ste_name; /* string: name of current block */
PyObject *ste_varnames; /* list of variable names */
PyObject *ste_children; /* list of child blocks */
_Py_block_ty ste_type; /* module, class, or function */
int ste_unoptimized; /* false if namespace is optimized */
int ste_nested; /* true if block is nested */
unsigned ste_free : 1; /* true if block has free variables */
unsigned ste_child_free : 1; /* true if a child block has free vars,
including free refs to globals */
unsigned ste_generator : 1; /* true if namespace is a generator */
unsigned ste_varargs : 1; /* true if block has varargs */
unsigned ste_varkeywords : 1; /* true if block has varkeywords */
unsigned ste_returns_value : 1; /* true if namespace uses return with
an argument */
int ste_lineno; /* first line of block */
int ste_opt_lineno; /* lineno of last exec or import * */
int ste_tmpname; /* counter for listcomp temp vars */
struct symtable *ste_table;
} PySTEntryObject;
PyAPI_DATA(PyTypeObject) PySTEntry_Type;
@ -57,8 +57,8 @@ PyAPI_DATA(PyTypeObject) PySTEntry_Type;
PyAPI_FUNC(int) PyST_GetScope(PySTEntryObject *, PyObject *);
PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *,
PyFutureFeatures *);
PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *,
PyFutureFeatures *);
PyAPI_FUNC(PySTEntryObject *) PySymtable_Lookup(struct symtable *, void *);
PyAPI_FUNC(void) PySymtable_Free(struct symtable *);
@ -77,7 +77,7 @@ PyAPI_FUNC(void) PySymtable_Free(struct symtable *);
#define DEF_BOUND (DEF_LOCAL | DEF_PARAM | DEF_IMPORT)
/* GLOBAL_EXPLICIT and GLOBAL_IMPLICIT are used internally by the symbol
table. GLOBAL is returned from PyST_GetScope() for either of them.
table. GLOBAL is returned from PyST_GetScope() for either of them.
It is stored in ste_symbols at bits 12-15.
*/
#define SCOPE_OFFSET 11

File diff suppressed because it is too large Load diff

View file

@ -39,8 +39,8 @@ extern char** environ;
* In a regular framework the structure is:
*
* Python.framework/Versions/2.7
* /Python
* /Resources/Python.app/Contents/MacOS/Python
* /Python
* /Resources/Python.app/Contents/MacOS/Python
*
* In a virtualenv style structure the expected
* structure is:
@ -50,121 +50,121 @@ extern char** environ;
* /.Python <- the dylib
* /.Resources/Python.app/Contents/MacOS/Python
*
* NOTE: virtualenv's are not an officially supported
* NOTE: virtualenv's are not an officially supported
* feature, support for that structure is provided as
* a convenience.
*/
static char* get_python_path(void)
{
size_t len;
Dl_info info;
char* end;
char* g_path;
size_t len;
Dl_info info;
char* end;
char* g_path;
if (dladdr(Py_Initialize, &info) == 0) {
return NULL;
}
if (dladdr(Py_Initialize, &info) == 0) {
return NULL;
}
len = strlen(info.dli_fname);
len = strlen(info.dli_fname);
g_path = malloc(len+60);
if (g_path == NULL) {
return NULL;
}
g_path = malloc(len+60);
if (g_path == NULL) {
return NULL;
}
strcpy(g_path, info.dli_fname);
end = g_path + len - 1;
while (end != g_path && *end != '/') {
end --;
}
end++;
if (*end == '.') {
end++;
}
strcpy(end, "Resources/Python.app/Contents/MacOS/" PYTHONFRAMEWORK);
strcpy(g_path, info.dli_fname);
end = g_path + len - 1;
while (end != g_path && *end != '/') {
end --;
}
end++;
if (*end == '.') {
end++;
}
strcpy(end, "Resources/Python.app/Contents/MacOS/" PYTHONFRAMEWORK);
return g_path;
return g_path;
}
#ifdef HAVE_SPAWN_H
static void
setup_spawnattr(posix_spawnattr_t* spawnattr)
{
size_t ocount;
size_t count;
cpu_type_t cpu_types[1];
short flags = 0;
size_t ocount;
size_t count;
cpu_type_t cpu_types[1];
short flags = 0;
#ifdef __LP64__
int ch;
int ch;
#endif
if ((errno = posix_spawnattr_init(spawnattr)) != 0) {
err(2, "posix_spawnattr_int");
/* NOTREACHTED */
}
if ((errno = posix_spawnattr_init(spawnattr)) != 0) {
err(2, "posix_spawnattr_int");
/* NOTREACHTED */
}
count = 1;
count = 1;
/* Run the real python executable using the same architure as this
* executable, this allows users to controle the architecture using
* "arch -ppc python"
*/
/* Run the real python executable using the same architure as this
* executable, this allows users to controle the architecture using
* "arch -ppc python"
*/
#if defined(__ppc64__)
cpu_types[0] = CPU_TYPE_POWERPC64;
cpu_types[0] = CPU_TYPE_POWERPC64;
#elif defined(__x86_64__)
cpu_types[0] = CPU_TYPE_X86_64;
cpu_types[0] = CPU_TYPE_X86_64;
#elif defined(__ppc__)
cpu_types[0] = CPU_TYPE_POWERPC;
cpu_types[0] = CPU_TYPE_POWERPC;
#elif defined(__i386__)
cpu_types[0] = CPU_TYPE_X86;
cpu_types[0] = CPU_TYPE_X86;
#else
# error "Unknown CPU"
# error "Unknown CPU"
#endif
if (posix_spawnattr_setbinpref_np(spawnattr, count,
cpu_types, &ocount) == -1) {
err(1, "posix_spawnattr_setbinpref");
/* NOTREACHTED */
}
if (count != ocount) {
fprintf(stderr, "posix_spawnattr_setbinpref failed to copy\n");
exit(1);
/* NOTREACHTED */
}
if (posix_spawnattr_setbinpref_np(spawnattr, count,
cpu_types, &ocount) == -1) {
err(1, "posix_spawnattr_setbinpref");
/* NOTREACHTED */
}
if (count != ocount) {
fprintf(stderr, "posix_spawnattr_setbinpref failed to copy\n");
exit(1);
/* NOTREACHTED */
}
/*
* Set flag that causes posix_spawn to behave like execv
*/
flags |= POSIX_SPAWN_SETEXEC;
if ((errno = posix_spawnattr_setflags(spawnattr, flags)) != 0) {
err(1, "posix_spawnattr_setflags");
/* NOTREACHTED */
}
/*
* Set flag that causes posix_spawn to behave like execv
*/
flags |= POSIX_SPAWN_SETEXEC;
if ((errno = posix_spawnattr_setflags(spawnattr, flags)) != 0) {
err(1, "posix_spawnattr_setflags");
/* NOTREACHTED */
}
}
#endif
int
int
main(int argc, char **argv) {
char* exec_path = get_python_path();
char* exec_path = get_python_path();
#ifdef HAVE_SPAWN_H
/* We're weak-linking to posix-spawnv to ensure that
* an executable build on 10.5 can work on 10.4.
*/
if (posix_spawn != NULL) {
posix_spawnattr_t spawnattr = NULL;
/* We're weak-linking to posix-spawnv to ensure that
* an executable build on 10.5 can work on 10.4.
*/
if (posix_spawn != NULL) {
posix_spawnattr_t spawnattr = NULL;
setup_spawnattr(&spawnattr);
posix_spawn(NULL, exec_path, NULL,
&spawnattr, argv, environ);
err(1, "posix_spawn: %s", exec_path);
}
setup_spawnattr(&spawnattr);
posix_spawn(NULL, exec_path, NULL,
&spawnattr, argv, environ);
err(1, "posix_spawn: %s", exec_path);
}
#endif
execve(exec_path, argv, environ);
err(1, "execve: %s", argv[0]);
/* NOTREACHED */
execve(exec_path, argv, environ);
err(1, "execve: %s", argv[0]);
/* NOTREACHED */
}

View file

@ -21,28 +21,28 @@
Assuming the script is a Bourne shell script, the first line of the
script should be
#!/bin/sh -
#!/bin/sh -
The - is important, don't omit it. If you're using esh, the first
line should be
#!/usr/local/bin/esh -f
#!/usr/local/bin/esh -f
and for ksh, the first line should be
#!/usr/local/bin/ksh -p
#!/usr/local/bin/ksh -p
The script should then set the variable IFS to the string
consisting of <space>, <tab>, and <newline>. After this (*not*
before!), the PATH variable should be set to a reasonable value and
exported. Do not expect the PATH to have a reasonable value, so do
not trust the old value of PATH. You should then set the umask of
the program by calling
umask 077 # or 022 if you want the files to be readable
umask 077 # or 022 if you want the files to be readable
If you plan to change directories, you should either unset CDPATH
or set it to a good value. Setting CDPATH to just ``.'' (dot) is a
good idea.
If, for some reason, you want to use csh, the first line should be
#!/bin/csh -fb
#!/bin/csh -fb
You should then set the path variable to something reasonable,
without trusting the inherited path. Here too, you should set the
umask using the command
umask 077 # or 022 if you want the files to be readable
umask 077 # or 022 if you want the files to be readable
*/
#include <unistd.h>
@ -54,14 +54,14 @@
/* CONFIGURATION SECTION */
#ifndef FULL_PATH /* so that this can be specified from the Makefile */
#ifndef FULL_PATH /* so that this can be specified from the Makefile */
/* Uncomment the following line:
#define FULL_PATH "/full/path/of/script"
#define FULL_PATH "/full/path/of/script"
* Then comment out the #error line. */
#error "You must define FULL_PATH somewhere"
#endif
#ifndef UMASK
#define UMASK 077
#define UMASK 077
#endif
/* END OF CONFIGURATION SECTION */
@ -101,76 +101,76 @@ char def_ENV[] = "ENV=:";
void
clean_environ(void)
{
char **p;
extern char **environ;
char **p;
extern char **environ;
for (p = environ; *p; p++) {
if (strncmp(*p, "LD_", 3) == 0)
**p = 'X';
else if (strncmp(*p, "_RLD", 4) == 0)
**p = 'X';
else if (strncmp(*p, "PYTHON", 6) == 0)
**p = 'X';
else if (strncmp(*p, "IFS=", 4) == 0)
*p = def_IFS;
else if (strncmp(*p, "CDPATH=", 7) == 0)
*p = def_CDPATH;
else if (strncmp(*p, "ENV=", 4) == 0)
*p = def_ENV;
}
putenv(def_PATH);
for (p = environ; *p; p++) {
if (strncmp(*p, "LD_", 3) == 0)
**p = 'X';
else if (strncmp(*p, "_RLD", 4) == 0)
**p = 'X';
else if (strncmp(*p, "PYTHON", 6) == 0)
**p = 'X';
else if (strncmp(*p, "IFS=", 4) == 0)
*p = def_IFS;
else if (strncmp(*p, "CDPATH=", 7) == 0)
*p = def_CDPATH;
else if (strncmp(*p, "ENV=", 4) == 0)
*p = def_ENV;
}
putenv(def_PATH);
}
int
main(int argc, char **argv)
{
struct stat statb;
gid_t egid = getegid();
uid_t euid = geteuid();
struct stat statb;
gid_t egid = getegid();
uid_t euid = geteuid();
/*
Sanity check #1.
This check should be made compile-time, but that's not possible.
If you're sure that you specified a full path name for FULL_PATH,
you can omit this check.
*/
if (FULL_PATH[0] != '/') {
fprintf(stderr, "%s: %s is not a full path name\n", argv[0],
FULL_PATH);
fprintf(stderr, "You can only use this wrapper if you\n");
fprintf(stderr, "compile it with an absolute path.\n");
exit(1);
}
/*
Sanity check #1.
This check should be made compile-time, but that's not possible.
If you're sure that you specified a full path name for FULL_PATH,
you can omit this check.
*/
if (FULL_PATH[0] != '/') {
fprintf(stderr, "%s: %s is not a full path name\n", argv[0],
FULL_PATH);
fprintf(stderr, "You can only use this wrapper if you\n");
fprintf(stderr, "compile it with an absolute path.\n");
exit(1);
}
/*
Sanity check #2.
Check that the owner of the script is equal to either the
effective uid or the super user.
*/
if (stat(FULL_PATH, &statb) < 0) {
perror("stat");
exit(1);
}
if (statb.st_uid != 0 && statb.st_uid != euid) {
fprintf(stderr, "%s: %s has the wrong owner\n", argv[0],
FULL_PATH);
fprintf(stderr, "The script should be owned by root,\n");
fprintf(stderr, "and shouldn't be writable by anyone.\n");
exit(1);
}
/*
Sanity check #2.
Check that the owner of the script is equal to either the
effective uid or the super user.
*/
if (stat(FULL_PATH, &statb) < 0) {
perror("stat");
exit(1);
}
if (statb.st_uid != 0 && statb.st_uid != euid) {
fprintf(stderr, "%s: %s has the wrong owner\n", argv[0],
FULL_PATH);
fprintf(stderr, "The script should be owned by root,\n");
fprintf(stderr, "and shouldn't be writable by anyone.\n");
exit(1);
}
if (setregid(egid, egid) < 0)
perror("setregid");
if (setreuid(euid, euid) < 0)
perror("setreuid");
if (setregid(egid, egid) < 0)
perror("setregid");
if (setreuid(euid, euid) < 0)
perror("setreuid");
clean_environ();
clean_environ();
umask(UMASK);
umask(UMASK);
while (**argv == '-') /* don't let argv[0] start with '-' */
(*argv)++;
execv(FULL_PATH, argv);
fprintf(stderr, "%s: could not execute the script\n", argv[0]);
exit(1);
while (**argv == '-') /* don't let argv[0] start with '-' */
(*argv)++;
execv(FULL_PATH, argv);
fprintf(stderr, "%s: could not execute the script\n", argv[0]);
exit(1);
}

View file

@ -8,51 +8,51 @@ Converted to C by Dmitry Vasiliev (dima at hlabs.spb.ru).
static Py_ssize_t
internal_bisect_right(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi)
{
PyObject *litem;
Py_ssize_t mid, res;
PyObject *litem;
Py_ssize_t mid, res;
if (lo < 0) {
PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
return -1;
}
if (hi == -1) {
hi = PySequence_Size(list);
if (hi < 0)
return -1;
}
while (lo < hi) {
mid = (lo + hi) / 2;
litem = PySequence_GetItem(list, mid);
if (litem == NULL)
return -1;
res = PyObject_RichCompareBool(item, litem, Py_LT);
Py_DECREF(litem);
if (res < 0)
return -1;
if (res)
hi = mid;
else
lo = mid + 1;
}
return lo;
if (lo < 0) {
PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
return -1;
}
if (hi == -1) {
hi = PySequence_Size(list);
if (hi < 0)
return -1;
}
while (lo < hi) {
mid = (lo + hi) / 2;
litem = PySequence_GetItem(list, mid);
if (litem == NULL)
return -1;
res = PyObject_RichCompareBool(item, litem, Py_LT);
Py_DECREF(litem);
if (res < 0)
return -1;
if (res)
hi = mid;
else
lo = mid + 1;
}
return lo;
}
static PyObject *
bisect_right(PyObject *self, PyObject *args, PyObject *kw)
{
PyObject *list, *item;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
PyObject *list, *item;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_right(list, item, lo, hi);
if (index < 0)
return NULL;
return PyLong_FromSsize_t(index);
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_right",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_right(list, item, lo, hi);
if (index < 0)
return NULL;
return PyLong_FromSsize_t(index);
}
PyDoc_STRVAR(bisect_right_doc,
@ -70,30 +70,30 @@ slice of a to be searched.\n");
static PyObject *
insort_right(PyObject *self, PyObject *args, PyObject *kw)
{
PyObject *list, *item, *result;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
PyObject *list, *item, *result;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_right(list, item, lo, hi);
if (index < 0)
return NULL;
if (PyList_CheckExact(list)) {
if (PyList_Insert(list, index, item) < 0)
return NULL;
} else {
result = PyObject_CallMethod(list, "insert", "nO",
index, item);
if (result == NULL)
return NULL;
Py_DECREF(result);
}
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_right",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_right(list, item, lo, hi);
if (index < 0)
return NULL;
if (PyList_CheckExact(list)) {
if (PyList_Insert(list, index, item) < 0)
return NULL;
} else {
result = PyObject_CallMethod(list, "insert", "nO",
index, item);
if (result == NULL)
return NULL;
Py_DECREF(result);
}
Py_RETURN_NONE;
Py_RETURN_NONE;
}
PyDoc_STRVAR(insort_right_doc,
@ -109,51 +109,51 @@ slice of a to be searched.\n");
static Py_ssize_t
internal_bisect_left(PyObject *list, PyObject *item, Py_ssize_t lo, Py_ssize_t hi)
{
PyObject *litem;
Py_ssize_t mid, res;
PyObject *litem;
Py_ssize_t mid, res;
if (lo < 0) {
PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
return -1;
}
if (hi == -1) {
hi = PySequence_Size(list);
if (hi < 0)
return -1;
}
while (lo < hi) {
mid = (lo + hi) / 2;
litem = PySequence_GetItem(list, mid);
if (litem == NULL)
return -1;
res = PyObject_RichCompareBool(litem, item, Py_LT);
Py_DECREF(litem);
if (res < 0)
return -1;
if (res)
lo = mid + 1;
else
hi = mid;
}
return lo;
if (lo < 0) {
PyErr_SetString(PyExc_ValueError, "lo must be non-negative");
return -1;
}
if (hi == -1) {
hi = PySequence_Size(list);
if (hi < 0)
return -1;
}
while (lo < hi) {
mid = (lo + hi) / 2;
litem = PySequence_GetItem(list, mid);
if (litem == NULL)
return -1;
res = PyObject_RichCompareBool(litem, item, Py_LT);
Py_DECREF(litem);
if (res < 0)
return -1;
if (res)
lo = mid + 1;
else
hi = mid;
}
return lo;
}
static PyObject *
bisect_left(PyObject *self, PyObject *args, PyObject *kw)
{
PyObject *list, *item;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
PyObject *list, *item;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_left(list, item, lo, hi);
if (index < 0)
return NULL;
return PyLong_FromSsize_t(index);
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:bisect_left",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_left(list, item, lo, hi);
if (index < 0)
return NULL;
return PyLong_FromSsize_t(index);
}
PyDoc_STRVAR(bisect_left_doc,
@ -171,30 +171,30 @@ slice of a to be searched.\n");
static PyObject *
insort_left(PyObject *self, PyObject *args, PyObject *kw)
{
PyObject *list, *item, *result;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
PyObject *list, *item, *result;
Py_ssize_t lo = 0;
Py_ssize_t hi = -1;
Py_ssize_t index;
static char *keywords[] = {"a", "x", "lo", "hi", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_left(list, item, lo, hi);
if (index < 0)
return NULL;
if (PyList_CheckExact(list)) {
if (PyList_Insert(list, index, item) < 0)
return NULL;
} else {
result = PyObject_CallMethod(list, "insert", "iO",
index, item);
if (result == NULL)
return NULL;
Py_DECREF(result);
}
if (!PyArg_ParseTupleAndKeywords(args, kw, "OO|nn:insort_left",
keywords, &list, &item, &lo, &hi))
return NULL;
index = internal_bisect_left(list, item, lo, hi);
if (index < 0)
return NULL;
if (PyList_CheckExact(list)) {
if (PyList_Insert(list, index, item) < 0)
return NULL;
} else {
result = PyObject_CallMethod(list, "insert", "iO",
index, item);
if (result == NULL)
return NULL;
Py_DECREF(result);
}
Py_RETURN_NONE;
Py_RETURN_NONE;
}
PyDoc_STRVAR(insort_left_doc,
@ -211,19 +211,19 @@ PyDoc_STRVAR(bisect_doc, "Alias for bisect_right().\n");
PyDoc_STRVAR(insort_doc, "Alias for insort_right().\n");
static PyMethodDef bisect_methods[] = {
{"bisect_right", (PyCFunction)bisect_right,
METH_VARARGS|METH_KEYWORDS, bisect_right_doc},
{"bisect", (PyCFunction)bisect_right,
METH_VARARGS|METH_KEYWORDS, bisect_doc},
{"insort_right", (PyCFunction)insort_right,
METH_VARARGS|METH_KEYWORDS, insort_right_doc},
{"insort", (PyCFunction)insort_right,
METH_VARARGS|METH_KEYWORDS, insort_doc},
{"bisect_left", (PyCFunction)bisect_left,
METH_VARARGS|METH_KEYWORDS, bisect_left_doc},
{"insort_left", (PyCFunction)insort_left,
METH_VARARGS|METH_KEYWORDS, insort_left_doc},
{NULL, NULL} /* sentinel */
{"bisect_right", (PyCFunction)bisect_right,
METH_VARARGS|METH_KEYWORDS, bisect_right_doc},
{"bisect", (PyCFunction)bisect_right,
METH_VARARGS|METH_KEYWORDS, bisect_doc},
{"insort_right", (PyCFunction)insort_right,
METH_VARARGS|METH_KEYWORDS, insort_right_doc},
{"insort", (PyCFunction)insort_right,
METH_VARARGS|METH_KEYWORDS, insort_doc},
{"bisect_left", (PyCFunction)bisect_left,
METH_VARARGS|METH_KEYWORDS, bisect_left_doc},
{"insort_left", (PyCFunction)insort_left,
METH_VARARGS|METH_KEYWORDS, insort_left_doc},
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
@ -236,19 +236,19 @@ common approach.\n");
static struct PyModuleDef _bisectmodule = {
PyModuleDef_HEAD_INIT,
"_bisect",
module_doc,
-1,
bisect_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_bisect",
module_doc,
-1,
bisect_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__bisect(void)
{
return PyModule_Create(&_bisectmodule);
return PyModule_Create(&_bisectmodule);
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -14,152 +14,152 @@
EXPORT(void)testfunc_array(int values[4])
{
printf("testfunc_array %d %d %d %d\n",
values[0],
values[1],
values[2],
values[3]);
printf("testfunc_array %d %d %d %d\n",
values[0],
values[1],
values[2],
values[3]);
}
EXPORT(long double)testfunc_Ddd(double a, double b)
{
long double result = (long double)(a * b);
printf("testfunc_Ddd(%p, %p)\n", &a, &b);
printf("testfunc_Ddd(%g, %g)\n", a, b);
return result;
long double result = (long double)(a * b);
printf("testfunc_Ddd(%p, %p)\n", &a, &b);
printf("testfunc_Ddd(%g, %g)\n", a, b);
return result;
}
EXPORT(long double)testfunc_DDD(long double a, long double b)
{
long double result = a * b;
printf("testfunc_DDD(%p, %p)\n", &a, &b);
printf("testfunc_DDD(%Lg, %Lg)\n", a, b);
return result;
long double result = a * b;
printf("testfunc_DDD(%p, %p)\n", &a, &b);
printf("testfunc_DDD(%Lg, %Lg)\n", a, b);
return result;
}
EXPORT(int)testfunc_iii(int a, int b)
{
int result = a * b;
printf("testfunc_iii(%p, %p)\n", &a, &b);
return result;
int result = a * b;
printf("testfunc_iii(%p, %p)\n", &a, &b);
return result;
}
EXPORT(int)myprintf(char *fmt, ...)
{
int result;
va_list argptr;
va_start(argptr, fmt);
result = vprintf(fmt, argptr);
va_end(argptr);
return result;
int result;
va_list argptr;
va_start(argptr, fmt);
result = vprintf(fmt, argptr);
va_end(argptr);
return result;
}
EXPORT(char *)my_strtok(char *token, const char *delim)
{
return strtok(token, delim);
return strtok(token, delim);
}
EXPORT(char *)my_strchr(const char *s, int c)
{
return strchr(s, c);
return strchr(s, c);
}
EXPORT(double) my_sqrt(double a)
{
return sqrt(a);
return sqrt(a);
}
EXPORT(void) my_qsort(void *base, size_t num, size_t width, int(*compare)(const void*, const void*))
{
qsort(base, num, width, compare);
qsort(base, num, width, compare);
}
EXPORT(int *) _testfunc_ai8(int a[8])
{
return a;
return a;
}
EXPORT(void) _testfunc_v(int a, int b, int *presult)
{
*presult = a + b;
*presult = a + b;
}
EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
*/
return (int)(b + h + i + l + f + d);
return (int)(b + h + i + l + f + d);
}
EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
*/
return (float)(b + h + i + l + f + d);
return (float)(b + h + i + l + f + d);
}
EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
*/
return (double)(b + h + i + l + f + d);
return (double)(b + h + i + l + f + d);
}
EXPORT(long double) _testfunc_D_bhilfD(signed char b, short h, int i, long l, float f, long double d)
{
/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
b, h, i, l, f, d);
*/
return (long double)(b + h + i + l + f + d);
return (long double)(b + h + i + l + f + d);
}
EXPORT(char *) _testfunc_p_p(void *s)
{
return (char *)s;
return (char *)s;
}
EXPORT(void *) _testfunc_c_p_p(int *argcp, char **argv)
{
return argv[(*argcp)-1];
return argv[(*argcp)-1];
}
EXPORT(void *) get_strchr(void)
{
return (void *)strchr;
return (void *)strchr;
}
EXPORT(char *) my_strdup(char *src)
{
char *dst = (char *)malloc(strlen(src)+1);
if (!dst)
return NULL;
strcpy(dst, src);
return dst;
char *dst = (char *)malloc(strlen(src)+1);
if (!dst)
return NULL;
strcpy(dst, src);
return dst;
}
EXPORT(void)my_free(void *ptr)
{
free(ptr);
free(ptr);
}
#ifdef HAVE_WCHAR_H
EXPORT(wchar_t *) my_wcsdup(wchar_t *src)
{
size_t len = wcslen(src);
wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
if (ptr == NULL)
return NULL;
memcpy(ptr, src, (len+1) * sizeof(wchar_t));
return ptr;
size_t len = wcslen(src);
wchar_t *ptr = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
if (ptr == NULL)
return NULL;
memcpy(ptr, src, (len+1) * sizeof(wchar_t));
return ptr;
}
EXPORT(size_t) my_wcslen(wchar_t *src)
{
return wcslen(src);
return wcslen(src);
}
#endif
@ -170,158 +170,158 @@ EXPORT(size_t) my_wcslen(wchar_t *src)
#endif
typedef struct {
int (*c)(int, int);
int (__stdcall *s)(int, int);
int (*c)(int, int);
int (__stdcall *s)(int, int);
} FUNCS;
EXPORT(int) _testfunc_callfuncp(FUNCS *fp)
{
fp->c(1, 2);
fp->s(3, 4);
return 0;
fp->c(1, 2);
fp->s(3, 4);
return 0;
}
EXPORT(int) _testfunc_deref_pointer(int *pi)
{
return *pi;
return *pi;
}
#ifdef MS_WIN32
EXPORT(int) _testfunc_piunk(IUnknown FAR *piunk)
{
piunk->lpVtbl->AddRef(piunk);
return piunk->lpVtbl->Release(piunk);
piunk->lpVtbl->AddRef(piunk);
return piunk->lpVtbl->Release(piunk);
}
#endif
EXPORT(int) _testfunc_callback_with_pointer(int (*func)(int *))
{
int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int table[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
return (*func)(table);
return (*func)(table);
}
#ifdef HAVE_LONG_LONG
EXPORT(PY_LONG_LONG) _testfunc_q_bhilfdq(signed char b, short h, int i, long l, float f,
double d, PY_LONG_LONG q)
double d, PY_LONG_LONG q)
{
return (PY_LONG_LONG)(b + h + i + l + f + d + q);
return (PY_LONG_LONG)(b + h + i + l + f + d + q);
}
EXPORT(PY_LONG_LONG) _testfunc_q_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
return (PY_LONG_LONG)(b + h + i + l + f + d);
return (PY_LONG_LONG)(b + h + i + l + f + d);
}
EXPORT(int) _testfunc_callback_i_if(int value, int (*func)(int))
{
int sum = 0;
while (value != 0) {
sum += func(value);
value /= 2;
}
return sum;
int sum = 0;
while (value != 0) {
sum += func(value);
value /= 2;
}
return sum;
}
EXPORT(PY_LONG_LONG) _testfunc_callback_q_qf(PY_LONG_LONG value,
PY_LONG_LONG (*func)(PY_LONG_LONG))
PY_LONG_LONG (*func)(PY_LONG_LONG))
{
PY_LONG_LONG sum = 0;
PY_LONG_LONG sum = 0;
while (value != 0) {
sum += func(value);
value /= 2;
}
return sum;
while (value != 0) {
sum += func(value);
value /= 2;
}
return sum;
}
#endif
typedef struct {
char *name;
char *value;
char *name;
char *value;
} SPAM;
typedef struct {
char *name;
int num_spams;
SPAM *spams;
char *name;
int num_spams;
SPAM *spams;
} EGG;
SPAM my_spams[2] = {
{ "name1", "value1" },
{ "name2", "value2" },
{ "name1", "value1" },
{ "name2", "value2" },
};
EGG my_eggs[1] = {
{ "first egg", 1, my_spams }
{ "first egg", 1, my_spams }
};
EXPORT(int) getSPAMANDEGGS(EGG **eggs)
{
*eggs = my_eggs;
return 1;
*eggs = my_eggs;
return 1;
}
typedef struct tagpoint {
int x;
int y;
int x;
int y;
} point;
EXPORT(int) _testfunc_byval(point in, point *pout)
{
if (pout) {
pout->x = in.x;
pout->y = in.y;
}
return in.x + in.y;
if (pout) {
pout->x = in.x;
pout->y = in.y;
}
return in.x + in.y;
}
EXPORT (int) an_integer = 42;
EXPORT(int) get_an_integer(void)
{
return an_integer;
return an_integer;
}
EXPORT(double)
integrate(double a, double b, double (*f)(double), long nstep)
{
double x, sum=0.0, dx=(b-a)/(double)nstep;
for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx)
sum += f(x);
return sum/(double)nstep;
double x, sum=0.0, dx=(b-a)/(double)nstep;
for(x=a+0.5*dx; (b-x)*(x-a)>0.0; x+=dx)
sum += f(x);
return sum/(double)nstep;
}
typedef struct {
void (*initialize)(void *(*)(int), void(*)(void *));
void (*initialize)(void *(*)(int), void(*)(void *));
} xxx_library;
static void _xxx_init(void *(*Xalloc)(int), void (*Xfree)(void *))
{
void *ptr;
printf("_xxx_init got %p %p\n", Xalloc, Xfree);
printf("calling\n");
ptr = Xalloc(32);
Xfree(ptr);
printf("calls done, ptr was %p\n", ptr);
void *ptr;
printf("_xxx_init got %p %p\n", Xalloc, Xfree);
printf("calling\n");
ptr = Xalloc(32);
Xfree(ptr);
printf("calls done, ptr was %p\n", ptr);
}
xxx_library _xxx_lib = {
_xxx_init
_xxx_init
};
EXPORT(xxx_library) *library_get(void)
{
return &_xxx_lib;
return &_xxx_lib;
}
#ifdef MS_WIN32
/* See Don Box (german), pp 79ff. */
EXPORT(void) GetString(BSTR *pbstr)
{
*pbstr = SysAllocString(L"Goodbye!");
*pbstr = SysAllocString(L"Goodbye!");
}
#endif
@ -330,12 +330,12 @@ EXPORT(void) GetString(BSTR *pbstr)
*/
PyObject *py_func_si(PyObject *self, PyObject *args)
{
char *name;
int i;
if (!PyArg_ParseTuple(args, "si", &name, &i))
return NULL;
Py_INCREF(Py_None);
return Py_None;
char *name;
int i;
if (!PyArg_ParseTuple(args, "si", &name, &i))
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
EXPORT(void) _py_func_si(char *s, int i)
@ -344,8 +344,8 @@ EXPORT(void) _py_func_si(char *s, int i)
PyObject *py_func(PyObject *self, PyObject *args)
{
Py_INCREF(Py_None);
return Py_None;
Py_INCREF(Py_None);
return Py_None;
}
EXPORT(void) _py_func(void)
@ -356,64 +356,64 @@ EXPORT(PY_LONG_LONG) last_tf_arg_s;
EXPORT(unsigned PY_LONG_LONG) last_tf_arg_u;
struct BITS {
int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9;
short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7;
int A: 1, B:2, C:3, D:4, E: 5, F: 6, G: 7, H: 8, I: 9;
short M: 1, N: 2, O: 3, P: 4, Q: 5, R: 6, S: 7;
};
EXPORT(void) set_bitfields(struct BITS *bits, char name, int value)
{
switch (name) {
case 'A': bits->A = value; break;
case 'B': bits->B = value; break;
case 'C': bits->C = value; break;
case 'D': bits->D = value; break;
case 'E': bits->E = value; break;
case 'F': bits->F = value; break;
case 'G': bits->G = value; break;
case 'H': bits->H = value; break;
case 'I': bits->I = value; break;
switch (name) {
case 'A': bits->A = value; break;
case 'B': bits->B = value; break;
case 'C': bits->C = value; break;
case 'D': bits->D = value; break;
case 'E': bits->E = value; break;
case 'F': bits->F = value; break;
case 'G': bits->G = value; break;
case 'H': bits->H = value; break;
case 'I': bits->I = value; break;
case 'M': bits->M = value; break;
case 'N': bits->N = value; break;
case 'O': bits->O = value; break;
case 'P': bits->P = value; break;
case 'Q': bits->Q = value; break;
case 'R': bits->R = value; break;
case 'S': bits->S = value; break;
}
case 'M': bits->M = value; break;
case 'N': bits->N = value; break;
case 'O': bits->O = value; break;
case 'P': bits->P = value; break;
case 'Q': bits->Q = value; break;
case 'R': bits->R = value; break;
case 'S': bits->S = value; break;
}
}
EXPORT(int) unpack_bitfields(struct BITS *bits, char name)
{
switch (name) {
case 'A': return bits->A;
case 'B': return bits->B;
case 'C': return bits->C;
case 'D': return bits->D;
case 'E': return bits->E;
case 'F': return bits->F;
case 'G': return bits->G;
case 'H': return bits->H;
case 'I': return bits->I;
switch (name) {
case 'A': return bits->A;
case 'B': return bits->B;
case 'C': return bits->C;
case 'D': return bits->D;
case 'E': return bits->E;
case 'F': return bits->F;
case 'G': return bits->G;
case 'H': return bits->H;
case 'I': return bits->I;
case 'M': return bits->M;
case 'N': return bits->N;
case 'O': return bits->O;
case 'P': return bits->P;
case 'Q': return bits->Q;
case 'R': return bits->R;
case 'S': return bits->S;
}
return 0;
case 'M': return bits->M;
case 'N': return bits->N;
case 'O': return bits->O;
case 'P': return bits->P;
case 'Q': return bits->Q;
case 'R': return bits->R;
case 'S': return bits->S;
}
return 0;
}
static PyMethodDef module_methods[] = {
/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS},
{"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS},
/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS},
{"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS},
*/
{"func_si", py_func_si, METH_VARARGS},
{"func", py_func, METH_NOARGS},
{ NULL, NULL, 0, NULL},
{"func_si", py_func_si, METH_VARARGS},
{"func", py_func, METH_NOARGS},
{ NULL, NULL, 0, NULL},
};
#define S last_tf_arg_s = (PY_LONG_LONG)c
@ -483,80 +483,80 @@ EXPORT(void) __stdcall s_tv_i(int c) { S; return; }
#endif
/********/
#ifndef MS_WIN32
typedef struct {
long x;
long y;
long x;
long y;
} POINT;
typedef struct {
long left;
long top;
long right;
long bottom;
long left;
long top;
long right;
long bottom;
} RECT;
#endif
EXPORT(int) PointInRect(RECT *prc, POINT pt)
{
if (pt.x < prc->left)
return 0;
if (pt.x > prc->right)
return 0;
if (pt.y < prc->top)
return 0;
if (pt.y > prc->bottom)
return 0;
return 1;
if (pt.x < prc->left)
return 0;
if (pt.x > prc->right)
return 0;
if (pt.y < prc->top)
return 0;
if (pt.y > prc->bottom)
return 0;
return 1;
}
typedef struct {
short x;
short y;
short x;
short y;
} S2H;
EXPORT(S2H) ret_2h_func(S2H inp)
{
inp.x *= 2;
inp.y *= 3;
return inp;
inp.x *= 2;
inp.y *= 3;
return inp;
}
typedef struct {
int a, b, c, d, e, f, g, h;
int a, b, c, d, e, f, g, h;
} S8I;
EXPORT(S8I) ret_8i_func(S8I inp)
{
inp.a *= 2;
inp.b *= 3;
inp.c *= 4;
inp.d *= 5;
inp.e *= 6;
inp.f *= 7;
inp.g *= 8;
inp.h *= 9;
return inp;
inp.a *= 2;
inp.b *= 3;
inp.c *= 4;
inp.d *= 5;
inp.e *= 6;
inp.f *= 7;
inp.g *= 8;
inp.h *= 9;
return inp;
}
EXPORT(int) GetRectangle(int flag, RECT *prect)
{
if (flag == 0)
return 0;
prect->left = (int)flag;
prect->top = (int)flag + 1;
prect->right = (int)flag + 2;
prect->bottom = (int)flag + 3;
return 1;
if (flag == 0)
return 0;
prect->left = (int)flag;
prect->top = (int)flag + 1;
prect->right = (int)flag + 2;
prect->bottom = (int)flag + 3;
return 1;
}
EXPORT(void) TwoOutArgs(int a, int *pi, int b, int *pj)
{
*pi += a;
*pj += b;
*pi += a;
*pj += b;
}
#ifdef MS_WIN32
@ -571,32 +571,32 @@ EXPORT(S8I) __stdcall s_ret_8i_func(S8I inp) { return ret_8i_func(inp); }
EXPORT (HRESULT) KeepObject(IUnknown *punk)
{
static IUnknown *pobj;
if (punk)
punk->lpVtbl->AddRef(punk);
if (pobj)
pobj->lpVtbl->Release(pobj);
pobj = punk;
return S_OK;
static IUnknown *pobj;
if (punk)
punk->lpVtbl->AddRef(punk);
if (pobj)
pobj->lpVtbl->Release(pobj);
pobj = punk;
return S_OK;
}
#endif
static struct PyModuleDef _ctypes_testmodule = {
PyModuleDef_HEAD_INIT,
"_ctypes_test",
NULL,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_ctypes_test",
NULL,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__ctypes_test(void)
{
return PyModule_Create(&_ctypes_testmodule);
return PyModule_Create(&_ctypes_testmodule);
}

View file

@ -12,65 +12,65 @@
static void
CThunkObject_dealloc(PyObject *_self)
{
CThunkObject *self = (CThunkObject *)_self;
Py_XDECREF(self->converters);
Py_XDECREF(self->callable);
Py_XDECREF(self->restype);
if (self->pcl)
_ctypes_free_closure(self->pcl);
PyObject_GC_Del(self);
CThunkObject *self = (CThunkObject *)_self;
Py_XDECREF(self->converters);
Py_XDECREF(self->callable);
Py_XDECREF(self->restype);
if (self->pcl)
_ctypes_free_closure(self->pcl);
PyObject_GC_Del(self);
}
static int
CThunkObject_traverse(PyObject *_self, visitproc visit, void *arg)
{
CThunkObject *self = (CThunkObject *)_self;
Py_VISIT(self->converters);
Py_VISIT(self->callable);
Py_VISIT(self->restype);
return 0;
CThunkObject *self = (CThunkObject *)_self;
Py_VISIT(self->converters);
Py_VISIT(self->callable);
Py_VISIT(self->restype);
return 0;
}
static int
CThunkObject_clear(PyObject *_self)
{
CThunkObject *self = (CThunkObject *)_self;
Py_CLEAR(self->converters);
Py_CLEAR(self->callable);
Py_CLEAR(self->restype);
return 0;
CThunkObject *self = (CThunkObject *)_self;
Py_CLEAR(self->converters);
Py_CLEAR(self->callable);
Py_CLEAR(self->restype);
return 0;
}
PyTypeObject PyCThunk_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_ctypes.CThunkObject",
sizeof(CThunkObject), /* tp_basicsize */
sizeof(ffi_type), /* tp_itemsize */
CThunkObject_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
"CThunkObject", /* tp_doc */
CThunkObject_traverse, /* tp_traverse */
CThunkObject_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
PyVarObject_HEAD_INIT(NULL, 0)
"_ctypes.CThunkObject",
sizeof(CThunkObject), /* tp_basicsize */
sizeof(ffi_type), /* tp_itemsize */
CThunkObject_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
"CThunkObject", /* tp_doc */
CThunkObject_traverse, /* tp_traverse */
CThunkObject_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
};
/**************************************************************/
@ -78,43 +78,43 @@ PyTypeObject PyCThunk_Type = {
static void
PrintError(char *msg, ...)
{
char buf[512];
PyObject *f = PySys_GetObject("stderr");
va_list marker;
char buf[512];
PyObject *f = PySys_GetObject("stderr");
va_list marker;
va_start(marker, msg);
vsnprintf(buf, sizeof(buf), msg, marker);
va_end(marker);
if (f != NULL && f != Py_None)
PyFile_WriteString(buf, f);
PyErr_Print();
va_start(marker, msg);
vsnprintf(buf, sizeof(buf), msg, marker);
va_end(marker);
if (f != NULL && f != Py_None)
PyFile_WriteString(buf, f);
PyErr_Print();
}
/* after code that pyrex generates */
void _ctypes_add_traceback(char *funcname, char *filename, int lineno)
{
PyObject *py_globals = 0;
PyCodeObject *py_code = 0;
PyFrameObject *py_frame = 0;
py_globals = PyDict_New();
if (!py_globals) goto bad;
py_code = PyCode_NewEmpty(filename, funcname, lineno);
if (!py_code) goto bad;
py_frame = PyFrame_New(
PyThreadState_Get(), /*PyThreadState *tstate,*/
py_code, /*PyCodeObject *code,*/
py_globals, /*PyObject *globals,*/
0 /*PyObject *locals*/
);
if (!py_frame) goto bad;
py_frame->f_lineno = lineno;
PyTraceBack_Here(py_frame);
PyObject *py_globals = 0;
PyCodeObject *py_code = 0;
PyFrameObject *py_frame = 0;
py_globals = PyDict_New();
if (!py_globals) goto bad;
py_code = PyCode_NewEmpty(filename, funcname, lineno);
if (!py_code) goto bad;
py_frame = PyFrame_New(
PyThreadState_Get(), /*PyThreadState *tstate,*/
py_code, /*PyCodeObject *code,*/
py_globals, /*PyObject *globals,*/
0 /*PyObject *locals*/
);
if (!py_frame) goto bad;
py_frame->f_lineno = lineno;
PyTraceBack_Here(py_frame);
bad:
Py_XDECREF(py_globals);
Py_XDECREF(py_code);
Py_XDECREF(py_frame);
Py_XDECREF(py_globals);
Py_XDECREF(py_code);
Py_XDECREF(py_frame);
}
#ifdef MS_WIN32
@ -131,15 +131,15 @@ void _ctypes_add_traceback(char *funcname, char *filename, int lineno)
static void
TryAddRef(StgDictObject *dict, CDataObject *obj)
{
IUnknown *punk;
IUnknown *punk;
if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_"))
return;
if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_"))
return;
punk = *(IUnknown **)obj->b_ptr;
if (punk)
punk->lpVtbl->AddRef(punk);
return;
punk = *(IUnknown **)obj->b_ptr;
if (punk)
punk->lpVtbl->AddRef(punk);
return;
}
#endif
@ -149,421 +149,421 @@ TryAddRef(StgDictObject *dict, CDataObject *obj)
*
*/
static void _CallPythonObject(void *mem,
ffi_type *restype,
SETFUNC setfunc,
PyObject *callable,
PyObject *converters,
int flags,
void **pArgs)
ffi_type *restype,
SETFUNC setfunc,
PyObject *callable,
PyObject *converters,
int flags,
void **pArgs)
{
Py_ssize_t i;
PyObject *result;
PyObject *arglist = NULL;
Py_ssize_t nArgs;
PyObject *error_object = NULL;
int *space;
Py_ssize_t i;
PyObject *result;
PyObject *arglist = NULL;
Py_ssize_t nArgs;
PyObject *error_object = NULL;
int *space;
#ifdef WITH_THREAD
PyGILState_STATE state = PyGILState_Ensure();
PyGILState_STATE state = PyGILState_Ensure();
#endif
nArgs = PySequence_Length(converters);
/* Hm. What to return in case of error?
For COM, 0xFFFFFFFF seems better than 0.
*/
if (nArgs < 0) {
PrintError("BUG: PySequence_Length");
goto Done;
}
nArgs = PySequence_Length(converters);
/* Hm. What to return in case of error?
For COM, 0xFFFFFFFF seems better than 0.
*/
if (nArgs < 0) {
PrintError("BUG: PySequence_Length");
goto Done;
}
arglist = PyTuple_New(nArgs);
if (!arglist) {
PrintError("PyTuple_New()");
goto Done;
}
for (i = 0; i < nArgs; ++i) {
/* Note: new reference! */
PyObject *cnv = PySequence_GetItem(converters, i);
StgDictObject *dict;
if (cnv)
dict = PyType_stgdict(cnv);
else {
PrintError("Getting argument converter %d\n", i);
goto Done;
}
arglist = PyTuple_New(nArgs);
if (!arglist) {
PrintError("PyTuple_New()");
goto Done;
}
for (i = 0; i < nArgs; ++i) {
/* Note: new reference! */
PyObject *cnv = PySequence_GetItem(converters, i);
StgDictObject *dict;
if (cnv)
dict = PyType_stgdict(cnv);
else {
PrintError("Getting argument converter %d\n", i);
goto Done;
}
if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) {
PyObject *v = dict->getfunc(*pArgs, dict->size);
if (!v) {
PrintError("create argument %d:\n", i);
Py_DECREF(cnv);
goto Done;
}
PyTuple_SET_ITEM(arglist, i, v);
/* XXX XXX XX
We have the problem that c_byte or c_short have dict->size of
1 resp. 4, but these parameters are pushed as sizeof(int) bytes.
BTW, the same problem occurrs when they are pushed as parameters
*/
} else if (dict) {
/* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */
CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL);
if (!obj) {
PrintError("create argument %d:\n", i);
Py_DECREF(cnv);
goto Done;
}
if (!CDataObject_Check(obj)) {
Py_DECREF(obj);
Py_DECREF(cnv);
PrintError("unexpected result of create argument %d:\n", i);
goto Done;
}
memcpy(obj->b_ptr, *pArgs, dict->size);
PyTuple_SET_ITEM(arglist, i, (PyObject *)obj);
if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) {
PyObject *v = dict->getfunc(*pArgs, dict->size);
if (!v) {
PrintError("create argument %d:\n", i);
Py_DECREF(cnv);
goto Done;
}
PyTuple_SET_ITEM(arglist, i, v);
/* XXX XXX XX
We have the problem that c_byte or c_short have dict->size of
1 resp. 4, but these parameters are pushed as sizeof(int) bytes.
BTW, the same problem occurrs when they are pushed as parameters
*/
} else if (dict) {
/* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */
CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL);
if (!obj) {
PrintError("create argument %d:\n", i);
Py_DECREF(cnv);
goto Done;
}
if (!CDataObject_Check(obj)) {
Py_DECREF(obj);
Py_DECREF(cnv);
PrintError("unexpected result of create argument %d:\n", i);
goto Done;
}
memcpy(obj->b_ptr, *pArgs, dict->size);
PyTuple_SET_ITEM(arglist, i, (PyObject *)obj);
#ifdef MS_WIN32
TryAddRef(dict, obj);
TryAddRef(dict, obj);
#endif
} else {
PyErr_SetString(PyExc_TypeError,
"cannot build parameter");
PrintError("Parsing argument %d\n", i);
Py_DECREF(cnv);
goto Done;
}
Py_DECREF(cnv);
/* XXX error handling! */
pArgs++;
}
} else {
PyErr_SetString(PyExc_TypeError,
"cannot build parameter");
PrintError("Parsing argument %d\n", i);
Py_DECREF(cnv);
goto Done;
}
Py_DECREF(cnv);
/* XXX error handling! */
pArgs++;
}
#define CHECK(what, x) \
if (x == NULL) _ctypes_add_traceback(what, "_ctypes/callbacks.c", __LINE__ - 1), PyErr_Print()
if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
error_object = _ctypes_get_errobj(&space);
if (error_object == NULL)
goto Done;
if (flags & FUNCFLAG_USE_ERRNO) {
int temp = space[0];
space[0] = errno;
errno = temp;
}
if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
error_object = _ctypes_get_errobj(&space);
if (error_object == NULL)
goto Done;
if (flags & FUNCFLAG_USE_ERRNO) {
int temp = space[0];
space[0] = errno;
errno = temp;
}
#ifdef MS_WIN32
if (flags & FUNCFLAG_USE_LASTERROR) {
int temp = space[1];
space[1] = GetLastError();
SetLastError(temp);
}
if (flags & FUNCFLAG_USE_LASTERROR) {
int temp = space[1];
space[1] = GetLastError();
SetLastError(temp);
}
#endif
}
}
result = PyObject_CallObject(callable, arglist);
CHECK("'calling callback function'", result);
result = PyObject_CallObject(callable, arglist);
CHECK("'calling callback function'", result);
#ifdef MS_WIN32
if (flags & FUNCFLAG_USE_LASTERROR) {
int temp = space[1];
space[1] = GetLastError();
SetLastError(temp);
}
if (flags & FUNCFLAG_USE_LASTERROR) {
int temp = space[1];
space[1] = GetLastError();
SetLastError(temp);
}
#endif
if (flags & FUNCFLAG_USE_ERRNO) {
int temp = space[0];
space[0] = errno;
errno = temp;
}
Py_XDECREF(error_object);
if (flags & FUNCFLAG_USE_ERRNO) {
int temp = space[0];
space[0] = errno;
errno = temp;
}
Py_XDECREF(error_object);
if ((restype != &ffi_type_void) && result) {
PyObject *keep;
assert(setfunc);
if ((restype != &ffi_type_void) && result) {
PyObject *keep;
assert(setfunc);
#ifdef WORDS_BIGENDIAN
/* See the corresponding code in callproc.c, around line 961 */
if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg))
mem = (char *)mem + sizeof(ffi_arg) - restype->size;
/* See the corresponding code in callproc.c, around line 961 */
if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg))
mem = (char *)mem + sizeof(ffi_arg) - restype->size;
#endif
keep = setfunc(mem, result, 0);
CHECK("'converting callback result'", keep);
/* keep is an object we have to keep alive so that the result
stays valid. If there is no such object, the setfunc will
have returned Py_None.
keep = setfunc(mem, result, 0);
CHECK("'converting callback result'", keep);
/* keep is an object we have to keep alive so that the result
stays valid. If there is no such object, the setfunc will
have returned Py_None.
If there is such an object, we have no choice than to keep
it alive forever - but a refcount and/or memory leak will
be the result. EXCEPT when restype is py_object - Python
itself knows how to manage the refcount of these objects.
*/
if (keep == NULL) /* Could not convert callback result. */
PyErr_WriteUnraisable(callable);
else if (keep == Py_None) /* Nothing to keep */
Py_DECREF(keep);
else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) {
if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning,
"memory leak in callback function.",
1))
PyErr_WriteUnraisable(callable);
}
}
Py_XDECREF(result);
If there is such an object, we have no choice than to keep
it alive forever - but a refcount and/or memory leak will
be the result. EXCEPT when restype is py_object - Python
itself knows how to manage the refcount of these objects.
*/
if (keep == NULL) /* Could not convert callback result. */
PyErr_WriteUnraisable(callable);
else if (keep == Py_None) /* Nothing to keep */
Py_DECREF(keep);
else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) {
if (-1 == PyErr_WarnEx(PyExc_RuntimeWarning,
"memory leak in callback function.",
1))
PyErr_WriteUnraisable(callable);
}
}
Py_XDECREF(result);
Done:
Py_XDECREF(arglist);
Py_XDECREF(arglist);
#ifdef WITH_THREAD
PyGILState_Release(state);
PyGILState_Release(state);
#endif
}
static void closure_fcn(ffi_cif *cif,
void *resp,
void **args,
void *userdata)
void *resp,
void **args,
void *userdata)
{
CThunkObject *p = (CThunkObject *)userdata;
CThunkObject *p = (CThunkObject *)userdata;
_CallPythonObject(resp,
p->ffi_restype,
p->setfunc,
p->callable,
p->converters,
p->flags,
args);
_CallPythonObject(resp,
p->ffi_restype,
p->setfunc,
p->callable,
p->converters,
p->flags,
args);
}
static CThunkObject* CThunkObject_new(Py_ssize_t nArgs)
{
CThunkObject *p;
int i;
CThunkObject *p;
int i;
p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs);
if (p == NULL) {
PyErr_NoMemory();
return NULL;
}
p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs);
if (p == NULL) {
PyErr_NoMemory();
return NULL;
}
p->pcl = NULL;
memset(&p->cif, 0, sizeof(p->cif));
p->converters = NULL;
p->callable = NULL;
p->setfunc = NULL;
p->ffi_restype = NULL;
for (i = 0; i < nArgs + 1; ++i)
p->atypes[i] = NULL;
PyObject_GC_Track((PyObject *)p);
return p;
p->pcl = NULL;
memset(&p->cif, 0, sizeof(p->cif));
p->converters = NULL;
p->callable = NULL;
p->setfunc = NULL;
p->ffi_restype = NULL;
for (i = 0; i < nArgs + 1; ++i)
p->atypes[i] = NULL;
PyObject_GC_Track((PyObject *)p);
return p;
}
CThunkObject *_ctypes_alloc_callback(PyObject *callable,
PyObject *converters,
PyObject *restype,
int flags)
PyObject *converters,
PyObject *restype,
int flags)
{
int result;
CThunkObject *p;
Py_ssize_t nArgs, i;
ffi_abi cc;
int result;
CThunkObject *p;
Py_ssize_t nArgs, i;
ffi_abi cc;
nArgs = PySequence_Size(converters);
p = CThunkObject_new(nArgs);
if (p == NULL)
return NULL;
nArgs = PySequence_Size(converters);
p = CThunkObject_new(nArgs);
if (p == NULL)
return NULL;
assert(CThunk_CheckExact((PyObject *)p));
assert(CThunk_CheckExact((PyObject *)p));
p->pcl = _ctypes_alloc_closure();
if (p->pcl == NULL) {
PyErr_NoMemory();
goto error;
}
p->pcl = _ctypes_alloc_closure();
if (p->pcl == NULL) {
PyErr_NoMemory();
goto error;
}
p->flags = flags;
for (i = 0; i < nArgs; ++i) {
PyObject *cnv = PySequence_GetItem(converters, i);
if (cnv == NULL)
goto error;
p->atypes[i] = _ctypes_get_ffi_type(cnv);
Py_DECREF(cnv);
}
p->atypes[i] = NULL;
p->flags = flags;
for (i = 0; i < nArgs; ++i) {
PyObject *cnv = PySequence_GetItem(converters, i);
if (cnv == NULL)
goto error;
p->atypes[i] = _ctypes_get_ffi_type(cnv);
Py_DECREF(cnv);
}
p->atypes[i] = NULL;
Py_INCREF(restype);
p->restype = restype;
if (restype == Py_None) {
p->setfunc = NULL;
p->ffi_restype = &ffi_type_void;
} else {
StgDictObject *dict = PyType_stgdict(restype);
if (dict == NULL || dict->setfunc == NULL) {
PyErr_SetString(PyExc_TypeError,
"invalid result type for callback function");
goto error;
}
p->setfunc = dict->setfunc;
p->ffi_restype = &dict->ffi_type_pointer;
}
Py_INCREF(restype);
p->restype = restype;
if (restype == Py_None) {
p->setfunc = NULL;
p->ffi_restype = &ffi_type_void;
} else {
StgDictObject *dict = PyType_stgdict(restype);
if (dict == NULL || dict->setfunc == NULL) {
PyErr_SetString(PyExc_TypeError,
"invalid result type for callback function");
goto error;
}
p->setfunc = dict->setfunc;
p->ffi_restype = &dict->ffi_type_pointer;
}
cc = FFI_DEFAULT_ABI;
cc = FFI_DEFAULT_ABI;
#if defined(MS_WIN32) && !defined(_WIN32_WCE) && !defined(MS_WIN64)
if ((flags & FUNCFLAG_CDECL) == 0)
cc = FFI_STDCALL;
if ((flags & FUNCFLAG_CDECL) == 0)
cc = FFI_STDCALL;
#endif
result = ffi_prep_cif(&p->cif, cc,
Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int),
_ctypes_get_ffi_type(restype),
&p->atypes[0]);
if (result != FFI_OK) {
PyErr_Format(PyExc_RuntimeError,
"ffi_prep_cif failed with %d", result);
goto error;
}
result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p);
if (result != FFI_OK) {
PyErr_Format(PyExc_RuntimeError,
"ffi_prep_closure failed with %d", result);
goto error;
}
result = ffi_prep_cif(&p->cif, cc,
Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int),
_ctypes_get_ffi_type(restype),
&p->atypes[0]);
if (result != FFI_OK) {
PyErr_Format(PyExc_RuntimeError,
"ffi_prep_cif failed with %d", result);
goto error;
}
result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p);
if (result != FFI_OK) {
PyErr_Format(PyExc_RuntimeError,
"ffi_prep_closure failed with %d", result);
goto error;
}
Py_INCREF(converters);
p->converters = converters;
Py_INCREF(callable);
p->callable = callable;
return p;
Py_INCREF(converters);
p->converters = converters;
Py_INCREF(callable);
p->callable = callable;
return p;
error:
Py_XDECREF(p);
return NULL;
Py_XDECREF(p);
return NULL;
}
#ifdef MS_WIN32
static void LoadPython(void)
{
if (!Py_IsInitialized()) {
if (!Py_IsInitialized()) {
#ifdef WITH_THREAD
PyEval_InitThreads();
PyEval_InitThreads();
#endif
Py_Initialize();
}
Py_Initialize();
}
}
/******************************************************************/
long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
{
PyObject *mod, *func, *result;
long retval;
static PyObject *context;
PyObject *mod, *func, *result;
long retval;
static PyObject *context;
if (context == NULL)
context = PyUnicode_InternFromString("_ctypes.DllGetClassObject");
if (context == NULL)
context = PyUnicode_InternFromString("_ctypes.DllGetClassObject");
mod = PyImport_ImportModuleNoBlock("ctypes");
if (!mod) {
PyErr_WriteUnraisable(context ? context : Py_None);
/* There has been a warning before about this already */
return E_FAIL;
}
mod = PyImport_ImportModuleNoBlock("ctypes");
if (!mod) {
PyErr_WriteUnraisable(context ? context : Py_None);
/* There has been a warning before about this already */
return E_FAIL;
}
func = PyObject_GetAttrString(mod, "DllGetClassObject");
Py_DECREF(mod);
if (!func) {
PyErr_WriteUnraisable(context ? context : Py_None);
return E_FAIL;
}
func = PyObject_GetAttrString(mod, "DllGetClassObject");
Py_DECREF(mod);
if (!func) {
PyErr_WriteUnraisable(context ? context : Py_None);
return E_FAIL;
}
{
PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid);
PyObject *py_riid = PyLong_FromVoidPtr((void *)riid);
PyObject *py_ppv = PyLong_FromVoidPtr(ppv);
if (!py_rclsid || !py_riid || !py_ppv) {
Py_XDECREF(py_rclsid);
Py_XDECREF(py_riid);
Py_XDECREF(py_ppv);
Py_DECREF(func);
PyErr_WriteUnraisable(context ? context : Py_None);
return E_FAIL;
}
result = PyObject_CallFunctionObjArgs(func,
py_rclsid,
py_riid,
py_ppv,
NULL);
Py_DECREF(py_rclsid);
Py_DECREF(py_riid);
Py_DECREF(py_ppv);
}
Py_DECREF(func);
if (!result) {
PyErr_WriteUnraisable(context ? context : Py_None);
return E_FAIL;
}
{
PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid);
PyObject *py_riid = PyLong_FromVoidPtr((void *)riid);
PyObject *py_ppv = PyLong_FromVoidPtr(ppv);
if (!py_rclsid || !py_riid || !py_ppv) {
Py_XDECREF(py_rclsid);
Py_XDECREF(py_riid);
Py_XDECREF(py_ppv);
Py_DECREF(func);
PyErr_WriteUnraisable(context ? context : Py_None);
return E_FAIL;
}
result = PyObject_CallFunctionObjArgs(func,
py_rclsid,
py_riid,
py_ppv,
NULL);
Py_DECREF(py_rclsid);
Py_DECREF(py_riid);
Py_DECREF(py_ppv);
}
Py_DECREF(func);
if (!result) {
PyErr_WriteUnraisable(context ? context : Py_None);
return E_FAIL;
}
retval = PyLong_AsLong(result);
if (PyErr_Occurred()) {
PyErr_WriteUnraisable(context ? context : Py_None);
retval = E_FAIL;
}
Py_DECREF(result);
return retval;
retval = PyLong_AsLong(result);
if (PyErr_Occurred()) {
PyErr_WriteUnraisable(context ? context : Py_None);
retval = E_FAIL;
}
Py_DECREF(result);
return retval;
}
STDAPI DllGetClassObject(REFCLSID rclsid,
REFIID riid,
LPVOID *ppv)
REFIID riid,
LPVOID *ppv)
{
long result;
long result;
#ifdef WITH_THREAD
PyGILState_STATE state;
PyGILState_STATE state;
#endif
LoadPython();
LoadPython();
#ifdef WITH_THREAD
state = PyGILState_Ensure();
state = PyGILState_Ensure();
#endif
result = Call_GetClassObject(rclsid, riid, ppv);
result = Call_GetClassObject(rclsid, riid, ppv);
#ifdef WITH_THREAD
PyGILState_Release(state);
PyGILState_Release(state);
#endif
return result;
return result;
}
long Call_CanUnloadNow(void)
{
PyObject *mod, *func, *result;
long retval;
static PyObject *context;
PyObject *mod, *func, *result;
long retval;
static PyObject *context;
if (context == NULL)
context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow");
if (context == NULL)
context = PyUnicode_InternFromString("_ctypes.DllCanUnloadNow");
mod = PyImport_ImportModuleNoBlock("ctypes");
if (!mod) {
/* OutputDebugString("Could not import ctypes"); */
/* We assume that this error can only occur when shutting
down, so we silently ignore it */
PyErr_Clear();
return E_FAIL;
}
/* Other errors cannot be raised, but are printed to stderr */
func = PyObject_GetAttrString(mod, "DllCanUnloadNow");
Py_DECREF(mod);
if (!func) {
PyErr_WriteUnraisable(context ? context : Py_None);
return E_FAIL;
}
mod = PyImport_ImportModuleNoBlock("ctypes");
if (!mod) {
/* OutputDebugString("Could not import ctypes"); */
/* We assume that this error can only occur when shutting
down, so we silently ignore it */
PyErr_Clear();
return E_FAIL;
}
/* Other errors cannot be raised, but are printed to stderr */
func = PyObject_GetAttrString(mod, "DllCanUnloadNow");
Py_DECREF(mod);
if (!func) {
PyErr_WriteUnraisable(context ? context : Py_None);
return E_FAIL;
}
result = PyObject_CallFunction(func, NULL);
Py_DECREF(func);
if (!result) {
PyErr_WriteUnraisable(context ? context : Py_None);
return E_FAIL;
}
result = PyObject_CallFunction(func, NULL);
Py_DECREF(func);
if (!result) {
PyErr_WriteUnraisable(context ? context : Py_None);
return E_FAIL;
}
retval = PyLong_AsLong(result);
if (PyErr_Occurred()) {
PyErr_WriteUnraisable(context ? context : Py_None);
retval = E_FAIL;
}
Py_DECREF(result);
return retval;
retval = PyLong_AsLong(result);
if (PyErr_Occurred()) {
PyErr_WriteUnraisable(context ? context : Py_None);
retval = E_FAIL;
}
Py_DECREF(result);
return retval;
}
/*
@ -572,26 +572,26 @@ long Call_CanUnloadNow(void)
STDAPI DllCanUnloadNow(void)
{
long result;
long result;
#ifdef WITH_THREAD
PyGILState_STATE state = PyGILState_Ensure();
PyGILState_STATE state = PyGILState_Ensure();
#endif
result = Call_CanUnloadNow();
result = Call_CanUnloadNow();
#ifdef WITH_THREAD
PyGILState_Release(state);
PyGILState_Release(state);
#endif
return result;
return result;
}
#ifndef Py_NO_ENABLE_SHARED
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvRes)
{
switch(fdwReason) {
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hinstDLL);
break;
}
return TRUE;
switch(fdwReason) {
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hinstDLL);
break;
}
return TRUE;
}
#endif

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -21,16 +21,16 @@ Making CDataObject a variable size object would be a better solution, but more
difficult in the presence of PyCFuncPtrObject. Maybe later.
*/
union value {
char c[16];
short s;
int i;
long l;
float f;
double d;
char c[16];
short s;
int i;
long l;
float f;
double d;
#ifdef HAVE_LONG_LONG
PY_LONG_LONG ll;
PY_LONG_LONG ll;
#endif
long double D;
long double D;
};
/*
@ -40,67 +40,67 @@ union value {
*/
struct tagCDataObject {
PyObject_HEAD
char *b_ptr; /* pointer to memory block */
int b_needsfree; /* need _we_ free the memory? */
CDataObject *b_base; /* pointer to base object or NULL */
Py_ssize_t b_size; /* size of memory block in bytes */
Py_ssize_t b_length; /* number of references we need */
Py_ssize_t b_index; /* index of this object into base's
b_object list */
PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */
union value b_value;
PyObject_HEAD
char *b_ptr; /* pointer to memory block */
int b_needsfree; /* need _we_ free the memory? */
CDataObject *b_base; /* pointer to base object or NULL */
Py_ssize_t b_size; /* size of memory block in bytes */
Py_ssize_t b_length; /* number of references we need */
Py_ssize_t b_index; /* index of this object into base's
b_object list */
PyObject *b_objects; /* dictionary of references we need to keep, or Py_None */
union value b_value;
};
typedef struct {
PyObject_VAR_HEAD
ffi_closure *pcl; /* the C callable */
ffi_cif cif;
int flags;
PyObject *converters;
PyObject *callable;
PyObject *restype;
SETFUNC setfunc;
ffi_type *ffi_restype;
ffi_type *atypes[1];
PyObject_VAR_HEAD
ffi_closure *pcl; /* the C callable */
ffi_cif cif;
int flags;
PyObject *converters;
PyObject *callable;
PyObject *restype;
SETFUNC setfunc;
ffi_type *ffi_restype;
ffi_type *atypes[1];
} CThunkObject;
extern PyTypeObject PyCThunk_Type;
#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type)
#define CThunk_CheckExact(v) ((v)->ob_type == &PyCThunk_Type)
typedef struct {
/* First part identical to tagCDataObject */
PyObject_HEAD
char *b_ptr; /* pointer to memory block */
int b_needsfree; /* need _we_ free the memory? */
CDataObject *b_base; /* pointer to base object or NULL */
Py_ssize_t b_size; /* size of memory block in bytes */
Py_ssize_t b_length; /* number of references we need */
Py_ssize_t b_index; /* index of this object into base's
b_object list */
PyObject *b_objects; /* list of references we need to keep */
union value b_value;
/* end of tagCDataObject, additional fields follow */
/* First part identical to tagCDataObject */
PyObject_HEAD
char *b_ptr; /* pointer to memory block */
int b_needsfree; /* need _we_ free the memory? */
CDataObject *b_base; /* pointer to base object or NULL */
Py_ssize_t b_size; /* size of memory block in bytes */
Py_ssize_t b_length; /* number of references we need */
Py_ssize_t b_index; /* index of this object into base's
b_object list */
PyObject *b_objects; /* list of references we need to keep */
union value b_value;
/* end of tagCDataObject, additional fields follow */
CThunkObject *thunk;
PyObject *callable;
CThunkObject *thunk;
PyObject *callable;
/* These two fields will override the ones in the type's stgdict if
they are set */
PyObject *converters;
PyObject *argtypes;
PyObject *restype;
PyObject *checker;
PyObject *errcheck;
/* These two fields will override the ones in the type's stgdict if
they are set */
PyObject *converters;
PyObject *argtypes;
PyObject *restype;
PyObject *checker;
PyObject *errcheck;
#ifdef MS_WIN32
int index;
GUID *iid;
int index;
GUID *iid;
#endif
PyObject *paramflags;
PyObject *paramflags;
} PyCFuncPtrObject;
extern PyTypeObject PyCStgDict_Type;
#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type)
#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type)
#define PyCStgDict_CheckExact(v) ((v)->ob_type == &PyCStgDict_Type)
#define PyCStgDict_Check(v) PyObject_TypeCheck(v, &PyCStgDict_Type)
extern int PyCStructUnionType_update_stgdict(PyObject *fields, PyObject *type, int isStruct);
extern int PyType_stginfo(PyTypeObject *self, Py_ssize_t *psize, Py_ssize_t *palign, Py_ssize_t *plength);
@ -109,12 +109,12 @@ extern int PyObject_stginfo(PyObject *self, Py_ssize_t *psize, Py_ssize_t *palig
extern PyTypeObject PyCData_Type;
#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type)
#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type)
#define CDataObject_CheckExact(v) ((v)->ob_type == &PyCData_Type)
#define CDataObject_Check(v) PyObject_TypeCheck(v, &PyCData_Type)
extern PyTypeObject PyCSimpleType_Type;
#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type)
#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type)
#define PyCSimpleTypeObject_CheckExact(v) ((v)->ob_type == &PyCSimpleType_Type)
#define PyCSimpleTypeObject_Check(v) PyObject_TypeCheck(v, &PyCSimpleType_Type)
extern PyTypeObject PyCField_Type;
extern struct fielddesc *_ctypes_get_fielddesc(const char *fmt);
@ -122,9 +122,9 @@ extern struct fielddesc *_ctypes_get_fielddesc(const char *fmt);
extern PyObject *
PyCField_FromDesc(PyObject *desc, Py_ssize_t index,
Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
int pack, int is_big_endian);
Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
int pack, int is_big_endian);
extern PyObject *PyCData_AtAddress(PyObject *type, void *buf);
extern PyObject *PyCData_FromBytes(PyObject *type, char *data, Py_ssize_t length);
@ -137,13 +137,13 @@ extern PyTypeObject PyCFuncPtr_Type;
extern PyTypeObject PyCFuncPtrType_Type;
extern PyTypeObject PyCStructType_Type;
#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type)
#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type)
#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type)
#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type)
#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type)
#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type)
#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type)
#define PyCArrayTypeObject_Check(v) PyObject_TypeCheck(v, &PyCArrayType_Type)
#define ArrayObject_Check(v) PyObject_TypeCheck(v, &PyCArray_Type)
#define PointerObject_Check(v) PyObject_TypeCheck(v, &PyCPointer_Type)
#define PyCPointerTypeObject_Check(v) PyObject_TypeCheck(v, &PyCPointerType_Type)
#define PyCFuncPtrObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtr_Type)
#define PyCFuncPtrTypeObject_Check(v) PyObject_TypeCheck(v, &PyCFuncPtrType_Type)
#define PyCStructTypeObject_Check(v) PyObject_TypeCheck(v, &PyCStructType_Type)
extern PyObject *
PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length);
@ -151,35 +151,35 @@ PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length);
extern PyMethodDef _ctypes_module_methods[];
extern CThunkObject *_ctypes_alloc_callback(PyObject *callable,
PyObject *converters,
PyObject *restype,
int flags);
PyObject *converters,
PyObject *restype,
int flags);
/* a table entry describing a predefined ctypes type */
struct fielddesc {
char code;
SETFUNC setfunc;
GETFUNC getfunc;
ffi_type *pffi_type; /* always statically allocated */
SETFUNC setfunc_swapped;
GETFUNC getfunc_swapped;
char code;
SETFUNC setfunc;
GETFUNC getfunc;
ffi_type *pffi_type; /* always statically allocated */
SETFUNC setfunc_swapped;
GETFUNC getfunc_swapped;
};
typedef struct {
PyObject_HEAD
Py_ssize_t offset;
Py_ssize_t size;
Py_ssize_t index; /* Index into CDataObject's
object array */
PyObject *proto; /* a type or NULL */
GETFUNC getfunc; /* getter function if proto is NULL */
SETFUNC setfunc; /* setter function if proto is NULL */
int anonymous;
PyObject_HEAD
Py_ssize_t offset;
Py_ssize_t size;
Py_ssize_t index; /* Index into CDataObject's
object array */
PyObject *proto; /* a type or NULL */
GETFUNC getfunc; /* getter function if proto is NULL */
SETFUNC setfunc; /* setter function if proto is NULL */
int anonymous;
} CFieldObject;
/* A subclass of PyDictObject, used as the instance dictionary of ctypes
metatypes */
typedef struct {
PyDictObject dict; /* first part identical to PyDictObject */
PyDictObject dict; /* first part identical to PyDictObject */
/* The size and align fields are unneeded, they are in ffi_type as well. As
an experiment shows, it's trivial to get rid of them, the only thing to
remember is that in PyCArrayType_new the ffi_type fields must be filled in -
@ -188,28 +188,28 @@ typedef struct {
too much risk to change that now, and there are other fields which doen't
belong into this structure anyway. Maybe in ctypes 2.0... (ctypes 2000?)
*/
Py_ssize_t size; /* number of bytes */
Py_ssize_t align; /* alignment requirements */
Py_ssize_t length; /* number of fields */
ffi_type ffi_type_pointer;
PyObject *proto; /* Only for Pointer/ArrayObject */
SETFUNC setfunc; /* Only for simple objects */
GETFUNC getfunc; /* Only for simple objects */
PARAMFUNC paramfunc;
Py_ssize_t size; /* number of bytes */
Py_ssize_t align; /* alignment requirements */
Py_ssize_t length; /* number of fields */
ffi_type ffi_type_pointer;
PyObject *proto; /* Only for Pointer/ArrayObject */
SETFUNC setfunc; /* Only for simple objects */
GETFUNC getfunc; /* Only for simple objects */
PARAMFUNC paramfunc;
/* Following fields only used by PyCFuncPtrType_Type instances */
PyObject *argtypes; /* tuple of CDataObjects */
PyObject *converters; /* tuple([t.from_param for t in argtypes]) */
PyObject *restype; /* CDataObject or NULL */
PyObject *checker;
int flags; /* calling convention and such */
/* Following fields only used by PyCFuncPtrType_Type instances */
PyObject *argtypes; /* tuple of CDataObjects */
PyObject *converters; /* tuple([t.from_param for t in argtypes]) */
PyObject *restype; /* CDataObject or NULL */
PyObject *checker;
int flags; /* calling convention and such */
/* pep3118 fields, pointers neeed PyMem_Free */
char *format;
int ndim;
Py_ssize_t *shape;
/* Py_ssize_t *strides; */ /* unused in ctypes */
/* Py_ssize_t *suboffsets; */ /* unused in ctypes */
/* pep3118 fields, pointers neeed PyMem_Free */
char *format;
int ndim;
Py_ssize_t *shape;
/* Py_ssize_t *strides; */ /* unused in ctypes */
/* Py_ssize_t *suboffsets; */ /* unused in ctypes */
} StgDictObject;
@ -264,16 +264,16 @@ extern int PyCStgDict_clone(StgDictObject *src, StgDictObject *dst);
typedef int(* PPROC)(void);
PyObject *_ctypes_callproc(PPROC pProc,
PyObject *arguments,
PyObject *arguments,
#ifdef MS_WIN32
IUnknown *pIUnk,
GUID *iid,
IUnknown *pIUnk,
GUID *iid,
#endif
int flags,
PyObject *argtypes,
PyObject *restype,
PyObject *checker);
int flags,
PyObject *argtypes,
PyObject *restype,
PyObject *checker);
#define FUNCFLAG_STDCALL 0x0
#define FUNCFLAG_CDECL 0x1
@ -288,45 +288,45 @@ PyObject *_ctypes_callproc(PPROC pProc,
#define DICTFLAG_FINAL 0x1000
struct tagPyCArgObject {
PyObject_HEAD
ffi_type *pffi_type;
char tag;
union {
char c;
char b;
short h;
int i;
long l;
PyObject_HEAD
ffi_type *pffi_type;
char tag;
union {
char c;
char b;
short h;
int i;
long l;
#ifdef HAVE_LONG_LONG
PY_LONG_LONG q;
PY_LONG_LONG q;
#endif
long double D;
double d;
float f;
void *p;
} value;
PyObject *obj;
Py_ssize_t size; /* for the 'V' tag */
long double D;
double d;
float f;
void *p;
} value;
PyObject *obj;
Py_ssize_t size; /* for the 'V' tag */
};
extern PyTypeObject PyCArg_Type;
#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type)
#define PyCArg_CheckExact(v) ((v)->ob_type == &PyCArg_Type)
extern PyCArgObject *PyCArgObject_new(void);
extern PyObject *
PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
Py_ssize_t index, Py_ssize_t size, char *ptr);
Py_ssize_t index, Py_ssize_t size, char *ptr);
extern int
PyCData_set(PyObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
Py_ssize_t index, Py_ssize_t size, char *ptr);
Py_ssize_t index, Py_ssize_t size, char *ptr);
extern void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...);
struct basespec {
CDataObject *base;
Py_ssize_t index;
char *adr;
CDataObject *base;
Py_ssize_t index;
char *adr;
};
extern char basespec_string[];

View file

@ -81,167 +81,167 @@ static const char *error(int setget, const char *str, ...);
/* Set and get the error string for use by dlerror */
static const char *error(int setget, const char *str, ...)
{
static char errstr[ERR_STR_LEN];
static int err_filled = 0;
const char *retval;
va_list arg;
if (setget == 0)
{
va_start(arg, str);
strncpy(errstr, "dlcompat: ", ERR_STR_LEN);
vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg);
va_end(arg);
err_filled = 1;
retval = NULL;
}
else
{
if (!err_filled)
retval = NULL;
else
retval = errstr;
err_filled = 0;
}
return retval;
static char errstr[ERR_STR_LEN];
static int err_filled = 0;
const char *retval;
va_list arg;
if (setget == 0)
{
va_start(arg, str);
strncpy(errstr, "dlcompat: ", ERR_STR_LEN);
vsnprintf(errstr + 10, ERR_STR_LEN - 10, str, arg);
va_end(arg);
err_filled = 1;
retval = NULL;
}
else
{
if (!err_filled)
retval = NULL;
else
retval = errstr;
err_filled = 0;
}
return retval;
}
/* darwin_dlopen */
static void *darwin_dlopen(const char *path, int mode)
{
void *module = 0;
NSObjectFileImage ofi = 0;
NSObjectFileImageReturnCode ofirc;
void *module = 0;
NSObjectFileImage ofi = 0;
NSObjectFileImageReturnCode ofirc;
/* If we got no path, the app wants the global namespace, use -1 as the marker
in this case */
if (!path)
return (void *)-1;
/* If we got no path, the app wants the global namespace, use -1 as the marker
in this case */
if (!path)
return (void *)-1;
/* Create the object file image, works for things linked with the -bundle arg to ld */
ofirc = NSCreateObjectFileImageFromFile(path, &ofi);
switch (ofirc)
{
case NSObjectFileImageSuccess:
/* It was okay, so use NSLinkModule to link in the image */
module = NSLinkModule(ofi, path,
NSLINKMODULE_OPTION_RETURN_ON_ERROR
| (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE
| (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW);
NSDestroyObjectFileImage(ofi);
break;
case NSObjectFileImageInappropriateFile:
/* It may have been a dynamic library rather than a bundle, try to load it */
module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
break;
default:
/* God knows what we got */
error(0, "Can not open \"%s\"", path);
return 0;
}
if (!module)
error(0, "Can not open \"%s\"", path);
return module;
/* Create the object file image, works for things linked with the -bundle arg to ld */
ofirc = NSCreateObjectFileImageFromFile(path, &ofi);
switch (ofirc)
{
case NSObjectFileImageSuccess:
/* It was okay, so use NSLinkModule to link in the image */
module = NSLinkModule(ofi, path,
NSLINKMODULE_OPTION_RETURN_ON_ERROR
| (mode & RTLD_GLOBAL) ? 0 : NSLINKMODULE_OPTION_PRIVATE
| (mode & RTLD_LAZY) ? 0 : NSLINKMODULE_OPTION_BINDNOW);
NSDestroyObjectFileImage(ofi);
break;
case NSObjectFileImageInappropriateFile:
/* It may have been a dynamic library rather than a bundle, try to load it */
module = (void *)NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
break;
default:
/* God knows what we got */
error(0, "Can not open \"%s\"", path);
return 0;
}
if (!module)
error(0, "Can not open \"%s\"", path);
return module;
}
/* dlsymIntern is used by dlsym to find the symbol */
static void *dlsymIntern(void *handle, const char *symbol)
{
NSSymbol nssym = 0;
/* If the handle is -1, if is the app global context */
if (handle == (void *)-1)
{
/* Global context, use NSLookupAndBindSymbol */
if (NSIsSymbolNameDefined(symbol))
{
nssym = NSLookupAndBindSymbol(symbol);
}
NSSymbol nssym = 0;
/* If the handle is -1, if is the app global context */
if (handle == (void *)-1)
{
/* Global context, use NSLookupAndBindSymbol */
if (NSIsSymbolNameDefined(symbol))
{
nssym = NSLookupAndBindSymbol(symbol);
}
}
/* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image
for libraries, and NSLookupSymbolInModule for bundles */
else
{
/* Check for both possible magic numbers depending on x86/ppc byte order */
if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
(((struct mach_header *)handle)->magic == MH_CIGAM))
{
if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol))
{
nssym = NSLookupSymbolInImage((struct mach_header *)handle,
symbol,
NSLOOKUPSYMBOLINIMAGE_OPTION_BIND
| NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
}
}
/* Now see if the handle is a struch mach_header* or not, use NSLookupSymbol in image
for libraries, and NSLookupSymbolInModule for bundles */
else
{
/* Check for both possible magic numbers depending on x86/ppc byte order */
if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
(((struct mach_header *)handle)->magic == MH_CIGAM))
{
if (NSIsSymbolNameDefinedInImage((struct mach_header *)handle, symbol))
{
nssym = NSLookupSymbolInImage((struct mach_header *)handle,
symbol,
NSLOOKUPSYMBOLINIMAGE_OPTION_BIND
| NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
}
}
else
{
nssym = NSLookupSymbolInModule(handle, symbol);
}
}
if (!nssym)
{
error(0, "Symbol \"%s\" Not found", symbol);
return NULL;
}
return NSAddressOfSymbol(nssym);
}
else
{
nssym = NSLookupSymbolInModule(handle, symbol);
}
}
if (!nssym)
{
error(0, "Symbol \"%s\" Not found", symbol);
return NULL;
}
return NSAddressOfSymbol(nssym);
}
static const char *darwin_dlerror(void)
{
return error(1, (char *)NULL);
return error(1, (char *)NULL);
}
static int darwin_dlclose(void *handle)
{
if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
(((struct mach_header *)handle)->magic == MH_CIGAM))
{
error(0, "Can't remove dynamic libraries on darwin");
return 0;
}
if (!NSUnLinkModule(handle, 0))
{
error(0, "unable to unlink module %s", NSNameOfModule(handle));
return 1;
}
return 0;
if ((((struct mach_header *)handle)->magic == MH_MAGIC) ||
(((struct mach_header *)handle)->magic == MH_CIGAM))
{
error(0, "Can't remove dynamic libraries on darwin");
return 0;
}
if (!NSUnLinkModule(handle, 0))
{
error(0, "unable to unlink module %s", NSNameOfModule(handle));
return 1;
}
return 0;
}
/* dlsym, prepend the underscore and call dlsymIntern */
static void *darwin_dlsym(void *handle, const char *symbol)
{
static char undersym[257]; /* Saves calls to malloc(3) */
int sym_len = strlen(symbol);
void *value = NULL;
char *malloc_sym = NULL;
static char undersym[257]; /* Saves calls to malloc(3) */
int sym_len = strlen(symbol);
void *value = NULL;
char *malloc_sym = NULL;
if (sym_len < 256)
{
snprintf(undersym, 256, "_%s", symbol);
value = dlsymIntern(handle, undersym);
}
else
{
malloc_sym = malloc(sym_len + 2);
if (malloc_sym)
{
sprintf(malloc_sym, "_%s", symbol);
value = dlsymIntern(handle, malloc_sym);
free(malloc_sym);
}
else
{
error(0, "Unable to allocate memory");
}
}
return value;
if (sym_len < 256)
{
snprintf(undersym, 256, "_%s", symbol);
value = dlsymIntern(handle, undersym);
}
else
{
malloc_sym = malloc(sym_len + 2);
if (malloc_sym)
{
sprintf(malloc_sym, "_%s", symbol);
value = dlsymIntern(handle, malloc_sym);
free(malloc_sym);
}
else
{
error(0, "Unable to allocate memory");
}
}
return value;
}
static int darwin_dladdr(const void *handle, Dl_info *info) {
return 0;
return 0;
}
#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */
@ -252,21 +252,21 @@ static void __attribute__ ((constructor)) ctypes_dlfcn_init(void);
static
#endif
void ctypes_dlfcn_init(void) {
if (dlopen != NULL) {
ctypes_dlsym = dlsym;
ctypes_dlopen = dlopen;
ctypes_dlerror = dlerror;
ctypes_dlclose = dlclose;
ctypes_dladdr = dladdr;
} else {
if (dlopen != NULL) {
ctypes_dlsym = dlsym;
ctypes_dlopen = dlopen;
ctypes_dlerror = dlerror;
ctypes_dlclose = dlclose;
ctypes_dladdr = dladdr;
} else {
#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3
ctypes_dlsym = darwin_dlsym;
ctypes_dlopen = darwin_dlopen;
ctypes_dlerror = darwin_dlerror;
ctypes_dlclose = darwin_dlclose;
ctypes_dladdr = darwin_dladdr;
ctypes_dlsym = darwin_dlsym;
ctypes_dlopen = darwin_dlopen;
ctypes_dlerror = darwin_dlerror;
ctypes_dlclose = darwin_dlclose;
ctypes_dladdr = darwin_dladdr;
#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3 */
}
}
}
#endif /* CTYPES_DARWIN_DLFCN */

View file

@ -23,8 +23,8 @@
/******************************************************************/
typedef union _tagITEM {
ffi_closure closure;
union _tagITEM *next;
ffi_closure closure;
union _tagITEM *next;
} ITEM;
static ITEM *free_list;
@ -32,58 +32,58 @@ static int _pagesize;
static void more_core(void)
{
ITEM *item;
int count, i;
ITEM *item;
int count, i;
/* determine the pagesize */
#ifdef MS_WIN32
if (!_pagesize) {
SYSTEM_INFO systeminfo;
GetSystemInfo(&systeminfo);
_pagesize = systeminfo.dwPageSize;
}
if (!_pagesize) {
SYSTEM_INFO systeminfo;
GetSystemInfo(&systeminfo);
_pagesize = systeminfo.dwPageSize;
}
#else
if (!_pagesize) {
if (!_pagesize) {
#ifdef _SC_PAGESIZE
_pagesize = sysconf(_SC_PAGESIZE);
_pagesize = sysconf(_SC_PAGESIZE);
#else
_pagesize = getpagesize();
_pagesize = getpagesize();
#endif
}
}
#endif
/* calculate the number of nodes to allocate */
count = BLOCKSIZE / sizeof(ITEM);
/* calculate the number of nodes to allocate */
count = BLOCKSIZE / sizeof(ITEM);
/* allocate a memory block */
/* allocate a memory block */
#ifdef MS_WIN32
item = (ITEM *)VirtualAlloc(NULL,
count * sizeof(ITEM),
MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
if (item == NULL)
return;
item = (ITEM *)VirtualAlloc(NULL,
count * sizeof(ITEM),
MEM_COMMIT,
PAGE_EXECUTE_READWRITE);
if (item == NULL)
return;
#else
item = (ITEM *)mmap(NULL,
count * sizeof(ITEM),
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS,
-1,
0);
if (item == (void *)MAP_FAILED)
return;
item = (ITEM *)mmap(NULL,
count * sizeof(ITEM),
PROT_READ | PROT_WRITE | PROT_EXEC,
MAP_PRIVATE | MAP_ANONYMOUS,
-1,
0);
if (item == (void *)MAP_FAILED)
return;
#endif
#ifdef MALLOC_CLOSURE_DEBUG
printf("block at %p allocated (%d bytes), %d ITEMs\n",
item, count * sizeof(ITEM), count);
printf("block at %p allocated (%d bytes), %d ITEMs\n",
item, count * sizeof(ITEM), count);
#endif
/* put them into the free list */
for (i = 0; i < count; ++i) {
item->next = free_list;
free_list = item;
++item;
}
/* put them into the free list */
for (i = 0; i < count; ++i) {
item->next = free_list;
free_list = item;
++item;
}
}
/******************************************************************/
@ -91,20 +91,20 @@ static void more_core(void)
/* put the item back into the free list */
void _ctypes_free_closure(void *p)
{
ITEM *item = (ITEM *)p;
item->next = free_list;
free_list = item;
ITEM *item = (ITEM *)p;
item->next = free_list;
free_list = item;
}
/* return one item from the free list, allocating more if needed */
void *_ctypes_alloc_closure(void)
{
ITEM *item;
if (!free_list)
more_core();
if (!free_list)
return NULL;
item = free_list;
free_list = item->next;
return item;
ITEM *item;
if (!free_list)
more_core();
if (!free_list)
return NULL;
item = free_list;
free_list = item->next;
return item;
}

View file

@ -19,143 +19,143 @@
static int
PyCStgDict_init(StgDictObject *self, PyObject *args, PyObject *kwds)
{
if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0)
return -1;
self->format = NULL;
self->ndim = 0;
self->shape = NULL;
return 0;
if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0)
return -1;
self->format = NULL;
self->ndim = 0;
self->shape = NULL;
return 0;
}
static int
PyCStgDict_clear(StgDictObject *self)
{
Py_CLEAR(self->proto);
Py_CLEAR(self->argtypes);
Py_CLEAR(self->converters);
Py_CLEAR(self->restype);
Py_CLEAR(self->checker);
return 0;
Py_CLEAR(self->proto);
Py_CLEAR(self->argtypes);
Py_CLEAR(self->converters);
Py_CLEAR(self->restype);
Py_CLEAR(self->checker);
return 0;
}
static void
PyCStgDict_dealloc(StgDictObject *self)
{
PyCStgDict_clear(self);
PyMem_Free(self->format);
PyMem_Free(self->shape);
PyMem_Free(self->ffi_type_pointer.elements);
PyDict_Type.tp_dealloc((PyObject *)self);
PyCStgDict_clear(self);
PyMem_Free(self->format);
PyMem_Free(self->shape);
PyMem_Free(self->ffi_type_pointer.elements);
PyDict_Type.tp_dealloc((PyObject *)self);
}
int
PyCStgDict_clone(StgDictObject *dst, StgDictObject *src)
{
char *d, *s;
Py_ssize_t size;
char *d, *s;
Py_ssize_t size;
PyCStgDict_clear(dst);
PyMem_Free(dst->ffi_type_pointer.elements);
PyMem_Free(dst->format);
dst->format = NULL;
PyMem_Free(dst->shape);
dst->shape = NULL;
dst->ffi_type_pointer.elements = NULL;
PyCStgDict_clear(dst);
PyMem_Free(dst->ffi_type_pointer.elements);
PyMem_Free(dst->format);
dst->format = NULL;
PyMem_Free(dst->shape);
dst->shape = NULL;
dst->ffi_type_pointer.elements = NULL;
d = (char *)dst;
s = (char *)src;
memcpy(d + sizeof(PyDictObject),
s + sizeof(PyDictObject),
sizeof(StgDictObject) - sizeof(PyDictObject));
d = (char *)dst;
s = (char *)src;
memcpy(d + sizeof(PyDictObject),
s + sizeof(PyDictObject),
sizeof(StgDictObject) - sizeof(PyDictObject));
Py_XINCREF(dst->proto);
Py_XINCREF(dst->argtypes);
Py_XINCREF(dst->converters);
Py_XINCREF(dst->restype);
Py_XINCREF(dst->checker);
Py_XINCREF(dst->proto);
Py_XINCREF(dst->argtypes);
Py_XINCREF(dst->converters);
Py_XINCREF(dst->restype);
Py_XINCREF(dst->checker);
if (src->format) {
dst->format = PyMem_Malloc(strlen(src->format) + 1);
if (dst->format == NULL)
return -1;
strcpy(dst->format, src->format);
}
if (src->shape) {
dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim);
if (dst->shape == NULL)
return -1;
memcpy(dst->shape, src->shape,
sizeof(Py_ssize_t) * src->ndim);
}
if (src->format) {
dst->format = PyMem_Malloc(strlen(src->format) + 1);
if (dst->format == NULL)
return -1;
strcpy(dst->format, src->format);
}
if (src->shape) {
dst->shape = PyMem_Malloc(sizeof(Py_ssize_t) * src->ndim);
if (dst->shape == NULL)
return -1;
memcpy(dst->shape, src->shape,
sizeof(Py_ssize_t) * src->ndim);
}
if (src->ffi_type_pointer.elements == NULL)
return 0;
size = sizeof(ffi_type *) * (src->length + 1);
dst->ffi_type_pointer.elements = PyMem_Malloc(size);
if (dst->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memcpy(dst->ffi_type_pointer.elements,
src->ffi_type_pointer.elements,
size);
return 0;
if (src->ffi_type_pointer.elements == NULL)
return 0;
size = sizeof(ffi_type *) * (src->length + 1);
dst->ffi_type_pointer.elements = PyMem_Malloc(size);
if (dst->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memcpy(dst->ffi_type_pointer.elements,
src->ffi_type_pointer.elements,
size);
return 0;
}
PyTypeObject PyCStgDict_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"StgDict",
sizeof(StgDictObject),
0,
(destructor)PyCStgDict_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)PyCStgDict_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0, /* tp_free */
PyVarObject_HEAD_INIT(NULL, 0)
"StgDict",
sizeof(StgDictObject),
0,
(destructor)PyCStgDict_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)PyCStgDict_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0, /* tp_free */
};
/* May return NULL, but does not set an exception! */
StgDictObject *
PyType_stgdict(PyObject *obj)
{
PyTypeObject *type;
PyTypeObject *type;
if (!PyType_Check(obj))
return NULL;
type = (PyTypeObject *)obj;
if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
return NULL;
return (StgDictObject *)type->tp_dict;
if (!PyType_Check(obj))
return NULL;
type = (PyTypeObject *)obj;
if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
return NULL;
return (StgDictObject *)type->tp_dict;
}
/* May return NULL, but does not set an exception! */
@ -166,10 +166,10 @@ PyType_stgdict(PyObject *obj)
StgDictObject *
PyObject_stgdict(PyObject *self)
{
PyTypeObject *type = self->ob_type;
if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
return NULL;
return (StgDictObject *)type->tp_dict;
PyTypeObject *type = self->ob_type;
if (!type->tp_dict || !PyCStgDict_CheckExact(type->tp_dict))
return NULL;
return (StgDictObject *)type->tp_dict;
}
/* descr is the descriptor for a field marked as anonymous. Get all the
@ -178,78 +178,78 @@ PyObject_stgdict(PyObject *self)
*/
static int
MakeFields(PyObject *type, CFieldObject *descr,
Py_ssize_t index, Py_ssize_t offset)
Py_ssize_t index, Py_ssize_t offset)
{
Py_ssize_t i;
PyObject *fields;
PyObject *fieldlist;
Py_ssize_t i;
PyObject *fields;
PyObject *fieldlist;
fields = PyObject_GetAttrString(descr->proto, "_fields_");
if (fields == NULL)
return -1;
fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence");
Py_DECREF(fields);
if (fieldlist == NULL)
return -1;
fields = PyObject_GetAttrString(descr->proto, "_fields_");
if (fields == NULL)
return -1;
fieldlist = PySequence_Fast(fields, "_fields_ must be a sequence");
Py_DECREF(fields);
if (fieldlist == NULL)
return -1;
for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) {
PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */
PyObject *fname, *ftype, *bits;
CFieldObject *fdescr;
CFieldObject *new_descr;
/* Convert to PyArg_UnpackTuple... */
if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) {
Py_DECREF(fieldlist);
return -1;
}
fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname);
if (fdescr == NULL) {
Py_DECREF(fieldlist);
return -1;
}
if (Py_TYPE(fdescr) != &PyCField_Type) {
PyErr_SetString(PyExc_TypeError, "unexpected type");
Py_DECREF(fdescr);
Py_DECREF(fieldlist);
return -1;
}
if (fdescr->anonymous) {
int rc = MakeFields(type, fdescr,
index + fdescr->index,
offset + fdescr->offset);
Py_DECREF(fdescr);
if (rc == -1) {
Py_DECREF(fieldlist);
return -1;
}
continue;
}
new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL);
if (new_descr == NULL) {
Py_DECREF(fdescr);
Py_DECREF(fieldlist);
return -1;
}
assert(Py_TYPE(new_descr) == &PyCField_Type);
new_descr->size = fdescr->size;
new_descr->offset = fdescr->offset + offset;
new_descr->index = fdescr->index + index;
new_descr->proto = fdescr->proto;
Py_XINCREF(new_descr->proto);
new_descr->getfunc = fdescr->getfunc;
new_descr->setfunc = fdescr->setfunc;
for (i = 0; i < PySequence_Fast_GET_SIZE(fieldlist); ++i) {
PyObject *pair = PySequence_Fast_GET_ITEM(fieldlist, i); /* borrowed */
PyObject *fname, *ftype, *bits;
CFieldObject *fdescr;
CFieldObject *new_descr;
/* Convert to PyArg_UnpackTuple... */
if (!PyArg_ParseTuple(pair, "OO|O", &fname, &ftype, &bits)) {
Py_DECREF(fieldlist);
return -1;
}
fdescr = (CFieldObject *)PyObject_GetAttr(descr->proto, fname);
if (fdescr == NULL) {
Py_DECREF(fieldlist);
return -1;
}
if (Py_TYPE(fdescr) != &PyCField_Type) {
PyErr_SetString(PyExc_TypeError, "unexpected type");
Py_DECREF(fdescr);
Py_DECREF(fieldlist);
return -1;
}
if (fdescr->anonymous) {
int rc = MakeFields(type, fdescr,
index + fdescr->index,
offset + fdescr->offset);
Py_DECREF(fdescr);
if (rc == -1) {
Py_DECREF(fieldlist);
return -1;
}
continue;
}
new_descr = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type, NULL);
if (new_descr == NULL) {
Py_DECREF(fdescr);
Py_DECREF(fieldlist);
return -1;
}
assert(Py_TYPE(new_descr) == &PyCField_Type);
new_descr->size = fdescr->size;
new_descr->offset = fdescr->offset + offset;
new_descr->index = fdescr->index + index;
new_descr->proto = fdescr->proto;
Py_XINCREF(new_descr->proto);
new_descr->getfunc = fdescr->getfunc;
new_descr->setfunc = fdescr->setfunc;
Py_DECREF(fdescr);
if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) {
Py_DECREF(fieldlist);
Py_DECREF(new_descr);
return -1;
}
Py_DECREF(new_descr);
}
Py_DECREF(fieldlist);
return 0;
Py_DECREF(fdescr);
if (-1 == PyObject_SetAttr(type, fname, (PyObject *)new_descr)) {
Py_DECREF(fieldlist);
Py_DECREF(new_descr);
return -1;
}
Py_DECREF(new_descr);
}
Py_DECREF(fieldlist);
return 0;
}
/* Iterate over the names in the type's _anonymous_ attribute, if present,
@ -257,43 +257,43 @@ MakeFields(PyObject *type, CFieldObject *descr,
static int
MakeAnonFields(PyObject *type)
{
PyObject *anon;
PyObject *anon_names;
Py_ssize_t i;
PyObject *anon;
PyObject *anon_names;
Py_ssize_t i;
anon = PyObject_GetAttrString(type, "_anonymous_");
if (anon == NULL) {
PyErr_Clear();
return 0;
}
anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence");
Py_DECREF(anon);
if (anon_names == NULL)
return -1;
anon = PyObject_GetAttrString(type, "_anonymous_");
if (anon == NULL) {
PyErr_Clear();
return 0;
}
anon_names = PySequence_Fast(anon, "_anonymous_ must be a sequence");
Py_DECREF(anon);
if (anon_names == NULL)
return -1;
for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) {
PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */
CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname);
if (descr == NULL) {
Py_DECREF(anon_names);
return -1;
}
assert(Py_TYPE(descr) == &PyCField_Type);
descr->anonymous = 1;
for (i = 0; i < PySequence_Fast_GET_SIZE(anon_names); ++i) {
PyObject *fname = PySequence_Fast_GET_ITEM(anon_names, i); /* borrowed */
CFieldObject *descr = (CFieldObject *)PyObject_GetAttr(type, fname);
if (descr == NULL) {
Py_DECREF(anon_names);
return -1;
}
assert(Py_TYPE(descr) == &PyCField_Type);
descr->anonymous = 1;
/* descr is in the field descriptor. */
if (-1 == MakeFields(type, (CFieldObject *)descr,
((CFieldObject *)descr)->index,
((CFieldObject *)descr)->offset)) {
Py_DECREF(descr);
Py_DECREF(anon_names);
return -1;
}
Py_DECREF(descr);
}
/* descr is in the field descriptor. */
if (-1 == MakeFields(type, (CFieldObject *)descr,
((CFieldObject *)descr)->index,
((CFieldObject *)descr)->offset)) {
Py_DECREF(descr);
Py_DECREF(anon_names);
return -1;
}
Py_DECREF(descr);
}
Py_DECREF(anon_names);
return 0;
Py_DECREF(anon_names);
return 0;
}
/*
@ -303,261 +303,261 @@ MakeAnonFields(PyObject *type)
int
PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct)
{
StgDictObject *stgdict, *basedict;
Py_ssize_t len, offset, size, align, i;
Py_ssize_t union_size, total_align;
Py_ssize_t field_size = 0;
int bitofs;
PyObject *isPacked;
int pack = 0;
Py_ssize_t ffi_ofs;
int big_endian;
StgDictObject *stgdict, *basedict;
Py_ssize_t len, offset, size, align, i;
Py_ssize_t union_size, total_align;
Py_ssize_t field_size = 0;
int bitofs;
PyObject *isPacked;
int pack = 0;
Py_ssize_t ffi_ofs;
int big_endian;
/* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to
be a way to use the old, broken sematics: _fields_ are not extended
but replaced in subclasses.
XXX Remove this in ctypes 1.0!
*/
int use_broken_old_ctypes_semantics;
/* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to
be a way to use the old, broken sematics: _fields_ are not extended
but replaced in subclasses.
if (fields == NULL)
return 0;
XXX Remove this in ctypes 1.0!
*/
int use_broken_old_ctypes_semantics;
if (fields == NULL)
return 0;
#ifdef WORDS_BIGENDIAN
big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1;
big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1;
#else
big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0;
big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0;
#endif
use_broken_old_ctypes_semantics = \
PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_");
use_broken_old_ctypes_semantics = \
PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_");
isPacked = PyObject_GetAttrString(type, "_pack_");
if (isPacked) {
pack = PyLong_AsLong(isPacked);
if (pack < 0 || PyErr_Occurred()) {
Py_XDECREF(isPacked);
PyErr_SetString(PyExc_ValueError,
"_pack_ must be a non-negative integer");
return -1;
}
Py_DECREF(isPacked);
} else
PyErr_Clear();
isPacked = PyObject_GetAttrString(type, "_pack_");
if (isPacked) {
pack = PyLong_AsLong(isPacked);
if (pack < 0 || PyErr_Occurred()) {
Py_XDECREF(isPacked);
PyErr_SetString(PyExc_ValueError,
"_pack_ must be a non-negative integer");
return -1;
}
Py_DECREF(isPacked);
} else
PyErr_Clear();
len = PySequence_Length(fields);
if (len == -1) {
PyErr_SetString(PyExc_TypeError,
"'_fields_' must be a sequence of pairs");
return -1;
}
len = PySequence_Length(fields);
if (len == -1) {
PyErr_SetString(PyExc_TypeError,
"'_fields_' must be a sequence of pairs");
return -1;
}
stgdict = PyType_stgdict(type);
if (!stgdict)
return -1;
/* If this structure/union is already marked final we cannot assign
_fields_ anymore. */
stgdict = PyType_stgdict(type);
if (!stgdict)
return -1;
/* If this structure/union is already marked final we cannot assign
_fields_ anymore. */
if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */
PyErr_SetString(PyExc_AttributeError,
"_fields_ is final");
return -1;
}
if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */
PyErr_SetString(PyExc_AttributeError,
"_fields_ is final");
return -1;
}
if (stgdict->format) {
PyMem_Free(stgdict->format);
stgdict->format = NULL;
}
if (stgdict->format) {
PyMem_Free(stgdict->format);
stgdict->format = NULL;
}
if (stgdict->ffi_type_pointer.elements)
PyMem_Free(stgdict->ffi_type_pointer.elements);
if (stgdict->ffi_type_pointer.elements)
PyMem_Free(stgdict->ffi_type_pointer.elements);
basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base);
if (basedict && !use_broken_old_ctypes_semantics) {
size = offset = basedict->size;
align = basedict->align;
union_size = 0;
total_align = align ? align : 1;
stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
if (stgdict->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memset(stgdict->ffi_type_pointer.elements, 0,
sizeof(ffi_type *) * (basedict->length + len + 1));
memcpy(stgdict->ffi_type_pointer.elements,
basedict->ffi_type_pointer.elements,
sizeof(ffi_type *) * (basedict->length));
ffi_ofs = basedict->length;
} else {
offset = 0;
size = 0;
align = 0;
union_size = 0;
total_align = 1;
stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
if (stgdict->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memset(stgdict->ffi_type_pointer.elements, 0,
sizeof(ffi_type *) * (len + 1));
ffi_ofs = 0;
}
basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base);
if (basedict && !use_broken_old_ctypes_semantics) {
size = offset = basedict->size;
align = basedict->align;
union_size = 0;
total_align = align ? align : 1;
stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
if (stgdict->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memset(stgdict->ffi_type_pointer.elements, 0,
sizeof(ffi_type *) * (basedict->length + len + 1));
memcpy(stgdict->ffi_type_pointer.elements,
basedict->ffi_type_pointer.elements,
sizeof(ffi_type *) * (basedict->length));
ffi_ofs = basedict->length;
} else {
offset = 0;
size = 0;
align = 0;
union_size = 0;
total_align = 1;
stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
if (stgdict->ffi_type_pointer.elements == NULL) {
PyErr_NoMemory();
return -1;
}
memset(stgdict->ffi_type_pointer.elements, 0,
sizeof(ffi_type *) * (len + 1));
ffi_ofs = 0;
}
assert(stgdict->format == NULL);
if (isStruct && !isPacked) {
stgdict->format = _ctypes_alloc_format_string(NULL, "T{");
} else {
/* PEP3118 doesn't support union, or packed structures (well,
only standard packing, but we dont support the pep for
that). Use 'B' for bytes. */
stgdict->format = _ctypes_alloc_format_string(NULL, "B");
}
assert(stgdict->format == NULL);
if (isStruct && !isPacked) {
stgdict->format = _ctypes_alloc_format_string(NULL, "T{");
} else {
/* PEP3118 doesn't support union, or packed structures (well,
only standard packing, but we dont support the pep for
that). Use 'B' for bytes. */
stgdict->format = _ctypes_alloc_format_string(NULL, "B");
}
#define realdict ((PyObject *)&stgdict->dict)
for (i = 0; i < len; ++i) {
PyObject *name = NULL, *desc = NULL;
PyObject *pair = PySequence_GetItem(fields, i);
PyObject *prop;
StgDictObject *dict;
int bitsize = 0;
for (i = 0; i < len; ++i) {
PyObject *name = NULL, *desc = NULL;
PyObject *pair = PySequence_GetItem(fields, i);
PyObject *prop;
StgDictObject *dict;
int bitsize = 0;
if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) {
PyErr_SetString(PyExc_AttributeError,
"'_fields_' must be a sequence of pairs");
Py_XDECREF(pair);
return -1;
}
dict = PyType_stgdict(desc);
if (dict == NULL) {
Py_DECREF(pair);
PyErr_Format(PyExc_TypeError,
"second item in _fields_ tuple (index %zd) must be a C type",
i);
return -1;
}
stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer;
if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
stgdict->flags |= TYPEFLAG_HASPOINTER;
dict->flags |= DICTFLAG_FINAL; /* mark field type final */
if (PyTuple_Size(pair) == 3) { /* bits specified */
switch(dict->ffi_type_pointer.type) {
case FFI_TYPE_UINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT64:
case FFI_TYPE_UINT64:
break;
if (!pair || !PyArg_ParseTuple(pair, "OO|i", &name, &desc, &bitsize)) {
PyErr_SetString(PyExc_AttributeError,
"'_fields_' must be a sequence of pairs");
Py_XDECREF(pair);
return -1;
}
dict = PyType_stgdict(desc);
if (dict == NULL) {
Py_DECREF(pair);
PyErr_Format(PyExc_TypeError,
"second item in _fields_ tuple (index %zd) must be a C type",
i);
return -1;
}
stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer;
if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
stgdict->flags |= TYPEFLAG_HASPOINTER;
dict->flags |= DICTFLAG_FINAL; /* mark field type final */
if (PyTuple_Size(pair) == 3) { /* bits specified */
switch(dict->ffi_type_pointer.type) {
case FFI_TYPE_UINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT64:
case FFI_TYPE_UINT64:
break;
case FFI_TYPE_SINT8:
case FFI_TYPE_SINT16:
case FFI_TYPE_SINT32:
if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc
case FFI_TYPE_SINT8:
case FFI_TYPE_SINT16:
case FFI_TYPE_SINT32:
if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc
#ifdef CTYPES_UNICODE
&& dict->getfunc != _ctypes_get_fielddesc("u")->getfunc
&& dict->getfunc != _ctypes_get_fielddesc("u")->getfunc
#endif
)
break;
/* else fall through */
default:
PyErr_Format(PyExc_TypeError,
"bit fields not allowed for type %s",
((PyTypeObject *)desc)->tp_name);
Py_DECREF(pair);
return -1;
}
if (bitsize <= 0 || bitsize > dict->size * 8) {
PyErr_SetString(PyExc_ValueError,
"number of bits invalid for bit field");
Py_DECREF(pair);
return -1;
}
} else
bitsize = 0;
if (isStruct && !isPacked) {
char *fieldfmt = dict->format ? dict->format : "B";
char *fieldname = _PyUnicode_AsString(name);
char *ptr;
Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt);
char *buf = alloca(len + 2 + 1);
)
break;
/* else fall through */
default:
PyErr_Format(PyExc_TypeError,
"bit fields not allowed for type %s",
((PyTypeObject *)desc)->tp_name);
Py_DECREF(pair);
return -1;
}
if (bitsize <= 0 || bitsize > dict->size * 8) {
PyErr_SetString(PyExc_ValueError,
"number of bits invalid for bit field");
Py_DECREF(pair);
return -1;
}
} else
bitsize = 0;
if (isStruct && !isPacked) {
char *fieldfmt = dict->format ? dict->format : "B";
char *fieldname = _PyUnicode_AsString(name);
char *ptr;
Py_ssize_t len = strlen(fieldname) + strlen(fieldfmt);
char *buf = alloca(len + 2 + 1);
sprintf(buf, "%s:%s:", fieldfmt, fieldname);
sprintf(buf, "%s:%s:", fieldfmt, fieldname);
ptr = stgdict->format;
stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf);
PyMem_Free(ptr);
ptr = stgdict->format;
stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf);
PyMem_Free(ptr);
if (stgdict->format == NULL) {
Py_DECREF(pair);
return -1;
}
}
if (isStruct) {
prop = PyCField_FromDesc(desc, i,
&field_size, bitsize, &bitofs,
&size, &offset, &align,
pack, big_endian);
} else /* union */ {
size = 0;
offset = 0;
align = 0;
prop = PyCField_FromDesc(desc, i,
&field_size, bitsize, &bitofs,
&size, &offset, &align,
pack, big_endian);
union_size = max(size, union_size);
}
total_align = max(align, total_align);
if (stgdict->format == NULL) {
Py_DECREF(pair);
return -1;
}
}
if (isStruct) {
prop = PyCField_FromDesc(desc, i,
&field_size, bitsize, &bitofs,
&size, &offset, &align,
pack, big_endian);
} else /* union */ {
size = 0;
offset = 0;
align = 0;
prop = PyCField_FromDesc(desc, i,
&field_size, bitsize, &bitofs,
&size, &offset, &align,
pack, big_endian);
union_size = max(size, union_size);
}
total_align = max(align, total_align);
if (!prop) {
Py_DECREF(pair);
return -1;
}
if (-1 == PyObject_SetAttr(type, name, prop)) {
Py_DECREF(prop);
Py_DECREF(pair);
return -1;
}
Py_DECREF(pair);
Py_DECREF(prop);
}
if (!prop) {
Py_DECREF(pair);
return -1;
}
if (-1 == PyObject_SetAttr(type, name, prop)) {
Py_DECREF(prop);
Py_DECREF(pair);
return -1;
}
Py_DECREF(pair);
Py_DECREF(prop);
}
#undef realdict
if (isStruct && !isPacked) {
char *ptr = stgdict->format;
stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}");
PyMem_Free(ptr);
if (stgdict->format == NULL)
return -1;
}
if (isStruct && !isPacked) {
char *ptr = stgdict->format;
stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}");
PyMem_Free(ptr);
if (stgdict->format == NULL)
return -1;
}
if (!isStruct)
size = union_size;
if (!isStruct)
size = union_size;
/* Adjust the size according to the alignment requirements */
size = ((size + total_align - 1) / total_align) * total_align;
/* Adjust the size according to the alignment requirements */
size = ((size + total_align - 1) / total_align) * total_align;
stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align,
Py_ssize_t,
unsigned short);
stgdict->ffi_type_pointer.size = size;
stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align,
Py_ssize_t,
unsigned short);
stgdict->ffi_type_pointer.size = size;
stgdict->size = size;
stgdict->align = total_align;
stgdict->length = len; /* ADD ffi_ofs? */
stgdict->size = size;
stgdict->align = total_align;
stgdict->length = len; /* ADD ffi_ofs? */
/* We did check that this flag was NOT set above, it must not
have been set until now. */
if (stgdict->flags & DICTFLAG_FINAL) {
PyErr_SetString(PyExc_AttributeError,
"Structure or union cannot contain itself");
return -1;
}
stgdict->flags |= DICTFLAG_FINAL;
/* We did check that this flag was NOT set above, it must not
have been set until now. */
if (stgdict->flags & DICTFLAG_FINAL) {
PyErr_SetString(PyExc_AttributeError,
"Structure or union cannot contain itself");
return -1;
}
stgdict->flags |= DICTFLAG_FINAL;
return MakeAnonFields(type);
return MakeAnonFields(type);
}

View file

@ -22,7 +22,7 @@ static PyObject *PyCursesError;
/* Utility Functions */
/*
* Check the return code from a curses function and return None
* Check the return code from a curses function and return None
* or raise an exception as appropriate.
*/
@ -30,15 +30,15 @@ static PyObject *
PyCursesCheckERR(int code, char *fname)
{
if (code != ERR) {
Py_INCREF(Py_None);
return Py_None;
Py_INCREF(Py_None);
return Py_None;
} else {
if (fname == NULL) {
PyErr_SetString(PyCursesError, catchall_ERR);
} else {
PyErr_Format(PyCursesError, "%s() returned ERR", fname);
}
return NULL;
if (fname == NULL) {
PyErr_SetString(PyCursesError, catchall_ERR);
} else {
PyErr_Format(PyCursesError, "%s() returned ERR", fname);
}
return NULL;
}
}
@ -51,12 +51,12 @@ PyCursesCheckERR(int code, char *fname)
typedef struct {
PyObject_HEAD
PANEL *pan;
PyCursesWindowObject *wo; /* for reference counts */
PyCursesWindowObject *wo; /* for reference counts */
} PyCursesPanelObject;
PyTypeObject PyCursesPanel_Type;
#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type)
#define PyCursesPanel_Check(v) (Py_TYPE(v) == &PyCursesPanel_Type)
/* Some helper functions. The problem is that there's always a window
associated with a panel. To ensure that Python's GC doesn't pull
@ -88,10 +88,10 @@ static int
insert_lop(PyCursesPanelObject *po)
{
list_of_panels *new;
if ((new = (list_of_panels *)malloc(sizeof(list_of_panels))) == NULL) {
PyErr_NoMemory();
return -1;
PyErr_NoMemory();
return -1;
}
new->po = po;
new->next = lop;
@ -107,17 +107,17 @@ remove_lop(PyCursesPanelObject *po)
temp = lop;
if (temp->po == po) {
lop = temp->next;
free(temp);
return;
lop = temp->next;
free(temp);
return;
}
while (temp->next == NULL || temp->next->po != po) {
if (temp->next == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"remove_lop: can't find Panel Object");
return;
}
temp = temp->next;
if (temp->next == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"remove_lop: can't find Panel Object");
return;
}
temp = temp->next;
}
n = temp->next->next;
free(temp->next);
@ -131,7 +131,7 @@ find_po(PANEL *pan)
{
list_of_panels *temp;
for (temp = lop; temp->po->pan != pan; temp = temp->next)
if (temp->next == NULL) return NULL; /* not found!? */
if (temp->next == NULL) return NULL; /* not found!? */
return temp->po;
}
@ -179,9 +179,9 @@ PyCursesPanel_New(PANEL *pan, PyCursesWindowObject *wo)
if (po == NULL) return NULL;
po->pan = pan;
if (insert_lop(po) < 0) {
po->wo = NULL;
Py_DECREF(po);
return NULL;
po->wo = NULL;
Py_DECREF(po);
return NULL;
}
po->wo = wo;
Py_INCREF(wo);
@ -193,8 +193,8 @@ PyCursesPanel_Dealloc(PyCursesPanelObject *po)
{
(void)del_panel(po->pan);
if (po->wo != NULL) {
Py_DECREF(po->wo);
remove_lop(po);
Py_DECREF(po->wo);
remove_lop(po);
}
PyObject_DEL(po);
}
@ -206,19 +206,19 @@ PyCursesPanel_above(PyCursesPanelObject *self)
{
PANEL *pan;
PyCursesPanelObject *po;
pan = panel_above(self->pan);
if (pan == NULL) { /* valid output, it means the calling panel
is on top of the stack */
Py_INCREF(Py_None);
return Py_None;
if (pan == NULL) { /* valid output, it means the calling panel
is on top of the stack */
Py_INCREF(Py_None);
return Py_None;
}
po = find_po(pan);
if (po == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"panel_above: can't find Panel Object");
return NULL;
PyErr_SetString(PyExc_RuntimeError,
"panel_above: can't find Panel Object");
return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
@ -231,19 +231,19 @@ PyCursesPanel_below(PyCursesPanelObject *self)
{
PANEL *pan;
PyCursesPanelObject *po;
pan = panel_below(self->pan);
if (pan == NULL) { /* valid output, it means the calling panel
is on the bottom of the stack */
Py_INCREF(Py_None);
return Py_None;
if (pan == NULL) { /* valid output, it means the calling panel
is on the bottom of the stack */
Py_INCREF(Py_None);
return Py_None;
}
po = find_po(pan);
if (po == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"panel_below: can't find Panel Object");
return NULL;
PyErr_SetString(PyExc_RuntimeError,
"panel_below: can't find Panel Object");
return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
@ -262,26 +262,26 @@ PyCursesPanel_replace_panel(PyCursesPanelObject *self, PyObject *args)
PyCursesPanelObject *po;
PyCursesWindowObject *temp;
int rtn;
if (PyTuple_Size(args) != 1) {
PyErr_SetString(PyExc_TypeError, "replace requires one argument");
return NULL;
PyErr_SetString(PyExc_TypeError, "replace requires one argument");
return NULL;
}
if (!PyArg_ParseTuple(args, "O!;window object",
&PyCursesWindow_Type, &temp))
return NULL;
&PyCursesWindow_Type, &temp))
return NULL;
po = find_po(self->pan);
if (po == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"replace_panel: can't find Panel Object");
return NULL;
PyErr_SetString(PyExc_RuntimeError,
"replace_panel: can't find Panel Object");
return NULL;
}
rtn = replace_panel(self->pan, temp->win);
if (rtn == ERR) {
PyErr_SetString(PyCursesError, "replace_panel() returned ERR");
return NULL;
PyErr_SetString(PyCursesError, "replace_panel() returned ERR");
return NULL;
}
Py_DECREF(po->wo);
po->wo = temp;
@ -302,11 +302,11 @@ static PyObject *
PyCursesPanel_userptr(PyCursesPanelObject *self)
{
PyObject *obj;
PyCursesInitialised;
PyCursesInitialised;
obj = (PyObject *) panel_userptr(self->pan);
if (obj == NULL) {
PyErr_SetString(PyCursesError, "no userptr set");
return NULL;
PyErr_SetString(PyCursesError, "no userptr set");
return NULL;
}
Py_INCREF(obj);
@ -329,40 +329,40 @@ static PyMethodDef PyCursesPanel_Methods[] = {
{"top", (PyCFunction)PyCursesPanel_top_panel, METH_NOARGS},
{"userptr", (PyCFunction)PyCursesPanel_userptr, METH_NOARGS},
{"window", (PyCFunction)PyCursesPanel_window, METH_NOARGS},
{NULL, NULL} /* sentinel */
{NULL, NULL} /* sentinel */
};
/* -------------------------------------------------------*/
PyTypeObject PyCursesPanel_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_curses_panel.curses panel", /*tp_name*/
sizeof(PyCursesPanelObject), /*tp_basicsize*/
0, /*tp_itemsize*/
"_curses_panel.curses panel", /*tp_name*/
sizeof(PyCursesPanelObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)PyCursesPanel_Dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
PyCursesPanel_Methods, /*tp_methods*/
};
@ -380,16 +380,16 @@ PyCurses_bottom_panel(PyObject *self)
pan = panel_above(NULL);
if (pan == NULL) { /* valid output, it means
there's no panel at all */
Py_INCREF(Py_None);
return Py_None;
if (pan == NULL) { /* valid output, it means
there's no panel at all */
Py_INCREF(Py_None);
return Py_None;
}
po = find_po(pan);
if (po == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"panel_above: can't find Panel Object");
return NULL;
PyErr_SetString(PyExc_RuntimeError,
"panel_above: can't find Panel Object");
return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
@ -405,8 +405,8 @@ PyCurses_new_panel(PyObject *self, PyObject *args)
return NULL;
pan = new_panel(win->win);
if (pan == NULL) {
PyErr_SetString(PyCursesError, catchall_NULL);
return NULL;
PyErr_SetString(PyCursesError, catchall_NULL);
return NULL;
}
return (PyObject *)PyCursesPanel_New(pan, win);
}
@ -421,28 +421,28 @@ PyCurses_top_panel(PyObject *self)
{
PANEL *pan;
PyCursesPanelObject *po;
PyCursesInitialised;
pan = panel_below(NULL);
if (pan == NULL) { /* valid output, it means
there's no panel at all */
Py_INCREF(Py_None);
return Py_None;
if (pan == NULL) { /* valid output, it means
there's no panel at all */
Py_INCREF(Py_None);
return Py_None;
}
po = find_po(pan);
if (po == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"panel_below: can't find Panel Object");
return NULL;
PyErr_SetString(PyExc_RuntimeError,
"panel_below: can't find Panel Object");
return NULL;
}
Py_INCREF(po);
return (PyObject *)po;
}
static PyObject *PyCurses_update_panels(PyObject *self)
{
{
PyCursesInitialised;
update_panels();
Py_INCREF(Py_None);
@ -457,22 +457,22 @@ static PyMethodDef PyCurses_methods[] = {
{"new_panel", (PyCFunction)PyCurses_new_panel, METH_VARARGS},
{"top_panel", (PyCFunction)PyCurses_top_panel, METH_NOARGS},
{"update_panels", (PyCFunction)PyCurses_update_panels, METH_NOARGS},
{NULL, NULL} /* sentinel */
{NULL, NULL} /* sentinel */
};
/* Initialization function for the module */
static struct PyModuleDef _curses_panelmodule = {
PyModuleDef_HEAD_INIT,
"_curses_panel",
NULL,
-1,
PyCurses_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_curses_panel",
NULL,
-1,
PyCurses_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
@ -489,7 +489,7 @@ PyInit__curses_panel(void)
/* Create the module and add the functions */
m = PyModule_Create(&_curses_panelmodule);
if (m == NULL)
return NULL;
return NULL;
d = PyModule_GetDict(m);
/* For exception _curses_panel.error */

View file

@ -33,9 +33,9 @@ static char *which_dbm = "Berkeley DB";
#endif
typedef struct {
PyObject_HEAD
int di_size; /* -1 means recompute */
DBM *di_dbm;
PyObject_HEAD
int di_size; /* -1 means recompute */
DBM *di_dbm;
} dbmobject;
static PyTypeObject Dbmtype;
@ -50,18 +50,18 @@ static PyObject *DbmError;
static PyObject *
newdbmobject(char *file, int flags, int mode)
{
dbmobject *dp;
dbmobject *dp;
dp = PyObject_New(dbmobject, &Dbmtype);
if (dp == NULL)
return NULL;
dp->di_size = -1;
if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) {
PyErr_SetFromErrno(DbmError);
Py_DECREF(dp);
return NULL;
}
return (PyObject *)dp;
dp = PyObject_New(dbmobject, &Dbmtype);
if (dp == NULL)
return NULL;
dp->di_size = -1;
if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) {
PyErr_SetFromErrno(DbmError);
Py_DECREF(dp);
return NULL;
}
return (PyObject *)dp;
}
/* Methods */
@ -69,294 +69,294 @@ newdbmobject(char *file, int flags, int mode)
static void
dbm_dealloc(register dbmobject *dp)
{
if ( dp->di_dbm )
dbm_close(dp->di_dbm);
PyObject_Del(dp);
if ( dp->di_dbm )
dbm_close(dp->di_dbm);
PyObject_Del(dp);
}
static Py_ssize_t
dbm_length(dbmobject *dp)
{
if (dp->di_dbm == NULL) {
PyErr_SetString(DbmError, "DBM object has already been closed");
return -1;
}
if ( dp->di_size < 0 ) {
datum key;
int size;
if (dp->di_dbm == NULL) {
PyErr_SetString(DbmError, "DBM object has already been closed");
return -1;
}
if ( dp->di_size < 0 ) {
datum key;
int size;
size = 0;
for ( key=dbm_firstkey(dp->di_dbm); key.dptr;
key = dbm_nextkey(dp->di_dbm))
size++;
dp->di_size = size;
}
return dp->di_size;
size = 0;
for ( key=dbm_firstkey(dp->di_dbm); key.dptr;
key = dbm_nextkey(dp->di_dbm))
size++;
dp->di_size = size;
}
return dp->di_size;
}
static PyObject *
dbm_subscript(dbmobject *dp, register PyObject *key)
{
datum drec, krec;
Py_ssize_t tmp_size;
if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) )
return NULL;
krec.dsize = tmp_size;
check_dbmobject_open(dp);
drec = dbm_fetch(dp->di_dbm, krec);
if ( drec.dptr == 0 ) {
PyErr_SetObject(PyExc_KeyError, key);
return NULL;
}
if ( dbm_error(dp->di_dbm) ) {
dbm_clearerr(dp->di_dbm);
PyErr_SetString(DbmError, "");
return NULL;
}
return PyBytes_FromStringAndSize(drec.dptr, drec.dsize);
datum drec, krec;
Py_ssize_t tmp_size;
if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) )
return NULL;
krec.dsize = tmp_size;
check_dbmobject_open(dp);
drec = dbm_fetch(dp->di_dbm, krec);
if ( drec.dptr == 0 ) {
PyErr_SetObject(PyExc_KeyError, key);
return NULL;
}
if ( dbm_error(dp->di_dbm) ) {
dbm_clearerr(dp->di_dbm);
PyErr_SetString(DbmError, "");
return NULL;
}
return PyBytes_FromStringAndSize(drec.dptr, drec.dsize);
}
static int
dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w)
{
datum krec, drec;
Py_ssize_t tmp_size;
if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) {
PyErr_SetString(PyExc_TypeError,
"dbm mappings have bytes or string keys only");
return -1;
}
krec.dsize = tmp_size;
if (dp->di_dbm == NULL) {
PyErr_SetString(DbmError, "DBM object has already been closed");
return -1;
datum krec, drec;
Py_ssize_t tmp_size;
if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) {
PyErr_SetString(PyExc_TypeError,
"dbm mappings have bytes or string keys only");
return -1;
}
krec.dsize = tmp_size;
if (dp->di_dbm == NULL) {
PyErr_SetString(DbmError, "DBM object has already been closed");
return -1;
}
dp->di_size = -1;
if (w == NULL) {
if ( dbm_delete(dp->di_dbm, krec) < 0 ) {
dbm_clearerr(dp->di_dbm);
PyErr_SetObject(PyExc_KeyError, v);
return -1;
}
dp->di_size = -1;
if (w == NULL) {
if ( dbm_delete(dp->di_dbm, krec) < 0 ) {
dbm_clearerr(dp->di_dbm);
PyErr_SetObject(PyExc_KeyError, v);
return -1;
}
} else {
if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) {
PyErr_SetString(PyExc_TypeError,
"dbm mappings have byte or string elements only");
return -1;
}
drec.dsize = tmp_size;
if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) {
dbm_clearerr(dp->di_dbm);
PyErr_SetString(DbmError,
"cannot add item to database");
return -1;
}
}
if ( dbm_error(dp->di_dbm) ) {
dbm_clearerr(dp->di_dbm);
PyErr_SetString(DbmError, "");
return -1;
}
return 0;
} else {
if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) {
PyErr_SetString(PyExc_TypeError,
"dbm mappings have byte or string elements only");
return -1;
}
drec.dsize = tmp_size;
if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) {
dbm_clearerr(dp->di_dbm);
PyErr_SetString(DbmError,
"cannot add item to database");
return -1;
}
}
if ( dbm_error(dp->di_dbm) ) {
dbm_clearerr(dp->di_dbm);
PyErr_SetString(DbmError, "");
return -1;
}
return 0;
}
static PyMappingMethods dbm_as_mapping = {
(lenfunc)dbm_length, /*mp_length*/
(binaryfunc)dbm_subscript, /*mp_subscript*/
(objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/
(lenfunc)dbm_length, /*mp_length*/
(binaryfunc)dbm_subscript, /*mp_subscript*/
(objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/
};
static PyObject *
dbm__close(register dbmobject *dp, PyObject *unused)
{
if (dp->di_dbm)
dbm_close(dp->di_dbm);
dp->di_dbm = NULL;
Py_INCREF(Py_None);
return Py_None;
if (dp->di_dbm)
dbm_close(dp->di_dbm);
dp->di_dbm = NULL;
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
dbm_keys(register dbmobject *dp, PyObject *unused)
{
register PyObject *v, *item;
datum key;
int err;
register PyObject *v, *item;
datum key;
int err;
check_dbmobject_open(dp);
v = PyList_New(0);
if (v == NULL)
return NULL;
for (key = dbm_firstkey(dp->di_dbm); key.dptr;
key = dbm_nextkey(dp->di_dbm)) {
item = PyBytes_FromStringAndSize(key.dptr, key.dsize);
if (item == NULL) {
Py_DECREF(v);
return NULL;
}
err = PyList_Append(v, item);
Py_DECREF(item);
if (err != 0) {
Py_DECREF(v);
return NULL;
}
}
return v;
check_dbmobject_open(dp);
v = PyList_New(0);
if (v == NULL)
return NULL;
for (key = dbm_firstkey(dp->di_dbm); key.dptr;
key = dbm_nextkey(dp->di_dbm)) {
item = PyBytes_FromStringAndSize(key.dptr, key.dsize);
if (item == NULL) {
Py_DECREF(v);
return NULL;
}
err = PyList_Append(v, item);
Py_DECREF(item);
if (err != 0) {
Py_DECREF(v);
return NULL;
}
}
return v;
}
static int
dbm_contains(PyObject *self, PyObject *arg)
{
dbmobject *dp = (dbmobject *)self;
datum key, val;
dbmobject *dp = (dbmobject *)self;
datum key, val;
if ((dp)->di_dbm == NULL) {
PyErr_SetString(DbmError,
"DBM object has already been closed");
return -1;
}
if (PyUnicode_Check(arg)) {
arg = _PyUnicode_AsDefaultEncodedString(arg, NULL);
if (arg == NULL)
return -1;
}
if (!PyBytes_Check(arg)) {
PyErr_Format(PyExc_TypeError,
"dbm key must be string, not %.100s",
arg->ob_type->tp_name);
return -1;
}
key.dptr = PyBytes_AS_STRING(arg);
key.dsize = PyBytes_GET_SIZE(arg);
val = dbm_fetch(dp->di_dbm, key);
return val.dptr != NULL;
if ((dp)->di_dbm == NULL) {
PyErr_SetString(DbmError,
"DBM object has already been closed");
return -1;
}
if (PyUnicode_Check(arg)) {
arg = _PyUnicode_AsDefaultEncodedString(arg, NULL);
if (arg == NULL)
return -1;
}
if (!PyBytes_Check(arg)) {
PyErr_Format(PyExc_TypeError,
"dbm key must be string, not %.100s",
arg->ob_type->tp_name);
return -1;
}
key.dptr = PyBytes_AS_STRING(arg);
key.dsize = PyBytes_GET_SIZE(arg);
val = dbm_fetch(dp->di_dbm, key);
return val.dptr != NULL;
}
static PySequenceMethods dbm_as_sequence = {
0, /* sq_length */
0, /* sq_concat */
0, /* sq_repeat */
0, /* sq_item */
0, /* sq_slice */
0, /* sq_ass_item */
0, /* sq_ass_slice */
dbm_contains, /* sq_contains */
0, /* sq_inplace_concat */
0, /* sq_inplace_repeat */
0, /* sq_length */
0, /* sq_concat */
0, /* sq_repeat */
0, /* sq_item */
0, /* sq_slice */
0, /* sq_ass_item */
0, /* sq_ass_slice */
dbm_contains, /* sq_contains */
0, /* sq_inplace_concat */
0, /* sq_inplace_repeat */
};
static PyObject *
dbm_get(register dbmobject *dp, PyObject *args)
{
datum key, val;
PyObject *defvalue = Py_None;
char *tmp_ptr;
Py_ssize_t tmp_size;
datum key, val;
PyObject *defvalue = Py_None;
char *tmp_ptr;
Py_ssize_t tmp_size;
if (!PyArg_ParseTuple(args, "s#|O:get",
&tmp_ptr, &tmp_size, &defvalue))
return NULL;
key.dptr = tmp_ptr;
key.dsize = tmp_size;
check_dbmobject_open(dp);
val = dbm_fetch(dp->di_dbm, key);
if (val.dptr != NULL)
return PyBytes_FromStringAndSize(val.dptr, val.dsize);
else {
Py_INCREF(defvalue);
return defvalue;
}
if (!PyArg_ParseTuple(args, "s#|O:get",
&tmp_ptr, &tmp_size, &defvalue))
return NULL;
key.dptr = tmp_ptr;
key.dsize = tmp_size;
check_dbmobject_open(dp);
val = dbm_fetch(dp->di_dbm, key);
if (val.dptr != NULL)
return PyBytes_FromStringAndSize(val.dptr, val.dsize);
else {
Py_INCREF(defvalue);
return defvalue;
}
}
static PyObject *
dbm_setdefault(register dbmobject *dp, PyObject *args)
{
datum key, val;
PyObject *defvalue = NULL;
char *tmp_ptr;
Py_ssize_t tmp_size;
datum key, val;
PyObject *defvalue = NULL;
char *tmp_ptr;
Py_ssize_t tmp_size;
if (!PyArg_ParseTuple(args, "s#|O:setdefault",
&tmp_ptr, &tmp_size, &defvalue))
return NULL;
key.dptr = tmp_ptr;
key.dsize = tmp_size;
check_dbmobject_open(dp);
val = dbm_fetch(dp->di_dbm, key);
if (val.dptr != NULL)
return PyBytes_FromStringAndSize(val.dptr, val.dsize);
if (defvalue == NULL) {
defvalue = PyBytes_FromStringAndSize(NULL, 0);
if (defvalue == NULL)
return NULL;
val.dptr = NULL;
val.dsize = 0;
}
else {
if ( !PyArg_Parse(defvalue, "s#", &val.dptr, &tmp_size) ) {
PyErr_SetString(PyExc_TypeError,
"dbm mappings have byte string elements only");
return NULL;
}
val.dsize = tmp_size;
Py_INCREF(defvalue);
}
if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) {
dbm_clearerr(dp->di_dbm);
PyErr_SetString(DbmError, "cannot add item to database");
Py_DECREF(defvalue);
return NULL;
}
return defvalue;
if (!PyArg_ParseTuple(args, "s#|O:setdefault",
&tmp_ptr, &tmp_size, &defvalue))
return NULL;
key.dptr = tmp_ptr;
key.dsize = tmp_size;
check_dbmobject_open(dp);
val = dbm_fetch(dp->di_dbm, key);
if (val.dptr != NULL)
return PyBytes_FromStringAndSize(val.dptr, val.dsize);
if (defvalue == NULL) {
defvalue = PyBytes_FromStringAndSize(NULL, 0);
if (defvalue == NULL)
return NULL;
val.dptr = NULL;
val.dsize = 0;
}
else {
if ( !PyArg_Parse(defvalue, "s#", &val.dptr, &tmp_size) ) {
PyErr_SetString(PyExc_TypeError,
"dbm mappings have byte string elements only");
return NULL;
}
val.dsize = tmp_size;
Py_INCREF(defvalue);
}
if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) {
dbm_clearerr(dp->di_dbm);
PyErr_SetString(DbmError, "cannot add item to database");
Py_DECREF(defvalue);
return NULL;
}
return defvalue;
}
static PyMethodDef dbm_methods[] = {
{"close", (PyCFunction)dbm__close, METH_NOARGS,
"close()\nClose the database."},
{"keys", (PyCFunction)dbm_keys, METH_NOARGS,
"keys() -> list\nReturn a list of all keys in the database."},
{"get", (PyCFunction)dbm_get, METH_VARARGS,
"get(key[, default]) -> value\n"
"Return the value for key if present, otherwise default."},
{"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS,
"setdefault(key[, default]) -> value\n"
"Return the value for key if present, otherwise default. If key\n"
"is not in the database, it is inserted with default as the value."},
{NULL, NULL} /* sentinel */
{"close", (PyCFunction)dbm__close, METH_NOARGS,
"close()\nClose the database."},
{"keys", (PyCFunction)dbm_keys, METH_NOARGS,
"keys() -> list\nReturn a list of all keys in the database."},
{"get", (PyCFunction)dbm_get, METH_VARARGS,
"get(key[, default]) -> value\n"
"Return the value for key if present, otherwise default."},
{"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS,
"setdefault(key[, default]) -> value\n"
"Return the value for key if present, otherwise default. If key\n"
"is not in the database, it is inserted with default as the value."},
{NULL, NULL} /* sentinel */
};
static PyTypeObject Dbmtype = {
PyVarObject_HEAD_INIT(NULL, 0)
"_dbm.dbm",
sizeof(dbmobject),
0,
(destructor)dbm_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
&dbm_as_sequence, /*tp_as_sequence*/
&dbm_as_mapping, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
dbm_methods, /*tp_methods*/
PyVarObject_HEAD_INIT(NULL, 0)
"_dbm.dbm",
sizeof(dbmobject),
0,
(destructor)dbm_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
&dbm_as_sequence, /*tp_as_sequence*/
&dbm_as_mapping, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
dbm_methods, /*tp_methods*/
};
/* ----------------------------------------------------------------- */
@ -364,74 +364,74 @@ static PyTypeObject Dbmtype = {
static PyObject *
dbmopen(PyObject *self, PyObject *args)
{
char *name;
char *flags = "r";
int iflags;
int mode = 0666;
char *name;
char *flags = "r";
int iflags;
int mode = 0666;
if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) )
return NULL;
if ( strcmp(flags, "r") == 0 )
iflags = O_RDONLY;
else if ( strcmp(flags, "w") == 0 )
iflags = O_RDWR;
else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */
iflags = O_RDWR|O_CREAT;
else if ( strcmp(flags, "c") == 0 )
iflags = O_RDWR|O_CREAT;
else if ( strcmp(flags, "n") == 0 )
iflags = O_RDWR|O_CREAT|O_TRUNC;
else {
PyErr_SetString(DbmError,
"arg 2 to open should be 'r', 'w', 'c', or 'n'");
return NULL;
}
return newdbmobject(name, iflags, mode);
if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) )
return NULL;
if ( strcmp(flags, "r") == 0 )
iflags = O_RDONLY;
else if ( strcmp(flags, "w") == 0 )
iflags = O_RDWR;
else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */
iflags = O_RDWR|O_CREAT;
else if ( strcmp(flags, "c") == 0 )
iflags = O_RDWR|O_CREAT;
else if ( strcmp(flags, "n") == 0 )
iflags = O_RDWR|O_CREAT|O_TRUNC;
else {
PyErr_SetString(DbmError,
"arg 2 to open should be 'r', 'w', 'c', or 'n'");
return NULL;
}
return newdbmobject(name, iflags, mode);
}
static PyMethodDef dbmmodule_methods[] = {
{ "open", (PyCFunction)dbmopen, METH_VARARGS,
"open(path[, flag[, mode]]) -> mapping\n"
"Return a database object."},
{ 0, 0 },
{ "open", (PyCFunction)dbmopen, METH_VARARGS,
"open(path[, flag[, mode]]) -> mapping\n"
"Return a database object."},
{ 0, 0 },
};
static struct PyModuleDef _dbmmodule = {
PyModuleDef_HEAD_INIT,
"_dbm",
NULL,
-1,
dbmmodule_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_dbm",
NULL,
-1,
dbmmodule_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__dbm(void) {
PyObject *m, *d, *s;
PyObject *m, *d, *s;
if (PyType_Ready(&Dbmtype) < 0)
return NULL;
m = PyModule_Create(&_dbmmodule);
if (m == NULL)
return NULL;
d = PyModule_GetDict(m);
if (DbmError == NULL)
DbmError = PyErr_NewException("_dbm.error",
PyExc_IOError, NULL);
s = PyUnicode_FromString(which_dbm);
if (s != NULL) {
PyDict_SetItemString(d, "library", s);
Py_DECREF(s);
}
if (DbmError != NULL)
PyDict_SetItemString(d, "error", DbmError);
if (PyErr_Occurred()) {
Py_DECREF(m);
m = NULL;
}
return m;
if (PyType_Ready(&Dbmtype) < 0)
return NULL;
m = PyModule_Create(&_dbmmodule);
if (m == NULL)
return NULL;
d = PyModule_GetDict(m);
if (DbmError == NULL)
DbmError = PyErr_NewException("_dbm.error",
PyExc_IOError, NULL);
s = PyUnicode_FromString(which_dbm);
if (s != NULL) {
PyDict_SetItemString(d, "library", s);
Py_DECREF(s);
}
if (DbmError != NULL)
PyDict_SetItemString(d, "error", DbmError);
if (PyErr_Occurred()) {
Py_DECREF(m);
m = NULL;
}
return m;
}

View file

@ -2,7 +2,7 @@
#include "Python.h"
#include "structmember.h"
/* _functools module written and maintained
/* _functools module written and maintained
by Hye-Shik Chang <perky@FreeBSD.org>
with adaptations by Raymond Hettinger <python@rcn.com>
Copyright (c) 2004, 2005, 2006 Python Software Foundation.
@ -12,12 +12,12 @@
/* partial object **********************************************************/
typedef struct {
PyObject_HEAD
PyObject *fn;
PyObject *args;
PyObject *kw;
PyObject *dict;
PyObject *weakreflist; /* List of weak references */
PyObject_HEAD
PyObject *fn;
PyObject *args;
PyObject *kw;
PyObject *dict;
PyObject *weakreflist; /* List of weak references */
} partialobject;
static PyTypeObject partial_type;
@ -25,175 +25,175 @@ static PyTypeObject partial_type;
static PyObject *
partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
PyObject *func;
partialobject *pto;
PyObject *func;
partialobject *pto;
if (PyTuple_GET_SIZE(args) < 1) {
PyErr_SetString(PyExc_TypeError,
"type 'partial' takes at least one argument");
return NULL;
}
if (PyTuple_GET_SIZE(args) < 1) {
PyErr_SetString(PyExc_TypeError,
"type 'partial' takes at least one argument");
return NULL;
}
func = PyTuple_GET_ITEM(args, 0);
if (!PyCallable_Check(func)) {
PyErr_SetString(PyExc_TypeError,
"the first argument must be callable");
return NULL;
}
func = PyTuple_GET_ITEM(args, 0);
if (!PyCallable_Check(func)) {
PyErr_SetString(PyExc_TypeError,
"the first argument must be callable");
return NULL;
}
/* create partialobject structure */
pto = (partialobject *)type->tp_alloc(type, 0);
if (pto == NULL)
return NULL;
/* create partialobject structure */
pto = (partialobject *)type->tp_alloc(type, 0);
if (pto == NULL)
return NULL;
pto->fn = func;
Py_INCREF(func);
pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX);
if (pto->args == NULL) {
pto->kw = NULL;
Py_DECREF(pto);
return NULL;
}
if (kw != NULL) {
pto->kw = PyDict_Copy(kw);
if (pto->kw == NULL) {
Py_DECREF(pto);
return NULL;
}
} else {
pto->kw = Py_None;
Py_INCREF(Py_None);
}
pto->fn = func;
Py_INCREF(func);
pto->args = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX);
if (pto->args == NULL) {
pto->kw = NULL;
Py_DECREF(pto);
return NULL;
}
if (kw != NULL) {
pto->kw = PyDict_Copy(kw);
if (pto->kw == NULL) {
Py_DECREF(pto);
return NULL;
}
} else {
pto->kw = Py_None;
Py_INCREF(Py_None);
}
pto->weakreflist = NULL;
pto->dict = NULL;
pto->weakreflist = NULL;
pto->dict = NULL;
return (PyObject *)pto;
return (PyObject *)pto;
}
static void
partial_dealloc(partialobject *pto)
{
PyObject_GC_UnTrack(pto);
if (pto->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) pto);
Py_XDECREF(pto->fn);
Py_XDECREF(pto->args);
Py_XDECREF(pto->kw);
Py_XDECREF(pto->dict);
Py_TYPE(pto)->tp_free(pto);
PyObject_GC_UnTrack(pto);
if (pto->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) pto);
Py_XDECREF(pto->fn);
Py_XDECREF(pto->args);
Py_XDECREF(pto->kw);
Py_XDECREF(pto->dict);
Py_TYPE(pto)->tp_free(pto);
}
static PyObject *
partial_call(partialobject *pto, PyObject *args, PyObject *kw)
{
PyObject *ret;
PyObject *argappl = NULL, *kwappl = NULL;
PyObject *ret;
PyObject *argappl = NULL, *kwappl = NULL;
assert (PyCallable_Check(pto->fn));
assert (PyTuple_Check(pto->args));
assert (pto->kw == Py_None || PyDict_Check(pto->kw));
assert (PyCallable_Check(pto->fn));
assert (PyTuple_Check(pto->args));
assert (pto->kw == Py_None || PyDict_Check(pto->kw));
if (PyTuple_GET_SIZE(pto->args) == 0) {
argappl = args;
Py_INCREF(args);
} else if (PyTuple_GET_SIZE(args) == 0) {
argappl = pto->args;
Py_INCREF(pto->args);
} else {
argappl = PySequence_Concat(pto->args, args);
if (argappl == NULL)
return NULL;
}
if (PyTuple_GET_SIZE(pto->args) == 0) {
argappl = args;
Py_INCREF(args);
} else if (PyTuple_GET_SIZE(args) == 0) {
argappl = pto->args;
Py_INCREF(pto->args);
} else {
argappl = PySequence_Concat(pto->args, args);
if (argappl == NULL)
return NULL;
}
if (pto->kw == Py_None) {
kwappl = kw;
Py_XINCREF(kw);
} else {
kwappl = PyDict_Copy(pto->kw);
if (kwappl == NULL) {
Py_DECREF(argappl);
return NULL;
}
if (kw != NULL) {
if (PyDict_Merge(kwappl, kw, 1) != 0) {
Py_DECREF(argappl);
Py_DECREF(kwappl);
return NULL;
}
}
}
if (pto->kw == Py_None) {
kwappl = kw;
Py_XINCREF(kw);
} else {
kwappl = PyDict_Copy(pto->kw);
if (kwappl == NULL) {
Py_DECREF(argappl);
return NULL;
}
if (kw != NULL) {
if (PyDict_Merge(kwappl, kw, 1) != 0) {
Py_DECREF(argappl);
Py_DECREF(kwappl);
return NULL;
}
}
}
ret = PyObject_Call(pto->fn, argappl, kwappl);
Py_DECREF(argappl);
Py_XDECREF(kwappl);
return ret;
ret = PyObject_Call(pto->fn, argappl, kwappl);
Py_DECREF(argappl);
Py_XDECREF(kwappl);
return ret;
}
static int
partial_traverse(partialobject *pto, visitproc visit, void *arg)
{
Py_VISIT(pto->fn);
Py_VISIT(pto->args);
Py_VISIT(pto->kw);
Py_VISIT(pto->dict);
return 0;
Py_VISIT(pto->fn);
Py_VISIT(pto->args);
Py_VISIT(pto->kw);
Py_VISIT(pto->dict);
return 0;
}
PyDoc_STRVAR(partial_doc,
"partial(func, *args, **keywords) - new function with partial application\n\
of the given arguments and keywords.\n");
of the given arguments and keywords.\n");
#define OFF(x) offsetof(partialobject, x)
static PyMemberDef partial_memberlist[] = {
{"func", T_OBJECT, OFF(fn), READONLY,
"function object to use in future partial calls"},
{"args", T_OBJECT, OFF(args), READONLY,
"tuple of arguments to future partial calls"},
{"keywords", T_OBJECT, OFF(kw), READONLY,
"dictionary of keyword arguments to future partial calls"},
{NULL} /* Sentinel */
{"func", T_OBJECT, OFF(fn), READONLY,
"function object to use in future partial calls"},
{"args", T_OBJECT, OFF(args), READONLY,
"tuple of arguments to future partial calls"},
{"keywords", T_OBJECT, OFF(kw), READONLY,
"dictionary of keyword arguments to future partial calls"},
{NULL} /* Sentinel */
};
static PyObject *
partial_get_dict(partialobject *pto)
{
if (pto->dict == NULL) {
pto->dict = PyDict_New();
if (pto->dict == NULL)
return NULL;
}
Py_INCREF(pto->dict);
return pto->dict;
if (pto->dict == NULL) {
pto->dict = PyDict_New();
if (pto->dict == NULL)
return NULL;
}
Py_INCREF(pto->dict);
return pto->dict;
}
static int
partial_set_dict(partialobject *pto, PyObject *value)
{
PyObject *tmp;
PyObject *tmp;
/* It is illegal to del p.__dict__ */
if (value == NULL) {
PyErr_SetString(PyExc_TypeError,
"a partial object's dictionary may not be deleted");
return -1;
}
/* Can only set __dict__ to a dictionary */
if (!PyDict_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"setting partial object's dictionary to a non-dict");
return -1;
}
tmp = pto->dict;
Py_INCREF(value);
pto->dict = value;
Py_XDECREF(tmp);
return 0;
/* It is illegal to del p.__dict__ */
if (value == NULL) {
PyErr_SetString(PyExc_TypeError,
"a partial object's dictionary may not be deleted");
return -1;
}
/* Can only set __dict__ to a dictionary */
if (!PyDict_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"setting partial object's dictionary to a non-dict");
return -1;
}
tmp = pto->dict;
Py_INCREF(value);
pto->dict = value;
Py_XDECREF(tmp);
return 0;
}
static PyGetSetDef partial_getsetlist[] = {
{"__dict__", (getter)partial_get_dict, (setter)partial_set_dict},
{NULL} /* Sentinel */
{"__dict__", (getter)partial_get_dict, (setter)partial_set_dict},
{NULL} /* Sentinel */
};
/* Pickle strategy:
@ -206,85 +206,85 @@ static PyGetSetDef partial_getsetlist[] = {
static PyObject *
partial_reduce(partialobject *pto, PyObject *unused)
{
return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn,
pto->args, pto->kw,
pto->dict ? pto->dict : Py_None);
return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn,
pto->args, pto->kw,
pto->dict ? pto->dict : Py_None);
}
static PyObject *
partial_setstate(partialobject *pto, PyObject *args)
{
PyObject *fn, *fnargs, *kw, *dict;
if (!PyArg_ParseTuple(args, "(OOOO):__setstate__",
&fn, &fnargs, &kw, &dict))
return NULL;
Py_XDECREF(pto->fn);
Py_XDECREF(pto->args);
Py_XDECREF(pto->kw);
Py_XDECREF(pto->dict);
pto->fn = fn;
pto->args = fnargs;
pto->kw = kw;
if (dict != Py_None) {
pto->dict = dict;
Py_INCREF(dict);
} else {
pto->dict = NULL;
}
Py_INCREF(fn);
Py_INCREF(fnargs);
Py_INCREF(kw);
Py_RETURN_NONE;
PyObject *fn, *fnargs, *kw, *dict;
if (!PyArg_ParseTuple(args, "(OOOO):__setstate__",
&fn, &fnargs, &kw, &dict))
return NULL;
Py_XDECREF(pto->fn);
Py_XDECREF(pto->args);
Py_XDECREF(pto->kw);
Py_XDECREF(pto->dict);
pto->fn = fn;
pto->args = fnargs;
pto->kw = kw;
if (dict != Py_None) {
pto->dict = dict;
Py_INCREF(dict);
} else {
pto->dict = NULL;
}
Py_INCREF(fn);
Py_INCREF(fnargs);
Py_INCREF(kw);
Py_RETURN_NONE;
}
static PyMethodDef partial_methods[] = {
{"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS},
{"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS},
{NULL, NULL} /* sentinel */
{"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS},
{"__setstate__", (PyCFunction)partial_setstate, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
static PyTypeObject partial_type = {
PyVarObject_HEAD_INIT(NULL, 0)
"functools.partial", /* tp_name */
sizeof(partialobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)partial_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)partial_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
PyObject_GenericSetAttr, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASETYPE, /* tp_flags */
partial_doc, /* tp_doc */
(traverseproc)partial_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(partialobject, weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
partial_methods, /* tp_methods */
partial_memberlist, /* tp_members */
partial_getsetlist, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(partialobject, dict), /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
partial_new, /* tp_new */
PyObject_GC_Del, /* tp_free */
PyVarObject_HEAD_INIT(NULL, 0)
"functools.partial", /* tp_name */
sizeof(partialobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)partial_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)partial_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
PyObject_GenericSetAttr, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASETYPE, /* tp_flags */
partial_doc, /* tp_doc */
(traverseproc)partial_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(partialobject, weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
partial_methods, /* tp_methods */
partial_memberlist, /* tp_members */
partial_getsetlist, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(partialobject, dict), /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
partial_new, /* tp_new */
PyObject_GC_Del, /* tp_free */
};
@ -293,64 +293,64 @@ static PyTypeObject partial_type = {
static PyObject *
functools_reduce(PyObject *self, PyObject *args)
{
PyObject *seq, *func, *result = NULL, *it;
PyObject *seq, *func, *result = NULL, *it;
if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
return NULL;
if (result != NULL)
Py_INCREF(result);
if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
return NULL;
if (result != NULL)
Py_INCREF(result);
it = PyObject_GetIter(seq);
if (it == NULL) {
PyErr_SetString(PyExc_TypeError,
"reduce() arg 2 must support iteration");
Py_XDECREF(result);
return NULL;
}
it = PyObject_GetIter(seq);
if (it == NULL) {
PyErr_SetString(PyExc_TypeError,
"reduce() arg 2 must support iteration");
Py_XDECREF(result);
return NULL;
}
if ((args = PyTuple_New(2)) == NULL)
goto Fail;
if ((args = PyTuple_New(2)) == NULL)
goto Fail;
for (;;) {
PyObject *op2;
for (;;) {
PyObject *op2;
if (args->ob_refcnt > 1) {
Py_DECREF(args);
if ((args = PyTuple_New(2)) == NULL)
goto Fail;
}
if (args->ob_refcnt > 1) {
Py_DECREF(args);
if ((args = PyTuple_New(2)) == NULL)
goto Fail;
}
op2 = PyIter_Next(it);
if (op2 == NULL) {
if (PyErr_Occurred())
goto Fail;
break;
}
op2 = PyIter_Next(it);
if (op2 == NULL) {
if (PyErr_Occurred())
goto Fail;
break;
}
if (result == NULL)
result = op2;
else {
PyTuple_SetItem(args, 0, result);
PyTuple_SetItem(args, 1, op2);
if ((result = PyEval_CallObject(func, args)) == NULL)
goto Fail;
}
}
if (result == NULL)
result = op2;
else {
PyTuple_SetItem(args, 0, result);
PyTuple_SetItem(args, 1, op2);
if ((result = PyEval_CallObject(func, args)) == NULL)
goto Fail;
}
}
Py_DECREF(args);
Py_DECREF(args);
if (result == NULL)
PyErr_SetString(PyExc_TypeError,
"reduce() of empty sequence with no initial value");
if (result == NULL)
PyErr_SetString(PyExc_TypeError,
"reduce() of empty sequence with no initial value");
Py_DECREF(it);
return result;
Py_DECREF(it);
return result;
Fail:
Py_XDECREF(args);
Py_XDECREF(result);
Py_DECREF(it);
return NULL;
Py_XDECREF(args);
Py_XDECREF(result);
Py_DECREF(it);
return NULL;
}
PyDoc_STRVAR(functools_reduce_doc,
@ -369,47 +369,47 @@ PyDoc_STRVAR(module_doc,
"Tools that operate on functions.");
static PyMethodDef module_methods[] = {
{"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc},
{NULL, NULL} /* sentinel */
{"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc},
{NULL, NULL} /* sentinel */
};
static struct PyModuleDef _functoolsmodule = {
PyModuleDef_HEAD_INIT,
"_functools",
module_doc,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_functools",
module_doc,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__functools(void)
{
int i;
PyObject *m;
char *name;
PyTypeObject *typelist[] = {
&partial_type,
NULL
};
int i;
PyObject *m;
char *name;
PyTypeObject *typelist[] = {
&partial_type,
NULL
};
m = PyModule_Create(&_functoolsmodule);
if (m == NULL)
return NULL;
m = PyModule_Create(&_functoolsmodule);
if (m == NULL)
return NULL;
for (i=0 ; typelist[i] != NULL ; i++) {
if (PyType_Ready(typelist[i]) < 0) {
Py_DECREF(m);
return NULL;
}
name = strchr(typelist[i]->tp_name, '.');
assert (name != NULL);
Py_INCREF(typelist[i]);
PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
}
return m;
for (i=0 ; typelist[i] != NULL ; i++) {
if (PyType_Ready(typelist[i]) < 0) {
Py_DECREF(m);
return NULL;
}
name = strchr(typelist[i]->tp_name, '.');
assert (name != NULL);
Py_INCREF(typelist[i]);
PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
}
return m;
}

View file

@ -30,7 +30,7 @@ supported.");
typedef struct {
PyObject_HEAD
int di_size; /* -1 means recompute */
int di_size; /* -1 means recompute */
GDBM_FILE di_dbm;
} dbmobject;
@ -177,7 +177,7 @@ dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w)
}
static PyMappingMethods dbm_as_mapping = {
(lenfunc)dbm_length, /*mp_length*/
(lenfunc)dbm_length, /*mp_length*/
(binaryfunc)dbm_subscript, /*mp_subscript*/
(objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/
};
@ -247,15 +247,15 @@ dbm_contains(PyObject *self, PyObject *arg)
datum key;
if ((dp)->di_dbm == NULL) {
PyErr_SetString(DbmError,
"GDBM object has already been closed");
return -1;
PyErr_SetString(DbmError,
"GDBM object has already been closed");
return -1;
}
if (!PyBytes_Check(arg)) {
PyErr_Format(PyExc_TypeError,
"gdbm key must be bytes, not %.100s",
arg->ob_type->tp_name);
return -1;
PyErr_Format(PyExc_TypeError,
"gdbm key must be bytes, not %.100s",
arg->ob_type->tp_name);
return -1;
}
key.dptr = PyBytes_AS_STRING(arg);
key.dsize = PyBytes_GET_SIZE(arg);
@ -263,16 +263,16 @@ dbm_contains(PyObject *self, PyObject *arg)
}
static PySequenceMethods dbm_as_sequence = {
0, /* sq_length */
0, /* sq_concat */
0, /* sq_repeat */
0, /* sq_item */
0, /* sq_slice */
0, /* sq_ass_item */
0, /* sq_ass_slice */
dbm_contains, /* sq_contains */
0, /* sq_inplace_concat */
0, /* sq_inplace_repeat */
0, /* sq_length */
0, /* sq_concat */
0, /* sq_repeat */
0, /* sq_item */
0, /* sq_slice */
0, /* sq_ass_item */
0, /* sq_ass_slice */
dbm_contains, /* sq_contains */
0, /* sq_inplace_concat */
0, /* sq_inplace_repeat */
};
PyDoc_STRVAR(dbm_firstkey__doc__,
@ -372,13 +372,13 @@ dbm_sync(register dbmobject *dp, PyObject *unused)
}
static PyMethodDef dbm_methods[] = {
{"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__},
{"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__},
{"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__},
{"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__},
{"firstkey", (PyCFunction)dbm_firstkey,METH_NOARGS, dbm_firstkey__doc__},
{"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__},
{"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__},
{"reorganize",(PyCFunction)dbm_reorganize,METH_NOARGS, dbm_reorganize__doc__},
{"sync", (PyCFunction)dbm_sync, METH_NOARGS, dbm_sync__doc__},
{NULL, NULL} /* sentinel */
{NULL, NULL} /* sentinel */
};
static PyTypeObject Dbmtype = {
@ -486,7 +486,7 @@ dbmopen(PyObject *self, PyObject *args)
#endif
default:
PyOS_snprintf(buf, sizeof(buf), "Flag '%c' is not supported.",
*flags);
*flags);
PyErr_SetString(DbmError, buf);
return NULL;
}
@ -514,15 +514,15 @@ static PyMethodDef dbmmodule_methods[] = {
static struct PyModuleDef _gdbmmodule = {
PyModuleDef_HEAD_INIT,
"_gdbm",
gdbmmodule__doc__,
-1,
dbmmodule_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_gdbm",
gdbmmodule__doc__,
-1,
dbmmodule_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
@ -530,10 +530,10 @@ PyInit__gdbm(void) {
PyObject *m, *d, *s;
if (PyType_Ready(&Dbmtype) < 0)
return NULL;
return NULL;
m = PyModule_Create(&_gdbmmodule);
if (m == NULL)
return NULL;
return NULL;
d = PyModule_GetDict(m);
DbmError = PyErr_NewException("_gdbm.error", PyExc_IOError, NULL);
if (DbmError != NULL) {

View file

@ -4,10 +4,10 @@ The Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
@ -34,9 +34,9 @@ convert_to_OSType(PyObject *v, OSType *pr)
{
uint32_t tmp;
if (!PyUnicode_Check(v) || PyUnicode_GetSize(v) != 4) {
PyErr_SetString(PyExc_TypeError,
"OSType arg must be string of 4 chars");
return 0;
PyErr_SetString(PyExc_TypeError,
"OSType arg must be string of 4 chars");
return 0;
}
memcpy((char *)&tmp, _PyUnicode_AsString(v), 4);
*pr = (OSType)ntohl(tmp);
@ -50,12 +50,12 @@ gestalt_gestalt(PyObject *self, PyObject *args)
OSType selector;
SInt32 response;
if (!PyArg_ParseTuple(args, "O&", convert_to_OSType, &selector))
return NULL;
return NULL;
iErr = Gestalt(selector, &response);
if (iErr != 0) {
PyErr_SetString(PyExc_OSError,
"non-zero exit code!");
return NULL;
PyErr_SetString(PyExc_OSError,
"non-zero exit code!");
return NULL;
}
return PyLong_FromLong(response);
}
@ -66,19 +66,19 @@ static struct PyMethodDef gestalt_methods[] = {
};
static struct PyModuleDef gestaltmodule = {
PyModuleDef_HEAD_INIT,
"_gestalt",
NULL,
-1,
gestalt_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_gestalt",
NULL,
-1,
gestalt_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__gestalt(void)
{
return PyModule_Create(&gestaltmodule);
return PyModule_Create(&gestaltmodule);
}

View file

@ -1,4 +1,4 @@
/* Drop in replacement for heapq.py
/* Drop in replacement for heapq.py
C implementation derived directly from heapq.py in Py2.3
which was written by Kevin O'Connor, augmented by Tim Peters,
@ -11,115 +11,115 @@ annotated by Fran
static int
cmp_lt(PyObject *x, PyObject *y)
{
return PyObject_RichCompareBool(x, y, Py_LT);
return PyObject_RichCompareBool(x, y, Py_LT);
}
static int
_siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
{
PyObject *newitem, *parent;
int cmp;
Py_ssize_t parentpos;
PyObject *newitem, *parent;
int cmp;
Py_ssize_t parentpos;
assert(PyList_Check(heap));
if (pos >= PyList_GET_SIZE(heap)) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
assert(PyList_Check(heap));
if (pos >= PyList_GET_SIZE(heap)) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Follow the path to the root, moving parents down until finding
a place newitem fits. */
while (pos > startpos){
parentpos = (pos - 1) >> 1;
parent = PyList_GET_ITEM(heap, parentpos);
cmp = cmp_lt(newitem, parent);
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
break;
Py_INCREF(parent);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, parent);
pos = parentpos;
}
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return 0;
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Follow the path to the root, moving parents down until finding
a place newitem fits. */
while (pos > startpos){
parentpos = (pos - 1) >> 1;
parent = PyList_GET_ITEM(heap, parentpos);
cmp = cmp_lt(newitem, parent);
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
break;
Py_INCREF(parent);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, parent);
pos = parentpos;
}
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return 0;
}
static int
_siftup(PyListObject *heap, Py_ssize_t pos)
{
Py_ssize_t startpos, endpos, childpos, rightpos;
int cmp;
PyObject *newitem, *tmp;
Py_ssize_t startpos, endpos, childpos, rightpos;
int cmp;
PyObject *newitem, *tmp;
assert(PyList_Check(heap));
endpos = PyList_GET_SIZE(heap);
startpos = pos;
if (pos >= endpos) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
assert(PyList_Check(heap));
endpos = PyList_GET_SIZE(heap);
startpos = pos;
if (pos >= endpos) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Bubble up the smaller child until hitting a leaf. */
childpos = 2*pos + 1; /* leftmost child position */
while (childpos < endpos) {
/* Set childpos to index of smaller child. */
rightpos = childpos + 1;
if (rightpos < endpos) {
cmp = cmp_lt(
PyList_GET_ITEM(heap, childpos),
PyList_GET_ITEM(heap, rightpos));
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
childpos = rightpos;
}
/* Move the smaller child up. */
tmp = PyList_GET_ITEM(heap, childpos);
Py_INCREF(tmp);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, tmp);
pos = childpos;
childpos = 2*pos + 1;
}
/* Bubble up the smaller child until hitting a leaf. */
childpos = 2*pos + 1; /* leftmost child position */
while (childpos < endpos) {
/* Set childpos to index of smaller child. */
rightpos = childpos + 1;
if (rightpos < endpos) {
cmp = cmp_lt(
PyList_GET_ITEM(heap, childpos),
PyList_GET_ITEM(heap, rightpos));
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
childpos = rightpos;
}
/* Move the smaller child up. */
tmp = PyList_GET_ITEM(heap, childpos);
Py_INCREF(tmp);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, tmp);
pos = childpos;
childpos = 2*pos + 1;
}
/* The leaf at pos is empty now. Put newitem there, and and bubble
it up to its final resting place (by sifting its parents down). */
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return _siftdown(heap, startpos, pos);
/* The leaf at pos is empty now. Put newitem there, and and bubble
it up to its final resting place (by sifting its parents down). */
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return _siftdown(heap, startpos, pos);
}
static PyObject *
heappush(PyObject *self, PyObject *args)
{
PyObject *heap, *item;
PyObject *heap, *item;
if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
return NULL;
if (!PyArg_UnpackTuple(args, "heappush", 2, 2, &heap, &item))
return NULL;
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (PyList_Append(heap, item) == -1)
return NULL;
if (PyList_Append(heap, item) == -1)
return NULL;
if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
return NULL;
Py_INCREF(Py_None);
return Py_None;
if (_siftdown((PyListObject *)heap, 0, PyList_GET_SIZE(heap)-1) == -1)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(heappush_doc,
@ -128,35 +128,35 @@ PyDoc_STRVAR(heappush_doc,
static PyObject *
heappop(PyObject *self, PyObject *heap)
{
PyObject *lastelt, *returnitem;
Py_ssize_t n;
PyObject *lastelt, *returnitem;
Py_ssize_t n;
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
/* # raises appropriate IndexError if heap is empty */
n = PyList_GET_SIZE(heap);
if (n == 0) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return NULL;
}
/* # raises appropriate IndexError if heap is empty */
n = PyList_GET_SIZE(heap);
if (n == 0) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return NULL;
}
lastelt = PyList_GET_ITEM(heap, n-1) ;
Py_INCREF(lastelt);
PyList_SetSlice(heap, n-1, n, NULL);
n--;
lastelt = PyList_GET_ITEM(heap, n-1) ;
Py_INCREF(lastelt);
PyList_SetSlice(heap, n-1, n, NULL);
n--;
if (!n)
return lastelt;
returnitem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, lastelt);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
if (!n)
return lastelt;
returnitem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, lastelt);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
}
PyDoc_STRVAR(heappop_doc,
@ -165,29 +165,29 @@ PyDoc_STRVAR(heappop_doc,
static PyObject *
heapreplace(PyObject *self, PyObject *args)
{
PyObject *heap, *item, *returnitem;
PyObject *heap, *item, *returnitem;
if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
return NULL;
if (!PyArg_UnpackTuple(args, "heapreplace", 2, 2, &heap, &item))
return NULL;
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (PyList_GET_SIZE(heap) < 1) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return NULL;
}
if (PyList_GET_SIZE(heap) < 1) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return NULL;
}
returnitem = PyList_GET_ITEM(heap, 0);
Py_INCREF(item);
PyList_SET_ITEM(heap, 0, item);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
returnitem = PyList_GET_ITEM(heap, 0);
Py_INCREF(item);
PyList_SET_ITEM(heap, 0, item);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
}
PyDoc_STRVAR(heapreplace_doc,
@ -197,44 +197,44 @@ This is more efficient than heappop() followed by heappush(), and can be\n\
more appropriate when using a fixed-size heap. Note that the value\n\
returned may be larger than item! That constrains reasonable uses of\n\
this routine unless written as part of a conditional replacement:\n\n\
if item > heap[0]:\n\
item = heapreplace(heap, item)\n");
if item > heap[0]:\n\
item = heapreplace(heap, item)\n");
static PyObject *
heappushpop(PyObject *self, PyObject *args)
{
PyObject *heap, *item, *returnitem;
int cmp;
PyObject *heap, *item, *returnitem;
int cmp;
if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
return NULL;
if (!PyArg_UnpackTuple(args, "heappushpop", 2, 2, &heap, &item))
return NULL;
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (PyList_GET_SIZE(heap) < 1) {
Py_INCREF(item);
return item;
}
if (PyList_GET_SIZE(heap) < 1) {
Py_INCREF(item);
return item;
}
cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item);
if (cmp == -1)
return NULL;
if (cmp == 0) {
Py_INCREF(item);
return item;
}
cmp = cmp_lt(PyList_GET_ITEM(heap, 0), item);
if (cmp == -1)
return NULL;
if (cmp == 0) {
Py_INCREF(item);
return item;
}
returnitem = PyList_GET_ITEM(heap, 0);
Py_INCREF(item);
PyList_SET_ITEM(heap, 0, item);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
returnitem = PyList_GET_ITEM(heap, 0);
Py_INCREF(item);
PyList_SET_ITEM(heap, 0, item);
if (_siftup((PyListObject *)heap, 0) == -1) {
Py_DECREF(returnitem);
return NULL;
}
return returnitem;
}
PyDoc_STRVAR(heappushpop_doc,
@ -245,26 +245,26 @@ heappush() followed by a separate call to heappop().");
static PyObject *
heapify(PyObject *self, PyObject *heap)
{
Py_ssize_t i, n;
Py_ssize_t i, n;
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
if (!PyList_Check(heap)) {
PyErr_SetString(PyExc_TypeError, "heap argument must be a list");
return NULL;
}
n = PyList_GET_SIZE(heap);
/* Transform bottom-up. The largest index there's any point to
looking at is the largest with a child index in-range, so must
have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
(2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
and that's again n//2-1.
*/
for (i=n/2-1 ; i>=0 ; i--)
if(_siftup((PyListObject *)heap, i) == -1)
return NULL;
Py_INCREF(Py_None);
return Py_None;
n = PyList_GET_SIZE(heap);
/* Transform bottom-up. The largest index there's any point to
looking at is the largest with a child index in-range, so must
have 2*i + 1 < n, or i < (n-1)/2. If n is even = 2*j, this is
(2*j-1)/2 = j-1/2 so j-1 is the largest, which is n//2 - 1. If
n is odd = 2*j+1, this is (2*j+1-1)/2 = j so j-1 is the largest,
and that's again n//2-1.
*/
for (i=n/2-1 ; i>=0 ; i--)
if(_siftup((PyListObject *)heap, i) == -1)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(heapify_doc,
@ -273,79 +273,79 @@ PyDoc_STRVAR(heapify_doc,
static PyObject *
nlargest(PyObject *self, PyObject *args)
{
PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
Py_ssize_t i, n;
int cmp;
PyObject *heap=NULL, *elem, *iterable, *sol, *it, *oldelem;
Py_ssize_t i, n;
int cmp;
if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
return NULL;
if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
return NULL;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
heap = PyList_New(0);
if (heap == NULL)
goto fail;
heap = PyList_New(0);
if (heap == NULL)
goto fail;
for (i=0 ; i<n ; i++ ){
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
if (PyList_Append(heap, elem) == -1) {
Py_DECREF(elem);
goto fail;
}
Py_DECREF(elem);
}
if (PyList_GET_SIZE(heap) == 0)
goto sortit;
for (i=0 ; i<n ; i++ ){
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
if (PyList_Append(heap, elem) == -1) {
Py_DECREF(elem);
goto fail;
}
Py_DECREF(elem);
}
if (PyList_GET_SIZE(heap) == 0)
goto sortit;
for (i=n/2-1 ; i>=0 ; i--)
if(_siftup((PyListObject *)heap, i) == -1)
goto fail;
for (i=n/2-1 ; i>=0 ; i--)
if(_siftup((PyListObject *)heap, i) == -1)
goto fail;
sol = PyList_GET_ITEM(heap, 0);
while (1) {
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
cmp = cmp_lt(sol, elem);
if (cmp == -1) {
Py_DECREF(elem);
goto fail;
}
if (cmp == 0) {
Py_DECREF(elem);
continue;
}
oldelem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, elem);
Py_DECREF(oldelem);
if (_siftup((PyListObject *)heap, 0) == -1)
goto fail;
sol = PyList_GET_ITEM(heap, 0);
}
sol = PyList_GET_ITEM(heap, 0);
while (1) {
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
cmp = cmp_lt(sol, elem);
if (cmp == -1) {
Py_DECREF(elem);
goto fail;
}
if (cmp == 0) {
Py_DECREF(elem);
continue;
}
oldelem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, elem);
Py_DECREF(oldelem);
if (_siftup((PyListObject *)heap, 0) == -1)
goto fail;
sol = PyList_GET_ITEM(heap, 0);
}
sortit:
if (PyList_Sort(heap) == -1)
goto fail;
if (PyList_Reverse(heap) == -1)
goto fail;
Py_DECREF(it);
return heap;
if (PyList_Sort(heap) == -1)
goto fail;
if (PyList_Reverse(heap) == -1)
goto fail;
Py_DECREF(it);
return heap;
fail:
Py_DECREF(it);
Py_XDECREF(heap);
return NULL;
Py_DECREF(it);
Py_XDECREF(heap);
return NULL;
}
PyDoc_STRVAR(nlargest_doc,
@ -356,166 +356,166 @@ Equivalent to: sorted(iterable, reverse=True)[:n]\n");
static int
_siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
{
PyObject *newitem, *parent;
int cmp;
Py_ssize_t parentpos;
PyObject *newitem, *parent;
int cmp;
Py_ssize_t parentpos;
assert(PyList_Check(heap));
if (pos >= PyList_GET_SIZE(heap)) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
assert(PyList_Check(heap));
if (pos >= PyList_GET_SIZE(heap)) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Follow the path to the root, moving parents down until finding
a place newitem fits. */
while (pos > startpos){
parentpos = (pos - 1) >> 1;
parent = PyList_GET_ITEM(heap, parentpos);
cmp = cmp_lt(parent, newitem);
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
break;
Py_INCREF(parent);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, parent);
pos = parentpos;
}
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return 0;
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Follow the path to the root, moving parents down until finding
a place newitem fits. */
while (pos > startpos){
parentpos = (pos - 1) >> 1;
parent = PyList_GET_ITEM(heap, parentpos);
cmp = cmp_lt(parent, newitem);
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
break;
Py_INCREF(parent);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, parent);
pos = parentpos;
}
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return 0;
}
static int
_siftupmax(PyListObject *heap, Py_ssize_t pos)
{
Py_ssize_t startpos, endpos, childpos, rightpos;
int cmp;
PyObject *newitem, *tmp;
Py_ssize_t startpos, endpos, childpos, rightpos;
int cmp;
PyObject *newitem, *tmp;
assert(PyList_Check(heap));
endpos = PyList_GET_SIZE(heap);
startpos = pos;
if (pos >= endpos) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
assert(PyList_Check(heap));
endpos = PyList_GET_SIZE(heap);
startpos = pos;
if (pos >= endpos) {
PyErr_SetString(PyExc_IndexError, "index out of range");
return -1;
}
newitem = PyList_GET_ITEM(heap, pos);
Py_INCREF(newitem);
/* Bubble up the smaller child until hitting a leaf. */
childpos = 2*pos + 1; /* leftmost child position */
while (childpos < endpos) {
/* Set childpos to index of smaller child. */
rightpos = childpos + 1;
if (rightpos < endpos) {
cmp = cmp_lt(
PyList_GET_ITEM(heap, rightpos),
PyList_GET_ITEM(heap, childpos));
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
childpos = rightpos;
}
/* Move the smaller child up. */
tmp = PyList_GET_ITEM(heap, childpos);
Py_INCREF(tmp);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, tmp);
pos = childpos;
childpos = 2*pos + 1;
}
/* Bubble up the smaller child until hitting a leaf. */
childpos = 2*pos + 1; /* leftmost child position */
while (childpos < endpos) {
/* Set childpos to index of smaller child. */
rightpos = childpos + 1;
if (rightpos < endpos) {
cmp = cmp_lt(
PyList_GET_ITEM(heap, rightpos),
PyList_GET_ITEM(heap, childpos));
if (cmp == -1) {
Py_DECREF(newitem);
return -1;
}
if (cmp == 0)
childpos = rightpos;
}
/* Move the smaller child up. */
tmp = PyList_GET_ITEM(heap, childpos);
Py_INCREF(tmp);
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, tmp);
pos = childpos;
childpos = 2*pos + 1;
}
/* The leaf at pos is empty now. Put newitem there, and and bubble
it up to its final resting place (by sifting its parents down). */
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return _siftdownmax(heap, startpos, pos);
/* The leaf at pos is empty now. Put newitem there, and and bubble
it up to its final resting place (by sifting its parents down). */
Py_DECREF(PyList_GET_ITEM(heap, pos));
PyList_SET_ITEM(heap, pos, newitem);
return _siftdownmax(heap, startpos, pos);
}
static PyObject *
nsmallest(PyObject *self, PyObject *args)
{
PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
Py_ssize_t i, n;
int cmp;
PyObject *heap=NULL, *elem, *iterable, *los, *it, *oldelem;
Py_ssize_t i, n;
int cmp;
if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable))
return NULL;
if (!PyArg_ParseTuple(args, "nO:nsmallest", &n, &iterable))
return NULL;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
heap = PyList_New(0);
if (heap == NULL)
goto fail;
heap = PyList_New(0);
if (heap == NULL)
goto fail;
for (i=0 ; i<n ; i++ ){
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
if (PyList_Append(heap, elem) == -1) {
Py_DECREF(elem);
goto fail;
}
Py_DECREF(elem);
}
n = PyList_GET_SIZE(heap);
if (n == 0)
goto sortit;
for (i=0 ; i<n ; i++ ){
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
if (PyList_Append(heap, elem) == -1) {
Py_DECREF(elem);
goto fail;
}
Py_DECREF(elem);
}
n = PyList_GET_SIZE(heap);
if (n == 0)
goto sortit;
for (i=n/2-1 ; i>=0 ; i--)
if(_siftupmax((PyListObject *)heap, i) == -1)
goto fail;
for (i=n/2-1 ; i>=0 ; i--)
if(_siftupmax((PyListObject *)heap, i) == -1)
goto fail;
los = PyList_GET_ITEM(heap, 0);
while (1) {
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
cmp = cmp_lt(elem, los);
if (cmp == -1) {
Py_DECREF(elem);
goto fail;
}
if (cmp == 0) {
Py_DECREF(elem);
continue;
}
los = PyList_GET_ITEM(heap, 0);
while (1) {
elem = PyIter_Next(it);
if (elem == NULL) {
if (PyErr_Occurred())
goto fail;
else
goto sortit;
}
cmp = cmp_lt(elem, los);
if (cmp == -1) {
Py_DECREF(elem);
goto fail;
}
if (cmp == 0) {
Py_DECREF(elem);
continue;
}
oldelem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, elem);
Py_DECREF(oldelem);
if (_siftupmax((PyListObject *)heap, 0) == -1)
goto fail;
los = PyList_GET_ITEM(heap, 0);
}
oldelem = PyList_GET_ITEM(heap, 0);
PyList_SET_ITEM(heap, 0, elem);
Py_DECREF(oldelem);
if (_siftupmax((PyListObject *)heap, 0) == -1)
goto fail;
los = PyList_GET_ITEM(heap, 0);
}
sortit:
if (PyList_Sort(heap) == -1)
goto fail;
Py_DECREF(it);
return heap;
if (PyList_Sort(heap) == -1)
goto fail;
Py_DECREF(it);
return heap;
fail:
Py_DECREF(it);
Py_XDECREF(heap);
return NULL;
Py_DECREF(it);
Py_XDECREF(heap);
return NULL;
}
PyDoc_STRVAR(nsmallest_doc,
@ -524,21 +524,21 @@ PyDoc_STRVAR(nsmallest_doc,
Equivalent to: sorted(iterable)[:n]\n");
static PyMethodDef heapq_methods[] = {
{"heappush", (PyCFunction)heappush,
METH_VARARGS, heappush_doc},
{"heappushpop", (PyCFunction)heappushpop,
METH_VARARGS, heappushpop_doc},
{"heappop", (PyCFunction)heappop,
METH_O, heappop_doc},
{"heapreplace", (PyCFunction)heapreplace,
METH_VARARGS, heapreplace_doc},
{"heapify", (PyCFunction)heapify,
METH_O, heapify_doc},
{"nlargest", (PyCFunction)nlargest,
METH_VARARGS, nlargest_doc},
{"nsmallest", (PyCFunction)nsmallest,
METH_VARARGS, nsmallest_doc},
{NULL, NULL} /* sentinel */
{"heappush", (PyCFunction)heappush,
METH_VARARGS, heappush_doc},
{"heappushpop", (PyCFunction)heappushpop,
METH_VARARGS, heappushpop_doc},
{"heappop", (PyCFunction)heappop,
METH_O, heappop_doc},
{"heapreplace", (PyCFunction)heapreplace,
METH_VARARGS, heapreplace_doc},
{"heapify", (PyCFunction)heapify,
METH_O, heapify_doc},
{"nlargest", (PyCFunction)nlargest,
METH_VARARGS, nlargest_doc},
{"nsmallest", (PyCFunction)nsmallest,
METH_VARARGS, nsmallest_doc},
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
@ -668,27 +668,27 @@ From all times, sorting has always been a Great Art! :-)\n");
static struct PyModuleDef _heapqmodule = {
PyModuleDef_HEAD_INIT,
"_heapq",
module_doc,
-1,
heapq_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_heapq",
module_doc,
-1,
heapq_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__heapq(void)
{
PyObject *m, *about;
PyObject *m, *about;
m = PyModule_Create(&_heapqmodule);
if (m == NULL)
return NULL;
about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL);
PyModule_AddObject(m, "__about__", about);
return m;
m = PyModule_Create(&_heapqmodule);
if (m == NULL)
return NULL;
about = PyUnicode_DecodeUTF8(__about__, strlen(__about__), NULL);
PyModule_AddObject(m, "__about__", about);
return m;
}

View file

@ -511,7 +511,7 @@ py_scanstring(PyObject* self UNUSED, PyObject *args)
rval = scanstring_unicode(pystr, end, strict, &next_end);
}
else {
PyErr_Format(PyExc_TypeError,
PyErr_Format(PyExc_TypeError,
"first argument must be a string or bytes, not %.80s",
Py_TYPE(pystr)->tp_name);
return NULL;
@ -1394,7 +1394,7 @@ encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ss
if (PyObject_IsTrue(s->sort_keys)) {
if (code == NULL) {
code = Py_CompileString("sorted(d.items(), key=lambda kv: kv[0])",
code = Py_CompileString("sorted(d.items(), key=lambda kv: kv[0])",
"_json.c", Py_eval_input);
if (code == NULL)
goto bail;
@ -1409,14 +1409,14 @@ encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ss
}
items = PyEval_EvalCode((PyCodeObject *)code, PyEval_GetGlobals(), mapping);
Py_DECREF(mapping);
} else {
} else {
items = PyMapping_Items(dct);
}
if (items == NULL)
}
if (items == NULL)
goto bail;
it = PyObject_GetIter(items);
Py_DECREF(items);
if (it == NULL)
Py_DECREF(items);
if (it == NULL)
goto bail;
skipkeys = PyObject_IsTrue(s->skipkeys);
idx = 0;
@ -1437,8 +1437,8 @@ encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ss
goto bail;
}
else if (key == Py_True || key == Py_False || key == Py_None) {
/* This must come before the PyLong_Check because
True and False are also 1 and 0.*/
/* This must come before the PyLong_Check because
True and False are also 1 and 0.*/
kstr = _encoded_const(key);
if (kstr == NULL)
goto bail;
@ -1704,15 +1704,15 @@ PyDoc_STRVAR(module_doc,
"json speedups\n");
static struct PyModuleDef jsonmodule = {
PyModuleDef_HEAD_INIT,
"_json",
module_doc,
-1,
speedups_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_json",
module_doc,
-1,
speedups_methods,
NULL,
NULL,
NULL,
NULL
};
PyObject*

View file

@ -77,7 +77,7 @@ str2uni(const char* s)
if (dest != smallbuf)
PyMem_Free(dest);
return res2;
}
}
/* support functions for formatting floating point numbers */
@ -243,7 +243,7 @@ PyLocale_strcoll(PyObject* self, PyObject* args)
PyObject *os1, *os2, *result = NULL;
wchar_t *ws1 = NULL, *ws2 = NULL;
Py_ssize_t len1, len2;
if (!PyArg_ParseTuple(args, "UU:strcoll", &os1, &os2))
return NULL;
/* Convert the unicode strings to wchar[]. */
@ -373,9 +373,9 @@ PyLocale_getdefaultlocale(PyObject* self)
#ifdef HAVE_LANGINFO_H
#define LANGINFO(X) {#X, X}
static struct langinfo_constant{
char* name;
int value;
} langinfo_constants[] =
char* name;
int value;
} langinfo_constants[] =
{
/* These constants should exist on any langinfo implementation */
LANGINFO(DAY_1),
@ -514,10 +514,10 @@ PyDoc_STRVAR(gettext__doc__,
static PyObject*
PyIntl_gettext(PyObject* self, PyObject *args)
{
char *in;
if (!PyArg_ParseTuple(args, "s", &in))
return 0;
return str2uni(gettext(in));
char *in;
if (!PyArg_ParseTuple(args, "s", &in))
return 0;
return str2uni(gettext(in));
}
PyDoc_STRVAR(dgettext__doc__,
@ -527,10 +527,10 @@ PyDoc_STRVAR(dgettext__doc__,
static PyObject*
PyIntl_dgettext(PyObject* self, PyObject *args)
{
char *domain, *in;
if (!PyArg_ParseTuple(args, "zs", &domain, &in))
return 0;
return str2uni(dgettext(domain, in));
char *domain, *in;
if (!PyArg_ParseTuple(args, "zs", &domain, &in))
return 0;
return str2uni(dgettext(domain, in));
}
PyDoc_STRVAR(dcgettext__doc__,
@ -540,11 +540,11 @@ PyDoc_STRVAR(dcgettext__doc__,
static PyObject*
PyIntl_dcgettext(PyObject *self, PyObject *args)
{
char *domain, *msgid;
int category;
if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category))
return 0;
return str2uni(dcgettext(domain,msgid,category));
char *domain, *msgid;
int category;
if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category))
return 0;
return str2uni(dcgettext(domain,msgid,category));
}
PyDoc_STRVAR(textdomain__doc__,
@ -554,15 +554,15 @@ PyDoc_STRVAR(textdomain__doc__,
static PyObject*
PyIntl_textdomain(PyObject* self, PyObject* args)
{
char *domain;
if (!PyArg_ParseTuple(args, "z", &domain))
return 0;
domain = textdomain(domain);
if (!domain) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return str2uni(domain);
char *domain;
if (!PyArg_ParseTuple(args, "z", &domain))
return 0;
domain = textdomain(domain);
if (!domain) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return str2uni(domain);
}
PyDoc_STRVAR(bindtextdomain__doc__,
@ -572,19 +572,19 @@ PyDoc_STRVAR(bindtextdomain__doc__,
static PyObject*
PyIntl_bindtextdomain(PyObject* self,PyObject*args)
{
char *domain, *dirname;
if (!PyArg_ParseTuple(args, "sz", &domain, &dirname))
return 0;
if (!strlen(domain)) {
PyErr_SetString(Error, "domain must be a non-empty string");
return 0;
}
dirname = bindtextdomain(domain, dirname);
if (!dirname) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return str2uni(dirname);
char *domain, *dirname;
if (!PyArg_ParseTuple(args, "sz", &domain, &dirname))
return 0;
if (!strlen(domain)) {
PyErr_SetString(Error, "domain must be a non-empty string");
return 0;
}
dirname = bindtextdomain(domain, dirname);
if (!dirname) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return str2uni(dirname);
}
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
@ -595,32 +595,32 @@ PyDoc_STRVAR(bind_textdomain_codeset__doc__,
static PyObject*
PyIntl_bind_textdomain_codeset(PyObject* self,PyObject*args)
{
char *domain,*codeset;
if (!PyArg_ParseTuple(args, "sz", &domain, &codeset))
return NULL;
codeset = bind_textdomain_codeset(domain, codeset);
if (codeset)
return str2uni(codeset);
Py_RETURN_NONE;
char *domain,*codeset;
if (!PyArg_ParseTuple(args, "sz", &domain, &codeset))
return NULL;
codeset = bind_textdomain_codeset(domain, codeset);
if (codeset)
return str2uni(codeset);
Py_RETURN_NONE;
}
#endif
#endif
static struct PyMethodDef PyLocale_Methods[] = {
{"setlocale", (PyCFunction) PyLocale_setlocale,
{"setlocale", (PyCFunction) PyLocale_setlocale,
METH_VARARGS, setlocale__doc__},
{"localeconv", (PyCFunction) PyLocale_localeconv,
{"localeconv", (PyCFunction) PyLocale_localeconv,
METH_NOARGS, localeconv__doc__},
#ifdef HAVE_WCSCOLL
{"strcoll", (PyCFunction) PyLocale_strcoll,
{"strcoll", (PyCFunction) PyLocale_strcoll,
METH_VARARGS, strcoll__doc__},
#endif
#ifdef HAVE_WCSXFRM
{"strxfrm", (PyCFunction) PyLocale_strxfrm,
{"strxfrm", (PyCFunction) PyLocale_strxfrm,
METH_VARARGS, strxfrm__doc__},
#endif
#if defined(MS_WINDOWS)
#if defined(MS_WINDOWS)
{"_getdefaultlocale", (PyCFunction) PyLocale_getdefaultlocale, METH_NOARGS},
#endif
#ifdef HAVE_LANGINFO_H
@ -642,21 +642,21 @@ static struct PyMethodDef PyLocale_Methods[] = {
{"bind_textdomain_codeset",(PyCFunction)PyIntl_bind_textdomain_codeset,
METH_VARARGS, bind_textdomain_codeset__doc__},
#endif
#endif
#endif
{NULL, NULL}
};
static struct PyModuleDef _localemodule = {
PyModuleDef_HEAD_INIT,
"_locale",
locale__doc__,
-1,
PyLocale_Methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_locale",
locale__doc__,
-1,
PyLocale_Methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
@ -669,7 +669,7 @@ PyInit__locale(void)
m = PyModule_Create(&_localemodule);
if (m == NULL)
return NULL;
return NULL;
d = PyModule_GetDict(m);
@ -712,14 +712,14 @@ PyInit__locale(void)
#ifdef HAVE_LANGINFO_H
for (i = 0; langinfo_constants[i].name; i++) {
PyModule_AddIntConstant(m, langinfo_constants[i].name,
langinfo_constants[i].value);
PyModule_AddIntConstant(m, langinfo_constants[i].name,
langinfo_constants[i].value);
}
#endif
return m;
}
/*
/*
Local variables:
c-basic-offset: 4
indent-tabs-mode: nil

File diff suppressed because it is too large Load diff

View file

@ -14,7 +14,7 @@
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
@ -27,11 +27,11 @@ static const double zero = 0.0;
/* acosh(x)
* Method :
* Based on
* acosh(x) = log [ x + sqrt(x*x-1) ]
* acosh(x) = log [ x + sqrt(x*x-1) ]
* we have
* acosh(x) := log(x)+ln2, if x is large; else
* acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else
* acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1.
* acosh(x) := log(x)+ln2, if x is large; else
* acosh(x) := log(2x-1/(sqrt(x*x-1)+x)) if x>2; else
* acosh(x) := log1p(t+sqrt(2.0*t+t*t)); where t=x-1.
*
* Special cases:
* acosh(x) is NaN with signal if x<1.
@ -41,82 +41,82 @@ static const double zero = 0.0;
double
_Py_acosh(double x)
{
if (Py_IS_NAN(x)) {
return x+x;
}
if (x < 1.) { /* x < 1; return a signaling NaN */
errno = EDOM;
if (Py_IS_NAN(x)) {
return x+x;
}
if (x < 1.) { /* x < 1; return a signaling NaN */
errno = EDOM;
#ifdef Py_NAN
return Py_NAN;
return Py_NAN;
#else
return (x-x)/(x-x);
return (x-x)/(x-x);
#endif
}
else if (x >= two_pow_p28) { /* x > 2**28 */
if (Py_IS_INFINITY(x)) {
return x+x;
} else {
return log(x)+ln2; /* acosh(huge)=log(2x) */
}
}
else if (x == 1.) {
return 0.0; /* acosh(1) = 0 */
}
else if (x > 2.) { /* 2 < x < 2**28 */
double t = x*x;
return log(2.0*x - 1.0 / (x + sqrt(t - 1.0)));
}
else { /* 1 < x <= 2 */
double t = x - 1.0;
return m_log1p(t + sqrt(2.0*t + t*t));
}
}
else if (x >= two_pow_p28) { /* x > 2**28 */
if (Py_IS_INFINITY(x)) {
return x+x;
} else {
return log(x)+ln2; /* acosh(huge)=log(2x) */
}
}
else if (x == 1.) {
return 0.0; /* acosh(1) = 0 */
}
else if (x > 2.) { /* 2 < x < 2**28 */
double t = x*x;
return log(2.0*x - 1.0 / (x + sqrt(t - 1.0)));
}
else { /* 1 < x <= 2 */
double t = x - 1.0;
return m_log1p(t + sqrt(2.0*t + t*t));
}
}
/* asinh(x)
* Method :
* Based on
* asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ]
* we have
* asinh(x) := x if 1+x*x=1,
* := sign(x)*(log(x)+ln2)) for large |x|, else
* := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else
* := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2)))
* Based on
* asinh(x) = sign(x) * log [ |x| + sqrt(x*x+1) ]
* we have
* asinh(x) := x if 1+x*x=1,
* := sign(x)*(log(x)+ln2)) for large |x|, else
* := sign(x)*log(2|x|+1/(|x|+sqrt(x*x+1))) if|x|>2, else
* := sign(x)*log1p(|x| + x^2/(1 + sqrt(1+x^2)))
*/
double
_Py_asinh(double x)
{
double w;
double absx = fabs(x);
{
double w;
double absx = fabs(x);
if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) {
return x+x;
}
if (absx < two_pow_m28) { /* |x| < 2**-28 */
return x; /* return x inexact except 0 */
}
if (absx > two_pow_p28) { /* |x| > 2**28 */
w = log(absx)+ln2;
}
else if (absx > 2.0) { /* 2 < |x| < 2**28 */
w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx));
}
else { /* 2**-28 <= |x| < 2= */
double t = x*x;
w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t)));
}
return copysign(w, x);
if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) {
return x+x;
}
if (absx < two_pow_m28) { /* |x| < 2**-28 */
return x; /* return x inexact except 0 */
}
if (absx > two_pow_p28) { /* |x| > 2**28 */
w = log(absx)+ln2;
}
else if (absx > 2.0) { /* 2 < |x| < 2**28 */
w = log(2.0*absx + 1.0 / (sqrt(x*x + 1.0) + absx));
}
else { /* 2**-28 <= |x| < 2= */
double t = x*x;
w = m_log1p(absx + t / (1.0 + sqrt(1.0 + t)));
}
return copysign(w, x);
}
/* atanh(x)
* Method :
* 1.Reduced x to positive by atanh(-x) = -atanh(x)
* 2.For x>=0.5
* 1 2x x
* 1 2x x
* atanh(x) = --- * log(1 + -------) = 0.5 * log1p(2 * --------)
* 2 1 - x 1 - x
* 2 1 - x 1 - x
*
* For x<0.5
* atanh(x) = 0.5*log1p(2x+2x*x/(1-x))
@ -130,32 +130,32 @@ _Py_asinh(double x)
double
_Py_atanh(double x)
{
double absx;
double t;
double absx;
double t;
if (Py_IS_NAN(x)) {
return x+x;
}
absx = fabs(x);
if (absx >= 1.) { /* |x| >= 1 */
errno = EDOM;
if (Py_IS_NAN(x)) {
return x+x;
}
absx = fabs(x);
if (absx >= 1.) { /* |x| >= 1 */
errno = EDOM;
#ifdef Py_NAN
return Py_NAN;
return Py_NAN;
#else
return x/zero;
return x/zero;
#endif
}
if (absx < two_pow_m28) { /* |x| < 2**-28 */
return x;
}
if (absx < 0.5) { /* |x| < 0.5 */
t = absx+absx;
t = 0.5 * m_log1p(t + t*absx / (1.0 - absx));
}
else { /* 0.5 <= |x| <= 1.0 */
t = 0.5 * m_log1p((absx + absx) / (1.0 - absx));
}
return copysign(t, x);
}
if (absx < two_pow_m28) { /* |x| < 2**-28 */
return x;
}
if (absx < 0.5) { /* |x| < 0.5 */
t = absx+absx;
t = 0.5 * m_log1p(t + t*absx / (1.0 - absx));
}
else { /* 0.5 <= |x| <= 1.0 */
t = 0.5 * m_log1p((absx + absx) / (1.0 - absx));
}
return copysign(t, x);
}
/* Mathematically, expm1(x) = exp(x) - 1. The expm1 function is designed
@ -173,15 +173,15 @@ _Py_expm1(double x)
*/
if (fabs(x) < 0.7) {
double u;
u = exp(x);
if (u == 1.0)
return x;
else
return (u - 1.0) * x / log(u);
double u;
u = exp(x);
if (u == 1.0)
return x;
else
return (u - 1.0) * x / log(u);
}
else
return exp(x) - 1.0;
return exp(x) - 1.0;
}
/* log1p(x) = log(1+x). The log1p function is designed to avoid the
@ -194,7 +194,7 @@ _Py_log1p(double x)
/* For x small, we use the following approach. Let y be the nearest float
to 1+x, then
1+x = y * (1 - (y-1-x)/y)
1+x = y * (1 - (y-1-x)/y)
so log(1+x) = log(y) + log(1-(y-1-x)/y). Since (y-1-x)/y is tiny, the
second term is well approximated by (y-1-x)/y. If abs(x) >=
@ -213,17 +213,17 @@ _Py_log1p(double x)
double y;
if (fabs(x) < DBL_EPSILON/2.) {
return x;
return x;
} else if (-0.5 <= x && x <= 1.) {
/* WARNING: it's possible than an overeager compiler
will incorrectly optimize the following two lines
to the equivalent of "return log(1.+x)". If this
happens, then results from log1p will be inaccurate
for small x. */
y = 1.+x;
return log(y)-((y-1.)-x)/y;
/* WARNING: it's possible than an overeager compiler
will incorrectly optimize the following two lines
to the equivalent of "return log(1.+x)". If this
happens, then results from log1p will be inaccurate
for small x. */
y = 1.+x;
return log(y)-((y-1.)-x)/y;
} else {
/* NaNs and infinities should end up here */
return log(1.+x);
/* NaNs and infinities should end up here */
return log(1.+x);
}
}

View file

@ -1,5 +1,5 @@
/*
* Definition of a `Connection` type.
* Definition of a `Connection` type.
* Used by `socket_connection.c` and `pipe_connection.c`.
*
* connection.h
@ -19,14 +19,14 @@
#define CHECK_READABLE(self) \
if (!(self->flags & READABLE)) { \
PyErr_SetString(PyExc_IOError, "connection is write-only"); \
return NULL; \
PyErr_SetString(PyExc_IOError, "connection is write-only"); \
return NULL; \
}
#define CHECK_WRITABLE(self) \
if (!(self->flags & WRITABLE)) { \
PyErr_SetString(PyExc_IOError, "connection is read-only"); \
return NULL; \
PyErr_SetString(PyExc_IOError, "connection is read-only"); \
return NULL; \
}
/*
@ -36,57 +36,57 @@
static PyObject *
connection_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
ConnectionObject *self;
HANDLE handle;
BOOL readable = TRUE, writable = TRUE;
ConnectionObject *self;
HANDLE handle;
BOOL readable = TRUE, writable = TRUE;
static char *kwlist[] = {"handle", "readable", "writable", NULL};
static char *kwlist[] = {"handle", "readable", "writable", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist,
&handle, &readable, &writable))
return NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, F_HANDLE "|ii", kwlist,
&handle, &readable, &writable))
return NULL;
if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) {
PyErr_Format(PyExc_IOError, "invalid handle %zd",
(Py_ssize_t)handle);
return NULL;
}
if (handle == INVALID_HANDLE_VALUE || (Py_ssize_t)handle < 0) {
PyErr_Format(PyExc_IOError, "invalid handle %zd",
(Py_ssize_t)handle);
return NULL;
}
if (!readable && !writable) {
PyErr_SetString(PyExc_ValueError,
"either readable or writable must be true");
return NULL;
}
if (!readable && !writable) {
PyErr_SetString(PyExc_ValueError,
"either readable or writable must be true");
return NULL;
}
self = PyObject_New(ConnectionObject, type);
if (self == NULL)
return NULL;
self = PyObject_New(ConnectionObject, type);
if (self == NULL)
return NULL;
self->weakreflist = NULL;
self->handle = handle;
self->flags = 0;
self->weakreflist = NULL;
self->handle = handle;
self->flags = 0;
if (readable)
self->flags |= READABLE;
if (writable)
self->flags |= WRITABLE;
assert(self->flags >= 1 && self->flags <= 3);
if (readable)
self->flags |= READABLE;
if (writable)
self->flags |= WRITABLE;
assert(self->flags >= 1 && self->flags <= 3);
return (PyObject*)self;
return (PyObject*)self;
}
static void
connection_dealloc(ConnectionObject* self)
{
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject*)self);
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject*)self);
if (self->handle != INVALID_HANDLE_VALUE) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
}
PyObject_Del(self);
if (self->handle != INVALID_HANDLE_VALUE) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
}
PyObject_Del(self);
}
/*
@ -96,168 +96,168 @@ connection_dealloc(ConnectionObject* self)
static PyObject *
connection_sendbytes(ConnectionObject *self, PyObject *args)
{
Py_buffer pbuffer;
char *buffer;
Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN;
int res;
Py_buffer pbuffer;
char *buffer;
Py_ssize_t length, offset=0, size=PY_SSIZE_T_MIN;
int res;
if (!PyArg_ParseTuple(args, F_RBUFFER "*|" F_PY_SSIZE_T F_PY_SSIZE_T,
&pbuffer, &offset, &size))
return NULL;
buffer = pbuffer.buf;
length = pbuffer.len;
if (!PyArg_ParseTuple(args, F_RBUFFER "*|" F_PY_SSIZE_T F_PY_SSIZE_T,
&pbuffer, &offset, &size))
return NULL;
buffer = pbuffer.buf;
length = pbuffer.len;
CHECK_WRITABLE(self); /* XXX release buffer in case of failure */
CHECK_WRITABLE(self); /* XXX release buffer in case of failure */
if (offset < 0) {
PyBuffer_Release(&pbuffer);
PyErr_SetString(PyExc_ValueError, "offset is negative");
return NULL;
}
if (length < offset) {
PyBuffer_Release(&pbuffer);
PyErr_SetString(PyExc_ValueError, "buffer length < offset");
return NULL;
}
if (offset < 0) {
PyBuffer_Release(&pbuffer);
PyErr_SetString(PyExc_ValueError, "offset is negative");
return NULL;
}
if (length < offset) {
PyBuffer_Release(&pbuffer);
PyErr_SetString(PyExc_ValueError, "buffer length < offset");
return NULL;
}
if (size == PY_SSIZE_T_MIN) {
size = length - offset;
} else {
if (size < 0) {
PyBuffer_Release(&pbuffer);
PyErr_SetString(PyExc_ValueError, "size is negative");
return NULL;
}
if (offset + size > length) {
PyBuffer_Release(&pbuffer);
PyErr_SetString(PyExc_ValueError,
"buffer length < offset + size");
return NULL;
}
}
if (size == PY_SSIZE_T_MIN) {
size = length - offset;
} else {
if (size < 0) {
PyBuffer_Release(&pbuffer);
PyErr_SetString(PyExc_ValueError, "size is negative");
return NULL;
}
if (offset + size > length) {
PyBuffer_Release(&pbuffer);
PyErr_SetString(PyExc_ValueError,
"buffer length < offset + size");
return NULL;
}
}
res = conn_send_string(self, buffer + offset, size);
res = conn_send_string(self, buffer + offset, size);
PyBuffer_Release(&pbuffer);
if (res < 0) {
if (PyErr_Occurred())
return NULL;
else
return mp_SetError(PyExc_IOError, res);
}
PyBuffer_Release(&pbuffer);
if (res < 0) {
if (PyErr_Occurred())
return NULL;
else
return mp_SetError(PyExc_IOError, res);
}
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyObject *
connection_recvbytes(ConnectionObject *self, PyObject *args)
connection_recvbytes(ConnectionObject *self, PyObject *args)
{
char *freeme = NULL;
Py_ssize_t res, maxlength = PY_SSIZE_T_MAX;
PyObject *result = NULL;
char *freeme = NULL;
Py_ssize_t res, maxlength = PY_SSIZE_T_MAX;
PyObject *result = NULL;
if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength))
return NULL;
if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength))
return NULL;
CHECK_READABLE(self);
if (maxlength < 0) {
PyErr_SetString(PyExc_ValueError, "maxlength < 0");
return NULL;
}
res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
&freeme, maxlength);
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
result = PyBytes_FromStringAndSize(self->buffer, res);
} else {
result = PyBytes_FromStringAndSize(freeme, res);
PyMem_Free(freeme);
}
}
return result;
CHECK_READABLE(self);
if (maxlength < 0) {
PyErr_SetString(PyExc_ValueError, "maxlength < 0");
return NULL;
}
res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
&freeme, maxlength);
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
result = PyBytes_FromStringAndSize(self->buffer, res);
} else {
result = PyBytes_FromStringAndSize(freeme, res);
PyMem_Free(freeme);
}
}
return result;
}
static PyObject *
connection_recvbytes_into(ConnectionObject *self, PyObject *args)
connection_recvbytes_into(ConnectionObject *self, PyObject *args)
{
char *freeme = NULL, *buffer = NULL;
Py_ssize_t res, length, offset = 0;
PyObject *result = NULL;
Py_buffer pbuf;
char *freeme = NULL, *buffer = NULL;
Py_ssize_t res, length, offset = 0;
PyObject *result = NULL;
Py_buffer pbuf;
CHECK_READABLE(self);
if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T,
&pbuf, &offset))
return NULL;
CHECK_READABLE(self);
buffer = pbuf.buf;
length = pbuf.len;
if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T,
&pbuf, &offset))
return NULL;
if (offset < 0) {
PyErr_SetString(PyExc_ValueError, "negative offset");
goto _error;
}
buffer = pbuf.buf;
length = pbuf.len;
if (offset > length) {
PyErr_SetString(PyExc_ValueError, "offset too large");
goto _error;
}
if (offset < 0) {
PyErr_SetString(PyExc_ValueError, "negative offset");
goto _error;
}
res = conn_recv_string(self, buffer+offset, length-offset,
&freeme, PY_SSIZE_T_MAX);
if (offset > length) {
PyErr_SetString(PyExc_ValueError, "offset too large");
goto _error;
}
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
result = PyInt_FromSsize_t(res);
} else {
result = PyObject_CallFunction(BufferTooShort,
F_RBUFFER "#",
freeme, res);
PyMem_Free(freeme);
if (result) {
PyErr_SetObject(BufferTooShort, result);
Py_DECREF(result);
}
goto _error;
}
}
res = conn_recv_string(self, buffer+offset, length-offset,
&freeme, PY_SSIZE_T_MAX);
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
result = PyInt_FromSsize_t(res);
} else {
result = PyObject_CallFunction(BufferTooShort,
F_RBUFFER "#",
freeme, res);
PyMem_Free(freeme);
if (result) {
PyErr_SetObject(BufferTooShort, result);
Py_DECREF(result);
}
goto _error;
}
}
_cleanup:
PyBuffer_Release(&pbuf);
return result;
PyBuffer_Release(&pbuf);
return result;
_error:
result = NULL;
goto _cleanup;
result = NULL;
goto _cleanup;
}
/*
@ -267,74 +267,74 @@ _error:
static PyObject *
connection_send_obj(ConnectionObject *self, PyObject *obj)
{
char *buffer;
int res;
Py_ssize_t length;
PyObject *pickled_string = NULL;
char *buffer;
int res;
Py_ssize_t length;
PyObject *pickled_string = NULL;
CHECK_WRITABLE(self);
CHECK_WRITABLE(self);
pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj,
pickle_protocol, NULL);
if (!pickled_string)
goto failure;
pickled_string = PyObject_CallFunctionObjArgs(pickle_dumps, obj,
pickle_protocol, NULL);
if (!pickled_string)
goto failure;
if (PyBytes_AsStringAndSize(pickled_string, &buffer, &length) < 0)
goto failure;
if (PyBytes_AsStringAndSize(pickled_string, &buffer, &length) < 0)
goto failure;
res = conn_send_string(self, buffer, (int)length);
res = conn_send_string(self, buffer, (int)length);
if (res < 0) {
mp_SetError(PyExc_IOError, res);
goto failure;
}
if (res < 0) {
mp_SetError(PyExc_IOError, res);
goto failure;
}
Py_XDECREF(pickled_string);
Py_RETURN_NONE;
Py_XDECREF(pickled_string);
Py_RETURN_NONE;
failure:
Py_XDECREF(pickled_string);
return NULL;
Py_XDECREF(pickled_string);
return NULL;
}
static PyObject *
connection_recv_obj(ConnectionObject *self)
{
char *freeme = NULL;
Py_ssize_t res;
PyObject *temp = NULL, *result = NULL;
char *freeme = NULL;
Py_ssize_t res;
PyObject *temp = NULL, *result = NULL;
CHECK_READABLE(self);
CHECK_READABLE(self);
res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
&freeme, PY_SSIZE_T_MAX);
res = conn_recv_string(self, self->buffer, CONNECTION_BUFFER_SIZE,
&freeme, PY_SSIZE_T_MAX);
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
temp = PyBytes_FromStringAndSize(self->buffer, res);
} else {
temp = PyBytes_FromStringAndSize(freeme, res);
PyMem_Free(freeme);
}
}
if (res < 0) {
if (res == MP_BAD_MESSAGE_LENGTH) {
if ((self->flags & WRITABLE) == 0) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
} else {
self->flags = WRITABLE;
}
}
mp_SetError(PyExc_IOError, res);
} else {
if (freeme == NULL) {
temp = PyBytes_FromStringAndSize(self->buffer, res);
} else {
temp = PyBytes_FromStringAndSize(freeme, res);
PyMem_Free(freeme);
}
}
if (temp)
result = PyObject_CallFunctionObjArgs(pickle_loads,
temp, NULL);
Py_XDECREF(temp);
return result;
if (temp)
result = PyObject_CallFunctionObjArgs(pickle_loads,
temp, NULL);
Py_XDECREF(temp);
return result;
}
/*
@ -344,73 +344,73 @@ connection_recv_obj(ConnectionObject *self)
static PyObject *
connection_poll(ConnectionObject *self, PyObject *args)
{
PyObject *timeout_obj = NULL;
double timeout = 0.0;
int res;
PyObject *timeout_obj = NULL;
double timeout = 0.0;
int res;
CHECK_READABLE(self);
CHECK_READABLE(self);
if (!PyArg_ParseTuple(args, "|O", &timeout_obj))
return NULL;
if (!PyArg_ParseTuple(args, "|O", &timeout_obj))
return NULL;
if (timeout_obj == NULL) {
timeout = 0.0;
} else if (timeout_obj == Py_None) {
timeout = -1.0; /* block forever */
} else {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
if (timeout < 0.0)
timeout = 0.0;
}
if (timeout_obj == NULL) {
timeout = 0.0;
} else if (timeout_obj == Py_None) {
timeout = -1.0; /* block forever */
} else {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
if (timeout < 0.0)
timeout = 0.0;
}
Py_BEGIN_ALLOW_THREADS
res = conn_poll(self, timeout, _save);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
res = conn_poll(self, timeout, _save);
Py_END_ALLOW_THREADS
switch (res) {
case TRUE:
Py_RETURN_TRUE;
case FALSE:
Py_RETURN_FALSE;
default:
return mp_SetError(PyExc_IOError, res);
}
switch (res) {
case TRUE:
Py_RETURN_TRUE;
case FALSE:
Py_RETURN_FALSE;
default:
return mp_SetError(PyExc_IOError, res);
}
}
static PyObject *
connection_fileno(ConnectionObject* self)
{
if (self->handle == INVALID_HANDLE_VALUE) {
PyErr_SetString(PyExc_IOError, "handle is invalid");
return NULL;
}
return PyInt_FromLong((long)self->handle);
if (self->handle == INVALID_HANDLE_VALUE) {
PyErr_SetString(PyExc_IOError, "handle is invalid");
return NULL;
}
return PyInt_FromLong((long)self->handle);
}
static PyObject *
connection_close(ConnectionObject *self)
{
if (self->handle != INVALID_HANDLE_VALUE) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
}
if (self->handle != INVALID_HANDLE_VALUE) {
Py_BEGIN_ALLOW_THREADS
CLOSE(self->handle);
Py_END_ALLOW_THREADS
self->handle = INVALID_HANDLE_VALUE;
}
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyObject *
connection_repr(ConnectionObject *self)
{
static char *conn_type[] = {"read-only", "write-only", "read-write"};
static char *conn_type[] = {"read-only", "write-only", "read-write"};
assert(self->flags >= 1 && self->flags <= 3);
return FROM_FORMAT("<%s %s, handle %zd>",
conn_type[self->flags - 1],
CONNECTION_NAME, (Py_ssize_t)self->handle);
assert(self->flags >= 1 && self->flags <= 3);
return FROM_FORMAT("<%s %s, handle %zd>",
conn_type[self->flags - 1],
CONNECTION_NAME, (Py_ssize_t)self->handle);
}
/*
@ -420,19 +420,19 @@ connection_repr(ConnectionObject *self)
static PyObject *
connection_closed(ConnectionObject *self, void *closure)
{
return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE));
return PyBool_FromLong((long)(self->handle == INVALID_HANDLE_VALUE));
}
static PyObject *
connection_readable(ConnectionObject *self, void *closure)
{
return PyBool_FromLong((long)(self->flags & READABLE));
return PyBool_FromLong((long)(self->flags & READABLE));
}
static PyObject *
connection_writable(ConnectionObject *self, void *closure)
{
return PyBool_FromLong((long)(self->flags & WRITABLE));
return PyBool_FromLong((long)(self->flags & WRITABLE));
}
/*
@ -440,37 +440,37 @@ connection_writable(ConnectionObject *self, void *closure)
*/
static PyMethodDef connection_methods[] = {
{"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS,
"send the byte data from a readable buffer-like object"},
{"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS,
"receive byte data as a string"},
{"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS,
"receive byte data into a writeable buffer-like object\n"
"returns the number of bytes read"},
{"send_bytes", (PyCFunction)connection_sendbytes, METH_VARARGS,
"send the byte data from a readable buffer-like object"},
{"recv_bytes", (PyCFunction)connection_recvbytes, METH_VARARGS,
"receive byte data as a string"},
{"recv_bytes_into",(PyCFunction)connection_recvbytes_into,METH_VARARGS,
"receive byte data into a writeable buffer-like object\n"
"returns the number of bytes read"},
{"send", (PyCFunction)connection_send_obj, METH_O,
"send a (picklable) object"},
{"recv", (PyCFunction)connection_recv_obj, METH_NOARGS,
"receive a (picklable) object"},
{"send", (PyCFunction)connection_send_obj, METH_O,
"send a (picklable) object"},
{"recv", (PyCFunction)connection_recv_obj, METH_NOARGS,
"receive a (picklable) object"},
{"poll", (PyCFunction)connection_poll, METH_VARARGS,
"whether there is any input available to be read"},
{"fileno", (PyCFunction)connection_fileno, METH_NOARGS,
"file descriptor or handle of the connection"},
{"close", (PyCFunction)connection_close, METH_NOARGS,
"close the connection"},
{"poll", (PyCFunction)connection_poll, METH_VARARGS,
"whether there is any input available to be read"},
{"fileno", (PyCFunction)connection_fileno, METH_NOARGS,
"file descriptor or handle of the connection"},
{"close", (PyCFunction)connection_close, METH_NOARGS,
"close the connection"},
{NULL} /* Sentinel */
{NULL} /* Sentinel */
};
static PyGetSetDef connection_getset[] = {
{"closed", (getter)connection_closed, NULL,
"True if the connection is closed", NULL},
{"readable", (getter)connection_readable, NULL,
"True if the connection is readable", NULL},
{"writable", (getter)connection_writable, NULL,
"True if the connection is writable", NULL},
{NULL}
{"closed", (getter)connection_closed, NULL,
"True if the connection is closed", NULL},
{"readable", (getter)connection_readable, NULL,
"True if the connection is readable", NULL},
{"writable", (getter)connection_writable, NULL,
"True if the connection is writable", NULL},
{NULL}
};
/*
@ -478,50 +478,50 @@ static PyGetSetDef connection_getset[] = {
*/
PyDoc_STRVAR(connection_doc,
"Connection type whose constructor signature is\n\n"
" Connection(handle, readable=True, writable=True).\n\n"
"The constructor does *not* duplicate the handle.");
"Connection type whose constructor signature is\n\n"
" Connection(handle, readable=True, writable=True).\n\n"
"The constructor does *not* duplicate the handle.");
PyTypeObject CONNECTION_TYPE = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "_multiprocessing." CONNECTION_NAME,
/* tp_basicsize */ sizeof(ConnectionObject),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)connection_dealloc,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ (reprfunc)connection_repr,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Py_TPFLAGS_HAVE_WEAKREFS,
/* tp_doc */ connection_doc,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist),
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ connection_methods,
/* tp_members */ 0,
/* tp_getset */ connection_getset,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ connection_new,
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "_multiprocessing." CONNECTION_NAME,
/* tp_basicsize */ sizeof(ConnectionObject),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)connection_dealloc,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ (reprfunc)connection_repr,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Py_TPFLAGS_HAVE_WEAKREFS,
/* tp_doc */ connection_doc,
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklistoffset */ offsetof(ConnectionObject, weakreflist),
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ connection_methods,
/* tp_members */ 0,
/* tp_getset */ connection_getset,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ connection_new,
};
#endif /* CONNECTION_H */

View file

@ -9,9 +9,9 @@
#include "multiprocessing.h"
#ifdef SCM_RIGHTS
#define HAVE_FD_TRANSFER 1
#define HAVE_FD_TRANSFER 1
#else
#define HAVE_FD_TRANSFER 0
#define HAVE_FD_TRANSFER 0
#endif
PyObject *create_win32_namespace(void);
@ -26,46 +26,46 @@ PyObject *ProcessError, *BufferTooShort;
PyObject *
mp_SetError(PyObject *Type, int num)
{
switch (num) {
switch (num) {
#ifdef MS_WINDOWS
case MP_STANDARD_ERROR:
if (Type == NULL)
Type = PyExc_WindowsError;
PyErr_SetExcFromWindowsErr(Type, 0);
break;
case MP_SOCKET_ERROR:
if (Type == NULL)
Type = PyExc_WindowsError;
PyErr_SetExcFromWindowsErr(Type, WSAGetLastError());
break;
case MP_STANDARD_ERROR:
if (Type == NULL)
Type = PyExc_WindowsError;
PyErr_SetExcFromWindowsErr(Type, 0);
break;
case MP_SOCKET_ERROR:
if (Type == NULL)
Type = PyExc_WindowsError;
PyErr_SetExcFromWindowsErr(Type, WSAGetLastError());
break;
#else /* !MS_WINDOWS */
case MP_STANDARD_ERROR:
case MP_SOCKET_ERROR:
if (Type == NULL)
Type = PyExc_OSError;
PyErr_SetFromErrno(Type);
break;
case MP_STANDARD_ERROR:
case MP_SOCKET_ERROR:
if (Type == NULL)
Type = PyExc_OSError;
PyErr_SetFromErrno(Type);
break;
#endif /* !MS_WINDOWS */
case MP_MEMORY_ERROR:
PyErr_NoMemory();
break;
case MP_END_OF_FILE:
PyErr_SetNone(PyExc_EOFError);
break;
case MP_EARLY_END_OF_FILE:
PyErr_SetString(PyExc_IOError,
"got end of file during message");
break;
case MP_BAD_MESSAGE_LENGTH:
PyErr_SetString(PyExc_IOError, "bad message length");
break;
case MP_EXCEPTION_HAS_BEEN_SET:
break;
default:
PyErr_Format(PyExc_RuntimeError,
"unkown error number %d", num);
}
return NULL;
case MP_MEMORY_ERROR:
PyErr_NoMemory();
break;
case MP_END_OF_FILE:
PyErr_SetNone(PyExc_EOFError);
break;
case MP_EARLY_END_OF_FILE:
PyErr_SetString(PyExc_IOError,
"got end of file during message");
break;
case MP_BAD_MESSAGE_LENGTH:
PyErr_SetString(PyExc_IOError, "bad message length");
break;
case MP_EXCEPTION_HAS_BEEN_SET:
break;
default:
PyErr_Format(PyExc_RuntimeError,
"unkown error number %d", num);
}
return NULL;
}
@ -82,8 +82,8 @@ HANDLE sigint_event = NULL;
static BOOL WINAPI
ProcessingCtrlHandler(DWORD dwCtrlType)
{
SetEvent(sigint_event);
return FALSE;
SetEvent(sigint_event);
return FALSE;
}
/*
@ -101,72 +101,72 @@ ProcessingCtrlHandler(DWORD dwCtrlType)
static PyObject *
multiprocessing_sendfd(PyObject *self, PyObject *args)
{
int conn, fd, res;
char dummy_char;
char buf[CMSG_SPACE(sizeof(int))];
struct msghdr msg = {0};
struct iovec dummy_iov;
struct cmsghdr *cmsg;
int conn, fd, res;
char dummy_char;
char buf[CMSG_SPACE(sizeof(int))];
struct msghdr msg = {0};
struct iovec dummy_iov;
struct cmsghdr *cmsg;
if (!PyArg_ParseTuple(args, "ii", &conn, &fd))
return NULL;
if (!PyArg_ParseTuple(args, "ii", &conn, &fd))
return NULL;
dummy_iov.iov_base = &dummy_char;
dummy_iov.iov_len = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
msg.msg_iov = &dummy_iov;
msg.msg_iovlen = 1;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
msg.msg_controllen = cmsg->cmsg_len;
*(int*)CMSG_DATA(cmsg) = fd;
dummy_iov.iov_base = &dummy_char;
dummy_iov.iov_len = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
msg.msg_iov = &dummy_iov;
msg.msg_iovlen = 1;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
msg.msg_controllen = cmsg->cmsg_len;
*(int*)CMSG_DATA(cmsg) = fd;
Py_BEGIN_ALLOW_THREADS
res = sendmsg(conn, &msg, 0);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
res = sendmsg(conn, &msg, 0);
Py_END_ALLOW_THREADS
if (res < 0)
return PyErr_SetFromErrno(PyExc_OSError);
Py_RETURN_NONE;
if (res < 0)
return PyErr_SetFromErrno(PyExc_OSError);
Py_RETURN_NONE;
}
static PyObject *
multiprocessing_recvfd(PyObject *self, PyObject *args)
{
int conn, fd, res;
char dummy_char;
char buf[CMSG_SPACE(sizeof(int))];
struct msghdr msg = {0};
struct iovec dummy_iov;
struct cmsghdr *cmsg;
int conn, fd, res;
char dummy_char;
char buf[CMSG_SPACE(sizeof(int))];
struct msghdr msg = {0};
struct iovec dummy_iov;
struct cmsghdr *cmsg;
if (!PyArg_ParseTuple(args, "i", &conn))
return NULL;
if (!PyArg_ParseTuple(args, "i", &conn))
return NULL;
dummy_iov.iov_base = &dummy_char;
dummy_iov.iov_len = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
msg.msg_iov = &dummy_iov;
msg.msg_iovlen = 1;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
msg.msg_controllen = cmsg->cmsg_len;
dummy_iov.iov_base = &dummy_char;
dummy_iov.iov_len = 1;
msg.msg_control = buf;
msg.msg_controllen = sizeof(buf);
msg.msg_iov = &dummy_iov;
msg.msg_iovlen = 1;
cmsg = CMSG_FIRSTHDR(&msg);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int));
msg.msg_controllen = cmsg->cmsg_len;
Py_BEGIN_ALLOW_THREADS
res = recvmsg(conn, &msg, 0);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
res = recvmsg(conn, &msg, 0);
Py_END_ALLOW_THREADS
if (res < 0)
return PyErr_SetFromErrno(PyExc_OSError);
if (res < 0)
return PyErr_SetFromErrno(PyExc_OSError);
fd = *(int*)CMSG_DATA(cmsg);
return Py_BuildValue("i", fd);
fd = *(int*)CMSG_DATA(cmsg);
return Py_BuildValue("i", fd);
}
#endif /* HAVE_FD_TRANSFER */
@ -181,14 +181,14 @@ multiprocessing_recvfd(PyObject *self, PyObject *args)
static PyObject*
multiprocessing_address_of_buffer(PyObject *self, PyObject *obj)
{
void *buffer;
Py_ssize_t buffer_len;
void *buffer;
Py_ssize_t buffer_len;
if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0)
return NULL;
if (PyObject_AsWriteBuffer(obj, &buffer, &buffer_len) < 0)
return NULL;
return Py_BuildValue("N" F_PY_SSIZE_T,
PyLong_FromVoidPtr(buffer), buffer_len);
return Py_BuildValue("N" F_PY_SSIZE_T,
PyLong_FromVoidPtr(buffer), buffer_len);
}
@ -197,20 +197,20 @@ multiprocessing_address_of_buffer(PyObject *self, PyObject *obj)
*/
static PyMethodDef module_methods[] = {
{"address_of_buffer", multiprocessing_address_of_buffer, METH_O,
"address_of_buffer(obj) -> int\n"
"Return address of obj assuming obj supports buffer inteface"},
{"address_of_buffer", multiprocessing_address_of_buffer, METH_O,
"address_of_buffer(obj) -> int\n"
"Return address of obj assuming obj supports buffer inteface"},
#if HAVE_FD_TRANSFER
{"sendfd", multiprocessing_sendfd, METH_VARARGS,
"sendfd(sockfd, fd) -> None\n"
"Send file descriptor given by fd over the unix domain socket\n"
"whose file decriptor is sockfd"},
{"recvfd", multiprocessing_recvfd, METH_VARARGS,
"recvfd(sockfd) -> fd\n"
"Receive a file descriptor over a unix domain socket\n"
"whose file decriptor is sockfd"},
{"sendfd", multiprocessing_sendfd, METH_VARARGS,
"sendfd(sockfd, fd) -> None\n"
"Send file descriptor given by fd over the unix domain socket\n"
"whose file decriptor is sockfd"},
{"recvfd", multiprocessing_recvfd, METH_VARARGS,
"recvfd(sockfd) -> fd\n"
"Receive a file descriptor over a unix domain socket\n"
"whose file decriptor is sockfd"},
#endif
{NULL}
{NULL}
};
@ -219,117 +219,117 @@ static PyMethodDef module_methods[] = {
*/
static struct PyModuleDef multiprocessing_module = {
PyModuleDef_HEAD_INIT,
"_multiprocessing",
NULL,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_multiprocessing",
NULL,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyMODINIT_FUNC
PyInit__multiprocessing(void)
{
PyObject *module, *temp, *value;
PyObject *module, *temp, *value;
/* Initialize module */
module = PyModule_Create(&multiprocessing_module);
if (!module)
return NULL;
/* Initialize module */
module = PyModule_Create(&multiprocessing_module);
if (!module)
return NULL;
/* Get copy of objects from pickle */
temp = PyImport_ImportModule(PICKLE_MODULE);
if (!temp)
return NULL;
pickle_dumps = PyObject_GetAttrString(temp, "dumps");
pickle_loads = PyObject_GetAttrString(temp, "loads");
pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL");
Py_XDECREF(temp);
/* Get copy of objects from pickle */
temp = PyImport_ImportModule(PICKLE_MODULE);
if (!temp)
return NULL;
pickle_dumps = PyObject_GetAttrString(temp, "dumps");
pickle_loads = PyObject_GetAttrString(temp, "loads");
pickle_protocol = PyObject_GetAttrString(temp, "HIGHEST_PROTOCOL");
Py_XDECREF(temp);
/* Get copy of BufferTooShort */
temp = PyImport_ImportModule("multiprocessing");
if (!temp)
return NULL;
BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
Py_XDECREF(temp);
/* Get copy of BufferTooShort */
temp = PyImport_ImportModule("multiprocessing");
if (!temp)
return NULL;
BufferTooShort = PyObject_GetAttrString(temp, "BufferTooShort");
Py_XDECREF(temp);
/* Add connection type to module */
if (PyType_Ready(&ConnectionType) < 0)
return NULL;
Py_INCREF(&ConnectionType);
PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType);
/* Add connection type to module */
if (PyType_Ready(&ConnectionType) < 0)
return NULL;
Py_INCREF(&ConnectionType);
PyModule_AddObject(module, "Connection", (PyObject*)&ConnectionType);
#if defined(MS_WINDOWS) || \
#if defined(MS_WINDOWS) || \
(defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED))
/* Add SemLock type to module */
if (PyType_Ready(&SemLockType) < 0)
return NULL;
Py_INCREF(&SemLockType);
PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX",
Py_BuildValue("i", SEM_VALUE_MAX));
PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType);
/* Add SemLock type to module */
if (PyType_Ready(&SemLockType) < 0)
return NULL;
Py_INCREF(&SemLockType);
PyDict_SetItemString(SemLockType.tp_dict, "SEM_VALUE_MAX",
Py_BuildValue("i", SEM_VALUE_MAX));
PyModule_AddObject(module, "SemLock", (PyObject*)&SemLockType);
#endif
#ifdef MS_WINDOWS
/* Add PipeConnection to module */
if (PyType_Ready(&PipeConnectionType) < 0)
return NULL;
Py_INCREF(&PipeConnectionType);
PyModule_AddObject(module, "PipeConnection",
(PyObject*)&PipeConnectionType);
/* Add PipeConnection to module */
if (PyType_Ready(&PipeConnectionType) < 0)
return NULL;
Py_INCREF(&PipeConnectionType);
PyModule_AddObject(module, "PipeConnection",
(PyObject*)&PipeConnectionType);
/* Initialize win32 class and add to multiprocessing */
temp = create_win32_namespace();
if (!temp)
return NULL;
PyModule_AddObject(module, "win32", temp);
/* Initialize win32 class and add to multiprocessing */
temp = create_win32_namespace();
if (!temp)
return NULL;
PyModule_AddObject(module, "win32", temp);
/* Initialize the event handle used to signal Ctrl-C */
sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!sigint_event) {
PyErr_SetFromWindowsErr(0);
return NULL;
}
if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
PyErr_SetFromWindowsErr(0);
return NULL;
}
/* Initialize the event handle used to signal Ctrl-C */
sigint_event = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!sigint_event) {
PyErr_SetFromWindowsErr(0);
return NULL;
}
if (!SetConsoleCtrlHandler(ProcessingCtrlHandler, TRUE)) {
PyErr_SetFromWindowsErr(0);
return NULL;
}
#endif
/* Add configuration macros */
temp = PyDict_New();
if (!temp)
return NULL;
/* Add configuration macros */
temp = PyDict_New();
if (!temp)
return NULL;
#define ADD_FLAG(name) \
value = Py_BuildValue("i", name); \
if (value == NULL) { Py_DECREF(temp); return NULL; } \
if (PyDict_SetItemString(temp, #name, value) < 0) { \
Py_DECREF(temp); Py_DECREF(value); return NULL; } \
Py_DECREF(value)
#define ADD_FLAG(name) \
value = Py_BuildValue("i", name); \
if (value == NULL) { Py_DECREF(temp); return NULL; } \
if (PyDict_SetItemString(temp, #name, value) < 0) { \
Py_DECREF(temp); Py_DECREF(value); return NULL; } \
Py_DECREF(value)
#if defined(HAVE_SEM_OPEN) && !defined(POSIX_SEMAPHORES_NOT_ENABLED)
ADD_FLAG(HAVE_SEM_OPEN);
ADD_FLAG(HAVE_SEM_OPEN);
#endif
#ifdef HAVE_SEM_TIMEDWAIT
ADD_FLAG(HAVE_SEM_TIMEDWAIT);
ADD_FLAG(HAVE_SEM_TIMEDWAIT);
#endif
#ifdef HAVE_FD_TRANSFER
ADD_FLAG(HAVE_FD_TRANSFER);
ADD_FLAG(HAVE_FD_TRANSFER);
#endif
#ifdef HAVE_BROKEN_SEM_GETVALUE
ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE);
ADD_FLAG(HAVE_BROKEN_SEM_GETVALUE);
#endif
#ifdef HAVE_BROKEN_SEM_UNLINK
ADD_FLAG(HAVE_BROKEN_SEM_UNLINK);
ADD_FLAG(HAVE_BROKEN_SEM_UNLINK);
#endif
if (PyModule_AddObject(module, "flags", temp) < 0)
return NULL;
if (PyModule_AddObject(module, "flags", temp) < 0)
return NULL;
return module;
return module;
}

View file

@ -15,7 +15,7 @@
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# include <winsock2.h>
# include <process.h> /* getpid() */
# include <process.h> /* getpid() */
# ifdef Py_DEBUG
# include <crtdbg.h>
# endif
@ -45,15 +45,15 @@
* Issue 3110 - Solaris does not define SEM_VALUE_MAX
*/
#ifndef SEM_VALUE_MAX
#if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX)
# define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX)
#elif defined(_SEM_VALUE_MAX)
# define SEM_VALUE_MAX _SEM_VALUE_MAX
#elif defined(_POSIX_SEM_VALUE_MAX)
# define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX
#else
# define SEM_VALUE_MAX INT_MAX
#endif
#if defined(HAVE_SYSCONF) && defined(_SC_SEM_VALUE_MAX)
# define SEM_VALUE_MAX sysconf(_SC_SEM_VALUE_MAX)
#elif defined(_SEM_VALUE_MAX)
# define SEM_VALUE_MAX _SEM_VALUE_MAX
#elif defined(_POSIX_SEM_VALUE_MAX)
# define SEM_VALUE_MAX _POSIX_SEM_VALUE_MAX
#else
# define SEM_VALUE_MAX INT_MAX
#endif
#endif
@ -162,11 +162,11 @@ extern HANDLE sigint_event;
#define CONNECTION_BUFFER_SIZE 1024
typedef struct {
PyObject_HEAD
HANDLE handle;
int flags;
PyObject *weakreflist;
char buffer[CONNECTION_BUFFER_SIZE];
PyObject_HEAD
HANDLE handle;
int flags;
PyObject *weakreflist;
char buffer[CONNECTION_BUFFER_SIZE];
} ConnectionObject;
/*

View file

@ -17,19 +17,19 @@
static Py_ssize_t
conn_send_string(ConnectionObject *conn, char *string, size_t length)
{
DWORD amount_written;
BOOL ret;
DWORD amount_written;
BOOL ret;
Py_BEGIN_ALLOW_THREADS
ret = WriteFile(conn->handle, string, length, &amount_written, NULL);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
ret = WriteFile(conn->handle, string, length, &amount_written, NULL);
Py_END_ALLOW_THREADS
if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) {
PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length);
return MP_STANDARD_ERROR;
}
if (ret == 0 && GetLastError() == ERROR_NO_SYSTEM_RESOURCES) {
PyErr_Format(PyExc_ValueError, "Cannnot send %" PY_FORMAT_SIZE_T "d bytes over connection", length);
return MP_STANDARD_ERROR;
}
return ret ? MP_SUCCESS : MP_STANDARD_ERROR;
return ret ? MP_SUCCESS : MP_STANDARD_ERROR;
}
/*
@ -39,50 +39,50 @@ conn_send_string(ConnectionObject *conn, char *string, size_t length)
*/
static Py_ssize_t
conn_recv_string(ConnectionObject *conn, char *buffer,
size_t buflength, char **newbuffer, size_t maxlength)
conn_recv_string(ConnectionObject *conn, char *buffer,
size_t buflength, char **newbuffer, size_t maxlength)
{
DWORD left, length, full_length, err;
BOOL ret;
*newbuffer = NULL;
DWORD left, length, full_length, err;
BOOL ret;
*newbuffer = NULL;
Py_BEGIN_ALLOW_THREADS
ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength),
&length, NULL);
Py_END_ALLOW_THREADS
if (ret)
return length;
Py_BEGIN_ALLOW_THREADS
ret = ReadFile(conn->handle, buffer, MIN(buflength, maxlength),
&length, NULL);
Py_END_ALLOW_THREADS
if (ret)
return length;
err = GetLastError();
if (err != ERROR_MORE_DATA) {
if (err == ERROR_BROKEN_PIPE)
return MP_END_OF_FILE;
return MP_STANDARD_ERROR;
}
err = GetLastError();
if (err != ERROR_MORE_DATA) {
if (err == ERROR_BROKEN_PIPE)
return MP_END_OF_FILE;
return MP_STANDARD_ERROR;
}
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left))
return MP_STANDARD_ERROR;
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, NULL, &left))
return MP_STANDARD_ERROR;
full_length = length + left;
if (full_length > maxlength)
return MP_BAD_MESSAGE_LENGTH;
full_length = length + left;
if (full_length > maxlength)
return MP_BAD_MESSAGE_LENGTH;
*newbuffer = PyMem_Malloc(full_length);
if (*newbuffer == NULL)
return MP_MEMORY_ERROR;
*newbuffer = PyMem_Malloc(full_length);
if (*newbuffer == NULL)
return MP_MEMORY_ERROR;
memcpy(*newbuffer, buffer, length);
memcpy(*newbuffer, buffer, length);
Py_BEGIN_ALLOW_THREADS
ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL);
Py_END_ALLOW_THREADS
if (ret) {
assert(length == left);
return full_length;
} else {
PyMem_Free(*newbuffer);
return MP_STANDARD_ERROR;
}
Py_BEGIN_ALLOW_THREADS
ret = ReadFile(conn->handle, *newbuffer+length, left, &length, NULL);
Py_END_ALLOW_THREADS
if (ret) {
assert(length == left);
return full_length;
} else {
PyMem_Free(*newbuffer);
return MP_STANDARD_ERROR;
}
}
/*
@ -92,51 +92,51 @@ conn_recv_string(ConnectionObject *conn, char *buffer,
static int
conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save)
{
DWORD bytes, deadline, delay;
int difference, res;
BOOL block = FALSE;
DWORD bytes, deadline, delay;
int difference, res;
BOOL block = FALSE;
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
return MP_STANDARD_ERROR;
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
return MP_STANDARD_ERROR;
if (timeout == 0.0)
return bytes > 0;
if (timeout == 0.0)
return bytes > 0;
if (timeout < 0.0)
block = TRUE;
else
/* XXX does not check for overflow */
deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5);
if (timeout < 0.0)
block = TRUE;
else
/* XXX does not check for overflow */
deadline = GetTickCount() + (DWORD)(1000 * timeout + 0.5);
Sleep(0);
Sleep(0);
for (delay = 1 ; ; delay += 1) {
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
return MP_STANDARD_ERROR;
else if (bytes > 0)
return TRUE;
for (delay = 1 ; ; delay += 1) {
if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
return MP_STANDARD_ERROR;
else if (bytes > 0)
return TRUE;
if (!block) {
difference = deadline - GetTickCount();
if (difference < 0)
return FALSE;
if ((int)delay > difference)
delay = difference;
}
if (!block) {
difference = deadline - GetTickCount();
if (difference < 0)
return FALSE;
if ((int)delay > difference)
delay = difference;
}
if (delay > 20)
delay = 20;
if (delay > 20)
delay = 20;
Sleep(delay);
Sleep(delay);
/* check for signals */
Py_BLOCK_THREADS
res = PyErr_CheckSignals();
Py_UNBLOCK_THREADS
/* check for signals */
Py_BLOCK_THREADS
res = PyErr_CheckSignals();
Py_UNBLOCK_THREADS
if (res)
return MP_EXCEPTION_HAS_BEEN_SET;
}
if (res)
return MP_EXCEPTION_HAS_BEEN_SET;
}
}
/*

View file

@ -11,12 +11,12 @@
enum { RECURSIVE_MUTEX, SEMAPHORE };
typedef struct {
PyObject_HEAD
SEM_HANDLE handle;
long last_tid;
int count;
int maxvalue;
int kind;
PyObject_HEAD
SEM_HANDLE handle;
long last_tid;
int count;
int maxvalue;
int kind;
} SemLockObject;
#define ISMINE(o) (o->count > 0 && PyThread_get_thread_ident() == o->last_tid)
@ -40,148 +40,148 @@ typedef struct {
static int
_GetSemaphoreValue(HANDLE handle, long *value)
{
long previous;
long previous;
switch (WaitForSingleObject(handle, 0)) {
case WAIT_OBJECT_0:
if (!ReleaseSemaphore(handle, 1, &previous))
return MP_STANDARD_ERROR;
*value = previous + 1;
return 0;
case WAIT_TIMEOUT:
*value = 0;
return 0;
default:
return MP_STANDARD_ERROR;
}
switch (WaitForSingleObject(handle, 0)) {
case WAIT_OBJECT_0:
if (!ReleaseSemaphore(handle, 1, &previous))
return MP_STANDARD_ERROR;
*value = previous + 1;
return 0;
case WAIT_TIMEOUT:
*value = 0;
return 0;
default:
return MP_STANDARD_ERROR;
}
}
static PyObject *
semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds)
{
int blocking = 1;
double timeout;
PyObject *timeout_obj = Py_None;
DWORD res, full_msecs, msecs, start, ticks;
int blocking = 1;
double timeout;
PyObject *timeout_obj = Py_None;
DWORD res, full_msecs, msecs, start, ticks;
static char *kwlist[] = {"block", "timeout", NULL};
static char *kwlist[] = {"block", "timeout", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
&blocking, &timeout_obj))
return NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
&blocking, &timeout_obj))
return NULL;
/* calculate timeout */
if (!blocking) {
full_msecs = 0;
} else if (timeout_obj == Py_None) {
full_msecs = INFINITE;
} else {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
timeout *= 1000.0; /* convert to millisecs */
if (timeout < 0.0) {
timeout = 0.0;
} else if (timeout >= 0.5 * INFINITE) { /* 25 days */
PyErr_SetString(PyExc_OverflowError,
"timeout is too large");
return NULL;
}
full_msecs = (DWORD)(timeout + 0.5);
}
/* check whether we already own the lock */
if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
++self->count;
Py_RETURN_TRUE;
}
/* calculate timeout */
if (!blocking) {
full_msecs = 0;
} else if (timeout_obj == Py_None) {
full_msecs = INFINITE;
} else {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
timeout *= 1000.0; /* convert to millisecs */
if (timeout < 0.0) {
timeout = 0.0;
} else if (timeout >= 0.5 * INFINITE) { /* 25 days */
PyErr_SetString(PyExc_OverflowError,
"timeout is too large");
return NULL;
}
full_msecs = (DWORD)(timeout + 0.5);
}
/* check whether we can acquire without blocking */
if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) {
self->last_tid = GetCurrentThreadId();
++self->count;
Py_RETURN_TRUE;
}
msecs = full_msecs;
start = GetTickCount();
/* check whether we already own the lock */
if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
++self->count;
Py_RETURN_TRUE;
}
for ( ; ; ) {
HANDLE handles[2] = {self->handle, sigint_event};
/* do the wait */
Py_BEGIN_ALLOW_THREADS
ResetEvent(sigint_event);
res = WaitForMultipleObjects(2, handles, FALSE, msecs);
Py_END_ALLOW_THREADS
/* handle result */
if (res != WAIT_OBJECT_0 + 1)
break;
/* got SIGINT so give signal handler a chance to run */
Sleep(1);
/* if this is main thread let KeyboardInterrupt be raised */
if (PyErr_CheckSignals())
return NULL;
/* recalculate timeout */
if (msecs != INFINITE) {
ticks = GetTickCount();
if ((DWORD)(ticks - start) >= full_msecs)
Py_RETURN_FALSE;
msecs = full_msecs - (ticks - start);
}
}
/* handle result */
switch (res) {
case WAIT_TIMEOUT:
Py_RETURN_FALSE;
case WAIT_OBJECT_0:
self->last_tid = GetCurrentThreadId();
++self->count;
Py_RETURN_TRUE;
case WAIT_FAILED:
return PyErr_SetFromWindowsErr(0);
default:
PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or "
"WaitForMultipleObjects() gave unrecognized "
"value %d", res);
return NULL;
}
/* check whether we can acquire without blocking */
if (WaitForSingleObject(self->handle, 0) == WAIT_OBJECT_0) {
self->last_tid = GetCurrentThreadId();
++self->count;
Py_RETURN_TRUE;
}
msecs = full_msecs;
start = GetTickCount();
for ( ; ; ) {
HANDLE handles[2] = {self->handle, sigint_event};
/* do the wait */
Py_BEGIN_ALLOW_THREADS
ResetEvent(sigint_event);
res = WaitForMultipleObjects(2, handles, FALSE, msecs);
Py_END_ALLOW_THREADS
/* handle result */
if (res != WAIT_OBJECT_0 + 1)
break;
/* got SIGINT so give signal handler a chance to run */
Sleep(1);
/* if this is main thread let KeyboardInterrupt be raised */
if (PyErr_CheckSignals())
return NULL;
/* recalculate timeout */
if (msecs != INFINITE) {
ticks = GetTickCount();
if ((DWORD)(ticks - start) >= full_msecs)
Py_RETURN_FALSE;
msecs = full_msecs - (ticks - start);
}
}
/* handle result */
switch (res) {
case WAIT_TIMEOUT:
Py_RETURN_FALSE;
case WAIT_OBJECT_0:
self->last_tid = GetCurrentThreadId();
++self->count;
Py_RETURN_TRUE;
case WAIT_FAILED:
return PyErr_SetFromWindowsErr(0);
default:
PyErr_Format(PyExc_RuntimeError, "WaitForSingleObject() or "
"WaitForMultipleObjects() gave unrecognized "
"value %d", res);
return NULL;
}
}
static PyObject *
semlock_release(SemLockObject *self, PyObject *args)
{
if (self->kind == RECURSIVE_MUTEX) {
if (!ISMINE(self)) {
PyErr_SetString(PyExc_AssertionError, "attempt to "
"release recursive lock not owned "
"by thread");
return NULL;
}
if (self->count > 1) {
--self->count;
Py_RETURN_NONE;
}
assert(self->count == 1);
}
if (self->kind == RECURSIVE_MUTEX) {
if (!ISMINE(self)) {
PyErr_SetString(PyExc_AssertionError, "attempt to "
"release recursive lock not owned "
"by thread");
return NULL;
}
if (self->count > 1) {
--self->count;
Py_RETURN_NONE;
}
assert(self->count == 1);
}
if (!ReleaseSemaphore(self->handle, 1, NULL)) {
if (GetLastError() == ERROR_TOO_MANY_POSTS) {
PyErr_SetString(PyExc_ValueError, "semaphore or lock "
"released too many times");
return NULL;
} else {
return PyErr_SetFromWindowsErr(0);
}
}
if (!ReleaseSemaphore(self->handle, 1, NULL)) {
if (GetLastError() == ERROR_TOO_MANY_POSTS) {
PyErr_SetString(PyExc_ValueError, "semaphore or lock "
"released too many times");
return NULL;
} else {
return PyErr_SetFromWindowsErr(0);
}
}
--self->count;
Py_RETURN_NONE;
--self->count;
Py_RETURN_NONE;
}
#else /* !MS_WINDOWS */
@ -207,59 +207,59 @@ semlock_release(SemLockObject *self, PyObject *args)
int
sem_timedwait_save(sem_t *sem, struct timespec *deadline, PyThreadState *_save)
{
int res;
unsigned long delay, difference;
struct timeval now, tvdeadline, tvdelay;
int res;
unsigned long delay, difference;
struct timeval now, tvdeadline, tvdelay;
errno = 0;
tvdeadline.tv_sec = deadline->tv_sec;
tvdeadline.tv_usec = deadline->tv_nsec / 1000;
errno = 0;
tvdeadline.tv_sec = deadline->tv_sec;
tvdeadline.tv_usec = deadline->tv_nsec / 1000;
for (delay = 0 ; ; delay += 1000) {
/* poll */
if (sem_trywait(sem) == 0)
return 0;
else if (errno != EAGAIN)
return MP_STANDARD_ERROR;
for (delay = 0 ; ; delay += 1000) {
/* poll */
if (sem_trywait(sem) == 0)
return 0;
else if (errno != EAGAIN)
return MP_STANDARD_ERROR;
/* get current time */
if (gettimeofday(&now, NULL) < 0)
return MP_STANDARD_ERROR;
/* get current time */
if (gettimeofday(&now, NULL) < 0)
return MP_STANDARD_ERROR;
/* check for timeout */
if (tvdeadline.tv_sec < now.tv_sec ||
(tvdeadline.tv_sec == now.tv_sec &&
tvdeadline.tv_usec <= now.tv_usec)) {
errno = ETIMEDOUT;
return MP_STANDARD_ERROR;
}
/* check for timeout */
if (tvdeadline.tv_sec < now.tv_sec ||
(tvdeadline.tv_sec == now.tv_sec &&
tvdeadline.tv_usec <= now.tv_usec)) {
errno = ETIMEDOUT;
return MP_STANDARD_ERROR;
}
/* calculate how much time is left */
difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 +
(tvdeadline.tv_usec - now.tv_usec);
/* calculate how much time is left */
difference = (tvdeadline.tv_sec - now.tv_sec) * 1000000 +
(tvdeadline.tv_usec - now.tv_usec);
/* check delay not too long -- maximum is 20 msecs */
if (delay > 20000)
delay = 20000;
if (delay > difference)
delay = difference;
/* check delay not too long -- maximum is 20 msecs */
if (delay > 20000)
delay = 20000;
if (delay > difference)
delay = difference;
/* sleep */
tvdelay.tv_sec = delay / 1000000;
tvdelay.tv_usec = delay % 1000000;
if (select(0, NULL, NULL, NULL, &tvdelay) < 0)
return MP_STANDARD_ERROR;
/* sleep */
tvdelay.tv_sec = delay / 1000000;
tvdelay.tv_usec = delay % 1000000;
if (select(0, NULL, NULL, NULL, &tvdelay) < 0)
return MP_STANDARD_ERROR;
/* check for signals */
Py_BLOCK_THREADS
res = PyErr_CheckSignals();
Py_UNBLOCK_THREADS
/* check for signals */
Py_BLOCK_THREADS
res = PyErr_CheckSignals();
Py_UNBLOCK_THREADS
if (res) {
errno = EINTR;
return MP_EXCEPTION_HAS_BEEN_SET;
}
}
if (res) {
errno = EINTR;
return MP_EXCEPTION_HAS_BEEN_SET;
}
}
}
#endif /* !HAVE_SEM_TIMEDWAIT */
@ -267,129 +267,129 @@ sem_timedwait_save(sem_t *sem, struct timespec *deadline, PyThreadState *_save)
static PyObject *
semlock_acquire(SemLockObject *self, PyObject *args, PyObject *kwds)
{
int blocking = 1, res;
double timeout;
PyObject *timeout_obj = Py_None;
struct timespec deadline = {0};
struct timeval now;
long sec, nsec;
int blocking = 1, res;
double timeout;
PyObject *timeout_obj = Py_None;
struct timespec deadline = {0};
struct timeval now;
long sec, nsec;
static char *kwlist[] = {"block", "timeout", NULL};
static char *kwlist[] = {"block", "timeout", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
&blocking, &timeout_obj))
return NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO", kwlist,
&blocking, &timeout_obj))
return NULL;
if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
++self->count;
Py_RETURN_TRUE;
}
if (self->kind == RECURSIVE_MUTEX && ISMINE(self)) {
++self->count;
Py_RETURN_TRUE;
}
if (timeout_obj != Py_None) {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
if (timeout < 0.0)
timeout = 0.0;
if (timeout_obj != Py_None) {
timeout = PyFloat_AsDouble(timeout_obj);
if (PyErr_Occurred())
return NULL;
if (timeout < 0.0)
timeout = 0.0;
if (gettimeofday(&now, NULL) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
sec = (long) timeout;
nsec = (long) (1e9 * (timeout - sec) + 0.5);
deadline.tv_sec = now.tv_sec + sec;
deadline.tv_nsec = now.tv_usec * 1000 + nsec;
deadline.tv_sec += (deadline.tv_nsec / 1000000000);
deadline.tv_nsec %= 1000000000;
}
if (gettimeofday(&now, NULL) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
sec = (long) timeout;
nsec = (long) (1e9 * (timeout - sec) + 0.5);
deadline.tv_sec = now.tv_sec + sec;
deadline.tv_nsec = now.tv_usec * 1000 + nsec;
deadline.tv_sec += (deadline.tv_nsec / 1000000000);
deadline.tv_nsec %= 1000000000;
}
do {
Py_BEGIN_ALLOW_THREADS
if (blocking && timeout_obj == Py_None)
res = sem_wait(self->handle);
else if (!blocking)
res = sem_trywait(self->handle);
else
res = sem_timedwait(self->handle, &deadline);
Py_END_ALLOW_THREADS
if (res == MP_EXCEPTION_HAS_BEEN_SET)
break;
} while (res < 0 && errno == EINTR && !PyErr_CheckSignals());
do {
Py_BEGIN_ALLOW_THREADS
if (blocking && timeout_obj == Py_None)
res = sem_wait(self->handle);
else if (!blocking)
res = sem_trywait(self->handle);
else
res = sem_timedwait(self->handle, &deadline);
Py_END_ALLOW_THREADS
if (res == MP_EXCEPTION_HAS_BEEN_SET)
break;
} while (res < 0 && errno == EINTR && !PyErr_CheckSignals());
if (res < 0) {
if (errno == EAGAIN || errno == ETIMEDOUT)
Py_RETURN_FALSE;
else if (errno == EINTR)
return NULL;
else
return PyErr_SetFromErrno(PyExc_OSError);
}
if (res < 0) {
if (errno == EAGAIN || errno == ETIMEDOUT)
Py_RETURN_FALSE;
else if (errno == EINTR)
return NULL;
else
return PyErr_SetFromErrno(PyExc_OSError);
}
++self->count;
self->last_tid = PyThread_get_thread_ident();
++self->count;
self->last_tid = PyThread_get_thread_ident();
Py_RETURN_TRUE;
Py_RETURN_TRUE;
}
static PyObject *
semlock_release(SemLockObject *self, PyObject *args)
{
if (self->kind == RECURSIVE_MUTEX) {
if (!ISMINE(self)) {
PyErr_SetString(PyExc_AssertionError, "attempt to "
"release recursive lock not owned "
"by thread");
return NULL;
}
if (self->count > 1) {
--self->count;
Py_RETURN_NONE;
}
assert(self->count == 1);
} else {
if (self->kind == RECURSIVE_MUTEX) {
if (!ISMINE(self)) {
PyErr_SetString(PyExc_AssertionError, "attempt to "
"release recursive lock not owned "
"by thread");
return NULL;
}
if (self->count > 1) {
--self->count;
Py_RETURN_NONE;
}
assert(self->count == 1);
} else {
#ifdef HAVE_BROKEN_SEM_GETVALUE
/* We will only check properly the maxvalue == 1 case */
if (self->maxvalue == 1) {
/* make sure that already locked */
if (sem_trywait(self->handle) < 0) {
if (errno != EAGAIN) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
/* it is already locked as expected */
} else {
/* it was not locked so undo wait and raise */
if (sem_post(self->handle) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
PyErr_SetString(PyExc_ValueError, "semaphore "
"or lock released too many "
"times");
return NULL;
}
}
/* We will only check properly the maxvalue == 1 case */
if (self->maxvalue == 1) {
/* make sure that already locked */
if (sem_trywait(self->handle) < 0) {
if (errno != EAGAIN) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
/* it is already locked as expected */
} else {
/* it was not locked so undo wait and raise */
if (sem_post(self->handle) < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
PyErr_SetString(PyExc_ValueError, "semaphore "
"or lock released too many "
"times");
return NULL;
}
}
#else
int sval;
int sval;
/* This check is not an absolute guarantee that the semaphore
does not rise above maxvalue. */
if (sem_getvalue(self->handle, &sval) < 0) {
return PyErr_SetFromErrno(PyExc_OSError);
} else if (sval >= self->maxvalue) {
PyErr_SetString(PyExc_ValueError, "semaphore or lock "
"released too many times");
return NULL;
}
/* This check is not an absolute guarantee that the semaphore
does not rise above maxvalue. */
if (sem_getvalue(self->handle, &sval) < 0) {
return PyErr_SetFromErrno(PyExc_OSError);
} else if (sval >= self->maxvalue) {
PyErr_SetString(PyExc_ValueError, "semaphore or lock "
"released too many times");
return NULL;
}
#endif
}
}
if (sem_post(self->handle) < 0)
return PyErr_SetFromErrno(PyExc_OSError);
if (sem_post(self->handle) < 0)
return PyErr_SetFromErrno(PyExc_OSError);
--self->count;
Py_RETURN_NONE;
--self->count;
Py_RETURN_NONE;
}
#endif /* !MS_WINDOWS */
@ -401,111 +401,111 @@ semlock_release(SemLockObject *self, PyObject *args)
static PyObject *
newsemlockobject(PyTypeObject *type, SEM_HANDLE handle, int kind, int maxvalue)
{
SemLockObject *self;
SemLockObject *self;
self = PyObject_New(SemLockObject, type);
if (!self)
return NULL;
self->handle = handle;
self->kind = kind;
self->count = 0;
self->last_tid = 0;
self->maxvalue = maxvalue;
return (PyObject*)self;
self = PyObject_New(SemLockObject, type);
if (!self)
return NULL;
self->handle = handle;
self->kind = kind;
self->count = 0;
self->last_tid = 0;
self->maxvalue = maxvalue;
return (PyObject*)self;
}
static PyObject *
semlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
char buffer[256];
SEM_HANDLE handle = SEM_FAILED;
int kind, maxvalue, value;
PyObject *result;
static char *kwlist[] = {"kind", "value", "maxvalue", NULL};
static int counter = 0;
char buffer[256];
SEM_HANDLE handle = SEM_FAILED;
int kind, maxvalue, value;
PyObject *result;
static char *kwlist[] = {"kind", "value", "maxvalue", NULL};
static int counter = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist,
&kind, &value, &maxvalue))
return NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "iii", kwlist,
&kind, &value, &maxvalue))
return NULL;
if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) {
PyErr_SetString(PyExc_ValueError, "unrecognized kind");
return NULL;
}
if (kind != RECURSIVE_MUTEX && kind != SEMAPHORE) {
PyErr_SetString(PyExc_ValueError, "unrecognized kind");
return NULL;
}
PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++);
PyOS_snprintf(buffer, sizeof(buffer), "/mp%d-%d", getpid(), counter++);
SEM_CLEAR_ERROR();
handle = SEM_CREATE(buffer, value, maxvalue);
/* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */
if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0)
goto failure;
SEM_CLEAR_ERROR();
handle = SEM_CREATE(buffer, value, maxvalue);
/* On Windows we should fail if GetLastError()==ERROR_ALREADY_EXISTS */
if (handle == SEM_FAILED || SEM_GET_LAST_ERROR() != 0)
goto failure;
if (SEM_UNLINK(buffer) < 0)
goto failure;
if (SEM_UNLINK(buffer) < 0)
goto failure;
result = newsemlockobject(type, handle, kind, maxvalue);
if (!result)
goto failure;
result = newsemlockobject(type, handle, kind, maxvalue);
if (!result)
goto failure;
return result;
return result;
failure:
if (handle != SEM_FAILED)
SEM_CLOSE(handle);
mp_SetError(NULL, MP_STANDARD_ERROR);
return NULL;
if (handle != SEM_FAILED)
SEM_CLOSE(handle);
mp_SetError(NULL, MP_STANDARD_ERROR);
return NULL;
}
static PyObject *
semlock_rebuild(PyTypeObject *type, PyObject *args)
{
SEM_HANDLE handle;
int kind, maxvalue;
SEM_HANDLE handle;
int kind, maxvalue;
if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii",
&handle, &kind, &maxvalue))
return NULL;
if (!PyArg_ParseTuple(args, F_SEM_HANDLE "ii",
&handle, &kind, &maxvalue))
return NULL;
return newsemlockobject(type, handle, kind, maxvalue);
return newsemlockobject(type, handle, kind, maxvalue);
}
static void
semlock_dealloc(SemLockObject* self)
{
if (self->handle != SEM_FAILED)
SEM_CLOSE(self->handle);
PyObject_Del(self);
if (self->handle != SEM_FAILED)
SEM_CLOSE(self->handle);
PyObject_Del(self);
}
static PyObject *
semlock_count(SemLockObject *self)
{
return PyInt_FromLong((long)self->count);
return PyInt_FromLong((long)self->count);
}
static PyObject *
semlock_ismine(SemLockObject *self)
{
/* only makes sense for a lock */
return PyBool_FromLong(ISMINE(self));
/* only makes sense for a lock */
return PyBool_FromLong(ISMINE(self));
}
static PyObject *
semlock_getvalue(SemLockObject *self)
{
#ifdef HAVE_BROKEN_SEM_GETVALUE
PyErr_SetNone(PyExc_NotImplementedError);
return NULL;
PyErr_SetNone(PyExc_NotImplementedError);
return NULL;
#else
int sval;
if (SEM_GETVALUE(self->handle, &sval) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
/* some posix implementations use negative numbers to indicate
the number of waiting threads */
if (sval < 0)
sval = 0;
return PyInt_FromLong((long)sval);
int sval;
if (SEM_GETVALUE(self->handle, &sval) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
/* some posix implementations use negative numbers to indicate
the number of waiting threads */
if (sval < 0)
sval = 0;
return PyInt_FromLong((long)sval);
#endif
}
@ -513,28 +513,28 @@ static PyObject *
semlock_iszero(SemLockObject *self)
{
#ifdef HAVE_BROKEN_SEM_GETVALUE
if (sem_trywait(self->handle) < 0) {
if (errno == EAGAIN)
Py_RETURN_TRUE;
return mp_SetError(NULL, MP_STANDARD_ERROR);
} else {
if (sem_post(self->handle) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
Py_RETURN_FALSE;
}
if (sem_trywait(self->handle) < 0) {
if (errno == EAGAIN)
Py_RETURN_TRUE;
return mp_SetError(NULL, MP_STANDARD_ERROR);
} else {
if (sem_post(self->handle) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
Py_RETURN_FALSE;
}
#else
int sval;
if (SEM_GETVALUE(self->handle, &sval) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
return PyBool_FromLong((long)sval == 0);
int sval;
if (SEM_GETVALUE(self->handle, &sval) < 0)
return mp_SetError(NULL, MP_STANDARD_ERROR);
return PyBool_FromLong((long)sval == 0);
#endif
}
static PyObject *
semlock_afterfork(SemLockObject *self)
{
self->count = 0;
Py_RETURN_NONE;
self->count = 0;
Py_RETURN_NONE;
}
/*
@ -542,27 +542,27 @@ semlock_afterfork(SemLockObject *self)
*/
static PyMethodDef semlock_methods[] = {
{"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS,
"acquire the semaphore/lock"},
{"release", (PyCFunction)semlock_release, METH_NOARGS,
"release the semaphore/lock"},
{"acquire", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS,
"acquire the semaphore/lock"},
{"release", (PyCFunction)semlock_release, METH_NOARGS,
"release the semaphore/lock"},
{"__enter__", (PyCFunction)semlock_acquire, METH_VARARGS | METH_KEYWORDS,
"enter the semaphore/lock"},
{"__exit__", (PyCFunction)semlock_release, METH_VARARGS,
"exit the semaphore/lock"},
{"_count", (PyCFunction)semlock_count, METH_NOARGS,
"num of `acquire()`s minus num of `release()`s for this process"},
{"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS,
"whether the lock is owned by this thread"},
{"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS,
"get the value of the semaphore"},
{"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS,
"returns whether semaphore has value zero"},
{"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS,
""},
{"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS,
"rezero the net acquisition count after fork()"},
{NULL}
"enter the semaphore/lock"},
{"__exit__", (PyCFunction)semlock_release, METH_VARARGS,
"exit the semaphore/lock"},
{"_count", (PyCFunction)semlock_count, METH_NOARGS,
"num of `acquire()`s minus num of `release()`s for this process"},
{"_is_mine", (PyCFunction)semlock_ismine, METH_NOARGS,
"whether the lock is owned by this thread"},
{"_get_value", (PyCFunction)semlock_getvalue, METH_NOARGS,
"get the value of the semaphore"},
{"_is_zero", (PyCFunction)semlock_iszero, METH_NOARGS,
"returns whether semaphore has value zero"},
{"_rebuild", (PyCFunction)semlock_rebuild, METH_VARARGS | METH_CLASS,
""},
{"_after_fork", (PyCFunction)semlock_afterfork, METH_NOARGS,
"rezero the net acquisition count after fork()"},
{NULL}
};
/*
@ -570,13 +570,13 @@ static PyMethodDef semlock_methods[] = {
*/
static PyMemberDef semlock_members[] = {
{"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY,
""},
{"kind", T_INT, offsetof(SemLockObject, kind), READONLY,
""},
{"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY,
""},
{NULL}
{"handle", T_SEM_HANDLE, offsetof(SemLockObject, handle), READONLY,
""},
{"kind", T_INT, offsetof(SemLockObject, kind), READONLY,
""},
{"maxvalue", T_INT, offsetof(SemLockObject, maxvalue), READONLY,
""},
{NULL}
};
/*
@ -584,42 +584,42 @@ static PyMemberDef semlock_members[] = {
*/
PyTypeObject SemLockType = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "_multiprocessing.SemLock",
/* tp_basicsize */ sizeof(SemLockObject),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)semlock_dealloc,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ 0,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
/* tp_doc */ "Semaphore/Mutex type",
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklistoffset */ 0,
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ semlock_methods,
/* tp_members */ semlock_members,
/* tp_getset */ 0,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ semlock_new,
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "_multiprocessing.SemLock",
/* tp_basicsize */ sizeof(SemLockObject),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)semlock_dealloc,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 0,
/* tp_repr */ 0,
/* tp_as_number */ 0,
/* tp_as_sequence */ 0,
/* tp_as_mapping */ 0,
/* tp_hash */ 0,
/* tp_call */ 0,
/* tp_str */ 0,
/* tp_getattro */ 0,
/* tp_setattro */ 0,
/* tp_as_buffer */ 0,
/* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
/* tp_doc */ "Semaphore/Mutex type",
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklistoffset */ 0,
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ semlock_methods,
/* tp_members */ semlock_members,
/* tp_getset */ 0,
/* tp_base */ 0,
/* tp_dict */ 0,
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* tp_init */ 0,
/* tp_alloc */ 0,
/* tp_new */ semlock_new,
};

View file

@ -25,45 +25,45 @@
static Py_ssize_t
_conn_sendall(HANDLE h, char *string, size_t length)
{
char *p = string;
Py_ssize_t res;
char *p = string;
Py_ssize_t res;
while (length > 0) {
res = WRITE(h, p, length);
if (res < 0)
return MP_SOCKET_ERROR;
length -= res;
p += res;
}
while (length > 0) {
res = WRITE(h, p, length);
if (res < 0)
return MP_SOCKET_ERROR;
length -= res;
p += res;
}
return MP_SUCCESS;
return MP_SUCCESS;
}
/*
* Receive string of exact length from file descriptor
* Receive string of exact length from file descriptor
*/
static Py_ssize_t
_conn_recvall(HANDLE h, char *buffer, size_t length)
{
size_t remaining = length;
Py_ssize_t temp;
char *p = buffer;
size_t remaining = length;
Py_ssize_t temp;
char *p = buffer;
while (remaining > 0) {
temp = READ(h, p, remaining);
if (temp <= 0) {
if (temp == 0)
return remaining == length ?
MP_END_OF_FILE : MP_EARLY_END_OF_FILE;
else
return temp;
}
remaining -= temp;
p += temp;
}
while (remaining > 0) {
temp = READ(h, p, remaining);
if (temp <= 0) {
if (temp == 0)
return remaining == length ?
MP_END_OF_FILE : MP_EARLY_END_OF_FILE;
else
return temp;
}
remaining -= temp;
p += temp;
}
return MP_SUCCESS;
return MP_SUCCESS;
}
/*
@ -73,38 +73,38 @@ _conn_recvall(HANDLE h, char *buffer, size_t length)
static Py_ssize_t
conn_send_string(ConnectionObject *conn, char *string, size_t length)
{
Py_ssize_t res;
/* The "header" of the message is a 32 bit unsigned number (in
network order) which specifies the length of the "body". If
the message is shorter than about 16kb then it is quicker to
combine the "header" and the "body" of the message and send
them at once. */
if (length < (16*1024)) {
char *message;
Py_ssize_t res;
/* The "header" of the message is a 32 bit unsigned number (in
network order) which specifies the length of the "body". If
the message is shorter than about 16kb then it is quicker to
combine the "header" and the "body" of the message and send
them at once. */
if (length < (16*1024)) {
char *message;
message = PyMem_Malloc(length+4);
if (message == NULL)
return MP_MEMORY_ERROR;
message = PyMem_Malloc(length+4);
if (message == NULL)
return MP_MEMORY_ERROR;
*(UINT32*)message = htonl((UINT32)length);
memcpy(message+4, string, length);
Py_BEGIN_ALLOW_THREADS
res = _conn_sendall(conn->handle, message, length+4);
Py_END_ALLOW_THREADS
PyMem_Free(message);
} else {
UINT32 lenbuff;
*(UINT32*)message = htonl((UINT32)length);
memcpy(message+4, string, length);
Py_BEGIN_ALLOW_THREADS
res = _conn_sendall(conn->handle, message, length+4);
Py_END_ALLOW_THREADS
PyMem_Free(message);
} else {
UINT32 lenbuff;
if (length > MAX_MESSAGE_LENGTH)
return MP_BAD_MESSAGE_LENGTH;
if (length > MAX_MESSAGE_LENGTH)
return MP_BAD_MESSAGE_LENGTH;
lenbuff = htonl((UINT32)length);
Py_BEGIN_ALLOW_THREADS
res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) ||
_conn_sendall(conn->handle, string, length);
Py_END_ALLOW_THREADS
}
return res;
lenbuff = htonl((UINT32)length);
Py_BEGIN_ALLOW_THREADS
res = _conn_sendall(conn->handle, (char*)&lenbuff, 4) ||
_conn_sendall(conn->handle, string, length);
Py_END_ALLOW_THREADS
}
return res;
}
/*
@ -114,38 +114,38 @@ conn_send_string(ConnectionObject *conn, char *string, size_t length)
*/
static Py_ssize_t
conn_recv_string(ConnectionObject *conn, char *buffer,
size_t buflength, char **newbuffer, size_t maxlength)
conn_recv_string(ConnectionObject *conn, char *buffer,
size_t buflength, char **newbuffer, size_t maxlength)
{
int res;
UINT32 ulength;
int res;
UINT32 ulength;
*newbuffer = NULL;
*newbuffer = NULL;
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, (char*)&ulength, 4);
Py_END_ALLOW_THREADS
if (res < 0)
return res;
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, (char*)&ulength, 4);
Py_END_ALLOW_THREADS
if (res < 0)
return res;
ulength = ntohl(ulength);
if (ulength > maxlength)
return MP_BAD_MESSAGE_LENGTH;
ulength = ntohl(ulength);
if (ulength > maxlength)
return MP_BAD_MESSAGE_LENGTH;
if (ulength <= buflength) {
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, buffer, (size_t)ulength);
Py_END_ALLOW_THREADS
return res < 0 ? res : ulength;
} else {
*newbuffer = PyMem_Malloc((size_t)ulength);
if (*newbuffer == NULL)
return MP_MEMORY_ERROR;
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength);
Py_END_ALLOW_THREADS
return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength;
}
if (ulength <= buflength) {
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, buffer, (size_t)ulength);
Py_END_ALLOW_THREADS
return res < 0 ? res : ulength;
} else {
*newbuffer = PyMem_Malloc((size_t)ulength);
if (*newbuffer == NULL)
return MP_MEMORY_ERROR;
Py_BEGIN_ALLOW_THREADS
res = _conn_recvall(conn->handle, *newbuffer, (size_t)ulength);
Py_END_ALLOW_THREADS
return res < 0 ? (Py_ssize_t)res : (Py_ssize_t)ulength;
}
}
/*
@ -155,41 +155,41 @@ conn_recv_string(ConnectionObject *conn, char *buffer,
static int
conn_poll(ConnectionObject *conn, double timeout, PyThreadState *_save)
{
int res;
fd_set rfds;
int res;
fd_set rfds;
/*
* Verify the handle, issue 3321. Not required for windows.
*/
#ifndef MS_WINDOWS
if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) {
Py_BLOCK_THREADS
PyErr_SetString(PyExc_IOError, "handle out of range in select()");
Py_UNBLOCK_THREADS
return MP_EXCEPTION_HAS_BEEN_SET;
}
#endif
/*
* Verify the handle, issue 3321. Not required for windows.
*/
#ifndef MS_WINDOWS
if (((int)conn->handle) < 0 || ((int)conn->handle) >= FD_SETSIZE) {
Py_BLOCK_THREADS
PyErr_SetString(PyExc_IOError, "handle out of range in select()");
Py_UNBLOCK_THREADS
return MP_EXCEPTION_HAS_BEEN_SET;
}
#endif
FD_ZERO(&rfds);
FD_SET((SOCKET)conn->handle, &rfds);
FD_ZERO(&rfds);
FD_SET((SOCKET)conn->handle, &rfds);
if (timeout < 0.0) {
res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL);
} else {
struct timeval tv;
tv.tv_sec = (long)timeout;
tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5);
res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv);
}
if (timeout < 0.0) {
res = select((int)conn->handle+1, &rfds, NULL, NULL, NULL);
} else {
struct timeval tv;
tv.tv_sec = (long)timeout;
tv.tv_usec = (long)((timeout - tv.tv_sec) * 1e6 + 0.5);
res = select((int)conn->handle+1, &rfds, NULL, NULL, &tv);
}
if (res < 0) {
return MP_SOCKET_ERROR;
} else if (FD_ISSET(conn->handle, &rfds)) {
return TRUE;
} else {
assert(res == 0);
return FALSE;
}
if (res < 0) {
return MP_SOCKET_ERROR;
} else if (FD_ISSET(conn->handle, &rfds)) {
return TRUE;
} else {
assert(res == 0);
return FALSE;
}
}
/*

View file

@ -19,248 +19,248 @@
static PyObject *
win32_CloseHandle(PyObject *self, PyObject *args)
{
HANDLE hObject;
BOOL success;
HANDLE hObject;
BOOL success;
if (!PyArg_ParseTuple(args, F_HANDLE, &hObject))
return NULL;
if (!PyArg_ParseTuple(args, F_HANDLE, &hObject))
return NULL;
Py_BEGIN_ALLOW_THREADS
success = CloseHandle(hObject);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
success = CloseHandle(hObject);
Py_END_ALLOW_THREADS
if (!success)
return PyErr_SetFromWindowsErr(0);
if (!success)
return PyErr_SetFromWindowsErr(0);
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyObject *
win32_ConnectNamedPipe(PyObject *self, PyObject *args)
{
HANDLE hNamedPipe;
LPOVERLAPPED lpOverlapped;
BOOL success;
HANDLE hNamedPipe;
LPOVERLAPPED lpOverlapped;
BOOL success;
if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER,
&hNamedPipe, &lpOverlapped))
return NULL;
if (!PyArg_ParseTuple(args, F_HANDLE F_POINTER,
&hNamedPipe, &lpOverlapped))
return NULL;
Py_BEGIN_ALLOW_THREADS
success = ConnectNamedPipe(hNamedPipe, lpOverlapped);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
success = ConnectNamedPipe(hNamedPipe, lpOverlapped);
Py_END_ALLOW_THREADS
if (!success)
return PyErr_SetFromWindowsErr(0);
if (!success)
return PyErr_SetFromWindowsErr(0);
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyObject *
win32_CreateFile(PyObject *self, PyObject *args)
{
LPCTSTR lpFileName;
DWORD dwDesiredAccess;
DWORD dwShareMode;
LPSECURITY_ATTRIBUTES lpSecurityAttributes;
DWORD dwCreationDisposition;
DWORD dwFlagsAndAttributes;
HANDLE hTemplateFile;
HANDLE handle;
LPCTSTR lpFileName;
DWORD dwDesiredAccess;
DWORD dwShareMode;
LPSECURITY_ATTRIBUTES lpSecurityAttributes;
DWORD dwCreationDisposition;
DWORD dwFlagsAndAttributes;
HANDLE hTemplateFile;
HANDLE handle;
if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER
F_DWORD F_DWORD F_HANDLE,
&lpFileName, &dwDesiredAccess, &dwShareMode,
&lpSecurityAttributes, &dwCreationDisposition,
&dwFlagsAndAttributes, &hTemplateFile))
return NULL;
if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_POINTER
F_DWORD F_DWORD F_HANDLE,
&lpFileName, &dwDesiredAccess, &dwShareMode,
&lpSecurityAttributes, &dwCreationDisposition,
&dwFlagsAndAttributes, &hTemplateFile))
return NULL;
Py_BEGIN_ALLOW_THREADS
handle = CreateFile(lpFileName, dwDesiredAccess,
dwShareMode, lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes, hTemplateFile);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
handle = CreateFile(lpFileName, dwDesiredAccess,
dwShareMode, lpSecurityAttributes,
dwCreationDisposition,
dwFlagsAndAttributes, hTemplateFile);
Py_END_ALLOW_THREADS
if (handle == INVALID_HANDLE_VALUE)
return PyErr_SetFromWindowsErr(0);
if (handle == INVALID_HANDLE_VALUE)
return PyErr_SetFromWindowsErr(0);
return Py_BuildValue(F_HANDLE, handle);
return Py_BuildValue(F_HANDLE, handle);
}
static PyObject *
win32_CreateNamedPipe(PyObject *self, PyObject *args)
{
LPCTSTR lpName;
DWORD dwOpenMode;
DWORD dwPipeMode;
DWORD nMaxInstances;
DWORD nOutBufferSize;
DWORD nInBufferSize;
DWORD nDefaultTimeOut;
LPSECURITY_ATTRIBUTES lpSecurityAttributes;
HANDLE handle;
LPCTSTR lpName;
DWORD dwOpenMode;
DWORD dwPipeMode;
DWORD nMaxInstances;
DWORD nOutBufferSize;
DWORD nInBufferSize;
DWORD nDefaultTimeOut;
LPSECURITY_ATTRIBUTES lpSecurityAttributes;
HANDLE handle;
if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD
F_DWORD F_DWORD F_DWORD F_POINTER,
&lpName, &dwOpenMode, &dwPipeMode,
&nMaxInstances, &nOutBufferSize,
&nInBufferSize, &nDefaultTimeOut,
&lpSecurityAttributes))
return NULL;
if (!PyArg_ParseTuple(args, "s" F_DWORD F_DWORD F_DWORD
F_DWORD F_DWORD F_DWORD F_POINTER,
&lpName, &dwOpenMode, &dwPipeMode,
&nMaxInstances, &nOutBufferSize,
&nInBufferSize, &nDefaultTimeOut,
&lpSecurityAttributes))
return NULL;
Py_BEGIN_ALLOW_THREADS
handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode,
nMaxInstances, nOutBufferSize,
nInBufferSize, nDefaultTimeOut,
lpSecurityAttributes);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
handle = CreateNamedPipe(lpName, dwOpenMode, dwPipeMode,
nMaxInstances, nOutBufferSize,
nInBufferSize, nDefaultTimeOut,
lpSecurityAttributes);
Py_END_ALLOW_THREADS
if (handle == INVALID_HANDLE_VALUE)
return PyErr_SetFromWindowsErr(0);
if (handle == INVALID_HANDLE_VALUE)
return PyErr_SetFromWindowsErr(0);
return Py_BuildValue(F_HANDLE, handle);
return Py_BuildValue(F_HANDLE, handle);
}
static PyObject *
win32_ExitProcess(PyObject *self, PyObject *args)
{
UINT uExitCode;
UINT uExitCode;
if (!PyArg_ParseTuple(args, "I", &uExitCode))
return NULL;
if (!PyArg_ParseTuple(args, "I", &uExitCode))
return NULL;
#if defined(Py_DEBUG)
SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
#endif
#if defined(Py_DEBUG)
SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOALIGNMENTFAULTEXCEPT|SEM_NOGPFAULTERRORBOX|SEM_NOOPENFILEERRORBOX);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
#endif
ExitProcess(uExitCode);
ExitProcess(uExitCode);
return NULL;
return NULL;
}
static PyObject *
win32_GetLastError(PyObject *self, PyObject *args)
{
return Py_BuildValue(F_DWORD, GetLastError());
return Py_BuildValue(F_DWORD, GetLastError());
}
static PyObject *
win32_OpenProcess(PyObject *self, PyObject *args)
{
DWORD dwDesiredAccess;
BOOL bInheritHandle;
DWORD dwProcessId;
HANDLE handle;
DWORD dwDesiredAccess;
BOOL bInheritHandle;
DWORD dwProcessId;
HANDLE handle;
if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD,
&dwDesiredAccess, &bInheritHandle, &dwProcessId))
return NULL;
if (!PyArg_ParseTuple(args, F_DWORD "i" F_DWORD,
&dwDesiredAccess, &bInheritHandle, &dwProcessId))
return NULL;
handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
if (handle == NULL)
return PyErr_SetFromWindowsErr(0);
handle = OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId);
if (handle == NULL)
return PyErr_SetFromWindowsErr(0);
return Py_BuildValue(F_HANDLE, handle);
return Py_BuildValue(F_HANDLE, handle);
}
static PyObject *
win32_SetNamedPipeHandleState(PyObject *self, PyObject *args)
{
HANDLE hNamedPipe;
PyObject *oArgs[3];
DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
int i;
HANDLE hNamedPipe;
PyObject *oArgs[3];
DWORD dwArgs[3], *pArgs[3] = {NULL, NULL, NULL};
int i;
if (!PyArg_ParseTuple(args, F_HANDLE "OOO",
&hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2]))
return NULL;
if (!PyArg_ParseTuple(args, F_HANDLE "OOO",
&hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2]))
return NULL;
PyErr_Clear();
PyErr_Clear();
for (i = 0 ; i < 3 ; i++) {
if (oArgs[i] != Py_None) {
dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]);
if (PyErr_Occurred())
return NULL;
pArgs[i] = &dwArgs[i];
}
}
for (i = 0 ; i < 3 ; i++) {
if (oArgs[i] != Py_None) {
dwArgs[i] = PyLong_AsUnsignedLongMask(oArgs[i]);
if (PyErr_Occurred())
return NULL;
pArgs[i] = &dwArgs[i];
}
}
if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2]))
return PyErr_SetFromWindowsErr(0);
if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2]))
return PyErr_SetFromWindowsErr(0);
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyObject *
win32_WaitNamedPipe(PyObject *self, PyObject *args)
{
LPCTSTR lpNamedPipeName;
DWORD nTimeOut;
BOOL success;
LPCTSTR lpNamedPipeName;
DWORD nTimeOut;
BOOL success;
if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut))
return NULL;
if (!PyArg_ParseTuple(args, "s" F_DWORD, &lpNamedPipeName, &nTimeOut))
return NULL;
Py_BEGIN_ALLOW_THREADS
success = WaitNamedPipe(lpNamedPipeName, nTimeOut);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
success = WaitNamedPipe(lpNamedPipeName, nTimeOut);
Py_END_ALLOW_THREADS
if (!success)
return PyErr_SetFromWindowsErr(0);
if (!success)
return PyErr_SetFromWindowsErr(0);
Py_RETURN_NONE;
Py_RETURN_NONE;
}
static PyMethodDef win32_methods[] = {
WIN32_FUNCTION(CloseHandle),
WIN32_FUNCTION(GetLastError),
WIN32_FUNCTION(OpenProcess),
WIN32_FUNCTION(ExitProcess),
WIN32_FUNCTION(ConnectNamedPipe),
WIN32_FUNCTION(CreateFile),
WIN32_FUNCTION(CreateNamedPipe),
WIN32_FUNCTION(SetNamedPipeHandleState),
WIN32_FUNCTION(WaitNamedPipe),
{NULL}
WIN32_FUNCTION(CloseHandle),
WIN32_FUNCTION(GetLastError),
WIN32_FUNCTION(OpenProcess),
WIN32_FUNCTION(ExitProcess),
WIN32_FUNCTION(ConnectNamedPipe),
WIN32_FUNCTION(CreateFile),
WIN32_FUNCTION(CreateNamedPipe),
WIN32_FUNCTION(SetNamedPipeHandleState),
WIN32_FUNCTION(WaitNamedPipe),
{NULL}
};
PyTypeObject Win32Type = {
PyVarObject_HEAD_INIT(NULL, 0)
PyVarObject_HEAD_INIT(NULL, 0)
};
PyObject *
create_win32_namespace(void)
{
Win32Type.tp_name = "_multiprocessing.win32";
Win32Type.tp_methods = win32_methods;
if (PyType_Ready(&Win32Type) < 0)
return NULL;
Py_INCREF(&Win32Type);
Win32Type.tp_name = "_multiprocessing.win32";
Win32Type.tp_methods = win32_methods;
if (PyType_Ready(&Win32Type) < 0)
return NULL;
Py_INCREF(&Win32Type);
WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS);
WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY);
WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED);
WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT);
WIN32_CONSTANT(F_DWORD, GENERIC_READ);
WIN32_CONSTANT(F_DWORD, GENERIC_WRITE);
WIN32_CONSTANT(F_DWORD, INFINITE);
WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER);
WIN32_CONSTANT(F_DWORD, OPEN_EXISTING);
WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX);
WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND);
WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE);
WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE);
WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES);
WIN32_CONSTANT(F_DWORD, PIPE_WAIT);
WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS);
WIN32_CONSTANT(F_DWORD, ERROR_ALREADY_EXISTS);
WIN32_CONSTANT(F_DWORD, ERROR_PIPE_BUSY);
WIN32_CONSTANT(F_DWORD, ERROR_PIPE_CONNECTED);
WIN32_CONSTANT(F_DWORD, ERROR_SEM_TIMEOUT);
WIN32_CONSTANT(F_DWORD, GENERIC_READ);
WIN32_CONSTANT(F_DWORD, GENERIC_WRITE);
WIN32_CONSTANT(F_DWORD, INFINITE);
WIN32_CONSTANT(F_DWORD, NMPWAIT_WAIT_FOREVER);
WIN32_CONSTANT(F_DWORD, OPEN_EXISTING);
WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_DUPLEX);
WIN32_CONSTANT(F_DWORD, PIPE_ACCESS_INBOUND);
WIN32_CONSTANT(F_DWORD, PIPE_READMODE_MESSAGE);
WIN32_CONSTANT(F_DWORD, PIPE_TYPE_MESSAGE);
WIN32_CONSTANT(F_DWORD, PIPE_UNLIMITED_INSTANCES);
WIN32_CONSTANT(F_DWORD, PIPE_WAIT);
WIN32_CONSTANT(F_DWORD, PROCESS_ALL_ACCESS);
WIN32_CONSTANT("i", NULL);
WIN32_CONSTANT("i", NULL);
return (PyObject*)&Win32Type;
return (PyObject*)&Win32Type;
}

View file

@ -2,23 +2,23 @@
/* ------------------------------------------------------------------
The code in this module was based on a download from:
http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html
http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html
It was modified in 2002 by Raymond Hettinger as follows:
* the principal computational lines untouched except for tabbing.
* the principal computational lines untouched except for tabbing.
* renamed genrand_res53() to random_random() and wrapped
in python calling/return code.
* renamed genrand_res53() to random_random() and wrapped
in python calling/return code.
* genrand_int32() and the helper functions, init_genrand()
and init_by_array(), were declared static, wrapped in
Python calling/return code. also, their global data
references were replaced with structure references.
* genrand_int32() and the helper functions, init_genrand()
and init_by_array(), were declared static, wrapped in
Python calling/return code. also, their global data
references were replaced with structure references.
* unused functions from the original were deleted.
new, original C python code was added to implement the
Random() interface.
* unused functions from the original were deleted.
new, original C python code was added to implement the
Random() interface.
The following are the verbatim comments from the original code:
@ -36,15 +36,15 @@
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
@ -67,24 +67,24 @@
/* ---------------------------------------------------------------*/
#include "Python.h"
#include <time.h> /* for seeding to current time */
#include <time.h> /* for seeding to current time */
/* Period parameters -- These are all magic. Don't change. */
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
typedef struct {
PyObject_HEAD
unsigned long state[N];
int index;
PyObject_HEAD
unsigned long state[N];
int index;
} RandomObject;
static PyTypeObject Random_Type;
#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)
#define RandomObject_Check(v) (Py_TYPE(v) == &Random_Type)
/* Random methods */
@ -94,28 +94,28 @@ static PyTypeObject Random_Type;
static unsigned long
genrand_int32(RandomObject *self)
{
unsigned long y;
static unsigned long mag01[2]={0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
unsigned long *mt;
unsigned long y;
static unsigned long mag01[2]={0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
unsigned long *mt;
mt = self->state;
if (self->index >= N) { /* generate N words at one time */
int kk;
mt = self->state;
if (self->index >= N) { /* generate N words at one time */
int kk;
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
self->index = 0;
}
self->index = 0;
}
y = mt[self->index++];
y ^= (y >> 11);
@ -137,31 +137,31 @@ genrand_int32(RandomObject *self)
static PyObject *
random_random(RandomObject *self)
{
unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
unsigned long a=genrand_int32(self)>>5, b=genrand_int32(self)>>6;
return PyFloat_FromDouble((a*67108864.0+b)*(1.0/9007199254740992.0));
}
/* initializes mt[N] with a seed */
static void
init_genrand(RandomObject *self, unsigned long s)
{
int mti;
unsigned long *mt;
int mti;
unsigned long *mt;
mt = self->state;
mt[0]= s & 0xffffffffUL;
for (mti=1; mti<N; mti++) {
mt[mti] =
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
mt[mti] &= 0xffffffffUL;
/* for >32 bit machines */
}
self->index = mti;
return;
mt = self->state;
mt[0]= s & 0xffffffffUL;
for (mti=1; mti<N; mti++) {
mt[mti] =
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
mt[mti] &= 0xffffffffUL;
/* for >32 bit machines */
}
self->index = mti;
return;
}
/* initialize by an array with array-length */
@ -170,28 +170,28 @@ init_genrand(RandomObject *self, unsigned long s)
static PyObject *
init_by_array(RandomObject *self, unsigned long init_key[], unsigned long key_length)
{
unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */
unsigned long *mt;
unsigned int i, j, k; /* was signed in the original code. RDH 12/16/2002 */
unsigned long *mt;
mt = self->state;
init_genrand(self, 19650218UL);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
+ init_key[j] + j; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- i; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt = self->state;
init_genrand(self, 19650218UL);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
+ init_key[j] + j; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- i; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
Py_INCREF(Py_None);
@ -206,291 +206,291 @@ init_by_array(RandomObject *self, unsigned long init_key[], unsigned long key_le
static PyObject *
random_seed(RandomObject *self, PyObject *args)
{
PyObject *result = NULL; /* guilty until proved innocent */
PyObject *masklower = NULL;
PyObject *thirtytwo = NULL;
PyObject *n = NULL;
unsigned long *key = NULL;
unsigned long keymax; /* # of allocated slots in key */
unsigned long keyused; /* # of used slots in key */
int err;
PyObject *result = NULL; /* guilty until proved innocent */
PyObject *masklower = NULL;
PyObject *thirtytwo = NULL;
PyObject *n = NULL;
unsigned long *key = NULL;
unsigned long keymax; /* # of allocated slots in key */
unsigned long keyused; /* # of used slots in key */
int err;
PyObject *arg = NULL;
PyObject *arg = NULL;
if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
return NULL;
if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
return NULL;
if (arg == NULL || arg == Py_None) {
time_t now;
if (arg == NULL || arg == Py_None) {
time_t now;
time(&now);
init_genrand(self, (unsigned long)now);
Py_INCREF(Py_None);
return Py_None;
}
/* If the arg is an int or long, use its absolute value; else use
* the absolute value of its hash code.
*/
if (PyLong_Check(arg))
n = PyNumber_Absolute(arg);
else {
long hash = PyObject_Hash(arg);
if (hash == -1)
goto Done;
n = PyLong_FromUnsignedLong((unsigned long)hash);
}
if (n == NULL)
goto Done;
time(&now);
init_genrand(self, (unsigned long)now);
Py_INCREF(Py_None);
return Py_None;
}
/* If the arg is an int or long, use its absolute value; else use
* the absolute value of its hash code.
*/
if (PyLong_Check(arg))
n = PyNumber_Absolute(arg);
else {
long hash = PyObject_Hash(arg);
if (hash == -1)
goto Done;
n = PyLong_FromUnsignedLong((unsigned long)hash);
}
if (n == NULL)
goto Done;
/* Now split n into 32-bit chunks, from the right. Each piece is
* stored into key, which has a capacity of keymax chunks, of which
* keyused are filled. Alas, the repeated shifting makes this a
* quadratic-time algorithm; we'd really like to use
* _PyLong_AsByteArray here, but then we'd have to break into the
* long representation to figure out how big an array was needed
* in advance.
*/
keymax = 8; /* arbitrary; grows later if needed */
keyused = 0;
key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key));
if (key == NULL)
goto Done;
/* Now split n into 32-bit chunks, from the right. Each piece is
* stored into key, which has a capacity of keymax chunks, of which
* keyused are filled. Alas, the repeated shifting makes this a
* quadratic-time algorithm; we'd really like to use
* _PyLong_AsByteArray here, but then we'd have to break into the
* long representation to figure out how big an array was needed
* in advance.
*/
keymax = 8; /* arbitrary; grows later if needed */
keyused = 0;
key = (unsigned long *)PyMem_Malloc(keymax * sizeof(*key));
if (key == NULL)
goto Done;
masklower = PyLong_FromUnsignedLong(0xffffffffU);
if (masklower == NULL)
goto Done;
thirtytwo = PyLong_FromLong(32L);
if (thirtytwo == NULL)
goto Done;
while ((err=PyObject_IsTrue(n))) {
PyObject *newn;
PyObject *pychunk;
unsigned long chunk;
masklower = PyLong_FromUnsignedLong(0xffffffffU);
if (masklower == NULL)
goto Done;
thirtytwo = PyLong_FromLong(32L);
if (thirtytwo == NULL)
goto Done;
while ((err=PyObject_IsTrue(n))) {
PyObject *newn;
PyObject *pychunk;
unsigned long chunk;
if (err == -1)
goto Done;
pychunk = PyNumber_And(n, masklower);
if (pychunk == NULL)
goto Done;
chunk = PyLong_AsUnsignedLong(pychunk);
Py_DECREF(pychunk);
if (chunk == (unsigned long)-1 && PyErr_Occurred())
goto Done;
newn = PyNumber_Rshift(n, thirtytwo);
if (newn == NULL)
goto Done;
Py_DECREF(n);
n = newn;
if (keyused >= keymax) {
unsigned long bigger = keymax << 1;
if ((bigger >> 1) != keymax) {
PyErr_NoMemory();
goto Done;
}
key = (unsigned long *)PyMem_Realloc(key,
bigger * sizeof(*key));
if (key == NULL)
goto Done;
keymax = bigger;
}
assert(keyused < keymax);
key[keyused++] = chunk;
}
if (err == -1)
goto Done;
pychunk = PyNumber_And(n, masklower);
if (pychunk == NULL)
goto Done;
chunk = PyLong_AsUnsignedLong(pychunk);
Py_DECREF(pychunk);
if (chunk == (unsigned long)-1 && PyErr_Occurred())
goto Done;
newn = PyNumber_Rshift(n, thirtytwo);
if (newn == NULL)
goto Done;
Py_DECREF(n);
n = newn;
if (keyused >= keymax) {
unsigned long bigger = keymax << 1;
if ((bigger >> 1) != keymax) {
PyErr_NoMemory();
goto Done;
}
key = (unsigned long *)PyMem_Realloc(key,
bigger * sizeof(*key));
if (key == NULL)
goto Done;
keymax = bigger;
}
assert(keyused < keymax);
key[keyused++] = chunk;
}
if (keyused == 0)
key[keyused++] = 0UL;
result = init_by_array(self, key, keyused);
if (keyused == 0)
key[keyused++] = 0UL;
result = init_by_array(self, key, keyused);
Done:
Py_XDECREF(masklower);
Py_XDECREF(thirtytwo);
Py_XDECREF(n);
PyMem_Free(key);
return result;
Py_XDECREF(masklower);
Py_XDECREF(thirtytwo);
Py_XDECREF(n);
PyMem_Free(key);
return result;
}
static PyObject *
random_getstate(RandomObject *self)
{
PyObject *state;
PyObject *element;
int i;
PyObject *state;
PyObject *element;
int i;
state = PyTuple_New(N+1);
if (state == NULL)
return NULL;
for (i=0; i<N ; i++) {
element = PyLong_FromUnsignedLong(self->state[i]);
if (element == NULL)
goto Fail;
PyTuple_SET_ITEM(state, i, element);
}
element = PyLong_FromLong((long)(self->index));
if (element == NULL)
goto Fail;
PyTuple_SET_ITEM(state, i, element);
return state;
state = PyTuple_New(N+1);
if (state == NULL)
return NULL;
for (i=0; i<N ; i++) {
element = PyLong_FromUnsignedLong(self->state[i]);
if (element == NULL)
goto Fail;
PyTuple_SET_ITEM(state, i, element);
}
element = PyLong_FromLong((long)(self->index));
if (element == NULL)
goto Fail;
PyTuple_SET_ITEM(state, i, element);
return state;
Fail:
Py_DECREF(state);
return NULL;
Py_DECREF(state);
return NULL;
}
static PyObject *
random_setstate(RandomObject *self, PyObject *state)
{
int i;
unsigned long element;
long index;
int i;
unsigned long element;
long index;
if (!PyTuple_Check(state)) {
PyErr_SetString(PyExc_TypeError,
"state vector must be a tuple");
return NULL;
}
if (PyTuple_Size(state) != N+1) {
PyErr_SetString(PyExc_ValueError,
"state vector is the wrong size");
return NULL;
}
if (!PyTuple_Check(state)) {
PyErr_SetString(PyExc_TypeError,
"state vector must be a tuple");
return NULL;
}
if (PyTuple_Size(state) != N+1) {
PyErr_SetString(PyExc_ValueError,
"state vector is the wrong size");
return NULL;
}
for (i=0; i<N ; i++) {
element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
if (element == (unsigned long)-1 && PyErr_Occurred())
return NULL;
self->state[i] = element & 0xffffffffUL; /* Make sure we get sane state */
}
for (i=0; i<N ; i++) {
element = PyLong_AsUnsignedLong(PyTuple_GET_ITEM(state, i));
if (element == (unsigned long)-1 && PyErr_Occurred())
return NULL;
self->state[i] = element & 0xffffffffUL; /* Make sure we get sane state */
}
index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
if (index == -1 && PyErr_Occurred())
return NULL;
self->index = (int)index;
index = PyLong_AsLong(PyTuple_GET_ITEM(state, i));
if (index == -1 && PyErr_Occurred())
return NULL;
self->index = (int)index;
Py_INCREF(Py_None);
return Py_None;
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
random_getrandbits(RandomObject *self, PyObject *args)
{
int k, i, bytes;
unsigned long r;
unsigned char *bytearray;
PyObject *result;
int k, i, bytes;
unsigned long r;
unsigned char *bytearray;
PyObject *result;
if (!PyArg_ParseTuple(args, "i:getrandbits", &k))
return NULL;
if (!PyArg_ParseTuple(args, "i:getrandbits", &k))
return NULL;
if (k <= 0) {
PyErr_SetString(PyExc_ValueError,
"number of bits must be greater than zero");
return NULL;
}
if (k <= 0) {
PyErr_SetString(PyExc_ValueError,
"number of bits must be greater than zero");
return NULL;
}
bytes = ((k - 1) / 32 + 1) * 4;
bytearray = (unsigned char *)PyMem_Malloc(bytes);
if (bytearray == NULL) {
PyErr_NoMemory();
return NULL;
}
bytes = ((k - 1) / 32 + 1) * 4;
bytearray = (unsigned char *)PyMem_Malloc(bytes);
if (bytearray == NULL) {
PyErr_NoMemory();
return NULL;
}
/* Fill-out whole words, byte-by-byte to avoid endianness issues */
for (i=0 ; i<bytes ; i+=4, k-=32) {
r = genrand_int32(self);
if (k < 32)
r >>= (32 - k);
bytearray[i+0] = (unsigned char)r;
bytearray[i+1] = (unsigned char)(r >> 8);
bytearray[i+2] = (unsigned char)(r >> 16);
bytearray[i+3] = (unsigned char)(r >> 24);
}
/* Fill-out whole words, byte-by-byte to avoid endianness issues */
for (i=0 ; i<bytes ; i+=4, k-=32) {
r = genrand_int32(self);
if (k < 32)
r >>= (32 - k);
bytearray[i+0] = (unsigned char)r;
bytearray[i+1] = (unsigned char)(r >> 8);
bytearray[i+2] = (unsigned char)(r >> 16);
bytearray[i+3] = (unsigned char)(r >> 24);
}
/* little endian order to match bytearray assignment order */
result = _PyLong_FromByteArray(bytearray, bytes, 1, 0);
PyMem_Free(bytearray);
return result;
/* little endian order to match bytearray assignment order */
result = _PyLong_FromByteArray(bytearray, bytes, 1, 0);
PyMem_Free(bytearray);
return result;
}
static PyObject *
random_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
RandomObject *self;
PyObject *tmp;
RandomObject *self;
PyObject *tmp;
if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds))
return NULL;
if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds))
return NULL;
self = (RandomObject *)type->tp_alloc(type, 0);
if (self == NULL)
return NULL;
tmp = random_seed(self, args);
if (tmp == NULL) {
Py_DECREF(self);
return NULL;
}
Py_DECREF(tmp);
return (PyObject *)self;
self = (RandomObject *)type->tp_alloc(type, 0);
if (self == NULL)
return NULL;
tmp = random_seed(self, args);
if (tmp == NULL) {
Py_DECREF(self);
return NULL;
}
Py_DECREF(tmp);
return (PyObject *)self;
}
static PyMethodDef random_methods[] = {
{"random", (PyCFunction)random_random, METH_NOARGS,
PyDoc_STR("random() -> x in the interval [0, 1).")},
{"seed", (PyCFunction)random_seed, METH_VARARGS,
PyDoc_STR("seed([n]) -> None. Defaults to current time.")},
{"getstate", (PyCFunction)random_getstate, METH_NOARGS,
PyDoc_STR("getstate() -> tuple containing the current state.")},
{"setstate", (PyCFunction)random_setstate, METH_O,
PyDoc_STR("setstate(state) -> None. Restores generator state.")},
{"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS,
PyDoc_STR("getrandbits(k) -> x. Generates a long int with "
"k random bits.")},
{NULL, NULL} /* sentinel */
{"random", (PyCFunction)random_random, METH_NOARGS,
PyDoc_STR("random() -> x in the interval [0, 1).")},
{"seed", (PyCFunction)random_seed, METH_VARARGS,
PyDoc_STR("seed([n]) -> None. Defaults to current time.")},
{"getstate", (PyCFunction)random_getstate, METH_NOARGS,
PyDoc_STR("getstate() -> tuple containing the current state.")},
{"setstate", (PyCFunction)random_setstate, METH_O,
PyDoc_STR("setstate(state) -> None. Restores generator state.")},
{"getrandbits", (PyCFunction)random_getrandbits, METH_VARARGS,
PyDoc_STR("getrandbits(k) -> x. Generates a long int with "
"k random bits.")},
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(random_doc,
"Random() -> create a random number generator with its own internal state.");
static PyTypeObject Random_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_random.Random", /*tp_name*/
sizeof(RandomObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
PyObject_GenericGetAttr, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
random_doc, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
random_methods, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
random_new, /*tp_new*/
PyObject_Free, /*tp_free*/
0, /*tp_is_gc*/
PyVarObject_HEAD_INIT(NULL, 0)
"_random.Random", /*tp_name*/
sizeof(RandomObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
0, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
PyObject_GenericGetAttr, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
random_doc, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
random_methods, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
random_new, /*tp_new*/
PyObject_Free, /*tp_free*/
0, /*tp_is_gc*/
};
PyDoc_STRVAR(module_doc,
@ -498,28 +498,28 @@ PyDoc_STRVAR(module_doc,
static struct PyModuleDef _randommodule = {
PyModuleDef_HEAD_INIT,
"_random",
module_doc,
-1,
NULL,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_random",
module_doc,
-1,
NULL,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__random(void)
{
PyObject *m;
PyObject *m;
if (PyType_Ready(&Random_Type) < 0)
return NULL;
m = PyModule_Create(&_randommodule);
if (m == NULL)
return NULL;
Py_INCREF(&Random_Type);
PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
return m;
if (PyType_Ready(&Random_Type) < 0)
return NULL;
m = PyModule_Create(&_randommodule);
if (m == NULL)
return NULL;
Py_INCREF(&Random_Type);
PyModule_AddObject(m, "Random", (PyObject *)&Random_Type);
return m;
}

View file

@ -5,167 +5,167 @@
#include <Python.h>
#include <SystemConfiguration/SystemConfiguration.h>
static int32_t
static int32_t
cfnum_to_int32(CFNumberRef num)
{
int32_t result;
int32_t result;
CFNumberGetValue(num, kCFNumberSInt32Type, &result);
return result;
CFNumberGetValue(num, kCFNumberSInt32Type, &result);
return result;
}
static PyObject*
cfstring_to_pystring(CFStringRef ref)
{
const char* s;
const char* s;
s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8);
if (s) {
return PyUnicode_DecodeUTF8(
s, strlen(s), NULL);
s = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8);
if (s) {
return PyUnicode_DecodeUTF8(
s, strlen(s), NULL);
} else {
CFIndex len = CFStringGetLength(ref);
Boolean ok;
PyObject* result;
char* buf;
buf = PyMem_Malloc(len*4);
if (buf == NULL) {
PyErr_NoMemory();
return NULL;
}
} else {
CFIndex len = CFStringGetLength(ref);
Boolean ok;
PyObject* result;
char* buf;
ok = CFStringGetCString(ref,
buf, len * 4,
kCFStringEncodingUTF8);
if (!ok) {
PyMem_Free(buf);
return NULL;
} else {
result = PyUnicode_DecodeUTF8(
buf, strlen(buf), NULL);
PyMem_Free(buf);
}
return result;
}
buf = PyMem_Malloc(len*4);
if (buf == NULL) {
PyErr_NoMemory();
return NULL;
}
ok = CFStringGetCString(ref,
buf, len * 4,
kCFStringEncodingUTF8);
if (!ok) {
PyMem_Free(buf);
return NULL;
} else {
result = PyUnicode_DecodeUTF8(
buf, strlen(buf), NULL);
PyMem_Free(buf);
}
return result;
}
}
static PyObject*
get_proxy_settings(PyObject* mod __attribute__((__unused__)))
{
CFDictionaryRef proxyDict = NULL;
CFNumberRef aNum = NULL;
CFArrayRef anArray = NULL;
PyObject* result = NULL;
PyObject* v;
int r;
CFDictionaryRef proxyDict = NULL;
CFNumberRef aNum = NULL;
CFArrayRef anArray = NULL;
PyObject* result = NULL;
PyObject* v;
int r;
proxyDict = SCDynamicStoreCopyProxies(NULL);
if (!proxyDict) {
Py_INCREF(Py_None);
return Py_None;
}
proxyDict = SCDynamicStoreCopyProxies(NULL);
if (!proxyDict) {
Py_INCREF(Py_None);
return Py_None;
}
result = PyDict_New();
if (result == NULL) goto error;
result = PyDict_New();
if (result == NULL) goto error;
if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) {
aNum = CFDictionaryGetValue(proxyDict,
kSCPropNetProxiesExcludeSimpleHostnames);
if (aNum == NULL) {
v = PyBool_FromLong(1);
} else {
v = PyBool_FromLong(cfnum_to_int32(aNum));
}
} else {
v = PyBool_FromLong(1);
}
if (&kSCPropNetProxiesExcludeSimpleHostnames != NULL) {
aNum = CFDictionaryGetValue(proxyDict,
kSCPropNetProxiesExcludeSimpleHostnames);
if (aNum == NULL) {
v = PyBool_FromLong(1);
} else {
v = PyBool_FromLong(cfnum_to_int32(aNum));
}
} else {
v = PyBool_FromLong(1);
}
if (v == NULL) goto error;
if (v == NULL) goto error;
r = PyDict_SetItemString(result, "exclude_simple", v);
Py_DECREF(v); v = NULL;
if (r == -1) goto error;
r = PyDict_SetItemString(result, "exclude_simple", v);
Py_DECREF(v); v = NULL;
if (r == -1) goto error;
anArray = CFDictionaryGetValue(proxyDict,
kSCPropNetProxiesExceptionsList);
if (anArray != NULL) {
CFIndex len = CFArrayGetCount(anArray);
CFIndex i;
v = PyTuple_New(len);
if (v == NULL) goto error;
anArray = CFDictionaryGetValue(proxyDict,
kSCPropNetProxiesExceptionsList);
if (anArray != NULL) {
CFIndex len = CFArrayGetCount(anArray);
CFIndex i;
v = PyTuple_New(len);
if (v == NULL) goto error;
r = PyDict_SetItemString(result, "exceptions", v);
Py_DECREF(v);
if (r == -1) goto error;
r = PyDict_SetItemString(result, "exceptions", v);
Py_DECREF(v);
if (r == -1) goto error;
for (i = 0; i < len; i++) {
CFStringRef aString = NULL;
for (i = 0; i < len; i++) {
CFStringRef aString = NULL;
aString = CFArrayGetValueAtIndex(anArray, i);
if (aString == NULL) {
PyTuple_SetItem(v, i, Py_None);
Py_INCREF(Py_None);
} else {
PyObject* t = cfstring_to_pystring(aString);
if (!t) {
PyTuple_SetItem(v, i, Py_None);
Py_INCREF(Py_None);
} else {
PyTuple_SetItem(v, i, t);
}
}
}
}
aString = CFArrayGetValueAtIndex(anArray, i);
if (aString == NULL) {
PyTuple_SetItem(v, i, Py_None);
Py_INCREF(Py_None);
} else {
PyObject* t = cfstring_to_pystring(aString);
if (!t) {
PyTuple_SetItem(v, i, Py_None);
Py_INCREF(Py_None);
} else {
PyTuple_SetItem(v, i, t);
}
}
}
}
CFRelease(proxyDict);
return result;
CFRelease(proxyDict);
return result;
error:
if (proxyDict) CFRelease(proxyDict);
Py_XDECREF(result);
return NULL;
if (proxyDict) CFRelease(proxyDict);
Py_XDECREF(result);
return NULL;
}
static int
set_proxy(PyObject* proxies, char* proto, CFDictionaryRef proxyDict,
CFStringRef enabledKey,
CFStringRef hostKey, CFStringRef portKey)
CFStringRef enabledKey,
CFStringRef hostKey, CFStringRef portKey)
{
CFNumberRef aNum;
CFNumberRef aNum;
aNum = CFDictionaryGetValue(proxyDict, enabledKey);
if (aNum && cfnum_to_int32(aNum)) {
CFStringRef hostString;
aNum = CFDictionaryGetValue(proxyDict, enabledKey);
if (aNum && cfnum_to_int32(aNum)) {
CFStringRef hostString;
hostString = CFDictionaryGetValue(proxyDict, hostKey);
aNum = CFDictionaryGetValue(proxyDict, portKey);
hostString = CFDictionaryGetValue(proxyDict, hostKey);
aNum = CFDictionaryGetValue(proxyDict, portKey);
if (hostString) {
int r;
PyObject* h = cfstring_to_pystring(hostString);
PyObject* v;
if (h) {
if (aNum) {
int32_t port = cfnum_to_int32(aNum);
v = PyUnicode_FromFormat("http://%U:%ld",
h, (long)port);
} else {
v = PyUnicode_FromFormat("http://%U", h);
}
Py_DECREF(h);
if (!v) return -1;
r = PyDict_SetItemString(proxies, proto,
v);
Py_DECREF(v);
return r;
}
}
if (hostString) {
int r;
PyObject* h = cfstring_to_pystring(hostString);
PyObject* v;
if (h) {
if (aNum) {
int32_t port = cfnum_to_int32(aNum);
v = PyUnicode_FromFormat("http://%U:%ld",
h, (long)port);
} else {
v = PyUnicode_FromFormat("http://%U", h);
}
Py_DECREF(h);
if (!v) return -1;
r = PyDict_SetItemString(proxies, proto,
v);
Py_DECREF(v);
return r;
}
}
}
return 0;
}
return 0;
}
@ -173,75 +173,75 @@ set_proxy(PyObject* proxies, char* proto, CFDictionaryRef proxyDict,
static PyObject*
get_proxies(PyObject* mod __attribute__((__unused__)))
{
PyObject* result = NULL;
int r;
CFDictionaryRef proxyDict = NULL;
PyObject* result = NULL;
int r;
CFDictionaryRef proxyDict = NULL;
proxyDict = SCDynamicStoreCopyProxies(NULL);
if (proxyDict == NULL) {
return PyDict_New();
}
proxyDict = SCDynamicStoreCopyProxies(NULL);
if (proxyDict == NULL) {
return PyDict_New();
}
result = PyDict_New();
if (result == NULL) goto error;
result = PyDict_New();
if (result == NULL) goto error;
r = set_proxy(result, "http", proxyDict,
kSCPropNetProxiesHTTPEnable,
kSCPropNetProxiesHTTPProxy,
kSCPropNetProxiesHTTPPort);
if (r == -1) goto error;
r = set_proxy(result, "https", proxyDict,
kSCPropNetProxiesHTTPSEnable,
kSCPropNetProxiesHTTPSProxy,
kSCPropNetProxiesHTTPSPort);
if (r == -1) goto error;
r = set_proxy(result, "ftp", proxyDict,
kSCPropNetProxiesFTPEnable,
kSCPropNetProxiesFTPProxy,
kSCPropNetProxiesFTPPort);
if (r == -1) goto error;
r = set_proxy(result, "gopher", proxyDict,
kSCPropNetProxiesGopherEnable,
kSCPropNetProxiesGopherProxy,
kSCPropNetProxiesGopherPort);
if (r == -1) goto error;
r = set_proxy(result, "http", proxyDict,
kSCPropNetProxiesHTTPEnable,
kSCPropNetProxiesHTTPProxy,
kSCPropNetProxiesHTTPPort);
if (r == -1) goto error;
r = set_proxy(result, "https", proxyDict,
kSCPropNetProxiesHTTPSEnable,
kSCPropNetProxiesHTTPSProxy,
kSCPropNetProxiesHTTPSPort);
if (r == -1) goto error;
r = set_proxy(result, "ftp", proxyDict,
kSCPropNetProxiesFTPEnable,
kSCPropNetProxiesFTPProxy,
kSCPropNetProxiesFTPPort);
if (r == -1) goto error;
r = set_proxy(result, "gopher", proxyDict,
kSCPropNetProxiesGopherEnable,
kSCPropNetProxiesGopherProxy,
kSCPropNetProxiesGopherPort);
if (r == -1) goto error;
CFRelease(proxyDict);
return result;
CFRelease(proxyDict);
return result;
error:
if (proxyDict) CFRelease(proxyDict);
Py_XDECREF(result);
return NULL;
if (proxyDict) CFRelease(proxyDict);
Py_XDECREF(result);
return NULL;
}
static PyMethodDef mod_methods[] = {
{
"_get_proxy_settings",
(PyCFunction)get_proxy_settings,
METH_NOARGS,
NULL,
},
{
"_get_proxies",
(PyCFunction)get_proxies,
METH_NOARGS,
NULL,
},
{ 0, 0, 0, 0 }
{
"_get_proxy_settings",
(PyCFunction)get_proxy_settings,
METH_NOARGS,
NULL,
},
{
"_get_proxies",
(PyCFunction)get_proxies,
METH_NOARGS,
NULL,
},
{ 0, 0, 0, 0 }
};
static struct PyModuleDef mod_module = {
PyModuleDef_HEAD_INIT,
"_scproxy",
NULL,
-1,
mod_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_scproxy",
NULL,
-1,
mod_methods,
NULL,
NULL,
NULL,
NULL
};
@ -249,10 +249,10 @@ static struct PyModuleDef mod_module = {
extern "C" {
#endif
PyObject*
PyObject*
PyInit__scproxy(void)
{
return PyModule_Create(&mod_module);
return PyModule_Create(&mod_module);
}
#ifdef __cplusplus

View file

@ -64,7 +64,7 @@ static PyObject* module_connect(PyObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOi", kwlist,
&database, &timeout, &detect_types, &isolation_level, &check_same_thread, &factory, &cached_statements))
{
return NULL;
return NULL;
}
if (factory == NULL) {
@ -93,7 +93,7 @@ static PyObject* module_complete(PyObject* self, PyObject* args, PyObject*
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &statement))
{
return NULL;
return NULL;
}
if (sqlite3_complete(statement)) {
@ -122,7 +122,7 @@ static PyObject* module_enable_shared_cache(PyObject* self, PyObject* args, PyOb
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i", kwlist, &do_enable))
{
return NULL;
return NULL;
}
rc = sqlite3_enable_shared_cache(do_enable);
@ -302,15 +302,15 @@ static IntConstantPair _int_constants[] = {
static struct PyModuleDef _sqlite3module = {
PyModuleDef_HEAD_INIT,
"_sqlite3",
NULL,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_sqlite3",
NULL,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit__sqlite3(void)
@ -329,7 +329,7 @@ PyMODINIT_FUNC PyInit__sqlite3(void)
(pysqlite_statement_setup_types() < 0) ||
(pysqlite_prepare_protocol_setup_types() < 0)
) {
Py_DECREF(module);
Py_DECREF(module);
return NULL;
}
@ -448,7 +448,7 @@ PyMODINIT_FUNC PyInit__sqlite3(void)
/* Original comment from _bsddb.c in the Python core. This is also still
* needed nowadays for Python 2.3/2.4.
*
*
* PyEval_InitThreads is called here due to a quirk in python 1.5
* - 2.2.1 (at least) according to Russell Williamson <merel@wt.net>:
* The global interpreter lock is not initialized until the first
@ -467,8 +467,8 @@ error:
if (PyErr_Occurred())
{
PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed");
Py_DECREF(module);
module = NULL;
Py_DECREF(module);
module = NULL;
}
return module;
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
/*
* Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project.
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
@ -13,7 +13,7 @@
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
@ -55,20 +55,20 @@
#define getaddrinfo fake_getaddrinfo
#endif /* EAI_ADDRFAMILY */
#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */
#define EAI_AGAIN 2 /* temporary failure in name resolution */
#define EAI_BADFLAGS 3 /* invalid value for ai_flags */
#define EAI_FAIL 4 /* non-recoverable failure in name resolution */
#define EAI_FAMILY 5 /* ai_family not supported */
#define EAI_MEMORY 6 /* memory allocation failure */
#define EAI_NODATA 7 /* no address associated with hostname */
#define EAI_NONAME 8 /* hostname nor servname provided, or not known */
#define EAI_SERVICE 9 /* servname not supported for ai_socktype */
#define EAI_SOCKTYPE 10 /* ai_socktype not supported */
#define EAI_SYSTEM 11 /* system error returned in errno */
#define EAI_BADHINTS 12
#define EAI_PROTOCOL 13
#define EAI_MAX 14
#define EAI_ADDRFAMILY 1 /* address family for hostname not supported */
#define EAI_AGAIN 2 /* temporary failure in name resolution */
#define EAI_BADFLAGS 3 /* invalid value for ai_flags */
#define EAI_FAIL 4 /* non-recoverable failure in name resolution */
#define EAI_FAMILY 5 /* ai_family not supported */
#define EAI_MEMORY 6 /* memory allocation failure */
#define EAI_NODATA 7 /* no address associated with hostname */
#define EAI_NONAME 8 /* hostname nor servname provided, or not known */
#define EAI_SERVICE 9 /* servname not supported for ai_socktype */
#define EAI_SOCKTYPE 10 /* ai_socktype not supported */
#define EAI_SYSTEM 11 /* system error returned in errno */
#define EAI_BADHINTS 12
#define EAI_PROTOCOL 13
#define EAI_MAX 14
/*
* Flag values for getaddrinfo()
@ -85,18 +85,18 @@
#undef AI_DEFAULT
#endif /* AI_PASSIVE */
#define AI_PASSIVE 0x00000001 /* get address to use bind() */
#define AI_CANONNAME 0x00000002 /* fill ai_canonname */
#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */
#define AI_PASSIVE 0x00000001 /* get address to use bind() */
#define AI_CANONNAME 0x00000002 /* fill ai_canonname */
#define AI_NUMERICHOST 0x00000004 /* prevent name resolution */
/* valid flags for addrinfo */
#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST)
#define AI_MASK (AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST)
#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */
#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */
#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */
#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */
#define AI_ALL 0x00000100 /* IPv6 and IPv4-mapped (with AI_V4MAPPED) */
#define AI_V4MAPPED_CFG 0x00000200 /* accept IPv4-mapped if kernel supports */
#define AI_ADDRCONFIG 0x00000400 /* only if any address is assigned */
#define AI_V4MAPPED 0x00000800 /* accept IPv4-mapped IPv6 address */
/* special recommended flags for getipnodebyname */
#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG)
#define AI_DEFAULT (AI_V4MAPPED_CFG | AI_ADDRCONFIG)
#endif /* !HAVE_GETADDRINFO */
@ -106,33 +106,33 @@
* Constants for getnameinfo()
*/
#ifndef NI_MAXHOST
#define NI_MAXHOST 1025
#define NI_MAXSERV 32
#define NI_MAXHOST 1025
#define NI_MAXSERV 32
#endif /* !NI_MAXHOST */
/*
* Flag values for getnameinfo()
*/
#ifndef NI_NOFQDN
#define NI_NOFQDN 0x00000001
#define NI_NUMERICHOST 0x00000002
#define NI_NAMEREQD 0x00000004
#define NI_NUMERICSERV 0x00000008
#define NI_DGRAM 0x00000010
#define NI_NOFQDN 0x00000001
#define NI_NUMERICHOST 0x00000002
#define NI_NAMEREQD 0x00000004
#define NI_NUMERICSERV 0x00000008
#define NI_DGRAM 0x00000010
#endif /* !NI_NOFQDN */
#endif /* !HAVE_GETNAMEINFO */
#ifndef HAVE_ADDRINFO
struct addrinfo {
int ai_flags; /* AI_PASSIVE, AI_CANONNAME */
int ai_family; /* PF_xxx */
int ai_socktype; /* SOCK_xxx */
int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
size_t ai_addrlen; /* length of ai_addr */
char *ai_canonname; /* canonical name for hostname */
struct sockaddr *ai_addr; /* binary address */
struct addrinfo *ai_next; /* next structure in linked list */
int ai_flags; /* AI_PASSIVE, AI_CANONNAME */
int ai_family; /* PF_xxx */
int ai_socktype; /* SOCK_xxx */
int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
size_t ai_addrlen; /* length of ai_addr */
char *ai_canonname; /* canonical name for hostname */
struct sockaddr *ai_addr; /* binary address */
struct addrinfo *ai_next; /* next structure in linked list */
};
#endif /* !HAVE_ADDRINFO */
@ -140,30 +140,30 @@ struct addrinfo {
/*
* RFC 2553: protocol-independent placeholder for socket addresses
*/
#define _SS_MAXSIZE 128
#define _SS_MAXSIZE 128
#ifdef HAVE_LONG_LONG
#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG))
#define _SS_ALIGNSIZE (sizeof(PY_LONG_LONG))
#else
#define _SS_ALIGNSIZE (sizeof(double))
#define _SS_ALIGNSIZE (sizeof(double))
#endif /* HAVE_LONG_LONG */
#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2)
#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \
_SS_PAD1SIZE - _SS_ALIGNSIZE)
#define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(u_char) * 2)
#define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(u_char) * 2 - \
_SS_PAD1SIZE - _SS_ALIGNSIZE)
struct sockaddr_storage {
#ifdef HAVE_SOCKADDR_SA_LEN
unsigned char ss_len; /* address length */
unsigned char ss_family; /* address family */
unsigned char ss_len; /* address length */
unsigned char ss_family; /* address family */
#else
unsigned short ss_family; /* address family */
unsigned short ss_family; /* address family */
#endif /* HAVE_SOCKADDR_SA_LEN */
char __ss_pad1[_SS_PAD1SIZE];
char __ss_pad1[_SS_PAD1SIZE];
#ifdef HAVE_LONG_LONG
PY_LONG_LONG __ss_align; /* force desired structure storage alignment */
PY_LONG_LONG __ss_align; /* force desired structure storage alignment */
#else
double __ss_align; /* force desired structure storage alignment */
double __ss_align; /* force desired structure storage alignment */
#endif /* HAVE_LONG_LONG */
char __ss_pad2[_SS_PAD2SIZE];
char __ss_pad2[_SS_PAD2SIZE];
};
#endif /* !HAVE_SOCKADDR_STORAGE */

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -17,24 +17,24 @@
/* GBK and GB2312 map differently in few codepoints that are listed below:
*
* gb2312 gbk
* A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT
* A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH
* A844 undefined U+2015 HORIZONTAL BAR
* gb2312 gbk
* A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT
* A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH
* A844 undefined U+2015 HORIZONTAL BAR
*/
#define GBK_DECODE(dc1, dc2, assi) \
if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \
else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \
else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \
else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \
else TRYMAP_DEC(gbkext, assi, dc1, dc2);
if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \
else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \
else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \
else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \
else TRYMAP_DEC(gbkext, assi, dc1, dc2);
#define GBK_ENCODE(code, assi) \
if ((code) == 0x2014) (assi) = 0xa1aa; \
else if ((code) == 0x2015) (assi) = 0xa844; \
else if ((code) == 0x00b7) (assi) = 0xa1a4; \
else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code));
if ((code) == 0x2014) (assi) = 0xa1aa; \
else if ((code) == 0x2015) (assi) = 0xa844; \
else if ((code) == 0x00b7) (assi) = 0xa1a4; \
else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code));
/*
* GB2312 codec
@ -42,53 +42,53 @@
ENCODER(gb2312)
{
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
REQUIRE_OUTBUF(2)
TRYMAP_ENC(gbcommon, code, c);
else return 1;
REQUIRE_OUTBUF(2)
TRYMAP_ENC(gbcommon, code, c);
else return 1;
if (code & 0x8000) /* MSB set: GBK */
return 1;
if (code & 0x8000) /* MSB set: GBK */
return 1;
OUT1((code >> 8) | 0x80)
OUT2((code & 0xFF) | 0x80)
NEXT(1, 2)
}
OUT1((code >> 8) | 0x80)
OUT2((code & 0xFF) | 0x80)
NEXT(1, 2)
}
return 0;
return 0;
}
DECODER(gb2312)
{
while (inleft > 0) {
unsigned char c = **inbuf;
while (inleft > 0) {
unsigned char c = **inbuf;
REQUIRE_OUTBUF(1)
REQUIRE_OUTBUF(1)
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
REQUIRE_INBUF(2)
TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
NEXT(2, 1)
}
else return 2;
}
REQUIRE_INBUF(2)
TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
NEXT(2, 1)
}
else return 2;
}
return 0;
return 0;
}
@ -98,55 +98,55 @@ DECODER(gb2312)
ENCODER(gbk)
{
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
REQUIRE_OUTBUF(2)
REQUIRE_OUTBUF(2)
GBK_ENCODE(c, code)
else return 1;
GBK_ENCODE(c, code)
else return 1;
OUT1((code >> 8) | 0x80)
if (code & 0x8000)
OUT2((code & 0xFF)) /* MSB set: GBK */
else
OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
NEXT(1, 2)
}
OUT1((code >> 8) | 0x80)
if (code & 0x8000)
OUT2((code & 0xFF)) /* MSB set: GBK */
else
OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
NEXT(1, 2)
}
return 0;
return 0;
}
DECODER(gbk)
{
while (inleft > 0) {
unsigned char c = IN1;
while (inleft > 0) {
unsigned char c = IN1;
REQUIRE_OUTBUF(1)
REQUIRE_OUTBUF(1)
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
REQUIRE_INBUF(2)
REQUIRE_INBUF(2)
GBK_DECODE(c, IN2, **outbuf)
else return 2;
GBK_DECODE(c, IN2, **outbuf)
else return 2;
NEXT(2, 1)
}
NEXT(2, 1)
}
return 0;
return 0;
}
@ -156,153 +156,153 @@ DECODER(gbk)
ENCODER(gb18030)
{
while (inleft > 0) {
ucs4_t c = IN1;
DBCHAR code;
while (inleft > 0) {
ucs4_t c = IN1;
DBCHAR code;
if (c < 0x80) {
WRITE1(c)
NEXT(1, 1)
continue;
}
if (c < 0x80) {
WRITE1(c)
NEXT(1, 1)
continue;
}
DECODE_SURROGATE(c)
if (c > 0x10FFFF)
DECODE_SURROGATE(c)
if (c > 0x10FFFF)
#if Py_UNICODE_SIZE == 2
return 2; /* surrogates pair */
return 2; /* surrogates pair */
#else
return 1;
return 1;
#endif
else if (c >= 0x10000) {
ucs4_t tc = c - 0x10000;
else if (c >= 0x10000) {
ucs4_t tc = c - 0x10000;
REQUIRE_OUTBUF(4)
REQUIRE_OUTBUF(4)
OUT4((unsigned char)(tc % 10) + 0x30)
tc /= 10;
OUT3((unsigned char)(tc % 126) + 0x81)
tc /= 126;
OUT2((unsigned char)(tc % 10) + 0x30)
tc /= 10;
OUT1((unsigned char)(tc + 0x90))
OUT4((unsigned char)(tc % 10) + 0x30)
tc /= 10;
OUT3((unsigned char)(tc % 126) + 0x81)
tc /= 126;
OUT2((unsigned char)(tc % 10) + 0x30)
tc /= 10;
OUT1((unsigned char)(tc + 0x90))
#if Py_UNICODE_SIZE == 2
NEXT(2, 4) /* surrogates pair */
NEXT(2, 4) /* surrogates pair */
#else
NEXT(1, 4)
NEXT(1, 4)
#endif
continue;
}
continue;
}
REQUIRE_OUTBUF(2)
REQUIRE_OUTBUF(2)
GBK_ENCODE(c, code)
else TRYMAP_ENC(gb18030ext, code, c);
else {
const struct _gb18030_to_unibmp_ranges *utrrange;
GBK_ENCODE(c, code)
else TRYMAP_ENC(gb18030ext, code, c);
else {
const struct _gb18030_to_unibmp_ranges *utrrange;
REQUIRE_OUTBUF(4)
REQUIRE_OUTBUF(4)
for (utrrange = gb18030_to_unibmp_ranges;
utrrange->first != 0;
utrrange++)
if (utrrange->first <= c &&
c <= utrrange->last) {
Py_UNICODE tc;
for (utrrange = gb18030_to_unibmp_ranges;
utrrange->first != 0;
utrrange++)
if (utrrange->first <= c &&
c <= utrrange->last) {
Py_UNICODE tc;
tc = c - utrrange->first +
utrrange->base;
tc = c - utrrange->first +
utrrange->base;
OUT4((unsigned char)(tc % 10) + 0x30)
tc /= 10;
OUT3((unsigned char)(tc % 126) + 0x81)
tc /= 126;
OUT2((unsigned char)(tc % 10) + 0x30)
tc /= 10;
OUT1((unsigned char)tc + 0x81)
OUT4((unsigned char)(tc % 10) + 0x30)
tc /= 10;
OUT3((unsigned char)(tc % 126) + 0x81)
tc /= 126;
OUT2((unsigned char)(tc % 10) + 0x30)
tc /= 10;
OUT1((unsigned char)tc + 0x81)
NEXT(1, 4)
break;
}
NEXT(1, 4)
break;
}
if (utrrange->first == 0)
return 1;
continue;
}
if (utrrange->first == 0)
return 1;
continue;
}
OUT1((code >> 8) | 0x80)
if (code & 0x8000)
OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */
else
OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
OUT1((code >> 8) | 0x80)
if (code & 0x8000)
OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */
else
OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
NEXT(1, 2)
}
NEXT(1, 2)
}
return 0;
return 0;
}
DECODER(gb18030)
{
while (inleft > 0) {
unsigned char c = IN1, c2;
while (inleft > 0) {
unsigned char c = IN1, c2;
REQUIRE_OUTBUF(1)
REQUIRE_OUTBUF(1)
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
REQUIRE_INBUF(2)
REQUIRE_INBUF(2)
c2 = IN2;
if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */
const struct _gb18030_to_unibmp_ranges *utr;
unsigned char c3, c4;
ucs4_t lseq;
c2 = IN2;
if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */
const struct _gb18030_to_unibmp_ranges *utr;
unsigned char c3, c4;
ucs4_t lseq;
REQUIRE_INBUF(4)
c3 = IN3;
c4 = IN4;
if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39)
return 4;
c -= 0x81; c2 -= 0x30;
c3 -= 0x81; c4 -= 0x30;
REQUIRE_INBUF(4)
c3 = IN3;
c4 = IN4;
if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39)
return 4;
c -= 0x81; c2 -= 0x30;
c3 -= 0x81; c4 -= 0x30;
if (c < 4) { /* U+0080 - U+FFFF */
lseq = ((ucs4_t)c * 10 + c2) * 1260 +
(ucs4_t)c3 * 10 + c4;
if (lseq < 39420) {
for (utr = gb18030_to_unibmp_ranges;
lseq >= (utr + 1)->base;
utr++) ;
OUT1(utr->first - utr->base + lseq)
NEXT(4, 1)
continue;
}
}
else if (c >= 15) { /* U+10000 - U+10FFFF */
lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2)
* 1260 + (ucs4_t)c3 * 10 + c4;
if (lseq <= 0x10FFFF) {
WRITEUCS4(lseq);
NEXT_IN(4)
continue;
}
}
return 4;
}
if (c < 4) { /* U+0080 - U+FFFF */
lseq = ((ucs4_t)c * 10 + c2) * 1260 +
(ucs4_t)c3 * 10 + c4;
if (lseq < 39420) {
for (utr = gb18030_to_unibmp_ranges;
lseq >= (utr + 1)->base;
utr++) ;
OUT1(utr->first - utr->base + lseq)
NEXT(4, 1)
continue;
}
}
else if (c >= 15) { /* U+10000 - U+10FFFF */
lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2)
* 1260 + (ucs4_t)c3 * 10 + c4;
if (lseq <= 0x10FFFF) {
WRITEUCS4(lseq);
NEXT_IN(4)
continue;
}
}
return 4;
}
GBK_DECODE(c, c2, **outbuf)
else TRYMAP_DEC(gb18030ext, **outbuf, c, c2);
else return 2;
GBK_DECODE(c, c2, **outbuf)
else TRYMAP_DEC(gb18030ext, **outbuf, c, c2);
else return 2;
NEXT(2, 1)
}
NEXT(2, 1)
}
return 0;
return 0;
}
@ -312,118 +312,118 @@ DECODER(gb18030)
ENCODER_INIT(hz)
{
state->i = 0;
return 0;
state->i = 0;
return 0;
}
ENCODER_RESET(hz)
{
if (state->i != 0) {
WRITE2('~', '}')
state->i = 0;
NEXT_OUT(2)
}
return 0;
if (state->i != 0) {
WRITE2('~', '}')
state->i = 0;
NEXT_OUT(2)
}
return 0;
}
ENCODER(hz)
{
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
if (c < 0x80) {
if (state->i == 0) {
WRITE1((unsigned char)c)
NEXT(1, 1)
}
else {
WRITE3('~', '}', (unsigned char)c)
NEXT(1, 3)
state->i = 0;
}
continue;
}
if (c < 0x80) {
if (state->i == 0) {
WRITE1((unsigned char)c)
NEXT(1, 1)
}
else {
WRITE3('~', '}', (unsigned char)c)
NEXT(1, 3)
state->i = 0;
}
continue;
}
UCS4INVALID(c)
UCS4INVALID(c)
TRYMAP_ENC(gbcommon, code, c);
else return 1;
TRYMAP_ENC(gbcommon, code, c);
else return 1;
if (code & 0x8000) /* MSB set: GBK */
return 1;
if (code & 0x8000) /* MSB set: GBK */
return 1;
if (state->i == 0) {
WRITE4('~', '{', code >> 8, code & 0xff)
NEXT(1, 4)
state->i = 1;
}
else {
WRITE2(code >> 8, code & 0xff)
NEXT(1, 2)
}
}
if (state->i == 0) {
WRITE4('~', '{', code >> 8, code & 0xff)
NEXT(1, 4)
state->i = 1;
}
else {
WRITE2(code >> 8, code & 0xff)
NEXT(1, 2)
}
}
return 0;
return 0;
}
DECODER_INIT(hz)
{
state->i = 0;
return 0;
state->i = 0;
return 0;
}
DECODER_RESET(hz)
{
state->i = 0;
return 0;
state->i = 0;
return 0;
}
DECODER(hz)
{
while (inleft > 0) {
unsigned char c = IN1;
while (inleft > 0) {
unsigned char c = IN1;
if (c == '~') {
unsigned char c2 = IN2;
if (c == '~') {
unsigned char c2 = IN2;
REQUIRE_INBUF(2)
if (c2 == '~') {
WRITE1('~')
NEXT(2, 1)
continue;
}
else if (c2 == '{' && state->i == 0)
state->i = 1; /* set GB */
else if (c2 == '}' && state->i == 1)
state->i = 0; /* set ASCII */
else if (c2 == '\n')
; /* line-continuation */
else
return 2;
NEXT(2, 0);
continue;
}
REQUIRE_INBUF(2)
if (c2 == '~') {
WRITE1('~')
NEXT(2, 1)
continue;
}
else if (c2 == '{' && state->i == 0)
state->i = 1; /* set GB */
else if (c2 == '}' && state->i == 1)
state->i = 0; /* set ASCII */
else if (c2 == '\n')
; /* line-continuation */
else
return 2;
NEXT(2, 0);
continue;
}
if (c & 0x80)
return 1;
if (c & 0x80)
return 1;
if (state->i == 0) { /* ASCII mode */
WRITE1(c)
NEXT(1, 1)
}
else { /* GB mode */
REQUIRE_INBUF(2)
REQUIRE_OUTBUF(1)
TRYMAP_DEC(gb2312, **outbuf, c, IN2) {
NEXT(2, 1)
}
else
return 2;
}
}
if (state->i == 0) { /* ASCII mode */
WRITE1(c)
NEXT(1, 1)
}
else { /* GB mode */
REQUIRE_INBUF(2)
REQUIRE_OUTBUF(1)
TRYMAP_DEC(gb2312, **outbuf, c, IN2) {
NEXT(2, 1)
}
else
return 2;
}
}
return 0;
return 0;
}

View file

@ -18,12 +18,12 @@ static const decode_map *big5_decmap = NULL;
CODEC_INIT(big5hkscs)
{
static int initialized = 0;
static int initialized = 0;
if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap))
return -1;
initialized = 1;
return 0;
if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap))
return -1;
initialized = 1;
return 0;
}
/*
@ -38,135 +38,135 @@ static const DBCHAR big5hkscs_pairenc_table[4] = {0x8862, 0x8864, 0x88a3, 0x88a5
ENCODER(big5hkscs)
{
while (inleft > 0) {
ucs4_t c = **inbuf;
DBCHAR code;
Py_ssize_t insize;
while (inleft > 0) {
ucs4_t c = **inbuf;
DBCHAR code;
Py_ssize_t insize;
if (c < 0x80) {
REQUIRE_OUTBUF(1)
**outbuf = (unsigned char)c;
NEXT(1, 1)
continue;
}
if (c < 0x80) {
REQUIRE_OUTBUF(1)
**outbuf = (unsigned char)c;
NEXT(1, 1)
continue;
}
DECODE_SURROGATE(c)
insize = GET_INSIZE(c);
DECODE_SURROGATE(c)
insize = GET_INSIZE(c);
REQUIRE_OUTBUF(2)
REQUIRE_OUTBUF(2)
if (c < 0x10000) {
TRYMAP_ENC(big5hkscs_bmp, code, c) {
if (code == MULTIC) {
if (inleft >= 2 &&
((c & 0xffdf) == 0x00ca) &&
(((*inbuf)[1] & 0xfff7) == 0x0304)) {
code = big5hkscs_pairenc_table[
((c >> 4) |
((*inbuf)[1] >> 3)) & 3];
insize = 2;
}
else if (inleft < 2 &&
!(flags & MBENC_FLUSH))
return MBERR_TOOFEW;
else {
if (c == 0xca)
code = 0x8866;
else /* c == 0xea */
code = 0x88a7;
}
}
}
else TRYMAP_ENC(big5, code, c);
else return 1;
}
else if (c < 0x20000)
return insize;
else if (c < 0x30000) {
TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff);
else return insize;
}
else
return insize;
if (c < 0x10000) {
TRYMAP_ENC(big5hkscs_bmp, code, c) {
if (code == MULTIC) {
if (inleft >= 2 &&
((c & 0xffdf) == 0x00ca) &&
(((*inbuf)[1] & 0xfff7) == 0x0304)) {
code = big5hkscs_pairenc_table[
((c >> 4) |
((*inbuf)[1] >> 3)) & 3];
insize = 2;
}
else if (inleft < 2 &&
!(flags & MBENC_FLUSH))
return MBERR_TOOFEW;
else {
if (c == 0xca)
code = 0x8866;
else /* c == 0xea */
code = 0x88a7;
}
}
}
else TRYMAP_ENC(big5, code, c);
else return 1;
}
else if (c < 0x20000)
return insize;
else if (c < 0x30000) {
TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff);
else return insize;
}
else
return insize;
OUT1(code >> 8)
OUT2(code & 0xFF)
NEXT(insize, 2)
}
OUT1(code >> 8)
OUT2(code & 0xFF)
NEXT(insize, 2)
}
return 0;
return 0;
}
#define BH2S(c1, c2) (((c1) - 0x87) * (0xfe - 0x40 + 1) + ((c2) - 0x40))
DECODER(big5hkscs)
{
while (inleft > 0) {
unsigned char c = IN1;
ucs4_t decoded;
while (inleft > 0) {
unsigned char c = IN1;
ucs4_t decoded;
REQUIRE_OUTBUF(1)
REQUIRE_OUTBUF(1)
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
REQUIRE_INBUF(2)
REQUIRE_INBUF(2)
if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1))
goto hkscsdec;
if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1))
goto hkscsdec;
TRYMAP_DEC(big5, **outbuf, c, IN2) {
NEXT(2, 1)
}
else
hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) {
int s = BH2S(c, IN2);
const unsigned char *hintbase;
TRYMAP_DEC(big5, **outbuf, c, IN2) {
NEXT(2, 1)
}
else
hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) {
int s = BH2S(c, IN2);
const unsigned char *hintbase;
assert(0x87 <= c && c <= 0xfe);
assert(0x40 <= IN2 && IN2 <= 0xfe);
assert(0x87 <= c && c <= 0xfe);
assert(0x40 <= IN2 && IN2 <= 0xfe);
if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) {
hintbase = big5hkscs_phint_0;
s -= BH2S(0x87, 0x40);
}
else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){
hintbase = big5hkscs_phint_12130;
s -= BH2S(0xc6, 0xa1);
}
else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){
hintbase = big5hkscs_phint_21924;
s -= BH2S(0xf9, 0xd6);
}
else
return MBERR_INTERNAL;
if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) {
hintbase = big5hkscs_phint_0;
s -= BH2S(0x87, 0x40);
}
else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){
hintbase = big5hkscs_phint_12130;
s -= BH2S(0xc6, 0xa1);
}
else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){
hintbase = big5hkscs_phint_21924;
s -= BH2S(0xf9, 0xd6);
}
else
return MBERR_INTERNAL;
if (hintbase[s >> 3] & (1 << (s & 7))) {
WRITEUCS4(decoded | 0x20000)
NEXT_IN(2)
}
else {
OUT1(decoded)
NEXT(2, 1)
}
}
else {
switch ((c << 8) | IN2) {
case 0x8862: WRITE2(0x00ca, 0x0304); break;
case 0x8864: WRITE2(0x00ca, 0x030c); break;
case 0x88a3: WRITE2(0x00ea, 0x0304); break;
case 0x88a5: WRITE2(0x00ea, 0x030c); break;
default: return 2;
}
if (hintbase[s >> 3] & (1 << (s & 7))) {
WRITEUCS4(decoded | 0x20000)
NEXT_IN(2)
}
else {
OUT1(decoded)
NEXT(2, 1)
}
}
else {
switch ((c << 8) | IN2) {
case 0x8862: WRITE2(0x00ca, 0x0304); break;
case 0x8864: WRITE2(0x00ca, 0x030c); break;
case 0x88a3: WRITE2(0x00ea, 0x0304); break;
case 0x88a5: WRITE2(0x00ea, 0x030c); break;
default: return 2;
}
NEXT(2, 2) /* all decoded codepoints are pairs, above. */
}
}
NEXT(2, 2) /* all decoded codepoints are pairs, above. */
}
}
return 0;
return 0;
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -11,151 +11,151 @@
* EUC-KR codec
*/
#define EUCKR_JAMO_FIRSTBYTE 0xA4
#define EUCKR_JAMO_FILLER 0xD4
#define EUCKR_JAMO_FIRSTBYTE 0xA4
#define EUCKR_JAMO_FILLER 0xD4
static const unsigned char u2cgk_choseong[19] = {
0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2,
0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb,
0xbc, 0xbd, 0xbe
0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2,
0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb,
0xbc, 0xbd, 0xbe
};
static const unsigned char u2cgk_jungseong[21] = {
0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6,
0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
0xcf, 0xd0, 0xd1, 0xd2, 0xd3
0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6,
0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
0xcf, 0xd0, 0xd1, 0xd2, 0xd3
};
static const unsigned char u2cgk_jongseong[28] = {
0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0,
0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba,
0xbb, 0xbc, 0xbd, 0xbe
0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0,
0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba,
0xbb, 0xbc, 0xbd, 0xbe
};
ENCODER(euc_kr)
{
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
REQUIRE_OUTBUF(2)
TRYMAP_ENC(cp949, code, c);
else return 1;
REQUIRE_OUTBUF(2)
TRYMAP_ENC(cp949, code, c);
else return 1;
if ((code & 0x8000) == 0) {
/* KS X 1001 coded character */
OUT1((code >> 8) | 0x80)
OUT2((code & 0xFF) | 0x80)
NEXT(1, 2)
}
else { /* Mapping is found in CP949 extension,
* but we encode it in KS X 1001:1998 Annex 3,
* make-up sequence for EUC-KR. */
if ((code & 0x8000) == 0) {
/* KS X 1001 coded character */
OUT1((code >> 8) | 0x80)
OUT2((code & 0xFF) | 0x80)
NEXT(1, 2)
}
else { /* Mapping is found in CP949 extension,
* but we encode it in KS X 1001:1998 Annex 3,
* make-up sequence for EUC-KR. */
REQUIRE_OUTBUF(8)
REQUIRE_OUTBUF(8)
/* syllable composition precedence */
OUT1(EUCKR_JAMO_FIRSTBYTE)
OUT2(EUCKR_JAMO_FILLER)
/* syllable composition precedence */
OUT1(EUCKR_JAMO_FIRSTBYTE)
OUT2(EUCKR_JAMO_FILLER)
/* All codepoints in CP949 extension are in unicode
* Hangul Syllable area. */
assert(0xac00 <= c && c <= 0xd7a3);
c -= 0xac00;
/* All codepoints in CP949 extension are in unicode
* Hangul Syllable area. */
assert(0xac00 <= c && c <= 0xd7a3);
c -= 0xac00;
OUT3(EUCKR_JAMO_FIRSTBYTE)
OUT4(u2cgk_choseong[c / 588])
NEXT_OUT(4)
OUT3(EUCKR_JAMO_FIRSTBYTE)
OUT4(u2cgk_choseong[c / 588])
NEXT_OUT(4)
OUT1(EUCKR_JAMO_FIRSTBYTE)
OUT2(u2cgk_jungseong[(c / 28) % 21])
OUT3(EUCKR_JAMO_FIRSTBYTE)
OUT4(u2cgk_jongseong[c % 28])
NEXT(1, 4)
}
}
OUT1(EUCKR_JAMO_FIRSTBYTE)
OUT2(u2cgk_jungseong[(c / 28) % 21])
OUT3(EUCKR_JAMO_FIRSTBYTE)
OUT4(u2cgk_jongseong[c % 28])
NEXT(1, 4)
}
}
return 0;
return 0;
}
#define NONE 127
#define NONE 127
static const unsigned char cgk2u_choseong[] = { /* [A1, BE] */
0, 1, NONE, 2, NONE, NONE, 3, 4,
5, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
6, 7, 8, NONE, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18
0, 1, NONE, 2, NONE, NONE, 3, 4,
5, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
6, 7, 8, NONE, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18
};
static const unsigned char cgk2u_jongseong[] = { /* [A1, BE] */
1, 2, 3, 4, 5, 6, 7, NONE,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, NONE, 18, 19, 20, 21, 22,
NONE, 23, 24, 25, 26, 27
1, 2, 3, 4, 5, 6, 7, NONE,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, NONE, 18, 19, 20, 21, 22,
NONE, 23, 24, 25, 26, 27
};
DECODER(euc_kr)
{
while (inleft > 0) {
unsigned char c = IN1;
while (inleft > 0) {
unsigned char c = IN1;
REQUIRE_OUTBUF(1)
REQUIRE_OUTBUF(1)
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
REQUIRE_INBUF(2)
REQUIRE_INBUF(2)
if (c == EUCKR_JAMO_FIRSTBYTE &&
IN2 == EUCKR_JAMO_FILLER) {
/* KS X 1001:1998 Annex 3 make-up sequence */
DBCHAR cho, jung, jong;
if (c == EUCKR_JAMO_FIRSTBYTE &&
IN2 == EUCKR_JAMO_FILLER) {
/* KS X 1001:1998 Annex 3 make-up sequence */
DBCHAR cho, jung, jong;
REQUIRE_INBUF(8)
if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE ||
(*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE ||
(*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE)
return 8;
REQUIRE_INBUF(8)
if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE ||
(*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE ||
(*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE)
return 8;
c = (*inbuf)[3];
if (0xa1 <= c && c <= 0xbe)
cho = cgk2u_choseong[c - 0xa1];
else
cho = NONE;
c = (*inbuf)[3];
if (0xa1 <= c && c <= 0xbe)
cho = cgk2u_choseong[c - 0xa1];
else
cho = NONE;
c = (*inbuf)[5];
jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE;
c = (*inbuf)[5];
jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE;
c = (*inbuf)[7];
if (c == EUCKR_JAMO_FILLER)
jong = 0;
else if (0xa1 <= c && c <= 0xbe)
jong = cgk2u_jongseong[c - 0xa1];
else
jong = NONE;
c = (*inbuf)[7];
if (c == EUCKR_JAMO_FILLER)
jong = 0;
else if (0xa1 <= c && c <= 0xbe)
jong = cgk2u_jongseong[c - 0xa1];
else
jong = NONE;
if (cho == NONE || jung == NONE || jong == NONE)
return 8;
if (cho == NONE || jung == NONE || jong == NONE)
return 8;
OUT1(0xac00 + cho*588 + jung*28 + jong);
NEXT(8, 1)
}
else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
NEXT(2, 1)
}
else
return 2;
}
OUT1(0xac00 + cho*588 + jung*28 + jong);
NEXT(8, 1)
}
else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
NEXT(2, 1)
}
else
return 2;
}
return 0;
return 0;
}
#undef NONE
@ -166,54 +166,54 @@ DECODER(euc_kr)
ENCODER(cp949)
{
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
REQUIRE_OUTBUF(2)
TRYMAP_ENC(cp949, code, c);
else return 1;
REQUIRE_OUTBUF(2)
TRYMAP_ENC(cp949, code, c);
else return 1;
OUT1((code >> 8) | 0x80)
if (code & 0x8000)
OUT2(code & 0xFF) /* MSB set: CP949 */
else
OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */
NEXT(1, 2)
}
OUT1((code >> 8) | 0x80)
if (code & 0x8000)
OUT2(code & 0xFF) /* MSB set: CP949 */
else
OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */
NEXT(1, 2)
}
return 0;
return 0;
}
DECODER(cp949)
{
while (inleft > 0) {
unsigned char c = IN1;
while (inleft > 0) {
unsigned char c = IN1;
REQUIRE_OUTBUF(1)
REQUIRE_OUTBUF(1)
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
REQUIRE_INBUF(2)
TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80);
else TRYMAP_DEC(cp949ext, **outbuf, c, IN2);
else return 2;
REQUIRE_INBUF(2)
TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80);
else TRYMAP_DEC(cp949ext, **outbuf, c, IN2);
else return 2;
NEXT(2, 1)
}
NEXT(2, 1)
}
return 0;
return 0;
}
@ -250,58 +250,58 @@ static const DBCHAR u2johabjamo[] = {
ENCODER(johab)
{
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
REQUIRE_OUTBUF(2)
REQUIRE_OUTBUF(2)
if (c >= 0xac00 && c <= 0xd7a3) {
c -= 0xac00;
code = 0x8000 |
(u2johabidx_choseong[c / 588] << 10) |
(u2johabidx_jungseong[(c / 28) % 21] << 5) |
u2johabidx_jongseong[c % 28];
}
else if (c >= 0x3131 && c <= 0x3163)
code = u2johabjamo[c - 0x3131];
else TRYMAP_ENC(cp949, code, c) {
unsigned char c1, c2, t2;
unsigned short t1;
if (c >= 0xac00 && c <= 0xd7a3) {
c -= 0xac00;
code = 0x8000 |
(u2johabidx_choseong[c / 588] << 10) |
(u2johabidx_jungseong[(c / 28) % 21] << 5) |
u2johabidx_jongseong[c % 28];
}
else if (c >= 0x3131 && c <= 0x3163)
code = u2johabjamo[c - 0x3131];
else TRYMAP_ENC(cp949, code, c) {
unsigned char c1, c2, t2;
unsigned short t1;
assert((code & 0x8000) == 0);
c1 = code >> 8;
c2 = code & 0xff;
if (((c1 >= 0x21 && c1 <= 0x2c) ||
(c1 >= 0x4a && c1 <= 0x7d)) &&
(c2 >= 0x21 && c2 <= 0x7e)) {
t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) :
(c1 - 0x21 + 0x197));
t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21);
OUT1(t1 >> 1)
OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43)
NEXT(1, 2)
continue;
}
else
return 1;
}
else
return 1;
assert((code & 0x8000) == 0);
c1 = code >> 8;
c2 = code & 0xff;
if (((c1 >= 0x21 && c1 <= 0x2c) ||
(c1 >= 0x4a && c1 <= 0x7d)) &&
(c2 >= 0x21 && c2 <= 0x7e)) {
t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) :
(c1 - 0x21 + 0x197));
t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21);
OUT1(t1 >> 1)
OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43)
NEXT(1, 2)
continue;
}
else
return 1;
}
else
return 1;
OUT1(code >> 8)
OUT2(code & 0xff)
NEXT(1, 2)
}
OUT1(code >> 8)
OUT2(code & 0xff)
NEXT(1, 2)
}
return 0;
return 0;
}
#define FILL 0xfd
@ -347,91 +347,91 @@ static const unsigned char johabjamo_jongseong[32] = {
DECODER(johab)
{
while (inleft > 0) {
unsigned char c = IN1, c2;
while (inleft > 0) {
unsigned char c = IN1, c2;
REQUIRE_OUTBUF(1)
REQUIRE_OUTBUF(1)
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
REQUIRE_INBUF(2)
c2 = IN2;
REQUIRE_INBUF(2)
c2 = IN2;
if (c < 0xd8) {
/* johab hangul */
unsigned char c_cho, c_jung, c_jong;
unsigned char i_cho, i_jung, i_jong;
if (c < 0xd8) {
/* johab hangul */
unsigned char c_cho, c_jung, c_jong;
unsigned char i_cho, i_jung, i_jong;
c_cho = (c >> 2) & 0x1f;
c_jung = ((c << 3) | c2 >> 5) & 0x1f;
c_jong = c2 & 0x1f;
c_cho = (c >> 2) & 0x1f;
c_jung = ((c << 3) | c2 >> 5) & 0x1f;
c_jong = c2 & 0x1f;
i_cho = johabidx_choseong[c_cho];
i_jung = johabidx_jungseong[c_jung];
i_jong = johabidx_jongseong[c_jong];
i_cho = johabidx_choseong[c_cho];
i_jung = johabidx_jungseong[c_jung];
i_jong = johabidx_jongseong[c_jong];
if (i_cho == NONE || i_jung == NONE || i_jong == NONE)
return 2;
if (i_cho == NONE || i_jung == NONE || i_jong == NONE)
return 2;
/* we don't use U+1100 hangul jamo yet. */
if (i_cho == FILL) {
if (i_jung == FILL) {
if (i_jong == FILL)
OUT1(0x3000)
else
OUT1(0x3100 |
johabjamo_jongseong[c_jong])
}
else {
if (i_jong == FILL)
OUT1(0x3100 |
johabjamo_jungseong[c_jung])
else
return 2;
}
} else {
if (i_jung == FILL) {
if (i_jong == FILL)
OUT1(0x3100 |
johabjamo_choseong[c_cho])
else
return 2;
}
else
OUT1(0xac00 +
i_cho * 588 +
i_jung * 28 +
(i_jong == FILL ? 0 : i_jong))
}
NEXT(2, 1)
} else {
/* KS X 1001 except hangul jamos and syllables */
if (c == 0xdf || c > 0xf9 ||
c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) ||
(c2 & 0x7f) == 0x7f ||
(c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3)))
return 2;
else {
unsigned char t1, t2;
/* we don't use U+1100 hangul jamo yet. */
if (i_cho == FILL) {
if (i_jung == FILL) {
if (i_jong == FILL)
OUT1(0x3000)
else
OUT1(0x3100 |
johabjamo_jongseong[c_jong])
}
else {
if (i_jong == FILL)
OUT1(0x3100 |
johabjamo_jungseong[c_jung])
else
return 2;
}
} else {
if (i_jung == FILL) {
if (i_jong == FILL)
OUT1(0x3100 |
johabjamo_choseong[c_cho])
else
return 2;
}
else
OUT1(0xac00 +
i_cho * 588 +
i_jung * 28 +
(i_jong == FILL ? 0 : i_jong))
}
NEXT(2, 1)
} else {
/* KS X 1001 except hangul jamos and syllables */
if (c == 0xdf || c > 0xf9 ||
c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) ||
(c2 & 0x7f) == 0x7f ||
(c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3)))
return 2;
else {
unsigned char t1, t2;
t1 = (c < 0xe0 ? 2 * (c - 0xd9) :
2 * c - 0x197);
t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43);
t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21;
t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21;
t1 = (c < 0xe0 ? 2 * (c - 0xd9) :
2 * c - 0x197);
t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43);
t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21;
t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21;
TRYMAP_DEC(ksx1001, **outbuf, t1, t2);
else return 2;
NEXT(2, 1)
}
}
}
TRYMAP_DEC(ksx1001, **outbuf, t1, t2);
else return 2;
NEXT(2, 1)
}
}
}
return 0;
return 0;
}
#undef NONE
#undef FILL

View file

@ -13,52 +13,52 @@
ENCODER(big5)
{
while (inleft > 0) {
Py_UNICODE c = **inbuf;
DBCHAR code;
while (inleft > 0) {
Py_UNICODE c = **inbuf;
DBCHAR code;
if (c < 0x80) {
REQUIRE_OUTBUF(1)
**outbuf = (unsigned char)c;
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
if (c < 0x80) {
REQUIRE_OUTBUF(1)
**outbuf = (unsigned char)c;
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
REQUIRE_OUTBUF(2)
REQUIRE_OUTBUF(2)
TRYMAP_ENC(big5, code, c);
else return 1;
TRYMAP_ENC(big5, code, c);
else return 1;
OUT1(code >> 8)
OUT2(code & 0xFF)
NEXT(1, 2)
}
OUT1(code >> 8)
OUT2(code & 0xFF)
NEXT(1, 2)
}
return 0;
return 0;
}
DECODER(big5)
{
while (inleft > 0) {
unsigned char c = IN1;
while (inleft > 0) {
unsigned char c = IN1;
REQUIRE_OUTBUF(1)
REQUIRE_OUTBUF(1)
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
REQUIRE_INBUF(2)
TRYMAP_DEC(big5, **outbuf, c, IN2) {
NEXT(2, 1)
}
else return 2;
}
REQUIRE_INBUF(2)
TRYMAP_DEC(big5, **outbuf, c, IN2) {
NEXT(2, 1)
}
else return 2;
}
return 0;
return 0;
}
@ -68,53 +68,53 @@ DECODER(big5)
ENCODER(cp950)
{
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
while (inleft > 0) {
Py_UNICODE c = IN1;
DBCHAR code;
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
if (c < 0x80) {
WRITE1((unsigned char)c)
NEXT(1, 1)
continue;
}
UCS4INVALID(c)
REQUIRE_OUTBUF(2)
TRYMAP_ENC(cp950ext, code, c);
else TRYMAP_ENC(big5, code, c);
else return 1;
REQUIRE_OUTBUF(2)
TRYMAP_ENC(cp950ext, code, c);
else TRYMAP_ENC(big5, code, c);
else return 1;
OUT1(code >> 8)
OUT2(code & 0xFF)
NEXT(1, 2)
}
OUT1(code >> 8)
OUT2(code & 0xFF)
NEXT(1, 2)
}
return 0;
return 0;
}
DECODER(cp950)
{
while (inleft > 0) {
unsigned char c = IN1;
while (inleft > 0) {
unsigned char c = IN1;
REQUIRE_OUTBUF(1)
REQUIRE_OUTBUF(1)
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
if (c < 0x80) {
OUT1(c)
NEXT(1, 1)
continue;
}
REQUIRE_INBUF(2)
REQUIRE_INBUF(2)
TRYMAP_DEC(cp950ext, **outbuf, c, IN2);
else TRYMAP_DEC(big5, **outbuf, c, IN2);
else return 2;
TRYMAP_DEC(cp950ext, **outbuf, c, IN2);
else TRYMAP_DEC(big5, **outbuf, c, IN2);
else return 2;
NEXT(2, 1)
}
NEXT(2, 1)
}
return 0;
return 0;
}

View file

@ -1,24 +1,24 @@
#define JISX0201_R_ENCODE(c, assi) \
if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \
(assi) = (c); \
else if ((c) == 0x00a5) (assi) = 0x5c; \
else if ((c) == 0x203e) (assi) = 0x7e;
#define JISX0201_K_ENCODE(c, assi) \
if ((c) >= 0xff61 && (c) <= 0xff9f) \
(assi) = (c) - 0xfec0;
#define JISX0201_ENCODE(c, assi) \
JISX0201_R_ENCODE(c, assi) \
else JISX0201_K_ENCODE(c, assi)
#define JISX0201_R_ENCODE(c, assi) \
if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \
(assi) = (c); \
else if ((c) == 0x00a5) (assi) = 0x5c; \
else if ((c) == 0x203e) (assi) = 0x7e;
#define JISX0201_K_ENCODE(c, assi) \
if ((c) >= 0xff61 && (c) <= 0xff9f) \
(assi) = (c) - 0xfec0;
#define JISX0201_ENCODE(c, assi) \
JISX0201_R_ENCODE(c, assi) \
else JISX0201_K_ENCODE(c, assi)
#define JISX0201_R_DECODE(c, assi) \
if ((c) < 0x5c) (assi) = (c); \
else if ((c) == 0x5c) (assi) = 0x00a5; \
else if ((c) < 0x7e) (assi) = (c); \
else if ((c) == 0x7e) (assi) = 0x203e; \
else if ((c) == 0x7f) (assi) = 0x7f;
#define JISX0201_K_DECODE(c, assi) \
if ((c) >= 0xa1 && (c) <= 0xdf) \
(assi) = 0xfec0 + (c);
#define JISX0201_DECODE(c, assi) \
JISX0201_R_DECODE(c, assi) \
else JISX0201_K_DECODE(c, assi)
#define JISX0201_R_DECODE(c, assi) \
if ((c) < 0x5c) (assi) = (c); \
else if ((c) == 0x5c) (assi) = 0x00a5; \
else if ((c) < 0x7e) (assi) = (c); \
else if ((c) == 0x7e) (assi) = 0x203e; \
else if ((c) == 0x7f) (assi) = 0x7f;
#define JISX0201_K_DECODE(c, assi) \
if ((c) >= 0xa1 && (c) <= 0xdf) \
(assi) = 0xfec0 + (c);
#define JISX0201_DECODE(c, assi) \
JISX0201_R_DECODE(c, assi) \
else JISX0201_K_DECODE(c, assi)

View file

@ -13,12 +13,12 @@
/* a unicode "undefined" codepoint */
#define UNIINV 0xFFFE
#define UNIINV 0xFFFE
/* internal-use DBCS codepoints which aren't used by any charsets */
#define NOCHAR 0xFFFF
#define MULTIC 0xFFFE
#define DBCINV 0xFFFD
#define NOCHAR 0xFFFF
#define MULTIC 0xFFFE
#define DBCINV 0xFFFD
/* shorter macros to save source size of mapping tables */
#define U UNIINV
@ -27,94 +27,94 @@
#define D DBCINV
struct dbcs_index {
const ucs2_t *map;
unsigned char bottom, top;
const ucs2_t *map;
unsigned char bottom, top;
};
typedef struct dbcs_index decode_map;
struct widedbcs_index {
const ucs4_t *map;
unsigned char bottom, top;
const ucs4_t *map;
unsigned char bottom, top;
};
typedef struct widedbcs_index widedecode_map;
struct unim_index {
const DBCHAR *map;
unsigned char bottom, top;
const DBCHAR *map;
unsigned char bottom, top;
};
typedef struct unim_index encode_map;
struct unim_index_bytebased {
const unsigned char *map;
unsigned char bottom, top;
const unsigned char *map;
unsigned char bottom, top;
};
struct dbcs_map {
const char *charset;
const struct unim_index *encmap;
const struct dbcs_index *decmap;
const char *charset;
const struct unim_index *encmap;
const struct dbcs_index *decmap;
};
struct pair_encodemap {
ucs4_t uniseq;
DBCHAR code;
ucs4_t uniseq;
DBCHAR code;
};
static const MultibyteCodec *codec_list;
static const struct dbcs_map *mapping_list;
#define CODEC_INIT(encoding) \
static int encoding##_codec_init(const void *config)
#define CODEC_INIT(encoding) \
static int encoding##_codec_init(const void *config)
#define ENCODER_INIT(encoding) \
static int encoding##_encode_init( \
MultibyteCodec_State *state, const void *config)
#define ENCODER(encoding) \
static Py_ssize_t encoding##_encode( \
MultibyteCodec_State *state, const void *config, \
const Py_UNICODE **inbuf, Py_ssize_t inleft, \
unsigned char **outbuf, Py_ssize_t outleft, int flags)
#define ENCODER_RESET(encoding) \
static Py_ssize_t encoding##_encode_reset( \
MultibyteCodec_State *state, const void *config, \
unsigned char **outbuf, Py_ssize_t outleft)
#define ENCODER_INIT(encoding) \
static int encoding##_encode_init( \
MultibyteCodec_State *state, const void *config)
#define ENCODER(encoding) \
static Py_ssize_t encoding##_encode( \
MultibyteCodec_State *state, const void *config, \
const Py_UNICODE **inbuf, Py_ssize_t inleft, \
unsigned char **outbuf, Py_ssize_t outleft, int flags)
#define ENCODER_RESET(encoding) \
static Py_ssize_t encoding##_encode_reset( \
MultibyteCodec_State *state, const void *config, \
unsigned char **outbuf, Py_ssize_t outleft)
#define DECODER_INIT(encoding) \
static int encoding##_decode_init( \
MultibyteCodec_State *state, const void *config)
#define DECODER(encoding) \
static Py_ssize_t encoding##_decode( \
MultibyteCodec_State *state, const void *config, \
const unsigned char **inbuf, Py_ssize_t inleft, \
Py_UNICODE **outbuf, Py_ssize_t outleft)
#define DECODER_RESET(encoding) \
static Py_ssize_t encoding##_decode_reset( \
MultibyteCodec_State *state, const void *config)
#define DECODER_INIT(encoding) \
static int encoding##_decode_init( \
MultibyteCodec_State *state, const void *config)
#define DECODER(encoding) \
static Py_ssize_t encoding##_decode( \
MultibyteCodec_State *state, const void *config, \
const unsigned char **inbuf, Py_ssize_t inleft, \
Py_UNICODE **outbuf, Py_ssize_t outleft)
#define DECODER_RESET(encoding) \
static Py_ssize_t encoding##_decode_reset( \
MultibyteCodec_State *state, const void *config)
#if Py_UNICODE_SIZE == 4
#define UCS4INVALID(code) \
if ((code) > 0xFFFF) \
return 1;
#define UCS4INVALID(code) \
if ((code) > 0xFFFF) \
return 1;
#else
#define UCS4INVALID(code) \
if (0) ;
#define UCS4INVALID(code) \
if (0) ;
#endif
#define NEXT_IN(i) \
(*inbuf) += (i); \
(inleft) -= (i);
#define NEXT_OUT(o) \
(*outbuf) += (o); \
(outleft) -= (o);
#define NEXT(i, o) \
NEXT_IN(i) NEXT_OUT(o)
#define NEXT_IN(i) \
(*inbuf) += (i); \
(inleft) -= (i);
#define NEXT_OUT(o) \
(*outbuf) += (o); \
(outleft) -= (o);
#define NEXT(i, o) \
NEXT_IN(i) NEXT_OUT(o)
#define REQUIRE_INBUF(n) \
if (inleft < (n)) \
return MBERR_TOOFEW;
#define REQUIRE_OUTBUF(n) \
if (outleft < (n)) \
return MBERR_TOOSMALL;
#define REQUIRE_INBUF(n) \
if (inleft < (n)) \
return MBERR_TOOFEW;
#define REQUIRE_OUTBUF(n) \
if (outleft < (n)) \
return MBERR_TOOSMALL;
#define IN1 ((*inbuf)[0])
#define IN2 ((*inbuf)[1])
@ -126,289 +126,289 @@ static const struct dbcs_map *mapping_list;
#define OUT3(c) ((*outbuf)[2]) = (c);
#define OUT4(c) ((*outbuf)[3]) = (c);
#define WRITE1(c1) \
REQUIRE_OUTBUF(1) \
(*outbuf)[0] = (c1);
#define WRITE2(c1, c2) \
REQUIRE_OUTBUF(2) \
(*outbuf)[0] = (c1); \
(*outbuf)[1] = (c2);
#define WRITE3(c1, c2, c3) \
REQUIRE_OUTBUF(3) \
(*outbuf)[0] = (c1); \
(*outbuf)[1] = (c2); \
(*outbuf)[2] = (c3);
#define WRITE4(c1, c2, c3, c4) \
REQUIRE_OUTBUF(4) \
(*outbuf)[0] = (c1); \
(*outbuf)[1] = (c2); \
(*outbuf)[2] = (c3); \
(*outbuf)[3] = (c4);
#define WRITE1(c1) \
REQUIRE_OUTBUF(1) \
(*outbuf)[0] = (c1);
#define WRITE2(c1, c2) \
REQUIRE_OUTBUF(2) \
(*outbuf)[0] = (c1); \
(*outbuf)[1] = (c2);
#define WRITE3(c1, c2, c3) \
REQUIRE_OUTBUF(3) \
(*outbuf)[0] = (c1); \
(*outbuf)[1] = (c2); \
(*outbuf)[2] = (c3);
#define WRITE4(c1, c2, c3, c4) \
REQUIRE_OUTBUF(4) \
(*outbuf)[0] = (c1); \
(*outbuf)[1] = (c2); \
(*outbuf)[2] = (c3); \
(*outbuf)[3] = (c4);
#if Py_UNICODE_SIZE == 2
# define WRITEUCS4(c) \
REQUIRE_OUTBUF(2) \
(*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \
(*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \
NEXT_OUT(2)
# define WRITEUCS4(c) \
REQUIRE_OUTBUF(2) \
(*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \
(*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \
NEXT_OUT(2)
#else
# define WRITEUCS4(c) \
REQUIRE_OUTBUF(1) \
**outbuf = (Py_UNICODE)(c); \
NEXT_OUT(1)
# define WRITEUCS4(c) \
REQUIRE_OUTBUF(1) \
**outbuf = (Py_UNICODE)(c); \
NEXT_OUT(1)
#endif
#define _TRYMAP_ENC(m, assi, val) \
((m)->map != NULL && (val) >= (m)->bottom && \
(val)<= (m)->top && ((assi) = (m)->map[(val) - \
(m)->bottom]) != NOCHAR)
#define TRYMAP_ENC_COND(charset, assi, uni) \
_TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff)
#define TRYMAP_ENC(charset, assi, uni) \
if TRYMAP_ENC_COND(charset, assi, uni)
#define _TRYMAP_ENC(m, assi, val) \
((m)->map != NULL && (val) >= (m)->bottom && \
(val)<= (m)->top && ((assi) = (m)->map[(val) - \
(m)->bottom]) != NOCHAR)
#define TRYMAP_ENC_COND(charset, assi, uni) \
_TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff)
#define TRYMAP_ENC(charset, assi, uni) \
if TRYMAP_ENC_COND(charset, assi, uni)
#define _TRYMAP_DEC(m, assi, val) \
((m)->map != NULL && (val) >= (m)->bottom && \
(val)<= (m)->top && ((assi) = (m)->map[(val) - \
(m)->bottom]) != UNIINV)
#define TRYMAP_DEC(charset, assi, c1, c2) \
if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2)
#define _TRYMAP_DEC(m, assi, val) \
((m)->map != NULL && (val) >= (m)->bottom && \
(val)<= (m)->top && ((assi) = (m)->map[(val) - \
(m)->bottom]) != UNIINV)
#define TRYMAP_DEC(charset, assi, c1, c2) \
if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2)
#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \
((m)->map != NULL && (val) >= (m)->bottom && \
(val)<= (m)->top && \
((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \
(((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \
(((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1))
#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \
if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \
assplane, asshi, asslo, (uni) & 0xff)
#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \
if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2)
#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \
((m)->map != NULL && (val) >= (m)->bottom && \
(val)<= (m)->top && \
((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \
(((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \
(((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1))
#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \
if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \
assplane, asshi, asslo, (uni) & 0xff)
#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \
if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2)
#if Py_UNICODE_SIZE == 2
#define DECODE_SURROGATE(c) \
if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \
REQUIRE_INBUF(2) \
if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \
c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \
((ucs4_t)(IN2) - 0xdc00); \
} \
}
#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1)
#define DECODE_SURROGATE(c) \
if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \
REQUIRE_INBUF(2) \
if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \
c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \
((ucs4_t)(IN2) - 0xdc00); \
} \
}
#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1)
#else
#define DECODE_SURROGATE(c) {;}
#define GET_INSIZE(c) 1
#define GET_INSIZE(c) 1
#endif
#define BEGIN_MAPPINGS_LIST static const struct dbcs_map _mapping_list[] = {
#define MAPPING_ENCONLY(enc) {#enc, (void*)enc##_encmap, NULL},
#define MAPPING_DECONLY(enc) {#enc, NULL, (void*)enc##_decmap},
#define MAPPING_ENCDEC(enc) {#enc, (void*)enc##_encmap, (void*)enc##_decmap},
#define END_MAPPINGS_LIST \
{"", NULL, NULL} }; \
static const struct dbcs_map *mapping_list = \
(const struct dbcs_map *)_mapping_list;
#define END_MAPPINGS_LIST \
{"", NULL, NULL} }; \
static const struct dbcs_map *mapping_list = \
(const struct dbcs_map *)_mapping_list;
#define BEGIN_CODECS_LIST static const MultibyteCodec _codec_list[] = {
#define _STATEFUL_METHODS(enc) \
enc##_encode, \
enc##_encode_init, \
enc##_encode_reset, \
enc##_decode, \
enc##_decode_init, \
enc##_decode_reset,
#define _STATELESS_METHODS(enc) \
enc##_encode, NULL, NULL, \
enc##_decode, NULL, NULL,
#define CODEC_STATEFUL(enc) { \
#enc, NULL, NULL, \
_STATEFUL_METHODS(enc) \
#define _STATEFUL_METHODS(enc) \
enc##_encode, \
enc##_encode_init, \
enc##_encode_reset, \
enc##_decode, \
enc##_decode_init, \
enc##_decode_reset,
#define _STATELESS_METHODS(enc) \
enc##_encode, NULL, NULL, \
enc##_decode, NULL, NULL,
#define CODEC_STATEFUL(enc) { \
#enc, NULL, NULL, \
_STATEFUL_METHODS(enc) \
},
#define CODEC_STATELESS(enc) { \
#enc, NULL, NULL, \
_STATELESS_METHODS(enc) \
#define CODEC_STATELESS(enc) { \
#enc, NULL, NULL, \
_STATELESS_METHODS(enc) \
},
#define CODEC_STATELESS_WINIT(enc) { \
#enc, NULL, \
enc##_codec_init, \
_STATELESS_METHODS(enc) \
#define CODEC_STATELESS_WINIT(enc) { \
#enc, NULL, \
enc##_codec_init, \
_STATELESS_METHODS(enc) \
},
#define END_CODECS_LIST \
{"", NULL,} }; \
static const MultibyteCodec *codec_list = \
(const MultibyteCodec *)_codec_list;
#define END_CODECS_LIST \
{"", NULL,} }; \
static const MultibyteCodec *codec_list = \
(const MultibyteCodec *)_codec_list;
static PyObject *
getmultibytecodec(void)
{
static PyObject *cofunc = NULL;
static PyObject *cofunc = NULL;
if (cofunc == NULL) {
PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec");
if (mod == NULL)
return NULL;
cofunc = PyObject_GetAttrString(mod, "__create_codec");
Py_DECREF(mod);
}
return cofunc;
if (cofunc == NULL) {
PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec");
if (mod == NULL)
return NULL;
cofunc = PyObject_GetAttrString(mod, "__create_codec");
Py_DECREF(mod);
}
return cofunc;
}
static PyObject *
getcodec(PyObject *self, PyObject *encoding)
{
PyObject *codecobj, *r, *cofunc;
const MultibyteCodec *codec;
const char *enc;
PyObject *codecobj, *r, *cofunc;
const MultibyteCodec *codec;
const char *enc;
if (!PyUnicode_Check(encoding)) {
PyErr_SetString(PyExc_TypeError,
"encoding name must be a string.");
return NULL;
}
enc = _PyUnicode_AsString(encoding);
if (enc == NULL)
return NULL;
if (!PyUnicode_Check(encoding)) {
PyErr_SetString(PyExc_TypeError,
"encoding name must be a string.");
return NULL;
}
enc = _PyUnicode_AsString(encoding);
if (enc == NULL)
return NULL;
cofunc = getmultibytecodec();
if (cofunc == NULL)
return NULL;
cofunc = getmultibytecodec();
if (cofunc == NULL)
return NULL;
for (codec = codec_list; codec->encoding[0]; codec++)
if (strcmp(codec->encoding, enc) == 0)
break;
for (codec = codec_list; codec->encoding[0]; codec++)
if (strcmp(codec->encoding, enc) == 0)
break;
if (codec->encoding[0] == '\0') {
PyErr_SetString(PyExc_LookupError,
"no such codec is supported.");
return NULL;
}
if (codec->encoding[0] == '\0') {
PyErr_SetString(PyExc_LookupError,
"no such codec is supported.");
return NULL;
}
codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL);
if (codecobj == NULL)
return NULL;
codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL);
if (codecobj == NULL)
return NULL;
r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL);
Py_DECREF(codecobj);
r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL);
Py_DECREF(codecobj);
return r;
return r;
}
static struct PyMethodDef __methods[] = {
{"getcodec", (PyCFunction)getcodec, METH_O, ""},
{NULL, NULL},
{"getcodec", (PyCFunction)getcodec, METH_O, ""},
{NULL, NULL},
};
static int
register_maps(PyObject *module)
{
const struct dbcs_map *h;
const struct dbcs_map *h;
for (h = mapping_list; h->charset[0] != '\0'; h++) {
char mhname[256] = "__map_";
int r;
strcpy(mhname + sizeof("__map_") - 1, h->charset);
r = PyModule_AddObject(module, mhname,
PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL));
if (r == -1)
return -1;
}
return 0;
for (h = mapping_list; h->charset[0] != '\0'; h++) {
char mhname[256] = "__map_";
int r;
strcpy(mhname + sizeof("__map_") - 1, h->charset);
r = PyModule_AddObject(module, mhname,
PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL));
if (r == -1)
return -1;
}
return 0;
}
#ifdef USING_BINARY_PAIR_SEARCH
static DBCHAR
find_pairencmap(ucs2_t body, ucs2_t modifier,
const struct pair_encodemap *haystack, int haystacksize)
const struct pair_encodemap *haystack, int haystacksize)
{
int pos, min, max;
ucs4_t value = body << 16 | modifier;
int pos, min, max;
ucs4_t value = body << 16 | modifier;
min = 0;
max = haystacksize;
min = 0;
max = haystacksize;
for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1)
if (value < haystack[pos].uniseq) {
if (max == pos) break;
else max = pos;
}
else if (value > haystack[pos].uniseq) {
if (min == pos) break;
else min = pos;
}
else
break;
for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1)
if (value < haystack[pos].uniseq) {
if (max == pos) break;
else max = pos;
}
else if (value > haystack[pos].uniseq) {
if (min == pos) break;
else min = pos;
}
else
break;
if (value == haystack[pos].uniseq)
return haystack[pos].code;
else
return DBCINV;
if (value == haystack[pos].uniseq)
return haystack[pos].code;
else
return DBCINV;
}
#endif
#ifdef USING_IMPORTED_MAPS
#define IMPORT_MAP(locale, charset, encmap, decmap) \
importmap("_codecs_" #locale, "__map_" #charset, \
(const void**)encmap, (const void**)decmap)
importmap("_codecs_" #locale, "__map_" #charset, \
(const void**)encmap, (const void**)decmap)
static int
importmap(const char *modname, const char *symbol,
const void **encmap, const void **decmap)
const void **encmap, const void **decmap)
{
PyObject *o, *mod;
PyObject *o, *mod;
mod = PyImport_ImportModule((char *)modname);
if (mod == NULL)
return -1;
mod = PyImport_ImportModule((char *)modname);
if (mod == NULL)
return -1;
o = PyObject_GetAttrString(mod, (char*)symbol);
if (o == NULL)
goto errorexit;
else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) {
PyErr_SetString(PyExc_ValueError,
"map data must be a Capsule.");
goto errorexit;
}
else {
struct dbcs_map *map;
map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME);
if (encmap != NULL)
*encmap = map->encmap;
if (decmap != NULL)
*decmap = map->decmap;
Py_DECREF(o);
}
o = PyObject_GetAttrString(mod, (char*)symbol);
if (o == NULL)
goto errorexit;
else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) {
PyErr_SetString(PyExc_ValueError,
"map data must be a Capsule.");
goto errorexit;
}
else {
struct dbcs_map *map;
map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME);
if (encmap != NULL)
*encmap = map->encmap;
if (decmap != NULL)
*decmap = map->decmap;
Py_DECREF(o);
}
Py_DECREF(mod);
return 0;
Py_DECREF(mod);
return 0;
errorexit:
Py_DECREF(mod);
return -1;
Py_DECREF(mod);
return -1;
}
#endif
#define I_AM_A_MODULE_FOR(loc) \
static struct PyModuleDef __module = { \
PyModuleDef_HEAD_INIT, \
"_codecs_"#loc, \
NULL, \
0, \
__methods, \
NULL, \
NULL, \
NULL, \
NULL \
}; \
PyObject* \
PyInit__codecs_##loc(void) \
{ \
PyObject *m = PyModule_Create(&__module); \
if (m != NULL) \
(void)register_maps(m); \
return m; \
}
#define I_AM_A_MODULE_FOR(loc) \
static struct PyModuleDef __module = { \
PyModuleDef_HEAD_INIT, \
"_codecs_"#loc, \
NULL, \
0, \
__methods, \
NULL, \
NULL, \
NULL, \
NULL \
}; \
PyObject* \
PyInit__codecs_##loc(void) \
{ \
PyObject *m = PyModule_Create(&__module); \
if (m != NULL) \
(void)register_maps(m); \
return m; \
}
#endif

View file

@ -5,39 +5,39 @@
#define EMULATE_JISX0213_2000_ENCODE_INVALID 1
#endif
#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \
if (config == (void *)2000 && ( \
(c) == 0x9B1C || (c) == 0x4FF1 || \
(c) == 0x525D || (c) == 0x541E || \
(c) == 0x5653 || (c) == 0x59F8 || \
(c) == 0x5C5B || (c) == 0x5E77 || \
(c) == 0x7626 || (c) == 0x7E6B)) \
return EMULATE_JISX0213_2000_ENCODE_INVALID; \
else if (config == (void *)2000 && (c) == 0x9B1D) \
(assi) = 0x8000 | 0x7d3b; \
#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \
if (config == (void *)2000 && ( \
(c) == 0x9B1C || (c) == 0x4FF1 || \
(c) == 0x525D || (c) == 0x541E || \
(c) == 0x5653 || (c) == 0x59F8 || \
(c) == 0x5C5B || (c) == 0x5E77 || \
(c) == 0x7626 || (c) == 0x7E6B)) \
return EMULATE_JISX0213_2000_ENCODE_INVALID; \
else if (config == (void *)2000 && (c) == 0x9B1D) \
(assi) = 0x8000 | 0x7d3b; \
#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \
if (config == (void *)2000 && (c) == 0x20B9F) \
return EMULATE_JISX0213_2000_ENCODE_INVALID;
#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \
if (config == (void *)2000 && (c) == 0x20B9F) \
return EMULATE_JISX0213_2000_ENCODE_INVALID;
#ifndef EMULATE_JISX0213_2000_DECODE_INVALID
#define EMULATE_JISX0213_2000_DECODE_INVALID 2
#endif
#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \
if (config == (void *)2000 && \
(((c1) == 0x2E && (c2) == 0x21) || \
((c1) == 0x2F && (c2) == 0x7E) || \
((c1) == 0x4F && (c2) == 0x54) || \
((c1) == 0x4F && (c2) == 0x7E) || \
((c1) == 0x74 && (c2) == 0x27) || \
((c1) == 0x7E && (c2) == 0x7A) || \
((c1) == 0x7E && (c2) == 0x7B) || \
((c1) == 0x7E && (c2) == 0x7C) || \
((c1) == 0x7E && (c2) == 0x7D) || \
((c1) == 0x7E && (c2) == 0x7E))) \
return EMULATE_JISX0213_2000_DECODE_INVALID;
#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \
if (config == (void *)2000 && \
(((c1) == 0x2E && (c2) == 0x21) || \
((c1) == 0x2F && (c2) == 0x7E) || \
((c1) == 0x4F && (c2) == 0x54) || \
((c1) == 0x4F && (c2) == 0x7E) || \
((c1) == 0x74 && (c2) == 0x27) || \
((c1) == 0x7E && (c2) == 0x7A) || \
((c1) == 0x7E && (c2) == 0x7B) || \
((c1) == 0x7E && (c2) == 0x7C) || \
((c1) == 0x7E && (c2) == 0x7D) || \
((c1) == 0x7E && (c2) == 0x7E))) \
return EMULATE_JISX0213_2000_DECODE_INVALID;
#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \
if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \
(assi) = 0x9B1D;
#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \
if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \
(assi) = 0x9B1D;

File diff suppressed because it is too large Load diff

View file

@ -23,114 +23,114 @@ typedef unsigned short ucs2_t, DBCHAR;
#endif
typedef union {
void *p;
int i;
unsigned char c[8];
ucs2_t u2[4];
ucs4_t u4[2];
void *p;
int i;
unsigned char c[8];
ucs2_t u2[4];
ucs4_t u4[2];
} MultibyteCodec_State;
typedef int (*mbcodec_init)(const void *config);
typedef Py_ssize_t (*mbencode_func)(MultibyteCodec_State *state,
const void *config,
const Py_UNICODE **inbuf, Py_ssize_t inleft,
unsigned char **outbuf, Py_ssize_t outleft,
int flags);
const void *config,
const Py_UNICODE **inbuf, Py_ssize_t inleft,
unsigned char **outbuf, Py_ssize_t outleft,
int flags);
typedef int (*mbencodeinit_func)(MultibyteCodec_State *state,
const void *config);
const void *config);
typedef Py_ssize_t (*mbencodereset_func)(MultibyteCodec_State *state,
const void *config,
unsigned char **outbuf, Py_ssize_t outleft);
const void *config,
unsigned char **outbuf, Py_ssize_t outleft);
typedef Py_ssize_t (*mbdecode_func)(MultibyteCodec_State *state,
const void *config,
const unsigned char **inbuf, Py_ssize_t inleft,
Py_UNICODE **outbuf, Py_ssize_t outleft);
const void *config,
const unsigned char **inbuf, Py_ssize_t inleft,
Py_UNICODE **outbuf, Py_ssize_t outleft);
typedef int (*mbdecodeinit_func)(MultibyteCodec_State *state,
const void *config);
const void *config);
typedef Py_ssize_t (*mbdecodereset_func)(MultibyteCodec_State *state,
const void *config);
const void *config);
typedef struct {
const char *encoding;
const void *config;
mbcodec_init codecinit;
mbencode_func encode;
mbencodeinit_func encinit;
mbencodereset_func encreset;
mbdecode_func decode;
mbdecodeinit_func decinit;
mbdecodereset_func decreset;
const char *encoding;
const void *config;
mbcodec_init codecinit;
mbencode_func encode;
mbencodeinit_func encinit;
mbencodereset_func encreset;
mbdecode_func decode;
mbdecodeinit_func decinit;
mbdecodereset_func decreset;
} MultibyteCodec;
typedef struct {
PyObject_HEAD
MultibyteCodec *codec;
PyObject_HEAD
MultibyteCodec *codec;
} MultibyteCodecObject;
#define MultibyteCodec_Check(op) ((op)->ob_type == &MultibyteCodec_Type)
#define _MultibyteStatefulCodec_HEAD \
PyObject_HEAD \
MultibyteCodec *codec; \
MultibyteCodec_State state; \
PyObject *errors;
#define _MultibyteStatefulCodec_HEAD \
PyObject_HEAD \
MultibyteCodec *codec; \
MultibyteCodec_State state; \
PyObject *errors;
typedef struct {
_MultibyteStatefulCodec_HEAD
_MultibyteStatefulCodec_HEAD
} MultibyteStatefulCodecContext;
#define MAXENCPENDING 2
#define _MultibyteStatefulEncoder_HEAD \
_MultibyteStatefulCodec_HEAD \
Py_UNICODE pending[MAXENCPENDING]; \
Py_ssize_t pendingsize;
#define MAXENCPENDING 2
#define _MultibyteStatefulEncoder_HEAD \
_MultibyteStatefulCodec_HEAD \
Py_UNICODE pending[MAXENCPENDING]; \
Py_ssize_t pendingsize;
typedef struct {
_MultibyteStatefulEncoder_HEAD
_MultibyteStatefulEncoder_HEAD
} MultibyteStatefulEncoderContext;
#define MAXDECPENDING 8
#define _MultibyteStatefulDecoder_HEAD \
_MultibyteStatefulCodec_HEAD \
unsigned char pending[MAXDECPENDING]; \
Py_ssize_t pendingsize;
#define MAXDECPENDING 8
#define _MultibyteStatefulDecoder_HEAD \
_MultibyteStatefulCodec_HEAD \
unsigned char pending[MAXDECPENDING]; \
Py_ssize_t pendingsize;
typedef struct {
_MultibyteStatefulDecoder_HEAD
_MultibyteStatefulDecoder_HEAD
} MultibyteStatefulDecoderContext;
typedef struct {
_MultibyteStatefulEncoder_HEAD
_MultibyteStatefulEncoder_HEAD
} MultibyteIncrementalEncoderObject;
typedef struct {
_MultibyteStatefulDecoder_HEAD
_MultibyteStatefulDecoder_HEAD
} MultibyteIncrementalDecoderObject;
typedef struct {
_MultibyteStatefulDecoder_HEAD
PyObject *stream;
_MultibyteStatefulDecoder_HEAD
PyObject *stream;
} MultibyteStreamReaderObject;
typedef struct {
_MultibyteStatefulEncoder_HEAD
PyObject *stream;
_MultibyteStatefulEncoder_HEAD
PyObject *stream;
} MultibyteStreamWriterObject;
/* positive values for illegal sequences */
#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */
#define MBERR_TOOFEW (-2) /* incomplete input buffer */
#define MBERR_INTERNAL (-3) /* internal runtime error */
#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */
#define MBERR_TOOFEW (-2) /* incomplete input buffer */
#define MBERR_INTERNAL (-3) /* internal runtime error */
#define ERROR_STRICT (PyObject *)(1)
#define ERROR_IGNORE (PyObject *)(2)
#define ERROR_REPLACE (PyObject *)(3)
#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p))
#define ERROR_DECREF(p) do { \
if (p != NULL && ERROR_ISCUSTOM(p)) { \
Py_DECREF(p); \
} \
#define ERROR_STRICT (PyObject *)(1)
#define ERROR_IGNORE (PyObject *)(2)
#define ERROR_REPLACE (PyObject *)(3)
#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p))
#define ERROR_DECREF(p) do { \
if (p != NULL && ERROR_ISCUSTOM(p)) { \
Py_DECREF(p); \
} \
} while (0);
#define MBENC_FLUSH 0x0001 /* encode all characters encodable */
#define MBENC_MAX MBENC_FLUSH
#define MBENC_FLUSH 0x0001 /* encode all characters encodable */
#define MBENC_MAX MBENC_FLUSH
#define PyMultibyteCodec_CAPSULE_NAME "multibytecodec.__map_*"

File diff suppressed because it is too large Load diff

View file

@ -14,17 +14,17 @@
static PyObject *crypt_crypt(PyObject *self, PyObject *args)
{
char *word, *salt;
char *word, *salt;
#ifndef __VMS
extern char * crypt(const char *, const char *);
extern char * crypt(const char *, const char *);
#endif
if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) {
return NULL;
}
/* On some platforms (AtheOS) crypt returns NULL for an invalid
salt. Return None in that case. XXX Maybe raise an exception? */
return Py_BuildValue("s", crypt(word, salt));
if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) {
return NULL;
}
/* On some platforms (AtheOS) crypt returns NULL for an invalid
salt. Return None in that case. XXX Maybe raise an exception? */
return Py_BuildValue("s", crypt(word, salt));
}
@ -38,25 +38,25 @@ the same alphabet as the salt.");
static PyMethodDef crypt_methods[] = {
{"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__},
{NULL, NULL} /* sentinel */
{"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__},
{NULL, NULL} /* sentinel */
};
static struct PyModuleDef cryptmodule = {
PyModuleDef_HEAD_INIT,
"crypt",
NULL,
-1,
crypt_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"crypt",
NULL,
-1,
crypt_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_crypt(void)
{
return PyModule_Create(&cryptmodule);
return PyModule_Create(&cryptmodule);
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -21,7 +21,7 @@ conv_descriptor(PyObject *object, int *target)
int fd = PyObject_AsFileDescriptor(object);
if (fd < 0)
return 0;
return 0;
*target = fd;
return 1;
}
@ -32,48 +32,48 @@ conv_descriptor(PyObject *object, int *target)
static PyObject *
fcntl_fcntl(PyObject *self, PyObject *args)
{
int fd;
int code;
long arg;
int ret;
char *str;
Py_ssize_t len;
char buf[1024];
int fd;
int code;
long arg;
int ret;
char *str;
Py_ssize_t len;
char buf[1024];
if (PyArg_ParseTuple(args, "O&is#:fcntl",
conv_descriptor, &fd, &code, &str, &len)) {
if (len > sizeof buf) {
PyErr_SetString(PyExc_ValueError,
"fcntl string arg too long");
return NULL;
}
memcpy(buf, str, len);
Py_BEGIN_ALLOW_THREADS
ret = fcntl(fd, code, buf);
Py_END_ALLOW_THREADS
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
return PyBytes_FromStringAndSize(buf, len);
}
if (PyArg_ParseTuple(args, "O&is#:fcntl",
conv_descriptor, &fd, &code, &str, &len)) {
if (len > sizeof buf) {
PyErr_SetString(PyExc_ValueError,
"fcntl string arg too long");
return NULL;
}
memcpy(buf, str, len);
Py_BEGIN_ALLOW_THREADS
ret = fcntl(fd, code, buf);
Py_END_ALLOW_THREADS
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
return PyBytes_FromStringAndSize(buf, len);
}
PyErr_Clear();
arg = 0;
if (!PyArg_ParseTuple(args,
"O&i|l;fcntl requires a file or file descriptor,"
" an integer and optionally a third integer or a string",
conv_descriptor, &fd, &code, &arg)) {
return NULL;
}
Py_BEGIN_ALLOW_THREADS
ret = fcntl(fd, code, arg);
Py_END_ALLOW_THREADS
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
return PyLong_FromLong((long)ret);
PyErr_Clear();
arg = 0;
if (!PyArg_ParseTuple(args,
"O&i|l;fcntl requires a file or file descriptor,"
" an integer and optionally a third integer or a string",
conv_descriptor, &fd, &code, &arg)) {
return NULL;
}
Py_BEGIN_ALLOW_THREADS
ret = fcntl(fd, code, arg);
Py_END_ALLOW_THREADS
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
return PyLong_FromLong((long)ret);
}
PyDoc_STRVAR(fcntl_doc,
@ -96,128 +96,128 @@ static PyObject *
fcntl_ioctl(PyObject *self, PyObject *args)
{
#define IOCTL_BUFSZ 1024
int fd;
/* In PyArg_ParseTuple below, we use the unsigned non-checked 'I'
format for the 'code' parameter because Python turns 0x8000000
into either a large positive number (PyLong or PyInt on 64-bit
platforms) or a negative number on others (32-bit PyInt)
whereas the system expects it to be a 32bit bit field value
regardless of it being passed as an int or unsigned long on
various platforms. See the termios.TIOCSWINSZ constant across
platforms for an example of thise.
int fd;
/* In PyArg_ParseTuple below, we use the unsigned non-checked 'I'
format for the 'code' parameter because Python turns 0x8000000
into either a large positive number (PyLong or PyInt on 64-bit
platforms) or a negative number on others (32-bit PyInt)
whereas the system expects it to be a 32bit bit field value
regardless of it being passed as an int or unsigned long on
various platforms. See the termios.TIOCSWINSZ constant across
platforms for an example of thise.
If any of the 64bit platforms ever decide to use more than 32bits
in their unsigned long ioctl codes this will break and need
special casing based on the platform being built on.
*/
unsigned int code;
int arg;
int ret;
Py_buffer pstr;
char *str;
Py_ssize_t len;
int mutate_arg = 1;
char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */
If any of the 64bit platforms ever decide to use more than 32bits
in their unsigned long ioctl codes this will break and need
special casing based on the platform being built on.
*/
unsigned int code;
int arg;
int ret;
Py_buffer pstr;
char *str;
Py_ssize_t len;
int mutate_arg = 1;
char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */
if (PyArg_ParseTuple(args, "O&Iw*|i:ioctl",
conv_descriptor, &fd, &code,
&pstr, &mutate_arg)) {
char *arg;
str = pstr.buf;
len = pstr.len;
if (PyArg_ParseTuple(args, "O&Iw*|i:ioctl",
conv_descriptor, &fd, &code,
&pstr, &mutate_arg)) {
char *arg;
str = pstr.buf;
len = pstr.len;
if (mutate_arg) {
if (len <= IOCTL_BUFSZ) {
memcpy(buf, str, len);
buf[len] = '\0';
arg = buf;
}
else {
arg = str;
}
}
else {
if (len > IOCTL_BUFSZ) {
PyBuffer_Release(&pstr);
PyErr_SetString(PyExc_ValueError,
"ioctl string arg too long");
return NULL;
}
else {
memcpy(buf, str, len);
buf[len] = '\0';
arg = buf;
}
}
if (buf == arg) {
Py_BEGIN_ALLOW_THREADS /* think array.resize() */
ret = ioctl(fd, code, arg);
Py_END_ALLOW_THREADS
}
else {
ret = ioctl(fd, code, arg);
}
if (mutate_arg && (len < IOCTL_BUFSZ)) {
memcpy(str, buf, len);
}
PyBuffer_Release(&pstr); /* No further access to str below this point */
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
if (mutate_arg) {
return PyLong_FromLong(ret);
}
else {
return PyBytes_FromStringAndSize(buf, len);
}
}
if (mutate_arg) {
if (len <= IOCTL_BUFSZ) {
memcpy(buf, str, len);
buf[len] = '\0';
arg = buf;
}
else {
arg = str;
}
}
else {
if (len > IOCTL_BUFSZ) {
PyBuffer_Release(&pstr);
PyErr_SetString(PyExc_ValueError,
"ioctl string arg too long");
return NULL;
}
else {
memcpy(buf, str, len);
buf[len] = '\0';
arg = buf;
}
}
if (buf == arg) {
Py_BEGIN_ALLOW_THREADS /* think array.resize() */
ret = ioctl(fd, code, arg);
Py_END_ALLOW_THREADS
}
else {
ret = ioctl(fd, code, arg);
}
if (mutate_arg && (len < IOCTL_BUFSZ)) {
memcpy(str, buf, len);
}
PyBuffer_Release(&pstr); /* No further access to str below this point */
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
if (mutate_arg) {
return PyLong_FromLong(ret);
}
else {
return PyBytes_FromStringAndSize(buf, len);
}
}
PyErr_Clear();
if (PyArg_ParseTuple(args, "O&Is*:ioctl",
conv_descriptor, &fd, &code, &pstr)) {
str = pstr.buf;
len = pstr.len;
if (len > IOCTL_BUFSZ) {
PyBuffer_Release(&pstr);
PyErr_SetString(PyExc_ValueError,
"ioctl string arg too long");
return NULL;
}
memcpy(buf, str, len);
buf[len] = '\0';
Py_BEGIN_ALLOW_THREADS
ret = ioctl(fd, code, buf);
Py_END_ALLOW_THREADS
if (ret < 0) {
PyBuffer_Release(&pstr);
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
PyBuffer_Release(&pstr);
return PyBytes_FromStringAndSize(buf, len);
}
PyErr_Clear();
if (PyArg_ParseTuple(args, "O&Is*:ioctl",
conv_descriptor, &fd, &code, &pstr)) {
str = pstr.buf;
len = pstr.len;
if (len > IOCTL_BUFSZ) {
PyBuffer_Release(&pstr);
PyErr_SetString(PyExc_ValueError,
"ioctl string arg too long");
return NULL;
}
memcpy(buf, str, len);
buf[len] = '\0';
Py_BEGIN_ALLOW_THREADS
ret = ioctl(fd, code, buf);
Py_END_ALLOW_THREADS
if (ret < 0) {
PyBuffer_Release(&pstr);
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
PyBuffer_Release(&pstr);
return PyBytes_FromStringAndSize(buf, len);
}
PyErr_Clear();
arg = 0;
if (!PyArg_ParseTuple(args,
"O&I|i;ioctl requires a file or file descriptor,"
" an integer and optionally an integer or buffer argument",
conv_descriptor, &fd, &code, &arg)) {
return NULL;
}
Py_BEGIN_ALLOW_THREADS
PyErr_Clear();
arg = 0;
if (!PyArg_ParseTuple(args,
"O&I|i;ioctl requires a file or file descriptor,"
" an integer and optionally an integer or buffer argument",
conv_descriptor, &fd, &code, &arg)) {
return NULL;
}
Py_BEGIN_ALLOW_THREADS
#ifdef __VMS
ret = ioctl(fd, code, (void *)arg);
ret = ioctl(fd, code, (void *)arg);
#else
ret = ioctl(fd, code, arg);
ret = ioctl(fd, code, arg);
#endif
Py_END_ALLOW_THREADS
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
return PyLong_FromLong((long)ret);
Py_END_ALLOW_THREADS
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
return PyLong_FromLong((long)ret);
#undef IOCTL_BUFSZ
}
@ -258,51 +258,51 @@ code.");
static PyObject *
fcntl_flock(PyObject *self, PyObject *args)
{
int fd;
int code;
int ret;
int fd;
int code;
int ret;
if (!PyArg_ParseTuple(args, "O&i:flock",
conv_descriptor, &fd, &code))
return NULL;
if (!PyArg_ParseTuple(args, "O&i:flock",
conv_descriptor, &fd, &code))
return NULL;
#ifdef HAVE_FLOCK
Py_BEGIN_ALLOW_THREADS
ret = flock(fd, code);
Py_END_ALLOW_THREADS
Py_BEGIN_ALLOW_THREADS
ret = flock(fd, code);
Py_END_ALLOW_THREADS
#else
#ifndef LOCK_SH
#define LOCK_SH 1 /* shared lock */
#define LOCK_EX 2 /* exclusive lock */
#define LOCK_NB 4 /* don't block when locking */
#define LOCK_UN 8 /* unlock */
#define LOCK_SH 1 /* shared lock */
#define LOCK_EX 2 /* exclusive lock */
#define LOCK_NB 4 /* don't block when locking */
#define LOCK_UN 8 /* unlock */
#endif
{
struct flock l;
if (code == LOCK_UN)
l.l_type = F_UNLCK;
else if (code & LOCK_SH)
l.l_type = F_RDLCK;
else if (code & LOCK_EX)
l.l_type = F_WRLCK;
else {
PyErr_SetString(PyExc_ValueError,
"unrecognized flock argument");
return NULL;
}
l.l_whence = l.l_start = l.l_len = 0;
Py_BEGIN_ALLOW_THREADS
ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
Py_END_ALLOW_THREADS
}
{
struct flock l;
if (code == LOCK_UN)
l.l_type = F_UNLCK;
else if (code & LOCK_SH)
l.l_type = F_RDLCK;
else if (code & LOCK_EX)
l.l_type = F_WRLCK;
else {
PyErr_SetString(PyExc_ValueError,
"unrecognized flock argument");
return NULL;
}
l.l_whence = l.l_start = l.l_len = 0;
Py_BEGIN_ALLOW_THREADS
ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
Py_END_ALLOW_THREADS
}
#endif /* HAVE_FLOCK */
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(flock_doc,
@ -317,72 +317,72 @@ emulated using fcntl().)");
static PyObject *
fcntl_lockf(PyObject *self, PyObject *args)
{
int fd, code, ret, whence = 0;
PyObject *lenobj = NULL, *startobj = NULL;
int fd, code, ret, whence = 0;
PyObject *lenobj = NULL, *startobj = NULL;
if (!PyArg_ParseTuple(args, "O&i|OOi:lockf",
conv_descriptor, &fd, &code,
&lenobj, &startobj, &whence))
return NULL;
if (!PyArg_ParseTuple(args, "O&i|OOi:lockf",
conv_descriptor, &fd, &code,
&lenobj, &startobj, &whence))
return NULL;
#if defined(PYOS_OS2) && defined(PYCC_GCC)
PyErr_SetString(PyExc_NotImplementedError,
"lockf not supported on OS/2 (EMX)");
return NULL;
PyErr_SetString(PyExc_NotImplementedError,
"lockf not supported on OS/2 (EMX)");
return NULL;
#else
#ifndef LOCK_SH
#define LOCK_SH 1 /* shared lock */
#define LOCK_EX 2 /* exclusive lock */
#define LOCK_NB 4 /* don't block when locking */
#define LOCK_UN 8 /* unlock */
#define LOCK_SH 1 /* shared lock */
#define LOCK_EX 2 /* exclusive lock */
#define LOCK_NB 4 /* don't block when locking */
#define LOCK_UN 8 /* unlock */
#endif /* LOCK_SH */
{
struct flock l;
if (code == LOCK_UN)
l.l_type = F_UNLCK;
else if (code & LOCK_SH)
l.l_type = F_RDLCK;
else if (code & LOCK_EX)
l.l_type = F_WRLCK;
else {
PyErr_SetString(PyExc_ValueError,
"unrecognized lockf argument");
return NULL;
}
l.l_start = l.l_len = 0;
if (startobj != NULL) {
{
struct flock l;
if (code == LOCK_UN)
l.l_type = F_UNLCK;
else if (code & LOCK_SH)
l.l_type = F_RDLCK;
else if (code & LOCK_EX)
l.l_type = F_WRLCK;
else {
PyErr_SetString(PyExc_ValueError,
"unrecognized lockf argument");
return NULL;
}
l.l_start = l.l_len = 0;
if (startobj != NULL) {
#if !defined(HAVE_LARGEFILE_SUPPORT)
l.l_start = PyLong_AsLong(startobj);
l.l_start = PyLong_AsLong(startobj);
#else
l.l_start = PyLong_Check(startobj) ?
PyLong_AsLongLong(startobj) :
PyLong_AsLong(startobj);
l.l_start = PyLong_Check(startobj) ?
PyLong_AsLongLong(startobj) :
PyLong_AsLong(startobj);
#endif
if (PyErr_Occurred())
return NULL;
}
if (lenobj != NULL) {
if (PyErr_Occurred())
return NULL;
}
if (lenobj != NULL) {
#if !defined(HAVE_LARGEFILE_SUPPORT)
l.l_len = PyLong_AsLong(lenobj);
l.l_len = PyLong_AsLong(lenobj);
#else
l.l_len = PyLong_Check(lenobj) ?
PyLong_AsLongLong(lenobj) :
PyLong_AsLong(lenobj);
l.l_len = PyLong_Check(lenobj) ?
PyLong_AsLongLong(lenobj) :
PyLong_AsLong(lenobj);
#endif
if (PyErr_Occurred())
return NULL;
}
l.l_whence = whence;
Py_BEGIN_ALLOW_THREADS
ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
Py_END_ALLOW_THREADS
}
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
if (PyErr_Occurred())
return NULL;
}
l.l_whence = whence;
Py_BEGIN_ALLOW_THREADS
ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
Py_END_ALLOW_THREADS
}
if (ret < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
#endif /* defined(PYOS_OS2) && defined(PYCC_GCC) */
}
@ -414,11 +414,11 @@ starts. whence is as with fileobj.seek(), specifically:\n\
/* List of functions */
static PyMethodDef fcntl_methods[] = {
{"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc},
{"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc},
{"flock", fcntl_flock, METH_VARARGS, flock_doc},
{"lockf", fcntl_lockf, METH_VARARGS, lockf_doc},
{NULL, NULL} /* sentinel */
{"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc},
{"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc},
{"flock", fcntl_flock, METH_VARARGS, flock_doc},
{"lockf", fcntl_lockf, METH_VARARGS, lockf_doc},
{NULL, NULL} /* sentinel */
};
@ -433,12 +433,12 @@ a file or socket object.");
static int
ins(PyObject* d, char* symbol, long value)
{
PyObject* v = PyLong_FromLong(value);
if (!v || PyDict_SetItemString(d, symbol, v) < 0)
return -1;
PyObject* v = PyLong_FromLong(value);
if (!v || PyDict_SetItemString(d, symbol, v) < 0)
return -1;
Py_DECREF(v);
return 0;
Py_DECREF(v);
return 0;
}
#define INS(x) if (ins(d, #x, (long)x)) return -1
@ -446,199 +446,199 @@ ins(PyObject* d, char* symbol, long value)
static int
all_ins(PyObject* d)
{
if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1;
if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1;
if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1;
if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1;
if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1;
if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1;
if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1;
if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1;
/* GNU extensions, as of glibc 2.2.4 */
#ifdef LOCK_MAND
if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1;
if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1;
#endif
#ifdef LOCK_READ
if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1;
if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1;
#endif
#ifdef LOCK_WRITE
if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1;
if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1;
#endif
#ifdef LOCK_RW
if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1;
if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1;
#endif
#ifdef F_DUPFD
if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1;
if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1;
#endif
#ifdef F_GETFD
if (ins(d, "F_GETFD", (long)F_GETFD)) return -1;
if (ins(d, "F_GETFD", (long)F_GETFD)) return -1;
#endif
#ifdef F_SETFD
if (ins(d, "F_SETFD", (long)F_SETFD)) return -1;
if (ins(d, "F_SETFD", (long)F_SETFD)) return -1;
#endif
#ifdef F_GETFL
if (ins(d, "F_GETFL", (long)F_GETFL)) return -1;
if (ins(d, "F_GETFL", (long)F_GETFL)) return -1;
#endif
#ifdef F_SETFL
if (ins(d, "F_SETFL", (long)F_SETFL)) return -1;
if (ins(d, "F_SETFL", (long)F_SETFL)) return -1;
#endif
#ifdef F_GETLK
if (ins(d, "F_GETLK", (long)F_GETLK)) return -1;
if (ins(d, "F_GETLK", (long)F_GETLK)) return -1;
#endif
#ifdef F_SETLK
if (ins(d, "F_SETLK", (long)F_SETLK)) return -1;
if (ins(d, "F_SETLK", (long)F_SETLK)) return -1;
#endif
#ifdef F_SETLKW
if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1;
if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1;
#endif
#ifdef F_GETOWN
if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1;
if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1;
#endif
#ifdef F_SETOWN
if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1;
if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1;
#endif
#ifdef F_GETSIG
if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1;
if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1;
#endif
#ifdef F_SETSIG
if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1;
if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1;
#endif
#ifdef F_RDLCK
if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1;
if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1;
#endif
#ifdef F_WRLCK
if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1;
if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1;
#endif
#ifdef F_UNLCK
if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1;
if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1;
#endif
/* LFS constants */
#ifdef F_GETLK64
if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1;
if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1;
#endif
#ifdef F_SETLK64
if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1;
if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1;
#endif
#ifdef F_SETLKW64
if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1;
if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1;
#endif
/* GNU extensions, as of glibc 2.2.4. */
#ifdef FASYNC
if (ins(d, "FASYNC", (long)FASYNC)) return -1;
if (ins(d, "FASYNC", (long)FASYNC)) return -1;
#endif
#ifdef F_SETLEASE
if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1;
if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1;
#endif
#ifdef F_GETLEASE
if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1;
if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1;
#endif
#ifdef F_NOTIFY
if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1;
if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1;
#endif
/* Old BSD flock(). */
#ifdef F_EXLCK
if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1;
if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1;
#endif
#ifdef F_SHLCK
if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1;
if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1;
#endif
/* OS X (and maybe others) let you tell the storage device to flush to physical media */
#ifdef F_FULLFSYNC
if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1;
if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1;
#endif
/* For F_{GET|SET}FL */
#ifdef FD_CLOEXEC
if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1;
if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1;
#endif
/* For F_NOTIFY */
#ifdef DN_ACCESS
if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1;
if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1;
#endif
#ifdef DN_MODIFY
if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1;
if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1;
#endif
#ifdef DN_CREATE
if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1;
if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1;
#endif
#ifdef DN_DELETE
if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1;
if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1;
#endif
#ifdef DN_RENAME
if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1;
if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1;
#endif
#ifdef DN_ATTRIB
if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1;
if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1;
#endif
#ifdef DN_MULTISHOT
if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1;
if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1;
#endif
#ifdef HAVE_STROPTS_H
/* Unix 98 guarantees that these are in stropts.h. */
INS(I_PUSH);
INS(I_POP);
INS(I_LOOK);
INS(I_FLUSH);
INS(I_FLUSHBAND);
INS(I_SETSIG);
INS(I_GETSIG);
INS(I_FIND);
INS(I_PEEK);
INS(I_SRDOPT);
INS(I_GRDOPT);
INS(I_NREAD);
INS(I_FDINSERT);
INS(I_STR);
INS(I_SWROPT);
/* Unix 98 guarantees that these are in stropts.h. */
INS(I_PUSH);
INS(I_POP);
INS(I_LOOK);
INS(I_FLUSH);
INS(I_FLUSHBAND);
INS(I_SETSIG);
INS(I_GETSIG);
INS(I_FIND);
INS(I_PEEK);
INS(I_SRDOPT);
INS(I_GRDOPT);
INS(I_NREAD);
INS(I_FDINSERT);
INS(I_STR);
INS(I_SWROPT);
#ifdef I_GWROPT
/* despite the comment above, old-ish glibcs miss a couple... */
INS(I_GWROPT);
/* despite the comment above, old-ish glibcs miss a couple... */
INS(I_GWROPT);
#endif
INS(I_SENDFD);
INS(I_RECVFD);
INS(I_LIST);
INS(I_ATMARK);
INS(I_CKBAND);
INS(I_GETBAND);
INS(I_CANPUT);
INS(I_SETCLTIME);
INS(I_SENDFD);
INS(I_RECVFD);
INS(I_LIST);
INS(I_ATMARK);
INS(I_CKBAND);
INS(I_GETBAND);
INS(I_CANPUT);
INS(I_SETCLTIME);
#ifdef I_GETCLTIME
INS(I_GETCLTIME);
INS(I_GETCLTIME);
#endif
INS(I_LINK);
INS(I_UNLINK);
INS(I_PLINK);
INS(I_PUNLINK);
INS(I_LINK);
INS(I_UNLINK);
INS(I_PLINK);
INS(I_PUNLINK);
#endif
return 0;
return 0;
}
static struct PyModuleDef fcntlmodule = {
PyModuleDef_HEAD_INIT,
"fcntl",
module_doc,
-1,
fcntl_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"fcntl",
module_doc,
-1,
fcntl_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_fcntl(void)
{
PyObject *m, *d;
PyObject *m, *d;
/* Create the module and add the functions and documentation */
m = PyModule_Create(&fcntlmodule);
if (m == NULL)
return NULL;
/* Create the module and add the functions and documentation */
m = PyModule_Create(&fcntlmodule);
if (m == NULL)
return NULL;
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
all_ins(d);
return m;
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
all_ins(d);
return m;
}

View file

@ -1,6 +1,6 @@
/*
---------------------------------------------------------------------
/ Copyright (c) 1996. \
---------------------------------------------------------------------
/ Copyright (c) 1996. \
| The Regents of the University of California. |
| All rights reserved. |
| |
@ -32,12 +32,12 @@
| opinions of authors expressed herein do not necessarily state or |
| reflect those of the United States Government or the University |
| of California, and shall not be used for advertising or product |
\ endorsement purposes. /
---------------------------------------------------------------------
\ endorsement purposes. /
---------------------------------------------------------------------
*/
/*
Floating point exception control module.
Floating point exception control module.
This Python module provides bare-bones control over floating point
units from several hardware manufacturers. Specifically, it allows
@ -96,8 +96,8 @@ static PyObject *turnon_sigfpe (PyObject *self,PyObject *args);
static PyObject *turnoff_sigfpe (PyObject *self,PyObject *args);
static PyMethodDef fpectl_methods[] = {
{"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS},
{"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS},
{"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS},
{"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS},
{0,0}
};
@ -122,19 +122,19 @@ static void fpe_reset(Sigfunc *handler)
* My usage doesn't follow the man page exactly. Maybe somebody
* else can explain handle_sigfpes to me....
* cc -c -I/usr/local/python/include fpectlmodule.c
* ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe
* ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe
*/
#include <sigfpe.h>
typedef void user_routine (unsigned[5], int[2]);
typedef void abort_routine (unsigned long);
handle_sigfpes(_OFF, 0,
(user_routine *)0,
_TURN_OFF_HANDLER_ON_ERROR,
NULL);
(user_routine *)0,
_TURN_OFF_HANDLER_ON_ERROR,
NULL);
handle_sigfpes(_ON, _EN_OVERFL | _EN_DIVZERO | _EN_INVALID,
(user_routine *)0,
_ABORT_ON_ERROR,
NULL);
(user_routine *)0,
_ABORT_ON_ERROR,
NULL);
PyOS_setsig(SIGFPE, handler);
/*-- SunOS and Solaris ----------------------------------------------------*/
@ -195,16 +195,16 @@ static void fpe_reset(Sigfunc *handler)
/*-- DEC ALPHA VMS --------------------------------------------------------*/
#elif defined(__ALPHA) && defined(__VMS)
IEEE clrmsk;
IEEE setmsk;
clrmsk.ieee$q_flags =
IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
IEEE$M_MAP_UMZ;
setmsk.ieee$q_flags =
IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE |
IEEE$M_TRAP_ENABLE_OVF;
sys$ieee_set_fp_control(&clrmsk, &setmsk, 0);
PyOS_setsig(SIGFPE, handler);
IEEE clrmsk;
IEEE setmsk;
clrmsk.ieee$q_flags =
IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
IEEE$M_MAP_UMZ;
setmsk.ieee$q_flags =
IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE |
IEEE$M_TRAP_ENABLE_OVF;
sys$ieee_set_fp_control(&clrmsk, &setmsk, 0);
PyOS_setsig(SIGFPE, handler);
/*-- HP IA64 VMS --------------------------------------------------------*/
#elif defined(__ia64) && defined(__VMS)
@ -263,13 +263,13 @@ static PyObject *turnoff_sigfpe(PyObject *self,PyObject *args)
fpresetsticky(fpgetsticky());
fpsetmask(0);
#elif defined(__VMS)
IEEE clrmsk;
clrmsk.ieee$q_flags =
IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV |
IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF |
IEEE$M_INHERIT;
sys$ieee_set_fp_control(&clrmsk, 0, 0);
IEEE clrmsk;
clrmsk.ieee$q_flags =
IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV |
IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF |
IEEE$M_INHERIT;
sys$ieee_set_fp_control(&clrmsk, 0, 0);
#else
fputs("Operation not implemented\n", stderr);
#endif
@ -288,15 +288,15 @@ static void sigfpe_handler(int signo)
}
static struct PyModuleDef fpectlmodule = {
PyModuleDef_HEAD_INIT,
"fpectl",
NULL,
-1,
fpectl_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"fpectl",
NULL,
-1,
fpectl_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_fpectl(void)
@ -304,11 +304,11 @@ PyMODINIT_FUNC PyInit_fpectl(void)
PyObject *m, *d;
m = PyModule_Create(&fpectlmodule);
if (m == NULL)
return NULL;
return NULL;
d = PyModule_GetDict(m);
fpe_error = PyErr_NewException("fpectl.error", NULL, NULL);
if (fpe_error != NULL)
PyDict_SetItemString(d, "error", fpe_error);
PyDict_SetItemString(d, "error", fpe_error);
return m;
}

View file

@ -1,6 +1,6 @@
/*
---------------------------------------------------------------------
/ Copyright (c) 1996. \
---------------------------------------------------------------------
/ Copyright (c) 1996. \
| The Regents of the University of California. |
| All rights reserved. |
| |
@ -32,12 +32,12 @@
| opinions of authors expressed herein do not necessarily state or |
| reflect those of the United States Government or the University |
| of California, and shall not be used for advertising or product |
\ endorsement purposes. /
---------------------------------------------------------------------
\ endorsement purposes. /
---------------------------------------------------------------------
*/
/*
Floating point exception test module.
Floating point exception test module.
*/
@ -55,7 +55,7 @@ static double nest3(double);
static void printerr(double);
static PyMethodDef fpetest_methods[] = {
{"test", (PyCFunction) test, METH_VARARGS},
{"test", (PyCFunction) test, METH_VARARGS},
{0,0}
};
@ -174,15 +174,15 @@ static double overflow(double b)
}
static struct PyModuleDef fpetestmodule = {
PyModuleDef_HEAD_INIT,
"fpetest",
NULL,
-1,
fpetest_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"fpetest",
NULL,
-1,
fpetest_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_fpetest(void)
@ -191,10 +191,10 @@ PyMODINIT_FUNC PyInit_fpetest(void)
m = PyModule_Create(&fpetestmodule);
if (m == NULL)
return NULL;
return NULL;
d = PyModule_GetDict(m);
fpe_error = PyErr_NewException("fpetest.error", NULL, NULL);
if (fpe_error != NULL)
PyDict_SetItemString(d, "error", fpe_error);
PyDict_SetItemString(d, "error", fpe_error);
return m;
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -31,22 +31,22 @@
const char *
Py_GetBuildInfo(void)
{
static char buildinfo[50];
const char *revision = Py_SubversionRevision();
const char *sep = *revision ? ":" : "";
const char *branch = Py_SubversionShortBranch();
PyOS_snprintf(buildinfo, sizeof(buildinfo),
"%s%s%s, %.20s, %.9s", branch, sep, revision,
DATE, TIME);
return buildinfo;
static char buildinfo[50];
const char *revision = Py_SubversionRevision();
const char *sep = *revision ? ":" : "";
const char *branch = Py_SubversionShortBranch();
PyOS_snprintf(buildinfo, sizeof(buildinfo),
"%s%s%s, %.20s, %.9s", branch, sep, revision,
DATE, TIME);
return buildinfo;
}
const char *
_Py_svnversion(void)
{
/* the following string can be modified by subwcrev.exe */
static const char svnversion[] = SVNVERSION;
if (svnversion[0] != '$')
return svnversion; /* it was interpolated, or passed on command line */
return "Unversioned directory";
/* the following string can be modified by subwcrev.exe */
static const char svnversion[] = SVNVERSION;
if (svnversion[0] != '$')
return svnversion; /* it was interpolated, or passed on command line */
return "Unversioned directory";
}

View file

@ -1,7 +1,7 @@
/*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
@ -13,7 +13,7 @@
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
@ -53,162 +53,162 @@
#define NO 0
static struct gni_afd {
int a_af;
int a_addrlen;
int a_socklen;
int a_off;
int a_af;
int a_addrlen;
int a_socklen;
int a_off;
} gni_afdl [] = {
#ifdef ENABLE_IPV6
{PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6),
offsetof(struct sockaddr_in6, sin6_addr)},
{PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6),
offsetof(struct sockaddr_in6, sin6_addr)},
#endif
{PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in),
offsetof(struct sockaddr_in, sin_addr)},
{0, 0, 0},
{PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in),
offsetof(struct sockaddr_in, sin_addr)},
{0, 0, 0},
};
struct gni_sockinet {
u_char si_len;
u_char si_family;
u_short si_port;
u_char si_len;
u_char si_family;
u_short si_port;
};
#define ENI_NOSOCKET 0
#define ENI_NOSERVNAME 1
#define ENI_NOHOSTNAME 2
#define ENI_MEMORY 3
#define ENI_SYSTEM 4
#define ENI_FAMILY 5
#define ENI_SALEN 6
#define ENI_NOSOCKET 0
#define ENI_NOSERVNAME 1
#define ENI_NOHOSTNAME 2
#define ENI_MEMORY 3
#define ENI_SYSTEM 4
#define ENI_FAMILY 5
#define ENI_SALEN 6
/* forward declaration to make gcc happy */
int getnameinfo(const struct sockaddr *, size_t, char *, size_t,
char *, size_t, int);
char *, size_t, int);
int
getnameinfo(sa, salen, host, hostlen, serv, servlen, flags)
const struct sockaddr *sa;
size_t salen;
char *host;
size_t hostlen;
char *serv;
size_t servlen;
int flags;
const struct sockaddr *sa;
size_t salen;
char *host;
size_t hostlen;
char *serv;
size_t servlen;
int flags;
{
struct gni_afd *gni_afd;
struct servent *sp;
struct hostent *hp;
u_short port;
int family, len, i;
char *addr, *p;
u_long v4a;
struct gni_afd *gni_afd;
struct servent *sp;
struct hostent *hp;
u_short port;
int family, len, i;
char *addr, *p;
u_long v4a;
#ifdef ENABLE_IPV6
u_char pfx;
u_char pfx;
#endif
int h_error;
char numserv[512];
char numaddr[512];
int h_error;
char numserv[512];
char numaddr[512];
if (sa == NULL)
return ENI_NOSOCKET;
if (sa == NULL)
return ENI_NOSOCKET;
#ifdef HAVE_SOCKADDR_SA_LEN
len = sa->sa_len;
if (len != salen) return ENI_SALEN;
len = sa->sa_len;
if (len != salen) return ENI_SALEN;
#else
len = salen;
len = salen;
#endif
family = sa->sa_family;
for (i = 0; gni_afdl[i].a_af; i++)
if (gni_afdl[i].a_af == family) {
gni_afd = &gni_afdl[i];
goto found;
}
return ENI_FAMILY;
family = sa->sa_family;
for (i = 0; gni_afdl[i].a_af; i++)
if (gni_afdl[i].a_af == family) {
gni_afd = &gni_afdl[i];
goto found;
}
return ENI_FAMILY;
found:
if (len != gni_afd->a_socklen) return ENI_SALEN;
port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */
addr = (char *)sa + gni_afd->a_off;
if (len != gni_afd->a_socklen) return ENI_SALEN;
if (serv == NULL || servlen == 0) {
/* what we should do? */
} else if (flags & NI_NUMERICSERV) {
sprintf(numserv, "%d", ntohs(port));
if (strlen(numserv) > servlen)
return ENI_MEMORY;
strcpy(serv, numserv);
} else {
sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp");
if (sp) {
if (strlen(sp->s_name) > servlen)
return ENI_MEMORY;
strcpy(serv, sp->s_name);
} else
return ENI_NOSERVNAME;
}
port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */
addr = (char *)sa + gni_afd->a_off;
switch (sa->sa_family) {
case AF_INET:
v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr;
if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
flags |= NI_NUMERICHOST;
v4a >>= IN_CLASSA_NSHIFT;
if (v4a == 0 || v4a == IN_LOOPBACKNET)
flags |= NI_NUMERICHOST;
break;
if (serv == NULL || servlen == 0) {
/* what we should do? */
} else if (flags & NI_NUMERICSERV) {
sprintf(numserv, "%d", ntohs(port));
if (strlen(numserv) > servlen)
return ENI_MEMORY;
strcpy(serv, numserv);
} else {
sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp");
if (sp) {
if (strlen(sp->s_name) > servlen)
return ENI_MEMORY;
strcpy(serv, sp->s_name);
} else
return ENI_NOSERVNAME;
}
switch (sa->sa_family) {
case AF_INET:
v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr;
if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
flags |= NI_NUMERICHOST;
v4a >>= IN_CLASSA_NSHIFT;
if (v4a == 0 || v4a == IN_LOOPBACKNET)
flags |= NI_NUMERICHOST;
break;
#ifdef ENABLE_IPV6
case AF_INET6:
pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0];
if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
flags |= NI_NUMERICHOST;
break;
case AF_INET6:
pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0];
if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
flags |= NI_NUMERICHOST;
break;
#endif
}
if (host == NULL || hostlen == 0) {
/* what should we do? */
} else if (flags & NI_NUMERICHOST) {
if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
== NULL)
return ENI_SYSTEM;
if (strlen(numaddr) > hostlen)
return ENI_MEMORY;
strcpy(host, numaddr);
} else {
}
if (host == NULL || hostlen == 0) {
/* what should we do? */
} else if (flags & NI_NUMERICHOST) {
if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
== NULL)
return ENI_SYSTEM;
if (strlen(numaddr) > hostlen)
return ENI_MEMORY;
strcpy(host, numaddr);
} else {
#ifdef ENABLE_IPV6
hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error);
hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error);
#else
hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af);
h_error = h_errno;
hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af);
h_error = h_errno;
#endif
if (hp) {
if (flags & NI_NOFQDN) {
p = strchr(hp->h_name, '.');
if (p) *p = '\0';
}
if (strlen(hp->h_name) > hostlen) {
if (hp) {
if (flags & NI_NOFQDN) {
p = strchr(hp->h_name, '.');
if (p) *p = '\0';
}
if (strlen(hp->h_name) > hostlen) {
#ifdef ENABLE_IPV6
freehostent(hp);
freehostent(hp);
#endif
return ENI_MEMORY;
}
strcpy(host, hp->h_name);
return ENI_MEMORY;
}
strcpy(host, hp->h_name);
#ifdef ENABLE_IPV6
freehostent(hp);
freehostent(hp);
#endif
} else {
if (flags & NI_NAMEREQD)
return ENI_NOHOSTNAME;
if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
== NULL)
return ENI_NOHOSTNAME;
if (strlen(numaddr) > hostlen)
return ENI_MEMORY;
strcpy(host, numaddr);
}
}
return SUCCESS;
} else {
if (flags & NI_NAMEREQD)
return ENI_NOHOSTNAME;
if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
== NULL)
return ENI_NOHOSTNAME;
if (strlen(numaddr) > hostlen)
return ENI_MEMORY;
strcpy(host, numaddr);
}
}
return SUCCESS;
}

View file

@ -142,8 +142,8 @@ _wstat(const wchar_t* path, struct stat *buf)
char fname[PATH_MAX];
size_t res = wcstombs(fname, path, sizeof(fname));
if (res == (size_t)-1) {
errno = EINVAL;
return -1;
errno = EINVAL;
return -1;
}
return stat(fname, buf);
}
@ -155,17 +155,17 @@ _wgetcwd(wchar_t *buf, size_t size)
{
char fname[PATH_MAX];
if (getcwd(fname, PATH_MAX) == NULL)
return NULL;
return NULL;
if (mbstowcs(buf, fname, size) >= size) {
errno = ERANGE;
return NULL;
errno = ERANGE;
return NULL;
}
return buf;
}
#endif
#ifdef HAVE_READLINK
int
int
_Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz)
{
char cbuf[PATH_MAX];
@ -173,24 +173,24 @@ _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t bufsiz)
int res;
size_t r1 = wcstombs(cpath, path, PATH_MAX);
if (r1 == (size_t)-1 || r1 >= PATH_MAX) {
errno = EINVAL;
return -1;
errno = EINVAL;
return -1;
}
res = (int)readlink(cpath, cbuf, PATH_MAX);
if (res == -1)
return -1;
return -1;
if (res == PATH_MAX) {
errno = EINVAL;
return -1;
errno = EINVAL;
return -1;
}
cbuf[res] = '\0'; /* buf will be null terminated */
r1 = mbstowcs(buf, cbuf, bufsiz);
if (r1 == -1) {
errno = EINVAL;
return -1;
errno = EINVAL;
return -1;
}
return (int)r1;
}
#endif
@ -279,7 +279,7 @@ joinpath(wchar_t *buffer, wchar_t *stuff)
buffer[n++] = SEP;
}
if (n > MAXPATHLEN)
Py_FatalError("buffer overflow in getpath.c's joinpath()");
Py_FatalError("buffer overflow in getpath.c's joinpath()");
k = wcslen(stuff);
if (n + k > MAXPATHLEN)
k = MAXPATHLEN - n;
@ -457,25 +457,25 @@ calculate_path(void)
#else
unsigned long nsexeclength = MAXPATHLEN;
#endif
char execpath[MAXPATHLEN+1];
char execpath[MAXPATHLEN+1];
#endif
if (_path) {
size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1);
path = wpath;
if (r == (size_t)-1 || r > MAXPATHLEN) {
/* Could not convert PATH, or it's too long. */
path = NULL;
}
size_t r = mbstowcs(wpath, _path, MAXPATHLEN+1);
path = wpath;
if (r == (size_t)-1 || r > MAXPATHLEN) {
/* Could not convert PATH, or it's too long. */
path = NULL;
}
}
/* If there is no slash in the argv0 path, then we have to
* assume python is on the user's $PATH, since there's no
* other way to find a directory to start the search from. If
* $PATH isn't exported, you lose.
*/
if (wcschr(prog, SEP))
wcsncpy(progpath, prog, MAXPATHLEN);
/* If there is no slash in the argv0 path, then we have to
* assume python is on the user's $PATH, since there's no
* other way to find a directory to start the search from. If
* $PATH isn't exported, you lose.
*/
if (wcschr(prog, SEP))
wcsncpy(progpath, prog, MAXPATHLEN);
#ifdef __APPLE__
/* On Mac OS X, if a script uses an interpreter of the form
* "#!/opt/python2.3/bin/python", the kernel only passes "python"
@ -487,52 +487,52 @@ calculate_path(void)
* will fail if a relative path was used. but in that case,
* absolutize() should help us out below
*/
else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) {
size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1);
if (r == (size_t)-1 || r > MAXPATHLEN) {
/* Could not convert execpath, or it's too long. */
progpath[0] = '\0';
}
}
else if(0 == _NSGetExecutablePath(execpath, &nsexeclength) && execpath[0] == SEP) {
size_t r = mbstowcs(progpath, execpath, MAXPATHLEN+1);
if (r == (size_t)-1 || r > MAXPATHLEN) {
/* Could not convert execpath, or it's too long. */
progpath[0] = '\0';
}
}
#endif /* __APPLE__ */
else if (path) {
while (1) {
wchar_t *delim = wcschr(path, DELIM);
else if (path) {
while (1) {
wchar_t *delim = wcschr(path, DELIM);
if (delim) {
size_t len = delim - path;
if (len > MAXPATHLEN)
len = MAXPATHLEN;
wcsncpy(progpath, path, len);
*(progpath + len) = '\0';
}
else
wcsncpy(progpath, path, MAXPATHLEN);
if (delim) {
size_t len = delim - path;
if (len > MAXPATHLEN)
len = MAXPATHLEN;
wcsncpy(progpath, path, len);
*(progpath + len) = '\0';
}
else
wcsncpy(progpath, path, MAXPATHLEN);
joinpath(progpath, prog);
if (isxfile(progpath))
break;
joinpath(progpath, prog);
if (isxfile(progpath))
break;
if (!delim) {
progpath[0] = L'\0';
break;
}
path = delim + 1;
}
}
else
progpath[0] = '\0';
if (progpath[0] != SEP && progpath[0] != '\0')
absolutize(progpath);
wcsncpy(argv0_path, progpath, MAXPATHLEN);
argv0_path[MAXPATHLEN] = '\0';
if (!delim) {
progpath[0] = L'\0';
break;
}
path = delim + 1;
}
}
else
progpath[0] = '\0';
if (progpath[0] != SEP && progpath[0] != '\0')
absolutize(progpath);
wcsncpy(argv0_path, progpath, MAXPATHLEN);
argv0_path[MAXPATHLEN] = '\0';
#ifdef WITH_NEXT_FRAMEWORK
/* On Mac OS X we have a special case if we're running from a framework.
** This is because the python home should be set relative to the library,
** which is in the framework, not relative to the executable, which may
** be outside of the framework. Except when we're in the build directory...
*/
/* On Mac OS X we have a special case if we're running from a framework.
** This is because the python home should be set relative to the library,
** which is in the framework, not relative to the executable, which may
** be outside of the framework. Except when we're in the build directory...
*/
pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize"));
/* Use dylib functions to find out where the framework was loaded from */
buf = (wchar_t *)NSLibraryNameForModule(pythonModule);
@ -604,7 +604,7 @@ calculate_path(void)
else
wcsncpy(zip_path, L"" PREFIX, MAXPATHLEN);
joinpath(zip_path, L"lib/python00.zip");
bufsz = wcslen(zip_path); /* Replace "00" with version */
bufsz = wcslen(zip_path); /* Replace "00" with version */
zip_path[bufsz - 6] = VERSION[0];
zip_path[bufsz - 5] = VERSION[2];
@ -626,12 +626,12 @@ calculate_path(void)
bufsz = 0;
if (_rtpypath) {
size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t));
if (s == (size_t)-1 || s >=sizeof(rtpypath))
/* XXX deal with errors more gracefully */
_rtpypath = NULL;
if (_rtpypath)
bufsz += wcslen(rtpypath) + 1;
size_t s = mbstowcs(rtpypath, _rtpypath, sizeof(rtpypath)/sizeof(wchar_t));
if (s == (size_t)-1 || s >=sizeof(rtpypath))
/* XXX deal with errors more gracefully */
_rtpypath = NULL;
if (_rtpypath)
bufsz += wcslen(rtpypath) + 1;
}
prefixsz = wcslen(prefix) + 1;
@ -718,10 +718,10 @@ calculate_path(void)
if (pfound > 0) {
reduce(prefix);
reduce(prefix);
/* The prefix is the root directory, but reduce() chopped
* off the "/". */
if (!prefix[0])
wcscpy(prefix, separator);
/* The prefix is the root directory, but reduce() chopped
* off the "/". */
if (!prefix[0])
wcscpy(prefix, separator);
}
else
wcsncpy(prefix, L"" PREFIX, MAXPATHLEN);
@ -730,8 +730,8 @@ calculate_path(void)
reduce(exec_prefix);
reduce(exec_prefix);
reduce(exec_prefix);
if (!exec_prefix[0])
wcscpy(exec_prefix, separator);
if (!exec_prefix[0])
wcscpy(exec_prefix, separator);
}
else
wcsncpy(exec_prefix, L"" EXEC_PREFIX, MAXPATHLEN);

View file

@ -10,8 +10,8 @@
static PyStructSequence_Field struct_group_type_fields[] = {
{"gr_name", "group name"},
{"gr_passwd", "password"},
{"gr_gid", "group id"},
{"gr_mem", "group memebers"},
{"gr_gid", "group id"},
{"gr_mem", "group memebers"},
{0}
};
@ -64,10 +64,10 @@ mkgrent(struct group *p)
Py_INCREF(Py_None);
#else
if (p->gr_passwd)
SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_passwd));
SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_passwd));
else {
SET(setIndex++, Py_None);
Py_INCREF(Py_None);
SET(setIndex++, Py_None);
Py_INCREF(Py_None);
}
#endif
SET(setIndex++, PyLong_FromLong((long) p->gr_gid));
@ -91,12 +91,12 @@ grp_getgrgid(PyObject *self, PyObject *pyo_id)
py_int_id = PyNumber_Long(pyo_id);
if (!py_int_id)
return NULL;
return NULL;
gid = PyLong_AS_LONG(py_int_id);
Py_DECREF(py_int_id);
if ((p = getgrgid(gid)) == NULL) {
PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %d", gid);
PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %d", gid);
return NULL;
}
return mkgrent(p);
@ -116,9 +116,9 @@ grp_getgrnam(PyObject *self, PyObject *args)
return NULL;
if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1)
goto out;
if ((p = getgrnam(name)) == NULL) {
PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name);
PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name);
goto out;
}
retval = mkgrent(p);
@ -151,18 +151,18 @@ grp_getgrall(PyObject *self, PyObject *ignore)
}
static PyMethodDef grp_methods[] = {
{"getgrgid", grp_getgrgid, METH_O,
{"getgrgid", grp_getgrgid, METH_O,
"getgrgid(id) -> tuple\n\
Return the group database entry for the given numeric group ID. If\n\
id is not valid, raise KeyError."},
{"getgrnam", grp_getgrnam, METH_VARARGS,
{"getgrnam", grp_getgrnam, METH_VARARGS,
"getgrnam(name) -> tuple\n\
Return the group database entry for the given group name. If\n\
name is not valid, raise KeyError."},
{"getgrall", grp_getgrall, METH_NOARGS,
{"getgrall", grp_getgrall, METH_NOARGS,
"getgrall() -> list of tuples\n\
Return a list of all available group entries, in arbitrary order."},
{NULL, NULL} /* sentinel */
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(grp__doc__,
@ -184,15 +184,15 @@ complete membership information.)");
static struct PyModuleDef grpmodule = {
PyModuleDef_HEAD_INIT,
"grp",
grp__doc__,
-1,
grp_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"grp",
grp__doc__,
-1,
grp_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
@ -204,7 +204,7 @@ PyInit_grp(void)
return NULL;
d = PyModule_GetDict(m);
if (!initialized)
PyStructSequence_InitType(&StructGrpType, &struct_group_type_desc);
PyStructSequence_InitType(&StructGrpType, &struct_group_type_desc);
PyDict_SetItemString(d, "struct_group", (PyObject *) &StructGrpType);
initialized = 1;
return m;

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -23,8 +23,8 @@
/* Some useful types */
#if SIZEOF_INT == 4
typedef unsigned int MD5_INT32; /* 32-bit integer */
typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */
typedef unsigned int MD5_INT32; /* 32-bit integer */
typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */
#else
/* not defined. compilation will die. */
#endif
@ -127,7 +127,7 @@ static void md5_compress(struct md5_state *md5, unsigned char *buf)
for (i = 0; i < 16; i++) {
LOAD32L(W[i], buf + (4*i));
}
/* copy state */
a = md5->state[0];
b = md5->state[1];
@ -386,21 +386,21 @@ MD5_hexdigest(MD5object *self, PyObject *unused)
/* Create a new string */
retval = PyUnicode_FromStringAndSize(NULL, MD5_DIGESTSIZE * 2);
if (!retval)
return NULL;
return NULL;
hex_digest = PyUnicode_AS_UNICODE(retval);
if (!hex_digest) {
Py_DECREF(retval);
return NULL;
Py_DECREF(retval);
return NULL;
}
/* Make hex version of the digest */
for(i=j=0; i<MD5_DIGESTSIZE; i++) {
char c;
c = (digest[i] >> 4) & 0xf;
c = (c>9) ? c+'a'-10 : c + '0';
c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
c = (digest[i] & 0xf);
c = (c>9) ? c+'a'-10 : c + '0';
c = (c>9) ? c+'a'-10 : c + '0';
hex_digest[j++] = c;
}
return retval;
@ -414,7 +414,7 @@ MD5_update(MD5object *self, PyObject *args)
{
PyObject *obj;
Py_buffer buf;
if (!PyArg_ParseTuple(args, "O:update", &obj))
return NULL;
@ -428,11 +428,11 @@ MD5_update(MD5object *self, PyObject *args)
}
static PyMethodDef MD5_methods[] = {
{"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__},
{"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__},
{"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__},
{"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__},
{"hexdigest", (PyCFunction)MD5_hexdigest, METH_NOARGS, MD5_hexdigest__doc__},
{"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__},
{NULL, NULL} /* sentinel */
{"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__},
{NULL, NULL} /* sentinel */
};
static PyObject *
@ -472,13 +472,13 @@ static PyGetSetDef MD5_getseters[] = {
static PyTypeObject MD5type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_md5.md5", /*tp_name*/
sizeof(MD5object), /*tp_size*/
0, /*tp_itemsize*/
"_md5.md5", /*tp_name*/
sizeof(MD5object), /*tp_size*/
0, /*tp_itemsize*/
/* methods */
MD5_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
MD5_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
@ -494,13 +494,13 @@ static PyTypeObject MD5type = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
MD5_methods, /* tp_methods */
NULL, /* tp_members */
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
MD5_methods, /* tp_methods */
NULL, /* tp_members */
MD5_getseters, /* tp_getset */
};
@ -553,7 +553,7 @@ MD5_new(PyObject *self, PyObject *args, PyObject *kwdict)
static struct PyMethodDef MD5_functions[] = {
{"md5", (PyCFunction)MD5_new, METH_VARARGS|METH_KEYWORDS, MD5_new__doc__},
{NULL, NULL} /* Sentinel */
{NULL, NULL} /* Sentinel */
};
@ -563,15 +563,15 @@ static struct PyMethodDef MD5_functions[] = {
static struct PyModuleDef _md5module = {
PyModuleDef_HEAD_INIT,
"_md5",
NULL,
-1,
MD5_functions,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"_md5",
NULL,
-1,
MD5_functions,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,11 @@
/***********************************************************
Written by:
Fred Gansevles <Fred.Gansevles@cs.utwente.nl>
B&O group,
Faculteit der Informatica,
Universiteit Twente,
Enschede,
the Netherlands.
Fred Gansevles <Fred.Gansevles@cs.utwente.nl>
B&O group,
Faculteit der Informatica,
Universiteit Twente,
Enschede,
the Netherlands.
******************************************************************/
/* NIS module implementation */
@ -23,7 +23,7 @@
extern int yp_get_default_domain(char **);
#endif
PyDoc_STRVAR(get_default_domain__doc__,
PyDoc_STRVAR(get_default_domain__doc__,
"get_default_domain() -> str\n\
Corresponds to the C library yp_get_default_domain() call, returning\n\
the default NIS domain.\n");
@ -49,44 +49,44 @@ static PyObject *NisError;
static PyObject *
nis_error (int err)
{
PyErr_SetString(NisError, yperr_string(err));
return NULL;
PyErr_SetString(NisError, yperr_string(err));
return NULL;
}
static struct nis_map {
char *alias;
char *map;
int fix;
char *alias;
char *map;
int fix;
} aliases [] = {
{"passwd", "passwd.byname", 0},
{"group", "group.byname", 0},
{"networks", "networks.byaddr", 0},
{"hosts", "hosts.byname", 0},
{"protocols", "protocols.bynumber", 0},
{"services", "services.byname", 0},
{"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */
{"ethers", "ethers.byname", 0},
{0L, 0L, 0}
{"passwd", "passwd.byname", 0},
{"group", "group.byname", 0},
{"networks", "networks.byaddr", 0},
{"hosts", "hosts.byname", 0},
{"protocols", "protocols.bynumber", 0},
{"services", "services.byname", 0},
{"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */
{"ethers", "ethers.byname", 0},
{0L, 0L, 0}
};
static char *
nis_mapname (char *map, int *pfix)
{
int i;
int i;
*pfix = 0;
for (i=0; aliases[i].alias != 0L; i++) {
if (!strcmp (aliases[i].alias, map)) {
*pfix = aliases[i].fix;
return aliases[i].map;
}
if (!strcmp (aliases[i].map, map)) {
*pfix = aliases[i].fix;
return aliases[i].map;
}
}
*pfix = 0;
for (i=0; aliases[i].alias != 0L; i++) {
if (!strcmp (aliases[i].alias, map)) {
*pfix = aliases[i].fix;
return aliases[i].map;
}
if (!strcmp (aliases[i].map, map)) {
*pfix = aliases[i].fix;
return aliases[i].map;
}
}
return map;
return map;
}
#if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__)
@ -96,168 +96,168 @@ typedef int (*foreachfunc)(int, char *, int, char *, int, char *);
#endif
struct ypcallback_data {
PyObject *dict;
int fix;
PyThreadState *state;
PyObject *dict;
int fix;
PyThreadState *state;
};
static int
nis_foreach (int instatus, char *inkey, int inkeylen, char *inval,
int invallen, struct ypcallback_data *indata)
{
if (instatus == YP_TRUE) {
PyObject *key;
PyObject *val;
int err;
if (instatus == YP_TRUE) {
PyObject *key;
PyObject *val;
int err;
PyEval_RestoreThread(indata->state);
if (indata->fix) {
if (inkeylen > 0 && inkey[inkeylen-1] == '\0')
inkeylen--;
if (invallen > 0 && inval[invallen-1] == '\0')
invallen--;
}
key = PyUnicode_FromStringAndSize(inkey, inkeylen);
val = PyUnicode_FromStringAndSize(inval, invallen);
if (key == NULL || val == NULL) {
/* XXX error -- don't know how to handle */
PyErr_Clear();
Py_XDECREF(key);
Py_XDECREF(val);
return 1;
}
err = PyDict_SetItem(indata->dict, key, val);
Py_DECREF(key);
Py_DECREF(val);
if (err != 0)
PyErr_Clear();
indata->state = PyEval_SaveThread();
if (err != 0)
return 1;
return 0;
}
return 1;
PyEval_RestoreThread(indata->state);
if (indata->fix) {
if (inkeylen > 0 && inkey[inkeylen-1] == '\0')
inkeylen--;
if (invallen > 0 && inval[invallen-1] == '\0')
invallen--;
}
key = PyUnicode_FromStringAndSize(inkey, inkeylen);
val = PyUnicode_FromStringAndSize(inval, invallen);
if (key == NULL || val == NULL) {
/* XXX error -- don't know how to handle */
PyErr_Clear();
Py_XDECREF(key);
Py_XDECREF(val);
return 1;
}
err = PyDict_SetItem(indata->dict, key, val);
Py_DECREF(key);
Py_DECREF(val);
if (err != 0)
PyErr_Clear();
indata->state = PyEval_SaveThread();
if (err != 0)
return 1;
return 0;
}
return 1;
}
static PyObject *
nis_get_default_domain (PyObject *self)
{
char *domain;
int err;
PyObject *res;
char *domain;
int err;
PyObject *res;
if ((err = yp_get_default_domain(&domain)) != 0)
return nis_error(err);
if ((err = yp_get_default_domain(&domain)) != 0)
return nis_error(err);
res = PyUnicode_FromStringAndSize (domain, strlen(domain));
return res;
res = PyUnicode_FromStringAndSize (domain, strlen(domain));
return res;
}
static PyObject *
nis_match (PyObject *self, PyObject *args, PyObject *kwdict)
{
char *match;
char *domain = NULL;
int keylen, len;
char *key, *map;
int err;
PyObject *res;
int fix;
static char *kwlist[] = {"key", "map", "domain", NULL};
char *match;
char *domain = NULL;
int keylen, len;
char *key, *map;
int err;
PyObject *res;
int fix;
static char *kwlist[] = {"key", "map", "domain", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwdict,
"s#s|s:match", kwlist,
&key, &keylen, &map, &domain))
return NULL;
if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
return nis_error(err);
map = nis_mapname (map, &fix);
if (fix)
keylen++;
Py_BEGIN_ALLOW_THREADS
err = yp_match (domain, map, key, keylen, &match, &len);
Py_END_ALLOW_THREADS
if (fix)
len--;
if (err != 0)
return nis_error(err);
res = PyUnicode_FromStringAndSize (match, len);
free (match);
return res;
if (!PyArg_ParseTupleAndKeywords(args, kwdict,
"s#s|s:match", kwlist,
&key, &keylen, &map, &domain))
return NULL;
if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
return nis_error(err);
map = nis_mapname (map, &fix);
if (fix)
keylen++;
Py_BEGIN_ALLOW_THREADS
err = yp_match (domain, map, key, keylen, &match, &len);
Py_END_ALLOW_THREADS
if (fix)
len--;
if (err != 0)
return nis_error(err);
res = PyUnicode_FromStringAndSize (match, len);
free (match);
return res;
}
static PyObject *
nis_cat (PyObject *self, PyObject *args, PyObject *kwdict)
{
char *domain = NULL;
char *map;
struct ypall_callback cb;
struct ypcallback_data data;
PyObject *dict;
int err;
static char *kwlist[] = {"map", "domain", NULL};
char *domain = NULL;
char *map;
struct ypall_callback cb;
struct ypcallback_data data;
PyObject *dict;
int err;
static char *kwlist[] = {"map", "domain", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat",
kwlist, &map, &domain))
return NULL;
if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
return nis_error(err);
dict = PyDict_New ();
if (dict == NULL)
return NULL;
cb.foreach = (foreachfunc)nis_foreach;
data.dict = dict;
map = nis_mapname (map, &data.fix);
cb.data = (char *)&data;
data.state = PyEval_SaveThread();
err = yp_all (domain, map, &cb);
PyEval_RestoreThread(data.state);
if (err != 0) {
Py_DECREF(dict);
return nis_error(err);
}
return dict;
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat",
kwlist, &map, &domain))
return NULL;
if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
return nis_error(err);
dict = PyDict_New ();
if (dict == NULL)
return NULL;
cb.foreach = (foreachfunc)nis_foreach;
data.dict = dict;
map = nis_mapname (map, &data.fix);
cb.data = (char *)&data;
data.state = PyEval_SaveThread();
err = yp_all (domain, map, &cb);
PyEval_RestoreThread(data.state);
if (err != 0) {
Py_DECREF(dict);
return nis_error(err);
}
return dict;
}
/* These should be u_long on Sun h/w but not on 64-bit h/w.
This is not portable to machines with 16-bit ints and no prototypes */
#ifndef YPPROC_MAPLIST
#define YPPROC_MAPLIST 11
#define YPPROC_MAPLIST 11
#endif
#ifndef YPPROG
#define YPPROG 100004
#define YPPROG 100004
#endif
#ifndef YPVERS
#define YPVERS 2
#define YPVERS 2
#endif
typedef char *domainname;
typedef char *mapname;
enum nisstat {
NIS_TRUE = 1,
NIS_NOMORE = 2,
NIS_FALSE = 0,
NIS_NOMAP = -1,
NIS_NODOM = -2,
NIS_NOKEY = -3,
NIS_BADOP = -4,
NIS_BADDB = -5,
NIS_YPERR = -6,
NIS_BADARGS = -7,
NIS_VERS = -8
NIS_TRUE = 1,
NIS_NOMORE = 2,
NIS_FALSE = 0,
NIS_NOMAP = -1,
NIS_NODOM = -2,
NIS_NOKEY = -3,
NIS_BADOP = -4,
NIS_BADDB = -5,
NIS_YPERR = -6,
NIS_BADARGS = -7,
NIS_VERS = -8
};
typedef enum nisstat nisstat;
struct nismaplist {
mapname map;
struct nismaplist *next;
mapname map;
struct nismaplist *next;
};
typedef struct nismaplist nismaplist;
struct nisresp_maplist {
nisstat stat;
nismaplist *maps;
nisstat stat;
nismaplist *maps;
};
typedef struct nisresp_maplist nisresp_maplist;
@ -267,45 +267,45 @@ static
bool_t
nis_xdr_domainname(XDR *xdrs, domainname *objp)
{
if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) {
return (FALSE);
}
return (TRUE);
if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) {
return (FALSE);
}
return (TRUE);
}
static
bool_t
nis_xdr_mapname(XDR *xdrs, mapname *objp)
{
if (!xdr_string(xdrs, objp, YPMAXMAP)) {
return (FALSE);
}
return (TRUE);
if (!xdr_string(xdrs, objp, YPMAXMAP)) {
return (FALSE);
}
return (TRUE);
}
static
bool_t
nis_xdr_ypmaplist(XDR *xdrs, nismaplist *objp)
{
if (!nis_xdr_mapname(xdrs, &objp->map)) {
return (FALSE);
}
if (!xdr_pointer(xdrs, (char **)&objp->next,
sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
{
return (FALSE);
}
return (TRUE);
if (!nis_xdr_mapname(xdrs, &objp->map)) {
return (FALSE);
}
if (!xdr_pointer(xdrs, (char **)&objp->next,
sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
{
return (FALSE);
}
return (TRUE);
}
static
bool_t
nis_xdr_ypstat(XDR *xdrs, nisstat *objp)
{
if (!xdr_enum(xdrs, (enum_t *)objp)) {
return (FALSE);
}
return (TRUE);
if (!xdr_enum(xdrs, (enum_t *)objp)) {
return (FALSE);
}
return (TRUE);
}
@ -313,15 +313,15 @@ static
bool_t
nis_xdr_ypresp_maplist(XDR *xdrs, nisresp_maplist *objp)
{
if (!nis_xdr_ypstat(xdrs, &objp->stat)) {
return (FALSE);
}
if (!xdr_pointer(xdrs, (char **)&objp->maps,
sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
{
return (FALSE);
}
return (TRUE);
if (!nis_xdr_ypstat(xdrs, &objp->stat)) {
return (FALSE);
}
if (!xdr_pointer(xdrs, (char **)&objp->maps,
sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
{
return (FALSE);
}
return (TRUE);
}
@ -329,132 +329,132 @@ static
nisresp_maplist *
nisproc_maplist_2(domainname *argp, CLIENT *clnt)
{
static nisresp_maplist res;
static nisresp_maplist res;
memset(&res, 0, sizeof(res));
if (clnt_call(clnt, YPPROC_MAPLIST,
(xdrproc_t)nis_xdr_domainname, (caddr_t)argp,
(xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res,
TIMEOUT) != RPC_SUCCESS)
{
return (NULL);
}
return (&res);
memset(&res, 0, sizeof(res));
if (clnt_call(clnt, YPPROC_MAPLIST,
(xdrproc_t)nis_xdr_domainname, (caddr_t)argp,
(xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res,
TIMEOUT) != RPC_SUCCESS)
{
return (NULL);
}
return (&res);
}
static
nismaplist *
nis_maplist (char *dom)
{
nisresp_maplist *list;
CLIENT *cl;
char *server = NULL;
int mapi = 0;
nisresp_maplist *list;
CLIENT *cl;
char *server = NULL;
int mapi = 0;
while (!server && aliases[mapi].map != 0L) {
yp_master (dom, aliases[mapi].map, &server);
mapi++;
}
if (!server) {
PyErr_SetString(NisError, "No NIS master found for any map");
return NULL;
}
cl = clnt_create(server, YPPROG, YPVERS, "tcp");
if (cl == NULL) {
PyErr_SetString(NisError, clnt_spcreateerror(server));
goto finally;
}
list = nisproc_maplist_2 (&dom, cl);
clnt_destroy(cl);
if (list == NULL)
goto finally;
if (list->stat != NIS_TRUE)
goto finally;
while (!server && aliases[mapi].map != 0L) {
yp_master (dom, aliases[mapi].map, &server);
mapi++;
}
if (!server) {
PyErr_SetString(NisError, "No NIS master found for any map");
return NULL;
}
cl = clnt_create(server, YPPROG, YPVERS, "tcp");
if (cl == NULL) {
PyErr_SetString(NisError, clnt_spcreateerror(server));
goto finally;
}
list = nisproc_maplist_2 (&dom, cl);
clnt_destroy(cl);
if (list == NULL)
goto finally;
if (list->stat != NIS_TRUE)
goto finally;
free(server);
return list->maps;
free(server);
return list->maps;
finally:
free(server);
return NULL;
free(server);
return NULL;
}
static PyObject *
nis_maps (PyObject *self, PyObject *args, PyObject *kwdict)
{
char *domain = NULL;
nismaplist *maps;
PyObject *list;
int err;
static char *kwlist[] = {"domain", NULL};
char *domain = NULL;
nismaplist *maps;
PyObject *list;
int err;
static char *kwlist[] = {"domain", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwdict,
"|s:maps", kwlist, &domain))
return NULL;
if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) {
nis_error(err);
return NULL;
}
if (!PyArg_ParseTupleAndKeywords(args, kwdict,
"|s:maps", kwlist, &domain))
return NULL;
if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) {
nis_error(err);
return NULL;
}
if ((maps = nis_maplist (domain)) == NULL)
return NULL;
if ((list = PyList_New(0)) == NULL)
return NULL;
for (maps = maps; maps; maps = maps->next) {
PyObject *str = PyUnicode_FromString(maps->map);
if (!str || PyList_Append(list, str) < 0)
{
Py_DECREF(list);
list = NULL;
break;
}
Py_DECREF(str);
}
/* XXX Shouldn't we free the list of maps now? */
return list;
if ((maps = nis_maplist (domain)) == NULL)
return NULL;
if ((list = PyList_New(0)) == NULL)
return NULL;
for (maps = maps; maps; maps = maps->next) {
PyObject *str = PyUnicode_FromString(maps->map);
if (!str || PyList_Append(list, str) < 0)
{
Py_DECREF(list);
list = NULL;
break;
}
Py_DECREF(str);
}
/* XXX Shouldn't we free the list of maps now? */
return list;
}
static PyMethodDef nis_methods[] = {
{"match", (PyCFunction)nis_match,
METH_VARARGS | METH_KEYWORDS,
match__doc__},
{"cat", (PyCFunction)nis_cat,
METH_VARARGS | METH_KEYWORDS,
cat__doc__},
{"maps", (PyCFunction)nis_maps,
METH_VARARGS | METH_KEYWORDS,
maps__doc__},
{"get_default_domain", (PyCFunction)nis_get_default_domain,
METH_NOARGS,
get_default_domain__doc__},
{NULL, NULL} /* Sentinel */
{"match", (PyCFunction)nis_match,
METH_VARARGS | METH_KEYWORDS,
match__doc__},
{"cat", (PyCFunction)nis_cat,
METH_VARARGS | METH_KEYWORDS,
cat__doc__},
{"maps", (PyCFunction)nis_maps,
METH_VARARGS | METH_KEYWORDS,
maps__doc__},
{"get_default_domain", (PyCFunction)nis_get_default_domain,
METH_NOARGS,
get_default_domain__doc__},
{NULL, NULL} /* Sentinel */
};
PyDoc_STRVAR(nis__doc__,
"This module contains functions for accessing NIS maps.\n");
static struct PyModuleDef nismodule = {
PyModuleDef_HEAD_INIT,
"nis",
nis__doc__,
-1,
nis_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"nis",
nis__doc__,
-1,
nis_methods,
NULL,
NULL,
NULL,
NULL
};
PyObject*
PyInit_nis (void)
{
PyObject *m, *d;
m = PyModule_Create(&nismodule);
if (m == NULL)
return NULL;
d = PyModule_GetDict(m);
NisError = PyErr_NewException("nis.error", NULL, NULL);
if (NisError != NULL)
PyDict_SetItemString(d, "error", NisError);
return m;
PyObject *m, *d;
m = PyModule_Create(&nismodule);
if (m == NULL)
return NULL;
d = PyModule_GetDict(m);
NisError = PyErr_NewException("nis.error", NULL, NULL);
if (NisError != NULL)
PyDict_SetItemString(d, "error", NisError);
return m;
}

View file

@ -112,47 +112,47 @@ spamrc(op_ge , Py_GE)
static PyObject*
op_pow(PyObject *s, PyObject *a)
{
PyObject *a1, *a2;
if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2))
return PyNumber_Power(a1, a2, Py_None);
return NULL;
PyObject *a1, *a2;
if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2))
return PyNumber_Power(a1, a2, Py_None);
return NULL;
}
static PyObject*
op_ipow(PyObject *s, PyObject *a)
{
PyObject *a1, *a2;
if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2))
return PyNumber_InPlacePower(a1, a2, Py_None);
return NULL;
PyObject *a1, *a2;
if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2))
return PyNumber_InPlacePower(a1, a2, Py_None);
return NULL;
}
static PyObject *
op_index(PyObject *s, PyObject *a)
{
return PyNumber_Index(a);
return PyNumber_Index(a);
}
static PyObject*
is_(PyObject *s, PyObject *a)
{
PyObject *a1, *a2, *result = NULL;
if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) {
result = (a1 == a2) ? Py_True : Py_False;
Py_INCREF(result);
}
return result;
PyObject *a1, *a2, *result = NULL;
if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) {
result = (a1 == a2) ? Py_True : Py_False;
Py_INCREF(result);
}
return result;
}
static PyObject*
is_not(PyObject *s, PyObject *a)
{
PyObject *a1, *a2, *result = NULL;
if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) {
result = (a1 != a2) ? Py_True : Py_False;
Py_INCREF(result);
}
return result;
PyObject *a1, *a2, *result = NULL;
if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) {
result = (a1 != a2) ? Py_True : Py_False;
Py_INCREF(result);
}
return result;
}
#undef spam1
@ -161,10 +161,10 @@ is_not(PyObject *s, PyObject *a)
#undef spam1o
#define spam1(OP,DOC) {#OP, OP, METH_VARARGS, PyDoc_STR(DOC)},
#define spam2(OP,ALTOP,DOC) {#OP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, \
{#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)},
{#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)},
#define spam1o(OP,DOC) {#OP, OP, METH_O, PyDoc_STR(DOC)},
#define spam2o(OP,ALTOP,DOC) {#OP, op_##OP, METH_O, PyDoc_STR(DOC)}, \
{#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)},
{#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)},
static struct PyMethodDef operator_methods[] = {
@ -227,16 +227,16 @@ spam2(ne,__ne__, "ne(a, b) -- Same as a!=b.")
spam2(gt,__gt__, "gt(a, b) -- Same as a>b.")
spam2(ge,__ge__, "ge(a, b) -- Same as a>=b.")
{NULL, NULL} /* sentinel */
{NULL, NULL} /* sentinel */
};
/* itemgetter object **********************************************************/
typedef struct {
PyObject_HEAD
Py_ssize_t nitems;
PyObject *item;
PyObject_HEAD
Py_ssize_t nitems;
PyObject *item;
} itemgetterobject;
static PyTypeObject itemgetter_type;
@ -244,77 +244,77 @@ static PyTypeObject itemgetter_type;
static PyObject *
itemgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
itemgetterobject *ig;
PyObject *item;
Py_ssize_t nitems;
itemgetterobject *ig;
PyObject *item;
Py_ssize_t nitems;
if (!_PyArg_NoKeywords("itemgetter()", kwds))
return NULL;
if (!_PyArg_NoKeywords("itemgetter()", kwds))
return NULL;
nitems = PyTuple_GET_SIZE(args);
if (nitems <= 1) {
if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item))
return NULL;
} else
item = args;
nitems = PyTuple_GET_SIZE(args);
if (nitems <= 1) {
if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item))
return NULL;
} else
item = args;
/* create itemgetterobject structure */
ig = PyObject_GC_New(itemgetterobject, &itemgetter_type);
if (ig == NULL)
return NULL;
Py_INCREF(item);
ig->item = item;
ig->nitems = nitems;
/* create itemgetterobject structure */
ig = PyObject_GC_New(itemgetterobject, &itemgetter_type);
if (ig == NULL)
return NULL;
PyObject_GC_Track(ig);
return (PyObject *)ig;
Py_INCREF(item);
ig->item = item;
ig->nitems = nitems;
PyObject_GC_Track(ig);
return (PyObject *)ig;
}
static void
itemgetter_dealloc(itemgetterobject *ig)
{
PyObject_GC_UnTrack(ig);
Py_XDECREF(ig->item);
PyObject_GC_Del(ig);
PyObject_GC_UnTrack(ig);
Py_XDECREF(ig->item);
PyObject_GC_Del(ig);
}
static int
itemgetter_traverse(itemgetterobject *ig, visitproc visit, void *arg)
{
Py_VISIT(ig->item);
return 0;
Py_VISIT(ig->item);
return 0;
}
static PyObject *
itemgetter_call(itemgetterobject *ig, PyObject *args, PyObject *kw)
{
PyObject *obj, *result;
Py_ssize_t i, nitems=ig->nitems;
PyObject *obj, *result;
Py_ssize_t i, nitems=ig->nitems;
if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj))
return NULL;
if (nitems == 1)
return PyObject_GetItem(obj, ig->item);
if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj))
return NULL;
if (nitems == 1)
return PyObject_GetItem(obj, ig->item);
assert(PyTuple_Check(ig->item));
assert(PyTuple_GET_SIZE(ig->item) == nitems);
assert(PyTuple_Check(ig->item));
assert(PyTuple_GET_SIZE(ig->item) == nitems);
result = PyTuple_New(nitems);
if (result == NULL)
return NULL;
result = PyTuple_New(nitems);
if (result == NULL)
return NULL;
for (i=0 ; i < nitems ; i++) {
PyObject *item, *val;
item = PyTuple_GET_ITEM(ig->item, i);
val = PyObject_GetItem(obj, item);
if (val == NULL) {
Py_DECREF(result);
return NULL;
}
PyTuple_SET_ITEM(result, i, val);
}
return result;
for (i=0 ; i < nitems ; i++) {
PyObject *item, *val;
item = PyTuple_GET_ITEM(ig->item, i);
val = PyObject_GetItem(obj, item);
if (val == NULL) {
Py_DECREF(result);
return NULL;
}
PyTuple_SET_ITEM(result, i, val);
}
return result;
}
PyDoc_STRVAR(itemgetter_doc,
@ -325,55 +325,55 @@ After, f=itemgetter(2), the call f(r) returns r[2].\n\
After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])");
static PyTypeObject itemgetter_type = {
PyVarObject_HEAD_INIT(NULL, 0)
"operator.itemgetter", /* tp_name */
sizeof(itemgetterobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)itemgetter_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)itemgetter_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
itemgetter_doc, /* tp_doc */
(traverseproc)itemgetter_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
itemgetter_new, /* tp_new */
0, /* tp_free */
PyVarObject_HEAD_INIT(NULL, 0)
"operator.itemgetter", /* tp_name */
sizeof(itemgetterobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)itemgetter_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)itemgetter_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
itemgetter_doc, /* tp_doc */
(traverseproc)itemgetter_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
itemgetter_new, /* tp_new */
0, /* tp_free */
};
/* attrgetter object **********************************************************/
typedef struct {
PyObject_HEAD
Py_ssize_t nattrs;
PyObject *attr;
PyObject_HEAD
Py_ssize_t nattrs;
PyObject *attr;
} attrgetterobject;
static PyTypeObject attrgetter_type;
@ -381,112 +381,112 @@ static PyTypeObject attrgetter_type;
static PyObject *
attrgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
attrgetterobject *ag;
PyObject *attr;
Py_ssize_t nattrs;
attrgetterobject *ag;
PyObject *attr;
Py_ssize_t nattrs;
if (!_PyArg_NoKeywords("attrgetter()", kwds))
return NULL;
if (!_PyArg_NoKeywords("attrgetter()", kwds))
return NULL;
nattrs = PyTuple_GET_SIZE(args);
if (nattrs <= 1) {
if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr))
return NULL;
} else
attr = args;
nattrs = PyTuple_GET_SIZE(args);
if (nattrs <= 1) {
if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr))
return NULL;
} else
attr = args;
/* create attrgetterobject structure */
ag = PyObject_GC_New(attrgetterobject, &attrgetter_type);
if (ag == NULL)
return NULL;
Py_INCREF(attr);
ag->attr = attr;
ag->nattrs = nattrs;
/* create attrgetterobject structure */
ag = PyObject_GC_New(attrgetterobject, &attrgetter_type);
if (ag == NULL)
return NULL;
PyObject_GC_Track(ag);
return (PyObject *)ag;
Py_INCREF(attr);
ag->attr = attr;
ag->nattrs = nattrs;
PyObject_GC_Track(ag);
return (PyObject *)ag;
}
static void
attrgetter_dealloc(attrgetterobject *ag)
{
PyObject_GC_UnTrack(ag);
Py_XDECREF(ag->attr);
PyObject_GC_Del(ag);
PyObject_GC_UnTrack(ag);
Py_XDECREF(ag->attr);
PyObject_GC_Del(ag);
}
static int
attrgetter_traverse(attrgetterobject *ag, visitproc visit, void *arg)
{
Py_VISIT(ag->attr);
return 0;
Py_VISIT(ag->attr);
return 0;
}
static PyObject *
dotted_getattr(PyObject *obj, PyObject *attr)
{
char *s, *p;
char *s, *p;
if (!PyUnicode_Check(attr)) {
PyErr_SetString(PyExc_TypeError,
"attribute name must be a string");
return NULL;
}
if (!PyUnicode_Check(attr)) {
PyErr_SetString(PyExc_TypeError,
"attribute name must be a string");
return NULL;
}
s = _PyUnicode_AsString(attr);
Py_INCREF(obj);
for (;;) {
PyObject *newobj, *str;
p = strchr(s, '.');
str = p ? PyUnicode_FromStringAndSize(s, (p-s)) :
PyUnicode_FromString(s);
if (str == NULL) {
Py_DECREF(obj);
return NULL;
}
newobj = PyObject_GetAttr(obj, str);
Py_DECREF(str);
Py_DECREF(obj);
if (newobj == NULL)
return NULL;
obj = newobj;
if (p == NULL) break;
s = p+1;
}
s = _PyUnicode_AsString(attr);
Py_INCREF(obj);
for (;;) {
PyObject *newobj, *str;
p = strchr(s, '.');
str = p ? PyUnicode_FromStringAndSize(s, (p-s)) :
PyUnicode_FromString(s);
if (str == NULL) {
Py_DECREF(obj);
return NULL;
}
newobj = PyObject_GetAttr(obj, str);
Py_DECREF(str);
Py_DECREF(obj);
if (newobj == NULL)
return NULL;
obj = newobj;
if (p == NULL) break;
s = p+1;
}
return obj;
return obj;
}
static PyObject *
attrgetter_call(attrgetterobject *ag, PyObject *args, PyObject *kw)
{
PyObject *obj, *result;
Py_ssize_t i, nattrs=ag->nattrs;
PyObject *obj, *result;
Py_ssize_t i, nattrs=ag->nattrs;
if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj))
return NULL;
if (ag->nattrs == 1)
return dotted_getattr(obj, ag->attr);
if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj))
return NULL;
if (ag->nattrs == 1)
return dotted_getattr(obj, ag->attr);
assert(PyTuple_Check(ag->attr));
assert(PyTuple_GET_SIZE(ag->attr) == nattrs);
assert(PyTuple_Check(ag->attr));
assert(PyTuple_GET_SIZE(ag->attr) == nattrs);
result = PyTuple_New(nattrs);
if (result == NULL)
return NULL;
result = PyTuple_New(nattrs);
if (result == NULL)
return NULL;
for (i=0 ; i < nattrs ; i++) {
PyObject *attr, *val;
attr = PyTuple_GET_ITEM(ag->attr, i);
val = dotted_getattr(obj, attr);
if (val == NULL) {
Py_DECREF(result);
return NULL;
}
PyTuple_SET_ITEM(result, i, val);
}
return result;
for (i=0 ; i < nattrs ; i++) {
PyObject *attr, *val;
attr = PyTuple_GET_ITEM(ag->attr, i);
val = dotted_getattr(obj, attr);
if (val == NULL) {
Py_DECREF(result);
return NULL;
}
PyTuple_SET_ITEM(result, i, val);
}
return result;
}
PyDoc_STRVAR(attrgetter_doc,
@ -499,56 +499,56 @@ After, h=attrgetter('name.first', 'name.last'), the call h(r) returns\n\
(r.name.first, r.name.last).");
static PyTypeObject attrgetter_type = {
PyVarObject_HEAD_INIT(NULL, 0)
"operator.attrgetter", /* tp_name */
sizeof(attrgetterobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)attrgetter_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)attrgetter_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
attrgetter_doc, /* tp_doc */
(traverseproc)attrgetter_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
attrgetter_new, /* tp_new */
0, /* tp_free */
PyVarObject_HEAD_INIT(NULL, 0)
"operator.attrgetter", /* tp_name */
sizeof(attrgetterobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)attrgetter_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)attrgetter_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
attrgetter_doc, /* tp_doc */
(traverseproc)attrgetter_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
attrgetter_new, /* tp_new */
0, /* tp_free */
};
/* methodcaller object **********************************************************/
typedef struct {
PyObject_HEAD
PyObject *name;
PyObject *args;
PyObject *kwds;
PyObject_HEAD
PyObject *name;
PyObject *args;
PyObject *kwds;
} methodcallerobject;
static PyTypeObject methodcaller_type;
@ -556,69 +556,69 @@ static PyTypeObject methodcaller_type;
static PyObject *
methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
methodcallerobject *mc;
PyObject *name, *newargs;
methodcallerobject *mc;
PyObject *name, *newargs;
if (PyTuple_GET_SIZE(args) < 1) {
PyErr_SetString(PyExc_TypeError, "methodcaller needs at least "
"one argument, the method name");
return NULL;
}
if (PyTuple_GET_SIZE(args) < 1) {
PyErr_SetString(PyExc_TypeError, "methodcaller needs at least "
"one argument, the method name");
return NULL;
}
/* create methodcallerobject structure */
mc = PyObject_GC_New(methodcallerobject, &methodcaller_type);
if (mc == NULL)
return NULL;
/* create methodcallerobject structure */
mc = PyObject_GC_New(methodcallerobject, &methodcaller_type);
if (mc == NULL)
return NULL;
newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
if (newargs == NULL) {
Py_DECREF(mc);
return NULL;
}
mc->args = newargs;
newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
if (newargs == NULL) {
Py_DECREF(mc);
return NULL;
}
mc->args = newargs;
name = PyTuple_GET_ITEM(args, 0);
Py_INCREF(name);
mc->name = name;
name = PyTuple_GET_ITEM(args, 0);
Py_INCREF(name);
mc->name = name;
Py_XINCREF(kwds);
mc->kwds = kwds;
Py_XINCREF(kwds);
mc->kwds = kwds;
PyObject_GC_Track(mc);
return (PyObject *)mc;
PyObject_GC_Track(mc);
return (PyObject *)mc;
}
static void
methodcaller_dealloc(methodcallerobject *mc)
{
PyObject_GC_UnTrack(mc);
Py_XDECREF(mc->name);
Py_XDECREF(mc->args);
Py_XDECREF(mc->kwds);
PyObject_GC_Del(mc);
PyObject_GC_UnTrack(mc);
Py_XDECREF(mc->name);
Py_XDECREF(mc->args);
Py_XDECREF(mc->kwds);
PyObject_GC_Del(mc);
}
static int
methodcaller_traverse(methodcallerobject *mc, visitproc visit, void *arg)
{
Py_VISIT(mc->args);
Py_VISIT(mc->kwds);
return 0;
Py_VISIT(mc->args);
Py_VISIT(mc->kwds);
return 0;
}
static PyObject *
methodcaller_call(methodcallerobject *mc, PyObject *args, PyObject *kw)
{
PyObject *method, *obj, *result;
PyObject *method, *obj, *result;
if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj))
return NULL;
method = PyObject_GetAttr(obj, mc->name);
if (method == NULL)
return NULL;
result = PyObject_Call(method, mc->args, mc->kwds);
Py_DECREF(method);
return result;
if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj))
return NULL;
method = PyObject_GetAttr(obj, mc->name);
if (method == NULL)
return NULL;
result = PyObject_Call(method, mc->args, mc->kwds);
Py_DECREF(method);
return result;
}
PyDoc_STRVAR(methodcaller_doc,
@ -630,46 +630,46 @@ After, g = methodcaller('name', 'date', foo=1), the call g(r) returns\n\
r.name('date', foo=1).");
static PyTypeObject methodcaller_type = {
PyVarObject_HEAD_INIT(NULL, 0)
"operator.methodcaller", /* tp_name */
sizeof(methodcallerobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)methodcaller_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)methodcaller_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
methodcaller_doc, /* tp_doc */
(traverseproc)methodcaller_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
methodcaller_new, /* tp_new */
0, /* tp_free */
PyVarObject_HEAD_INIT(NULL, 0)
"operator.methodcaller", /* tp_name */
sizeof(methodcallerobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)methodcaller_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)methodcaller_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
methodcaller_doc, /* tp_doc */
(traverseproc)methodcaller_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
methodcaller_new, /* tp_new */
0, /* tp_free */
};
@ -677,40 +677,40 @@ static PyTypeObject methodcaller_type = {
static struct PyModuleDef operatormodule = {
PyModuleDef_HEAD_INIT,
"operator",
operator_doc,
-1,
operator_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"operator",
operator_doc,
-1,
operator_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_operator(void)
{
PyObject *m;
/* Create the module and add the functions */
m = PyModule_Create(&operatormodule);
if (m == NULL)
return NULL;
PyObject *m;
if (PyType_Ready(&itemgetter_type) < 0)
return NULL;
Py_INCREF(&itemgetter_type);
PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type);
/* Create the module and add the functions */
m = PyModule_Create(&operatormodule);
if (m == NULL)
return NULL;
if (PyType_Ready(&attrgetter_type) < 0)
return NULL;
Py_INCREF(&attrgetter_type);
PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type);
if (PyType_Ready(&itemgetter_type) < 0)
return NULL;
Py_INCREF(&itemgetter_type);
PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type);
if (PyType_Ready(&methodcaller_type) < 0)
return NULL;
Py_INCREF(&methodcaller_type);
PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type);
return m;
if (PyType_Ready(&attrgetter_type) < 0)
return NULL;
Py_INCREF(&attrgetter_type);
PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type);
if (PyType_Ready(&methodcaller_type) < 0)
return NULL;
Py_INCREF(&methodcaller_type);
PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type);
return m;
}

View file

@ -809,8 +809,8 @@ oss_getattro(oss_audio_t *self, PyObject *nameobj)
PyObject * rval = NULL;
if (PyUnicode_Check(nameobj))
name = _PyUnicode_AsString(nameobj);
name = _PyUnicode_AsString(nameobj);
if (strcmp(name, "closed") == 0) {
rval = (self->fd == -1) ? Py_True : Py_False;
Py_INCREF(rval);
@ -975,15 +975,15 @@ error1:
static struct PyModuleDef ossaudiodevmodule = {
PyModuleDef_HEAD_INIT,
"ossaudiodev",
NULL,
-1,
ossaudiodev_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"ossaudiodev",
NULL,
-1,
ossaudiodev_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
@ -999,10 +999,10 @@ PyInit_ossaudiodev(void)
m = PyModule_Create(&ossaudiodevmodule);
if (m == NULL)
return NULL;
return NULL;
OSSAudioError = PyErr_NewException("ossaudiodev.OSSAudioError",
NULL, NULL);
NULL, NULL);
if (OSSAudioError) {
/* Each call to PyModule_AddObject decrefs it; compensate: */
Py_INCREF(OSSAudioError);

View file

@ -578,8 +578,8 @@ parser_do_parse(PyObject *args, PyObject *kw, char *argspec, int type)
? eval_input : file_input,
&err, &flags);
if (n) {
res = parser_newstobject(n, type);
if (n) {
res = parser_newstobject(n, type);
if (res)
((PyST_Object *)res)->st_flags.cf_flags = flags & PyCF_MASK;
}
@ -784,7 +784,7 @@ build_node_children(PyObject *tuple, node *root, int *line_num)
PyErr_Format(parser_error,
"third item in terminal node must be an"
" integer, found %s",
Py_TYPE(temp)->tp_name);
Py_TYPE(temp)->tp_name);
Py_DECREF(o);
Py_DECREF(temp);
Py_DECREF(elem);
@ -1051,7 +1051,7 @@ validate_class(node *tree)
{
int nch = NCH(tree);
int res = (validate_ntype(tree, classdef) &&
((nch == 4) || (nch == 6) || (nch == 7)));
((nch == 4) || (nch == 6) || (nch == 7)));
if (res) {
res = (validate_name(CHILD(tree, 0), "class")
@ -1064,15 +1064,15 @@ validate_class(node *tree)
}
if (res) {
if (nch == 7) {
res = ((validate_lparen(CHILD(tree, 2)) &&
validate_arglist(CHILD(tree, 3)) &&
validate_rparen(CHILD(tree, 4))));
}
else if (nch == 6) {
res = (validate_lparen(CHILD(tree,2)) &&
validate_rparen(CHILD(tree,3)));
}
if (nch == 7) {
res = ((validate_lparen(CHILD(tree, 2)) &&
validate_arglist(CHILD(tree, 3)) &&
validate_rparen(CHILD(tree, 4))));
}
else if (nch == 6) {
res = (validate_lparen(CHILD(tree,2)) &&
validate_rparen(CHILD(tree,3)));
}
}
return (res);
}
@ -1244,10 +1244,10 @@ validate_varargslist_trailer(node *tree, int start)
else {
/* skip over vfpdef (',' vfpdef ['=' test])* */
i = start + 1;
if (TYPE(CHILD(tree, i)) == vfpdef ||
TYPE(CHILD(tree, i)) == tfpdef) { /* skip over vfpdef or tfpdef */
i += 1;
}
if (TYPE(CHILD(tree, i)) == vfpdef ||
TYPE(CHILD(tree, i)) == tfpdef) { /* skip over vfpdef or tfpdef */
i += 1;
}
while (res && i+1 < nch) { /* validate (',' vfpdef ['=' test])* */
res = validate_comma(CHILD(tree, i));
if (TYPE(CHILD(tree, i+1)) == DOUBLESTAR)
@ -1718,14 +1718,14 @@ validate_dotted_as_name(node *tree)
static int
validate_dotted_as_names(node *tree)
{
int nch = NCH(tree);
int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0));
int i;
int nch = NCH(tree);
int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0));
int i;
for (i = 1; res && (i < nch); i += 2)
res = (validate_comma(CHILD(tree, i))
&& validate_dotted_as_name(CHILD(tree, i + 1)));
return (res);
for (i = 1; res && (i < nch); i += 2)
res = (validate_comma(CHILD(tree, i))
&& validate_dotted_as_name(CHILD(tree, i + 1)));
return (res);
}
@ -1738,8 +1738,8 @@ validate_import_as_names(node *tree)
int i;
for (i = 1; res && (i + 1 < nch); i += 2)
res = (validate_comma(CHILD(tree, i))
&& validate_import_as_name(CHILD(tree, i + 1)));
res = (validate_comma(CHILD(tree, i))
&& validate_import_as_name(CHILD(tree, i + 1)));
return (res);
}
@ -1748,10 +1748,10 @@ validate_import_as_names(node *tree)
static int
validate_import_name(node *tree)
{
return (validate_ntype(tree, import_name)
&& validate_numnodes(tree, 2, "import_name")
&& validate_name(CHILD(tree, 0), "import")
&& validate_dotted_as_names(CHILD(tree, 1)));
return (validate_ntype(tree, import_name)
&& validate_numnodes(tree, 2, "import_name")
&& validate_name(CHILD(tree, 0), "import")
&& validate_dotted_as_names(CHILD(tree, 1)));
}
/* Helper function to count the number of leading dots in
@ -1762,8 +1762,8 @@ count_from_dots(node *tree)
{
int i;
for (i = 1; i < NCH(tree); i++)
if (TYPE(CHILD(tree, i)) != DOT)
break;
if (TYPE(CHILD(tree, i)) != DOT)
break;
return i-1;
}
@ -1773,24 +1773,24 @@ count_from_dots(node *tree)
static int
validate_import_from(node *tree)
{
int nch = NCH(tree);
int ndots = count_from_dots(tree);
int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name);
int offset = ndots + havename;
int res = validate_ntype(tree, import_from)
&& (nch >= 4 + ndots)
&& validate_name(CHILD(tree, 0), "from")
&& (!havename || validate_dotted_name(CHILD(tree, ndots + 1)))
&& validate_name(CHILD(tree, offset + 1), "import");
int nch = NCH(tree);
int ndots = count_from_dots(tree);
int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name);
int offset = ndots + havename;
int res = validate_ntype(tree, import_from)
&& (nch >= 4 + ndots)
&& validate_name(CHILD(tree, 0), "from")
&& (!havename || validate_dotted_name(CHILD(tree, ndots + 1)))
&& validate_name(CHILD(tree, offset + 1), "import");
if (res && TYPE(CHILD(tree, offset + 2)) == LPAR)
res = ((nch == offset + 5)
&& validate_lparen(CHILD(tree, offset + 2))
&& validate_import_as_names(CHILD(tree, offset + 3))
&& validate_rparen(CHILD(tree, offset + 4)));
else if (res && TYPE(CHILD(tree, offset + 2)) != STAR)
res = validate_import_as_names(CHILD(tree, offset + 2));
return (res);
if (res && TYPE(CHILD(tree, offset + 2)) == LPAR)
res = ((nch == offset + 5)
&& validate_lparen(CHILD(tree, offset + 2))
&& validate_import_as_names(CHILD(tree, offset + 3))
&& validate_rparen(CHILD(tree, offset + 4)));
else if (res && TYPE(CHILD(tree, offset + 2)) != STAR)
res = validate_import_as_names(CHILD(tree, offset + 2));
return (res);
}
@ -1802,9 +1802,9 @@ validate_import_stmt(node *tree)
int res = validate_numnodes(tree, 1, "import_stmt");
if (res) {
int ntype = TYPE(CHILD(tree, 0));
int ntype = TYPE(CHILD(tree, 0));
if (ntype == import_name || ntype == import_from)
if (ntype == import_name || ntype == import_from)
res = validate_node(CHILD(tree, 0));
else {
res = 0;
@ -2323,11 +2323,11 @@ validate_atom(node *tree)
&& (validate_rparen(CHILD(tree, nch - 1))));
if (res && (nch == 3)) {
if (TYPE(CHILD(tree, 1))==yield_expr)
res = validate_yield_expr(CHILD(tree, 1));
else
res = validate_testlist_comp(CHILD(tree, 1));
}
if (TYPE(CHILD(tree, 1))==yield_expr)
res = validate_yield_expr(CHILD(tree, 1));
else
res = validate_testlist_comp(CHILD(tree, 1));
}
break;
case LSQB:
if (nch == 2)
@ -2355,11 +2355,11 @@ validate_atom(node *tree)
for (pos = 1; res && (pos < nch); ++pos)
res = validate_ntype(CHILD(tree, pos), STRING);
break;
case DOT:
res = (nch == 3 &&
validate_ntype(CHILD(tree, 1), DOT) &&
validate_ntype(CHILD(tree, 2), DOT));
break;
case DOT:
res = (nch == 3 &&
validate_ntype(CHILD(tree, 1), DOT) &&
validate_ntype(CHILD(tree, 2), DOT));
break;
default:
res = 0;
break;
@ -2416,17 +2416,17 @@ validate_decorator(node *tree)
int ok;
int nch = NCH(tree);
ok = (validate_ntype(tree, decorator) &&
(nch == 3 || nch == 5 || nch == 6) &&
validate_at(CHILD(tree, 0)) &&
validate_dotted_name(CHILD(tree, 1)) &&
validate_newline(RCHILD(tree, -1)));
(nch == 3 || nch == 5 || nch == 6) &&
validate_at(CHILD(tree, 0)) &&
validate_dotted_name(CHILD(tree, 1)) &&
validate_newline(RCHILD(tree, -1)));
if (ok && nch != 3) {
ok = (validate_lparen(CHILD(tree, 2)) &&
validate_rparen(RCHILD(tree, -2)));
ok = (validate_lparen(CHILD(tree, 2)) &&
validate_rparen(RCHILD(tree, -2)));
if (ok && nch == 6)
ok = validate_arglist(CHILD(tree, 3));
if (ok && nch == 6)
ok = validate_arglist(CHILD(tree, 3));
}
return ok;
@ -2443,7 +2443,7 @@ validate_decorators(node *tree)
ok = validate_ntype(tree, decorators) && nch >= 1;
for (i = 0; ok && i < nch; ++i)
ok = validate_decorator(CHILD(tree, i));
ok = validate_decorator(CHILD(tree, i));
return ok;
}
@ -2458,7 +2458,7 @@ validate_with_item(node *tree)
int ok = (validate_ntype(tree, with_item)
&& (nch == 1 || nch == 3)
&& validate_test(CHILD(tree, 0)));
if (ok && nch == 3)
if (ok && nch == 3)
ok = (validate_name(CHILD(tree, 1), "as")
&& validate_expr(CHILD(tree, 2)));
return ok;
@ -2493,12 +2493,12 @@ validate_funcdef(node *tree)
{
int nch = NCH(tree);
int ok = (validate_ntype(tree, funcdef)
&& (nch == 5)
&& validate_name(RCHILD(tree, -5), "def")
&& validate_ntype(RCHILD(tree, -4), NAME)
&& validate_colon(RCHILD(tree, -2))
&& validate_parameters(RCHILD(tree, -3))
&& validate_suite(RCHILD(tree, -1)));
&& (nch == 5)
&& validate_name(RCHILD(tree, -5), "def")
&& validate_ntype(RCHILD(tree, -4), NAME)
&& validate_colon(RCHILD(tree, -2))
&& validate_parameters(RCHILD(tree, -3))
&& validate_suite(RCHILD(tree, -1)));
return ok;
}
@ -2511,11 +2511,11 @@ validate_decorated(node *tree)
{
int nch = NCH(tree);
int ok = (validate_ntype(tree, decorated)
&& (nch == 2)
&& validate_decorators(RCHILD(tree, -2))
&& (validate_funcdef(RCHILD(tree, -1))
|| validate_class(RCHILD(tree, -1)))
);
&& (nch == 2)
&& validate_decorators(RCHILD(tree, -2))
&& (validate_funcdef(RCHILD(tree, -1))
|| validate_class(RCHILD(tree, -1)))
);
return ok;
}
@ -2882,9 +2882,9 @@ validate_node(node *tree)
case classdef:
res = validate_class(tree);
break;
case decorated:
res = validate_decorated(tree);
break;
case decorated:
res = validate_decorated(tree);
break;
/*
* "Trivial" parse tree nodes.
* (Why did I call these trivial?)
@ -2953,12 +2953,12 @@ validate_node(node *tree)
case import_stmt:
res = validate_import_stmt(tree);
break;
case import_name:
res = validate_import_name(tree);
break;
case import_from:
res = validate_import_from(tree);
break;
case import_name:
res = validate_import_name(tree);
break;
case import_from:
res = validate_import_from(tree);
break;
case global_stmt:
res = validate_global_stmt(tree);
break;
@ -3170,15 +3170,15 @@ static PyMethodDef parser_functions[] = {
static struct PyModuleDef parsermodule = {
PyModuleDef_HEAD_INIT,
"parser",
NULL,
-1,
parser_functions,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"parser",
NULL,
-1,
parser_functions,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_parser(void); /* supply a prototype */
@ -3192,7 +3192,7 @@ PyInit_parser(void)
return NULL;
module = PyModule_Create(&parsermodule);
if (module == NULL)
return NULL;
return NULL;
if (parser_error == 0)
parser_error = PyErr_NewException("parser.ParserError", NULL, NULL);

View file

@ -8,14 +8,14 @@
#include <pwd.h>
static PyStructSequence_Field struct_pwd_type_fields[] = {
{"pw_name", "user name"},
{"pw_passwd", "password"},
{"pw_uid", "user id"},
{"pw_gid", "group id"},
{"pw_gecos", "real name"},
{"pw_dir", "home directory"},
{"pw_shell", "shell program"},
{0}
{"pw_name", "user name"},
{"pw_passwd", "password"},
{"pw_uid", "user id"},
{"pw_gid", "group id"},
{"pw_gecos", "real name"},
{"pw_dir", "home directory"},
{"pw_shell", "shell program"},
{0}
};
PyDoc_STRVAR(struct_passwd__doc__,
@ -25,10 +25,10 @@ This object may be accessed either as a tuple of\n\
or via the object attributes as named in the above tuple.");
static PyStructSequence_Desc struct_pwd_type_desc = {
"pwd.struct_passwd",
struct_passwd__doc__,
struct_pwd_type_fields,
7,
"pwd.struct_passwd",
struct_passwd__doc__,
struct_pwd_type_fields,
7,
};
PyDoc_STRVAR(pwd__doc__,
@ -41,7 +41,7 @@ pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell.\n\
The uid and gid items are integers, all others are strings. An\n\
exception is raised if the entry asked for cannot be found.");
static int initialized;
static PyTypeObject StructPwdType;
@ -49,51 +49,51 @@ static void
sets(PyObject *v, int i, const char* val)
{
if (val) {
PyObject *o = PyUnicode_DecodeFSDefault(val);
PyStructSequence_SET_ITEM(v, i, o);
PyObject *o = PyUnicode_DecodeFSDefault(val);
PyStructSequence_SET_ITEM(v, i, o);
}
else {
PyStructSequence_SET_ITEM(v, i, Py_None);
Py_INCREF(Py_None);
PyStructSequence_SET_ITEM(v, i, Py_None);
Py_INCREF(Py_None);
}
}
static PyObject *
mkpwent(struct passwd *p)
{
int setIndex = 0;
PyObject *v = PyStructSequence_New(&StructPwdType);
if (v == NULL)
return NULL;
int setIndex = 0;
PyObject *v = PyStructSequence_New(&StructPwdType);
if (v == NULL)
return NULL;
#define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
#define SETS(i,val) sets(v, i, val)
SETS(setIndex++, p->pw_name);
SETS(setIndex++, p->pw_name);
#ifdef __VMS
SETS(setIndex++, "");
SETS(setIndex++, "");
#else
SETS(setIndex++, p->pw_passwd);
SETS(setIndex++, p->pw_passwd);
#endif
SETI(setIndex++, p->pw_uid);
SETI(setIndex++, p->pw_gid);
SETI(setIndex++, p->pw_uid);
SETI(setIndex++, p->pw_gid);
#ifdef __VMS
SETS(setIndex++, "");
SETS(setIndex++, "");
#else
SETS(setIndex++, p->pw_gecos);
SETS(setIndex++, p->pw_gecos);
#endif
SETS(setIndex++, p->pw_dir);
SETS(setIndex++, p->pw_shell);
SETS(setIndex++, p->pw_dir);
SETS(setIndex++, p->pw_shell);
#undef SETS
#undef SETI
if (PyErr_Occurred()) {
Py_XDECREF(v);
return NULL;
}
if (PyErr_Occurred()) {
Py_XDECREF(v);
return NULL;
}
return v;
return v;
}
PyDoc_STRVAR(pwd_getpwuid__doc__,
@ -105,16 +105,16 @@ See pwd.__doc__ for more on password database entries.");
static PyObject *
pwd_getpwuid(PyObject *self, PyObject *args)
{
unsigned int uid;
struct passwd *p;
if (!PyArg_ParseTuple(args, "I:getpwuid", &uid))
return NULL;
if ((p = getpwuid(uid)) == NULL) {
PyErr_Format(PyExc_KeyError,
"getpwuid(): uid not found: %d", uid);
return NULL;
}
return mkpwent(p);
unsigned int uid;
struct passwd *p;
if (!PyArg_ParseTuple(args, "I:getpwuid", &uid))
return NULL;
if ((p = getpwuid(uid)) == NULL) {
PyErr_Format(PyExc_KeyError,
"getpwuid(): uid not found: %d", uid);
return NULL;
}
return mkpwent(p);
}
PyDoc_STRVAR(pwd_getpwnam__doc__,
@ -126,27 +126,27 @@ See pwd.__doc__ for more on password database entries.");
static PyObject *
pwd_getpwnam(PyObject *self, PyObject *args)
{
char *name;
struct passwd *p;
PyObject *arg, *bytes, *retval = NULL;
char *name;
struct passwd *p;
PyObject *arg, *bytes, *retval = NULL;
if (!PyArg_ParseTuple(args, "U:getpwnam", &arg))
return NULL;
if ((bytes = PyUnicode_AsEncodedString(arg,
Py_FileSystemDefaultEncoding,
"surrogateescape")) == NULL)
return NULL;
if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1)
goto out;
if ((p = getpwnam(name)) == NULL) {
PyErr_Format(PyExc_KeyError,
"getpwnam(): name not found: %s", name);
goto out;
}
retval = mkpwent(p);
if (!PyArg_ParseTuple(args, "U:getpwnam", &arg))
return NULL;
if ((bytes = PyUnicode_AsEncodedString(arg,
Py_FileSystemDefaultEncoding,
"surrogateescape")) == NULL)
return NULL;
if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1)
goto out;
if ((p = getpwnam(name)) == NULL) {
PyErr_Format(PyExc_KeyError,
"getpwnam(): name not found: %s", name);
goto out;
}
retval = mkpwent(p);
out:
Py_DECREF(bytes);
return retval;
Py_DECREF(bytes);
return retval;
}
#ifdef HAVE_GETPWENT
@ -159,67 +159,67 @@ See pwd.__doc__ for more on password database entries.");
static PyObject *
pwd_getpwall(PyObject *self)
{
PyObject *d;
struct passwd *p;
if ((d = PyList_New(0)) == NULL)
return NULL;
PyObject *d;
struct passwd *p;
if ((d = PyList_New(0)) == NULL)
return NULL;
#if defined(PYOS_OS2) && defined(PYCC_GCC)
if ((p = getpwuid(0)) != NULL) {
if ((p = getpwuid(0)) != NULL) {
#else
setpwent();
while ((p = getpwent()) != NULL) {
setpwent();
while ((p = getpwent()) != NULL) {
#endif
PyObject *v = mkpwent(p);
if (v == NULL || PyList_Append(d, v) != 0) {
Py_XDECREF(v);
Py_DECREF(d);
endpwent();
return NULL;
}
Py_DECREF(v);
}
endpwent();
return d;
PyObject *v = mkpwent(p);
if (v == NULL || PyList_Append(d, v) != 0) {
Py_XDECREF(v);
Py_DECREF(d);
endpwent();
return NULL;
}
Py_DECREF(v);
}
endpwent();
return d;
}
#endif
static PyMethodDef pwd_methods[] = {
{"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__},
{"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__},
{"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__},
{"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__},
#ifdef HAVE_GETPWENT
{"getpwall", (PyCFunction)pwd_getpwall,
METH_NOARGS, pwd_getpwall__doc__},
{"getpwall", (PyCFunction)pwd_getpwall,
METH_NOARGS, pwd_getpwall__doc__},
#endif
{NULL, NULL} /* sentinel */
{NULL, NULL} /* sentinel */
};
static struct PyModuleDef pwdmodule = {
PyModuleDef_HEAD_INIT,
"pwd",
pwd__doc__,
-1,
pwd_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"pwd",
pwd__doc__,
-1,
pwd_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_pwd(void)
{
PyObject *m;
m = PyModule_Create(&pwdmodule);
if (m == NULL)
return NULL;
PyObject *m;
m = PyModule_Create(&pwdmodule);
if (m == NULL)
return NULL;
if (!initialized) {
PyStructSequence_InitType(&StructPwdType,
&struct_pwd_type_desc);
initialized = 1;
}
Py_INCREF((PyObject *) &StructPwdType);
PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType);
return m;
if (!initialized) {
PyStructSequence_InitType(&StructPwdType,
&struct_pwd_type_desc);
initialized = 1;
}
Py_INCREF((PyObject *) &StructPwdType);
PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType);
return m;
}

View file

@ -193,7 +193,7 @@ error_external_entity_ref_handler(XML_Parser parser,
used only from the character data handler trampoline, and must be
used right after `flag_error()` is called. */
static void
noop_character_data_handler(void *userData, const XML_Char *data, int len)
noop_character_data_handler(void *userData, const XML_Char *data, int len)
{
/* Do nothing. */
}
@ -222,25 +222,25 @@ trace_frame(PyThreadState *tstate, PyFrameObject *f, int code, PyObject *val)
{
int result = 0;
if (!tstate->use_tracing || tstate->tracing)
return 0;
return 0;
if (tstate->c_profilefunc != NULL) {
tstate->tracing++;
result = tstate->c_profilefunc(tstate->c_profileobj,
f, code , val);
tstate->use_tracing = ((tstate->c_tracefunc != NULL)
|| (tstate->c_profilefunc != NULL));
tstate->tracing--;
if (result)
return result;
tstate->tracing++;
result = tstate->c_profilefunc(tstate->c_profileobj,
f, code , val);
tstate->use_tracing = ((tstate->c_tracefunc != NULL)
|| (tstate->c_profilefunc != NULL));
tstate->tracing--;
if (result)
return result;
}
if (tstate->c_tracefunc != NULL) {
tstate->tracing++;
result = tstate->c_tracefunc(tstate->c_traceobj,
f, code , val);
tstate->use_tracing = ((tstate->c_tracefunc != NULL)
|| (tstate->c_profilefunc != NULL));
tstate->tracing--;
}
tstate->tracing++;
result = tstate->c_tracefunc(tstate->c_traceobj,
f, code , val);
tstate->use_tracing = ((tstate->c_tracefunc != NULL)
|| (tstate->c_profilefunc != NULL));
tstate->tracing--;
}
return result;
}
@ -251,12 +251,12 @@ trace_frame_exc(PyThreadState *tstate, PyFrameObject *f)
int err;
if (tstate->c_tracefunc == NULL)
return 0;
return 0;
PyErr_Fetch(&type, &value, &traceback);
if (value == NULL) {
value = Py_None;
Py_INCREF(value);
value = Py_None;
Py_INCREF(value);
}
#if PY_VERSION_HEX < 0x02040000
arg = Py_BuildValue("(OOO)", type, value, traceback);
@ -264,17 +264,17 @@ trace_frame_exc(PyThreadState *tstate, PyFrameObject *f)
arg = PyTuple_Pack(3, type, value, traceback);
#endif
if (arg == NULL) {
PyErr_Restore(type, value, traceback);
return 0;
PyErr_Restore(type, value, traceback);
return 0;
}
err = trace_frame(tstate, f, PyTrace_EXCEPTION, arg);
Py_DECREF(arg);
if (err == 0)
PyErr_Restore(type, value, traceback);
PyErr_Restore(type, value, traceback);
else {
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(traceback);
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(traceback);
}
return err;
}
@ -290,31 +290,31 @@ call_with_frame(PyCodeObject *c, PyObject* func, PyObject* args,
if (c == NULL)
return NULL;
f = PyFrame_New(tstate, c, PyEval_GetGlobals(), NULL);
if (f == NULL)
return NULL;
tstate->frame = f;
#ifdef FIX_TRACE
if (trace_frame(tstate, f, PyTrace_CALL, Py_None) < 0) {
return NULL;
return NULL;
}
#endif
res = PyEval_CallObject(func, args);
if (res == NULL) {
if (tstate->curexc_traceback == NULL)
PyTraceBack_Here(f);
if (tstate->curexc_traceback == NULL)
PyTraceBack_Here(f);
XML_StopParser(self->itself, XML_FALSE);
#ifdef FIX_TRACE
if (trace_frame_exc(tstate, f) < 0) {
return NULL;
}
if (trace_frame_exc(tstate, f) < 0) {
return NULL;
}
}
else {
if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) {
Py_XDECREF(res);
res = NULL;
}
if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) {
Py_XDECREF(res);
res = NULL;
}
}
#else
}
@ -331,12 +331,12 @@ string_intern(xmlparseobject *self, const char* str)
PyObject *value;
/* result can be NULL if the unicode conversion failed. */
if (!result)
return result;
return result;
if (!self->intern)
return result;
return result;
value = PyDict_GetItem(self->intern, result);
if (!value) {
if (PyDict_SetItem(self->intern, result, result) == 0)
if (PyDict_SetItem(self->intern, result, result) == 0)
return result;
else
return NULL;
@ -396,7 +396,7 @@ flush_character_buffer(xmlparseobject *self)
}
static void
my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
{
xmlparseobject *self = (xmlparseobject *) userData;
if (self->buffer == NULL)
@ -536,13 +536,13 @@ my_##NAME##Handler PARAMS {\
}
#define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \
RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\
(xmlparseobject *)userData)
RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\
(xmlparseobject *)userData)
#define INT_HANDLER(NAME, PARAMS, PARAM_FORMAT)\
RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \
rc = PyLong_AsLong(rv);, rc, \
(xmlparseobject *)userData)
RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \
rc = PyLong_AsLong(rv);, rc, \
(xmlparseobject *)userData)
VOID_HANDLER(EndElement,
(void *userData, const XML_Char *name),
@ -687,25 +687,25 @@ VOID_HANDLER(SkippedEntity,
#endif
VOID_HANDLER(NotationDecl,
(void *userData,
const XML_Char *notationName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId),
(void *userData,
const XML_Char *notationName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId),
("(NNNN)",
string_intern(self, notationName), string_intern(self, base),
string_intern(self, systemId), string_intern(self, publicId)))
string_intern(self, notationName), string_intern(self, base),
string_intern(self, systemId), string_intern(self, publicId)))
VOID_HANDLER(StartNamespaceDecl,
(void *userData,
const XML_Char *prefix,
const XML_Char *uri),
(void *userData,
const XML_Char *prefix,
const XML_Char *uri),
("(NN)",
string_intern(self, prefix), string_intern(self, uri)))
VOID_HANDLER(EndNamespaceDecl,
(void *userData,
const XML_Char *prefix),
(void *userData,
const XML_Char *prefix),
("(N)", string_intern(self, prefix)))
VOID_HANDLER(Comment,
@ -714,36 +714,36 @@ VOID_HANDLER(Comment,
VOID_HANDLER(StartCdataSection,
(void *userData),
("()"))
("()"))
VOID_HANDLER(EndCdataSection,
(void *userData),
("()"))
("()"))
VOID_HANDLER(Default,
(void *userData, const XML_Char *s, int len),
("(N)", (conv_string_len_to_unicode(s,len))))
(void *userData, const XML_Char *s, int len),
("(N)", (conv_string_len_to_unicode(s,len))))
VOID_HANDLER(DefaultHandlerExpand,
(void *userData, const XML_Char *s, int len),
("(N)", (conv_string_len_to_unicode(s,len))))
(void *userData, const XML_Char *s, int len),
("(N)", (conv_string_len_to_unicode(s,len))))
INT_HANDLER(NotStandalone,
(void *userData),
("()"))
(void *userData),
("()"))
RC_HANDLER(int, ExternalEntityRef,
(XML_Parser parser,
const XML_Char *context,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId),
int rc=0;,
(XML_Parser parser,
const XML_Char *context,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId),
int rc=0;,
("(O&NNN)",
conv_string_to_unicode ,context, string_intern(self, base),
string_intern(self, systemId), string_intern(self, publicId)),
rc = PyLong_AsLong(rv);, rc,
XML_GetUserData(parser))
conv_string_to_unicode ,context, string_intern(self, base),
string_intern(self, systemId), string_intern(self, publicId)),
rc = PyLong_AsLong(rv);, rc,
XML_GetUserData(parser))
/* XXX UnknownEncodingHandler */
@ -915,7 +915,7 @@ xmlparse_SetBase(xmlparseobject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "s:SetBase", &base))
return NULL;
if (!XML_SetBase(self->itself, base)) {
return PyErr_NoMemory();
return PyErr_NoMemory();
}
Py_INCREF(Py_None);
return Py_None;
@ -1005,7 +1005,7 @@ xmlparse_ExternalEntityParserCreate(xmlparseobject *self, PyObject *args)
new_parser->in_callback = 0;
new_parser->ns_prefixes = self->ns_prefixes;
new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context,
encoding);
encoding);
new_parser->handlers = 0;
new_parser->intern = self->intern;
Py_XINCREF(new_parser->intern);
@ -1096,26 +1096,26 @@ xmlparse_UseForeignDTD(xmlparseobject *self, PyObject *args)
static PyObject *xmlparse_dir(PyObject *self, PyObject* noargs);
static struct PyMethodDef xmlparse_methods[] = {
{"Parse", (PyCFunction)xmlparse_Parse,
METH_VARARGS, xmlparse_Parse__doc__},
{"Parse", (PyCFunction)xmlparse_Parse,
METH_VARARGS, xmlparse_Parse__doc__},
{"ParseFile", (PyCFunction)xmlparse_ParseFile,
METH_O, xmlparse_ParseFile__doc__},
METH_O, xmlparse_ParseFile__doc__},
{"SetBase", (PyCFunction)xmlparse_SetBase,
METH_VARARGS, xmlparse_SetBase__doc__},
METH_VARARGS, xmlparse_SetBase__doc__},
{"GetBase", (PyCFunction)xmlparse_GetBase,
METH_NOARGS, xmlparse_GetBase__doc__},
METH_NOARGS, xmlparse_GetBase__doc__},
{"ExternalEntityParserCreate", (PyCFunction)xmlparse_ExternalEntityParserCreate,
METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__},
METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__},
{"SetParamEntityParsing", (PyCFunction)xmlparse_SetParamEntityParsing,
METH_VARARGS, xmlparse_SetParamEntityParsing__doc__},
METH_VARARGS, xmlparse_SetParamEntityParsing__doc__},
{"GetInputContext", (PyCFunction)xmlparse_GetInputContext,
METH_NOARGS, xmlparse_GetInputContext__doc__},
METH_NOARGS, xmlparse_GetInputContext__doc__},
#if XML_COMBINED_VERSION >= 19505
{"UseForeignDTD", (PyCFunction)xmlparse_UseForeignDTD,
METH_VARARGS, xmlparse_UseForeignDTD__doc__},
METH_VARARGS, xmlparse_UseForeignDTD__doc__},
#endif
{"__dir__", xmlparse_dir, METH_NOARGS},
{NULL, NULL} /* sentinel */
{NULL, NULL} /* sentinel */
};
/* ---------- */
@ -1133,7 +1133,7 @@ init_template_buffer(void)
{
int i;
for (i = 0; i < 256; i++) {
template_buffer[i] = i;
template_buffer[i] = i;
}
template_buffer[256] = 0;
}
@ -1152,15 +1152,15 @@ PyUnknownEncodingHandler(void *encodingHandlerData,
PyUnicode_Decode(template_buffer, 256, name, "replace");
if (_u_string == NULL)
return result;
return result;
for (i = 0; i < 256; i++) {
/* Stupid to access directly, but fast */
Py_UNICODE c = _u_string->str[i];
if (c == Py_UNICODE_REPLACEMENT_CHARACTER)
info->map[i] = -1;
else
info->map[i] = c;
/* Stupid to access directly, but fast */
Py_UNICODE c = _u_string->str[i];
if (c == Py_UNICODE_REPLACEMENT_CHARACTER)
info->map[i] = -1;
else
info->map[i] = c;
}
info->data = NULL;
info->convert = NULL;
@ -1295,8 +1295,8 @@ xmlparse_getattro(xmlparseobject *self, PyObject *nameobj)
int handlernum = -1;
if (PyUnicode_Check(nameobj))
name = _PyUnicode_AsString(nameobj);
name = _PyUnicode_AsString(nameobj);
handlernum = handlername2int(name);
if (handlernum != -1) {
@ -1362,18 +1362,18 @@ xmlparse_getattro(xmlparseobject *self, PyObject *nameobj)
static PyObject *
xmlparse_dir(PyObject *self, PyObject* noargs)
{
#define APPEND(list, str) \
do { \
PyObject *o = PyUnicode_FromString(str); \
if (o != NULL) \
PyList_Append(list, o); \
Py_XDECREF(o); \
#define APPEND(list, str) \
do { \
PyObject *o = PyUnicode_FromString(str); \
if (o != NULL) \
PyList_Append(list, o); \
Py_XDECREF(o); \
} while (0)
int i;
PyObject *rc = PyList_New(0);
if (!rc)
return NULL;
return NULL;
for (i = 0; handler_info[i].name != NULL; i++) {
PyObject *o = get_handler_name(&handler_info[i]);
if (o != NULL)
@ -1494,42 +1494,42 @@ xmlparse_setattr(xmlparseobject *self, char *name, PyObject *v)
if (strcmp(name, "buffer_size") == 0) {
long new_buffer_size;
if (!PyLong_Check(v)) {
PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
return -1;
PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
return -1;
}
new_buffer_size=PyLong_AS_LONG(v);
/* trivial case -- no change */
if (new_buffer_size == self->buffer_size) {
return 0;
return 0;
}
if (new_buffer_size <= 0) {
PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero");
return -1;
PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero");
return -1;
}
/* check maximum */
if (new_buffer_size > INT_MAX) {
char errmsg[100];
sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX);
PyErr_SetString(PyExc_ValueError, errmsg);
return -1;
char errmsg[100];
sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX);
PyErr_SetString(PyExc_ValueError, errmsg);
return -1;
}
if (self->buffer != NULL) {
/* there is already a buffer */
if (self->buffer_used != 0) {
flush_character_buffer(self);
}
/* free existing buffer */
free(self->buffer);
/* there is already a buffer */
if (self->buffer_used != 0) {
flush_character_buffer(self);
}
/* free existing buffer */
free(self->buffer);
}
self->buffer = malloc(new_buffer_size);
if (self->buffer == NULL) {
PyErr_NoMemory();
return -1;
}
PyErr_NoMemory();
return -1;
}
self->buffer_size = new_buffer_size;
return 0;
}
@ -1570,39 +1570,39 @@ xmlparse_clear(xmlparseobject *op)
PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser");
static PyTypeObject Xmlparsetype = {
PyVarObject_HEAD_INIT(NULL, 0)
"pyexpat.xmlparser", /*tp_name*/
sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)xmlparse_dealloc, /*tp_dealloc*/
(printfunc)0, /*tp_print*/
0, /*tp_getattr*/
(setattrfunc)xmlparse_setattr, /*tp_setattr*/
0, /*tp_reserved*/
(reprfunc)0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
(hashfunc)0, /*tp_hash*/
(ternaryfunc)0, /*tp_call*/
(reprfunc)0, /*tp_str*/
(getattrofunc)xmlparse_getattro, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
PyVarObject_HEAD_INIT(NULL, 0)
"pyexpat.xmlparser", /*tp_name*/
sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)xmlparse_dealloc, /*tp_dealloc*/
(printfunc)0, /*tp_print*/
0, /*tp_getattr*/
(setattrfunc)xmlparse_setattr, /*tp_setattr*/
0, /*tp_reserved*/
(reprfunc)0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
(hashfunc)0, /*tp_hash*/
(ternaryfunc)0, /*tp_call*/
(reprfunc)0, /*tp_str*/
(getattrofunc)xmlparse_getattro, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
#ifdef Py_TPFLAGS_HAVE_GC
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
#else
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
#endif
Xmlparsetype__doc__, /* tp_doc - Documentation string */
(traverseproc)xmlparse_traverse, /* tp_traverse */
(inquiry)xmlparse_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
xmlparse_methods, /* tp_methods */
Xmlparsetype__doc__, /* tp_doc - Documentation string */
(traverseproc)xmlparse_traverse, /* tp_traverse */
(inquiry)xmlparse_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
xmlparse_methods, /* tp_methods */
};
/* End of code for xmlparser objects */
@ -1636,21 +1636,21 @@ pyexpat_ParserCreate(PyObject *notused, PyObject *args, PyObject *kw)
/* Explicitly passing None means no interning is desired.
Not passing anything means that a new dictionary is used. */
if (intern == Py_None)
intern = NULL;
intern = NULL;
else if (intern == NULL) {
intern = PyDict_New();
if (!intern)
return NULL;
intern_decref = 1;
intern = PyDict_New();
if (!intern)
return NULL;
intern_decref = 1;
}
else if (!PyDict_Check(intern)) {
PyErr_SetString(PyExc_TypeError, "intern must be a dictionary");
return NULL;
PyErr_SetString(PyExc_TypeError, "intern must be a dictionary");
return NULL;
}
result = newxmlparseobject(encoding, namespace_separator, intern);
if (intern_decref) {
Py_DECREF(intern);
Py_DECREF(intern);
}
return result;
}
@ -1672,12 +1672,12 @@ pyexpat_ErrorString(PyObject *self, PyObject *args)
/* List of methods defined in the module */
static struct PyMethodDef pyexpat_methods[] = {
{"ParserCreate", (PyCFunction)pyexpat_ParserCreate,
{"ParserCreate", (PyCFunction)pyexpat_ParserCreate,
METH_VARARGS|METH_KEYWORDS, pyexpat_ParserCreate__doc__},
{"ErrorString", (PyCFunction)pyexpat_ErrorString,
METH_VARARGS, pyexpat_ErrorString__doc__},
{"ErrorString", (PyCFunction)pyexpat_ErrorString,
METH_VARARGS, pyexpat_ErrorString__doc__},
{NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
{NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
};
/* Module docstring */
@ -1726,15 +1726,15 @@ get_version_string(void)
PyMODINIT_FUNC MODULE_INITFUNC(void); /* avoid compiler warnings */
static struct PyModuleDef pyexpatmodule = {
PyModuleDef_HEAD_INIT,
MODULE_NAME,
pyexpat_module_documentation,
-1,
pyexpat_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
MODULE_NAME,
pyexpat_module_documentation,
-1,
pyexpat_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
@ -1756,12 +1756,12 @@ MODULE_INITFUNC(void)
return NULL;
if (PyType_Ready(&Xmlparsetype) < 0)
return NULL;
return NULL;
/* Create the module and add the functions */
m = PyModule_Create(&pyexpatmodule);
if (m == NULL)
return NULL;
return NULL;
/* Add some symbolic constants to the module */
if (ErrorObject == NULL) {
@ -1818,7 +1818,7 @@ MODULE_INITFUNC(void)
if (errors_module == NULL || model_module == NULL)
/* Don't core dump later! */
return NULL;
#if XML_COMBINED_VERSION > 19505
{
const XML_Feature *features = XML_GetFeatureList();
@ -1943,7 +1943,7 @@ MODULE_INITFUNC(void)
capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler;
capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler;
capi.SetUserData = XML_SetUserData;
/* export using capsule */
capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL);
if (capi_object)
@ -1959,12 +1959,12 @@ clear_handlers(xmlparseobject *self, int initial)
for (; handler_info[i].name != NULL; i++) {
if (initial)
self->handlers[i] = NULL;
else {
self->handlers[i] = NULL;
else {
temp = self->handlers[i];
self->handlers[i] = NULL;
Py_XDECREF(temp);
handler_info[i].setter(self->itself, NULL);
handler_info[i].setter(self->itself, NULL);
}
}
}

View file

@ -11,48 +11,48 @@
int
wmain(int argc, wchar_t **argv)
{
return Py_Main(argc, argv);
return Py_Main(argc, argv);
}
#else
int
main(int argc, char **argv)
{
wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
/* We need a second copies, as Python might modify the first one. */
wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
int i, res;
char *oldloc;
/* 754 requires that FP exceptions run in "no stop" mode by default,
* and until C vendors implement C99's ways to control FP exceptions,
* Python requires non-stop mode. Alas, some platforms enable FP
* exceptions by default. Here we disable them.
*/
wchar_t **argv_copy = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
/* We need a second copies, as Python might modify the first one. */
wchar_t **argv_copy2 = (wchar_t **)PyMem_Malloc(sizeof(wchar_t*)*argc);
int i, res;
char *oldloc;
/* 754 requires that FP exceptions run in "no stop" mode by default,
* and until C vendors implement C99's ways to control FP exceptions,
* Python requires non-stop mode. Alas, some platforms enable FP
* exceptions by default. Here we disable them.
*/
#ifdef __FreeBSD__
fp_except_t m;
fp_except_t m;
m = fpgetmask();
fpsetmask(m & ~FP_X_OFL);
m = fpgetmask();
fpsetmask(m & ~FP_X_OFL);
#endif
if (!argv_copy || !argv_copy2) {
fprintf(stderr, "out of memory\n");
return 1;
}
oldloc = strdup(setlocale(LC_ALL, NULL));
setlocale(LC_ALL, "");
for (i = 0; i < argc; i++) {
argv_copy2[i] = argv_copy[i] = _Py_char2wchar(argv[i]);
if (!argv_copy[i])
return 1;
}
setlocale(LC_ALL, oldloc);
free(oldloc);
res = Py_Main(argc, argv_copy);
for (i = 0; i < argc; i++) {
PyMem_Free(argv_copy2[i]);
}
PyMem_Free(argv_copy);
PyMem_Free(argv_copy2);
return res;
if (!argv_copy || !argv_copy2) {
fprintf(stderr, "out of memory\n");
return 1;
}
oldloc = strdup(setlocale(LC_ALL, NULL));
setlocale(LC_ALL, "");
for (i = 0; i < argc; i++) {
argv_copy2[i] = argv_copy[i] = _Py_char2wchar(argv[i]);
if (!argv_copy[i])
return 1;
}
setlocale(LC_ALL, oldloc);
free(oldloc);
res = Py_Main(argc, argv_copy);
for (i = 0; i < argc; i++) {
PyMem_Free(argv_copy2[i]);
}
PyMem_Free(argv_copy);
PyMem_Free(argv_copy2);
return res;
}
#endif

File diff suppressed because it is too large Load diff

View file

@ -29,30 +29,30 @@ PyDoc_STRVAR(struct_rusage__doc__,
"or via the attributes ru_utime, ru_stime, ru_maxrss, and so on.");
static PyStructSequence_Field struct_rusage_fields[] = {
{"ru_utime", "user time used"},
{"ru_stime", "system time used"},
{"ru_maxrss", "max. resident set size"},
{"ru_ixrss", "shared memory size"},
{"ru_idrss", "unshared data size"},
{"ru_isrss", "unshared stack size"},
{"ru_minflt", "page faults not requiring I/O"},
{"ru_majflt", "page faults requiring I/O"},
{"ru_nswap", "number of swap outs"},
{"ru_inblock", "block input operations"},
{"ru_oublock", "block output operations"},
{"ru_msgsnd", "IPC messages sent"},
{"ru_msgrcv", "IPC messages received"},
{"ru_nsignals", "signals received"},
{"ru_nvcsw", "voluntary context switches"},
{"ru_nivcsw", "involuntary context switches"},
{0}
{"ru_utime", "user time used"},
{"ru_stime", "system time used"},
{"ru_maxrss", "max. resident set size"},
{"ru_ixrss", "shared memory size"},
{"ru_idrss", "unshared data size"},
{"ru_isrss", "unshared stack size"},
{"ru_minflt", "page faults not requiring I/O"},
{"ru_majflt", "page faults requiring I/O"},
{"ru_nswap", "number of swap outs"},
{"ru_inblock", "block input operations"},
{"ru_oublock", "block output operations"},
{"ru_msgsnd", "IPC messages sent"},
{"ru_msgrcv", "IPC messages received"},
{"ru_nsignals", "signals received"},
{"ru_nvcsw", "voluntary context switches"},
{"ru_nivcsw", "involuntary context switches"},
{0}
};
static PyStructSequence_Desc struct_rusage_desc = {
"resource.struct_rusage", /* name */
struct_rusage__doc__, /* doc */
struct_rusage_fields, /* fields */
16 /* n_in_sequence */
"resource.struct_rusage", /* name */
struct_rusage__doc__, /* doc */
struct_rusage_fields, /* fields */
16 /* n_in_sequence */
};
static int initialized;
@ -61,151 +61,151 @@ static PyTypeObject StructRUsageType;
static PyObject *
resource_getrusage(PyObject *self, PyObject *args)
{
int who;
struct rusage ru;
PyObject *result;
int who;
struct rusage ru;
PyObject *result;
if (!PyArg_ParseTuple(args, "i:getrusage", &who))
return NULL;
if (!PyArg_ParseTuple(args, "i:getrusage", &who))
return NULL;
if (getrusage(who, &ru) == -1) {
if (errno == EINVAL) {
PyErr_SetString(PyExc_ValueError,
"invalid who parameter");
return NULL;
}
PyErr_SetFromErrno(ResourceError);
return NULL;
}
if (getrusage(who, &ru) == -1) {
if (errno == EINVAL) {
PyErr_SetString(PyExc_ValueError,
"invalid who parameter");
return NULL;
}
PyErr_SetFromErrno(ResourceError);
return NULL;
}
result = PyStructSequence_New(&StructRUsageType);
if (!result)
return NULL;
result = PyStructSequence_New(&StructRUsageType);
if (!result)
return NULL;
PyStructSequence_SET_ITEM(result, 0,
PyFloat_FromDouble(doubletime(ru.ru_utime)));
PyStructSequence_SET_ITEM(result, 1,
PyFloat_FromDouble(doubletime(ru.ru_stime)));
PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(ru.ru_maxrss));
PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(ru.ru_ixrss));
PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(ru.ru_idrss));
PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(ru.ru_isrss));
PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(ru.ru_minflt));
PyStructSequence_SET_ITEM(result, 7, PyLong_FromLong(ru.ru_majflt));
PyStructSequence_SET_ITEM(result, 8, PyLong_FromLong(ru.ru_nswap));
PyStructSequence_SET_ITEM(result, 9, PyLong_FromLong(ru.ru_inblock));
PyStructSequence_SET_ITEM(result, 10, PyLong_FromLong(ru.ru_oublock));
PyStructSequence_SET_ITEM(result, 11, PyLong_FromLong(ru.ru_msgsnd));
PyStructSequence_SET_ITEM(result, 12, PyLong_FromLong(ru.ru_msgrcv));
PyStructSequence_SET_ITEM(result, 13, PyLong_FromLong(ru.ru_nsignals));
PyStructSequence_SET_ITEM(result, 14, PyLong_FromLong(ru.ru_nvcsw));
PyStructSequence_SET_ITEM(result, 15, PyLong_FromLong(ru.ru_nivcsw));
PyStructSequence_SET_ITEM(result, 0,
PyFloat_FromDouble(doubletime(ru.ru_utime)));
PyStructSequence_SET_ITEM(result, 1,
PyFloat_FromDouble(doubletime(ru.ru_stime)));
PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(ru.ru_maxrss));
PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(ru.ru_ixrss));
PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(ru.ru_idrss));
PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(ru.ru_isrss));
PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(ru.ru_minflt));
PyStructSequence_SET_ITEM(result, 7, PyLong_FromLong(ru.ru_majflt));
PyStructSequence_SET_ITEM(result, 8, PyLong_FromLong(ru.ru_nswap));
PyStructSequence_SET_ITEM(result, 9, PyLong_FromLong(ru.ru_inblock));
PyStructSequence_SET_ITEM(result, 10, PyLong_FromLong(ru.ru_oublock));
PyStructSequence_SET_ITEM(result, 11, PyLong_FromLong(ru.ru_msgsnd));
PyStructSequence_SET_ITEM(result, 12, PyLong_FromLong(ru.ru_msgrcv));
PyStructSequence_SET_ITEM(result, 13, PyLong_FromLong(ru.ru_nsignals));
PyStructSequence_SET_ITEM(result, 14, PyLong_FromLong(ru.ru_nvcsw));
PyStructSequence_SET_ITEM(result, 15, PyLong_FromLong(ru.ru_nivcsw));
if (PyErr_Occurred()) {
Py_DECREF(result);
return NULL;
}
if (PyErr_Occurred()) {
Py_DECREF(result);
return NULL;
}
return result;
return result;
}
static PyObject *
resource_getrlimit(PyObject *self, PyObject *args)
{
struct rlimit rl;
int resource;
struct rlimit rl;
int resource;
if (!PyArg_ParseTuple(args, "i:getrlimit", &resource))
return NULL;
if (!PyArg_ParseTuple(args, "i:getrlimit", &resource))
return NULL;
if (resource < 0 || resource >= RLIM_NLIMITS) {
PyErr_SetString(PyExc_ValueError,
"invalid resource specified");
return NULL;
}
if (resource < 0 || resource >= RLIM_NLIMITS) {
PyErr_SetString(PyExc_ValueError,
"invalid resource specified");
return NULL;
}
if (getrlimit(resource, &rl) == -1) {
PyErr_SetFromErrno(ResourceError);
return NULL;
}
if (getrlimit(resource, &rl) == -1) {
PyErr_SetFromErrno(ResourceError);
return NULL;
}
#if defined(HAVE_LONG_LONG)
if (sizeof(rl.rlim_cur) > sizeof(long)) {
return Py_BuildValue("LL",
(PY_LONG_LONG) rl.rlim_cur,
(PY_LONG_LONG) rl.rlim_max);
}
if (sizeof(rl.rlim_cur) > sizeof(long)) {
return Py_BuildValue("LL",
(PY_LONG_LONG) rl.rlim_cur,
(PY_LONG_LONG) rl.rlim_max);
}
#endif
return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max);
return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max);
}
static PyObject *
resource_setrlimit(PyObject *self, PyObject *args)
{
struct rlimit rl;
int resource;
PyObject *curobj, *maxobj;
struct rlimit rl;
int resource;
PyObject *curobj, *maxobj;
if (!PyArg_ParseTuple(args, "i(OO):setrlimit",
&resource, &curobj, &maxobj))
return NULL;
if (!PyArg_ParseTuple(args, "i(OO):setrlimit",
&resource, &curobj, &maxobj))
return NULL;
if (resource < 0 || resource >= RLIM_NLIMITS) {
PyErr_SetString(PyExc_ValueError,
"invalid resource specified");
return NULL;
}
if (resource < 0 || resource >= RLIM_NLIMITS) {
PyErr_SetString(PyExc_ValueError,
"invalid resource specified");
return NULL;
}
#if !defined(HAVE_LARGEFILE_SUPPORT)
rl.rlim_cur = PyLong_AsLong(curobj);
if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
return NULL;
rl.rlim_max = PyLong_AsLong(maxobj);
if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
return NULL;
rl.rlim_cur = PyLong_AsLong(curobj);
if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
return NULL;
rl.rlim_max = PyLong_AsLong(maxobj);
if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
return NULL;
#else
/* The limits are probably bigger than a long */
rl.rlim_cur = PyLong_AsLongLong(curobj);
if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
return NULL;
rl.rlim_max = PyLong_AsLongLong(maxobj);
if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
return NULL;
/* The limits are probably bigger than a long */
rl.rlim_cur = PyLong_AsLongLong(curobj);
if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
return NULL;
rl.rlim_max = PyLong_AsLongLong(maxobj);
if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
return NULL;
#endif
rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY;
rl.rlim_max = rl.rlim_max & RLIM_INFINITY;
if (setrlimit(resource, &rl) == -1) {
if (errno == EINVAL)
PyErr_SetString(PyExc_ValueError,
"current limit exceeds maximum limit");
else if (errno == EPERM)
PyErr_SetString(PyExc_ValueError,
"not allowed to raise maximum limit");
else
PyErr_SetFromErrno(ResourceError);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY;
rl.rlim_max = rl.rlim_max & RLIM_INFINITY;
if (setrlimit(resource, &rl) == -1) {
if (errno == EINVAL)
PyErr_SetString(PyExc_ValueError,
"current limit exceeds maximum limit");
else if (errno == EPERM)
PyErr_SetString(PyExc_ValueError,
"not allowed to raise maximum limit");
else
PyErr_SetFromErrno(ResourceError);
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
resource_getpagesize(PyObject *self, PyObject *unused)
{
long pagesize = 0;
long pagesize = 0;
#if defined(HAVE_GETPAGESIZE)
pagesize = getpagesize();
pagesize = getpagesize();
#elif defined(HAVE_SYSCONF)
#if defined(_SC_PAGE_SIZE)
pagesize = sysconf(_SC_PAGE_SIZE);
pagesize = sysconf(_SC_PAGE_SIZE);
#else
/* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */
pagesize = sysconf(_SC_PAGESIZE);
/* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */
pagesize = sysconf(_SC_PAGESIZE);
#endif
#endif
return Py_BuildValue("i", pagesize);
return Py_BuildValue("i", pagesize);
}
@ -213,11 +213,11 @@ resource_getpagesize(PyObject *self, PyObject *unused)
static struct PyMethodDef
resource_methods[] = {
{"getrusage", resource_getrusage, METH_VARARGS},
{"getrlimit", resource_getrlimit, METH_VARARGS},
{"setrlimit", resource_setrlimit, METH_VARARGS},
{"getpagesize", resource_getpagesize, METH_NOARGS},
{NULL, NULL} /* sentinel */
{"getrusage", resource_getrusage, METH_VARARGS},
{"getrlimit", resource_getrlimit, METH_VARARGS},
{"setrlimit", resource_setrlimit, METH_VARARGS},
{"getpagesize", resource_getpagesize, METH_NOARGS},
{NULL, NULL} /* sentinel */
};
@ -225,117 +225,117 @@ resource_methods[] = {
static struct PyModuleDef resourcemodule = {
PyModuleDef_HEAD_INIT,
"resource",
NULL,
-1,
resource_methods,
NULL,
NULL,
NULL,
NULL
PyModuleDef_HEAD_INIT,
"resource",
NULL,
-1,
resource_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_resource(void)
{
PyObject *m, *v;
PyObject *m, *v;
/* Create the module and add the functions */
m = PyModule_Create(&resourcemodule);
if (m == NULL)
return NULL;
/* Create the module and add the functions */
m = PyModule_Create(&resourcemodule);
if (m == NULL)
return NULL;
/* Add some symbolic constants to the module */
if (ResourceError == NULL) {
ResourceError = PyErr_NewException("resource.error",
NULL, NULL);
}
Py_INCREF(ResourceError);
PyModule_AddObject(m, "error", ResourceError);
if (!initialized)
PyStructSequence_InitType(&StructRUsageType,
&struct_rusage_desc);
Py_INCREF(&StructRUsageType);
PyModule_AddObject(m, "struct_rusage",
(PyObject*) &StructRUsageType);
/* Add some symbolic constants to the module */
if (ResourceError == NULL) {
ResourceError = PyErr_NewException("resource.error",
NULL, NULL);
}
Py_INCREF(ResourceError);
PyModule_AddObject(m, "error", ResourceError);
if (!initialized)
PyStructSequence_InitType(&StructRUsageType,
&struct_rusage_desc);
Py_INCREF(&StructRUsageType);
PyModule_AddObject(m, "struct_rusage",
(PyObject*) &StructRUsageType);
/* insert constants */
/* insert constants */
#ifdef RLIMIT_CPU
PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU);
PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU);
#endif
#ifdef RLIMIT_FSIZE
PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE);
PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE);
#endif
#ifdef RLIMIT_DATA
PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA);
PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA);
#endif
#ifdef RLIMIT_STACK
PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK);
PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK);
#endif
#ifdef RLIMIT_CORE
PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE);
PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE);
#endif
#ifdef RLIMIT_NOFILE
PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE);
PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE);
#endif
#ifdef RLIMIT_OFILE
PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE);
PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE);
#endif
#ifdef RLIMIT_VMEM
PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM);
PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM);
#endif
#ifdef RLIMIT_AS
PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS);
PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS);
#endif
#ifdef RLIMIT_RSS
PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS);
PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS);
#endif
#ifdef RLIMIT_NPROC
PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC);
PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC);
#endif
#ifdef RLIMIT_MEMLOCK
PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK);
PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK);
#endif
#ifdef RLIMIT_SBSIZE
PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE);
PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE);
#endif
#ifdef RUSAGE_SELF
PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF);
PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF);
#endif
#ifdef RUSAGE_CHILDREN
PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN);
PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN);
#endif
#ifdef RUSAGE_BOTH
PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH);
PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH);
#endif
#if defined(HAVE_LONG_LONG)
if (sizeof(RLIM_INFINITY) > sizeof(long)) {
v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY);
} else
if (sizeof(RLIM_INFINITY) > sizeof(long)) {
v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY);
} else
#endif
{
v = PyLong_FromLong((long) RLIM_INFINITY);
}
if (v) {
PyModule_AddObject(m, "RLIM_INFINITY", v);
}
initialized = 1;
return m;
{
v = PyLong_FromLong((long) RLIM_INFINITY);
}
if (v) {
PyModule_AddObject(m, "RLIM_INFINITY", v);
}
initialized = 1;
return m;
}

Some files were not shown because too many files have changed in this diff Show more