static char *
get_exc_trace()
{
    char *tbstr = NULL; 

    PyObject *iostrmod = NULL;
    PyObject *tbmod = NULL;
    PyObject *iostr = NULL;
    PyObject *obstr = NULL;
    PyObject *args = NULL;
    PyObject *newstr = NULL;
    PyObject *func = NULL;
    char* rv = NULL; 

    PyObject *type, *value, *traceback;
    TARGET_THREAD_BEGIN_BLOCK; 
    PyErr_Fetch(&type, &value, &traceback);
    debug("** type %p, value %p, traceback %p", type, value, traceback); 
    PyErr_Print(); 
    PyErr_Clear(); 
    PyErr_NormalizeException(&type, &value, &traceback);
    debug("** type %p, value %p, traceback %p", type, value, traceback); 

    iostrmod = PyImport_ImportModule("StringIO");
    if (iostrmod==NULL)
        TB_ERROR("can't import StringIO");

    iostr = PyObject_CallMethod(iostrmod, "StringIO", NULL);

    if (iostr==NULL)
        TB_ERROR("cStringIO.StringIO() failed");

    tbmod = PyImport_ImportModule("traceback");
    if (tbmod==NULL)
        TB_ERROR("can't import traceback");

    obstr = PyObject_CallMethod(tbmod, "print_exception",
        "(OOOOO)",
        type ? type : Py_None, 
        value ? value : Py_None,
        traceback ? traceback : Py_None,
        Py_None,
        iostr);

    if (obstr==NULL) 
    {
        PyErr_Print(); 
        TB_ERROR("traceback.print_exception() failed");
    }

    Py_DecRef(obstr);

    obstr = PyObject_CallMethod(iostr, "getvalue", NULL);
    if (obstr==NULL) 
        TB_ERROR("getvalue() failed.");

    if (!PyString_Check(obstr))
        TB_ERROR("getvalue() did not return a string");

    debug("%s", PyString_AsString(obstr)); 
    args = PyTuple_New(2);
    PyTuple_SetItem(args, 0, string2target("\n")); 
    PyTuple_SetItem(args, 1, string2target("<br>")); 
    
    func = PyObject_GetAttrString(obstr, "replace"); 
    //newstr = PyObject_CallMethod(obstr, "replace", args); 
    newstr = PyObject_CallObject(func, args); 

    tbstr = PyString_AsString(newstr); 

    rv = fmtstr("plugin:%s", tbstr); 

cleanup:
    PyErr_Restore(type, value, traceback);

    if (rv == NULL)
    {
        rv = tbstr ? tbstr : "";
    }

    Py_DecRef(func);
    Py_DecRef(args);
    Py_DecRef(newstr);
    Py_DecRef(iostr);
    Py_DecRef(obstr);
    Py_DecRef(iostrmod);
    Py_DecRef(tbmod);


    TARGET_THREAD_END_BLOCK; 
    return rv;
}
static int 
TargetCall(WsXmlDocH doc, PyObject* instance, 
                 const char* opname, int nargs, ...)
{
    va_list vargs; 
    PyObject *pyargs = NULL; 
    PyObject *pyfunc = NULL; 
    PyObject *result = NULL; 
    WsmanStatus status;
    wsman_status_init(&status);

    pyargs = PyTuple_New(nargs); 
    pyfunc = PyObject_GetAttrString(instance, opname); 
    if (pyfunc == NULL)
    {
        PyErr_Print(); 
        PyErr_Clear(); 
        char* str = fmtstr("Python module does not contain \"%s\"", opname); 
        debug("%s", str); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;

        free(str); 
        goto cleanup; 
    }
    if (! PyCallable_Check(pyfunc))
    {
        char* str = fmtstr("Python module attribute \"%s\" is not callable", 
                opname); 
        debug("%s", str); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        free(str); 
        goto cleanup; 
    }
    
    va_start(vargs, nargs); 
    int i; 
    for (i = 0; i < nargs; ++i)
    {
        PyObject* arg = va_arg(vargs, PyObject*); 
        if (arg == NULL)
        {
            arg = Py_None; 
            Py_IncRef(arg); 
        }
        PyTuple_SET_ITEM(pyargs, i, arg); 
    }
    va_end(vargs); 
    result = PyObject_CallObject(pyfunc, pyargs);
    if (PyErr_Occurred())
    {
        status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        PyErr_Clear(); 
        goto cleanup; 
    }

    if (! PyTuple_Check(result) || 
            (PyTuple_Size(result) != 2 && PyTuple_Size(result) != 1))
    {
        TARGET_THREAD_BEGIN_ALLOW;
        status.fault_msg = fmtstr("Python function \"%s\" didn't return a two-tuple", opname); 
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
    }
    PyObject* code = PyTuple_GetItem(result, 0);
    PyObject* detail = Py_None; 
    if (PyTuple_Size(result) == 2)
    {
        detail = PyTuple_GetItem(result, 1); 
    }

    if (! PyInt_Check(code) || (! PyInt_Check(detail) && detail != Py_None))
    {
        TARGET_THREAD_BEGIN_ALLOW;
        status.fault_msg = fmtstr("Python function \"%s\" didn't return a {<int>, <int>) two-tuple", opname); 
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
    }
    status.fault_code = PyInt_AsLong(code); 
    if (detail == Py_None)
    {
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
    }
    else
    {
        status.fault_detail_code = PyInt_AsLong(detail);
    }
cleanup:
    if (status.fault_code != WSMAN_RC_OK)
      wsman_generate_fault( doc, status.fault_code, status.fault_detail_code, status.fault_msg );
    Py_DecRef(pyargs);
    Py_DecRef(pyfunc);
    Py_DecRef(result);
 
    return status.fault_code != WSMAN_RC_OK; 
}
static list_t *
TargetEndpoints( void *self, void *data )
{
    int len, i;
    PyObject *instance = (PyObject *)data;
    PyObject *pyfunc, *pynamespaces = NULL;
    WsmanStatus status;
    wsman_status_init(&status);
    debug("TargetEndpoints(Python), data %p, instance %p", data, instance);

    /*
     * Get namespaces
     */
  
    list_t *namespaces = list_create(LISTCOUNT_T_MAX);

    pyfunc = PyObject_GetAttrString(instance, "namespaces"); 
    if (pyfunc == NULL)
    {
        PyErr_Print(); 
        PyErr_Clear(); 
        debug("Python module does not contain \"namespaces\""); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        goto cleanup; 
    }
    if (! PyCallable_Check(pyfunc))
    {
        debug("Python module attribute \"namespaces\" is not callable"); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        goto cleanup; 
    }
    pynamespaces = PyObject_CallObject(pyfunc, NULL);
    if (PyErr_Occurred())
    {
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        PyErr_Clear();
        goto cleanup; 
    }

    if (! PyTuple_Check(pynamespaces))
    {
        TARGET_THREAD_BEGIN_ALLOW;
        debug("Python function \"namespaces\" didn't return a two-tuple"); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
    }

    len = PyTuple_Size(pynamespaces);

    for (i = 0; i < len; ++i) {
      lnode_t *node;
      PyObject *ns, *prefix;
      PyObject* elem = PyTuple_GetItem(pynamespaces, i);
      if (! PyTuple_Check(elem)
	  || ! (PyTuple_Size(elem) == 2)) {
        TARGET_THREAD_BEGIN_ALLOW;
        debug("Python function \"namespaces\" didn't return a list of two-tuple");
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
      }
      ns = PyTuple_GetItem(elem, 0);
      prefix = PyTuple_GetItem(elem, 1);
      if (!PyString_Check(ns)
	  || !PyString_Check(prefix)) {
        TARGET_THREAD_BEGIN_ALLOW;
        debug("Python function \"namespaces\" didn't return a list of [<string>,<string>] tuples");
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
      }
      
      WsSupportedNamespaces *sup_ns = (WsSupportedNamespaces *)u_malloc(sizeof(WsSupportedNamespaces));
      sup_ns->ns = PyString_AsString(ns);
      sup_ns->class_prefix = PyString_AsString(prefix);
      node = lnode_create(ns);
      list_append(namespaces, node);
    }
cleanup:
    if (pyfunc) Py_DecRef(pyfunc);
    if (pynamespaces) Py_DecRef(pynamespaces);
  
    return namespaces;
}
Exemple #4
0
/* Frees a key protector object
 */
