Esempio n. 1
0
PyObject *
PySequence_Tuple(PyObject *v)
{
	PySequenceMethods *m;

	if (v == NULL)
		return null_error();

	if (PyTuple_Check(v)) {
		Py_INCREF(v);
		return v;
	}

	if (PyList_Check(v))
		return PyList_AsTuple(v);

	/* There used to be code for strings here, but tuplifying strings is
	   not a common activity, so I nuked it.  Down with code bloat! */

	/* Generic sequence object */
	m = v->ob_type->tp_as_sequence;
	if (m && m->sq_item) {
		int i;
		PyObject *t;
		int n = PySequence_Size(v);
		if (n < 0)
			return NULL;
		t = PyTuple_New(n);
		if (t == NULL)
			return NULL;
		for (i = 0; ; i++) {
			PyObject *item = (*m->sq_item)(v, i);
			if (item == NULL) {
				if (PyErr_ExceptionMatches(PyExc_IndexError))
					PyErr_Clear();
				else {
					Py_DECREF(t);
					t = NULL;
				}
				break;
			}
			if (i >= n) {
				if (n < 500)
					n += 10;
				else
					n += 100;
				if (_PyTuple_Resize(&t, n, 0) != 0)
					break;
			}
			PyTuple_SET_ITEM(t, i, item);
		}
		if (i < n && t != NULL)
			_PyTuple_Resize(&t, i, 0);
		return t;
	}

	/* None of the above */
	return type_error("tuple() argument must be a sequence");
}
Esempio n. 2
0
static PyObject *
devices(struct pyalsacontrol *self, PyObject *args,
			   int (*fcn)(snd_ctl_t *, int *))
{
	int dev, err, size = 0;
	PyObject *t;

	dev = -1;
	t = PyTuple_New(size);
	do {
		err = fcn(self->handle, &dev);
		if (err < 0) {
			PyErr_Format(PyExc_IOError,
			     "Control hwdep_next_device error: %s", strerror(-err));
			Py_DECREF(t);
			return NULL;
		}
		if (dev >= 0) {
			_PyTuple_Resize(&t, ++size);
			if (t)
				PyTuple_SetItem(t, size-1, PyInt_FromLong(dev));
		}
	} while (dev >= 0);
	return t;
}
Esempio n. 3
0
/*
  dummy.decode_command_n(stream, N) -> ((cmd_code, args), .... (cmd_code_N, args_N))
 */
static PyObject *
dummy_decode_command(PyObject *self, PyObject *args) {
  int N = 1;

  PyObject *po = PyTuple_GetItem(args, 0);
  if (!PyFile_Check(po)) {
    PyErr_SetString(DummyError, "First argument should be  a file object.");
    return NULL;
  }
  if (PyTuple_Size(args) == 2) {
    PyObject *pn = PyTuple_GetItem(args, 1);
    N = PyInt_AS_LONG(pn);
  }

  hu::FileInStream stream;
  FILE *handle = PyFile_AsFile(po);
  stream.open(handle);

  PyObject* res = PyTuple_New(N);
  
  for(int i = 0;  i < N ; ++i) {
    PyObject* cmd = decoder.decode_cmd_from_stream(stream);
    if (cmd == NULL) {
      return NULL;
    }
    PyTuple_SET_ITEM(res, i, cmd);
    if (PyInt_AS_LONG(PyTuple_GetItem(cmd, 0)) == CLOSE) {
      _PyTuple_Resize(&res, i + 1);
      return res;
    }
  }
  return res;
}
Esempio n. 4
0
static void python_process_general_event(struct perf_sample *sample,
					 struct perf_evsel *evsel,
					 struct thread *thread,
					 struct addr_location *al)
{
	PyObject *handler, *retval, *t, *dict;
	static char handler_name[64];
	unsigned n = 0;

	/*
	 * Use the MAX_FIELDS to make the function expandable, though
	 * currently there is only one item for the tuple.
	 */
	t = PyTuple_New(MAX_FIELDS);
	if (!t)
		Py_FatalError("couldn't create Python tuple");

	dict = PyDict_New();
	if (!dict)
		Py_FatalError("couldn't create Python dictionary");

	snprintf(handler_name, sizeof(handler_name), "%s", "process_event");

	handler = PyDict_GetItemString(main_dict, handler_name);
	if (!handler || !PyCallable_Check(handler))
		goto exit;

