Ejemplo n.º 1
0
static PyObject *
nis_get_default_domain (PyObject *self)
{
	char *domain;
	int err;
	PyObject *res;

	if ((err = yp_get_default_domain(&domain)) != 0)
		return nis_error(err);

	res = PyUnicode_FromStringAndSize (domain, strlen(domain));
	return res;
}
Ejemplo n.º 2
0
static PyObject *idprop_py_from_idp_string(const IDProperty *prop)
{
	if (prop->subtype == IDP_STRING_SUB_BYTE) {
		return PyBytes_FromStringAndSize(IDP_String(prop), prop->len);
	}
	else {
#ifdef USE_STRING_COERCE
		return PyC_UnicodeFromByteAndSize(IDP_Array(prop), prop->len - 1);
#else
		return PyUnicode_FromStringAndSize(IDP_String(prop), prop->len - 1);
#endif
	}
}
Ejemplo n.º 3
0
static PyObject *
_doc2pyobj(rapidjson::Document& doc, char *text)
{
    int is_float;
    unsigned int offset;
    PyObject *pyjson;

    if (!(doc.IsArray() || doc.IsObject())) {
        switch (text[0]) {
        case 't':
            return PyBool_FromLong(1);
        case 'f':
            return PyBool_FromLong(0);
        case 'n':
            Py_RETURN_NONE;
        case '"':
#ifdef PY3
            return PyString_FromStringAndSize(text + 1, strlen(text) - 2);
#else
            PyObject *utf8item;
            utf8item = PyUnicode_FromStringAndSize(text + 1, strlen(text) - 2);
            if (utf8item) {
                return utf8item;
            } else {
                return PyString_FromStringAndSize(text + 1, strlen(text) - 2);
            }
#endif
        default:
            is_float = 0;
            for (offset = 0; offset < strlen(text); offset++) {
                switch (text[offset]) {
                    case '.':
                    case 'e':
                    case 'E':
                        is_float = 1;
                        break;
                }
                if (is_float) break;
            }
            if (is_float) {
                pyjson = PyFloat_FromDouble(atof(text));
            }
            else {
                pyjson = PyInt_FromString(text, NULL, 10);
            }
            return pyjson;
        }
    }

    return doc2pyobj(doc);
}
Ejemplo n.º 4
0
static PyObject *
stat_filemode(PyObject *self, PyObject *omode)
{
    char buf[10];
    mode_t mode;

    mode = _PyLong_AsMode_t(omode);
    if ((mode == (mode_t)-1) && PyErr_Occurred())
        return NULL;

    buf[0] = filetype(mode);
    fileperm(mode, &buf[1]);
    return PyUnicode_FromStringAndSize(buf, 10);
}
Ejemplo n.º 5
0
static PyObject *
s_get(void *ptr, Py_ssize_t size)
{
    Py_ssize_t i;
    char *p;

    p = (char *)ptr;
    for (i = 0; i < size; ++i) {
        if (*p++ == '\0')
            break;
    }

    return PyUnicode_FromStringAndSize((char *)ptr, (Py_ssize_t)i);
}
Ejemplo n.º 6
0
static PyObject *
meth_get__text_signature__(PyCFunctionObject *m, void *closure)
{
    const char *start = find_signature(m);
    const char *trace;

    if (!start) {
        Py_INCREF(Py_None);
        return Py_None;
    }

    trace = skip_signature(start);
    return PyUnicode_FromStringAndSize(start, trace - start);
}
Ejemplo n.º 7
0
static PyObject *ethernet_get_dst(ethernet *self,
                                  void *closure)
{
    char buf[1024];

    snprintf(buf, 1023, "%x:%x:%x:%x:%x:%x",
             self->__ethernet.dst[0],
             self->__ethernet.dst[1],
             self->__ethernet.dst[2],
             self->__ethernet.dst[3],
             self->__ethernet.dst[4],
             self->__ethernet.dst[5]);
    return PyUnicode_FromStringAndSize(buf, strlen(buf));
}
Ejemplo n.º 8
0
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;

		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;
}
Ejemplo n.º 9
0
static PyObject *
zipimport_zipimporter_get_source_impl(ZipImporter *self, PyObject *fullname)
/*[clinic end generated code: output=bc059301b0c33729 input=4e4b186f2e690716]*/
{
    PyObject *toc_entry;
    PyObject *subname, *path, *fullpath;
    enum zi_module_info mi;

    mi = get_module_info(self, fullname);
    if (mi == MI_ERROR)
        return NULL;
    if (mi == MI_NOT_FOUND) {
        PyErr_Format(ZipImportError, "can't find module %R", fullname);
        return NULL;
    }

    subname = get_subname(fullname);
    if (subname == NULL)
        return NULL;

    path = make_filename(self->prefix, subname);
    Py_DECREF(subname);
    if (path == NULL)
        return NULL;

    if (mi == MI_PACKAGE)
        fullpath = PyUnicode_FromFormat("%U%c__init__.py", path, SEP);
    else
        fullpath = PyUnicode_FromFormat("%U.py", path);
    Py_DECREF(path);
    if (fullpath == NULL)
        return NULL;

    toc_entry = PyDict_GetItem(self->files, fullpath);
    Py_DECREF(fullpath);
    if (toc_entry != NULL) {
        PyObject *res, *bytes;
        bytes = get_data(self->archive, toc_entry);
        if (bytes == NULL)
            return NULL;
        res = PyUnicode_FromStringAndSize(PyBytes_AS_STRING(bytes),
                                          PyBytes_GET_SIZE(bytes));
        Py_DECREF(bytes);
        return res;
    }

    /* we have the module, but no source */
    Py_RETURN_NONE;
}
Ejemplo n.º 10
0
PyObject *
PyErr_NewException(const char *name, PyObject *base, PyObject *dict)
{
    const char *dot;
    PyObject *modulename = NULL;
    PyObject *classname = NULL;
    PyObject *mydict = NULL;
    PyObject *bases = NULL;
    PyObject *result = NULL;
    dot = strrchr(name, '.');
    if (dot == NULL) {
        PyErr_SetString(PyExc_SystemError,
            "PyErr_NewException: name must be module.class");
        return NULL;
    }
    if (base == NULL)
        base = PyExc_Exception;
    if (dict == NULL) {
        dict = mydict = PyDict_New();
        if (dict == NULL)
            goto failure;
    }
    if (PyDict_GetItemString(dict, "__module__") == NULL) {
        modulename = PyUnicode_FromStringAndSize(name,
                                             (Py_ssize_t)(dot-name));
        if (modulename == NULL)
            goto failure;
        if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
            goto failure;
    }
    if (PyTuple_Check(base)) {
        bases = base;
        /* INCREF as we create a new ref in the else branch */
        Py_INCREF(bases);
    } else {
        bases = PyTuple_Pack(1, base);
        if (bases == NULL)
            goto failure;
    }
    /* Create a real class. */
    result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
                                   dot+1, bases, dict);
  failure:
    Py_XDECREF(bases);
    Py_XDECREF(mydict);
    Py_XDECREF(classname);
    Py_XDECREF(modulename);
    return result;
}
Ejemplo n.º 11
0
static PyObject *from_entry_data_list(MMDB_entry_data_list_s **entry_data_list)
{
    if (NULL == entry_data_list || NULL == *entry_data_list) {
        PyErr_SetString(
            MaxMindDB_error,
            "Error while looking up data. Your database may be corrupt or you have found a bug in libmaxminddb."
            );
        return NULL;
    }

    switch ((*entry_data_list)->entry_data.type) {
    case MMDB_DATA_TYPE_MAP:
        return from_map(entry_data_list);
    case MMDB_DATA_TYPE_ARRAY:
        return from_array(entry_data_list);
    case MMDB_DATA_TYPE_UTF8_STRING:
        return PyUnicode_FromStringAndSize(
                   (*entry_data_list)->entry_data.utf8_string,
                   (*entry_data_list)->entry_data.data_size
                   );
    case MMDB_DATA_TYPE_BYTES:
        return PyByteArray_FromStringAndSize(
                   (const char *)(*entry_data_list)->entry_data.bytes,
                   (Py_ssize_t)(*entry_data_list)->entry_data.data_size);
    case MMDB_DATA_TYPE_DOUBLE:
        return PyFloat_FromDouble((*entry_data_list)->entry_data.double_value);
    case MMDB_DATA_TYPE_FLOAT:
        return PyFloat_FromDouble((*entry_data_list)->entry_data.float_value);
    case MMDB_DATA_TYPE_UINT16:
        return PyLong_FromLong( (*entry_data_list)->entry_data.uint16);
    case MMDB_DATA_TYPE_UINT32:
        return PyLong_FromLong((*entry_data_list)->entry_data.uint32);
    case MMDB_DATA_TYPE_BOOLEAN:
        return PyBool_FromLong((*entry_data_list)->entry_data.boolean);
    case MMDB_DATA_TYPE_UINT64:
        return PyLong_FromUnsignedLongLong(
                   (*entry_data_list)->entry_data.uint64);
    case MMDB_DATA_TYPE_UINT128:
        return from_uint128(*entry_data_list);
    case MMDB_DATA_TYPE_INT32:
        return PyLong_FromLong((*entry_data_list)->entry_data.int32);
    default:
        PyErr_Format(MaxMindDB_error,
                     "Invalid data type arguments: %d",
                     (*entry_data_list)->entry_data.type);
        return NULL;
    }
    return NULL;
}
Ejemplo n.º 12
0
static PyObject *
Byte_tp_str(PyObject *self)
{
    long i = NATIVEINT_ASLONG(self);
    unsigned char str[2] = { 0, 0 };

    if (i == -1 && PyErr_Occurred())
        return NULL;
    if (i < 0 || i > 255) {
        PyErr_SetString(PyExc_RuntimeError, "Integer outside range 0-255");
        return NULL;
    }

    str[0] = (unsigned char)i;
    return PyUnicode_FromStringAndSize((char *)str, 1);
}
Ejemplo n.º 13
0
static PyObject *
_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {

	char namebuf[X509_NAME_MAXLEN];
	int buflen;
	PyObject *name_obj;
	PyObject *value_obj;
	PyObject *attr;
	unsigned char *valuebuf = NULL;

	buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
	if (buflen < 0) {
		_setSSLError(NULL, 0, __FILE__, __LINE__);
		goto fail;
	}
	name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
	if (name_obj == NULL)
		goto fail;

	buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
	if (buflen < 0) {
		_setSSLError(NULL, 0, __FILE__, __LINE__);
		Py_DECREF(name_obj);
		goto fail;
	}
	value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
						 buflen, "strict");
	OPENSSL_free(valuebuf);
	if (value_obj == NULL) {
		Py_DECREF(name_obj);
		goto fail;
	}
	attr = PyTuple_New(2);
	if (attr == NULL) {
		Py_DECREF(name_obj);
		Py_DECREF(value_obj);
		goto fail;
	}
	PyTuple_SET_ITEM(attr, 0, name_obj);
	PyTuple_SET_ITEM(attr, 1, value_obj);
	return attr;

  fail:
	return NULL;
}
Ejemplo n.º 14
0
PyObject* Preprocessor_format_tokens(Preprocessor *self, PyObject *args)
{
    PyObject *tokens;
    if (!PyArg_ParseTuple(args, "O:format_tokens", &tokens))
        return NULL;

    ScopedPyObject iter(PyObject_GetIter(tokens));
    if (!iter)
        return NULL;

    try
    {
        // Iterate through the tokens, accumulating in a vector.
        std::vector<cmonster::core::Token> token_vector;
        for (;;)
        {
            ScopedPyObject item(PyIter_Next(iter));
            if (!item)
            {
                if (PyErr_Occurred())
                    return NULL;
                else
                    break;
            }
            if (!PyObject_TypeCheck(item, get_token_type()))
            {
                PyErr_SetString(PyExc_TypeError, "Expected sequence of tokens");
                return NULL;
            }
            token_vector.push_back(get_token((Token*)(PyObject*)item));
        }

        // Format the sequence of tokens.
        std::ostringstream ss;
        if (!token_vector.empty())
            self->preprocessor->format(ss, token_vector);
        std::string formatted = ss.str();
        return PyUnicode_FromStringAndSize(formatted.data(), formatted.size());
    }
    catch (...)
    {
        set_python_exception();
        return NULL;
    }
}
Ejemplo n.º 15
0
static void *call_a_string_fun(const char* fun_name,
                               const char *utf8_str, size_t bytes)
{
	PyObject *py_str, *fun_arg;
	PyObject *ret = NULL;
	PyObject *cut_fun /* new ref */ =
	          PyObject_GetAttrString(jieba_module, fun_name);

	if (cut_fun == NULL) {
		printf("PyObject_GetAttrString(`%s') fails.\n",
		       JIEBA_WRAP_CUT_FUN);
		return NULL;
	}
	
	assert(1 == PyCallable_Check(cut_fun));

	/* make function argument before calling cut() */
	fun_arg = PyTuple_New(1); /* new ref */
	
	/* PyUnicode_FromStringAndSize() Create a new Unicode object
	 * (`py_str') from the char buffer. */
	py_str = PyUnicode_FromStringAndSize(utf8_str, bytes);

	if (py_str == NULL) {
		printf("PyUnicode_FromStringAndSize() fails.\n");
		return NULL;
	}

	/* py_str ref_cnt is stolen by PyTuple_SetItem(),
	 * thus no need to Py_DECREF(py_str). */
	PyTuple_SetItem(fun_arg, 0 /* arg[0] */, py_str);
	ret = PyObject_CallObject(cut_fun, fun_arg);
	
	// PRINT_REF_CNT(py_str);

	// PRINT_REF_CNT(cut_fun);
	Py_DECREF(cut_fun);

	// PRINT_REF_CNT(fun_arg);
	Py_XDECREF(fun_arg);
	
	return ret;
}
Ejemplo n.º 16
0
static PyObject *
PongoDict_json(PongoDict *self, PyObject *args)
{
    char *key = NULL, *val = NULL;
    Py_ssize_t klen, vlen;
    PyObject *ret = Py_None;
    dbtype_t dict, obj, k;
    jsonctx_t *jctx;

    if (!PyArg_ParseTuple(args, "|s#s#:json", &key, &klen, &val, &vlen))
        return NULL;

    dblock(self->ctx);
    dict = self->dbptr;
    jctx = json_init(self->ctx);
    if (key) {
        if (val) {
            // 2-arg form is dict.json('key', 'value')
            // inserts dict['key'] = json_parse('value')
            k = dbstring_new(self->ctx, key, klen);
            obj = json_parse(jctx, val, vlen);
            dbobject_setitem(SELF_CTX_AND_DBPTR, k, obj, self->ctx->sync);
        } else {
            // 1-arg form is replace dict.items with parsed json
            obj = json_parse(jctx, key, klen);
            dict.ptr = dbptr(self->ctx, dict);
            obj.ptr = dbptr(self->ctx, obj);
            dict.ptr->obj = obj.ptr->obj;
        }
        Py_INCREF(ret);
    } else {
        // The 0-arg form is to generate the json string from dictionary
        // contents
        json_emit(jctx, dict);
        if (jctx->outstr)
            ret = PyUnicode_FromStringAndSize(
                (const char*)jctx->outstr, jctx->outlen);
    }
    json_cleanup(jctx);
    dbunlock(self->ctx);
    return ret;
}
Ejemplo n.º 17
0
/*
 * Convert a C string in the PostgreSQL server encoding to a Python
 * unicode object.  Reference ownership is passed to the caller.
 */