void pybde_key_protector_free(
      pybde_key_protector_t *pybde_key_protector )
{
	libcerror_error_t *error = NULL;
	static char *function    = "pybde_key_protector_free";

	if( pybde_key_protector == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid key protector.",
		 function );

		return;
	}
	if( pybde_key_protector->ob_type == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid key protector - missing ob_type.",
		 function );

		return;
	}
	if( pybde_key_protector->ob_type->tp_free == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid key protector - invalid ob_type - missing tp_free.",
		 function );

		return;
	}
	if( pybde_key_protector->key_protector == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid key protector - missing libbde key protector.",
		 function );

		return;
	}
	if( libbde_key_protector_free(
	     &( pybde_key_protector->key_protector ),
	     &error ) != 1 )
	{
		pybde_error_raise(
		 error,
		 PyExc_IOError,
		 "%s: unable to free libbde key protector.",
		 function );

		libcerror_error_free(
		 &error );
	}
	if( pybde_key_protector->volume_object != NULL )
	{
		Py_DecRef(
		 (PyObject *) pybde_key_protector->volume_object );
	}
	pybde_key_protector->ob_type->tp_free(
	 (PyObject*) pybde_key_protector );
}
/* Creates a new records object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyevt_records_new(
           pyevt_file_t *file_object,
           PyObject* (*get_record_by_index)(
                        pyevt_file_t *file_object,
                        int record_index ),
           int number_of_records )
{
	pyevt_records_t *pyevt_records = NULL;
	static char *function          = "pyevt_records_new";

	if( file_object == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid file object.",
		 function );

		return( NULL );
	}
	if( get_record_by_index == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid get record by index function.",
		 function );

		return( NULL );
	}
	/* Make sure the records values are initialized
	 */
	pyevt_records = PyObject_New(
	                 struct pyevt_records,
	                 &pyevt_records_type_object );

	if( pyevt_records == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize records.",
		 function );

		goto on_error;
	}
	if( pyevt_records_init(
	     pyevt_records ) != 0 )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize records.",
		 function );

		goto on_error;
	}
	pyevt_records->file_object         = file_object;
	pyevt_records->get_record_by_index = get_record_by_index;
	pyevt_records->number_of_records   = number_of_records;

	Py_IncRef(
	 (PyObject *) pyevt_records->file_object );

	return( (PyObject *) pyevt_records );

on_error:
	if( pyevt_records != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyevt_records );
	}
	return( NULL );
}
/* Creates a new logical volumes object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyvslvm_logical_volumes_new(
           pyvslvm_volume_group_t *volume_group_object,
           PyObject* (*get_logical_volume_by_index)(
                        pyvslvm_volume_group_t *volume_group_object,
                        int logical_volume_index ),
           int number_of_logical_volumes )
{
	pyvslvm_logical_volumes_t *pyvslvm_logical_volumes = NULL;
	static char *function                              = "pyvslvm_logical_volumes_new";

	if( volume_group_object == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid volume group object.",
		 function );

		return( NULL );
	}
	if( get_logical_volume_by_index == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid get logical volume by index function.",
		 function );

		return( NULL );
	}
	/* Make sure the logical volumes values are initialized
	 */
	pyvslvm_logical_volumes = PyObject_New(
	                           struct pyvslvm_logical_volumes,
	                           &pyvslvm_logical_volumes_type_object );

	if( pyvslvm_logical_volumes == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize logical volumes.",
		 function );

		goto on_error;
	}
	if( pyvslvm_logical_volumes_init(
	     pyvslvm_logical_volumes ) != 0 )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize logical volumes.",
		 function );

		goto on_error;
	}
	pyvslvm_logical_volumes->volume_group_object         = volume_group_object;
	pyvslvm_logical_volumes->get_logical_volume_by_index = get_logical_volume_by_index;
	pyvslvm_logical_volumes->number_of_logical_volumes   = number_of_logical_volumes;

	Py_IncRef(
	 (PyObject *) pyvslvm_logical_volumes->volume_group_object );

	return( (PyObject *) pyvslvm_logical_volumes );

on_error:
	if( pyvslvm_logical_volumes != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyvslvm_logical_volumes );
	}
	return( NULL );
}
/* Initializes the type object
 * Returns 1 if successful or -1 on error
 */