	pydict_set_item_string_decref(dict, "ev_name", PyString_FromString(perf_evsel__name(evsel)));
	pydict_set_item_string_decref(dict, "attr", PyString_FromStringAndSize(
			(const char *)&evsel->attr, sizeof(evsel->attr)));
	pydict_set_item_string_decref(dict, "sample", PyString_FromStringAndSize(
			(const char *)sample, sizeof(*sample)));
	pydict_set_item_string_decref(dict, "raw_buf", PyString_FromStringAndSize(
			(const char *)sample->raw_data, sample->raw_size));
	pydict_set_item_string_decref(dict, "comm",
			PyString_FromString(thread__comm_str(thread)));
	if (al->map) {
		pydict_set_item_string_decref(dict, "dso",
			PyString_FromString(al->map->dso->name));
	}
	if (al->sym) {
		pydict_set_item_string_decref(dict, "symbol",
			PyString_FromString(al->sym->name));
	}

	PyTuple_SetItem(t, n++, dict);
	if (_PyTuple_Resize(&t, n) == -1)
		Py_FatalError("error resizing Python tuple");

	retval = PyObject_CallObject(handler, t);
	if (retval == NULL)
		handler_call_die(handler_name);
exit:
	Py_DECREF(dict);
	Py_DECREF(t);
}
Esempio n. 5
0
PyObject *netinfo_get_routes(PyObject *self, PyObject *args)
{
    char buffer[1024], *tok, *c, *ipstr;
    int field = 0, i = 1;
    struct in_addr addr;
    PyObject *dict, *tuple = PyTuple_New(0);
    FILE *file = fopen("/proc/net/route", "r");

    if (!file) {
        PyErr_SetFromErrno(PyExc_Exception);
        return NULL;
    }
    if (!fgets(buffer, 1024, file)) {
        PyErr_SetFromErrno(PyExc_Exception);
        fclose(file); 
        return NULL;
    }
//     strtok_r(buffer, " \t", &tok);
    while (fgets(buffer, 1024, file)) {
        dict = PyDict_New();
        field = 0;
        while ((c = strtok_r(field ? NULL : buffer, " \t", &tok))) {
            switch (field++) {
                case 0:
//                     printf("iface: %s\n", c);
                    PyDict_SetItemString(dict, "dev", Py_BuildValue("s", c));
                    break;
                case 1:
//                     printf("dest: %s\n", c);
                    sscanf(c, "%X", (uint32_t *)&addr);
                    ipstr = inet_ntoa(addr);
                    PyDict_SetItemString(dict, "dest", Py_BuildValue("s", ipstr));
                    break;
                case 2:
//                     printf("gateway: %s\n", c);
                    sscanf(c, "%X", (uint32_t *)&addr);
                    ipstr = inet_ntoa(addr);
                    PyDict_SetItemString(dict, "gateway", Py_BuildValue("s", ipstr));
                    break;  
                case 7:
//                     printf("netmask: %s\n", c);
                    sscanf(c, "%X", (uint32_t *)&addr);
                    ipstr = inet_ntoa(addr);
                    PyDict_SetItemString(dict, "netmask", Py_BuildValue("s", ipstr));
                    break;  
                default:  
                    break;
            }
        }
        _PyTuple_Resize(&tuple, i);
        PyTuple_SET_ITEM(tuple, i++-1, dict);
    }
    fclose(file); 
    return tuple;
}
Esempio n. 6
0
PyObject *
PP_Debug_Function(PyObject *func, PyObject *args)
{
    int oops, res;
    PyObject *presult;

    /* expand tuple at front */
    // it seems that some versions of python want just 2 arguments; in that
    // case, remove trailing 1
#if (PY_MAJOR_VERSION==2)&&(PY_MINOR_VERSION>=2)
    oops = _PyTuple_Resize(&args, (1 + PyTuple_Size(args))); 
#else
    oops = _PyTuple_Resize(&args, (1 + PyTuple_Size(args)),1); 
#endif    
    oops |= PyTuple_SetItem(args, 0, func);   
    if (oops) 
        return NULL;                        /* "args = (funcobj,) + (arg,..)" */

    res = PP_Run_Function(                  /* "pdb.runcall(funcobj, arg,..)" */
                 "pdb",  "runcall",         /* recursive run_function */
                 "O",    &presult,
                 "O",     args);            /* args already is a tuple */
    return (res != 0) ? NULL : presult;     /* errors in run_function? */
}                                           /* presult not yet decref'd */
PyObject *
PP_Debug_Function(PyObject *func, PyObject *args)
{
    int oops, res, i;
    PyObject *presult;

    /* expand tuple for func */
    oops = _PyTuple_Resize(&args, (1 + PyTuple_Size(args)));    /* NO 3RD ARG */
    if (oops) 
        return NULL;                        /* "args = (funcobj,) + (arg,..)" */

    /* move orig args right */
    for (i=PyTuple_Size(args)-1; i > 1; i--)
        PyTuple_SetItem(args, i, PyTuple_GetItem(args, i-1));
    PyTuple_SetItem(args, 0, func);   

    res = PP_Run_Function(                  /* "pdb.runcall(funcobj, arg,..)" */
                 "pdb",  "runcall",         /* recursive run_function */
                 "O",    &presult,
                 "O",     args);            /* args already is a tuple */
    return (res != 0) ? NULL : presult;     /* errors in run_function? */
}                                           /* presult not yet decref'd */
static void python_process_event(int cpu, void *data,
				 int size __unused,
				 unsigned long long nsecs, char *comm)
{
	PyObject *handler, *retval, *context, *t, *obj, *dict = NULL;
	static char handler_name[256];
	struct format_field *field;
	unsigned long long val;
	unsigned long s, ns;
	struct event *event;
	unsigned n = 0;
	int type;
	int pid;

	t = PyTuple_New(MAX_FIELDS);
	if (!t)
		Py_FatalError("couldn't create Python tuple");

	type = trace_parse_common_type(data);

	event = find_cache_event(type);
	if (!event)
		die("ug! no event found for type %d", type);

	pid = trace_parse_common_pid(data);

	sprintf(handler_name, "%s__%s", event->system, event->name);

	handler = PyDict_GetItemString(main_dict, handler_name);
	if (handler && !PyCallable_Check(handler))
		handler = NULL;
	if (!handler) {
		dict = PyDict_New();
		if (!dict)
			Py_FatalError("couldn't create Python dict");
	}
	s = nsecs / NSECS_PER_SEC;
	ns = nsecs - s * NSECS_PER_SEC;

	scripting_context->event_data = data;

	context = PyCObject_FromVoidPtr(scripting_context, NULL);

	PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
	PyTuple_SetItem(t, n++,
			PyCObject_FromVoidPtr(scripting_context, NULL));

	if (handler) {
		PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
		PyTuple_SetItem(t, n++, PyInt_FromLong(s));
		PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
		PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
		PyTuple_SetItem(t, n++, PyString_FromString(comm));
	} else {
		PyDict_SetItemString(dict, "common_cpu", PyInt_FromLong(cpu));
		PyDict_SetItemString(dict, "common_s", PyInt_FromLong(s));
		PyDict_SetItemString(dict, "common_ns", PyInt_FromLong(ns));
		PyDict_SetItemString(dict, "common_pid", PyInt_FromLong(pid));
		PyDict_SetItemString(dict, "common_comm", PyString_FromString(comm));
	}
	for (field = event->format.fields; field; field = field->next) {
		if (field->flags & FIELD_IS_STRING) {
			int offset;
			if (field->flags & FIELD_IS_DYNAMIC) {
				offset = *(int *)(data + field->offset);
				offset &= 0xffff;
			} else
				offset = field->offset;
			obj = PyString_FromString((char *)data + offset);
		} else { /* FIELD_IS_NUMERIC */
			val = read_size(data + field->offset, field->size);
			if (field->flags & FIELD_IS_SIGNED) {
				if ((long long)val >= LONG_MIN &&
				    (long long)val <= LONG_MAX)
					obj = PyInt_FromLong(val);
				else
					obj = PyLong_FromLongLong(val);
			} else {
				if (val <= LONG_MAX)
					obj = PyInt_FromLong(val);
				else
					obj = PyLong_FromUnsignedLongLong(val);
			}
		}
		if (handler)
			PyTuple_SetItem(t, n++, obj);
		else
			PyDict_SetItemString(dict, field->name, obj);

	}
	if (!handler)
		PyTuple_SetItem(t, n++, dict);

	if (_PyTuple_Resize(&t, n) == -1)
		Py_FatalError("error resizing Python tuple");

	if (handler) {
		retval = PyObject_CallObject(handler, t);
		if (retval == NULL)
			handler_call_die(handler_name);
	} else {
		handler = PyDict_GetItemString(main_dict, "trace_unhandled");
		if (handler && PyCallable_Check(handler)) {

			retval = PyObject_CallObject(handler, t);
			if (retval == NULL)
				handler_call_die("trace_unhandled");
		}
		Py_DECREF(dict);
	}

	Py_DECREF(t);
}
Esempio n. 9
0
void
_pygi_closure_handle (ffi_cif *cif,
                      void    *result,
                      void   **args,
                      void    *data)
{
    PyGILState_STATE state;
    PyGICClosure *closure = data;
    gint n_args, i;
    GIArgInfo  *arg_info;
    GIDirection arg_direction;
    GITypeInfo *arg_type;
    GITransfer arg_transfer;
    GITypeTag  arg_tag;
    GITypeTag  return_tag;
    GITransfer return_transfer;
    GITypeInfo *return_type;
    PyObject *retval;
    PyObject *py_args;
    PyObject *pyarg;
    gint n_in_args, n_out_args;


    /* Lock the GIL as we are coming into this code without the lock and we
      may be executing python code */
    state = PyGILState_Ensure();

    return_type = g_callable_info_get_return_type(closure->info);
    return_tag = g_type_info_get_tag(return_type);
    return_transfer = g_callable_info_get_caller_owns(closure->info);

    n_args = g_callable_info_get_n_args (closure->info);

    py_args = PyTuple_New(n_args);
    if (py_args == NULL) {
        PyErr_Clear();
        goto end;
    }

    n_in_args = 0;

    for (i = 0; i < n_args; i++) {
        arg_info = g_callable_info_get_arg (closure->info, i);
        arg_type = g_arg_info_get_type (arg_info);
        arg_transfer = g_arg_info_get_ownership_transfer(arg_info);
        arg_tag = g_type_info_get_tag(arg_type);
        arg_direction = g_arg_info_get_direction(arg_info);
        switch (arg_tag) {
        case GI_TYPE_TAG_VOID:
        {
            if (g_type_info_is_pointer(arg_type)) {
                if (PyTuple_SetItem(py_args, n_in_args, closure->user_data) != 0) {
                    PyErr_Clear();
                    goto end;
                }
                n_in_args++;
                continue;
            }
        }
        case GI_TYPE_TAG_ERROR:
        {
            continue;
        }
        default:
        {
            pyarg = _pygi_argument_to_object (args[i],
                                              arg_type,
                                              arg_transfer);

            if(PyTuple_SetItem(py_args, n_in_args, pyarg) != 0) {
                PyErr_Clear();
                goto end;
            }
            n_in_args++;
            g_base_info_unref((GIBaseInfo*)arg_info);
            g_base_info_unref((GIBaseInfo*)arg_type);
        }
        }

    }

    if(_PyTuple_Resize (&py_args, n_in_args) != 0) {
        PyErr_Clear();
        goto end;
    }

    retval = PyObject_CallObject((PyObject *)closure->function, py_args);

    Py_DECREF(py_args);

    if (retval == NULL) {
        goto end;
    }

    *(GArgument*)result = _pygi_argument_from_object(retval, return_type, return_transfer);

end:
    g_base_info_unref((GIBaseInfo*)return_type);

    PyGILState_Release(state);

    if (closure->user_data)
        Py_XDECREF(closure->user_data);

    /* Now that the closure has finished we can make a decision about how
       to free it.  Scope call gets free'd now, scope notified will be freed
       when the notify is called and we can free async anytime we want
       once we return from this function */
    switch (closure->scope) {
    case GI_SCOPE_TYPE_CALL:
        _pygi_invoke_closure_free(closure);
        break;
    case GI_SCOPE_TYPE_NOTIFIED:
        break;
    case GI_SCOPE_TYPE_ASYNC:
        /* Append this PyGICClosure to a list of closure that we will free
           after we're done with this function invokation */
        async_free_list = g_slist_prepend(async_free_list, closure);
        break;
    default:
        g_assert_not_reached();
    }
}
Esempio n. 10
0
static void python_process_tracepoint(struct perf_sample *sample,
				      struct perf_evsel *evsel,
				      struct thread *thread,
				      struct addr_location *al)
{
	PyObject *handler, *retval, *context, *t, *obj, *dict = NULL;
	static char handler_name[256];
	struct format_field *field;
	unsigned long long val;
	unsigned long s, ns;
	struct event_format *event;
	unsigned n = 0;
	int pid;
	int cpu = sample->cpu;
	void *data = sample->raw_data;
	unsigned long long nsecs = sample->time;
	const char *comm = thread__comm_str(thread);