PyObject *
PLyUnicode_FromStringAndSize(const char *s, Py_ssize_t size)
{
	char	   *utf8string;
	PyObject   *o;

	utf8string = pg_server_to_any(s, size, PG_UTF8);

	if (utf8string == s)
	{
		o = PyUnicode_FromStringAndSize(s, size);
	}
	else
	{
		o = PyUnicode_FromString(utf8string);
		pfree(utf8string);
	}

	return o;
}
Ejemplo n.º 18
0
static void
http_vrow_callback(lcbex_vrow_ctx_t *rctx,
                   const void *cookie,
                   const lcbex_vrow_datum_t *row)
{
    pycbc_HttpResult *htres = (pycbc_HttpResult *)cookie;

    if (row->type == LCBEX_VROW_ROW) {
        if (row->ndata) {
            PyObject *s = PyUnicode_FromStringAndSize(row->data, row->ndata);
            PyList_Append(htres->rowsbuf, s);
            Py_DECREF(s);
        }

    } else {
        add_data(htres, row->data, row->ndata);
    }

    (void)rctx;
}
Ejemplo n.º 19
0
static BOOL CALLBACK list_windows_callback(HWND hwnd, LPARAM lParam)
{
    PyObject* window_list = (PyObject*) lParam;
    PyObject* item;
    PyObject* title;
    RECT inner, outer;
    int title_size;
    int status;
    
    /* get window title */
    title_size = GetWindowTextLength(hwnd);
    if (title_size > 0) {
        title = PyUnicode_FromStringAndSize(NULL, title_size);
        if (title)
            GetWindowText(hwnd, PyUnicode_AS_UNICODE(title), title_size+1);
    } else
        title = PyUnicode_FromString("");
    if (!title)
        return 0;

    /* get bounding boxes */
    GetClientRect(hwnd, &inner);
    GetWindowRect(hwnd, &outer);

    item = Py_BuildValue(
        "nN(iiii)(iiii)", (Py_ssize_t) hwnd, title,
        inner.left, inner.top, inner.right, inner.bottom,
        outer.left, outer.top, outer.right, outer.bottom
        );
    if (!item)
        return 0;

    status = PyList_Append(window_list, item);

    Py_DECREF(item);

    if (status < 0)
        return 0;
    
    return 1;
}
Ejemplo n.º 20
0
static PyObject *LuaConvert(lua_State *L, int n) {
    PyObject *ret = NULL;
    lua_Object lobj = lua_getparam(L, n);

    if (lua_isnil(L, lobj)) {
        Py_INCREF(Py_None);
        ret = Py_None;

    } else if (lua_isnumber(L, lobj)) {
        double num = lua_getnumber(L, lobj);
        if (rintf((float) num) == num) {  // is int?
            ret = PyInt_FromLong((long) num);
        } else {
            ret = PyFloat_FromDouble(num);
        }
    } else if (lua_isstring(L, lobj)) {
        const char *s = lua_getstring(L, lobj);
        int len = lua_strlen(L, lobj);
        ret = PyString_FromStringAndSize(s, len);
        if (!ret) {
            ret = PyUnicode_FromStringAndSize(s, len);
        }
    } else if (lua_istable(L, lobj)) {
        if (get_base_tag(L) == lua_tag(L, lobj)) {
            py_object *pobj = get_py_object(L, n);
            ret = pobj->o;
            free(pobj);
        } else {
            lua_error(L, "param not supported");
        }
    } else if (lua_isboolean(L, lobj)) {
        if (lua_getboolean(L, lobj)) {
            Py_INCREF(Py_True);
            ret = Py_True;
        } else {
            Py_INCREF(Py_False);
            ret = Py_False;
        }
    }
    return ret;
}
Ejemplo n.º 21
0
static void
add_data(pycbc_HttpResult *htres, const void *data, size_t ndata)
{
    PyObject *o;

    if (!ndata) {
        return;
    }

    if (htres->format == PYCBC_FMT_JSON) {
        o = PyUnicode_FromStringAndSize(data, ndata);

    } else {
        o = PyBytes_FromStringAndSize(data, ndata);
    }

    pycbc_assert(htres->http_data);
    pycbc_assert(o);

    PyList_Append(htres->http_data, o);
    Py_XDECREF(o);
}
Ejemplo n.º 22
0
PyObject* EntityApp<E>::__py_matchPath(PyObject* self, PyObject* args)
{
	int argCount = PyTuple_Size(args);
	if(argCount != 1)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::matchPath(): args is error!");
		PyErr_PrintEx(0);
		return 0;
	}

	char* respath = NULL;

	if(PyArg_ParseTuple(args, "s", &respath) == -1)
	{
		PyErr_Format(PyExc_TypeError, "KBEngine::matchPath(): args is error!");
		PyErr_PrintEx(0);
		return 0;
	}

	std::string path = Resmgr::getSingleton().matchPath(respath);
	return PyUnicode_FromStringAndSize(path.c_str(), path.size());
}
Ejemplo n.º 23
0
Archivo: py.c Proyecto: JanX2/readable
static PyObject *
readable_get_article(PyObject *self, PyObject *args, PyObject *kw)
{
    static char *keywords[] = {
        "html",
        "options",
        NULL,
    };

    char *html;
    int options = READABLE_OPTIONS_DEFAULT;
    if (!PyArg_ParseTupleAndKeywords(args, kw, "s|i", keywords, &html, &options)) {
        return NULL;
    }
    char *article_html = readable(html, "", "UTF-8", options);
    if (!article_html) {
        Py_RETURN_NONE;
    }
    PyObject *article = PyUnicode_FromStringAndSize(article_html, strlen(article_html));
    free(article_html);
    return article;
}
Ejemplo n.º 24
0
static PyObject *ppcap_findalldevs(ppcap *self)
{
    pcap_if_t *alldevsp, *ptr;
    char errbuf[PCAP_ERRBUF_SIZE], buf[1024];
    int num = 0;
    PyObject *list, *unicode;

    if (pcap_findalldevs(&alldevsp, errbuf) == -1) {
        PyErr_Format(PyExc_Ppcap, "%s", errbuf);
        return NULL;
    }
    list = PyList_New(0);

    ptr = alldevsp;
    while (ptr) {
        snprintf(buf, 1023, "%d. device:%s (%s)\nstatus:", ++num,
                 ptr->name, (ptr->description) ? ptr->description :
                 "No description");
        if (ptr->flags & PCAP_IF_LOOPBACK)
            strncat(buf, "loopback, ", 10);
#ifdef PCAP_IF_UP
        if (ptr->flags & PCAP_IF_UP)
            strncat(buf, "up, ", 4);
#endif
#ifdef PCAP_IF_RUNNING
        if (ptr->flags & PCAP_IF_RUNNING)
            strncat(buf, "running", 7);
#endif
        strncat(buf, "\n-------------------------------", 32);
        unicode = PyUnicode_FromStringAndSize(buf, strlen(buf));
        PyList_Append(list, unicode);

        ptr = ptr->next;
    }
    if (alldevsp)
        pcap_freealldevs(alldevsp);
    return list;
}
Ejemplo n.º 25
0
/*
 * Convert a C string in the PostgreSQL server encoding to a Python
 * unicode object.	Reference ownership is passed to the caller.
 */