int pylnk_data_flags_init_type(
     PyTypeObject *type_object )
{
	PyObject *value_object = NULL;

	if( type_object == NULL )
	{
		return( -1 );
	}
	type_object->tp_dict = PyDict_New();

	if( type_object->tp_dict == NULL )
	{
		return( -1 );
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_HAS_LINK_TARGET_IDENTIFIER );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_HAS_LINK_TARGET_IDENTIFIER );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "HAS_LINK_TARGET_IDENTIFIER",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_HAS_LOCATION_INFORMATION );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_HAS_LOCATION_INFORMATION );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "HAS_LOCATION_INFORMATION",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_HAS_DESCRIPTION_STRING );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_HAS_DESCRIPTION_STRING );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "HAS_DESCRIPTION_STRING",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_HAS_RELATIVE_PATH_STRING );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_HAS_RELATIVE_PATH_STRING );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "HAS_RELATIVE_PATH_STRING",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_HAS_WORKING_DIRECTORY_STRING );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_HAS_WORKING_DIRECTORY_STRING );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "HAS_WORKING_DIRECTORY_STRING",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_HAS_COMMAND_LINE_ARGUMENTS_STRING );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_HAS_COMMAND_LINE_ARGUMENTS_STRING );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "HAS_COMMAND_LINE_ARGUMENTS_STRING",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_HAS_ICON_LOCATION_STRING );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_HAS_ICON_LOCATION_STRING );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "HAS_ICON_LOCATION_STRING",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_IS_UNICODE );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_IS_UNICODE );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "IS_UNICODE",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_FORCE_NO_LOCATION_INFORMATION );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_FORCE_NO_LOCATION_INFORMATION );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "FORCE_NO_LOCATION_INFORMATION",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_HAS_ENVIRONMENT_VARIABLES_LOCATION_BLOCK );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_HAS_ENVIRONMENT_VARIABLES_LOCATION_BLOCK );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "HAS_ENVIRONMENT_VARIABLES_LOCATION_BLOCK",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_RUN_IN_SEPARATE_PROCESS );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_RUN_IN_SEPARATE_PROCESS );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "RUN_IN_SEPARATE_PROCESS",
	     value_object ) != 0 )
	{
		goto on_error;
	}

#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_HAS_DARWIN_IDENTIFIER );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_HAS_DARWIN_IDENTIFIER );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "HAS_DARWIN_IDENTIFIER",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_RUN_AS_USER );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_RUN_AS_USER );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "RUN_AS_USER",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_HAS_ICON_LOCATION_BLOCK );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_HAS_ICON_LOCATION_BLOCK );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "HAS_ICON_LOCATION_BLOCK",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_NO_PIDL_ALIAS );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_NO_PIDL_ALIAS );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "NO_PIDL_ALIAS",
	     value_object ) != 0 )
	{
		goto on_error;
	}

#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_RUN_WITH_SHIM_LAYER );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_RUN_WITH_SHIM_LAYER );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "RUN_WITH_SHIM_LAYER",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_NO_DISTRIBUTED_LINK_TRACKING_DATA_BLOCK );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_NO_DISTRIBUTED_LINK_TRACKING_DATA_BLOCK );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "NO_DISTRIBUTED_LINK_TRACKING_DATA_BLOCK",
	     value_object ) != 0 )
	{
		goto on_error;
	}
#if PY_MAJOR_VERSION >= 3
	value_object = PyLong_FromLong(
	                LIBLNK_DATA_FLAG_HAS_METADATA_PROPERTY_STORE_DATA_BLOCK );
#else
	value_object = PyInt_FromLong(
	                LIBLNK_DATA_FLAG_HAS_METADATA_PROPERTY_STORE_DATA_BLOCK );
#endif
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "HAS_METADATA_PROPERTY_STORE_DATA_BLOCK",
	     value_object ) != 0 )
	{
		goto on_error;
	}
	return( 1 );

