コード例 #1
0
ファイル: connection_int.c プロジェクト: psycopg/psycopg2
RAISES_NEG int
conn_tpc_command(connectionObject *self, const char *cmd, xidObject *xid)
{
    PyObject *tid = NULL;
    const char *ctid;
    int rv = -1;

    Dprintf("conn_tpc_command: %s", cmd);

    /* convert the xid into PostgreSQL transaction id while keeping the GIL */
    if (!(tid = psyco_ensure_bytes(xid_get_tid(xid)))) { goto exit; }
    if (!(ctid = Bytes_AsString(tid))) { goto exit; }

    Py_BEGIN_ALLOW_THREADS;
    pthread_mutex_lock(&self->lock);

    if (0 > (rv = pq_tpc_command_locked(self, cmd, ctid, &_save))) {
        pthread_mutex_unlock(&self->lock);
        Py_BLOCK_THREADS;
        pq_complete_error(self);
        goto exit;
    }

    pthread_mutex_unlock(&self->lock);
    Py_END_ALLOW_THREADS;

exit:
    Py_XDECREF(tid);
    return rv;
}
コード例 #2
0
ファイル: rwobject.c プロジェクト: Abstak/Mastermind_Python
static int
rw_read (SDL_RWops* context, void* ptr, int size, int maxnum)
{
    RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
    PyObject* result;
    int retval;

    if (!helper->read)
        return -1;

    result = PyObject_CallFunction (helper->read, "i", size * maxnum);
    if (!result)
        return -1;

    if (!Bytes_Check (result))
    {
        Py_DECREF (result);
        return -1;
    }

    retval = Bytes_GET_SIZE (result);
    memcpy (ptr, Bytes_AsString (result), retval);
    retval /= size;

    Py_DECREF (result);
    return retval;
}
コード例 #3
0
ファイル: rwobject.c プロジェクト: Abstak/Mastermind_Python
static int
rw_read_th (SDL_RWops* context, void* ptr, int size, int maxnum)
{
    RWHelper* helper = (RWHelper*) context->hidden.unknown.data1;
    PyObject* result;
    int retval;
    PyThreadState* oldstate;

    if (!helper->read)
        return -1;

    PyEval_AcquireLock ();
    oldstate = PyThreadState_Swap (helper->thread);

    result = PyObject_CallFunction (helper->read, "i", size * maxnum);
    if (!result)
    {
        PyErr_Print();
        retval = -1;
        goto end;
    }

    if (!Bytes_Check (result))
    {
        Py_DECREF (result);
        PyErr_Print();
        retval = -1;
        goto end;
    }

    retval = Bytes_GET_SIZE (result);
    memcpy (ptr, Bytes_AsString (result), retval);
    retval /= size;

    Py_DECREF (result);

end:
    PyThreadState_Swap (oldstate);
    PyEval_ReleaseLock ();

    return retval;
}
コード例 #4
0
ファイル: adapter_datetime.c プロジェクト: olasd/psycopg2
static PyObject *
_pydatetime_string_date_time(pydatetimeObject *self)
{
    PyObject *rv = NULL;
    PyObject *iso = NULL;
    PyObject *tz;

    /* Select the right PG type to cast into. */
    char *fmt = NULL;
    switch (self->type) {
    case PSYCO_DATETIME_TIME:
        tz = PyObject_GetAttrString(self->wrapped, "tzinfo");
        if (!tz) { goto error; }
        fmt = (tz == Py_None) ? "'%s'::time" : "'%s'::timetz";
        Py_DECREF(tz);
        break;
    case PSYCO_DATETIME_DATE:
        fmt = "'%s'::date";
        break;
    case PSYCO_DATETIME_TIMESTAMP:
        tz = PyObject_GetAttrString(self->wrapped, "tzinfo");
        if (!tz) { goto error; }
        fmt = (tz == Py_None) ? "'%s'::timestamp" : "'%s'::timestamptz";
        Py_DECREF(tz);
        break;
    }

    if (!(iso = psycopg_ensure_bytes(
            PyObject_CallMethod(self->wrapped, "isoformat", NULL)))) {
        goto error;
    }

    rv = Bytes_FromFormat(fmt, Bytes_AsString(iso));

    Py_DECREF(iso);
    return rv;

error:
    Py_XDECREF(iso);
    return rv;
}
コード例 #5
0
/* Read the number of arguments and the first argument from /proc/pid/cmdline
 *
 * Return 0 if found, else -1. Return arg0 in a malloc'd array.
 *
 * If the function fails in a way that shouldn't be ignored, also set
 * a Python exception.
 */
