Example #1
0
static PyObject*
Py_Config_add_dir(Py_Config *self, PyObject *args, PyObject *kwds)
{
    PyObject *pydir;
    PyObject *pydir_bytes;
    unsigned char *dir;

    static char *kwlist[] = {"dir", NULL};

    if (!PyArg_ParseTupleAndKeywords(
            args, kwds, "O:add_dir", kwlist,
            &pydir)) {
        return NULL;
    }

    pydir_bytes = PyUnicode_EncodeFSDefault(pydir);
    if (pydir_bytes == NULL) {
        return NULL;
    }

    dir = (unsigned char *)PyBytes_AsString(pydir_bytes);
    if (dir == NULL) {
        Py_DECREF(pydir_bytes);
        return NULL;
    }

    if (!FcConfigAppFontAddDir(self->x, dir)) {
        PyErr_SetString(PyExc_ValueError, "Could not add directory");
        return NULL;
    }

    Py_DECREF(pydir_bytes);

    Py_RETURN_NONE;
}
Example #2
0
File: gcmodule.c Project: d11/rts
void
_PyGC_Fini(void)
{
    if (!(debug & DEBUG_SAVEALL)
        && garbage != NULL && PyList_GET_SIZE(garbage) > 0) {
        char *message;
        if (debug & DEBUG_UNCOLLECTABLE)
            message = "gc: %zd uncollectable objects at " \
                "shutdown";
        else
            message = "gc: %zd uncollectable objects at " \
                "shutdown; use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them";
        if (PyErr_WarnFormat(PyExc_ResourceWarning, 0, message,
                             PyList_GET_SIZE(garbage)) < 0)
            PyErr_WriteUnraisable(NULL);
        if (debug & DEBUG_UNCOLLECTABLE) {
            PyObject *repr = NULL, *bytes = NULL;
            repr = PyObject_Repr(garbage);
            if (!repr || !(bytes = PyUnicode_EncodeFSDefault(repr)))
                PyErr_WriteUnraisable(garbage);
            else {
                PySys_WriteStderr(
                    "    %s\n",
                    PyBytes_AS_STRING(bytes)
                    );
            }
            Py_XDECREF(repr);
            Py_XDECREF(bytes);
        }
    }
}
Example #3
0
static PyObject*
Py_Config_add_file(Py_Config *self, PyObject *args, PyObject *kwds)
{
    PyObject *pyfile;
    PyObject *pyfile_bytes;
    unsigned char *file;

    static char *kwlist[] = {"file", NULL};

    if (!PyArg_ParseTupleAndKeywords(
            args, kwds, "O:add_file", kwlist,
            &pyfile)) {
        return NULL;
    }

    pyfile_bytes = PyUnicode_EncodeFSDefault(pyfile);
    if (pyfile_bytes == NULL) {
        return NULL;
    }

    file = (unsigned char *)PyBytes_AsString(pyfile_bytes);
    if (file == NULL) {
        Py_DECREF(pyfile_bytes);
        return NULL;
    }

    if (!FcConfigAppFontAddFile(self->x, file)) {
        PyErr_SetString(PyExc_ValueError, "Could not add font");
        return NULL;
    }

    Py_DECREF(pyfile_bytes);

    Py_RETURN_NONE;
}
Example #4
0
int
_Py_stat(PyObject *path, struct stat *statbuf)
{
#ifdef MS_WINDOWS
    int err;
    struct _stat wstatbuf;
    wchar_t *wpath;

    wpath = PyUnicode_AsUnicode(path);
    if (wpath == NULL)
        return -2;
    err = _wstat(wpath, &wstatbuf);
    if (!err)
        statbuf->st_mode = wstatbuf.st_mode;
    return err;
#else
    int ret;
    PyObject *bytes = PyUnicode_EncodeFSDefault(path);
    if (bytes == NULL)
        return -2;
    ret = stat(PyBytes_AS_STRING(bytes), statbuf);
    Py_DECREF(bytes);
    return ret;
#endif
}
Example #5
0
char *fname2char(PyObject *fname)
{
    PyObject* bytes;
    bytes = PyUnicode_EncodeFSDefault(fname);
    if (bytes == NULL) {
        return NULL;
    }
    return PyBytes_AsString(bytes);
}
Example #6
0
static PyObject *
nis_match (PyObject *self, PyObject *args, PyObject *kwdict)
{
    char *match;
    char *domain = NULL;
    Py_ssize_t keylen;
    int len;
    char *key, *map;
    int err;
    PyObject *ukey, *bkey, *res;
    int fix;
    static char *kwlist[] = {"key", "map", "domain", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwdict,
                                     "Us|s:match", kwlist,
                                     &ukey, &map, &domain))
        return NULL;
    if ((bkey = PyUnicode_EncodeFSDefault(ukey)) == NULL)
        return NULL;
    /* check for embedded null bytes */
    if (PyBytes_AsStringAndSize(bkey, &key, &keylen) == -1) {
        Py_DECREF(bkey);
        return NULL;
    }
    if (!domain && ((err = yp_get_default_domain(&domain)) != 0)) {
        Py_DECREF(bkey);
        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
    Py_DECREF(bkey);
    if (fix)
        len--;
    if (err != 0)
        return nis_error(err);
    res = PyUnicode_DecodeFSDefaultAndSize(match, len);
    free (match);
    return res;
}
Example #7
0
/* string conversion, escape non-unicode chars, coerce must be set to NULL */
const char *PyC_UnicodeAsByte(PyObject *py_str, PyObject **coerce)
{
	char *result;

	result= _PyUnicode_AsString(py_str);

	if(result) {
		/* 99% of the time this is enough but we better support non unicode
		 * chars since blender doesnt limit this */
		return result;
	}
	else if(PyBytes_Check(py_str)) {
		PyErr_Clear();
		return PyBytes_AS_STRING(py_str);
	}
	else {
		return PyBytes_AS_STRING((*coerce= PyUnicode_EncodeFSDefault(py_str)));
	}
}
Example #8
0
void load_tkinter_funcs(void)
{
    // Load tkinter global funcs from tkinter compiled module.
    // Sets an error on failure.
    void *main_program, *tkinter_lib;
    PyObject *module = NULL, *py_path = NULL, *py_path_b = NULL;
    char *path;

    // Try loading from the main program namespace first.
    main_program = dlopen(NULL, RTLD_LAZY);
    if (_func_loader(main_program) == 0) {
        goto exit;
    }
    // Clear exception triggered when we didn't find symbols above.
    PyErr_Clear();

    // Handle PyPy first, as that import will correctly fail on CPython.
    module = PyImport_ImportModule("_tkinter.tklib_cffi");   // PyPy
    if (!module) {
        PyErr_Clear();
        module = PyImport_ImportModule("_tkinter");  // CPython
    }
    if (!(module &&
          (py_path = PyObject_GetAttrString(module, "__file__")) &&
          (py_path_b = PyUnicode_EncodeFSDefault(py_path)) &&
          (path = PyBytes_AsString(py_path_b)))) {
        goto exit;
    }
    tkinter_lib = dlopen(path, RTLD_LAZY);
    if (!tkinter_lib) {
        PyErr_SetString(PyExc_RuntimeError, dlerror());
        goto exit;
    }
    _func_loader(tkinter_lib);
    // dlclose is safe because tkinter has been imported.
    dlclose(tkinter_lib);
    goto exit;
exit:
    Py_XDECREF(module);
    Py_XDECREF(py_path);
    Py_XDECREF(py_path_b);
}
Example #9
0
static PyObject* spwd_getspnam(PyObject *self, PyObject *args)
{
    char *name;
    struct spwd *p;
    PyObject *arg, *bytes, *retval = NULL;

    if (!PyArg_ParseTuple(args, "U:getspnam", &arg))
        return NULL;
    if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL)
        return NULL;
    if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1)
        goto out;
    if ((p = getspnam(name)) == NULL) {
        PyErr_SetString(PyExc_KeyError, "getspnam(): name not found");
        goto out;
    }
    retval = mkspent(p);
