1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
PC/msvcrtmodule.c
/*********************************************************

    msvcrtmodule.c

    A Python interface to the Microsoft Visual C Runtime
    Library, providing access to those non-portable, but
    still useful routines.

    Only ever compiled with an MS compiler, so no attempt
    has been made to avoid MS language extensions, etc...

    This may only work on NT or 95...

    Author: Mark Hammond and Guido van Rossum.
    Maintenance: Guido van Rossum.

***********************************************************/

#include "Python.h"
#include "malloc.h"
#include <io.h>
#include <conio.h>
#include <sys/locking.h>

#ifdef _MSC_VER
#if _MSC_VER >= 1500 && _MSC_VER < 1600
#include <crtassem.h>
#endif
#endif

// Force the malloc heap to clean itself up, and free unused blocks
// back to the OS.  (According to the docs, only works on NT.)
static PyObject *
msvcrt_heapmin(PyObject *self, PyObject *args)
{
    if (!PyArg_ParseTuple(args, ":heapmin"))
        return NULL;

    if (_heapmin() != 0)
        return PyErr_SetFromErrno(PyExc_IOError);

    Py_INCREF(Py_None);
    return Py_None;
}

PyDoc_STRVAR(heapmin_doc,
"heapmin() -> None\n\
\n\
Force the malloc() heap to clean itself up and return unused blocks\n\
to the operating system. On failure, this raises IOError.");

// Perform locking operations on a C runtime file descriptor.
static PyObject *
msvcrt_locking(PyObject *self, PyObject *args)
{
    int fd;
    int mode;
    long nbytes;
    int err;

    if (!PyArg_ParseTuple(args, "iil:locking", &fd, &mode, &nbytes))
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    err = _locking(fd, mode, nbytes);
    Py_END_ALLOW_THREADS
    if (err != 0)
        return PyErr_SetFromErrno(PyExc_IOError);

    Py_INCREF(Py_None);
    return Py_None;
}

PyDoc_STRVAR(locking_doc,
"locking(fd, mode, nbytes) -> None\n\
\n\
Lock part of a file based on file descriptor fd from the C runtime.\n\
Raises IOError on failure. The locked region of the file extends from\n\
the current file position for nbytes bytes, and may continue beyond\n\
the end of the file. mode must be one of the LK_* constants listed\n\
below. Multiple regions in a file may be locked at the same time, but\n\
may not overlap. Adjacent regions are not merged; they must be unlocked\n\
individually.");

// Set the file translation mode for a C runtime file descriptor.
static PyObject *
msvcrt_setmode(PyObject *self, PyObject *args)
{
    int fd;
    int flags;
    if (!PyArg_ParseTuple(args,"ii:setmode", &fd, &flags))
        return NULL;

    flags = _setmode(fd, flags);
    if (flags == -1)
        return PyErr_SetFromErrno(PyExc_IOError);

    return PyInt_FromLong(flags);
}

PyDoc_STRVAR(setmode_doc,
"setmode(fd, mode) -> Previous mode\n\
\n\
Set the line-end translation mode for the file descriptor fd. To set\n\
it to text mode, flags should be os.O_TEXT; for binary, it should be\n\
os.O_BINARY.");

// Convert an OS file handle to a C runtime file descriptor.
static PyObject *
msvcrt_open_osfhandle(PyObject *self, PyObject *args)
{
    long handle;
    int flags;
    int fd;

    if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags))
        return NULL;

    fd = _open_osfhandle(handle, flags);
    if (fd == -1)
        return PyErr_SetFromErrno(PyExc_IOError);

    return PyInt_FromLong(fd);
}

PyDoc_STRVAR(open_osfhandle_doc,
"open_osfhandle(handle, flags) -> file descriptor\n\
\n\
Create a C runtime file descriptor from the file handle handle. The\n\
flags parameter should be a bitwise OR of os.O_APPEND, os.O_RDONLY,\n\
and os.O_TEXT. The returned file descriptor may be used as a parameter\n\
to os.fdopen() to create a file object.");

// Convert a C runtime file descriptor to an OS file handle.
static PyObject *
msvcrt_get_osfhandle(PyObject *self, PyObject *args)
{
    int fd;
    Py_intptr_t handle;

    if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd))
        return NULL;

    if (!_PyVerify_fd(fd))
        return PyErr_SetFromErrno(PyExc_IOError);

    handle = _get_osfhandle(fd);
    if (handle == -1)
        return PyErr_SetFromErrno(PyExc_IOError);

    /* technically 'handle' is not a pointer, but a integer as
       large as a pointer, Python's *VoidPtr interface is the
       most appropriate here */
    return PyLong_FromVoidPtr((void*)handle);
}