on_error:
	if( type_object->tp_dict != NULL )
	{
		Py_DecRef(
		 type_object->tp_dict );

		type_object->tp_dict = NULL;
	}
	return( -1 );
}
Exemple #8
0
PythonContext::PythonContext(QObject *parent) : QObject(parent)
{
  if(!initialised())
    return;

  // acquire the GIL and make sure this thread is init'd
  PyGILState_STATE gil = PyGILState_Ensure();

  // clone our own local context
  context_namespace = PyDict_Copy(main_dict);

  PyObject *rlcompleter = PyDict_GetItemString(main_dict, "rlcompleter");

  // for compatibility with earlier versions of python that took a char * instead of const char *
  char noparams[1] = "";

  // set global output that point to this context. It is responsible for deleting the context when
  // it goes out of scope
  PyObject *redirector = PyObject_CallFunction((PyObject *)&OutputRedirectorType, noparams);
  if(redirector)
  {
    PyDict_SetItemString(context_namespace, "_renderdoc_internal", redirector);

    OutputRedirector *output = (OutputRedirector *)redirector;
    output->context = this;
    Py_DECREF(redirector);
  }

  if(rlcompleter)
  {
    PyObject *Completer = PyObject_GetAttrString(rlcompleter, "Completer");

    if(Completer)
    {
      // create a completer for our context's namespace
      m_Completer = PyObject_CallFunction(Completer, "O", context_namespace);

      if(m_Completer)
      {
        PyDict_SetItemString(context_namespace, "_renderdoc_completer", m_Completer);
      }
      else
      {
        QString typeStr;
        QString valueStr;
        int finalLine = -1;
        QList<QString> frames;
        FetchException(typeStr, valueStr, finalLine, frames);

        // failure is not fatal
        qWarning() << "Couldn't create completion object. " << typeStr << ": " << valueStr;
        PyErr_Clear();
      }
    }

    Py_DecRef(Completer);
  }
  else
  {
    m_Completer = NULL;
  }

  // release the GIL again
  PyGILState_Release(gil);

  // every 100ms while running, check for new output
  outputTicker = new QTimer(this);
  outputTicker->setInterval(100);
  QObject::connect(outputTicker, &QTimer::timeout, this, &PythonContext::outputTick);

  // we have to start it here, because we can't start on another thread.
  outputTicker->start();
}
Exemple #9
0
void PythonContext::executeString(const QString &filename, const QString &source)
{
  if(!initialised())
  {
    emit exception(
        lit("SystemError"),
        tr("Python integration failed to initialise, see diagnostic log for more information."), -1,
        {});
    return;
  }

  location.file = filename;
  location.line = 1;

  PyGILState_STATE gil = PyGILState_Ensure();

  PyObject *compiled =
      Py_CompileString(source.toUtf8().data(), filename.toUtf8().data(),
                       source.count(QLatin1Char('\n')) == 0 ? Py_single_input : Py_file_input);

  PyObject *ret = NULL;

  if(compiled)
  {
    PyObject *traceContext = PyDict_New();

    uintptr_t thisint = (uintptr_t) this;
    uint64_t thisuint64 = (uint64_t)thisint;
    PyObject *thisobj = PyLong_FromUnsignedLongLong(thisuint64);

    PyDict_SetItemString(traceContext, "thisobj", thisobj);
    PyDict_SetItemString(traceContext, "compiled", compiled);

    PyEval_SetTrace(&PythonContext::traceEvent, traceContext);

    m_Abort = false;

    m_State = PyGILState_GetThisThreadState();

    ret = PyEval_EvalCode(compiled, context_namespace, context_namespace);

    m_State = NULL;

    // catch any output
    outputTick();

    PyEval_SetTrace(NULL, NULL);

    Py_XDECREF(thisobj);
    Py_XDECREF(traceContext);
  }

  Py_DecRef(compiled);

  QString typeStr;
  QString valueStr;
  int finalLine = -1;
  QList<QString> frames;
  bool caughtException = (ret == NULL);

  if(caughtException)
    FetchException(typeStr, valueStr, finalLine, frames);

  Py_XDECREF(ret);

  PyGILState_Release(gil);

  if(caughtException)
    emit exception(typeStr, valueStr, finalLine, frames);
}
Exemple #10
0
void FetchException(QString &typeStr, QString &valueStr, int &finalLine, QList<QString> &frames)
{
  PyObject *exObj = NULL, *valueObj = NULL, *tracebackObj = NULL;

  PyErr_Fetch(&exObj, &valueObj, &tracebackObj);

  PyErr_NormalizeException(&exObj, &valueObj, &tracebackObj);

  if(exObj && PyType_Check(exObj))
  {
    PyTypeObject *type = (PyTypeObject *)exObj;

    typeStr = QString::fromUtf8(type->tp_name);
  }
  else
  {
    typeStr = QString();
  }

  if(valueObj)
    valueStr = ToQStr(valueObj);

  if(tracebackObj)
  {
    PyObject *tracebackModule = PyImport_ImportModule("traceback");

    if(tracebackModule)
    {
      PyObject *func = PyObject_GetAttrString(tracebackModule, "format_tb");

      if(func && PyCallable_Check(func))
      {
        PyObject *args = Py_BuildValue("(N)", tracebackObj);
        PyObject *formattedTB = PyObject_CallObject(func, args);

        PyTracebackObject *tb = (PyTracebackObject *)tracebackObj;

        while(tb->tb_next)
          tb = tb->tb_next;

        finalLine = tb->tb_lineno;

        if(formattedTB)
        {
          Py_ssize_t size = PyList_Size(formattedTB);
          for(Py_ssize_t i = 0; i < size; i++)
          {
            PyObject *el = PyList_GetItem(formattedTB, i);

            frames << ToQStr(el).trimmed();
          }

          Py_DecRef(formattedTB);
        }

        Py_DecRef(args);
      }
    }
  }

  Py_DecRef(exObj);
  Py_DecRef(valueObj);
  Py_DecRef(tracebackObj);
}
Exemple #11
0
void PythonContext::GlobalInit()
{
  // must happen on the UI thread
  if(qApp->thread() != QThread::currentThread())
  {
    qFatal("PythonContext::GlobalInit MUST be called from the UI thread");
    return;
  }

  // for the exception signal
  qRegisterMetaType<QList<QString>>("QList<QString>");

  PyImport_AppendInittab("_renderdoc", &PyInit_renderdoc);
  PyImport_AppendInittab("_qrenderdoc", &PyInit_qrenderdoc);

#if defined(STATIC_QRENDERDOC)
  // add the location where our libs will be for statically-linked python installs
  {
    QDir bin = QFileInfo(QCoreApplication::applicationFilePath()).absoluteDir();

    QString pylibs = QDir::cleanPath(bin.absoluteFilePath(lit("../share/renderdoc/pylibs")));

    pylibs.toWCharArray(python_home);

    Py_SetPythonHome(python_home);
  }
#endif

  Py_SetProgramName(program_name);

  Py_Initialize();

  PyEval_InitThreads();

  OutputRedirectorType.tp_name = "renderdoc_output_redirector";
  OutputRedirectorType.tp_basicsize = sizeof(OutputRedirector);
  OutputRedirectorType.tp_flags = Py_TPFLAGS_DEFAULT;
  OutputRedirectorType.tp_doc =
      "Output redirector, to be able to catch output to stdout and stderr";
  OutputRedirectorType.tp_new = PyType_GenericNew;
  OutputRedirectorType.tp_dealloc = &PythonContext::outstream_del;
  OutputRedirectorType.tp_methods = OutputRedirector_methods;

  OutputRedirector_methods[0].ml_meth = &PythonContext::outstream_write;
  OutputRedirector_methods[1].ml_meth = &PythonContext::outstream_flush;

  PyObject *main_module = PyImport_AddModule("__main__");

  PyModule_AddObject(main_module, "renderdoc", PyImport_ImportModule("_renderdoc"));
  PyModule_AddObject(main_module, "qrenderdoc", PyImport_ImportModule("_qrenderdoc"));

  main_dict = PyModule_GetDict(main_module);

  // replace sys.stdout and sys.stderr with our own objects. These have a 'this' pointer of NULL,
  // which then indicates they need to forward to a global object

  // import sys
  PyDict_SetItemString(main_dict, "sys", PyImport_ImportModule("sys"));

  PyObject *rlcompleter = PyImport_ImportModule("rlcompleter");

  if(rlcompleter)
  {
    PyDict_SetItemString(main_dict, "rlcompleter", rlcompleter);
  }
  else
  {
    // ignore a failed import
    PyErr_Clear();
  }

  // sysobj = sys
  PyObject *sysobj = PyDict_GetItemString(main_dict, "sys");

  // sysobj.stdout = renderdoc_output_redirector()
  // sysobj.stderr = renderdoc_output_redirector()
  if(PyType_Ready(&OutputRedirectorType) >= 0)
  {
    // for compatibility with earlier versions of python that took a char * instead of const char *
    char noparams[1] = "";

    PyObject *redirector = PyObject_CallFunction((PyObject *)&OutputRedirectorType, noparams);
    PyObject_SetAttrString(sysobj, "stdout", redirector);

    OutputRedirector *output = (OutputRedirector *)redirector;
    output->isStdError = 0;
    output->context = NULL;

    redirector = PyObject_CallFunction((PyObject *)&OutputRedirectorType, noparams);
    PyObject_SetAttrString(sysobj, "stderr", redirector);

    output = (OutputRedirector *)redirector;
    output->isStdError = 1;
    output->context = NULL;
  }

// if we need to append to sys.path to locate PySide2, do that now
#if defined(PYSIDE2_SYS_PATH)
  {
    PyObject *syspath = PyObject_GetAttrString(sysobj, "path");

#ifndef STRINGIZE
#define STRINGIZE2(a) #a
#define STRINGIZE(a) STRINGIZE2(a)
#endif

    PyObject *str = PyUnicode_FromString(STRINGIZE(PYSIDE2_SYS_PATH));

    PyList_Append(syspath, str);

    Py_DecRef(str);
    Py_DecRef(syspath);
  }
#endif

// set up PySide
#if PYSIDE2_ENABLED
  {
    Shiboken::AutoDecRef core(Shiboken::Module::import("PySide2.QtCore"));
    if(!core.isNull())
      SbkPySide2_QtCoreTypes = Shiboken::Module::getTypes(core);
    else
      qCritical() << "Failed to load PySide2.QtCore";

    Shiboken::AutoDecRef gui(Shiboken::Module::import("PySide2.QtGui"));
    if(!gui.isNull())
      SbkPySide2_QtGuiTypes = Shiboken::Module::getTypes(gui);
    else
      qCritical() << "Failed to load PySide2.QtGui";

    Shiboken::AutoDecRef widgets(Shiboken::Module::import("PySide2.QtWidgets"));
    if(!widgets.isNull())
      SbkPySide2_QtWidgetsTypes = Shiboken::Module::getTypes(widgets);
    else
      qCritical() << "Failed to load PySide2.QtWidgets";
  }
#endif

  // release GIL so that python work can now happen on any thread
  PyEval_SaveThread();
}
/* Frees an block object
 */