	t = PyTuple_New(MAX_FIELDS);
	if (!t)
		Py_FatalError("couldn't create Python tuple");

	event = find_cache_event(evsel);
	if (!event)
		die("ug! no event found for type %d", (int)evsel->attr.config);

	pid = raw_field_value(event, "common_pid", data);

	sprintf(handler_name, "%s__%s", event->system, event->name);

	handler = PyDict_GetItemString(main_dict, handler_name);
	if (handler && !PyCallable_Check(handler))
		handler = NULL;
	if (!handler) {
		dict = PyDict_New();
		if (!dict)
			Py_FatalError("couldn't create Python dict");
	}
	s = nsecs / NSECS_PER_SEC;
	ns = nsecs - s * NSECS_PER_SEC;

	scripting_context->event_data = data;
	scripting_context->pevent = evsel->tp_format->pevent;

	context = PyCObject_FromVoidPtr(scripting_context, NULL);

	PyTuple_SetItem(t, n++, PyString_FromString(handler_name));
	PyTuple_SetItem(t, n++, context);

	if (handler) {
		PyTuple_SetItem(t, n++, PyInt_FromLong(cpu));
		PyTuple_SetItem(t, n++, PyInt_FromLong(s));
		PyTuple_SetItem(t, n++, PyInt_FromLong(ns));
		PyTuple_SetItem(t, n++, PyInt_FromLong(pid));
		PyTuple_SetItem(t, n++, PyString_FromString(comm));
	} else {
		pydict_set_item_string_decref(dict, "common_cpu", PyInt_FromLong(cpu));
		pydict_set_item_string_decref(dict, "common_s", PyInt_FromLong(s));
		pydict_set_item_string_decref(dict, "common_ns", PyInt_FromLong(ns));
		pydict_set_item_string_decref(dict, "common_pid", PyInt_FromLong(pid));
		pydict_set_item_string_decref(dict, "common_comm", PyString_FromString(comm));
	}
	for (field = event->format.fields; field; field = field->next) {
		if (field->flags & FIELD_IS_STRING) {
			int offset;
			if (field->flags & FIELD_IS_DYNAMIC) {
				offset = *(int *)(data + field->offset);
				offset &= 0xffff;
			} else
				offset = field->offset;
			obj = PyString_FromString((char *)data + offset);
		} else { /* FIELD_IS_NUMERIC */
			val = read_size(event, data + field->offset,
					field->size);
			if (field->flags & FIELD_IS_SIGNED) {
				if ((long long)val >= LONG_MIN &&
				    (long long)val <= LONG_MAX)
					obj = PyInt_FromLong(val);
				else
					obj = PyLong_FromLongLong(val);
			} else {
				if (val <= LONG_MAX)
					obj = PyInt_FromLong(val);
				else
					obj = PyLong_FromUnsignedLongLong(val);
			}
		}
		if (handler)
			PyTuple_SetItem(t, n++, obj);
		else
			pydict_set_item_string_decref(dict, field->name, obj);

	}
	if (!handler)
		PyTuple_SetItem(t, n++, dict);