out:
    Py_DECREF(bytes);
    return retval;
}
Example #10
0
/* Given a string buffer containing Python source code, compile it
   return and return a code object as a new reference. */
static PyObject *
compile_source(PyObject *pathname, PyObject *source)
{
    PyObject *code, *fixed_source, *pathbytes;

    pathbytes = PyUnicode_EncodeFSDefault(pathname);
    if (pathbytes == NULL)
        return NULL;

    fixed_source = normalize_line_endings(source);
    if (fixed_source == NULL) {
        Py_DECREF(pathbytes);
        return NULL;
    }

    code = Py_CompileString(PyBytes_AsString(fixed_source),
                            PyBytes_AsString(pathbytes),
                            Py_file_input);
    Py_DECREF(pathbytes);
    Py_DECREF(fixed_source);
    return code;
}
FILE*
_Py_fopen(PyObject *path, const char *mode)
{
#ifdef MS_WINDOWS
    wchar_t wmode[10];
    int usize;

    usize = MultiByteToWideChar(CP_ACP, 0, mode, -1, wmode, sizeof(wmode));
    if (usize == 0)
        return NULL;

    return _wfopen(PyUnicode_AS_UNICODE(path), wmode);
#else
    FILE *f;
    PyObject *bytes = PyUnicode_EncodeFSDefault(path);
    if (bytes == NULL)
        return NULL;
    f = fopen(PyBytes_AS_STRING(bytes), mode);
    Py_DECREF(bytes);
    return f;
#endif
}
Example #12
0
static PyObject *
grp_getgrnam_impl(PyModuleDef *module, PyObject *name)
/*[clinic end generated code: output=cd47511f4854da8e input=08ded29affa3c863]*/
{
    char *name_chars;
    struct group *p;
    PyObject *bytes, *retval = NULL;

    if ((bytes = PyUnicode_EncodeFSDefault(name)) == NULL)
        return NULL;
    if (PyBytes_AsStringAndSize(bytes, &name_chars, NULL) == -1)
        goto out;

    if ((p = getgrnam(name_chars)) == NULL) {
        PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %s", name_chars);
        goto out;
    }
    retval = mkgrent(p);
out:
    Py_DECREF(bytes);
    return retval;
}
Example #13
0
static PyObject *
pwd_getpwnam_impl(PyModuleDef *module, PyObject *arg)
/*[clinic end generated code: output=66848d42d386fca3 input=d5f7e700919b02d3]*/
{
    char *name;
    struct passwd *p;
    PyObject *bytes, *retval = NULL;

    if ((bytes = PyUnicode_EncodeFSDefault(arg)) == 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;
}
Example #14
0
static PyObject *
dbmopen_impl(PyObject *module, PyObject *filename, const char *flags,
             int mode)
/*[clinic end generated code: output=9527750f5df90764 input=376a9d903a50df59]*/
{
    int iflags;

    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;
    }

    PyObject *filenamebytes = PyUnicode_EncodeFSDefault(filename);
    if (filenamebytes == NULL) {
        return NULL;
    }
    const char *name = PyBytes_AS_STRING(filenamebytes);
    if (strlen(name) != (size_t)PyBytes_GET_SIZE(filenamebytes)) {
        Py_DECREF(filenamebytes);
        PyErr_SetString(PyExc_ValueError, "embedded null character");
        return NULL;
    }
    PyObject *self = newdbmobject(name, iflags, mode);
    Py_DECREF(filenamebytes);
    return self;
}
Example #15
0
int
_Py_stat(PyObject *path, struct stat *statbuf)
{
#ifdef MS_WINDOWS
    int err;
    struct _stat wstatbuf;
    const wchar_t *wpath;

    wpath = _PyUnicode_AsUnicode(path);
    if (wpath == NULL)
        return -2;

    err = _wstat(wpath, &wstatbuf);
    if (!err)
        statbuf->st_mode = wstatbuf.st_mode;
    return err;
#else
    int ret;
    PyObject *bytes;
    char *cpath;

    bytes = PyUnicode_EncodeFSDefault(path);
    if (bytes == NULL)
        return -2;

    /* check for embedded null bytes */
    if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) {
        Py_DECREF(bytes);
        return -2;
    }

    ret = stat(cpath, statbuf);
    Py_DECREF(bytes);
    return ret;