void pyvshadow_block_free(
      pyvshadow_block_t *pyvshadow_block )
{
	libcerror_error_t *error    = NULL;
	struct _typeobject *ob_type = NULL;
	static char *function       = "pyvshadow_block_free";

	if( pyvshadow_block == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid block.",
		 function );

		return;
	}
	if( pyvshadow_block->block == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid block - missing libvshadow block.",
		 function );

		return;
	}
	ob_type = Py_TYPE(
	           pyvshadow_block );

	if( ob_type == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: missing ob_type.",
		 function );

		return;
	}
	if( ob_type->tp_free == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid ob_type - missing tp_free.",
		 function );

		return;
	}
	if( libvshadow_block_free(
	     &( pyvshadow_block->block ),
	     &error ) != 1 )
	{
		pyvshadow_error_raise(
		 error,
		 PyExc_IOError,
		 "%s: unable to free libvshadow block.",
		 function );

		libcerror_error_free(
		 &error );
	}
	if( pyvshadow_block->store_object != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyvshadow_block->store_object );
	}
	ob_type->tp_free(
	 (PyObject*) pyvshadow_block );
}
Exemple #13
0
/* Initializes the type object
 * Returns 1 if successful or -1 on error
 */
int pyewf_media_types_init_type(
     PyTypeObject *type_object )
{
	if( type_object == NULL )
	{
		return( -1 );
	}
	type_object->tp_dict = PyDict_New();

	if( type_object->tp_dict == NULL )
	{
		return( -1 );
	}
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "REMOVABLE",
	     PyInt_FromLong(
	      LIBEWF_MEDIA_TYPE_REMOVABLE ) ) != 0 )
	{
		goto on_error;
	}
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "FIXED",
	     PyInt_FromLong(
	      LIBEWF_MEDIA_TYPE_FIXED ) ) != 0 )
	{
		goto on_error;
	}
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "OPTICAL",
	     PyInt_FromLong(
	      LIBEWF_MEDIA_TYPE_OPTICAL ) ) != 0 )
	{
		goto on_error;
	}
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "SINGLE_FILES",
	     PyInt_FromLong(
	      LIBEWF_MEDIA_TYPE_SINGLE_FILES ) ) != 0 )
	{
		goto on_error;
	}
	if( PyDict_SetItemString(
	     type_object->tp_dict,
	     "MEMORY",
	     PyInt_FromLong(
	      LIBEWF_MEDIA_TYPE_MEMORY ) ) != 0 )
	{
		goto on_error;
	}
	return( 1 );

on_error:
	if( type_object->tp_dict != NULL )
	{
		Py_DecRef(
		 type_object->tp_dict );

		type_object->tp_dict = NULL;
	}
	return( -1 );
}
Exemple #14
0
/*********************
 *** Plugin object ***
 ********************/