PyDoc_STRVAR(get_osfhandle_doc,
"get_osfhandle(fd) -> file handle\n\
\n\
Return the file handle for the file descriptor fd. Raises IOError\n\
if fd is not recognized.");

/* Console I/O */

static PyObject *
msvcrt_kbhit(PyObject *self, PyObject *args)
{
    int ok;

    if (!PyArg_ParseTuple(args, ":kbhit"))
        return NULL;

    ok = _kbhit();
    return PyInt_FromLong(ok);
}

PyDoc_STRVAR(kbhit_doc,
"kbhit() -> bool\n\
\n\
Return true if a keypress is waiting to be read.");

static PyObject *
msvcrt_getch(PyObject *self, PyObject *args)
{
    int ch;
    char s[1];

    if (!PyArg_ParseTuple(args, ":getch"))
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    ch = _getch();
    Py_END_ALLOW_THREADS
    s[0] = ch;
    return PyString_FromStringAndSize(s, 1);
}

PyDoc_STRVAR(getch_doc,
"getch() -> key character\n\
\n\
Read a keypress and return the resulting character. Nothing is echoed to\n\
the console. This call will block if a keypress is not already\n\
available, but will not wait for Enter to be pressed. If the pressed key\n\
was a special function key, this will return '\\000' or '\\xe0'; the next\n\
call will return the keycode. The Control-C keypress cannot be read with\n\
this function.");

#ifdef _WCONIO_DEFINED
static PyObject *
msvcrt_getwch(PyObject *self, PyObject *args)
{
    Py_UNICODE ch;
    Py_UNICODE u[1];

    if (!PyArg_ParseTuple(args, ":getwch"))
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    ch = _getwch();
    Py_END_ALLOW_THREADS
    u[0] = ch;
    return PyUnicode_FromUnicode(u, 1);
}

PyDoc_STRVAR(getwch_doc,
"getwch() -> Unicode key character\n\
\n\
Wide char variant of getch(), returning a Unicode value.");
#endif

static PyObject *
msvcrt_getche(PyObject *self, PyObject *args)
{
    int ch;
    char s[1];

    if (!PyArg_ParseTuple(args, ":getche"))
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    ch = _getche();
    Py_END_ALLOW_THREADS
    s[0] = ch;
    return PyString_FromStringAndSize(s, 1);
}

PyDoc_STRVAR(getche_doc,
"getche() -> key character\n\
\n\
Similar to getch(), but the keypress will be echoed if it represents\n\
a printable character.");

#ifdef _WCONIO_DEFINED
static PyObject *
msvcrt_getwche(PyObject *self, PyObject *args)
{
    Py_UNICODE ch;
    Py_UNICODE s[1];

    if (!PyArg_ParseTuple(args, ":getwche"))
        return NULL;

    Py_BEGIN_ALLOW_THREADS
    ch = _getwche();
    Py_END_ALLOW_THREADS
    s[0] = ch;
    return PyUnicode_FromUnicode(s, 1);
}

PyDoc_STRVAR(getwche_doc,
"getwche() -> Unicode key character\n\
\n\
Wide char variant of getche(), returning a Unicode value.");
#endif

static PyObject *
msvcrt_putch(PyObject *self, PyObject *args)
{
    char ch;

    if (!PyArg_ParseTuple(args, "c:putch", &ch))
        return NULL;

    _putch(ch);
    Py_INCREF(Py_None);
    return Py_None;
}

PyDoc_STRVAR(putch_doc,
"putch(char) -> None\n\
\n\
Print the character char to the console without buffering.");

#ifdef _WCONIO_DEFINED
static PyObject *
msvcrt_putwch(PyObject *self, PyObject *args)
{
    Py_UNICODE *ch;
    int size;

    if (!PyArg_ParseTuple(args, "u#:putwch", &ch, &size))
        return NULL;

    if (size == 0) {
        PyErr_SetString(PyExc_ValueError,
            "Expected unicode string of length 1");
        return NULL;
    }
    _putwch(*ch);
    Py_RETURN_NONE;

}

PyDoc_STRVAR(putwch_doc,
"putwch(unicode_char) -> None\n\
\n\
Wide char variant of putch(), accepting a Unicode value.");
#endif