PyObject *
PyString_FromStringAndSize(const char *s, Py_ssize_t size)
{
	char	   *utf8string;
	PyObject   *o;

	utf8string = (char *) pg_do_encoding_conversion((unsigned char *) s,
													strlen(s),
													GetDatabaseEncoding(),
													PG_UTF8);
	if (size < 0)
	{
		o = PyUnicode_FromString(utf8string);
	}
	else
	{
		o = PyUnicode_FromStringAndSize(utf8string, size);
	}
	if (utf8string != s)
		pfree(utf8string);

	return o;
}
Ejemplo n.º 26
0
static PyObject *from_map(MMDB_entry_data_list_s **entry_data_list)
{
    PyObject *py_obj = PyDict_New();
    if (NULL == py_obj) {
        PyErr_NoMemory();
        return NULL;
    }

    const uint32_t map_size = (*entry_data_list)->entry_data.data_size;

    uint i;
    // entry_data_list cannot start out NULL (see from_entry_data_list). We
    // check it in the loop because it may become NULL.
    // coverity[check_after_deref]
    for (i = 0; i < map_size && entry_data_list; i++) {
        *entry_data_list = (*entry_data_list)->next;

        PyObject *key = PyUnicode_FromStringAndSize(
            (char *)(*entry_data_list)->entry_data.utf8_string,
            (*entry_data_list)->entry_data.data_size
            );

        *entry_data_list = (*entry_data_list)->next;

        PyObject *value = from_entry_data_list(entry_data_list);
        if (NULL == value) {
            Py_DECREF(key);
            Py_DECREF(py_obj);
            return NULL;
        }
        PyDict_SetItem(py_obj, key, value);
        Py_DECREF(value);
        Py_DECREF(key);
    }

    return py_obj;
}
Ejemplo n.º 27
0
static PyObject*
_get_unit(
    PyObject *unit_class,
    PyObject *unit) {

  PyObject *args;
  PyObject *kw;
  PyObject *fits;
  PyObject *result;

  args = PyTuple_New(1);
  PyTuple_SetItem(args, 0, unit);
  Py_INCREF(unit);
  fits = PyUnicode_FromStringAndSize("fits", 4);
  kw = PyDict_New();
  PyDict_SetItemString(kw, "format", fits);

  result = PyObject_Call(unit_class, args, kw);

  Py_DECREF(args);
  Py_DECREF(fits);
  Py_DECREF(kw);
  return result;
}
Ejemplo n.º 28
0
static int handle_string(void *ctx, const unsigned char *value, unsigned int length)
{
    return PlaceObject(ctx, PyUnicode_FromStringAndSize((char *)value, length));
}
Ejemplo n.º 29
0
void PythonTransform::transform(const QByteArray &input, QByteArray &output)
{
    if (input.isEmpty())
        return;

    PyGILState_STATE lgstate;
    lgstate = PyGILState_Ensure();
    if (loadModule()) {
        PyObject * pyInbound = Py_False; // needs reference count management

        if (twoWays)
            pyInbound = (wayValue == INBOUND ? Py_True : Py_False );
        Py_INCREF(pyInbound);

        if (PyModule_AddObject(pModule, PythonModules::INBOUND_ATTR_NAME, pyInbound) == -1) { // steal reference
            pythonmgm->checkPyError();
            logError(tr("T_T Could not set the direction value properly:\n%1").arg(pythonmgm->getLastError()),id);
            Py_XDECREF(pyInbound);
            PyGILState_Release(lgstate);
            return;
        }

        PyObject *paramsdict = PyDict_New(); // setting an empty dictionary
        // setting parameters in the python environment
        if (!parameters.isEmpty()) {
            if (!pythonmgm->checkPyError()) {
                logError(tr("T_T Error while creating the Python parameter dict:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(paramsdict);
                PyGILState_Release(lgstate);
                return;
            }
            // adding parameters to the python list
            QHashIterator<QByteArray, QByteArray> i(parameters);
            while (i.hasNext()) {
                i.next();
                PyObject* paramKey = PyUnicode_FromStringAndSize(i.key(),i.key().size());
                if (!pythonmgm->checkPyError()) {
                    logError(tr("T_T Error while creating Python parameter key:\n%1").arg(pythonmgm->getLastError()), id);
                    Py_XDECREF(paramsdict);
                    PyGILState_Release(lgstate);
                    return;
                }

                PyObject* paramValue = PyUnicode_FromStringAndSize(i.value(),i.value().size());
                if (!pythonmgm->checkPyError()) {
                    logError(tr("T_T Error while creating Python parameter value:\n%1").arg(pythonmgm->getLastError()), id);
                    Py_XDECREF(paramsdict);
                    Py_XDECREF(paramKey);
                    PyGILState_Release(lgstate);
                    return;
                }

                if (PyDict_SetItem(paramsdict,paramKey,paramValue) == -1) { // not stealing reference
                    pythonmgm->checkPyError(); // we already know there was an error
                    logError(tr("T_T Error while setting Python parameter pair:\n%1").arg(pythonmgm->getLastError()), id);
                    Py_XDECREF(paramsdict);
                    Py_XDECREF(paramKey);
                    Py_XDECREF(paramValue);
                    PyGILState_Release(lgstate);
                    return;
                }

                // Cleaning the values (references not stolen)

                Py_XDECREF(paramKey);
                Py_XDECREF(paramValue);
            }
        }

        // setting the dictionary in any case, even if it is empty
        if (PyModule_AddObject(pModule,PythonModules::PARAMS_ATTR_NAME , paramsdict) == -1) { // stolen paramsdict reference
            pythonmgm->checkPyError();
            logError(tr("T_T Could not set the Pip3line_params value properly:\n%1").arg(pythonmgm->getLastError()),id);
        }

        PyObject * pFunc = PyObject_GetAttrString(pModule, PythonModules::MAIN_FUNCTION_NAME);

        if (pythonmgm->checkPyError() && PyCallable_Check(pFunc)) {
            PyObject* pArgs = PyTuple_New(1);

            if (!pythonmgm->checkPyError()) {
                Q_EMIT error(tr("T_T Error while creating the Python argument tuple:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(pFunc);
                Py_XDECREF(pArgs);
                PyGILState_Release(lgstate);
                return;
            }

            PyObject* inputPy = PyByteArray_FromStringAndSize(input.data(),input.size());
            if (!pythonmgm->checkPyError()) {
                Q_EMIT error(tr("T_T Error while creating the Python byte array:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(pFunc);
                Py_XDECREF(pArgs);
                Py_XDECREF(inputPy);
                PyGILState_Release(lgstate);
                return;
            }

            if (PyTuple_SetItem(pArgs, 0, inputPy) != 0) {// stealing the reference of inputPy
                pythonmgm->checkPyError();
                Q_EMIT error(tr("T_T Error while creating the Python byte array:\n%1").arg(pythonmgm->getLastError()), id);
                Py_XDECREF(inputPy);
                Py_XDECREF(pFunc);
                Py_XDECREF(pArgs);
                PyGILState_Release(lgstate);
                return;
            }
            PyObject* returnValue = PyObject_CallObject(pFunc, pArgs); // new ref or NULL

            if (!pythonmgm->checkPyError()) {
                Q_EMIT error(tr("T_T Python error while executing the function:\n %1").arg(pythonmgm->getLastError()), id);
            } else {
                if (PyByteArray_Check(returnValue)) {

                    Py_ssize_t templength = PyByteArray_Size(returnValue);
                    if (templength > BLOCK_MAX_SIZE) {
                        templength = BLOCK_MAX_SIZE;
                        Q_EMIT warning(tr("Data block returned is too large, truncating."),id);
                    }

                    char * buffer = PyByteArray_AsString(returnValue); // never to be deleted
                    output.append(QByteArray(buffer,static_cast<int>(templength))); // safe cast as value was checked earlier
                } else {
                    Q_EMIT error(tr("The Python object returned is not a bytearray"), id);
                }
            }

            Py_XDECREF(returnValue);
            Py_XDECREF(pArgs);
          //  Py_DECREF(inputPy); // stolen reference, don't touch that
            Py_XDECREF(pFunc);

        } else {
            Q_EMIT error(tr("Python error while calling the function %1():\n%2").arg(PythonModules::MAIN_FUNCTION_NAME).arg(pythonmgm->getLastError()), id);
        }
    } else {
        qDebug() << "[Python transform] could not load the module";
    }

    PyGILState_Release(lgstate);
}
Ejemplo n.º 30
0
PyMODINIT_FUNC
init_io(void)
{
    PyObject *m = Py_InitModule4("_io", module_methods,
                                 module_doc, NULL, PYTHON_API_VERSION);
    if (m == NULL)
        return;

    /* put os in the module state */
    _PyIO_os_module = PyImport_ImportModule("os");
    if (_PyIO_os_module == NULL)
        goto fail;

#define ADD_TYPE(type, name) \
    if (PyType_Ready(type) < 0) \
        goto fail; \
    Py_INCREF(type); \
    if (PyModule_AddObject(m, name, (PyObject *)type) < 0) {  \
        Py_DECREF(type); \
        goto fail; \
    }

    /* DEFAULT_BUFFER_SIZE */
    if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
        goto fail;

    /* UnsupportedOperation inherits from ValueError and IOError */
    _PyIO_unsupported_operation = PyObject_CallFunction(
        (PyObject *)&PyType_Type, "s(OO){}",
        "UnsupportedOperation", PyExc_ValueError, PyExc_IOError);
    if (_PyIO_unsupported_operation == NULL)
        goto fail;
    Py_INCREF(_PyIO_unsupported_operation);
    if (PyModule_AddObject(m, "UnsupportedOperation",
                           _PyIO_unsupported_operation) < 0)
        goto fail;

    /* BlockingIOError */
    _PyExc_BlockingIOError.tp_base = (PyTypeObject *) PyExc_IOError;
    ADD_TYPE(&_PyExc_BlockingIOError, "BlockingIOError");

    /* Concrete base types of the IO ABCs.
       (the ABCs themselves are declared through inheritance in io.py)
    */
    ADD_TYPE(&PyIOBase_Type, "_IOBase");
    ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase");
    ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase");
    ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase");

    /* Implementation of concrete IO objects. */
    /* FileIO */
    PyFileIO_Type.tp_base = &PyRawIOBase_Type;
    ADD_TYPE(&PyFileIO_Type, "FileIO");

    /* BytesIO */
    PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBytesIO_Type, "BytesIO");

    /* StringIO */
    PyStringIO_Type.tp_base = &PyTextIOBase_Type;
    ADD_TYPE(&PyStringIO_Type, "StringIO");

    /* BufferedReader */
    PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedReader_Type, "BufferedReader");

    /* BufferedWriter */
    PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter");

    /* BufferedRWPair */
    PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair");

    /* BufferedRandom */
    PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type;
    ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom");

    /* TextIOWrapper */
    PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type;
    ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper");

    /* IncrementalNewlineDecoder */
    ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder");

    /* Interned strings */
    if (!(_PyIO_str_close = PyString_InternFromString("close")))
        goto fail;
    if (!(_PyIO_str_closed = PyString_InternFromString("closed")))
        goto fail;
    if (!(_PyIO_str_decode = PyString_InternFromString("decode")))
        goto fail;
    if (!(_PyIO_str_encode = PyString_InternFromString("encode")))
        goto fail;
    if (!(_PyIO_str_fileno = PyString_InternFromString("fileno")))
        goto fail;
    if (!(_PyIO_str_flush = PyString_InternFromString("flush")))
        goto fail;
    if (!(_PyIO_str_getstate = PyString_InternFromString("getstate")))
        goto fail;
    if (!(_PyIO_str_isatty = PyString_InternFromString("isatty")))
        goto fail;
    if (!(_PyIO_str_newlines = PyString_InternFromString("newlines")))
        goto fail;
    if (!(_PyIO_str_nl = PyString_InternFromString("\n")))
        goto fail;
    if (!(_PyIO_str_read = PyString_InternFromString("read")))
        goto fail;
    if (!(_PyIO_str_read1 = PyString_InternFromString("read1")))
        goto fail;
    if (!(_PyIO_str_readable = PyString_InternFromString("readable")))
        goto fail;
    if (!(_PyIO_str_readinto = PyString_InternFromString("readinto")))
        goto fail;
    if (!(_PyIO_str_readline = PyString_InternFromString("readline")))
        goto fail;
    if (!(_PyIO_str_reset = PyString_InternFromString("reset")))
        goto fail;
    if (!(_PyIO_str_seek = PyString_InternFromString("seek")))
        goto fail;
    if (!(_PyIO_str_seekable = PyString_InternFromString("seekable")))
        goto fail;
    if (!(_PyIO_str_setstate = PyString_InternFromString("setstate")))
        goto fail;
    if (!(_PyIO_str_tell = PyString_InternFromString("tell")))
        goto fail;
    if (!(_PyIO_str_truncate = PyString_InternFromString("truncate")))
        goto fail;
    if (!(_PyIO_str_write = PyString_InternFromString("write")))
        goto fail;
    if (!(_PyIO_str_writable = PyString_InternFromString("writable")))
        goto fail;
    
    if (!(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0)))
        goto fail;
    if (!(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0)))
        goto fail;
    if (!(_PyIO_zero = PyLong_FromLong(0L)))
        goto fail;

    return;

  fail:
    Py_CLEAR(_PyIO_os_module);
    Py_CLEAR(_PyIO_unsupported_operation);
    Py_DECREF(m);
}