Plugin::Plugin(const QString &moduleName)
{
    //load module
    module = PyImport_ImportModule(moduleName.toUtf8().constData());
    if (module == NULL)
    {
        PyErr_Print();
        exit(-1);
    }
    name = moduleName.mid(7);
    //get search() and parse()
    searchFunc = PyObject_GetAttrString(module, "search");
    parseFunc = PyObject_GetAttrString(module, "parse");
    if (searchFunc == NULL || parseFunc == NULL)
    {
        PyErr_Print();
        exit(-1);
    }

    searchAlbumFunc = PyObject_GetAttrString(module, "search_album");
    if (searchAlbumFunc == NULL)
        PyErr_Clear();

    //get hosts
    PyObject *hosts = PyObject_GetAttrString(module, "hosts");
    if (hosts)
    {
        int size = PyTuple_Size(hosts);
        if (size < 0)
        {
            PyErr_Print();
            exit(EXIT_FAILURE);
        }
        for (int i = 0; i < size; i++)
        {
            const char *str = PyString_AsString(PyTuple_GetItem(hosts, i));
            host2plugin[QString::fromUtf8(str)] = this;
        }
    }
    else
        PyErr_Clear();

    //get resources library
    libraryFunc = PyObject_GetAttrString(module, "library");
    if (libraryFunc == NULL)
        PyErr_Clear();

    PyObject *types = PyObject_GetAttrString(module, "movie_types");
    if (types)
    {
        for (int i = 0; i < PyList_Size(types); i++)
        {
            const char *str = PyString_AsString(PyList_GetItem(types, i));
            mvTypes << QString::fromUtf8(str);
        }
        Py_DecRef(types);
    }
    else
        PyErr_Clear();

    types = PyObject_GetAttrString(module, "tv_types");
    if (types)
    {
        for (int i = 0; i < PyList_Size(types); i++)
        {
            const char *str = PyString_AsString(PyList_GetItem(types, i));
            tvTypes << QString::fromUtf8(str);
        }
        Py_DecRef(types);
    }
    else
        PyErr_Clear();
}
Exemple #15
0
/* Creates a new records sequence and iterator object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyevtx_records_new(
           PyObject *parent_object,
           PyObject* (*get_item_by_index)(
                        PyObject *parent_object,
                        int index ),
           int number_of_items )
{
	pyevtx_records_t *sequence_object = NULL;
	static char *function             = "pyevtx_records_new";

	if( parent_object == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid parent object.",
		 function );

		return( NULL );
	}
	if( get_item_by_index == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid get item by index function.",
		 function );

		return( NULL );
	}
	/* Make sure the records values are initialized
	 */
	sequence_object = PyObject_New(
	                   struct pyevtx_records,
	                   &pyevtx_records_type_object );

	if( sequence_object == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to create sequence object.",
		 function );

		goto on_error;
	}
	sequence_object->parent_object     = parent_object;
	sequence_object->get_item_by_index = get_item_by_index;
	sequence_object->current_index     = 0;
	sequence_object->number_of_items   = number_of_items;

	Py_IncRef(
	 (PyObject *) sequence_object->parent_object );

	return( (PyObject *) sequence_object );

on_error:
	if( sequence_object != NULL )
	{
		Py_DecRef(
		 (PyObject *) sequence_object );
	}
	return( NULL );
}
Exemple #16
0
QStringList PythonContext::completionOptions(QString base)
{
  QStringList ret;

  if(!m_Completer)
    return ret;

  QByteArray bytes = base.toUtf8();
  const char *input = (const char *)bytes.data();

  PyGILState_STATE gil = PyGILState_Ensure();

  PyObject *completeFunction = PyObject_GetAttrString(m_Completer, "complete");

  int idx = 0;
  PyObject *opt = NULL;
  do
  {
    opt = PyObject_CallFunction(completeFunction, "si", input, idx);

    if(opt && opt != Py_None)
    {
      QString optstr = ToQStr(opt);

      bool add = true;

      // little hack, remove some of the ugly swig template instantiations that we can't avoid.
      if(optstr.contains(lit("renderdoc.rdcarray")) || optstr.contains(lit("renderdoc.rdcstr")) ||
         optstr.contains(lit("renderdoc.bytebuf")))
        add = false;

      if(add)
        ret << optstr;
    }

    idx++;
  } while(opt && opt != Py_None);

  // extra hack, remove the swig object functions/data but ONLY if we find a sure-fire identifier
  // (thisown) since otherwise we could remove append from a list object
  bool containsSwigInternals = false;
  for(const QString &optstr : ret)
  {
    if(optstr.contains(lit(".thisown")))
    {
      containsSwigInternals = true;
      break;
    }
  }

  if(containsSwigInternals)
  {
    for(int i = 0; i < ret.count();)
    {
      if(ret[i].endsWith(lit(".acquire(")) || ret[i].endsWith(lit(".append(")) ||
         ret[i].endsWith(lit(".disown(")) || ret[i].endsWith(lit(".next(")) ||
         ret[i].endsWith(lit(".own(")) || ret[i].endsWith(lit(".this")) ||
         ret[i].endsWith(lit(".thisown")))
        ret.removeAt(i);
      else
        i++;
    }
  }

  Py_DecRef(completeFunction);

  PyGILState_Release(gil);

  return ret;
}
/* Creates a new cache directories object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pymsiecf_cache_directories_new(
           PyObject *parent_object,
           PyObject* (*get_cache_directory_by_index)(
                        PyObject *parent_object,
                        int cache_directory_index ),
           int number_of_cache_directories )
{
	pymsiecf_cache_directories_t *pymsiecf_cache_directories = NULL;
	static char *function                                    = "pymsiecf_cache_directories_new";

	if( parent_object == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid parent object.",
		 function );

		return( NULL );
	}
	if( get_cache_directory_by_index == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid get cache directory by index function.",
		 function );

		return( NULL );
	}
	/* Make sure the cache directories values are initialized
	 */
	pymsiecf_cache_directories = PyObject_New(
	                              struct pymsiecf_cache_directories,
	                              &pymsiecf_cache_directories_type_object );

	if( pymsiecf_cache_directories == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize cache directories.",
		 function );

		goto on_error;
	}
	if( pymsiecf_cache_directories_init(
	     pymsiecf_cache_directories ) != 0 )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize cache directories.",
		 function );

		goto on_error;
	}
	pymsiecf_cache_directories->parent_object                = parent_object;
	pymsiecf_cache_directories->get_cache_directory_by_index = get_cache_directory_by_index;
	pymsiecf_cache_directories->number_of_cache_directories  = number_of_cache_directories;

	Py_IncRef(
	 (PyObject *) pymsiecf_cache_directories->parent_object );

	return( (PyObject *) pymsiecf_cache_directories );

on_error:
	if( pymsiecf_cache_directories != NULL )
	{
		Py_DecRef(
		 (PyObject *) pymsiecf_cache_directories );
	}
	return( NULL );
}
Exemple #18
0
/* Fetches an error
 */