static PyObject *
msvcrt_ungetch(PyObject *self, PyObject *args)
{
    char ch;

    if (!PyArg_ParseTuple(args, "c:ungetch", &ch))
        return NULL;

    if (_ungetch(ch) == EOF)
        return PyErr_SetFromErrno(PyExc_IOError);
    Py_INCREF(Py_None);
    return Py_None;
}

PyDoc_STRVAR(ungetch_doc,
"ungetch(char) -> None\n\
\n\
Cause the character char to be \"pushed back\" into the console buffer;\n\
it will be the next character read by getch() or getche().");

#ifdef _WCONIO_DEFINED
static PyObject *
msvcrt_ungetwch(PyObject *self, PyObject *args)
{
    Py_UNICODE ch;

    if (!PyArg_ParseTuple(args, "u:ungetwch", &ch))
        return NULL;

    if (_ungetch(ch) == EOF)
        return PyErr_SetFromErrno(PyExc_IOError);
    Py_INCREF(Py_None);
    return Py_None;
}

PyDoc_STRVAR(ungetwch_doc,
"ungetwch(unicode_char) -> None\n\
\n\
Wide char variant of ungetch(), accepting a Unicode value.");
#endif

static void
insertint(PyObject *d, char *name, int value)
{
    PyObject *v = PyInt_FromLong((long) value);
    if (v == NULL) {
        /* Don't bother reporting this error */
        PyErr_Clear();
    }
    else {
        PyDict_SetItemString(d, name, v);
        Py_DECREF(v);
    }
}


/* List of functions exported by this module */
static struct PyMethodDef msvcrt_functions[] = {
    {"heapmin",                 msvcrt_heapmin, METH_VARARGS, heapmin_doc},
    {"locking",             msvcrt_locking, METH_VARARGS, locking_doc},
    {"setmode",                 msvcrt_setmode, METH_VARARGS, setmode_doc},
    {"open_osfhandle",          msvcrt_open_osfhandle, METH_VARARGS, open_osfhandle_doc},
    {"get_osfhandle",           msvcrt_get_osfhandle, METH_VARARGS, get_osfhandle_doc},
    {"kbhit",                   msvcrt_kbhit, METH_VARARGS, kbhit_doc},
    {"getch",                   msvcrt_getch, METH_VARARGS, getch_doc},
    {"getche",                  msvcrt_getche, METH_VARARGS, getche_doc},
    {"putch",                   msvcrt_putch, METH_VARARGS, putch_doc},
    {"ungetch",                 msvcrt_ungetch, METH_VARARGS, ungetch_doc},
#ifdef _WCONIO_DEFINED
    {"getwch",                  msvcrt_getwch, METH_VARARGS, getwch_doc},
    {"getwche",                 msvcrt_getwche, METH_VARARGS, getwche_doc},
    {"putwch",                  msvcrt_putwch, METH_VARARGS, putwch_doc},
    {"ungetwch",                msvcrt_ungetwch, METH_VARARGS, ungetwch_doc},
#endif
    {NULL,                      NULL}
};

PyMODINIT_FUNC
initmsvcrt(void)
{
    int st;
    PyObject *d;
    PyObject *m = Py_InitModule("msvcrt", msvcrt_functions);
    if (m == NULL)
        return;
    d = PyModule_GetDict(m);

    /* constants for the locking() function's mode argument */
    insertint(d, "LK_LOCK", _LK_LOCK);
    insertint(d, "LK_NBLCK", _LK_NBLCK);
    insertint(d, "LK_NBRLCK", _LK_NBRLCK);
    insertint(d, "LK_RLCK", _LK_RLCK);
    insertint(d, "LK_UNLCK", _LK_UNLCK);

    /* constants for the crt versions */
#ifdef _VC_ASSEMBLY_PUBLICKEYTOKEN
    st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN",
                                    _VC_ASSEMBLY_PUBLICKEYTOKEN);
    if (st < 0)return;
#endif
#ifdef _CRT_ASSEMBLY_VERSION
    st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION",
                                    _CRT_ASSEMBLY_VERSION);
    if (st < 0)return;
#endif
#ifdef __LIBRARIES_ASSEMBLY_NAME_PREFIX
    st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX",
                                    __LIBRARIES_ASSEMBLY_NAME_PREFIX);
    if (st < 0)return;
#endif
}