#endif
}
Example #16
0
static PyObject *
spwd_getspnam_impl(PyObject *module, PyObject *arg)
/*[clinic end generated code: output=701250cf57dc6ebe input=dd89429e6167a00f]*/
{
    char *name;
    struct spwd *p;
    PyObject *bytes, *retval = NULL;

    if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL)
        return NULL;
    if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1)
        goto out;
    if ((p = getspnam(name)) == NULL) {
        if (errno != 0)
            PyErr_SetFromErrno(PyExc_OSError);
        else
            PyErr_SetString(PyExc_KeyError, "getspnam(): name not found");
        goto out;
    }
    retval = mkspent(p);
out:
    Py_DECREF(bytes);
    return retval;
}
Example #17
0
PyObject *
_PyImport_LoadDynamicModuleWithSpec(PyObject *spec, FILE *fp)
{
#ifndef MS_WINDOWS
    PyObject *pathbytes = NULL;
#endif
    PyObject *name_unicode = NULL, *name = NULL, *path = NULL, *m = NULL;
    const char *name_buf, *hook_prefix;
    const char *oldcontext;
    dl_funcptr exportfunc;
    PyModuleDef *def;
    PyObject *(*p0)(void);

    name_unicode = PyObject_GetAttrString(spec, "name");
    if (name_unicode == NULL) {
        return NULL;
    }

    name = get_encoded_name(name_unicode, &hook_prefix);
    if (name == NULL) {
        goto error;
    }
    name_buf = PyBytes_AS_STRING(name);

    path = PyObject_GetAttrString(spec, "origin");
    if (path == NULL)
        goto error;

#ifdef MS_WINDOWS
    exportfunc = _PyImport_FindSharedFuncptrWindows(hook_prefix, name_buf,
                                                    path, fp);
#else
    pathbytes = PyUnicode_EncodeFSDefault(path);
    if (pathbytes == NULL)
        goto error;
    exportfunc = _PyImport_FindSharedFuncptr(hook_prefix, name_buf,
                                             PyBytes_AS_STRING(pathbytes),
                                             fp);
    Py_DECREF(pathbytes);
#endif

    if (exportfunc == NULL) {
        if (!PyErr_Occurred()) {
            PyObject *msg;
            msg = PyUnicode_FromFormat(
                "dynamic module does not define "
                "module export function (%s_%s)",
                hook_prefix, name_buf);
            if (msg == NULL)
                goto error;
            PyErr_SetImportError(msg, name_unicode, path);
            Py_DECREF(msg);
        }
        goto error;
    }

    p0 = (PyObject *(*)(void))exportfunc;

    /* Package context is needed for single-phase init */
    oldcontext = _Py_PackageContext;
    _Py_PackageContext = PyUnicode_AsUTF8(name_unicode);
    if (_Py_PackageContext == NULL) {
        _Py_PackageContext = oldcontext;
        goto error;
    }
    m = p0();
    _Py_PackageContext = oldcontext;

    if (m == NULL) {
        if (!PyErr_Occurred()) {
            PyErr_Format(
                PyExc_SystemError,
                "initialization of %s failed without raising an exception",
                name_buf);
        }
        goto error;
    } else if (PyErr_Occurred()) {
        PyErr_Clear();
        PyErr_Format(
            PyExc_SystemError,
            "initialization of %s raised unreported exception",
            name_buf);
        m = NULL;
        goto error;
    }
    if (Py_TYPE(m) == NULL) {
        /* This can happen when a PyModuleDef is returned without calling
         * PyModuleDef_Init on it
         */
        PyErr_Format(PyExc_SystemError,
                     "init function of %s returned uninitialized object",
                     name_buf);
        m = NULL; /* prevent segfault in DECREF */
        goto error;
    }
    if (PyObject_TypeCheck(m, &PyModuleDef_Type)) {
        Py_DECREF(name_unicode);
        Py_DECREF(name);
        Py_DECREF(path);
        return PyModule_FromDefAndSpec((PyModuleDef*)m, spec);
    }

    /* Fall back to single-phase init mechanism */

    if (hook_prefix == nonascii_prefix) {
        /* don't allow legacy init for non-ASCII module names */
        PyErr_Format(
            PyExc_SystemError,
            "initialization of * did not return PyModuleDef",
            name_buf);
        goto error;
    }

    /* Remember pointer to module init function. */
    def = PyModule_GetDef(m);
    if (def == NULL) {
        PyErr_Format(PyExc_SystemError,
                     "initialization of %s did not return an extension "
                     "module", name_buf);
        goto error;
    }
    def->m_base.m_init = p0;

    /* Remember the filename as the __file__ attribute */
    if (PyModule_AddObject(m, "__file__", path) < 0)
        PyErr_Clear(); /* Not important enough to report */
    else
        Py_INCREF(path);

    if (_PyImport_FixupExtensionObject(m, name_unicode, path) < 0)
        goto error;

    Py_DECREF(name_unicode);
    Py_DECREF(name);
    Py_DECREF(path);

    return m;

error:
    Py_DECREF(name_unicode);
    Py_XDECREF(name);
    Py_XDECREF(path);
    Py_XDECREF(m);
    return NULL;
}
Example #18
0
static PyObject *
_Py_FindSourceFile(PyObject *filename, char* namebuf, size_t namelen, PyObject *io)
{
    Py_ssize_t i;
    PyObject *binary;
    PyObject *v;
    Py_ssize_t npath;
    size_t taillen;
    PyObject *syspath;
    PyObject *path;
    const char* tail;
    PyObject *filebytes;
    const char* filepath;
    Py_ssize_t len;
    PyObject* result;

    filebytes = PyUnicode_EncodeFSDefault(filename);
    if (filebytes == NULL) {
        PyErr_Clear();
        return NULL;
    }
    filepath = PyBytes_AS_STRING(filebytes);

    /* Search tail of filename in sys.path before giving up */
    tail = strrchr(filepath, SEP);
    if (tail == NULL)
        tail = filepath;
    else
        tail++;
    taillen = strlen(tail);

    syspath = _PySys_GetObjectId(&PyId_path);
    if (syspath == NULL || !PyList_Check(syspath))
        goto error;
    npath = PyList_Size(syspath);

    for (i = 0; i < npath; i++) {
        v = PyList_GetItem(syspath, i);
        if (v == NULL) {
            PyErr_Clear();
            break;
        }
        if (!PyUnicode_Check(v))
            continue;
        path = PyUnicode_EncodeFSDefault(v);
        if (path == NULL) {
            PyErr_Clear();
            continue;
        }
        len = PyBytes_GET_SIZE(path);
        if (len + 1 + (Py_ssize_t)taillen >= (Py_ssize_t)namelen - 1) {
            Py_DECREF(path);
            continue; /* Too long */
        }
        strcpy(namebuf, PyBytes_AS_STRING(path));
        Py_DECREF(path);
        if (strlen(namebuf) != (size_t)len)
            continue; /* v contains '\0' */
        if (len > 0 && namebuf[len-1] != SEP)
            namebuf[len++] = SEP;
        strcpy(namebuf+len, tail);

        binary = _PyObject_CallMethodId(io, &PyId_open, "ss", namebuf, "rb");
        if (binary != NULL) {
            result = binary;
            goto finally;
        }
        PyErr_Clear();
    }
    goto error;

error:
    result = NULL;
finally:
    Py_DECREF(filebytes);
    return result;
}
Example #19
0
static const char *traceback_filepath(PyTracebackObject *tb, PyObject **coerce)
{
	return PyBytes_AS_STRING((*coerce = PyUnicode_EncodeFSDefault(tb->tb_frame->f_code->co_filename)));
}
Example #20
0
static PyObject *
time_strftime(PyObject *self, PyObject *args)
{
    PyObject *tup = NULL;
    struct tm buf;
    const time_char *fmt;
#ifdef HAVE_WCSFTIME
    wchar_t *format;
#else
    PyObject *format;
#endif
    PyObject *format_arg;
    size_t fmtlen, buflen;
    time_char *outbuf = NULL;
    size_t i;
    PyObject *ret = NULL;

    memset((void *) &buf, '\0', sizeof(buf));

    /* Will always expect a unicode string to be passed as format.
       Given that there's no str type anymore in py3k this seems safe.
    */
    if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
        return NULL;

    if (tup == NULL) {
        time_t tt = time(NULL);
        buf = *localtime(&tt);
    }
    else if (!gettmarg(tup, &buf) || !checktm(&buf))
        return NULL;

#if defined(_MSC_VER) || defined(sun)
    if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
        PyErr_SetString(PyExc_ValueError,
                        "strftime() requires year in [1; 9999]");
        return NULL;
    }