void VARARGS(
      pyqcow_error_fetch,
      libcerror_error_t **error,
      int error_domain,
      int error_code,
      const char *,
      format_string )
{
	va_list argument_list;

	char error_string[ PYQCOW_ERROR_STRING_SIZE ];

        PyObject *exception_traceback = NULL;
        PyObject *exception_type      = NULL;
        PyObject *exception_value     = NULL;
        PyObject *string_object       = NULL;
	static char *function         = "pyqcow_error_fetch";
	char *exception_string        = NULL;
	size_t error_string_length    = 0;
	int print_count               = 0;

#if PY_MAJOR_VERSION >= 3
	PyObject *utf8_string_object  = NULL;
#endif

	if( format_string == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: missing format string.",
		 function );

		return;
	}
	VASTART(
	 argument_list,
	 const char *,
	 format_string );

	print_count = PyOS_vsnprintf(
	               error_string,
	               PYQCOW_ERROR_STRING_SIZE,
	               format_string,
	               argument_list );

	VAEND(
	 argument_list );

	if( print_count < 0 )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: unable to format error string.",
		 function );

		return;
	}
	error_string_length = libcstring_narrow_string_length(
	                       error_string );

	if( ( error_string_length >= 1 )
	 && ( error_string[ error_string_length - 1 ] == '.' ) )
	{
		error_string[ error_string_length - 1 ] = 0;
	}
	PyErr_Fetch(
	 &exception_type,
	 &exception_value,
	 &exception_traceback );

	string_object = PyObject_Repr(
	                 exception_value );

#if PY_MAJOR_VERSION >= 3
	utf8_string_object = PyUnicode_AsUTF8String(
	                      string_object );

	if( utf8_string_object != NULL )
	{
		exception_string = PyBytes_AsString(
		                    utf8_string_object );
	}
#else
	exception_string = PyString_AsString(
	                    string_object );
#endif
	if( exception_string != NULL )
	{
		libcerror_error_set(
		 error,
		 error_domain,
		 error_code,
		 "%s with error: %s.",
		 error_string,
		 exception_string );
	}
	else
	{
		libcerror_error_set(
		 error,
		 error_domain,
		 error_code,
		 "%s.",
		 error_string );
	}
#if PY_MAJOR_VERSION >= 3
	if( utf8_string_object != NULL )
	{
		Py_DecRef(
		 utf8_string_object );
	}
#endif
	Py_DecRef(
	 string_object );

	return;
}
Exemple #19
0
/* Creates a new segments object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyvslvm_segments_new(
           pyvslvm_logical_volume_t *logical_volume_object,
           PyObject* (*get_segment_by_index)(
                        pyvslvm_logical_volume_t *logical_volume_object,
                        int segment_index ),
           int number_of_segments )
{
	pyvslvm_segments_t *pyvslvm_segments = NULL;
	static char *function                = "pyvslvm_segments_new";

	if( logical_volume_object == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid logical volume object.",
		 function );

		return( NULL );
	}
	if( get_segment_by_index == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid get segment by index function.",
		 function );

		return( NULL );
	}
	/* Make sure the segments values are initialized
	 */
	pyvslvm_segments = PyObject_New(
	                    struct pyvslvm_segments,
	                    &pyvslvm_segments_type_object );

	if( pyvslvm_segments == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize segments.",
		 function );

		goto on_error;
	}
	if( pyvslvm_segments_init(
	     pyvslvm_segments ) != 0 )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize segments.",
		 function );

		goto on_error;
	}
	pyvslvm_segments->logical_volume_object = logical_volume_object;
	pyvslvm_segments->get_segment_by_index  = get_segment_by_index;
	pyvslvm_segments->number_of_segments    = number_of_segments;

	Py_IncRef(
	 (PyObject *) pyvslvm_segments->logical_volume_object );

	return( (PyObject *) pyvslvm_segments );

on_error:
	if( pyvslvm_segments != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyvslvm_segments );
	}
	return( NULL );
}
/* Frees a file_entry object
 */
void pyewf_file_entry_free(
      pyewf_file_entry_t *pyewf_file_entry )
{
	char error_string[ PYEWF_ERROR_STRING_SIZE ];

	libcerror_error_t *error = NULL;
	static char *function    = "pyewf_file_entry_free";
	int result               = 0;

	if( pyewf_file_entry == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid file_entry.",
		 function );

		return;
	}
	if( pyewf_file_entry->ob_type == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid file_entry - missing ob_type.",
		 function );

		return;
	}
	if( pyewf_file_entry->ob_type->tp_free == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid file_entry - invalid ob_type - missing tp_free.",
		 function );

		return;
	}
	if( pyewf_file_entry->file_entry == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid file_entry - missing libewf file_entry.",
		 function );

		return;
	}
	Py_BEGIN_ALLOW_THREADS

	result = libewf_file_entry_free(
	          &( pyewf_file_entry->file_entry ),
	          &error );

	Py_END_ALLOW_THREADS

	if( result != 1 )
	{
		if( libcerror_error_backtrace_sprint(
		     error,
		     error_string,
		     PYEWF_ERROR_STRING_SIZE ) == -1 )
		{
			PyErr_Format(
			 PyExc_MemoryError,
			 "%s: unable to free file_entry.",
			 function );
		}
		else
		{
			PyErr_Format(
			 PyExc_MemoryError,
			 "%s: unable to free file_entry.\n%s",
			 function,
			 error_string );
		}
		libcerror_error_free(
		 &error );
	}
        if( pyewf_file_entry->handle_object != NULL )
        {
                Py_DecRef(
                 (PyObject *) pyewf_file_entry->handle_object );
        }
	pyewf_file_entry->ob_type->tp_free(
	 (PyObject*) pyewf_file_entry );
}
Exemple #21
0
/**
 * Replace the current condition list with the new one.
 *
 * @param self TODO. Must not be NULL.
 * @param args TODO. Must not be NULL.
 *
 * @retval SRD_OK The new condition list was set successfully.
 * @retval SRD_ERR There was an error setting the new condition list.
 *                 The contents of di->condition_list are undefined.
 * @retval 9999 TODO.
 */
