static PyObject * new_membership_msg(int type, PyObject *group, int num_members, char (*members)[MAX_GROUP_NAME], char *buffer, int size) { MembershipMsg *self; group_id grp_id; membership_info memb_info; int32 num_extra_members = 0; int i; int ret; assert(group != NULL); self = PyObject_New(MembershipMsg, &MembershipMsg_Type); if (self == NULL) return NULL; self->reason = type & CAUSED_BY_MASK; /* from sp.h defines */ self->msg_subtype = type & (TRANSITION_MESS | REG_MEMB_MESS); Py_INCREF(group); self->group = group; self->members = NULL; self->extra = NULL; self->group_id = NULL; self->changed_member = NULL; self->members = PyTuple_New(num_members); if (self->members == NULL) { Py_DECREF(self); return NULL; } for (i = 0; i < num_members; ++i) { PyObject *s = PyString_FromString(members[i]); if (!s) { Py_DECREF(self); return NULL; } PyTuple_SET_ITEM(self->members, i, s); } if ((ret = SP_get_memb_info(buffer, type, &memb_info)) < 0) { PyErr_Format(SpreadError, "error %d on SP_get_memb_info", ret); Py_DECREF(self); return NULL; } memcpy(&grp_id, &memb_info.gid, sizeof(group_id)); self->group_id = new_group_id(grp_id); if (self->group_id == NULL) { Py_DECREF(self); return NULL; } /* The extra attribute is a tuple initialized for 0 or more items. * If the member event is a single member event such as a join, leave or disconnect, * the changed member attribute is set from memb_info.changed_member * and a single value from vs_set, which is stored inside the message, is added to extra tuple. * If the member event is a merge or partition, the list of member names * from vs_set is stored in extra. */ if (Is_reg_memb_mess(type) && (Is_caused_join_mess(type) || Is_caused_disconnect_mess(type) || Is_caused_leave_mess(type))) { self->changed_member = PyString_FromString(memb_info.changed_member); if (!self->changed_member) { Py_DECREF(self); return NULL; } } else { self->changed_member = Py_BuildValue(""); } num_extra_members = memb_info.my_vs_set.num_members; self->extra = PyTuple_New(num_extra_members); if (self->extra == NULL) { Py_DECREF(self); return NULL; } if (num_extra_members > 0) { char (*member_names)[MAX_GROUP_NAME] = (char (*)[MAX_GROUP_NAME]) malloc(num_extra_members * MAX_GROUP_NAME); if (member_names == NULL) { Py_DECREF(self); PyErr_NoMemory(); return NULL; } if ((ret = SP_get_vs_set_members(buffer, &memb_info.my_vs_set, member_names, num_extra_members)) < 0) { PyErr_Format(SpreadError, "error %d on SP_get_vs_set_members", ret); Py_DECREF(self); free(member_names); return NULL; } for (i = 0; i < num_extra_members; i++) { PyObject *s; s = PyString_FromString(member_names[i]); if (!s) { Py_DECREF(self); free(member_names); return NULL; } PyTuple_SET_ITEM(self->extra, i, s); } free(member_names); } return (PyObject *)self; }
static PyObject * pcre_RegexObject_match(pcre_RegexObject* self, PyObject *args, PyObject *keywds) { char *subject; int pos = INT_MIN, endpos = INT_MIN; // values of non-passed parameters static char *kwlist[] = {"string", "pos", "endpos", NULL}; if (!PyArg_ParseTupleAndKeywords(args, keywds, "s|ii", kwlist, &subject, &pos, &endpos)) return NULL; // negative positions aren't accepted if ((pos < 0 && pos != INT_MIN) || (endpos < 0 && endpos != INT_MIN)) { Py_RETURN_NONE; } int subject_len = strlen(subject); int lastindex = subject_len - 1; if (pos > lastindex || endpos > lastindex) { Py_RETURN_NONE; } // set defaults if (pos == INT_MIN) pos = 0; if (endpos == INT_MIN) endpos = lastindex; // length of substring int substring_len = endpos - pos + 1; // FIXME: jak spravne spocitat velikost vektoru???!!! int ovector_size = self->groups * 3; int *ovector = (int*)malloc(ovector_size * sizeof(int)); if (ovector == NULL) { PyErr_SetString(PcreError, "An error when allocating the offset vector."); return NULL; } int rc = pcre_exec(self->re, self->study, subject, substring_len, pos, 0, ovector, ovector_size); if (rc < 0) { if (rc == PCRE_ERROR_NOMATCH) goto NOMATCH; sprintf(message_buffer, "Match execution exited with an error (code = %d).", rc); PyErr_SetString(PcreError, message_buffer); // TODO: rozliseni chybovych kodu goto ERROR; } pcre_MatchObject *match = PyObject_New(pcre_MatchObject, &pcre_MatchType); if (match == NULL) { PyErr_SetString(PcreError, "An error when allocating _pcre.MatchObject."); goto ERROR; } Py_INCREF(match); Py_INCREF(self); match->re = self; match->offsetvector = ovector; match->stringcount = rc; match->pos = pos; match->endpos = endpos; match->subject = (char *)malloc((subject_len + 1) * sizeof(char)); // +1 for '\0' if (match->subject == NULL) { PyErr_SetString(PcreError, "An error when allocating the subject."); goto ERROR1; } strcpy(match->subject, subject); return match; NOMATCH: free(ovector); Py_RETURN_NONE; ERROR1: Py_XDECREF(self); Py_XDECREF(match); ERROR: free(ovector); return NULL; }
BLOCK_CREATE_FROM(keydata, klen, k, k_len); ivdata = NULL; if (iv_len) BLOCK_CREATE_FROM(ivdata, len, iv, iv_len); cipher->ctx = CYFER_BlockCipher_Init(type, keydata, klen, mtype, ivdata); if (!cipher->ctx) { Py_DECREF(cipher); PyErr_SetString(PyExc_ValueError, "out of memory"); return -1; } return 0; } static PyObject *new(PyTypeObject *objtype, PyObject *args, PyObject *kwargs) { BlockCipherObject *obj = PyObject_New(BlockCipherObject, &BlockCipherType); obj->ctx = NULL; obj->keylen = 0; obj->length = 0; return (PyObject *) obj; } static PyObject *bcipher_encrypt(BlockCipherObject *self, PyObject *args) { unsigned char *s, *in, *out; size_t s_len; if (!PyArg_ParseTuple(args, "s#:Encrypt", &s, &s_len)) return NULL;
PyObject *py_ue_new_edgraphpin(UEdGraphPin *pin) { ue_PyEdGraphPin *ret = (ue_PyEdGraphPin *)PyObject_New(ue_PyEdGraphPin, &ue_PyEdGraphPinType); ret->pin = pin; return (PyObject *)ret; }
static PyObject * AerospikeNullObject_Type_New(PyTypeObject * parent, PyObject * args, PyObject * kwds) { return (PyObject *) PyObject_New(AerospikeNullObject, parent); }
PyObject * wrap_patch(git_patch *patch) { Patch *py_patch; if (!patch) Py_RETURN_NONE; py_patch = PyObject_New(Patch, &PatchType); if (py_patch) { size_t i, j, hunk_amounts, lines_in_hunk, additions, deletions; const git_diff_delta *delta; const git_diff_hunk *hunk; const git_diff_line *line; int err; delta = git_patch_get_delta(patch); py_patch->old_file_path = delta->old_file.path; py_patch->new_file_path = delta->new_file.path; py_patch->status = git_diff_status_char(delta->status); py_patch->similarity = delta->similarity; py_patch->flags = delta->flags; py_patch->old_id = git_oid_allocfmt(&delta->old_file.id); py_patch->new_id = git_oid_allocfmt(&delta->new_file.id); git_patch_line_stats(NULL, &additions, &deletions, patch); py_patch->additions = additions; py_patch->deletions = deletions; hunk_amounts = git_patch_num_hunks(patch); py_patch->hunks = PyList_New(hunk_amounts); for (i = 0; i < hunk_amounts; ++i) { Hunk *py_hunk = NULL; err = git_patch_get_hunk(&hunk, &lines_in_hunk, patch, i); if (err < 0) return Error_set(err); py_hunk = PyObject_New(Hunk, &HunkType); if (py_hunk != NULL) { py_hunk->old_start = hunk->old_start; py_hunk->old_lines = hunk->old_lines; py_hunk->new_start = hunk->new_start; py_hunk->new_lines = hunk->new_lines; py_hunk->lines = PyList_New(lines_in_hunk); for (j = 0; j < lines_in_hunk; ++j) { PyObject *py_line_origin = NULL, *py_line = NULL; err = git_patch_get_line_in_hunk(&line, patch, i, j); if (err < 0) return Error_set(err); py_line_origin = to_unicode_n(&line->origin, 1, NULL, NULL); py_line = to_unicode_n(line->content, line->content_len, NULL, NULL); PyList_SetItem(py_hunk->lines, j, Py_BuildValue("OO", py_line_origin, py_line)); Py_DECREF(py_line_origin); Py_DECREF(py_line); } PyList_SetItem((PyObject*) py_patch->hunks, i, (PyObject*) py_hunk); } } } git_patch_free(patch); return (PyObject*) py_patch; }
static SpongeObject *alloc_sponge(void) { return PyObject_New(SpongeObject, &SpongeType); }
PyObject* pyLODDist_FromLODDist(plLODDist& dist) { pyLODDist* obj = PyObject_New(pyLODDist, &pyLODDist_Type); obj->fThis = &dist; return (PyObject*)obj; }
/* * Constructor for X509Extension, never called by Python code directly * * Arguments: type_name - ??? * critical - ??? * value - ??? * subject - An x509v3 certificate which is the subject for this extension. * issuer - An x509v3 certificate which is the issuer for this extension. * Returns: The newly created X509Extension object */ crypto_X509ExtensionObj * crypto_X509Extension_New(char *type_name, int critical, char *value, crypto_X509Obj *subject, crypto_X509Obj *issuer) { X509V3_CTX ctx; crypto_X509ExtensionObj *self; char* value_with_critical = NULL; /* * A context is necessary for any extension which uses the r2i conversion * method. That is, X509V3_EXT_nconf may segfault if passed a NULL ctx. * Start off by initializing most of the fields to NULL. */ X509V3_set_ctx(&ctx, NULL, NULL, NULL, NULL, 0); /* * We have no configuration database - but perhaps we should (some * extensions may require it). */ X509V3_set_ctx_nodb(&ctx); /* * Initialize the subject and issuer, if appropriate. ctx is a local, and * as far as I can tell none of the X509V3_* APIs invoked here steal any * references, so no need to incref subject or issuer. */ if (subject) { ctx.subject_cert = subject->x509; } if (issuer) { ctx.issuer_cert = issuer->x509; } self = PyObject_New(crypto_X509ExtensionObj, &crypto_X509Extension_Type); if (self == NULL) { goto error; } self->dealloc = 0; /* There are other OpenSSL APIs which would let us pass in critical * separately, but they're harder to use, and since value is already a pile * of crappy junk smuggling a ton of utterly important structured data, * what's the point of trying to avoid nasty stuff with strings? (However, * X509V3_EXT_i2d in particular seems like it would be a better API to * invoke. I do not know where to get the ext_struc it desires for its * last parameter, though.) */ value_with_critical = malloc(strlen("critical,") + strlen(value) + 1); if (!value_with_critical) { goto critical_malloc_error; } if (critical) { strcpy(value_with_critical, "critical,"); strcpy(value_with_critical + strlen("critical,"), value); } else { strcpy(value_with_critical, value); } self->x509_extension = X509V3_EXT_nconf( NULL, &ctx, type_name, value_with_critical); free(value_with_critical); if (!self->x509_extension) { goto nconf_error; } self->dealloc = 1; return self; nconf_error: exception_from_error_queue(crypto_Error); critical_malloc_error: Py_XDECREF(self); error: return NULL; }
inline PyObject_t *pynew(void) { return PyObject_New(PyObject_t, &_body); }
PyObject *py_ue_new_fviewport_client(TSharedRef<FViewportClient> viewport_client) { ue_PyFViewportClient *ret = (ue_PyFViewportClient *)PyObject_New(ue_PyFViewportClient, &ue_PyFViewportClientType); new(&ret->viewport_client) TSharedRef<FViewportClient>(viewport_client); return (PyObject *)ret; }
PyObject* pyLocation_FromLocation(const plLocation& loc) { pyLocation* obj = PyObject_New(pyLocation, &pyLocation_Type); obj->fThis = new plLocation(loc); return (PyObject*)obj; }
PySfColor * GetNewPySfColor() { return PyObject_New(PySfColor, &PySfColorType); }
/** * Decode a chunk of samples. * * @param di The decoder instance to call. Must not be NULL. * @param start_samplenum The starting sample number for the buffer's sample * set, relative to the start of capture. * @param end_samplenum The ending sample number for the buffer's sample * set, relative to the start of capture. * @param inbuf The buffer to decode. Must not be NULL. * @param inbuflen Length of the buffer. Must be > 0. * @param unitsize The number of bytes per sample. Must be > 0. * * @return SRD_OK upon success, a (negative) error code otherwise. * * @private */ SRD_PRIV int srd_inst_decode(const struct srd_decoder_inst *di, uint64_t start_samplenum, uint64_t end_samplenum, const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize) { PyObject *py_res; srd_logic *logic; long apiver; /* Return an error upon unusable input. */ if (!di) { srd_dbg("empty decoder instance"); return SRD_ERR_ARG; } if (!inbuf) { srd_dbg("NULL buffer pointer"); return SRD_ERR_ARG; } if (inbuflen == 0) { srd_dbg("empty buffer"); return SRD_ERR_ARG; } if (unitsize == 0) { srd_dbg("unitsize 0"); return SRD_ERR_ARG; } ((struct srd_decoder_inst *)di)->data_unitsize = unitsize; srd_dbg("Decoding: start sample %" PRIu64 ", end sample %" PRIu64 " (%" PRIu64 " samples, %" PRIu64 " bytes, unitsize = " "%d), instance %s.", start_samplenum, end_samplenum, end_samplenum - start_samplenum, inbuflen, di->data_unitsize, di->inst_id); apiver = srd_decoder_apiver(di->decoder); if (apiver == 2) { /* * Create new srd_logic object. Each iteration around the PD's * loop will fill one sample into this object. */ logic = PyObject_New(srd_logic, (PyTypeObject *)srd_logic_type); Py_INCREF(logic); logic->di = (struct srd_decoder_inst *)di; logic->start_samplenum = start_samplenum; logic->itercnt = 0; logic->inbuf = (uint8_t *)inbuf; logic->inbuflen = inbuflen; logic->sample = PyList_New(2); Py_INCREF(logic->sample); Py_IncRef(di->py_inst); if (!(py_res = PyObject_CallMethod(di->py_inst, "decode", "KKO", start_samplenum, end_samplenum, logic))) { srd_exception_catch("Protocol decoder instance %s", di->inst_id); return SRD_ERR_PYTHON; } Py_DecRef(py_res); } return SRD_OK; }
PyObject* cDBResult::getPyObject() { wpDbResult* returnVal = PyObject_New( wpDbResult, &wpDbResultType ); returnVal->result = this; return ( PyObject * ) returnVal; }
PyObject* pyMatrix44_FromMatrix44(const hsMatrix44& mat) { pyMatrix44* pmat = PyObject_New(pyMatrix44, &pyMatrix44_Type); pmat->fThis = new hsMatrix44(mat); return (PyObject*)pmat; }
PyObject* diff_get_patch_byindex(git_diff_list* list, size_t idx) { const git_diff_delta* delta; const git_diff_range* range; git_diff_patch* patch = NULL; size_t i, j, hunk_amounts, lines_in_hunk, line_len, header_len; const char* line, *header; int err; Hunk *py_hunk = NULL; Patch *py_patch = NULL; err = git_diff_get_patch(&patch, &delta, list, idx); if (err < 0) return Error_set(err); py_patch = PyObject_New(Patch, &PatchType); if (py_patch != NULL) { py_patch->old_file_path = delta->old_file.path; py_patch->new_file_path = delta->new_file.path; py_patch->status = git_diff_status_char(delta->status); py_patch->similarity = delta->similarity; py_patch->old_oid = git_oid_allocfmt(&delta->old_file.oid); py_patch->new_oid = git_oid_allocfmt(&delta->new_file.oid); hunk_amounts = git_diff_patch_num_hunks(patch); py_patch->hunks = PyList_New(hunk_amounts); for (i=0; i < hunk_amounts; ++i) { err = git_diff_patch_get_hunk(&range, &header, &header_len, &lines_in_hunk, patch, i); if (err < 0) goto cleanup; py_hunk = PyObject_New(Hunk, &HunkType); if (py_hunk != NULL) { py_hunk->old_start = range->old_start; py_hunk->old_lines = range->old_lines; py_hunk->new_start = range->new_start; py_hunk->new_lines = range->new_lines; py_hunk->lines = PyList_New(lines_in_hunk + 1); PyList_SetItem(py_hunk->lines, 0, to_unicode_n(header, header_len, NULL, NULL)); for (j=1; j < lines_in_hunk + 1; ++j) { err = git_diff_patch_get_line_in_hunk(&py_hunk->origin, &line, &line_len, NULL, NULL, patch, i, j - 1); if (err < 0) goto cleanup; PyList_SetItem(py_hunk->lines, j, to_unicode_n(line, line_len, NULL, NULL)); } PyList_SetItem((PyObject*) py_patch->hunks, i, (PyObject*) py_hunk); } } } cleanup: git_diff_patch_free(patch); return (err < 0) ? Error_set(err) : (PyObject*) py_patch; }
void *uwsgi_request_subhandler_wsgi(struct wsgi_request *wsgi_req, struct uwsgi_app *wi) { PyObject *zero; int i; PyObject *pydictkey, *pydictvalue; char *path_info; for (i = 0; i < wsgi_req->var_cnt; i += 2) { #ifdef UWSGI_DEBUG uwsgi_debug("%.*s: %.*s\n", wsgi_req->hvec[i].iov_len, wsgi_req->hvec[i].iov_base, wsgi_req->hvec[i+1].iov_len, wsgi_req->hvec[i+1].iov_base); #endif #ifdef PYTHREE pydictkey = PyUnicode_DecodeLatin1(wsgi_req->hvec[i].iov_base, wsgi_req->hvec[i].iov_len, NULL); pydictvalue = PyUnicode_DecodeLatin1(wsgi_req->hvec[i + 1].iov_base, wsgi_req->hvec[i + 1].iov_len, NULL); #else pydictkey = PyString_FromStringAndSize(wsgi_req->hvec[i].iov_base, wsgi_req->hvec[i].iov_len); pydictvalue = PyString_FromStringAndSize(wsgi_req->hvec[i + 1].iov_base, wsgi_req->hvec[i + 1].iov_len); #endif #ifdef UWSGI_DEBUG uwsgi_log("%p %d %p %d\n", pydictkey, wsgi_req->hvec[i].iov_len, pydictvalue, wsgi_req->hvec[i + 1].iov_len); #endif PyDict_SetItem(wsgi_req->async_environ, pydictkey, pydictvalue); Py_DECREF(pydictkey); Py_DECREF(pydictvalue); } if (wsgi_req->uh.modifier1 == UWSGI_MODIFIER_MANAGE_PATH_INFO) { wsgi_req->uh.modifier1 = 0; pydictkey = PyDict_GetItemString(wsgi_req->async_environ, "SCRIPT_NAME"); if (pydictkey) { if (PyString_Check(pydictkey)) { pydictvalue = PyDict_GetItemString(wsgi_req->async_environ, "PATH_INFO"); if (pydictvalue) { if (PyString_Check(pydictvalue)) { path_info = PyString_AsString(pydictvalue); PyDict_SetItemString(wsgi_req->async_environ, "PATH_INFO", PyString_FromString(path_info + PyString_Size(pydictkey))); } } } } } // if async_post is mapped as a file, directly use it as wsgi.input if (wsgi_req->async_post) { #ifdef PYTHREE wsgi_req->async_input = PyFile_FromFd(fileno((FILE *)wsgi_req->async_post), "wsgi_input", "rb", 0, NULL, NULL, NULL, 0); #else wsgi_req->async_input = PyFile_FromFile(wsgi_req->async_post, "wsgi_input", "r", NULL); #endif } else { // create wsgi.input custom object wsgi_req->async_input = (PyObject *) PyObject_New(uwsgi_Input, &uwsgi_InputType); ((uwsgi_Input*)wsgi_req->async_input)->wsgi_req = wsgi_req; ((uwsgi_Input*)wsgi_req->async_input)->pos = 0; ((uwsgi_Input*)wsgi_req->async_input)->readline_pos = 0; ((uwsgi_Input*)wsgi_req->async_input)->readline_max_size = 0; } PyDict_SetItemString(wsgi_req->async_environ, "wsgi.input", wsgi_req->async_input); #ifdef UWSGI_SENDFILE PyDict_SetItemString(wsgi_req->async_environ, "wsgi.file_wrapper", wi->sendfile); #endif #ifdef UWSGI_ASYNC if (uwsgi.async > 1) { PyDict_SetItemString(wsgi_req->async_environ, "x-wsgiorg.fdevent.readable", wi->eventfd_read); PyDict_SetItemString(wsgi_req->async_environ, "x-wsgiorg.fdevent.writable", wi->eventfd_write); PyDict_SetItemString(wsgi_req->async_environ, "x-wsgiorg.fdevent.timeout", Py_None); } #endif PyDict_SetItemString(wsgi_req->async_environ, "wsgi.version", wi->gateway_version); zero = PyFile_FromFile(stderr, "wsgi_errors", "w", NULL); PyDict_SetItemString(wsgi_req->async_environ, "wsgi.errors", zero); Py_DECREF(zero); PyDict_SetItemString(wsgi_req->async_environ, "wsgi.run_once", Py_False); if (uwsgi.threads > 1) { PyDict_SetItemString(wsgi_req->async_environ, "wsgi.multithread", Py_True); } else { PyDict_SetItemString(wsgi_req->async_environ, "wsgi.multithread", Py_False); } if (uwsgi.numproc == 1) { PyDict_SetItemString(wsgi_req->async_environ, "wsgi.multiprocess", Py_False); } else { PyDict_SetItemString(wsgi_req->async_environ, "wsgi.multiprocess", Py_True); } if (wsgi_req->scheme_len > 0) { zero = UWSGI_PYFROMSTRINGSIZE(wsgi_req->scheme, wsgi_req->scheme_len); } else if (wsgi_req->https_len > 0) { if (!strncasecmp(wsgi_req->https, "on", 2) || wsgi_req->https[0] == '1') { zero = UWSGI_PYFROMSTRING("https"); } else { zero = UWSGI_PYFROMSTRING("http"); } } else { zero = UWSGI_PYFROMSTRING("http"); } PyDict_SetItemString(wsgi_req->async_environ, "wsgi.url_scheme", zero); Py_DECREF(zero); wsgi_req->async_app = wi->callable; // export .env only in non-threaded mode if (uwsgi.threads < 2) { PyDict_SetItemString(up.embedded_dict, "env", wsgi_req->async_environ); } PyDict_SetItemString(wsgi_req->async_environ, "uwsgi.version", wi->uwsgi_version); if (uwsgi.cores > 1) { zero = PyInt_FromLong(wsgi_req->async_id); PyDict_SetItemString(wsgi_req->async_environ, "uwsgi.core", zero); Py_DECREF(zero); } // cache this ? if (uwsgi.cluster_fd >= 0) { zero = PyString_FromString(uwsgi.cluster); PyDict_SetItemString(wsgi_req->async_environ, "uwsgi.cluster", zero); Py_DECREF(zero); zero = PyString_FromString(uwsgi.hostname); PyDict_SetItemString(wsgi_req->async_environ, "uwsgi.cluster_node", zero); Py_DECREF(zero); } PyDict_SetItemString(wsgi_req->async_environ, "uwsgi.node", wi->uwsgi_node); // call PyTuple_SetItem(wsgi_req->async_args, 0, wsgi_req->async_environ); return python_call(wsgi_req->async_app, wsgi_req->async_args, uwsgi.catch_exceptions, wsgi_req); }
PyObject *py_ue_new_fraw_anim_sequence_track(FRawAnimSequenceTrack raw_anim_sequence_track) { ue_PyFRawAnimSequenceTrack *ret = (ue_PyFRawAnimSequenceTrack *)PyObject_New(ue_PyFRawAnimSequenceTrack, &ue_PyFRawAnimSequenceTrackType); new(&ret->raw_anim_sequence_track) FRawAnimSequenceTrack(raw_anim_sequence_track); return (PyObject *)ret; }
/* XXX(nnorwitz): should we error check if the user passes any empty ranges? range(-10) range(0, -5) range(0, 5, -1) */ static PyObject * range_new(PyTypeObject *type, PyObject *args, PyObject *kw) { rangeobject *obj = NULL; PyObject *start = NULL, *stop = NULL, *step = NULL; if (!_PyArg_NoKeywords("range()", kw)) return NULL; if (PyTuple_Size(args) <= 1) { if (!PyArg_UnpackTuple(args, "range", 1, 1, &stop)) return NULL; stop = PyNumber_Index(stop); if (!stop) return NULL; start = PyLong_FromLong(0); if (!start) { Py_DECREF(stop); return NULL; } step = PyLong_FromLong(1); if (!step) { Py_DECREF(stop); Py_DECREF(start); return NULL; } } else { if (!PyArg_UnpackTuple(args, "range", 2, 3, &start, &stop, &step)) return NULL; /* Convert borrowed refs to owned refs */ start = PyNumber_Index(start); if (!start) return NULL; stop = PyNumber_Index(stop); if (!stop) { Py_DECREF(start); return NULL; } step = validate_step(step); /* Caution, this can clear exceptions */ if (!step) { Py_DECREF(start); Py_DECREF(stop); return NULL; } } obj = PyObject_New(rangeobject, &PyRange_Type); if (obj == NULL) goto Fail; obj->start = start; obj->stop = stop; obj->step = step; return (PyObject *) obj; Fail: Py_XDECREF(start); Py_XDECREF(stop); Py_XDECREF(step); return NULL; }
static PyObject * range_reverse(PyObject *seq) { rangeobject *range = (rangeobject*) seq; longrangeiterobject *it; PyObject *one, *sum, *diff, *product; long lstart, lstop, lstep, new_start, new_stop; unsigned long ulen; assert(PyRange_Check(seq)); /* reversed(range(start, stop, step)) can be expressed as range(start+(n-1)*step, start-step, -step), where n is the number of integers in the range. If each of start, stop, step, -step, start-step, and the length of the iterator is representable as a C long, use the int version. This excludes some cases where the reversed range is representable as a range_iterator, but it's good enough for common cases and it makes the checks simple. */ lstart = PyLong_AsLong(range->start); if (lstart == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } lstop = PyLong_AsLong(range->stop); if (lstop == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } lstep = PyLong_AsLong(range->step); if (lstep == -1 && PyErr_Occurred()) { PyErr_Clear(); goto long_range; } /* check for possible overflow of -lstep */ if (lstep == LONG_MIN) goto long_range; /* check for overflow of lstart - lstep: for lstep > 0, need only check whether lstart - lstep < LONG_MIN. for lstep < 0, need only check whether lstart - lstep > LONG_MAX Rearrange these inequalities as: lstart - LONG_MIN < lstep (lstep > 0) LONG_MAX - lstart < -lstep (lstep < 0) and compute both sides as unsigned longs, to avoid the possibility of undefined behaviour due to signed overflow. */ if (lstep > 0) { if ((unsigned long)lstart - LONG_MIN < (unsigned long)lstep) goto long_range; } else { if (LONG_MAX - (unsigned long)lstart < 0UL - lstep) goto long_range; } ulen = get_len_of_range(lstart, lstop, lstep); if (ulen > (unsigned long)LONG_MAX) goto long_range; new_stop = lstart - lstep; new_start = (long)(new_stop + ulen * lstep); return fast_range_iter(new_start, new_stop, -lstep); long_range: it = PyObject_New(longrangeiterobject, &PyLongRangeIter_Type); if (it == NULL) return NULL; /* start + (len - 1) * step */ it->len = range->length; Py_INCREF(it->len); one = PyLong_FromLong(1); if (!one) goto create_failure; diff = PyNumber_Subtract(it->len, one); Py_DECREF(one); if (!diff) goto create_failure; product = PyNumber_Multiply(diff, range->step); Py_DECREF(diff); if (!product) goto create_failure; sum = PyNumber_Add(range->start, product); Py_DECREF(product); it->start = sum; if (!it->start) goto create_failure; it->step = PyNumber_Negative(range->step); if (!it->step) goto create_failure; it->index = PyLong_FromLong(0); if (!it->index) goto create_failure; return (PyObject *)it; create_failure: Py_DECREF(it); return NULL; }
krb5KeyblockObject *keyblock_new(PyObject *unused, PyObject *args) { krb5_error_code ret; krb5ContextObject *context; krb5EnctypeObject *enctype; char *password; PyObject *arg; krb5KeyblockObject *self = (krb5KeyblockObject *) PyObject_New(krb5KeyblockObject, &krb5KeyblockType); int error = 0; if (!PyArg_ParseTuple(args, "OOsO", &context, &enctype, &password, &arg)) return NULL; if (self == NULL) return NULL; self->context = context->context; #if PY_MAJOR_VERSION >= 2 && PY_MINOR_VERSION >= 2 if (PyObject_TypeCheck(arg, &krb5SaltType)) { krb5SaltObject *salt = (krb5SaltObject*)arg; ret = krb5_string_to_key_salt(context->context, enctype->enctype, password, salt->salt, &self->keyblock); } else if (PyObject_TypeCheck(arg, &krb5PrincipalType)) { #else if (1) { #endif krb5PrincipalObject *principal = (krb5PrincipalObject*)arg; ret = krb5_string_to_key(context->context, enctype->enctype, password, principal->principal, &self->keyblock); } else { PyErr_SetString(PyExc_TypeError, "either principal or salt needs to be passed"); error = 1; goto out; } if (ret) { error = 1; krb5_exception(NULL, ret); goto out; } out: if (error) return NULL; else return self; } krb5KeyblockObject *keyblock_raw_new(PyObject *unused, PyObject *args) { krb5_error_code ret; krb5ContextObject *py_context; PyObject *py_enctype; PyObject *py_key; uint8_t *key_buf; size_t key_len; krb5_enctype enctype; int error = 0; krb5KeyblockObject *self = (krb5KeyblockObject *) PyObject_NEW(krb5KeyblockObject, &krb5KeyblockType); if (!PyArg_ParseTuple(args, "O!OS", &krb5ContextType, &py_context, &py_enctype, &py_key)) return NULL; if (self == NULL) return NULL; self->context = py_context->context; if (PyObject_TypeCheck(py_enctype, &krb5EnctypeType)) { krb5EnctypeObject *enctype_obj = (krb5EnctypeObject*)py_enctype; enctype = enctype_obj>enctype; } else if (PyInt_Check(py_enctype)) { enctype = PyInt_AsLong(py_enctype); } else { PyErr_SetString(PyExc_TypeError, "enctype must be of type integer or krb5EnctypeObject"); error = 1; goto out; } key_buf = (uint8_t *) PyString_AsString(py_key); key_len = PyString_Size(py_key); ret = krb5_keyblock_init(py_context->context, enctype, key_buf, key_len, &self->keyblock); if (ret) { error = 1; krb5_exception(NULL, ret); goto out; } out: if (error) return NULL; else return self; }
static SHAobject * newSHA3object(void) { return (SHAobject *)PyObject_New(SHAobject, &SHA3type); }
ue_PyFSlateStyleSet* py_ue_new_fslate_style_set(FSlateStyleSet* styleSet) { ue_PyFSlateStyleSet *ret = (ue_PyFSlateStyleSet *)PyObject_New(ue_PyFSlateStyleSet, &ue_PyFSlateStyleSetType); ret->style_set = styleSet; return ret; }
// @pymethod <o Pymmapfile>|mmapfile|mmapfile|Creates or opens a memory mapped file. // This method uses the following API functions: CreateFileMapping, MapViewOfFile, VirtualQuery // @comm Accepts keyword args. // @pyseeapi CreateFileMapping // @pyseeapi MapViewOfFile // @pyseeapi VirtualQuery static PyObject * new_mmapfile_object (PyObject * self, PyObject * args, PyObject *kwargs) { mmapfile_object * m_obj; TCHAR * filename; PyObject *obfilename, *obtagname, *obview_size=Py_None; PSECURITY_ATTRIBUTES psa=NULL; // Not accepted as a parameter yet m_obj = PyObject_New (mmapfile_object, &mmapfile_object_type); if (m_obj == NULL) return NULL; m_obj->file_handle = INVALID_HANDLE_VALUE; m_obj->map_handle = NULL; m_obj->data = NULL; m_obj->pos = 0; m_obj->size = 0; m_obj->mapping_size.QuadPart = 0; m_obj->offset.QuadPart = 0; m_obj->tagname = NULL; m_obj->creation_status = 0; static char *keywords[]={"File", "Name", "MaximumSize", "FileOffset", "NumberOfBytesToMap", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|KKO", keywords, &obfilename, // @pyparm str|File||Name of file. Use None or '' when opening an existing named mapping, or to use system pagefile. &obtagname, // @pyparm str|Name||Name of mapping object to create or open, can be None &m_obj->mapping_size.QuadPart, // @pyparm int|MaximumSize|0|Size of file mapping to create, should be specified as a multiple // of system page size (see <om win32api.GetSystemInfo>). Defaults to size of existing file if 0. // If an existing named mapping is opened, the returned object will have the same size as the original mapping. &m_obj->offset.QuadPart, // @pyparm int|FileOffset|0|Offset into the file at which to create view. This should be specified as a // multiple of system allocation granularity. (see <om win32api.GetSystemInfo>) &obview_size)){ // @pyparm int|NumberOfBytesToMap|0|Size of view to create, also a multiple of system page size. // If 0, view will span from offset to end of file mapping. Py_DECREF(m_obj); return NULL; } if (!PyWinObject_AsTCHAR(obtagname, &m_obj->tagname, TRUE)){ Py_DECREF(m_obj); return NULL; } if (!PyWinObject_AsTCHAR(obfilename, &filename, TRUE)){ Py_DECREF(m_obj); return NULL; } if (obview_size!=Py_None){ m_obj->size=PyInt_AsSsize_t(obview_size); if (m_obj->size==-1 && PyErr_Occurred()){ Py_DECREF(m_obj); PyWinObject_FreeTCHAR(filename); return NULL; } } // if an actual filename has been specified if (filename && _tcslen(filename)){ m_obj->file_handle = CreateFile (filename, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, psa, OPEN_ALWAYS, 0, NULL); if (m_obj->file_handle == INVALID_HANDLE_VALUE){ Py_DECREF(m_obj); PyWinObject_FreeTCHAR(filename); return PyWin_SetAPIError("CreateFile"); } } PyWinObject_FreeTCHAR(filename); // If mapping size was not specified, use existing file size if ((!m_obj->mapping_size.QuadPart) && (m_obj->file_handle != INVALID_HANDLE_VALUE)){ m_obj->mapping_size.LowPart = GetFileSize (m_obj->file_handle, &m_obj->mapping_size.HighPart); if (m_obj->mapping_size.LowPart == INVALID_FILE_SIZE){ DWORD err=GetLastError(); if (err != NO_ERROR){ Py_DECREF(m_obj); return PyWin_SetAPIError("GetFileSize", err); } } // Must specify either mapping size or a non-empty file if (!m_obj->mapping_size.QuadPart){ PyErr_SetString(PyExc_ValueError, "Specified file is empty, and no mapping size given"); return NULL; } // Round file size up to a multiple of system page size SYSTEM_INFO si; GetSystemInfo(&si); if (m_obj->mapping_size.QuadPart % si.dwPageSize) m_obj->mapping_size.QuadPart += si.dwPageSize-(m_obj->mapping_size.QuadPart % si.dwPageSize); } m_obj->map_handle = CreateFileMapping (m_obj->file_handle, psa, PAGE_READWRITE, m_obj->mapping_size.HighPart, m_obj->mapping_size.LowPart, m_obj->tagname); if (m_obj->map_handle == NULL){ Py_DECREF(m_obj); return PyWin_SetAPIError("CreateFileMapping"); } /* ??? If an existing named mapping was opened, but a filename was also specified, we've created a superfluous HANDLE that needs to be closed. Should probably also delete the file if one was created. Maybe issue a warning also ??? */ m_obj->creation_status = GetLastError(); if (m_obj->creation_status == ERROR_ALREADY_EXISTS) if (m_obj->file_handle != INVALID_HANDLE_VALUE){ CloseHandle(m_obj->file_handle); m_obj->file_handle = INVALID_HANDLE_VALUE; } m_obj->data = (char *) MapViewOfFile (m_obj->map_handle, FILE_MAP_WRITE, m_obj->offset.HighPart, m_obj->offset.LowPart, m_obj->size); if (m_obj->data == NULL){ Py_DECREF(m_obj); return PyWin_SetAPIError("MapViewOfFile"); } // If view size was not given, use VirtualQuery to determine actual memory available in view if (!m_obj->size){ MEMORY_BASIC_INFORMATION mb; if (!VirtualQuery(m_obj->data, &mb, sizeof(mb))){ Py_DECREF(m_obj); return PyWin_SetAPIError("VirtualQuery"); } m_obj->size = mb.RegionSize; } return ((PyObject *) m_obj); }
PyObject* pyBounds_FromBounds(const hsBounds& bounds) { pyBounds* obj = PyObject_New(pyBounds, &pyBounds_Type); obj->fThis = new hsBounds(bounds); return (PyObject*)obj; }
static oss_audio_t * newossobject(PyObject *arg) { oss_audio_t *self; int fd, afmts, imode; char *devicename = NULL; char *mode = NULL; /* Two ways to call open(): open(device, mode) (for consistency with builtin open()) open(mode) (for backwards compatibility) because the *first* argument is optional, parsing args is a wee bit tricky. */ if (!PyArg_ParseTuple(arg, "s|s:open", &devicename, &mode)) return NULL; if (mode == NULL) { /* only one arg supplied */ mode = devicename; devicename = NULL; } if (strcmp(mode, "r") == 0) imode = O_RDONLY; else if (strcmp(mode, "w") == 0) imode = O_WRONLY; else if (strcmp(mode, "rw") == 0) imode = O_RDWR; else { PyErr_SetString(OSSAudioError, "mode must be 'r', 'w', or 'rw'"); return NULL; } /* Open the correct device: either the 'device' argument, or the AUDIODEV environment variable, or "/dev/dsp". */ if (devicename == NULL) { /* called with one arg */ devicename = getenv("AUDIODEV"); if (devicename == NULL) /* $AUDIODEV not set */ devicename = "/dev/dsp"; } /* Open with O_NONBLOCK to avoid hanging on devices that only allow one open at a time. This does *not* affect later I/O; OSS provides a special ioctl() for non-blocking read/write, which is exposed via oss_nonblock() below. */ fd = _Py_open(devicename, imode|O_NONBLOCK); if (fd == -1) { PyErr_SetFromErrnoWithFilename(PyExc_IOError, devicename); return NULL; } /* And (try to) put it back in blocking mode so we get the expected write() semantics. */ if (fcntl(fd, F_SETFL, 0) == -1) { close(fd); PyErr_SetFromErrnoWithFilename(PyExc_IOError, devicename); return NULL; } if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) { close(fd); PyErr_SetFromErrnoWithFilename(PyExc_IOError, devicename); return NULL; } /* Create and initialize the object */ if ((self = PyObject_New(oss_audio_t, &OSSAudioType)) == NULL) { close(fd); return NULL; } self->devicename = devicename; self->fd = fd; self->mode = imode; self->icount = self->ocount = 0; self->afmts = afmts; return self; }
/* Create a new speller *******************************************************/ static PyObject* new_speller(PyObject* self, PyObject* args) { aspell_AspellObject* newobj; AspellSpeller* speller = 0; AspellConfig* config; AspellCanHaveError* possible_error; int i; int n; /* arg count */ char *key, *value; config = new_aspell_config(); if (config == NULL) { PyErr_SetString(_AspellModuleException, "can't create config"); return NULL; } /* check constructor arguments */ n = PyTuple_Size(args); switch (n) { case 0: /* no arguments passed */ break; case 2: /* constructor is called with single pair: key & value */ if (PyArg_ParseTuple(args, "ss", &key, &value)) { if (!aspell_config_replace(config, key, value)) { PyErr_SetString(_AspellConfigException, aspell_config_error_message(config)); goto arg_error; } break; } PyErr_Clear(); default: /* list of tuples key&value */ for (i=0; i<n; i++) { if (!PyArg_ParseTuple(PyTuple_GetItem(args, i), "ss", &key, &value)) { PyErr_Format(PyExc_TypeError, "argument %d: tuple of two strings (key, value) expeced", i); goto arg_error; } if (!aspell_config_replace(config, key, value)) { PyErr_SetString(_AspellConfigException, aspell_config_error_message(config)); goto arg_error; } } Py_DECREF(args); break; } /* try to create a new speller */ possible_error = new_aspell_speller(config); delete_aspell_config(config); if (aspell_error_number(possible_error) == 0) /* save a speller */ speller = to_aspell_speller(possible_error); else { /* or raise an exception */ PyErr_SetString(_AspellSpellerException, aspell_error_message(possible_error)); delete_aspell_can_have_error(possible_error); return NULL; } /* create a new py-object */ newobj = (aspell_AspellObject*)PyObject_New(aspell_AspellObject, &aspell_AspellType); newobj->speller = speller; return (PyObject*)newobj; /* argument error: before return NULL we need to delete speller's config we've created */ arg_error: delete_aspell_config(config); return NULL; }
PyObject* getPyObjectFromQSqlQuery( QSqlQuery& t ) { wpDbResult* returnVal = PyObject_New( wpDbResult, &wpDbResultType ); returnVal->result = t; return ( PyObject * ) returnVal; }
PyObject *BPy_BMDeformVert_CreatePyObject(struct MDeformVert *dvert) { BPy_BMDeformVert *self = PyObject_New(BPy_BMDeformVert, &BPy_BMDeformVert_Type); self->data = dvert; return (PyObject *)self; }