	if (_PyTuple_Resize(&t, n) == -1)
		Py_FatalError("error resizing Python tuple");

	if (handler) {
		retval = PyObject_CallObject(handler, t);
		if (retval == NULL)
			handler_call_die(handler_name);
	} else {
		handler = PyDict_GetItemString(main_dict, "trace_unhandled");
		if (handler && PyCallable_Check(handler)) {

			retval = PyObject_CallObject(handler, t);
			if (retval == NULL)
				handler_call_die("trace_unhandled");
		}
		Py_DECREF(dict);
	}

	Py_DECREF(t);
}
Esempio n. 11
0
static gboolean
_pygi_closure_convert_arguments (PyGIInvokeState *state,
                                 PyGIClosureCache *closure_cache)
{
    PyGICallableCache *cache = (PyGICallableCache *) closure_cache;
    gssize n_in_args = 0;
    gssize i;

    for (i = 0; i < _pygi_callable_cache_args_len (cache); i++) {
        PyGIArgCache *arg_cache;

        arg_cache = g_ptr_array_index (cache->args_cache, i);

        if (arg_cache->direction & PYGI_DIRECTION_TO_PYTHON) {
            PyObject *value;

            if (cache->user_data_index == i) {
                if (state->user_data == NULL) {
                    /* user_data can be NULL for connect functions which don't accept
                     * user_data or as the default for user_data in the middle of function
                     * arguments.
                     */
                    Py_INCREF (Py_None);
                    value = Py_None;
                } else {
                    /* Extend the callbacks args with user_data as variable args. */
                    gssize j, user_data_len;
                    PyObject *py_user_data = state->user_data;

                    if (!PyTuple_Check (py_user_data)) {
                        PyErr_SetString (PyExc_TypeError, "expected tuple for callback user_data");
                        return FALSE;
                    }

                    user_data_len = PyTuple_Size (py_user_data);
                    _PyTuple_Resize (&state->py_in_args,
                                     state->n_py_in_args + user_data_len - 1);

                    for (j = 0; j < user_data_len; j++, n_in_args++) {
                        value = PyTuple_GetItem (py_user_data, j);
                        Py_INCREF (value);
                        PyTuple_SET_ITEM (state->py_in_args, n_in_args, value);
                    }
                    /* We can assume user_data args are never going to be inout,
                     * so just continue here.
                     */
                    continue;
                }
            } else if (arg_cache->meta_type != PYGI_META_ARG_TYPE_PARENT) {
                continue;
            } else {
                value = arg_cache->to_py_marshaller (state,
                                                     cache,
                                                     arg_cache,
                                                     &state->args[i].arg_value);

                if (value == NULL) {
                    pygi_marshal_cleanup_args_to_py_parameter_fail (state,
                                                                    cache,
                                                                    i);
                    return FALSE;
                }
            }

            PyTuple_SET_ITEM (state->py_in_args, n_in_args, value);
            n_in_args++;
        }
    }

    if (_PyTuple_Resize (&state->py_in_args, n_in_args) == -1)
        return FALSE;

    return TRUE;
}
Esempio n. 12
0
static PyObject*
neighbors(PygtsVertex* self, PyObject *args)
{
  PyObject *s_=NULL;
  GtsSurface *s=NULL;
  GSList *vertices,*v;
  PygtsVertex *vertex;
  PyObject *tuple;
  guint n,N;

  SELF_CHECK

  /* Parse the args */
  if(! PyArg_ParseTuple(args, "|O", &s_) ) {
    return NULL;
  }

  /* Convert */
  if( s_ != NULL ) {
    if(!pygts_surface_check(s_)) {
      PyErr_SetString(PyExc_TypeError,"expected a Surface");
      return NULL;
    }
    s = PYGTS_SURFACE_AS_GTS_SURFACE(s_);
  }

  /* Get the neighbors */
  vertices = gts_vertex_neighbors(PYGTS_VERTEX_AS_GTS_VERTEX(self),
				  NULL,s);
  N = g_slist_length(vertices);

  /* Create the tuple */
  if( (tuple=PyTuple_New(N)) == NULL) {
    PyErr_SetString(PyExc_MemoryError,"could not create tuple");
    return NULL;
  }

  /* Put PygtsVertex objects into the tuple */
  v = vertices;
  for(n=0;n<N;n++) {

    /* Skip this vertex if it is a parent */
    while( v!=NULL && PYGTS_IS_PARENT_VERTEX(GTS_VERTEX(v->data)) ) {
      v = g_slist_next(v);      
    }
    if( v==NULL ) break;

    if( (vertex = pygts_vertex_new(GTS_VERTEX(v->data))) == NULL ) {
      Py_DECREF((PyObject*)tuple);
      return NULL;
    }

    PyTuple_SET_ITEM(tuple, n, (PyObject*)vertex);
    
    v = g_slist_next(v);
  }

  if(_PyTuple_Resize(&tuple,n)!=0) {
    Py_DECREF(tuple);
    return NULL;
  }

  return tuple;
}
void plPythonSDLModifier::SetItemIdx(const char* key, int idx, PyObject* value, hsBool sendImmediate)
{
    if (!value)
    {
        PyLoggedAssert(0, "[SDL] Trying to set a value to nil");
        return;
    }

    SDLMap::iterator it = fMap.find(key);

    if (it == fMap.end())
    {
        PyLoggedAssert(0, "[SDL] Tried to set a nonexistent SDL value");
        return;
    }

    PyObject* pyTuple = it->second.obj;
    int size = it->second.size;

    if (size != 0 && idx >= size)
    {
        PyLoggedAssert(0, "[SDL] Trying to resize a SDL value that can't be");
        return;
    }

    if (pyTuple && pyTuple->ob_refcnt != 1)
    {
        // others already have references to the tuple and expect it to be immutable, must make a copy
        int n = PyTuple_Size(pyTuple);
        PyObject* newTuple = PyTuple_New(n);
        for (int j = 0; j < n; j++)
        {
            PyObject* item = PyTuple_GetItem(pyTuple, j);
            Py_INCREF(item);
            PyTuple_SetItem(newTuple, j, item);
        }
        Py_DECREF(pyTuple);
        pyTuple = newTuple;
        it->second.obj = newTuple;
    }

    if (pyTuple)
    {
        if (PyTuple_Size(pyTuple) <= idx)
        {
            int oldsize = PyTuple_Size(pyTuple);
            _PyTuple_Resize(&pyTuple, idx+1);
            // initialize the tuple elements to None, because Python don't like NULLs
            int j;
            for ( j=oldsize; j<idx+1; j++ )
            {
                Py_INCREF(Py_None);
                PyTuple_SetItem(pyTuple, j, Py_None);
            }
            // _PyTuple_Resize may have changed pyTuple
            it->second.obj = pyTuple;
        }
    }
    else
    {
        int newSize = (size == 0) ? idx+1 : size;
        pyTuple = PyTuple_New(newSize);
        // initialize the tuple elements to None, because Python don't like NULLs
        int j;
        for ( j=0; j<newSize; j++ )
        {
            Py_INCREF(Py_None);
            PyTuple_SetItem(pyTuple, j, Py_None);
        }
        it->second.obj = pyTuple;
    }

    Py_XINCREF(value);  // PyTuple_SetItem doesn't increment the ref count
    PyTuple_SetItem(pyTuple, idx, value);

    IDirtySynchState(key, sendImmediate);
}
Esempio n. 14
0
static PyObject *
internal_parse_depset(PyObject *dep_str, char **ptr, int *has_conditionals,
	PyObject *element_func,
	PyObject *and_func, PyObject *or_func,
	PyObject *parent_func,
	char initial_frame)
{
	char *start = *ptr;
	char *p = NULL;
	PyObject *restrictions = NULL;
	PyObject *item = NULL;
	PyObject *tmp = NULL;

	// should just use alloca here.

	#define PARSE_DEPSET_STACK_STORAGE 16
	PyObject *stack_restricts[PARSE_DEPSET_STACK_STORAGE];
	Py_ssize_t item_count = 0, tup_size = PARSE_DEPSET_STACK_STORAGE;
	Py_ssize_t item_size = 1;

	SKIP_SPACES(start);
	p = start;
	while('\0' != *start) {
		start = p;
		SKIP_NONSPACES(p);
		if('(' == *start) {
			// new and frame.
			if(!and_func) {
				Err_SetParse(dep_str, "this depset doesn't support and blocks",
				start, p);
				goto internal_parse_depset_error;
			}
			if(p - start != 1) {
				Err_SetParse(dep_str,
					"either a space or end of string is required after (",
					start, p);
				goto internal_parse_depset_error;
			}
			if(!(tmp = internal_parse_depset(dep_str, &p, has_conditionals,
				element_func, and_func, or_func, and_func, 0)))
				goto internal_parse_depset_error;

			if(tmp == Py_None) {
				Py_DECREF(tmp);
				Err_SetParse(dep_str, "empty payload", start, p);
				goto internal_parse_depset_error;
			} else if(!PyTuple_CheckExact(tmp)) {
				item = tmp;
			} else {
				item = PyObject_CallObject(and_func, tmp);
				Py_DECREF(tmp);
				if(!item)
					goto internal_parse_depset_error;
			}

		} else if(')' == *start) {
			// end of a frame
			if(initial_frame) {
				Err_SetParse(dep_str, ") found without matching (",
					NULL, NULL);
				goto internal_parse_depset_error;
			}
			if(p - start != 1) {
				Err_SetParse(dep_str,
					"either a space or end of string is required after )",
					start, p);
				goto internal_parse_depset_error;
			}

			if(!*p)
				p--;
			break;

		} else if('?' == p[-1]) {
			// use conditional
			if (p - start == 1 || ('!' == *start && p - start == 2)) {
				Err_SetParse(dep_str, "empty use conditional", start, p);
				goto internal_parse_depset_error;
			}
			char *conditional_end = p - 1;
			SKIP_SPACES(p);
			if ('(' != *p) {
				Err_SetParse(dep_str,
					"( has to be the next token for a conditional",
					start, p);
				goto internal_parse_depset_error;
			} else if(!isspace(*(p + 1)) || '\0' == p[1]) {
				Err_SetParse(dep_str,
					"( has to be followed by whitespace",
					start, p);
				goto internal_parse_depset_error;
			}
			p++;
			if(!(tmp = internal_parse_depset(dep_str, &p, has_conditionals,
				element_func, and_func, or_func, NULL, 0)))
				goto internal_parse_depset_error;

			if(tmp == Py_None) {
				Py_DECREF(tmp);
				Err_SetParse(dep_str, "empty payload", start, p);
				goto internal_parse_depset_error;

			} else if(!PyTuple_CheckExact(tmp)) {
				item = PyTuple_New(1);
				if(!tmp) {
					Py_DECREF(item);
					goto internal_parse_depset_error;
				}
				PyTuple_SET_ITEM(item, 0, tmp);
				tmp = item;
			}
			item = make_use_conditional(start, conditional_end, tmp);
			Py_DECREF(tmp);
			if(!item)
				goto internal_parse_depset_error;
			*has_conditionals = 1;

		} else if ('|' == *start) {
			if('|' != start[1] || !or_func) {
				Err_SetParse(dep_str,
					"stray |, or this depset doesn't support or blocks",
					NULL, NULL);
				goto internal_parse_depset_error;
			}

			if(p - start != 2) {
				Err_SetParse(dep_str, "|| must have space followed by a (",
					start, p);
				goto internal_parse_depset_error;
			}
			SKIP_SPACES(p);
			if ('(' != *p || (!isspace(*(p + 1)) && '\0' != p[1])) {
				Err_SetParse(dep_str,
					"( has to be the next token for a conditional",
					start, p);
				goto internal_parse_depset_error;
			}
			p++;
			if(!(tmp = internal_parse_depset(dep_str, &p, has_conditionals,
				element_func, and_func, or_func, NULL, 0)))
				goto internal_parse_depset_error;

			if(tmp == Py_None) {
				Py_DECREF(tmp);
				Err_SetParse(dep_str, "empty payload", start, p);
				goto internal_parse_depset_error;
			} else if (!PyTuple_CheckExact(tmp)) {
				item = tmp;
			} else {
				item = PyObject_CallObject(or_func, tmp);
				Py_DECREF(tmp);
				if(!item)
					goto internal_parse_depset_error;
			}
		} else {
			item = PyObject_CallFunction(element_func, "s#", start, p - start);
			if(!item) {
				Err_WrapException(dep_str, start, p);
				goto internal_parse_depset_error;
			}
			assert(!PyErr_Occurred());
		}

		// append it.
		if(item_count + item_size > tup_size) {
			while(tup_size < item_count + item_size)
				tup_size <<= 1;
			if(!restrictions) {
				// switch over.
				if(!(restrictions = PyTuple_New(tup_size))) {
					Py_DECREF(item);
					goto internal_parse_depset_error;
				}
				Py_ssize_t x = 0;
				for(; x < item_count; x++) {
					PyTuple_SET_ITEM(restrictions, x,
						stack_restricts[x]);
				}
			} else if(_PyTuple_Resize(&restrictions, tup_size)) {
				Py_DECREF(item);
				goto internal_parse_depset_error;
			}
			// now we're using restrictions.
		}
		if(restrictions) {
			if(item_size == 1) {
				PyTuple_SET_ITEM(restrictions, item_count++, item);
			} else {
				Py_ssize_t x = 0;
				for(; x < item_size; x++) {
					Py_INCREF(PyTuple_GET_ITEM(item, x));
					PyTuple_SET_ITEM(restrictions, item_count + x,
						PyTuple_GET_ITEM(item, x));
				}
				item_count += x;
				item_size = 1;
				// we're done with the tuple, already stole the items from it.
				Py_DECREF(item);
			}
		} else {
			if(item_size == 1) {
				stack_restricts[item_count++] = item;
			} else {
				Py_ssize_t x = 0;
				for(;x < item_size; x++) {
					Py_INCREF(PyTuple_GET_ITEM(item, x));
					stack_restricts[item_count + x] = PyTuple_GET_ITEM(item, x);
				}
				item_count += item_size;
				item_size = 1;
				// we're done with the tuple, already stole the items from it.
				Py_DECREF(item);
			}
		}
		SKIP_SPACES(p);
		start = p;
	}

	if(initial_frame) {
		if(*p) {
			Err_SetParse(dep_str, "stray ')' encountered", start, p);
			goto internal_parse_depset_error;
		}
	} else {
		if('\0' == *p) {
			Err_SetParse(dep_str, "depset lacks closure", *ptr, p);
			goto internal_parse_depset_error;
		}
		p++;
	}

	if(!restrictions) {
		if(item_count == 0) {
			restrictions = Py_None;
			Py_INCREF(restrictions);
		} else if(item_count == 1) {
			restrictions = stack_restricts[0];
		} else {
			restrictions = PyTuple_New(item_count);
			if(!restrictions)
				goto internal_parse_depset_error;
			Py_ssize_t x =0;
			for(;x < item_count; x++) {
				PyTuple_SET_ITEM(restrictions, x,
					stack_restricts[x]);
			}
		}
	} else if(item_count < tup_size) {
		if(_PyTuple_Resize(&restrictions, item_count))
			goto internal_parse_depset_error;
	}
	*ptr = p;
	return restrictions;

	internal_parse_depset_error:
	if(item_count) {
		if(!restrictions) {
			item_count--;
			while(item_count >= 0) {
				Py_DECREF(stack_restricts[item_count]);
				item_count--;
			}
		} else
			Py_DECREF(restrictions);
	}
	// dealloc.
	return NULL;
}