static int set_new_condition_list(PyObject *self, PyObject *args)
{
	struct srd_decoder_inst *di;
	GSList *term_list;
	PyObject *py_conditionlist, *py_conds, *py_dict;
	int i, num_conditions, ret;

	if (!self || !args)
		return SRD_ERR_ARG;

	/* Get the decoder instance. */
	if (!(di = srd_inst_find_by_obj(NULL, self))) {
		PyErr_SetString(PyExc_Exception, "decoder instance not found");
		return SRD_ERR;
	}

	/*
	 * Return an error condition from .wait() when termination is
	 * requested, such that decode() will terminate.
	 */
	if (di->want_wait_terminate) {
		srd_dbg("%s: %s: Skip (want_term).", di->inst_id, __func__);
		return SRD_ERR;
	}

	/* Parse the argument of self.wait() into 'py_conds'. */
	if (!PyArg_ParseTuple(args, "O", &py_conds)) {
		/* Let Python raise this exception. */
		return SRD_ERR;
	}

	/* Check whether 'py_conds' is a dict or a list. */
	if (PyList_Check(py_conds)) {
		/* 'py_conds' is a list. */
		py_conditionlist = py_conds;
		num_conditions = PyList_Size(py_conditionlist);
		if (num_conditions == 0)
			return 9999; /* The PD invoked self.wait([]). */
		Py_IncRef(py_conditionlist);
	} else if (PyDict_Check(py_conds)) {
		/* 'py_conds' is a dict. */
		if (PyDict_Size(py_conds) == 0)
			return 9999; /* The PD invoked self.wait({}). */
		/* Make a list and put the dict in there for convenience. */
		py_conditionlist = PyList_New(1);
		Py_IncRef(py_conds);
		PyList_SetItem(py_conditionlist, 0, py_conds);
		num_conditions = 1;
	} else {
		srd_err("Condition list is neither a list nor a dict.");
		return SRD_ERR;
	}

	/* Free the old condition list. */
	condition_list_free(di);

	ret = SRD_OK;

	/* Iterate over the conditions, set di->condition_list accordingly. */
	for (i = 0; i < num_conditions; i++) {
		/* Get a condition (dict) from the condition list. */
		py_dict = PyList_GetItem(py_conditionlist, i);
		if (!PyDict_Check(py_dict)) {
			srd_err("Condition is not a dict.");
			ret = SRD_ERR;
			break;
		}

		/* Create the list of terms in this condition. */
		if ((ret = create_term_list(py_dict, &term_list)) < 0)
			break;

		/* Add the new condition to the PD instance's condition list. */
		di->condition_list = g_slist_append(di->condition_list, term_list);
	}

	Py_DecRef(py_conditionlist);

	return ret;
}
Exemple #22
0
/* Frees a file metrics object
 */
void pyscca_file_metrics_free(
      pyscca_file_metrics_t *pyscca_file_metrics )
{
	struct _typeobject *ob_type = NULL;
	libcerror_error_t *error    = NULL;
	static char *function       = "pyscca_file_metrics_free";
	int result                  = 0;

	if( pyscca_file_metrics == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid file metrics.",
		 function );

		return;
	}
	if( pyscca_file_metrics->file_metrics == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid file metrics - missing libscca file metrics.",
		 function );

		return;
	}
	ob_type = Py_TYPE(
	           pyscca_file_metrics );

	if( ob_type == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: missing ob_type.",
		 function );

		return;
	}
	if( ob_type->tp_free == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid ob_type - missing tp_free.",
		 function );

		return;
	}
	Py_BEGIN_ALLOW_THREADS

	result = libscca_file_metrics_free(
	          &( pyscca_file_metrics->file_metrics ),
	          &error );

	Py_END_ALLOW_THREADS

	if( result != 1 )
	{
		pyscca_error_raise(
		 error,
		 PyExc_IOError,
		 "%s: unable to free libscca file metrics.",
		 function );

		libcerror_error_free(
		 &error );
	}
	if( pyscca_file_metrics->parent_object != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyscca_file_metrics->parent_object );
	}
	ob_type->tp_free(
	 (PyObject*) pyscca_file_metrics );
}
Exemple #23
0
/* Frees an item object
 */
void pyolecf_item_free(
      pyolecf_item_t *pyolecf_item )
{
	libcerror_error_t *error = NULL;
	static char *function    = "pyolecf_item_free";

	if( pyolecf_item == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid item.",
		 function );

		return;
	}
	if( pyolecf_item->ob_type == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid item - missing ob_type.",
		 function );

		return;
	}
	if( pyolecf_item->ob_type->tp_free == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid item - invalid ob_type - missing tp_free.",
		 function );

		return;
	}
	if( pyolecf_item->item == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid item - missing libolecf item.",
		 function );

		return;
	}
	if( libolecf_item_free(
	     &( pyolecf_item->item ),
	     &error ) != 1 )
	{
		pyolecf_error_raise(
		 error,
		 PyExc_IOError,
		 "%s: unable to free libolecf item.",
		 function );

		libcerror_error_free(
		 &error );
	}
	if( pyolecf_item->file_object != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyolecf_item->file_object );
	}
	pyolecf_item->ob_type->tp_free(
	 (PyObject*) pyolecf_item );
}
/* Frees a multi value object
 */
void pyesedb_multi_value_free(
      pyesedb_multi_value_t *pyesedb_multi_value )
{
	libcerror_error_t *error    = NULL;
	struct _typeobject *ob_type = NULL;
	static char *function       = "pyesedb_multi_value_free";

	if( pyesedb_multi_value == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid multi value.",
		 function );

		return;
	}
	if( pyesedb_multi_value->multi_value == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid multi value - missing libesedb multi value.",
		 function );

		return;
	}
	ob_type = Py_TYPE(
	           pyesedb_multi_value );

	if( ob_type == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: missing ob_type.",
		 function );

		return;
	}
	if( ob_type->tp_free == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid ob_type - missing tp_free.",
		 function );

		return;
	}
	if( libesedb_multi_value_free(
	     &( pyesedb_multi_value->multi_value ),
	     &error ) != 1 )
	{
		pyesedb_error_raise(
		 error,
		 PyExc_IOError,
		 "%s: unable to free libesedb multi value.",
		 function );

		libcerror_error_free(
		 &error );
	}
	if( pyesedb_multi_value->record_object != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyesedb_multi_value->record_object );
	}
	ob_type->tp_free(
	 (PyObject*) pyesedb_multi_value );
}