#endif

    /* Normalize tm_isdst just in case someone foolishly implements %Z
       based on the assumption that tm_isdst falls within the range of
       [-1, 1] */
    if (buf.tm_isdst < -1)
        buf.tm_isdst = -1;
    else if (buf.tm_isdst > 1)
        buf.tm_isdst = 1;

#ifdef HAVE_WCSFTIME
    format = PyUnicode_AsWideCharString(format_arg, NULL);
    if (format == NULL)
        return NULL;
    fmt = format;
#else
    /* Convert the unicode string to an ascii one */
    format = PyUnicode_EncodeFSDefault(format_arg);
    if (format == NULL)
        return NULL;
    fmt = PyBytes_AS_STRING(format);
#endif

#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
    /* check that the format string contains only valid directives */
    for(outbuf = strchr(fmt, '%');
        outbuf != NULL;
        outbuf = strchr(outbuf+2, '%'))
    {
        if (outbuf[1]=='#')
            ++outbuf; /* not documented by python, */
        if (outbuf[1]=='\0' ||
            !strchr("aAbBcdHIjmMpSUwWxXyYzZ%", outbuf[1]))
        {
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
            Py_DECREF(format);
            return NULL;
        }
    }
#endif

    fmtlen = time_strlen(fmt);

    /* I hate these functions that presume you know how big the output
     * will be ahead of time...
     */
    for (i = 1024; ; i += i) {
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        int err;
#endif
        outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
        if (outbuf == NULL) {
            PyErr_NoMemory();
            break;
        }
        buflen = format_time(outbuf, i, fmt, &buf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        err = errno;
#endif
        if (buflen > 0 || i >= 256 * fmtlen) {
            /* If the buffer is 256 times as long as the format,
               it's probably not failing for lack of room!
               More likely, the format yields an empty result,
               e.g. an empty format, or %Z when the timezone
               is unknown. */
#ifdef HAVE_WCSFTIME
            ret = PyUnicode_FromWideChar(outbuf, buflen);
#else
            ret = PyUnicode_DecodeFSDefaultAndSize(outbuf, buflen);
#endif
            PyMem_Free(outbuf);
            break;
        }
        PyMem_Free(outbuf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
        /* VisualStudio .NET 2005 does this properly */
        if (buflen == 0 && err == EINVAL) {
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
            break;
        }
#endif
    }
#ifdef HAVE_WCSFTIME
    PyMem_Free(format);
#else
    Py_DECREF(format);
#endif
    return ret;
}
Example #21
0
PyObject *
PyUnicode_FS_ENCODE(PyObject *text)
{
	return PyUnicode_EncodeFSDefault(text);
}
Example #22
0
PyObject *
_PyImport_LoadDynamicModule(PyObject *name, PyObject *path, FILE *fp)
{
    PyObject *m;
    PyObject *pathbytes;
    char *namestr, *lastdot, *shortname, *packagecontext, *oldcontext;
    dl_funcptr p0;
    PyObject* (*p)(void);
    struct PyModuleDef *def;

    namestr = _PyUnicode_AsString(name);
    if (namestr == NULL)
        return NULL;

    m = _PyImport_FindExtensionObject(name, path);
    if (m != NULL) {
        Py_INCREF(m);
        return m;
    }

    lastdot = strrchr(namestr, '.');
    if (lastdot == NULL) {
        packagecontext = NULL;
        shortname = namestr;
    }
    else {
        packagecontext = namestr;
        shortname = lastdot+1;
    }

    pathbytes = PyUnicode_EncodeFSDefault(path);
    if (pathbytes == NULL)
        return NULL;
    p0 = _PyImport_GetDynLoadFunc(shortname,
                                  PyBytes_AS_STRING(pathbytes), fp);
    Py_DECREF(pathbytes);
    p = (PyObject*(*)(void))p0;
    if (PyErr_Occurred())
        return NULL;
    if (p == NULL) {
        PyErr_Format(PyExc_ImportError,
                     "dynamic module does not define init function"
                     " (PyInit_%s)",
                     shortname);
        return NULL;
    }
    oldcontext = _Py_PackageContext;
    _Py_PackageContext = packagecontext;
    m = (*p)();
    _Py_PackageContext = oldcontext;
    if (m == NULL)
        return NULL;

    if (PyErr_Occurred()) {
        Py_DECREF(m);
        PyErr_Format(PyExc_SystemError,
                     "initialization of %s raised unreported exception",
                     shortname);
        return NULL;
    }

    /* Remember pointer to module init function. */
    def = PyModule_GetDef(m);
    def->m_base.m_init = p;

    /* Remember the filename as the __file__ attribute */
    if (PyModule_AddObject(m, "__file__", path) < 0)
        PyErr_Clear(); /* Not important enough to report */
    else
        Py_INCREF(path);

    if (_PyImport_FixupExtensionObject(m, name, path) < 0)
        return NULL;
    if (Py_VerboseFlag)
        PySys_FormatStderr(
            "import %U # dynamically loaded from %R\n",
            name, path);
    return m;
}
Example #23
0
int _parseArgs(PyObject **args, int count, const char *types, va_list list)
#endif
{
    if (count != strlen(types))
        return -1;

#else

int _parseArgs(PyObject **args, int count, const char *types, ...)
{
    va_list list;

    if (count != (int) strlen(types))
        return -1;

    va_start(list, types);

#endif

    if (PyErr_Occurred())
        return -1;

    for (int i = 0; i < count; i++) {
#ifdef PYPY_VERSION
        PyObject *arg = PyTuple_GetItem(args, i);
#else
        PyObject *arg = args[i];
#endif
        
        switch (types[i]) {
          case 'c':           /* string */
          case 'k':           /* string and size */
          case 'C':           /* string, not to be unpacked */
            if (PyBytes_Check(arg))
                break;
            return -1;

          case 's':           /* string or unicode, to UnicodeString ref */
          case 'u':           /* string or unicode, to new UnicodeString ptr */
          case 'n':           /* string or unicode, to utf8 charsArg */
          case 'f':           /* string or unicode filename, to charsArg */
            if (PyBytes_Check(arg) || PyUnicode_Check(arg))
                break;
            return -1;

          case 'S':           /* string, unicode or UnicodeString */
          case 'W':           /* string, unicode or UnicodeString, to save */
            if (PyBytes_Check(arg) || PyUnicode_Check(arg) ||
                isUnicodeString(arg))
                break;
            return -1;

          case 'T':           /* array of string, unicode or UnicodeString */
            if (PySequence_Check(arg))
            {
                if (PySequence_Length(arg) > 0)
                {
                    PyObject *obj = PySequence_GetItem(arg, 0);
                    int ok = (PyBytes_Check(obj) || PyUnicode_Check(obj) ||
                              isUnicodeString(obj));
                    Py_DECREF(obj);
                    if (ok)
                        break;
                }
                else
                    break;
            }
            return -1;

          case 'U':           /* UnicodeString */
          case 'V':           /* UnicodeString and raw arg object */
            if (isUnicodeString(arg))
                break;
            return -1;

          case 'K':           /* python object of any type */
              break;

          case 'M':           /* python callable */
          {
              if (PyCallable_Check(arg))
                  break;
              return -1;
          }

          case 'O':           /* python object of given type */
          {
              PyTypeObject *type = va_arg(list, PyTypeObject *);

              if (PyObject_TypeCheck(arg, type))
                  break;
              return -1;
          }

          case 'P':           /* wrapped ICU object */
          case 'p':           /* wrapped ICU object, to save */
          {
              classid id = va_arg(list, classid);
              PyTypeObject *type = va_arg(list, PyTypeObject *);

              if (isInstance(arg, id, type))
                  break;
              return -1;
          }

          case 'Q':           /* array of wrapped ICU object pointers */
          case 'R':           /* array of wrapped ICU objects */
          {
              classid id = va_arg(list, classid);
              PyTypeObject *type = va_arg(list, PyTypeObject *);
              
              if (PySequence_Check(arg))
              {
                  if (PySequence_Length(arg) > 0)
                  {
                      PyObject *obj = PySequence_GetItem(arg, 0);
                      int ok = isInstance(obj, id, type);

                      Py_DECREF(obj);
                      if (ok)
                          break;
                  }
                  else
                      break;
              }
              return -1;
          }

          case 'D':           /* date as UDate float or datetime */
            if (isDate(arg))
                break;
            return -1;

          case 'E':           /* date as datetime */
            if (isDateExact(arg))
                break;
            return -1;

          case 'a':           /* byte */
            if (PyBytes_Check(arg) && (PyBytes_Size(arg) == 1))
                break;
            return -1;

          case 'B':           /* boolean, strict */
            if (arg == Py_True || arg == Py_False)
                break;
            return -1;

          case 'b':           /* boolean */
            break;

          case 'i':           /* int */
            if (PyInt_Check(arg))
                break;
            return -1;

          case 'd':           /* double */
            if (PyFloat_Check(arg) || PyInt_Check(arg) || PyLong_Check(arg))
                break;
            return -1;

          case 'F':           /* array of double */
            if (PySequence_Check(arg))
            {
                if (PySequence_Length(arg) > 0)
                {
                    PyObject *obj = PySequence_GetItem(arg, 0);
                    int ok = (PyFloat_Check(obj) ||
                              PyInt_Check(obj) ||
                              PyLong_Check(obj));
                    Py_DECREF(obj);
                    if (ok)
                        break;
                }
                else
                    break;
            }
            return -1;

          case 'G':           /* array of bool */
            if (PySequence_Check(arg))
                break;
            return -1;

          case 'L':           /* PY_LONG_LONG */
            if (PyLong_Check(arg) || PyInt_Check(arg))
                break;
            return -1;

          default:
            return -1;
        }
    }

    for (int j = 0; j < count; j++) {
#ifdef PYPY_VERSION
        PyObject *arg = PyTuple_GetItem(args, j);
#else
        PyObject *arg = args[j];
#endif
        switch (types[j]) {
          case 'A':           /* previous Python arg object */
          {
              PyObject **obj = va_arg(list, PyObject **);
#ifdef PYPY_VERSION
              *obj = PyTuple_GetItem(args, j - 1);
#else
              *obj = args[j - 1];
#endif
              break;
          }
            
          case 'c':           /* string */
          {
              char **c = va_arg(list, char **);
              *c = PyBytes_AS_STRING(arg);
              break;
          }

          case 'k':           /* string and size */
          {
              char **c = va_arg(list, char **);
              int *l = va_arg(list, int *);
              *c = PyBytes_AS_STRING(arg);
              *l = PyBytes_GET_SIZE(arg);
              break;
          }

          case 'C':           /* string, not to be unpacked */
          {
              PyObject **obj = va_arg(list, PyObject **);
              *obj = arg;
              break;
          }

          case 's':           /* string or unicode, to UnicodeString ref */
          {
              UnicodeString *u = va_arg(list, UnicodeString *);

              try {
                  PyObject_AsUnicodeString(arg, *u);
              } catch (ICUException e) {
                  e.reportError();
                  return -1;
              }
              break;
          }

          case 'u':           /* string or unicode, to new UnicodeString ptr */
          {
              UnicodeString **u = va_arg(list, UnicodeString **);

              try {
                  *u = PyObject_AsUnicodeString(arg);
              } catch (ICUException e) {
                  e.reportError();
                  return -1;
              }
              break;
          }

          case 'n':           /* string or unicode, to utf8 charsArg */
          {
              charsArg *p = va_arg(list, charsArg *);

              if (PyUnicode_Check(arg))
              {
                  PyObject *bytes = PyUnicode_AsUTF8String(arg);
                  if (bytes == NULL)
                      return -1;
                  p->own(bytes);
              }
              else
              {
                  p->borrow(arg);
              }
              break;
          }

          case 'f':           /* string or unicode filename, to charsArg */
          {
              charsArg *p = va_arg(list, charsArg *);

              if (PyUnicode_Check(arg))
              {
#if PY_MAJOR_VERSION >= 3
                  PyObject *bytes = PyUnicode_EncodeFSDefault(arg);
#else
                  // TODO: Figure out fs encoding in a reasonable way
                  PyObject *bytes = PyUnicode_AsUTF8String(arg);
#endif
                  if (bytes == NULL)
                      return -1;
                  p->own(bytes);
              }
              else
              {
                  p->borrow(arg);
              }
              break;
          }

          case 'S':           /* string, unicode or UnicodeString */
          {
              UnicodeString **u = va_arg(list, UnicodeString **);
              UnicodeString *_u = va_arg(list, UnicodeString *);

              if (PyObject_TypeCheck(arg, &UObjectType_))
                  *u = (UnicodeString *) ((t_uobject *) arg)->object;
              else
              {
                  try {
                      PyObject_AsUnicodeString(arg, *_u);
                      *u = _u;
                  } catch (ICUException e) {
                      e.reportError();
                      return -1;
                  }
              }
              break;
          }

          case 'W':           /* string, unicode or UnicodeString, to save */
          {
              UnicodeString **u = va_arg(list, UnicodeString **);
              PyObject **obj = va_arg(list, PyObject **);

              if (PyObject_TypeCheck(arg, &UObjectType_))
              {
                  *u = (UnicodeString *) ((t_uobject *) arg)->object;
                  Py_INCREF(arg); Py_XDECREF(*obj); *obj = arg;
              }
              else
              {
                  try {
                      *u = PyObject_AsUnicodeString(arg);
                      Py_XDECREF(*obj); *obj = wrap_UnicodeString(*u, T_OWNED);
                  } catch (ICUException e) {
                      e.reportError();
                      return -1;
                  }
              }
              break;
          }

          case 'T':           /* array of string, unicode or UnicodeString */
          {
              UnicodeString **array = va_arg(list, UnicodeString **);
              int *len = va_arg(list, int *);
              *array = toUnicodeStringArray(arg, len);
              if (!*array)
                  return -1;
              break;
          }

          case 'U':           /* UnicodeString */
          {
              UnicodeString **u = va_arg(list, UnicodeString **);
              *u = (UnicodeString *) ((t_uobject *) arg)->object;
              break;
          }

          case 'V':           /* UnicodeString and raw arg object */
          {
              UnicodeString **u = va_arg(list, UnicodeString **);
              PyObject **obj = va_arg(list, PyObject **);
              *u = (UnicodeString *) ((t_uobject *) arg)->object;
              *obj = arg;
              break;
          }

          case 'K':           /* python object of any type */
          case 'M':           /* python callable */
          case 'O':           /* python object of given type */
          {
              PyObject **obj = va_arg(list, PyObject **);
              *obj = arg;
              break;
          }

          case 'P':           /* wrapped ICU object */
          {
              UObject **obj = va_arg(list, UObject **);
              *obj = ((t_uobject *) arg)->object;
              break;
          }

          case 'p':           /* wrapped ICU object, to save */
          {
              UObject **obj = va_arg(list, UObject **);
              PyObject **pyobj = va_arg(list, PyObject **);
              *obj = ((t_uobject *) arg)->object;
              Py_INCREF(arg); Py_XDECREF(*pyobj); *pyobj = arg;
              break;
          }

          case 'Q':           /* array of wrapped ICU object pointers */
          {
              UObject ***array = va_arg(list, UObject ***);
              int *len = va_arg(list, int *);
              classid id = va_arg(list, classid);
              PyTypeObject *type = va_arg(list, PyTypeObject *);
              *array = pl2cpa(arg, len, id, type);
              if (!*array)
                  return -1;
              break;
          }

          case 'R':           /* array of wrapped ICU objects */
          {
              typedef UObject *(*convFn)(PyObject *, int *,
                                         classid, PyTypeObject *);
              UObject **array = va_arg(list, UObject **);
              int *len = va_arg(list, int *);
              classid id = va_arg(list, classid);
              PyTypeObject *type = va_arg(list, PyTypeObject *);
              convFn fn = va_arg(list, convFn);
              *array = fn(arg, len, id, type);
              if (!*array)
                  return -1;
              break;
          }

          case 'D':           /* date as UDate float or datetime */
          case 'E':           /* date as datetime */
          {
              UDate *d = va_arg(list, UDate *);
              *d = PyObject_AsUDate(arg);
              break;
          }

          case 'a':           /* byte */
          {
              unsigned char *a = va_arg(list, unsigned char *);
              *a = (unsigned char) PyBytes_AS_STRING(arg)[0];
              break;
          }

          case 'B':           /* boolean, strict */
          case 'b':           /* boolean */
          {
              int *b = va_arg(list, int *);
              *b = PyObject_IsTrue(arg);
              break;
          }

          case 'i':           /* int */
          {
              int *n = va_arg(list, int *);
#if PY_MAJOR_VERSION >= 3
              if ((*n = PyLong_AsLong(arg)) == -1 && PyErr_Occurred())
                  return -1;
#else
              *n = PyInt_AsLong(arg);
#endif
              break;
          }

          case 'd':           /* double */
          {
              double *d = va_arg(list, double *);
              if (PyFloat_Check(arg))
                  *d = PyFloat_AsDouble(arg);
#if PY_MAJOR_VERSION < 3
              else if (PyInt_Check(arg))
                  *d = (double) PyInt_AsLong(arg);
#endif
              else
                  *d = PyLong_AsDouble(arg);
              break;
          }

          case 'F':           /* array of double */
          {
              double **array = va_arg(list, double **);
              int *len = va_arg(list, int *);
              *array = toDoubleArray(arg, len);
              if (!*array)
                  return -1;
              break;
          }

          case 'G':           /* array of UBool */
          {
              UBool **array = va_arg(list, UBool **);
              int *len = va_arg(list, int *);
              *array = toUBoolArray(arg, len);
              if (!*array)
                  return -1;
              break;
          }

          case 'L':           /* PY_LONG_LONG */
          {
              PY_LONG_LONG *l = va_arg(list, PY_LONG_LONG *);
              *l = PyLong_AsLongLong(arg);
              break;
          }

          default:
            return -1;
        }
    }

    return 0;
}