static int
get_args_from_proc(int *argc_o, char **arg0_o)
{
    /* allow /proc/PID/cmdline, with oversize max_pid, and them some. */
#define FNLEN 30
    char fn[FNLEN];

    PyObject *os = NULL;
    PyObject *pid_py = NULL;
    long pid;
    PyObject *f = NULL;
    PyObject *cl = NULL;

    PyObject *tmp = NULL;
    int rv = -1;

    spt_debug("looking for args into proc fs");

    /* get the pid from os.getpid() */
    if (!(os = PyImport_ImportModule("os"))) {
        spt_debug("failed to import os");
        goto exit;
    }
    if (!(pid_py = PyObject_CallMethod(os, "getpid", NULL))) {
        spt_debug("calling os.getpid() failed");
        /* os.getpid() may be not available, so ignore this error. */
        PyErr_Clear();
        goto exit;
    }
    if (-1 == (pid = PyInt_AsLong(pid_py))) {
        spt_debug("os.getpid() returned crap?");
        /* Don't bother to check PyErr_Occurred as pid can't just be -1. */
        goto exit;
    }

    /* get the content of /proc/PID/cmdline */
    snprintf(fn, FNLEN, "/proc/%ld/cmdline", pid);
    if (!(f = PyFile_FromString(fn, "rb"))) {
        spt_debug("opening '%s' failed", fn);
        /* That's ok: procfs is easily not available on menomated unices */
        PyErr_Clear();
        goto exit;
    }
    /* the file has been open in binary mode, so we get bytes */
    cl = PyObject_CallMethod(f, "read", NULL);
    if (!(tmp = PyObject_CallMethod(f, "close", NULL))) {
        spt_debug("closing failed");
    }
    else {
        Py_DECREF(tmp);
    }

    if (!cl) {
        spt_debug("reading failed");
        /* could there be some protected environment where a process cannot
         * read its own pid? Who knows, better not to risk. */
        PyErr_Clear();
        goto exit;
    }

    /* the cmdline is a buffer of null-terminated strings. We can strdup it to
     * get a copy of arg0, and count the zeros to get argc */
    {
        char *ccl;
        Py_ssize_t i;

        if (!(ccl = Bytes_AsString(cl))) {
            spt_debug("failed to get cmdline string");
            goto exit;
        }
        if (!(*arg0_o = strdup(ccl))) {
            spt_debug("arg0 strdup failed");
            PyErr_NoMemory();
            goto exit;
        }
        spt_debug("got argv[0] = '%s' from /proc", *arg0_o);

        *argc_o = 0;
        for (i = Bytes_Size(cl) - 1; i >= 0; --i) {
            if (ccl[i] == '\0') { (*argc_o)++; }
        }
        spt_debug("got argc = %d from /proc", *argc_o);
    }

    /* success */
    rv = 0;

exit:
    Py_XDECREF(cl);
    Py_XDECREF(f);
    Py_XDECREF(pid_py);
    Py_XDECREF(os);

    return rv;
}
コード例 #6
0
ファイル: font.c プロジェクト: Anugrahaa/anagrammatic
static PyObject*
font_render(PyObject* self, PyObject* args)
{
    TTF_Font* font = PyFont_AsFont (self);
    int aa;
    PyObject* text, *final;
    PyObject* fg_rgba_obj, *bg_rgba_obj = NULL;
    Uint8 rgba[] = {0, 0, 0, 0};
    SDL_Surface* surf;
    SDL_Color foreg, backg;
    int just_return;

    if (!PyArg_ParseTuple(args, "OiO|O", &text, &aa, &fg_rgba_obj,
                          &bg_rgba_obj)) {
        return NULL;
    }

    if (!RGBAFromColorObj(fg_rgba_obj, rgba)) {
        return RAISE(PyExc_TypeError, "Invalid foreground RGBA argument");
    }
    foreg.r = rgba[0];
    foreg.g = rgba[1];
    foreg.b = rgba[2];
    foreg.unused = 0;
    if (bg_rgba_obj != NULL) {
        if (!RGBAFromColorObj(bg_rgba_obj, rgba)) {
            bg_rgba_obj = NULL;
            backg.r = 0;
            backg.g = 0;
            backg.b = 0;
            backg.unused = 0;
        }
        else
        {
            backg.r = rgba[0];
            backg.g = rgba[1];
            backg.b = rgba[2];
            backg.unused = 0;
        }
    }
    else {
        backg.r = 0;
        backg.g = 0;
        backg.b = 0;
        backg.unused = 0;
    }

    just_return = PyObject_Not(text);
    if (just_return) {
        int height = TTF_FontHeight(font);

        if (just_return == -1 ||
            !(PyUnicode_Check(text) || Bytes_Check(text) || text == Py_None)) {
            PyErr_Clear();
            return RAISE_TEXT_TYPE_ERROR();
        }
        surf = SDL_CreateRGBSurface(SDL_SWSURFACE, 1, height, 32,
                                    0xff<<16, 0xff<<8, 0xff, 0);
        if (surf == NULL) {
            return RAISE(PyExc_SDLError, SDL_GetError());
        }
        if (bg_rgba_obj != NULL) {
            Uint32 c = SDL_MapRGB(surf->format, backg.r, backg.g, backg.b);
            SDL_FillRect(surf, NULL, c);
        }
        else {
            SDL_SetColorKey(surf, SDL_SRCCOLORKEY, 0);
        }
    }
    else if (PyUnicode_Check(text)) {
        PyObject *bytes = PyUnicode_AsEncodedString(text, "utf-8", "replace");
        const char *astring = NULL;

        if (!bytes) {
            return NULL;
        }
        astring = Bytes_AsString(bytes);
        if (strlen(astring) != Bytes_GET_SIZE(bytes)) {
            Py_DECREF(bytes);
            return RAISE(PyExc_ValueError,
                         "A null character was found in the text");
        }
        if (utf_8_needs_UCS_4(astring)) {
            Py_DECREF(bytes);
            return RAISE(PyExc_UnicodeError,
                         "A Unicode character above '\\uFFFF' was found;"
                         " not supported");
        }
        if (aa) {
            if (bg_rgba_obj == NULL) {
                surf = TTF_RenderUTF8_Blended(font, astring, foreg);
            }
            else {
                surf = TTF_RenderUTF8_Shaded(font, astring, foreg, backg);
            }
        }
        else {
            surf = TTF_RenderUTF8_Solid(font, astring, foreg);
        }
        Py_DECREF(bytes);
    }
    else if (Bytes_Check(text)) {
        const char *astring = Bytes_AsString(text);

        if (strlen(astring) != Bytes_GET_SIZE(text)) {
            return RAISE(PyExc_ValueError,
                         "A null character was found in the text");
        }
        if (aa) {
            if (bg_rgba_obj == NULL) {
                surf = TTF_RenderText_Blended(font, astring, foreg);
            }
            else {
                surf = TTF_RenderText_Shaded(font, astring, foreg, backg);
            }
        }
        else {
            surf = TTF_RenderText_Solid(font, astring, foreg);
        }
    }
    else {
        return RAISE_TEXT_TYPE_ERROR();
    }
    if (surf == NULL) {
        return RAISE(PyExc_SDLError, TTF_GetError());
    }
    if (!aa && (bg_rgba_obj != NULL) && !just_return) {
        /* turn off transparancy */
        SDL_SetColorKey(surf, 0, 0);
        surf->format->palette->colors[0].r = backg.r;
        surf->format->palette->colors[0].g = backg.g;
        surf->format->palette->colors[0].b = backg.b;
    }
    final = PySurface_New(surf);
コード例 #7
0
ファイル: scrap_win.c プロジェクト: IuryAlves/pygame
char*
pygame_scrap_get (char *type, unsigned long *count)
{
    UINT format = _convert_format (type);
    char *retval = NULL;

    if (!pygame_scrap_initialized ())
    {
        PyErr_SetString (PyExc_SDLError, "scrap system not initialized.");
        return NULL;
    }

    if (!pygame_scrap_lost ())
        return Bytes_AsString (PyDict_GetItemString (_clipdata, type));

    if (!OpenClipboard (SDL_Window))
        return NULL;

    if (!IsClipboardFormatAvailable (format))
    {
        /* The format was not found - was it a mapped type? */
        format = _convert_internal_type (type);
        if (format == -1)
        {
            CloseClipboard ();
            return NULL;
        }
    }

    if (IsClipboardFormatAvailable (format))
    {
        HANDLE hMem;
        char *src;
        src = NULL;

        hMem = GetClipboardData (format);
        if (hMem)
        {
            *count = 0;

            /* CF_BITMAP is not a global, so do not lock it. */
            if (format != CF_BITMAP)
            {
                src = GlobalLock (hMem);
                if (!src)
                {
                    CloseClipboard ();
                    return NULL;
                }
                *count = GlobalSize (hMem);
            }

            if (format == CF_DIB || format == CF_DIBV5)
            {
                /* Count will be increased accordingly in
                 * _create_dib_buffer.
                 */
                src = _create_dib_buffer (src, count);
                GlobalUnlock (hMem);
                CloseClipboard ();
                return src;
            }
            else if (*count != 0)
            {
                /* weird error, shouldn't get here. */
                if(!src) {
                    return NULL;
                }

                retval = malloc (*count);
                if (retval)
                {
                    memset (retval, 0, *count);
                    memcpy (retval, src, *count);
                }
            }
            GlobalUnlock (hMem);
        }
    }

    CloseClipboard ();
    return retval;
}
コード例 #8
0
ファイル: bytes_format.c プロジェクト: gencer/psycopg2
PyObject *
Bytes_Format(PyObject *format, PyObject *args)
{
    char *fmt, *res;
    Py_ssize_t arglen, argidx;
    Py_ssize_t reslen, rescnt, fmtcnt;
    int args_owned = 0;
    PyObject *result;
    PyObject *dict = NULL;
    if (format == NULL || !Bytes_Check(format) || args == NULL) {
        PyErr_BadInternalCall();
        return NULL;
    }
    fmt = Bytes_AS_STRING(format);
    fmtcnt = Bytes_GET_SIZE(format);
    reslen = rescnt = fmtcnt + 100;
    result = Bytes_FromStringAndSize((char *)NULL, reslen);
    if (result == NULL)
        return NULL;
    res = Bytes_AsString(result);
    if (PyTuple_Check(args)) {
        arglen = PyTuple_GET_SIZE(args);
        argidx = 0;
    }
    else {
        arglen = -1;
        argidx = -2;
    }
    if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
        !PyObject_TypeCheck(args, &Bytes_Type))
        dict = args;
    while (--fmtcnt >= 0) {
        if (*fmt != '%') {
            if (--rescnt < 0) {
                rescnt = fmtcnt + 100;
                reslen += rescnt;
                if (_Bytes_Resize(&result, reslen))
                    return NULL;
                res = Bytes_AS_STRING(result)
                    + reslen - rescnt;
                --rescnt;
            }
            *res++ = *fmt++;
        }
        else {
            /* Got a format specifier */
            Py_ssize_t width = -1;
            int c = '\0';
            PyObject *v = NULL;
            PyObject *temp = NULL;
            char *pbuf;
            Py_ssize_t len;
            fmt++;
            if (*fmt == '(') {
                char *keystart;
                Py_ssize_t keylen;
                PyObject *key;
                int pcount = 1;

                if (dict == NULL) {
                    PyErr_SetString(PyExc_TypeError,
                             "format requires a mapping");
                    goto error;
                }
                ++fmt;
                --fmtcnt;
                keystart = fmt;
                /* Skip over balanced parentheses */
                while (pcount > 0 && --fmtcnt >= 0) {
                    if (*fmt == ')')
                        --pcount;
                    else if (*fmt == '(')
                        ++pcount;
                    fmt++;
                }
                keylen = fmt - keystart - 1;
                if (fmtcnt < 0 || pcount > 0) {
                    PyErr_SetString(PyExc_ValueError,
                               "incomplete format key");
                    goto error;
                }
                key = Text_FromUTF8AndSize(keystart, keylen);
                if (key == NULL)
                    goto error;
                if (args_owned) {
                    Py_DECREF(args);
                    args_owned = 0;
                }
                args = PyObject_GetItem(dict, key);
                Py_DECREF(key);
                if (args == NULL) {
                    goto error;
                }
                args_owned = 1;
                arglen = -1;
                argidx = -2;
            }
            while (--fmtcnt >= 0) {
                c = *fmt++;
                break;
            }
            if (fmtcnt < 0) {
                PyErr_SetString(PyExc_ValueError,
                                "incomplete format");
                goto error;
            }
            if (c != '%') {
                v = getnextarg(args, arglen, &argidx);
                if (v == NULL)
                    goto error;
            }
            switch (c) {
            case '%':
                pbuf = "%";
                len = 1;
                break;
            case 's':
                /* only bytes! */
                if (!Bytes_CheckExact(v)) {
                    PyErr_Format(PyExc_ValueError,
                                    "only bytes values expected, got %s",
                                    Py_TYPE(v)->tp_name);
                    goto error;
                }
                temp = v;
                Py_INCREF(v);
                pbuf = Bytes_AS_STRING(temp);
                len = Bytes_GET_SIZE(temp);
                break;
            default:
                PyErr_Format(PyExc_ValueError,
                  "unsupported format character '%c' (0x%x) "
                  "at index " FORMAT_CODE_PY_SSIZE_T,
                  c, c,
                  (Py_ssize_t)(fmt - 1 -
                               Bytes_AsString(format)));
                goto error;
            }
            if (width < len)
                width = len;
            if (rescnt < width) {
                reslen -= rescnt;
                rescnt = width + fmtcnt + 100;
                reslen += rescnt;
                if (reslen < 0) {
                    Py_DECREF(result);
                    Py_XDECREF(temp);
                    return PyErr_NoMemory();
                }
                if (_Bytes_Resize(&result, reslen)) {
                    Py_XDECREF(temp);
                    return NULL;
                }
                res = Bytes_AS_STRING(result)
                    + reslen - rescnt;
            }
            Py_MEMCPY(res, pbuf, len);
            res += len;
            rescnt -= len;
            while (--width >= len) {
                --rescnt;
                *res++ = ' ';
            }
            if (dict && (argidx < arglen) && c != '%') {
                PyErr_SetString(PyExc_TypeError,
                           "not all arguments converted during string formatting");
                Py_XDECREF(temp);
                goto error;
            }
            Py_XDECREF(temp);
        } /* '%' */
    } /* until end */
    if (argidx < arglen && !dict) {
        PyErr_SetString(PyExc_TypeError,
                        "not all arguments converted during string formatting");
        goto error;
    }
    if (args_owned) {
        Py_DECREF(args);
    }
    if (_Bytes_Resize(&result, reslen - rescnt))
        return NULL;
    return result;

 error:
    Py_DECREF(result);
    if (args_owned) {
        Py_DECREF(args);
    }
    return NULL;
}