static PyObject *parse_qs(PyObject *self, PyObject *args, PyObject *kw) { PyObject *pairs, *dict; int i, n, len, lsize; char *qs; int keep_blank_values = 0; int strict_parsing = 0; /* XXX not implemented */ char *keywords[] = { "qs", "keep_blank_values", "strict_parsing", 0 }; if (! PyArg_ParseTupleAndKeywords(args, kw, "s|ii", keywords, &qs, &keep_blank_values, &strict_parsing)) return NULL; /* error */ /* split query string by '&' and ';' into a list of pairs */ /* PYTHON 2.5: 'PyList_New' uses Py_ssize_t for input parameters */ pairs = PyList_New(0); if (pairs == NULL) return NULL; i = 0; len = strlen(qs); while (i < len) { PyObject *pair; char *cpair; int j = 0; /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ pair = PyString_FromStringAndSize(NULL, len); if (pair == NULL) return NULL; /* split by '&' or ';' */ cpair = PyString_AS_STRING(pair); while ((qs[i] != '&') && (qs[i] != ';') && (i < len)) { /* replace '+' with ' ' */ cpair[j] = (qs[i] == '+') ? ' ' : qs[i]; i++; j++; } if (j) { /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */ _PyString_Resize(&pair, j); if (pair) PyList_Append(pairs, pair); } Py_XDECREF(pair); i++; } /* * now we have a list of "abc=def" string (pairs), let's split * them all by '=' and put them in a dictionary. */ dict = PyDict_New(); if (dict == NULL) return NULL; /* PYTHON 2.5: 'PyList_Size' uses Py_ssize_t for input parameters */ lsize = PyList_Size(pairs); n = 0; while (n < lsize) { PyObject *pair, *key, *val; char *cpair, *ckey, *cval; int k, v; pair = PyList_GET_ITEM(pairs, n); cpair = PyString_AS_STRING(pair); len = strlen(cpair); /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ key = PyString_FromStringAndSize(NULL, len); if (key == NULL) return NULL; /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ val = PyString_FromStringAndSize(NULL, len); if (val == NULL) return NULL; ckey = PyString_AS_STRING(key); cval = PyString_AS_STRING(val); i = 0; k = 0; v = 0; while (i < len) { if (cpair[i] != '=') { ckey[k] = cpair[i]; k++; i++; } else { i++; /* skip '=' */ while (i < len) { cval[v] = cpair[i]; v++; i++; } } } ckey[k] = '\0'; cval[v] = '\0'; if (keep_blank_values || (v > 0)) { ap_unescape_url(ckey); ap_unescape_url(cval); /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */ _PyString_Resize(&key, strlen(ckey)); /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */ _PyString_Resize(&val, strlen(cval)); if (key && val) { ckey = PyString_AS_STRING(key); cval = PyString_AS_STRING(val); if (PyMapping_HasKeyString(dict, ckey)) { PyObject *list; list = PyDict_GetItem(dict, key); PyList_Append(list, val); /* PyDict_GetItem is a borrowed ref, no decref */ } else { PyObject *list; list = Py_BuildValue("[O]", val); PyDict_SetItem(dict, key, list); Py_DECREF(list); } } } Py_XDECREF(key); Py_XDECREF(val); n++; } Py_DECREF(pairs); return dict; }
/* * Initial load of the Python module. * * Based on the parsed plugin options we set some prerequisits like the * module path and the module to load. We also load the dictionary used * for looking up the Python methods. */ static bRC PyLoadModule(bpContext *ctx, void *value) { bRC retval = bRC_Error; struct plugin_ctx *p_ctx = (struct plugin_ctx *)ctx->pContext; PyObject *sysPath, *mPath, *pName, *pFunc, *module; /* * Extend the Python search path with the given module_path. */ if (p_ctx->module_path) { sysPath = PySys_GetObject((char *)"path"); mPath = PyString_FromString(p_ctx->module_path); PyList_Append(sysPath, mPath); Py_DECREF(mPath); } /* * Make our callback methods available for Python. */ module = Py_InitModule("bareossd", BareosSDMethods); /* * Try to load the Python module by name. */ if (p_ctx->module_name) { Dmsg(ctx, dbglvl, "Trying to load module with name %s\n", p_ctx->module_name); pName = PyString_FromString(p_ctx->module_name); p_ctx->pModule = PyImport_Import(pName); Py_DECREF(pName); if (!p_ctx->pModule) { Dmsg(ctx, dbglvl, "Failed to load module with name %s\n", p_ctx->module_name); goto bail_out; } Dmsg(ctx, dbglvl, "Successfully loaded module with name %s\n", p_ctx->module_name); /* * Get the Python dictionary for lookups in the Python namespace. */ p_ctx->pDict = PyModule_GetDict(p_ctx->pModule); /* Borrowed reference */ /* * Encode the bpContext so a Python method can pass it in on calling back. */ p_ctx->bpContext = PyCreatebpContext(ctx); /* * Lookup the load_bareos_plugin() function in the python module. */ pFunc = PyDict_GetItemString(p_ctx->pDict, "load_bareos_plugin"); /* Borrowed reference */ if (pFunc && PyCallable_Check(pFunc)) { PyObject *pPluginDefinition, *pRetVal; pPluginDefinition = PyString_FromString((char *)value); if (!pPluginDefinition) { goto bail_out; } pRetVal = PyObject_CallFunctionObjArgs(pFunc, p_ctx->bpContext, pPluginDefinition, NULL); Py_DECREF(pPluginDefinition); if (!pRetVal) { goto bail_out; } else { retval = conv_python_retval(pRetVal); Py_DECREF(pRetVal); } } else { Dmsg(ctx, dbglvl, "Failed to find function named load_bareos_plugins()\n"); goto bail_out; } } /* * Keep track we successfully loaded. */ p_ctx->python_loaded = true; return retval; bail_out: if (PyErr_Occurred()) { PyErrorHandler(ctx, M_FATAL); } return retval; }
static void host_cb(void *arg, int status, int timeouts, struct hostent *hostent) { PyGILState_STATE gstate = PyGILState_Ensure(); char ip[INET6_ADDRSTRLEN]; char **ptr; ares_cb_data_t *data; DNSResolver *self; PyObject *callback, *dns_name, *errorno, *dns_aliases, *dns_addrlist, *dns_result, *tmp, *result; ASSERT(arg); data = (ares_cb_data_t*)arg; self = data->resolver; callback = data->cb; ASSERT(self); /* Object could go out of scope in the callback, increase refcount to avoid it */ Py_INCREF(self); if (status != ARES_SUCCESS) { errorno = PyInt_FromLong((long)status); dns_result = Py_None; Py_INCREF(Py_None); goto callback; } dns_aliases = PyList_New(0); dns_addrlist = PyList_New(0); dns_result = PyTuple_New(3); if (!(dns_aliases && dns_addrlist && dns_result)) { PyErr_NoMemory(); PyErr_WriteUnraisable(Py_None); Py_XDECREF(dns_aliases); Py_XDECREF(dns_addrlist); Py_XDECREF(dns_result); errorno = PyInt_FromLong((long)ARES_ENOMEM); dns_result = Py_None; Py_INCREF(Py_None); goto callback; } for (ptr = hostent->h_aliases; *ptr != NULL; ptr++) { if (*ptr != hostent->h_name && strcmp(*ptr, hostent->h_name)) { tmp = PyString_FromString(*ptr); if (tmp == NULL) { break; } PyList_Append(dns_aliases, tmp); Py_DECREF(tmp); } } for (ptr = hostent->h_addr_list; *ptr != NULL; ptr++) { if (hostent->h_addrtype == AF_INET) { uv_inet_ntop(AF_INET, *ptr, ip, INET_ADDRSTRLEN); tmp = PyString_FromString(ip); } else if (hostent->h_addrtype == AF_INET6) { uv_inet_ntop(AF_INET6, *ptr, ip, INET6_ADDRSTRLEN); tmp = PyString_FromString(ip); } else { continue; } if (tmp == NULL) { break; } PyList_Append(dns_addrlist, tmp); Py_DECREF(tmp); } dns_name = PyString_FromString(hostent->h_name); PyTuple_SET_ITEM(dns_result, 0, dns_name); PyTuple_SET_ITEM(dns_result, 1, dns_aliases); PyTuple_SET_ITEM(dns_result, 2, dns_addrlist); errorno = Py_None; Py_INCREF(Py_None); callback: result = PyObject_CallFunctionObjArgs(callback, self, dns_result, errorno, NULL); if (result == NULL) { PyErr_WriteUnraisable(callback); } Py_XDECREF(result); Py_DECREF(callback); PyMem_Free(data); Py_DECREF(self); PyGILState_Release(gstate); }
static PyObject * py_gauss_transform(PyObject *self, PyObject *args) { int m,n,dim; double scale, result; double *grad; PyObject *A, *B; PyArrayObject *arrayA, *arrayB; PyArrayObject *arrayGrad; PyObject *list; /* send Python arrays to C */ if (!PyArg_ParseTuple(args, "OOd", &A, &B, &scale)) { return NULL; } /* printf("getting input success. \n"); */ arrayA = (PyArrayObject *) PyArray_ContiguousFromObject(A, PyArray_DOUBLE, 1, 2); arrayB = (PyArrayObject *) PyArray_ContiguousFromObject(B, PyArray_DOUBLE, 1, 2); /* printf("converting success!\n"); */ if (arrayA->nd > 2 || arrayA->descr->type_num != PyArray_DOUBLE) { PyErr_SetString(PyExc_ValueError, "array must be two-dimensional and of type float"); return NULL; } /* printf("checking input success!\n"); */ m = (arrayA->dimensions)[0]; n = (arrayB->dimensions)[0]; if (arrayA->nd>1) dim = (arrayA->dimensions)[1]; else dim = 1; /* printf("m=%d,n=%d,dim=%d\n",m,n,dim); */ grad = (double *) malloc(m*dim*sizeof(double)); /* call function */ result = GaussTransform((double*)(arrayA->data), (double*)(arrayB->data), m, n, dim, scale, grad); /* PyArray_FromDimsAndData() deprecated, use PyArray_SimpleNewFromData() http://blog.enthought.com/?p=62 arrayGrad = (PyArrayObject*) PyArray_FromDimsAndData(2,arrayA->dimensions,PyArray_DOUBLE, (char*)grad); */ arrayGrad = PyArray_SimpleNewFromData(2,arrayA->dimensions,NPY_DOUBLE,grad); if (arrayGrad == NULL){ printf("creating %dx%d array failed\n", arrayA->dimensions[0],arrayA->dimensions[1]); return NULL; } /* free(grad); */ /* send the result back to Python */ Py_DECREF(arrayA); Py_DECREF(arrayB); //Build a list; send it back to interpreter list = PyList_New(0); // Check the API documentation for meaning of // return values. if(PyList_Append(list, PyFloat_FromDouble(result)) != 0) { // set exception context, raise (return 0) return 0; } if(PyList_Append(list, PyArray_Return(arrayGrad)) != 0) { // set exception context, raise (return 0) return 0; } return list; //return PyArray_Return(arrayGrad); //return PyFloat_FromDouble(result); /*return Py_BuildValue("d", result);*/ }
static PyObject * archpy_disassemble (PyObject *self, PyObject *args, PyObject *kw) { static char *keywords[] = { "start_pc", "end_pc", "count", NULL }; CORE_ADDR start, end = 0; CORE_ADDR pc; gdb_py_ulongest start_temp; long count = 0, i; PyObject *result_list, *end_obj = NULL, *count_obj = NULL; struct gdbarch *gdbarch = NULL; ARCHPY_REQUIRE_VALID (self, gdbarch); if (!PyArg_ParseTupleAndKeywords (args, kw, GDB_PY_LLU_ARG "|OO", keywords, &start_temp, &end_obj, &count_obj)) return NULL; start = start_temp; if (end_obj) { /* Make a long logic check first. In Python 3.x, internally, all integers are represented as longs. In Python 2.x, there is still a differentiation internally between a PyInt and a PyLong. Explicitly do this long check conversion first. In GDB, for Python 3.x, we #ifdef PyInt = PyLong. This check has to be done first to ensure we do not lose information in the conversion process. */ if (PyLong_Check (end_obj)) end = PyLong_AsUnsignedLongLong (end_obj); else if (PyInt_Check (end_obj)) /* If the end_pc value is specified without a trailing 'L', end_obj will be an integer and not a long integer. */ end = PyInt_AsLong (end_obj); else { Py_DECREF (end_obj); Py_XDECREF (count_obj); PyErr_SetString (PyExc_TypeError, _("Argument 'end_pc' should be a (long) integer.")); return NULL; } if (end < start) { Py_DECREF (end_obj); Py_XDECREF (count_obj); PyErr_SetString (PyExc_ValueError, _("Argument 'end_pc' should be greater than or " "equal to the argument 'start_pc'.")); return NULL; } } if (count_obj) { count = PyInt_AsLong (count_obj); if (PyErr_Occurred () || count < 0) { Py_DECREF (count_obj); Py_XDECREF (end_obj); PyErr_SetString (PyExc_TypeError, _("Argument 'count' should be an non-negative " "integer.")); return NULL; } } result_list = PyList_New (0); if (result_list == NULL) return NULL; for (pc = start, i = 0; /* All args are specified. */ (end_obj && count_obj && pc <= end && i < count) /* end_pc is specified, but no count. */ || (end_obj && count_obj == NULL && pc <= end) /* end_pc is not specified, but a count is. */ || (end_obj == NULL && count_obj && i < count) /* Both end_pc and count are not specified. */ || (end_obj == NULL && count_obj == NULL && pc == start);) { int insn_len = 0; char *as = NULL; struct ui_file *memfile = mem_fileopen (); PyObject *insn_dict = PyDict_New (); if (insn_dict == NULL) { Py_DECREF (result_list); ui_file_delete (memfile); return NULL; } if (PyList_Append (result_list, insn_dict)) { Py_DECREF (result_list); Py_DECREF (insn_dict); ui_file_delete (memfile); return NULL; /* PyList_Append Sets the exception. */ } TRY { insn_len = gdb_print_insn (gdbarch, pc, memfile, NULL); } CATCH (except, RETURN_MASK_ALL) { Py_DECREF (result_list); ui_file_delete (memfile); gdbpy_convert_exception (except); return NULL; } END_CATCH as = ui_file_xstrdup (memfile, NULL); if (PyDict_SetItemString (insn_dict, "addr", gdb_py_long_from_ulongest (pc)) || PyDict_SetItemString (insn_dict, "asm", PyString_FromString (*as ? as : "<unknown>")) || PyDict_SetItemString (insn_dict, "length", PyInt_FromLong (insn_len))) { Py_DECREF (result_list); ui_file_delete (memfile); xfree (as); return NULL; } pc += insn_len; i++; ui_file_delete (memfile); xfree (as); }
PyObject* xcsoar_Airspaces_findIntrusions(Pyxcsoar_Airspaces *self, PyObject *args) { PyObject *py_flight = nullptr; if (!PyArg_ParseTuple(args, "O", &py_flight)) { PyErr_SetString(PyExc_AttributeError, "Can't parse argument."); return nullptr; } DebugReplay *replay = ((Pyxcsoar_Flight*)py_flight)->flight->Replay(); if (replay == nullptr) { PyErr_SetString(PyExc_IOError, "Can't start replay - file not found."); return nullptr; } PyObject *py_result = PyDict_New(); Airspaces::AirspaceVector last_airspaces; while (replay->Next()) { const MoreData &basic = replay->Basic(); if (!basic.time_available || !basic.location_available || !basic.NavAltitudeAvailable()) continue; const auto range = self->airspace_database->QueryInside(ToAircraftState(basic, replay->Calculated())); Airspaces::AirspaceVector airspaces(range.begin(), range.end()); for (auto it = airspaces.begin(); it != airspaces.end(); it++) { PyObject *py_name = PyString_FromString((*it).GetAirspace().GetName()); PyObject *py_airspace = nullptr, *py_period = nullptr; if (PyDict_Contains(py_result, py_name) == 0) { // this is the first fix inside this airspace py_airspace = PyList_New(0); PyDict_SetItem(py_result, py_name, py_airspace); py_period = PyList_New(0); PyList_Append(py_airspace, py_period); Py_DECREF(py_period); } else { // this airspace was hit some time before... py_airspace = PyDict_GetItem(py_result, py_name); // check if the last fix was already inside this airspace auto in_last = std::find(last_airspaces.begin(), last_airspaces.end(), *it); if (in_last == last_airspaces.end()) { // create a new period py_period = PyList_New(0); PyList_Append(py_airspace, py_period); Py_DECREF(py_period); } else { py_period = PyList_GET_ITEM(py_airspace, PyList_GET_SIZE(py_airspace) - 1); } } PyList_Append(py_period, Py_BuildValue("{s:N,s:N}", "time", Python::BrokenDateTimeToPy(basic.date_time_utc), "location", Python::WriteLonLat(basic.location))); } last_airspaces = std::move(airspaces); } delete replay; return py_result; }
static int Printer_init(Printer *self, PyObject * /*args*/, PyObject * /*kwds*/) { if (!checkHaveDocument()) { return -1; } // pool system for installed printers // most code is stolen and little adopted from druck.cpp PyObject *allPrinters = PyList_New(0); if (allPrinters){ Py_DECREF(self->allPrinters); self->allPrinters = allPrinters; } QStringList printers = PrinterUtil::getPrinterNames(); for (int i = 0; i < printers.count(); ++i) { QString prn = printers[i]; if (prn.isEmpty()) continue; PyObject *tmppr = PyString_FromString(prn.toLocal8Bit().constData()); if (tmppr){ PyList_Append(self->allPrinters, tmppr); Py_DECREF(tmppr); } } PyObject *tmp2 = PyString_FromString("File"); PyList_Append(self->allPrinters, tmp2); Py_DECREF(tmp2); // as defaut set to print into file PyObject *printer = NULL; printer = PyString_FromString("File"); if (printer){ Py_DECREF(self->printer); self->printer = printer; } // set defaul name of file to print into QString tf(ScCore->primaryMainWindow()->doc->pdfOptions().fileName); if (tf.isEmpty()) { QFileInfo fi = QFileInfo(ScCore->primaryMainWindow()->doc->DocName); tf = fi.path()+"/"+fi.baseName()+".pdf"; } PyObject *file = NULL; file = PyString_FromString(tf.toLatin1()); if (file){ Py_DECREF(self->file); self->file = file; } else { PyErr_SetString(PyExc_SystemError, "Can not initialize 'file' attribute"); return -1; } // alternative printer commands default to "" PyObject *cmd = NULL; cmd = PyString_FromString(""); if (cmd){ Py_DECREF(self->cmd); self->cmd = cmd; } // if document exist when created Printer instance // set to print all pages PyObject *pages = NULL; int num = ScCore->primaryMainWindow()->doc->Pages->count(); pages = PyList_New(num); if (pages){ Py_DECREF(self->pages); self->pages = pages; } for (int i = 0; i<num; i++) { PyObject *tmp=NULL; tmp = PyInt_FromLong((long)i+1L); // instead of 1 put here first page number if (tmp) PyList_SetItem(self->pages, i, tmp); } // do not print separation PyObject *separation = NULL; separation = PyString_FromString("No"); if (separation){ Py_DECREF(self->separation); self->separation = separation; } // print in color self->color = 1; // do not use ICC Profile self->useICC = 0; // use PostScrip level 3 self->pslevel = 3; // do not mirror pages self->mph = 0; // do not mirror pages self->mpv = 0; // apply Under Color Removal as default self->ucr = 1; // number of copies self->copies = 1; return 0; }
PSP_DEVICE_INTERFACE_DETAIL_DATA get_device_ancestors(HDEVINFO hDevInfo, DWORD index, PyObject *candidates, BOOL *iterate, BOOL ddebug) { SP_DEVICE_INTERFACE_DATA interfaceData; SP_DEVINFO_DATA devInfoData; BOOL status; PSP_DEVICE_INTERFACE_DETAIL_DATA interfaceDetailData; DWORD interfaceDetailDataSize, reqSize; DEVINST parent, pos; wchar_t temp[BUFSIZE]; int i; PyObject *devid; interfaceData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA); devInfoData.cbSize = sizeof (SP_DEVINFO_DATA); status = SetupDiEnumDeviceInterfaces ( hDevInfo, // Interface Device Info handle NULL, // Device Info data (LPGUID)&GUID_DEVINTERFACE_VOLUME, // Interface registered by driver index, // Member &interfaceData // Device Interface Data ); if ( status == FALSE ) { *iterate = FALSE; return NULL; } SetupDiGetDeviceInterfaceDetail ( hDevInfo, // Interface Device info handle &interfaceData, // Interface data for the event class NULL, // Checking for buffer size 0, // Checking for buffer size &reqSize, // Buffer size required to get the detail data NULL // Checking for buffer size ); interfaceDetailDataSize = reqSize; interfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)PyMem_Malloc(interfaceDetailDataSize+50); if ( interfaceDetailData == NULL ) { PyErr_NoMemory(); return NULL; } interfaceDetailData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA); devInfoData.cbSize = sizeof(SP_DEVINFO_DATA); status = SetupDiGetDeviceInterfaceDetail ( hDevInfo, // Interface Device info handle &interfaceData, // Interface data for the event class interfaceDetailData, // Interface detail data interfaceDetailDataSize, // Interface detail data size &reqSize, // Buffer size required to get the detail data &devInfoData); // Interface device info if (ddebug) printf("Getting ancestors\n"); fflush(stdout); if ( status == FALSE ) {PyErr_SetFromWindowsErr(0); PyMem_Free(interfaceDetailData); return NULL;} pos = devInfoData.DevInst; for(i = 0; i < 10; i++) { // Get the device instance of parent. if (CM_Get_Parent(&parent, pos, 0) != CR_SUCCESS) break; if (CM_Get_Device_ID(parent, temp, BUFSIZE, 0) == CR_SUCCESS) { if (ddebug) console_out(L"device id: %s\n", temp); devid = PyUnicode_FromWideChar(temp, wcslen(temp)); if (devid) { PyList_Append(candidates, devid); Py_DECREF(devid); } } pos = parent; } return interfaceDetailData; }
PyObject *pkg_info(PyObject *self, PyObject *args) { /* collect package info of packages listed in given .files.tar.gz files * return a list of dict */ int found, existing; char *l = NULL, *p, *v; char pname[ABUFLEN], *fname, *dname; const char *filename=NULL, *pkgname; struct stat st; struct archive *a; struct archive_entry *entry; FILE *stream = NULL; PyObject *ret=NULL, *pkgnames_list=NULL, *pkg=NULL, *waiting_dict=NULL; Py_ssize_t lp, i; if (!PyArg_ParseTuple(args, "sO", &filename, &pkgnames_list)) { PyErr_SetString(PyExc_ValueError, "pkg_info() has invalid arguments"); return NULL; } if (filename == NULL || strlen(filename)<=0) { PyErr_SetString(PyExc_ValueError, "pkg_info() was given an empty files tarball name."); return NULL; } if (!PyList_Check(pkgnames_list)) { PyErr_SetString(PyExc_ValueError, "pkg_info() 2nd argument must be a list"); return NULL; } lp = PyList_Size(pkgnames_list); if ( lp == 0) { return PyList_New(0); } pname[ABUFLEN-1]='\0'; if(stat(filename, &st)==-1 || !S_ISREG(st.st_mode)) { PyErr_Format(PyExc_IOError, "File does not exist: %s\n", filename); return NULL; } ret = PyList_New(0); if (ret == NULL) { goto error; } waiting_dict = PyDict_New(); if (waiting_dict == NULL) { goto error; } a = archive_read_new(); archive_read_support_compression_all(a); archive_read_support_format_all(a); archive_read_open_filename(a, filename, 10240); l = NULL; while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { if(!S_ISREG(archive_entry_filetype(entry))) { archive_read_data_skip(a); continue; } strncpy(pname, archive_entry_pathname(entry), ABUFLEN-1); fname = basename(pname); dname = dirname(pname); if (splitname(dname, &p, &v) == -1) { archive_read_data_skip(a); continue; } found = 0; for (i=0; i<lp; i++) { pkgname = PyString_AsString(PyList_GetItem(pkgnames_list, i)); if (pkgname == NULL) { goto error; } if (strcmp(p, pkgname) == 0) { found = 1; break; } } free(p); free(v); if (!found) { archive_read_data_skip(a); continue; } pkg = PyDict_GetItemString(waiting_dict, pkgname); existing = 1; if (pkg == NULL) { existing = 0; pkg = PyDict_New(); if (pkg == NULL) { goto error; } } if(strcmp(fname, "desc") == 0) { stream = open_archive_stream(a); if (!stream) { PyErr_SetString(PyExc_IOError, "Unable to open archive stream."); goto error; } if (parse_desc(stream, &pkg) == -1) { fclose(stream); if (!existing) Py_DECREF(pkg); continue; } fclose(stream); } else if (strcmp(fname, "depends") == 0) { stream = open_archive_stream(a); if (!stream) { PyErr_SetString(PyExc_IOError, "Unable to open archive stream."); goto error; } if (parse_depends(stream, &pkg) == -1) { fclose(stream); if (!existing) Py_DECREF(pkg); continue; } fclose(stream); } else { archive_read_data_skip(a); continue; } if (existing) { PyList_Append(ret, pkg); PyDict_DelItemString(waiting_dict, pkgname); pkg = NULL; } else { PyDict_SetItemString(waiting_dict, pkgname, pkg); Py_DECREF(pkg); } } if(l) free(l); archive_read_finish(a); /* we discard element still present in waiting_dict because they miss either the desc * or depends values */ Py_DECREF(waiting_dict); return ret; error: Py_XDECREF(ret); Py_XDECREF(waiting_dict); Py_XDECREF(pkg); return NULL; }
/* Modified portion of _alpm_db_read from lib/libalpm/be_local.c */ int parse_desc(FILE *stream, PyObject **ppkg) { /* add to ppkg dict the values found in desc file */ char line[1024]; PyObject *s, *pyl, *pkg=*ppkg; while(!feof(stream)) { if(fgets(line, sizeof(line), stream) == NULL) { break; } strtrim(line); if(strcmp(line, "%NAME%") == 0) { if(fgets(line, sizeof(line), stream) == NULL) { goto error; } PyObject *tmp = PyDict_GetItemString(pkg, "name"); /* borrowed ref. ! */ if (tmp != NULL) { const char *pkgname = PyString_AsString(tmp); if(strcmp(strtrim(line), pkgname) != 0) { /* we have a problem */ return -1; } } else { s = PyString_FromString(strtrim(line)); PyDict_SetItemString(pkg, "name", s); Py_DECREF(s); } } else if(strcmp(line, "%VERSION%") == 0) { if(fgets(line, sizeof(line), stream) == NULL) { goto error; } PyObject *tmp = PyDict_GetItemString(pkg, "version"); if (tmp != NULL) { const char *pkgver = PyString_AsString(tmp); if(strcmp(strtrim(line), pkgver) != 0) { /* we have a problem */ return -1; } } else { s = PyString_FromString(strtrim(line)); PyDict_SetItemString(pkg, "version", s); Py_DECREF(s); } } else if(strcmp(line, "%FILENAME%") == 0) { if(fgets(line, sizeof(line), stream) == NULL) { goto error; } s = PyString_FromString(strtrim(line)); PyDict_SetItemString(pkg, "filename", s); Py_DECREF(s); } else if(strcmp(line, "%DESC%") == 0) { if(fgets(line, sizeof(line), stream) == NULL) { goto error; } s = PyString_FromString(strtrim(line)); PyDict_SetItemString(pkg, "desc", s); Py_DECREF(s); } else if(strcmp(line, "%GROUPS%") == 0) { PyObject *groups = PyList_New(0); while(fgets(line, sizeof(line), stream) && strlen(strtrim(line))) { s = PyString_FromString(strtrim(line)); PyList_Append(groups, s); Py_DECREF(s); } PyDict_SetItemString(pkg, "groups", groups); Py_DECREF(groups); } else if(strcmp(line, "%URL%") == 0) { if(fgets(line, sizeof(line), stream) == NULL) { goto error; } s = PyString_FromString(strtrim(line)); PyDict_SetItemString(pkg, "url", s); Py_DECREF(s); } else if(strcmp(line, "%LICENSE%") == 0) { PyObject *license = PyList_New(0); while(fgets(line, sizeof(line), stream) && strlen(strtrim(line))) { s = PyString_FromString(strtrim(line)); PyList_Append(license, s); Py_DECREF(s); } PyDict_SetItemString(pkg, "license", license); Py_DECREF(license); } else if(strcmp(line, "%ARCH%") == 0) { if(fgets(line, sizeof(line), stream) == NULL) { goto error; } s = PyString_FromString(strtrim(line)); PyDict_SetItemString(pkg, "arch", s); Py_DECREF(s); } else if(strcmp(line, "%BUILDDATE%") == 0) { if(fgets(line, sizeof(line), stream) == NULL) { goto error; } strtrim(line); char first = tolower((unsigned char)line[0]); long ltmp; if(first > 'a' && first < 'z') { struct tm tmp_tm = {0}; /* initialize to null in case of failure */ setlocale(LC_TIME, "C"); strptime(line, "%a %b %e %H:%M:%S %Y", &tmp_tm); ltmp = (long)mktime(&tmp_tm); /* BAD! assuming time_t == long */ setlocale(LC_TIME, ""); } else { ltmp = atol(line); } pyl = PyLong_FromLong(ltmp); PyDict_SetItemString(pkg, "builddate", pyl); Py_DECREF(pyl); } else if(strcmp(line, "%INSTALLDATE%") == 0) { if(fgets(line, sizeof(line), stream) == NULL) { goto error; } strtrim(line); char first = tolower((unsigned char)line[0]); long ltmp; if(first > 'a' && first < 'z') { struct tm tmp_tm = {0}; /* initialize to null in case of failure */ setlocale(LC_TIME, "C"); strptime(line, "%a %b %e %H:%M:%S %Y", &tmp_tm); ltmp = mktime(&tmp_tm); setlocale(LC_TIME, ""); } else { ltmp = atol(line); } pyl = PyLong_FromLong(ltmp); PyDict_SetItemString(pkg, "installdate", pyl); Py_DECREF(pyl); } else if(strcmp(line, "%PACKAGER%") == 0) { if(fgets(line, sizeof(line), stream) == NULL) { goto error; } s = PyString_FromString(strtrim(line)); PyDict_SetItemString(pkg, "packager", s); Py_DECREF(s); } else if(strcmp(line, "%REASON%") == 0) { if(fgets(line, sizeof(line), stream) == NULL) { goto error; } pyl = PyLong_FromLong(atol(strtrim(line))); PyDict_SetItemString(pkg, "reason", pyl); Py_DECREF(pyl); } else if(strcmp(line, "%SIZE%") == 0 || strcmp(line, "%CSIZE%") == 0) { /* NOTE: the CSIZE and SIZE fields both share the "size" field * in the pkginfo_t struct. This can be done b/c CSIZE * is currently only used in sync databases, and SIZE is * only used in local databases. */ if(fgets(line, sizeof(line), stream) == NULL) { goto error; } pyl = PyLong_FromLong(atol(strtrim(line))); PyDict_SetItemString(pkg, "size", pyl); /* also store this value to isize if isize is unset */ PyDict_SetItemString(pkg, "isize", pyl); Py_DECREF(pyl); } else if(strcmp(line, "%ISIZE%") == 0) { /* ISIZE (installed size) tag only appears in sync repositories, * not the local one. */ if(fgets(line, sizeof(line), stream) == NULL) { goto error; } pyl = PyLong_FromLong(atol(strtrim(line))); PyDict_SetItemString(pkg, "isize", pyl); Py_DECREF(pyl); } else if(strcmp(line, "%MD5SUM%") == 0) { /* MD5SUM tag only appears in sync repositories, * not the local one. */ if(fgets(line, sizeof(line), stream) == NULL) { goto error; } s = PyString_FromString(strtrim(line)); PyDict_SetItemString(pkg, "md5sum", s); Py_DECREF(s); } else if(strcmp(line, "%REPLACES%") == 0) { PyObject *replaces = PyList_New(0); while(fgets(line, sizeof(line), stream) && strlen(strtrim(line))) { s = PyString_FromString(strtrim(line)); PyList_Append(replaces, s); Py_DECREF(s); } PyDict_SetItemString(pkg, "replaces", replaces); Py_DECREF(replaces); } else if(strcmp(line, "%FORCE%") == 0) { PyDict_SetItemString(pkg, "force", Py_True); } } return 0; error: return -1; }
static PyObject *py_parse_tree(PyObject *self, PyObject *args) { char *text, *start, *end; int len, namelen; PyObject *ret, *item, *name; if (!PyArg_ParseTuple(args, "s#", &text, &len)) return NULL; /* TODO: currently this returns a list; if memory usage is a concern, * consider rewriting as a custom iterator object */ ret = PyList_New(0); if (ret == NULL) { return NULL; } start = text; end = text + len; while (text < end) { long mode; mode = strtol(text, &text, 8); if (*text != ' ') { PyErr_SetString(PyExc_ValueError, "Expected space"); Py_DECREF(ret); return NULL; } text++; namelen = strnlen(text, len - (text - start)); name = PyString_FromStringAndSize(text, namelen); if (name == NULL) { Py_DECREF(ret); return NULL; } if (text + namelen + 20 >= end) { PyErr_SetString(PyExc_ValueError, "SHA truncated"); Py_DECREF(ret); Py_DECREF(name); return NULL; } item = Py_BuildValue("(NlN)", name, mode, sha_to_pyhex((unsigned char *)text+namelen+1)); if (item == NULL) { Py_DECREF(ret); Py_DECREF(name); return NULL; } if (PyList_Append(ret, item) == -1) { Py_DECREF(ret); Py_DECREF(item); return NULL; } Py_DECREF(item); text += namelen+21; } return ret; }
/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP with LOAD_CONST binop(c1,c2) The consts table must still be in list form so that the new constant can be appended. Called with codestr pointing to the first LOAD_CONST. Abandons the transformation if the folding fails (i.e. 1+'a'). If the new constant is a sequence, only folds when the size is below a threshold value. That keeps pyc files from becoming large in the presence of code like: (None,)*1000. */ static int fold_binops_on_constants(unsigned char *codestr, PyObject *consts) { PyObject *newconst, *v, *w; Py_ssize_t len_consts, size; int opcode; /* Pre-conditions */ assert(PyList_CheckExact(consts)); assert(codestr[0] == LOAD_CONST); assert(codestr[3] == LOAD_CONST); /* Create new constant */ v = PyList_GET_ITEM(consts, GETARG(codestr, 0)); w = PyList_GET_ITEM(consts, GETARG(codestr, 3)); opcode = codestr[6]; switch (opcode) { case BINARY_POWER: newconst = PyNumber_Power(v, w, Py_None); break; case BINARY_MULTIPLY: newconst = PyNumber_Multiply(v, w); break; case BINARY_TRUE_DIVIDE: newconst = PyNumber_TrueDivide(v, w); break; case BINARY_FLOOR_DIVIDE: newconst = PyNumber_FloorDivide(v, w); break; case BINARY_MODULO: newconst = PyNumber_Remainder(v, w); break; case BINARY_ADD: newconst = PyNumber_Add(v, w); break; case BINARY_SUBTRACT: newconst = PyNumber_Subtract(v, w); break; case BINARY_SUBSCR: newconst = PyObject_GetItem(v, w); /* #5057: if v is unicode, there might be differences between wide and narrow builds in cases like '\U00012345'[0]. Wide builds will return a non-BMP char, whereas narrow builds will return a surrogate. In both the cases skip the optimization in order to produce compatible pycs. */ if (newconst != NULL && PyUnicode_Check(v) && PyUnicode_Check(newconst)) { Py_UNICODE ch = PyUnicode_AS_UNICODE(newconst)[0]; #ifdef Py_UNICODE_WIDE if (ch > 0xFFFF) { #else if (ch >= 0xD800 && ch <= 0xDFFF) { #endif Py_DECREF(newconst); return 0; } } break; case BINARY_LSHIFT: newconst = PyNumber_Lshift(v, w); break; case BINARY_RSHIFT: newconst = PyNumber_Rshift(v, w); break; case BINARY_AND: newconst = PyNumber_And(v, w); break; case BINARY_XOR: newconst = PyNumber_Xor(v, w); break; case BINARY_OR: newconst = PyNumber_Or(v, w); break; default: /* Called with an unknown opcode */ PyErr_Format(PyExc_SystemError, "unexpected binary operation %d on a constant", opcode); return 0; } if (newconst == NULL) { if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) PyErr_Clear(); return 0; } size = PyObject_Size(newconst); if (size == -1) { if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) return 0; PyErr_Clear(); } else if (size > 20) { Py_DECREF(newconst); return 0; } /* Append folded constant into consts table */ len_consts = PyList_GET_SIZE(consts); if (PyList_Append(consts, newconst)) { Py_DECREF(newconst); return 0; } Py_DECREF(newconst); /* Write NOP NOP NOP NOP LOAD_CONST newconst */ memset(codestr, NOP, 4); codestr[4] = LOAD_CONST; SETARG(codestr, 4, len_consts); return 1; } static int fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts) { PyObject *newconst=NULL, *v; Py_ssize_t len_consts; int opcode; /* Pre-conditions */ assert(PyList_CheckExact(consts)); assert(codestr[0] == LOAD_CONST); /* Create new constant */ v = PyList_GET_ITEM(consts, GETARG(codestr, 0)); opcode = codestr[3]; switch (opcode) { case UNARY_NEGATIVE: /* Preserve the sign of -0.0 */ if (PyObject_IsTrue(v) == 1) newconst = PyNumber_Negative(v); break; case UNARY_INVERT: newconst = PyNumber_Invert(v); break; case UNARY_POSITIVE: newconst = PyNumber_Positive(v); break; default: /* Called with an unknown opcode */ PyErr_Format(PyExc_SystemError, "unexpected unary operation %d on a constant", opcode); return 0; } if (newconst == NULL) { if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt)) PyErr_Clear(); return 0; } /* Append folded constant into consts table */ len_consts = PyList_GET_SIZE(consts); if (PyList_Append(consts, newconst)) { Py_DECREF(newconst); return 0; } Py_DECREF(newconst); /* Write NOP LOAD_CONST newconst */ codestr[0] = NOP; codestr[1] = LOAD_CONST; SETARG(codestr, 1, len_consts); return 1; }
/* * Return NICs information a-la ifconfig as a list of tuples. * TODO: on Solaris we won't get any MAC address. */ static PyObject* psutil_net_if_addrs(PyObject* self, PyObject* args) { struct ifaddrs *ifaddr, *ifa; int family; PyObject *py_retlist = PyList_New(0); PyObject *py_tuple = NULL; PyObject *py_address = NULL; PyObject *py_netmask = NULL; PyObject *py_broadcast = NULL; PyObject *py_ptp = NULL; if (py_retlist == NULL) return NULL; if (getifaddrs(&ifaddr) == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) continue; family = ifa->ifa_addr->sa_family; py_address = psutil_convert_ipaddr(ifa->ifa_addr, family); // If the primary address can't be determined just skip it. // I've never seen this happen on Linux but I did on FreeBSD. if (py_address == Py_None) continue; if (py_address == NULL) goto error; py_netmask = psutil_convert_ipaddr(ifa->ifa_netmask, family); if (py_netmask == NULL) goto error; if (ifa->ifa_flags & IFF_BROADCAST) { py_broadcast = psutil_convert_ipaddr(ifa->ifa_broadaddr, family); Py_INCREF(Py_None); py_ptp = Py_None; } else if (ifa->ifa_flags & IFF_POINTOPOINT) { py_ptp = psutil_convert_ipaddr(ifa->ifa_dstaddr, family); Py_INCREF(Py_None); py_broadcast = Py_None; } else { Py_INCREF(Py_None); Py_INCREF(Py_None); py_broadcast = Py_None; py_ptp = Py_None; } if ((py_broadcast == NULL) || (py_ptp == NULL)) goto error; py_tuple = Py_BuildValue( "(siOOOO)", ifa->ifa_name, family, py_address, py_netmask, py_broadcast, py_ptp ); if (! py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); Py_DECREF(py_address); Py_DECREF(py_netmask); Py_DECREF(py_broadcast); Py_DECREF(py_ptp); } freeifaddrs(ifaddr); return py_retlist; error: if (ifaddr != NULL) freeifaddrs(ifaddr); Py_DECREF(py_retlist); Py_XDECREF(py_tuple); Py_XDECREF(py_address); Py_XDECREF(py_netmask); Py_XDECREF(py_broadcast); Py_XDECREF(py_ptp); return NULL; }
PyObject* distorm_Decode(PyObject* pSelf, PyObject* pArgs) { _DecodeType dt; uint8_t* code; int codeLen; _OffsetType codeOffset; _DecodeResult res = DECRES_NONE; _DecodedInst decodedInstructions[MAX_INSTRUCTIONS]; unsigned int decodedInstructionsCount = 0, i = 0, next = 0; uint8_t instructionText[MAX_TEXT_SIZE*2]; PyObject *ret = NULL, *pyObj = NULL, *dtObj = NULL; pSelf = pSelf; /* UNREFERENCED_PARAMETER */ /* Decode(int32/64 offset, string code, int type=Decode32Bits) */ if (!PyArg_ParseTuple(pArgs, _PY_OFF_INT_SIZE_ "s#|O", &codeOffset, &code, &codeLen, &dtObj)) return NULL; if (code == NULL) { PyErr_SetString(PyExc_IOError, "Error while reading code buffer."); return NULL; } if (codeLen < 0) { PyErr_SetString(PyExc_OverflowError, "Code buffer is too long."); return NULL; } /* Default parameter. */ if (dtObj == NULL) dt = Decode32Bits; else if (!PyInt_Check(dtObj)) { PyErr_SetString(PyExc_IndexError, "Third parameter must be either Decode16Bits, Decode32Bits or Decode64Bits (integer type)."); return NULL; } else dt = (_DecodeType)PyInt_AsUnsignedLongMask(dtObj); if ((dt != Decode16Bits) && (dt != Decode32Bits) && (dt != Decode64Bits)) { PyErr_SetString(PyExc_IndexError, "Decoding-type must be either Decode16Bits, Decode32Bits or Decode64Bits."); return NULL; } /* Construct an empty list, which later will be filled with tuples of (offset, size, mnemonic, hex). */ ret = PyList_New(0); if (ret == NULL) { PyErr_SetString(PyExc_MemoryError, "Not enough memory to initialize a list."); return NULL; } while (res != DECRES_SUCCESS) { res = internal_decode(codeOffset, code, codeLen, dt, decodedInstructions, MAX_INSTRUCTIONS, &decodedInstructionsCount); if ((res == DECRES_MEMORYERR) && (decodedInstructionsCount == 0)) break; for (i = 0; i < decodedInstructionsCount; i++) { if (decodedInstructions[i].mnemonic.pos > 0) { memcpy(instructionText, decodedInstructions[i].mnemonic.p, decodedInstructions[i].mnemonic.pos + 1); /* Include \0. */ if (decodedInstructions[i].operands.pos > 0) instructionText[decodedInstructions[i].mnemonic.pos] = SP_CHR; memcpy(&instructionText[decodedInstructions[i].mnemonic.pos+1], decodedInstructions[i].operands.p, decodedInstructions[i].operands.pos + 1); } else instructionText[0] = '\0'; pyObj = Py_BuildValue("(" _PY_OFF_INT_SIZE_ "bss)", decodedInstructions[i].offset, decodedInstructions[i].size, instructionText, decodedInstructions[i].instructionHex.p); if (pyObj == NULL) { Py_DECREF(ret); PyErr_SetString(PyExc_MemoryError, "Not enough memory to append an item into the list."); return NULL; } if (PyList_Append(ret, pyObj) == -1) { Py_DECREF(pyObj); Py_DECREF(ret); PyErr_SetString(PyExc_MemoryError, "Not enough memory to append an item into the list."); return NULL; } // V 1.7.25 - Memleak fixed, it is necessary to DECREF the object, because PyList_Append INCREFs it on its own. Py_DECREF(pyObj); } /* Get offset difference. */ next = (unsigned int)(decodedInstructions[decodedInstructionsCount-1].offset - codeOffset); next += decodedInstructions[decodedInstructionsCount-1].size; /* Advance ptr and recalc offset. */ code += next; codeLen -= next; codeOffset += next; } return ret; }
static PyObject *parse_qsl(PyObject *self, PyObject *args, PyObject *kw) { PyObject *pairs; int i, len; char *qs; int keep_blank_values = 0; int strict_parsing = 0; /* XXX not implemented */ char *keywords[] = { "qs", "keep_blank_values", "strict_parsing", 0 }; if (! PyArg_ParseTupleAndKeywords(args, kw, "s|ii", keywords, &qs, &keep_blank_values, &strict_parsing)) return NULL; /* error */ /* split query string by '&' and ';' into a list of pairs */ /* PYTHON 2.5: 'PyList_New' uses Py_ssize_t for input parameters */ pairs = PyList_New(0); if (pairs == NULL) return NULL; i = 0; len = strlen(qs); while (i < len) { PyObject *pair, *key, *val; char *cpair, *ckey, *cval; int plen, j, p, k, v; /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ pair = PyString_FromStringAndSize(NULL, len); if (pair == NULL) return NULL; /* split by '&' or ';' */ cpair = PyString_AS_STRING(pair); j = 0; while ((qs[i] != '&') && (qs[i] != ';') && (i < len)) { /* replace '+' with ' ' */ cpair[j] = (qs[i] == '+') ? ' ' : qs[i]; i++; j++; } if (j == 0) { Py_XDECREF(pair); i++; continue; } cpair[j] = '\0'; /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */ _PyString_Resize(&pair, j); cpair = PyString_AS_STRING(pair); /* split the "abc=def" pair */ plen = strlen(cpair); /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ key = PyString_FromStringAndSize(NULL, plen); if (key == NULL) return NULL; /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ val = PyString_FromStringAndSize(NULL, plen); if (val == NULL) return NULL; ckey = PyString_AS_STRING(key); cval = PyString_AS_STRING(val); p = 0; k = 0; v = 0; while (p < plen) { if (cpair[p] != '=') { ckey[k] = cpair[p]; k++; p++; } else { p++; /* skip '=' */ while (p < plen) { cval[v] = cpair[p]; v++; p++; } } } ckey[k] = '\0'; cval[v] = '\0'; if (keep_blank_values || (v > 0)) { ap_unescape_url(ckey); ap_unescape_url(cval); /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */ _PyString_Resize(&key, strlen(ckey)); /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */ _PyString_Resize(&val, strlen(cval)); if (key && val) { PyObject* listitem = Py_BuildValue("(O,O)", key, val); if(listitem) { PyList_Append(pairs, listitem); Py_DECREF(listitem); } } } Py_XDECREF(pair); Py_XDECREF(key); Py_XDECREF(val); i++; } return pairs; }
/* * Return process memory mappings. */ static PyObject * psutil_proc_memory_maps(PyObject *self, PyObject *args) { int pid; int fd = -1; char path[1000]; char perms[10]; char *name; struct stat st; pstatus_t status; prxmap_t *xmap = NULL, *p; off_t size; size_t nread; int nmap; uintptr_t pr_addr_sz; uintptr_t stk_base_sz, brk_base_sz; const char *procfs_path; PyObject *py_tuple = NULL; PyObject *py_retlist = PyList_New(0); if (py_retlist == NULL) return NULL; if (! PyArg_ParseTuple(args, "is", &pid, &procfs_path)) goto error; sprintf(path, "%s/%i/status", procfs_path, pid); if (! psutil_file_to_struct(path, (void *)&status, sizeof(status))) goto error; sprintf(path, "%s/%i/xmap", procfs_path, pid); if (stat(path, &st) == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } size = st.st_size; fd = open(path, O_RDONLY); if (fd == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } xmap = (prxmap_t *)malloc(size); if (xmap == NULL) { PyErr_NoMemory(); goto error; } nread = pread(fd, xmap, size, 0); nmap = nread / sizeof(prxmap_t); p = xmap; while (nmap) { nmap -= 1; if (p == NULL) { p += 1; continue; } perms[0] = '\0'; pr_addr_sz = p->pr_vaddr + p->pr_size; // perms sprintf(perms, "%c%c%c%c%c%c", p->pr_mflags & MA_READ ? 'r' : '-', p->pr_mflags & MA_WRITE ? 'w' : '-', p->pr_mflags & MA_EXEC ? 'x' : '-', p->pr_mflags & MA_SHARED ? 's' : '-', p->pr_mflags & MA_NORESERVE ? 'R' : '-', p->pr_mflags & MA_RESERVED1 ? '*' : ' '); // name if (strlen(p->pr_mapname) > 0) { name = p->pr_mapname; } else { if ((p->pr_mflags & MA_ISM) || (p->pr_mflags & MA_SHM)) { name = "[shmid]"; } else { stk_base_sz = status.pr_stkbase + status.pr_stksize; brk_base_sz = status.pr_brkbase + status.pr_brksize; if ((pr_addr_sz > status.pr_stkbase) && (p->pr_vaddr < stk_base_sz)) { name = "[stack]"; } else if ((p->pr_mflags & MA_ANON) && \ (pr_addr_sz > status.pr_brkbase) && \ (p->pr_vaddr < brk_base_sz)) { name = "[heap]"; } else { name = "[anon]"; } } } py_tuple = Py_BuildValue( "iisslll", p->pr_vaddr, pr_addr_sz, perms, name, (long)p->pr_rss * p->pr_pagesize, (long)p->pr_anon * p->pr_pagesize, (long)p->pr_locked * p->pr_pagesize); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); // increment pointer p += 1; } close(fd); free(xmap); return py_retlist; error: if (fd != -1) close(fd); Py_XDECREF(py_tuple); Py_DECREF(py_retlist); if (xmap != NULL) free(xmap); return NULL; }
/* * Return TCP and UDP connections opened by process. * UNIX sockets are excluded. * * Thanks to: * https://github.com/DavidGriffith/finx/blob/master/ * nxsensor-3.5.0-1/src/sysdeps/solaris.c * ...and: * https://hg.java.net/hg/solaris~on-src/file/tip/usr/src/cmd/ * cmd-inet/usr.bin/netstat/netstat.c */ static PyObject * psutil_net_connections(PyObject *self, PyObject *args) { long pid; int sd = 0; mib2_tcpConnEntry_t *tp = NULL; mib2_udpEntry_t *ude; #if defined(AF_INET6) mib2_tcp6ConnEntry_t *tp6; mib2_udp6Entry_t *ude6; #endif char buf[512]; int i, flags, getcode, num_ent, state; char lip[200], rip[200]; int lport, rport; int processed_pid; int databuf_init = 0; struct strbuf ctlbuf, databuf; struct T_optmgmt_req *tor = (struct T_optmgmt_req *)buf; struct T_optmgmt_ack *toa = (struct T_optmgmt_ack *)buf; struct T_error_ack *tea = (struct T_error_ack *)buf; struct opthdr *mibhdr; PyObject *py_retlist = PyList_New(0); PyObject *py_tuple = NULL; PyObject *py_laddr = NULL; PyObject *py_raddr = NULL; if (py_retlist == NULL) return NULL; if (! PyArg_ParseTuple(args, "l", &pid)) goto error; sd = open("/dev/arp", O_RDWR); if (sd == -1) { PyErr_SetFromErrnoWithFilename(PyExc_OSError, "/dev/arp"); goto error; } /* XXX - These 2 are used in ifconfig.c but they seem unnecessary ret = ioctl(sd, I_PUSH, "tcp"); if (ret == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } ret = ioctl(sd, I_PUSH, "udp"); if (ret == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } */ // OK, this mess is basically copied and pasted from nxsensor project // which copied and pasted it from netstat source code, mibget() // function. Also see: // http://stackoverflow.com/questions/8723598/ tor->PRIM_type = T_SVR4_OPTMGMT_REQ; tor->OPT_offset = sizeof (struct T_optmgmt_req); tor->OPT_length = sizeof (struct opthdr); tor->MGMT_flags = T_CURRENT; mibhdr = (struct opthdr *)&tor[1]; mibhdr->level = EXPER_IP_AND_ALL_IRES; mibhdr->name = 0; mibhdr->len = 0; ctlbuf.buf = buf; ctlbuf.len = tor->OPT_offset + tor->OPT_length; flags = 0; // request to be sent in non-priority if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) { PyErr_SetFromErrno(PyExc_OSError); goto error; } mibhdr = (struct opthdr *)&toa[1]; ctlbuf.maxlen = sizeof (buf); for (;;) { flags = 0; getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags); if (getcode != MOREDATA || ctlbuf.len < sizeof (struct T_optmgmt_ack) || toa->PRIM_type != T_OPTMGMT_ACK || toa->MGMT_flags != T_SUCCESS) { break; } if (ctlbuf.len >= sizeof (struct T_error_ack) && tea->PRIM_type == T_ERROR_ACK) { PyErr_SetString(PyExc_RuntimeError, "ERROR_ACK"); goto error; } if (getcode == 0 && ctlbuf.len >= sizeof (struct T_optmgmt_ack) && toa->PRIM_type == T_OPTMGMT_ACK && toa->MGMT_flags == T_SUCCESS) { PyErr_SetString(PyExc_RuntimeError, "ERROR_T_OPTMGMT_ACK"); goto error; } databuf.maxlen = mibhdr->len; databuf.len = 0; databuf.buf = (char *)malloc((int)mibhdr->len); if (!databuf.buf) { PyErr_NoMemory(); goto error; } databuf_init = 1; flags = 0; getcode = getmsg(sd, (struct strbuf *)0, &databuf, &flags); if (getcode < 0) { PyErr_SetFromErrno(PyExc_OSError); goto error; } // TCPv4 if (mibhdr->level == MIB2_TCP && mibhdr->name == MIB2_TCP_13) { tp = (mib2_tcpConnEntry_t *)databuf.buf; num_ent = mibhdr->len / sizeof(mib2_tcpConnEntry_t); for (i = 0; i < num_ent; i++, tp++) { processed_pid = tp->tcpConnCreationProcess; if (pid != -1 && processed_pid != pid) continue; // construct local/remote addresses inet_ntop(AF_INET, &tp->tcpConnLocalAddress, lip, sizeof(lip)); inet_ntop(AF_INET, &tp->tcpConnRemAddress, rip, sizeof(rip)); lport = tp->tcpConnLocalPort; rport = tp->tcpConnRemPort; // contruct python tuple/list py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; if (rport != 0) py_raddr = Py_BuildValue("(si)", rip, rport); else { py_raddr = Py_BuildValue("()"); } if (!py_raddr) goto error; state = tp->tcpConnEntryInfo.ce_state; // add item py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_STREAM, py_laddr, py_raddr, state, processed_pid); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #if defined(AF_INET6) // TCPv6 else if (mibhdr->level == MIB2_TCP6 && mibhdr->name == MIB2_TCP6_CONN) { tp6 = (mib2_tcp6ConnEntry_t *)databuf.buf; num_ent = mibhdr->len / sizeof(mib2_tcp6ConnEntry_t); for (i = 0; i < num_ent; i++, tp6++) { processed_pid = tp6->tcp6ConnCreationProcess; if (pid != -1 && processed_pid != pid) continue; // construct local/remote addresses inet_ntop(AF_INET6, &tp6->tcp6ConnLocalAddress, lip, sizeof(lip)); inet_ntop(AF_INET6, &tp6->tcp6ConnRemAddress, rip, sizeof(rip)); lport = tp6->tcp6ConnLocalPort; rport = tp6->tcp6ConnRemPort; // contruct python tuple/list py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; if (rport != 0) py_raddr = Py_BuildValue("(si)", rip, rport); else py_raddr = Py_BuildValue("()"); if (!py_raddr) goto error; state = tp6->tcp6ConnEntryInfo.ce_state; // add item py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_STREAM, py_laddr, py_raddr, state, processed_pid); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #endif // UDPv4 else if (mibhdr->level == MIB2_UDP || mibhdr->level == MIB2_UDP_ENTRY) { ude = (mib2_udpEntry_t *)databuf.buf; num_ent = mibhdr->len / sizeof(mib2_udpEntry_t); for (i = 0; i < num_ent; i++, ude++) { processed_pid = ude->udpCreationProcess; if (pid != -1 && processed_pid != pid) continue; // XXX Very ugly hack! It seems we get here only the first // time we bump into a UDPv4 socket. PID is a very high // number (clearly impossible) and the address does not // belong to any valid interface. Not sure what else // to do other than skipping. if (processed_pid > 131072) continue; inet_ntop(AF_INET, &ude->udpLocalAddress, lip, sizeof(lip)); lport = ude->udpLocalPort; py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; py_raddr = Py_BuildValue("()"); if (!py_raddr) goto error; py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET, SOCK_DGRAM, py_laddr, py_raddr, PSUTIL_CONN_NONE, processed_pid); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #if defined(AF_INET6) // UDPv6 else if (mibhdr->level == MIB2_UDP6 || mibhdr->level == MIB2_UDP6_ENTRY) { ude6 = (mib2_udp6Entry_t *)databuf.buf; num_ent = mibhdr->len / sizeof(mib2_udp6Entry_t); for (i = 0; i < num_ent; i++, ude6++) { processed_pid = ude6->udp6CreationProcess; if (pid != -1 && processed_pid != pid) continue; inet_ntop(AF_INET6, &ude6->udp6LocalAddress, lip, sizeof(lip)); lport = ude6->udp6LocalPort; py_laddr = Py_BuildValue("(si)", lip, lport); if (!py_laddr) goto error; py_raddr = Py_BuildValue("()"); if (!py_raddr) goto error; py_tuple = Py_BuildValue("(iiiNNiI)", -1, AF_INET6, SOCK_DGRAM, py_laddr, py_raddr, PSUTIL_CONN_NONE, processed_pid); if (!py_tuple) goto error; if (PyList_Append(py_retlist, py_tuple)) goto error; Py_DECREF(py_tuple); } } #endif free(databuf.buf); } close(sd); return py_retlist; error: Py_XDECREF(py_tuple); Py_XDECREF(py_laddr); Py_XDECREF(py_raddr); Py_DECREF(py_retlist); if (databuf_init == 1) free(databuf.buf); if (sd != 0) close(sd); return NULL; }
void avtPythonExpression::ProcessArguments(ArgsExpr *args, ExprPipelineState *state) { // get the argument list and # of arguments std::vector<ArgExpr*> *arguments = args->GetArgs(); int nargs = arguments->size(); // check for call with improper # of arguments if (nargs < 2) PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - " "Python Filter Expression requires at least to input " "arguments:\n" "A variable and a string providing the python filter " "source"); // the last argument should be the python script defining the filter. // attempt to load it first: pyScript = ""; ExprParseTreeNode *last_node = ((*arguments)[nargs-1])->GetExpr(); std::string last_node_type = last_node ->GetTypeName(); if(last_node_type != "StringConst") PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - " "Last expression argument must be a string constant" "containing a python filter source."); pyScript = dynamic_cast<StringConstExpr*>(last_node)->GetValue(); if(!pyEnv->Initialize()) PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - " "Failed to initialize the python filter environment."); if(!pyEnv->LoadFilter(pyScript)) PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - " "Failed to load python filter script."); PyObject *py_vars_list = pyEnv->Filter()->FetchAttribute("input_var_names"); if(py_vars_list == NULL || !PyList_Check(py_vars_list)) PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - " "Failed to fetch 'input_var_names' " "list from python filter"); PyObject *py_args_list = pyEnv->Filter()->FetchAttribute("arguments"); if(py_args_list == NULL || !PyList_Check(py_args_list)) PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - " "Failed to fetch 'arguments' list " "from python filter."); // process the remaining arguments for(int i=0;i< nargs-1;i++) { ExprParseTreeNode *node = ((*arguments)[i])->GetExpr(); std::string node_type = node->GetTypeName(); PyObject *py_arg = NULL; if(node_type == "IntegerConst") { long ival = (long)dynamic_cast<IntegerConstExpr*>(node)->GetValue(); // create PyInt py_arg = PyInt_FromLong(ival); } else if(node_type == "FloatConst") { double fval = dynamic_cast<FloatConstExpr*>(node)->GetValue(); // create PyFloat py_arg = PyFloat_FromDouble(fval); } else if(node_type == "StringConst") { std::string sval = dynamic_cast<StringConstExpr*>(node)->GetValue(); // create Py_STRING py_arg = PyString_FromString(sval.c_str()); } else if(node_type == "BooleanConst") { bool bval = dynamic_cast<BooleanConstExpr*>(node)->GetValue(); // select either Py_True or Py_False if(bval) py_arg = Py_True; else py_arg = Py_False; Py_INCREF(py_arg); } if(py_arg) { // if it is a constant add it to the filter's arguments list // append to the filter's arguments list if(PyList_Append(py_args_list,py_arg) == -1) PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - " "Unable to add argument value to Python filter " "'arguments' list."); } else { // we have a variable or expression, let it build its own filters. // add add its name to the variables list avtExprNode *expr_node= dynamic_cast<avtExprNode*>(node); expr_node->CreateFilters(state); if(node_type == "Var") { PathExpr *path_expr= dynamic_cast<VarExpr*>(node)->GetVar(); std::string text =path_expr->GetFullpath(); PyObject *py_txt = PyString_FromString(text.c_str()); if(PyList_Append(py_vars_list,py_txt) == -1) PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - " "Unable to add variable name to Python filter " "'input_var_names' list."); } } } }
static PyObject * winutil_get_removable_drives(PyObject *self, PyObject *args) { HDEVINFO hDevInfo; BOOL iterate = TRUE, ddebug = FALSE; PSP_DEVICE_INTERFACE_DETAIL_DATA interfaceDetailData; DWORD i; unsigned int j, length; WCHAR volume[BUFSIZE]; struct tagDrives g_drives[MAX_DRIVES]; PyObject *volumes, *key, *candidates, *pdebug = Py_False, *temp; if (!PyArg_ParseTuple(args, "|O", &pdebug)) { return NULL; } // Find all removable drives for (j = 0; j < MAX_DRIVES; j++) g_drives[j].letter = 0; if (!get_all_removable_disks(g_drives)) return NULL; volumes = PyDict_New(); if (volumes == NULL) return PyErr_NoMemory(); ddebug = PyObject_IsTrue(pdebug); hDevInfo = create_device_info_set((LPGUID)&GUID_DEVINTERFACE_VOLUME, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); if (hDevInfo == INVALID_HANDLE_VALUE) { Py_DECREF(volumes); return NULL; } // Enumerate through the set for (i=0; iterate; i++) { candidates = PyList_New(0); if (candidates == NULL) { Py_DECREF(volumes); return PyErr_NoMemory();} interfaceDetailData = get_device_ancestors(hDevInfo, i, candidates, &iterate, ddebug); if (interfaceDetailData == NULL) { PyErr_Print(); Py_DECREF(candidates); candidates = NULL; continue; } length = wcslen(interfaceDetailData->DevicePath); interfaceDetailData->DevicePath[length] = L'\\'; interfaceDetailData->DevicePath[length+1] = 0; if (ddebug) console_out(L"Device path: %s\n", interfaceDetailData->DevicePath); // On Vista+ DevicePath contains the information we need. temp = PyUnicode_FromWideChar(interfaceDetailData->DevicePath, length); if (temp == NULL) return PyErr_NoMemory(); PyList_Append(candidates, temp); Py_DECREF(temp); if(GetVolumeNameForVolumeMountPointW(interfaceDetailData->DevicePath, volume, BUFSIZE)) { if (ddebug) console_out(L"Volume: %s\n", volume); for(j = 0; j < MAX_DRIVES; j++) { if(g_drives[j].letter != 0 && wcscmp(g_drives[j].volume, volume)==0) { if (ddebug) printf("Found drive: %c\n", (char)g_drives[j].letter); fflush(stdout); key = PyBytes_FromFormat("%c", (char)g_drives[j].letter); if (key == NULL) return PyErr_NoMemory(); PyDict_SetItem(volumes, key, candidates); Py_DECREF(key); key = NULL; break; } } } Py_XDECREF(candidates); candidates = NULL; PyMem_Free(interfaceDetailData); } //for SetupDiDestroyDeviceInfoList(hDevInfo); return volumes; }
PyObject* signalInstanceConnect(PyObject* self, PyObject* args, PyObject* kwds) { PyObject* slot = 0; PyObject* type = 0; static const char* kwlist[] = {"slot", "type", 0}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:" SIGNAL_INSTANCE_NAME, const_cast<char**>(kwlist), &slot, &type)) return 0; PySideSignalInstance* source = reinterpret_cast<PySideSignalInstance*>(self); Shiboken::AutoDecRef pyArgs(PyList_New(0)); bool match = false; if (slot->ob_type == &PySideSignalInstanceType) { PySideSignalInstance* sourceWalk = source; PySideSignalInstance* targetWalk; //find best match while (sourceWalk && !match) { targetWalk = reinterpret_cast<PySideSignalInstance*>(slot); while (targetWalk && !match) { if (QMetaObject::checkConnectArgs(sourceWalk->d->signature, targetWalk->d->signature)) { PyList_Append(pyArgs, sourceWalk->d->source); Shiboken::AutoDecRef sourceSignature(PySide::Signal::buildQtCompatible(sourceWalk->d->signature)); PyList_Append(pyArgs, sourceSignature); PyList_Append(pyArgs, targetWalk->d->source); Shiboken::AutoDecRef targetSignature(PySide::Signal::buildQtCompatible(targetWalk->d->signature)); PyList_Append(pyArgs, targetSignature); match = true; } targetWalk = reinterpret_cast<PySideSignalInstance*>(targetWalk->d->next); } sourceWalk = reinterpret_cast<PySideSignalInstance*>(sourceWalk->d->next); } } else { //try the first signature PyList_Append(pyArgs, source->d->source); Shiboken::AutoDecRef signature(PySide::Signal::buildQtCompatible(source->d->signature)); PyList_Append(pyArgs, signature); PyList_Append(pyArgs, slot); match = true; } if (type) PyList_Append(pyArgs, type); if (match) { Shiboken::AutoDecRef tupleArgs(PyList_AsTuple(pyArgs)); Shiboken::AutoDecRef pyMethod(PyObject_GetAttrString(source->d->source, "connect")); PyObject* result = PyObject_CallObject(pyMethod, tupleArgs); if (result == Py_True) return result; else Py_XDECREF(result); } if (!PyErr_Occurred()) PyErr_Format(PyExc_RuntimeError, "Failed to connect signal %s.", source->d->signature); return 0; }
/* +interp, +buf */ static PyObject *CReader_internalRead(CReader_Buffer *buffer, char inParens, char inMemberList) { PyObject *res; PyObject *key = NULL; PyObject *value = NULL; char multi = inParens && (inParens != '('); char separated = 1; char c; if (inParens == '{') res = PyDict_New(); else res = PyList_New(0); if (!res) return NULL; while (1) { if (!CReader_Buffer_unlockedExtend(buffer, 1)) { if (!PyObject_IsTrue(res) || inParens) goto CReader_internalRead_error; else goto CReader_internalRead_end; } c = buffer->buf[buffer->pos]; switch (c) { case NEWLINE: if (!PyObject_IsTrue(res) || inParens) { if (CReader_Buffer_unlockedAdvance(buffer, 1)) PyErr_SetString(PyExc_IOError, "APremature end of file reached"); continue; } goto CReader_internalRead_end; case ENDSEPARATORS: if (inParens) if (!CReader_Buffer_unlockedAdvance(buffer, 1)) goto CReader_internalRead_error; goto CReader_internalRead_end; case SPACE: if (!CReader_Buffer_unlockedAdvance(buffer, 1)) goto CReader_internalRead_error; continue; case ',': if (!inParens) goto CReader_internalRead_end; if (!CReader_Buffer_unlockedAdvance(buffer, 1)) goto CReader_internalRead_error; multi = 1; separated = 1; continue; case ':': if (inParens != '{') { PyErr_SetString(PyExc_SyntaxError, "Colon not inside a mapping"); goto CReader_internalRead_error; } if (!CReader_Buffer_unlockedAdvance(buffer, 1)) goto CReader_internalRead_error; if (!(value = CReader_internalRead(buffer, 0, 0))) goto CReader_internalRead_error; if (PyDict_SetItem(res, key, value) == -1) goto CReader_internalRead_error; key = value = NULL; continue; case '=': if (!CReader_Buffer_unlockedAdvance(buffer, 1)) goto CReader_internalRead_error; if (!(value = CReader_internalRead(buffer, 0, 0))) goto CReader_internalRead_error; if (!CReader_NameLast(res, ParameterName, value, 1)) goto CReader_internalRead_error; continue; case '.': if (inMemberList) { if (!PyObject_IsTrue(res)) { PyErr_SetString(PyExc_IOError, "CPremature end of file reached"); goto CReader_internalRead_error; } else goto CReader_internalRead_end; } if (!CReader_Buffer_unlockedAdvance(buffer, 1)) goto CReader_internalRead_error; if (!(value = CReader_internalRead(buffer, 0, 1))) goto CReader_internalRead_error; if (!CReader_NameLast(res, Member, value, 0)) goto CReader_internalRead_error; continue; case '(': if (!separated && inMemberList) goto CReader_internalRead_end; if (!CReader_Buffer_unlockedAdvance(buffer, 1)) goto CReader_internalRead_error; if (!(value = CReader_internalRead(buffer, separated ? c : '[', 0))) goto CReader_internalRead_error; if (!separated) { if (!CReader_NameLast(res, Application, value, 0)) goto CReader_internalRead_error; continue; } break; case KNOWNBEGINSEPARATORS: if (!CReader_Buffer_unlockedAdvance(buffer, 1)) goto CReader_internalRead_error; if (!(value = CReader_internalRead(buffer, c, 0))) goto CReader_internalRead_error; break; case '\'': case '"': CReader_Buffer_releaseInterpreter(buffer); value = CReader_readStr(buffer, 0); CReader_Buffer_lockInterpreter(buffer); if (!value) goto CReader_internalRead_error; break; case NUMBERLEADCHARS: CReader_Buffer_releaseInterpreter(buffer); value = CReader_readNum(buffer); CReader_Buffer_lockInterpreter(buffer); if (!value) goto CReader_internalRead_error; break; default: CReader_Buffer_releaseInterpreter(buffer); value = CReader_readUnicodeOrId(buffer); CReader_Buffer_lockInterpreter(buffer); if (!value) goto CReader_internalRead_error; break; } separated = 0; if (inParens == '{') key = value; else if (PyList_Append(res, value) == -1) goto CReader_internalRead_error; } CReader_internalRead_end: if (!multi) { if (!PyObject_IsTrue(res)) { if (inParens == '(') { Py_DECREF(res); res = PyTuple_New(0); } else { PyErr_SetString(PyExc_IOError, "GPremature end of file reached"); goto CReader_internalRead_error; } } else { if (!(value = PyList_GetItem(res, 0))) goto CReader_internalRead_error; Py_INCREF(value); Py_DECREF(res); res = value; } } else if (inParens == '(') { if (!(value = PyList_AsTuple(res))) goto CReader_internalRead_error; Py_DECREF(res); res = value; } else if (inParens == '<') { if (!(value = PyList_AsTuple(res))) goto CReader_internalRead_error; Py_DECREF(res); res = value; if (!(value = PyObject_CallObject(Extension, res))) goto CReader_internalRead_error; Py_DECREF(res); res = value; } PyErr_Clear(); /* Do not propagate EOF if we've come here... */ return res; CReader_internalRead_error: Py_DECREF(res); return NULL; }
PyObject *CalendarToPython(const GSM_CalendarEntry * entry) { PyObject *v; PyObject *f; PyObject *r; PyObject *d; int i; Py_UNICODE *s; char *t; GSM_DateTime dt; int ignore; v = PyList_New(0); if (v == NULL) return NULL; for (i = 0; i < entry->EntriesNum; i++) { f = Py_None; ignore = 0; switch (entry->Entries[i].EntryType) { case CAL_START_DATETIME: /* Fixup date */ dt = entry->Entries[i].Date; if (dt.Hour == 255) { dt.Hour = 0; } if (dt.Minute == 255) { dt.Minute = 0; } if (dt.Second == 255) { dt.Second = 0; } d = BuildPythonDateTime(&dt); if (d == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:O,s:i}", "Type", "START_DATETIME", "Value", d, "AddError", (int)entry->Entries[i]. AddError); Py_DECREF(d); break; case CAL_END_DATETIME: /* Fixup date */ dt = entry->Entries[i].Date; if (dt.Year == 0) { /* Ignore, there can be none end date. */ ignore = 1; break; } if (dt.Hour == 255) { dt.Hour = 23; } if (dt.Minute == 255) { dt.Minute = 59; } if (dt.Second == 255) { dt.Second = 59; } d = BuildPythonDateTime(&dt); if (d == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:O,s:i}", "Type", "END_DATETIME", "Value", d, "AddError", (int)entry->Entries[i]. AddError); Py_DECREF(d); break; case CAL_TONE_ALARM_DATETIME: d = BuildPythonDateTime(& (entry->Entries[i]. Date)); if (d == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:O,s:i}", "Type", "TONE_ALARM_DATETIME", "Value", d, "AddError", (int)entry->Entries[i]. AddError); Py_DECREF(d); break; case CAL_SILENT_ALARM_DATETIME: d = BuildPythonDateTime(& (entry->Entries[i]. Date)); if (d == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:O,s:i}", "Type", "SILENT_ALARM_DATETIME", "Value", d, "AddError", (int)entry->Entries[i]. AddError); Py_DECREF(d); break; case CAL_LAST_MODIFIED: d = BuildPythonDateTime(& (entry->Entries[i]. Date)); if (d == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:O,s:i}", "Type", "LAST_MODIFIED", "Value", d, "AddError", (int)entry->Entries[i]. AddError); Py_DECREF(d); break; case CAL_REPEAT_STARTDATE: d = BuildPythonDateTime(& (entry->Entries[i]. Date)); if (d == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:O,s:i}", "Type", "REPEAT_STARTDATE", "Value", d, "AddError", (int)entry->Entries[i]. AddError); Py_DECREF(d); break; case CAL_REPEAT_STOPDATE: d = BuildPythonDateTime(& (entry->Entries[i]. Date)); if (d == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:O,s:i}", "Type", "REPEAT_STOPDATE", "Value", d, "AddError", (int)entry->Entries[i]. AddError); Py_DECREF(d); break; case CAL_TEXT: s = strGammuToPython(entry->Entries[i].Text); if (s == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:u,s:i}", "Type", "TEXT", "Value", s, "AddError", (int)entry->Entries[i]. AddError); free(s); break; case CAL_DESCRIPTION: s = strGammuToPython(entry->Entries[i].Text); if (s == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:u,s:i}", "Type", "DESCRIPTION", "Value", s, "AddError", (int)entry->Entries[i]. AddError); free(s); break; case CAL_LUID: s = strGammuToPython(entry->Entries[i].Text); if (s == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:u,s:i}", "Type", "LUID", "Value", s, "AddError", (int)entry->Entries[i]. AddError); free(s); break; case CAL_LOCATION: s = strGammuToPython(entry->Entries[i].Text); if (s == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:u,s:i}", "Type", "LOCATION", "Value", s, "AddError", (int)entry->Entries[i]. AddError); free(s); break; case CAL_PHONE: s = strGammuToPython(entry->Entries[i].Text); if (s == NULL) { Py_DECREF(v); return NULL; } f = Py_BuildValue("{s:s,s:u,s:i}", "Type", "PHONE", "Value", s, "AddError", (int)entry->Entries[i]. AddError); free(s); break; case CAL_PRIVATE: f = Py_BuildValue("{s:s,s:i,s:i}", "Type", "PRIVATE", "Value", entry->Entries[i].Number, "AddError", (int)entry->Entries[i]. AddError); break; case CAL_CONTACTID: f = Py_BuildValue("{s:s,s:i,s:i}", "Type", "CONTACTID", "Value", entry->Entries[i].Number, "AddError", (int)entry->Entries[i]. AddError); break; case CAL_REPEAT_DAYOFWEEK: f = Py_BuildValue("{s:s,s:i,s:i}", "Type", "REPEAT_DAYOFWEEK", "Value", entry->Entries[i].Number, "AddError", (int)entry->Entries[i]. AddError); break; case CAL_REPEAT_DAY: f = Py_BuildValue("{s:s,s:i,s:i}", "Type", "REPEAT_DAY", "Value", entry->Entries[i].Number, "AddError", (int)entry->Entries[i]. AddError); break; case CAL_REPEAT_WEEKOFMONTH: f = Py_BuildValue("{s:s,s:i,s:i}", "Type", "REPEAT_WEEKOFMONTH", "Value", entry->Entries[i].Number, "AddError", (int)entry->Entries[i]. AddError); break; case CAL_REPEAT_MONTH: f = Py_BuildValue("{s:s,s:i,s:i}", "Type", "REPEAT_MONTH", "Value", entry->Entries[i].Number, "AddError", (int)entry->Entries[i]. AddError); break; case CAL_REPEAT_FREQUENCY: f = Py_BuildValue("{s:s,s:i,s:i}", "Type", "REPEAT_FREQUENCY", "Value", entry->Entries[i].Number, "AddError", (int)entry->Entries[i]. AddError); break; case CAL_REPEAT_COUNT: f = Py_BuildValue("{s:s,s:i,s:i}", "Type", "REPEAT_COUNT", "Value", entry->Entries[i].Number, "AddError", (int)entry->Entries[i]. AddError); break; case CAL_REPEAT_DAYOFYEAR: f = Py_BuildValue("{s:s,s:i,s:i}", "Type", "REPEAT_DAYOFYEAR", "Value", entry->Entries[i].Number, "AddError", (int)entry->Entries[i]. AddError); break; } if (ignore) { continue; } if (f == Py_None) { Py_DECREF(v); PyErr_Format(PyExc_ValueError, "Bad Calendar item type from gammu: %d", entry->Entries[i].EntryType); return NULL; } if (f == NULL) { Py_DECREF(v); return NULL; } if (PyList_Append(v, f) != 0) { Py_DECREF(f); Py_DECREF(v); return NULL; } Py_DECREF(f); } t = CalendarTypeToString(entry->Type); if (t == NULL) { Py_DECREF(v); return NULL; } r = Py_BuildValue("{s:i,s:s,s:O}", "Location", entry->Location, "Type", t, "Entries", v); free(t); Py_DECREF(v); return r; }
/* * returns a Python list representing the arguments for the process * with given pid or NULL on error. */ PyObject* get_arg_list(long pid) { int nArgs, i; LPWSTR *szArglist; HANDLE hProcess; PVOID pebAddress; PVOID rtlUserProcParamsAddress; UNICODE_STRING commandLine; WCHAR *commandLineContents; PyObject *arg = NULL; PyObject *arg_from_wchar = NULL; PyObject *argList = NULL; hProcess = handle_from_pid(pid); if(hProcess == NULL) { return NULL; } pebAddress = GetPebAddress(hProcess); /* get the address of ProcessParameters */ #ifdef _WIN64 if (!ReadProcessMemory(hProcess, (PCHAR)pebAddress + 32, &rtlUserProcParamsAddress, sizeof(PVOID), NULL)) #else if (!ReadProcessMemory(hProcess, (PCHAR)pebAddress + 0x10, &rtlUserProcParamsAddress, sizeof(PVOID), NULL)) #endif { ////printf("Could not read the address of ProcessParameters!\n"); PyErr_SetFromWindowsErr(0); CloseHandle(hProcess); return NULL; } /* read the CommandLine UNICODE_STRING structure */ #ifdef _WIN64 if (!ReadProcessMemory(hProcess, (PCHAR)rtlUserProcParamsAddress + 112, &commandLine, sizeof(commandLine), NULL)) #else if (!ReadProcessMemory(hProcess, (PCHAR)rtlUserProcParamsAddress + 0x40, &commandLine, sizeof(commandLine), NULL)) #endif { ////printf("Could not read CommandLine!\n"); CloseHandle(hProcess); PyErr_SetFromWindowsErr(0); return NULL; } /* allocate memory to hold the command line */ commandLineContents = (WCHAR *)malloc(commandLine.Length+1); /* read the command line */ if (!ReadProcessMemory(hProcess, commandLine.Buffer, commandLineContents, commandLine.Length, NULL)) { ////printf("Could not read the command line string!\n"); CloseHandle(hProcess); PyErr_SetFromWindowsErr(0); free(commandLineContents); return NULL; } /* print the commandline */ ////printf("%.*S\n", commandLine.Length / 2, commandLineContents); // null-terminate the string to prevent wcslen from returning incorrect length // the length specifier is in characters, but commandLine.Length is in bytes commandLineContents[(commandLine.Length/sizeof(WCHAR))] = '\0'; // attemempt tp parse the command line using Win32 API, fall back on string // cmdline version otherwise szArglist = CommandLineToArgvW(commandLineContents, &nArgs); if (NULL == szArglist) { // failed to parse arglist // encode as a UTF8 Python string object from WCHAR string arg_from_wchar = PyUnicode_FromWideChar(commandLineContents, commandLine.Length / 2); #if PY_MAJOR_VERSION >= 3 argList = Py_BuildValue("N", PyUnicode_AsUTF8String(arg_from_wchar)); #else argList = Py_BuildValue("N", PyUnicode_FromObject(arg_from_wchar)); #endif } else { // arglist parsed as array of UNICODE_STRING, so convert each to Python // string object and add to arg list argList = Py_BuildValue("[]"); for(i=0; i<nArgs; i++) { ////printf("%d: %.*S (%d characters)\n", i, wcslen(szArglist[i]), // szArglist[i], wcslen(szArglist[i])); arg_from_wchar = PyUnicode_FromWideChar(szArglist[i], wcslen(szArglist[i]) ); #if PY_MAJOR_VERSION >= 3 arg = PyUnicode_FromObject(arg_from_wchar); #else arg = PyUnicode_AsUTF8String(arg_from_wchar); #endif Py_XDECREF(arg_from_wchar); PyList_Append(argList, arg); Py_XDECREF(arg); } } LocalFree(szArglist); free(commandLineContents); CloseHandle(hProcess); return argList; }
static inline void PyList_AppendSteal(PyObject *list, PyObject *item) { PyList_Append(list, item); Py_DECREF(item); }
static int diff_hunk_cb( void *cb_data, const git_diff_delta *delta, const git_diff_range *range, const char *header, size_t header_len) { PyObject *hunks; Hunk *hunk; int len; char* old_path, *new_path; char oid[GIT_OID_HEXSZ]; hunks = PyDict_GetItemString(cb_data, "hunks"); if (hunks == NULL) { hunks = PyList_New(0); PyDict_SetItemString(cb_data, "hunks", hunks); Py_DECREF(hunks); } hunk = (Hunk*)PyType_GenericNew(&HunkType, NULL, NULL); if (hunk == NULL) return -1; hunk->old_start = range->old_start; hunk->old_lines = range->old_lines; hunk->new_start = range->new_start; hunk->new_lines = range->new_lines; hunk->old_mode = delta->old_file.mode; hunk->new_mode = delta->new_file.mode; git_oid_fmt(oid, &delta->old_file.oid); hunk->old_oid = PyUnicode_FromStringAndSize(oid, GIT_OID_HEXSZ); git_oid_fmt(oid, &delta->new_file.oid); hunk->new_oid = PyUnicode_FromStringAndSize(oid, GIT_OID_HEXSZ); if (header) { hunk->header = malloc(header_len+1); if (hunk->header == NULL) return -1; memcpy(hunk->header, header, header_len); hunk->header[header_len] = '\0'; } if (delta->old_file.path != NULL) { len = strlen(delta->old_file.path) + 1; old_path = malloc(sizeof(char) * len); if (old_path == NULL) { free(hunk->header); hunk->header = NULL; return -1; } memcpy(old_path, delta->old_file.path, len); hunk->old_file = old_path; } else { hunk->old_file = ""; } if (delta->new_file.path != NULL) { len = strlen(delta->new_file.path) + 1; new_path = malloc(sizeof(char) * len); if (new_path == NULL) { free(hunk->header); free(old_path); return -1; } memcpy(new_path, delta->new_file.path, len); hunk->new_file = new_path; } else { hunk->new_file = ""; } if (hunk->data == NULL) { hunk->data = PyList_New(0); } if(PyList_Append(hunks, (PyObject *)hunk) == 0) { Py_DECREF(hunk); } else { return -1; } return 0; };
JNIEXPORT void JNICALL Java_edu_cornell_vision_hadoop_HadoopPythonMRJob_00024Map_mapper_1init (JNIEnv * env, jobject thisObj, jlong impl, jobject context, jstring user_module, jstring mapper_class_name) { struct MapperImpl * ptr = (struct MapperImpl*)impl; PyObject * main_module = NULL; //borrowed PyObject * sys = NULL; //new PyObject * path = NULL; //new PyObject * dot_string = NULL; //new PyObject * module = NULL; //new PyObject * module_contents = NULL; //borrowed PyObject * mapper_class = NULL; //borrowed PyObject * mapper_object = NULL; PyObject * loads_function = NULL; //borrowed PyObject * dumps_function = NULL; //borrowed PyObject * result = NULL; //new PyObject * mapper_context = NULL; const char * user_module_char = NULL; const char * mapper_class_char = NULL; PyObject * faulthandler_enable_retval = NULL; //new PyObject * faulthandler_disable_retval = NULL; //new HANDLE_JAVA(ptr->Text = (*env)->FindClass(env, "org/apache/hadoop/io/Text")) HANDLE_JAVA(ptr->Text_getBytes = (*env)->GetMethodID(env, ptr->Text, "getBytes", "()[B")); HANDLE_JAVA(ptr->Text_getLength = (*env)->GetMethodID(env, ptr->Text, "getLength", "()I")); Py_SetProgramName("Mapper"); #ifdef FAULTHANDLER HANDLE_PYTHON(ptr->faulthandler = PyImport_ImportModule("faulthandler"), "import faulthandler") #else ptr->faulthandler = Py_None; Py_INCREF(ptr->faulthandler); #endif HANDLE_PYTHON(main_module = PyImport_AddModule("__main__"), "import __main__") HANDLE_PYTHON(sys = PyImport_ImportModule("sys"), "import sys") HANDLE_PYTHON(path = PyObject_GetAttrString(sys, "path"), "get sys.path") HANDLE_PYTHON(dot_string = PyString_FromString("."), "make . string") if (PyList_Append(path, dot_string) < 0) { raise_python_exception (env, "append ."); goto failure; } HANDLE_JAVA(user_module_char = (*env)->GetStringUTFChars(env, user_module, 0)) module = PyImport_ImportModule (user_module_char); HANDLE_JAVA((*env)->ReleaseStringUTFChars(env, user_module, user_module_char)) if (!module) { raise_python_exception (env, "import module"); goto failure; } HANDLE_PYTHON(module_contents = PyModule_GetDict (module), "get module contents"); if (!PyDict_GetItemString (module_contents, "Context")) { if (PyType_Ready(&Context_type) < 0) { raise_python_exception (env, "mapper context not ready"); goto failure; } Py_INCREF(&Context_type); if (PyModule_AddObject (module, "Context", (PyObject*)&Context_type) < 0) { raise_python_exception (env, "add context"); goto failure; } } if (!PyDict_GetItemString (module_contents, "Counter")) { if (PyType_Ready(&Counter_type) < 0) { raise_python_exception (env, "counter not ready"); goto failure; } Py_INCREF(&Counter_type); if (PyModule_AddObject (module, "Counter", (PyObject*)&Counter_type) < 0) { raise_python_exception (env, "add counter"); goto failure; } } HANDLE_JAVA(mapper_class_char = (*env)->GetStringUTFChars(env, mapper_class_name, 0)) mapper_class = PyDict_GetItemString (module_contents, mapper_class_char); HANDLE_JAVA((*env)->ReleaseStringUTFChars(env, mapper_class_name, mapper_class_char)) if (!mapper_class) { PyErr_SetString(PyExc_RuntimeError, "mapper not found"); raise_python_exception (env, "get mapper"); goto failure; } HANDLE_PYTHON(mapper_object = PyObject_CallObject (mapper_class, NULL), "create mapper") ptr->mapper = mapper_object; HANDLE_PYTHON(loads_function = PyObject_GetAttrString (mapper_object, "loads"), "get mapper loads"); ptr->loads = loads_function; HANDLE_PYTHON(dumps_function = PyObject_GetAttrString (mapper_object, "dumps"), "get mapper dumps"); ptr->dumps = dumps_function; HANDLE_PYTHON (mapper_context = build_context (env, context, ptr->dumps, ptr->faulthandler), "build map context") #ifdef FAULTHANDLER HANDLE_PYTHON(faulthandler_enable_retval = PyObject_CallMethod(ptr->faulthandler, "enable", NULL), "enable faulthandler"); #endif HANDLE_PYTHON(result = PyObject_CallMethod (mapper_object, "setup", "O", mapper_context), "call mapper setup") #ifdef FAULTHANDLER HANDLE_PYTHON(faulthandler_disable_retval = PyObject_CallMethod(ptr->faulthandler, "disable", NULL), "disable faulthandler"); #endif failure: Py_XDECREF(faulthandler_enable_retval); Py_XDECREF(faulthandler_disable_retval); Py_XDECREF(mapper_context); Py_XDECREF(sys); Py_XDECREF(path); Py_XDECREF(dot_string); Py_XDECREF(module); Py_XDECREF(result); }
PyObject *list_packages(PyObject *self, PyObject *args, PyObject *kw) { const char *filename; static char *kwlist[] = {"filename", NULL}; struct archive *a; struct archive_entry *entry; struct stat st; char pname[ABUFLEN], *fname, *dname, *pkgname, *pkgver; PyObject *ret, *dict, *pystr; if(!PyArg_ParseTupleAndKeywords(args, kw, "s", kwlist, &filename)) return NULL; if(filename == NULL || strlen(filename)<=0) { PyErr_SetString(PyExc_ValueError, "Empty files tarball name given."); return NULL; } pname[ABUFLEN-1]='\0'; if(stat(filename, &st)==-1 || !S_ISREG(st.st_mode)) { PyErr_Format(PyExc_IOError, "File does not exist: %s\n", filename); return NULL; } ret = PyList_New(0); if(ret == NULL) { return NULL; } a = archive_read_new(); archive_read_support_compression_all(a); archive_read_support_format_all(a); archive_read_open_filename(a, filename, 10240); while (archive_read_next_header(a, &entry) == ARCHIVE_OK) { if(!S_ISREG(archive_entry_filetype(entry))) { archive_read_data_skip(a); continue; } strncpy(pname, archive_entry_pathname(entry), ABUFLEN-1); fname = basename(pname); dname = dirname(pname); if(strcmp(fname, "files") == 0) { if (splitname(dname, &pkgname, &pkgver) == -1) { archive_read_data_skip(a); continue; } dict = PyDict_New(); if(dict == NULL) { goto cleanup_nodict; } pystr = PyUnicode_FromString(pkgname); free(pkgname); if(pystr == NULL) { free(pkgver); goto cleanup; } PyDict_SetItemString(dict, "name", pystr); Py_DECREF(pystr); pystr = PyUnicode_FromString(pkgver); free(pkgver); if(pystr == NULL) goto cleanup; PyDict_SetItemString(dict, "version", pystr); Py_DECREF(pystr); PyList_Append(ret, dict); Py_DECREF(dict); } archive_read_data_skip(a); } archive_read_finish(a); return ret; cleanup: Py_DECREF(dict); cleanup_nodict: archive_read_finish(a); Py_DECREF(ret); return NULL; }
static PyObject * GetModemList(io_iterator_t serialPortIterator) { io_object_t deviceService; int maxPathSize = MAXPATHLEN; PyObject *ret = Py_BuildValue("[]"); /* Iterate across all devices found. */ while ((deviceService = IOIteratorNext(serialPortIterator))) { CFTypeRef bsdIOTTYDeviceAsCFString; CFTypeRef bsdIOTTYBaseNameAsCFString; CFTypeRef bsdIOTTYSuffixAsCFString; CFTypeRef bsdCalloutPathAsCFString; CFTypeRef bsdDialinPathAsCFString; Boolean result; char name[MAXPATHLEN]; /* MAXPATHLEN = 1024 */ char base[MAXPATHLEN]; char suffix[MAXPATHLEN]; char callout[MAXPATHLEN]; char dialin[MAXPATHLEN]; PyObject *d; bsdIOTTYDeviceAsCFString = IORegistryEntryCreateCFProperty(deviceService, CFSTR(kIOTTYDeviceKey), kCFAllocatorDefault, 0); bsdIOTTYBaseNameAsCFString = IORegistryEntryCreateCFProperty(deviceService, CFSTR(kIOTTYBaseNameKey), kCFAllocatorDefault, 0); bsdIOTTYSuffixAsCFString = IORegistryEntryCreateCFProperty(deviceService, CFSTR(kIOTTYSuffixKey), kCFAllocatorDefault, 0); bsdCalloutPathAsCFString = IORegistryEntryCreateCFProperty(deviceService, CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0); bsdDialinPathAsCFString = IORegistryEntryCreateCFProperty(deviceService, CFSTR(kIODialinDeviceKey), kCFAllocatorDefault, 0); if (bsdIOTTYDeviceAsCFString) { result = CFStringGetCString(bsdIOTTYDeviceAsCFString, name, maxPathSize, kCFStringEncodingASCII); CFRelease(bsdIOTTYDeviceAsCFString); } if (bsdIOTTYBaseNameAsCFString) { result = CFStringGetCString(bsdIOTTYBaseNameAsCFString, base, maxPathSize, kCFStringEncodingASCII); CFRelease(bsdIOTTYBaseNameAsCFString); } if (bsdIOTTYSuffixAsCFString) { result = CFStringGetCString(bsdIOTTYSuffixAsCFString, suffix, maxPathSize, kCFStringEncodingASCII); CFRelease(bsdIOTTYSuffixAsCFString); } if (bsdCalloutPathAsCFString) { result = CFStringGetCString(bsdCalloutPathAsCFString, callout, maxPathSize, kCFStringEncodingASCII); CFRelease(bsdCalloutPathAsCFString); } if (bsdDialinPathAsCFString) { result = CFStringGetCString(bsdDialinPathAsCFString, dialin, maxPathSize, kCFStringEncodingASCII); CFRelease(bsdDialinPathAsCFString); } d = Py_BuildValue("{s:s,s:s,s:s,s:s,s:s}", "name", name, "base", base, "suffix", suffix, "callout", callout, "dialin", dialin); if (PyList_Append(ret, d)) { Py_DECREF(d); goto error; } else { Py_DECREF(d); } } error: /* Release the io_service_t now that we are done with it. */ (void) IOObjectRelease(deviceService); return ret; }
static void getaddrinfo_cb(uv_getaddrinfo_t* handle, int status, struct addrinfo* res) { PyGILState_STATE gstate = PyGILState_Ensure(); struct addrinfo *ptr; ares_cb_data_t *data; uv_err_t err; DNSResolver *self; PyObject *callback, *addr, *item, *errorno, *dns_result, *result; ASSERT(handle); data = (ares_cb_data_t*)(handle->data); self = data->resolver; callback = data->cb; ASSERT(self); /* Object could go out of scope in the callback, increase refcount to avoid it */ Py_INCREF(self); if (status != UV_OK) { err = uv_last_error(UV_LOOP(self)); errorno = PyInt_FromLong((long)err.code); dns_result = Py_None; Py_INCREF(Py_None); goto callback; } dns_result = PyList_New(0); if (!dns_result) { PyErr_NoMemory(); PyErr_WriteUnraisable(Py_None); errorno = PyInt_FromLong((long)UV_ENOMEM); dns_result = Py_None; Py_INCREF(Py_None); goto callback; } for (ptr = res; ptr; ptr = ptr->ai_next) { addr = makesockaddr(ptr->ai_addr, ptr->ai_addrlen); if (!addr) { PyErr_NoMemory(); PyErr_WriteUnraisable(callback); break; } item = Py_BuildValue("iiisO", ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol, ptr->ai_canonname ? ptr->ai_canonname : "", addr); Py_DECREF(addr); if (!item) { PyErr_NoMemory(); PyErr_WriteUnraisable(callback); break; } PyList_Append(dns_result, item); Py_DECREF(item); } errorno = Py_None; Py_INCREF(Py_None); callback: result = PyObject_CallFunctionObjArgs(callback, self, dns_result, errorno, NULL); if (result == NULL) { PyErr_WriteUnraisable(callback); } Py_XDECREF(result); Py_DECREF(callback); uv_freeaddrinfo(res); PyMem_Free(handle); PyMem_Free(data); Py_DECREF(self); PyGILState_Release(gstate); }
/* Append obj to list; return true if error (out of memory), false if OK. */ static int referentsvisit(PyObject *obj, PyObject *list) { return PyList_Append(list, obj) < 0; }