Exemplo n.º 1
0
template <typename T> void TypeSequence<T>::call_concat_inplace::call()
{
  TypeSequence &type = dynamic_cast<TypeSequence &>(TypeBase<T>::m_get());

  if (self)
  {
    try
    {
      T &obj = reinterpret_cast<typename TypeBase<T>::T_struct *>(self)->endosome;
      PYHROL_TRACE(tpMediator, type.address(obj), signature)
      type.concat(Ptr<T>(&obj, self), args);
      Py_IncRef(self);
    }
    catch(...)
    {
      self = NULL;
      throw;
    }
  }
  else
  {
    type.concat(Ptr<T>(), args);
  }
}
Exemplo n.º 2
0
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; 
}
/* Creates a file object IO handle
 * Make sure the value file_object_io_handle is referencing, is set to NULL
 * Returns 1 if successful or -1 on error
 */
int pymsiecf_file_object_io_handle_initialize(
     pymsiecf_file_object_io_handle_t **file_object_io_handle,
     PyObject *file_object,
     libcerror_error_t **error )
{
	static char *function = "pymsiecf_file_object_io_handle_initialize";

	if( file_object_io_handle == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid file object IO handle.",
		 function );

		return( -1 );
	}
	if( *file_object_io_handle != NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_VALUE_ALREADY_SET,
		 "%s: invalid file object IO handle value already set.",
		 function );

		return( -1 );
	}
	if( file_object == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
		 LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
		 "%s: invalid file object.",
		 function );

		return( -1 );
	}
	*file_object_io_handle = (pymsiecf_file_object_io_handle_t *) PyMem_Malloc(
	                                                               sizeof( pymsiecf_file_object_io_handle_t ) );

	if( *file_object_io_handle == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_MEMORY,
		 LIBCERROR_MEMORY_ERROR_INSUFFICIENT,
		 "%s: unable to create file object IO handle.",
		 function );

		goto on_error;
	}
	if( memory_set(
	     *file_object_io_handle,
	     0,
	     sizeof( pymsiecf_file_object_io_handle_t ) ) == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_MEMORY,
		 LIBCERROR_MEMORY_ERROR_SET_FAILED,
		 "%s: unable to clear file object IO handle.",
		 function );

		goto on_error;
	}
	( *file_object_io_handle )->file_object = file_object;

	Py_IncRef(
	 ( *file_object_io_handle )->file_object );

	return( 1 );

on_error:
	if( *file_object_io_handle != NULL )
	{
		PyMem_Free(
		 *file_object_io_handle );

		*file_object_io_handle = NULL;
	}
	return( -1 );
}
Exemplo n.º 4
0
/* Creates a new items object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyfwsi_items_new(
           pyfwsi_item_list_t *item_list_object,
           PyObject* (*get_item_by_index)(
                        pyfwsi_item_list_t *item_list_object,
                        int item_index ),
           int number_of_items )
{
	pyfwsi_items_t *pyfwsi_items = NULL;
	static char *function        = "pyfwsi_items_new";

	if( item_list_object == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid item list 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 items values are initialized
	 */
	pyfwsi_items = PyObject_New(
	                struct pyfwsi_items,
	                &pyfwsi_items_type_object );

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

		goto on_error;
	}
	if( pyfwsi_items_init(
	     pyfwsi_items ) != 0 )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize items.",
		 function );

		goto on_error;
	}
	pyfwsi_items->item_list_object  = item_list_object;
	pyfwsi_items->get_item_by_index = get_item_by_index;
	pyfwsi_items->number_of_items   = number_of_items;

	Py_IncRef(
	 (PyObject *) pyfwsi_items->item_list_object );

	return( (PyObject *) pyfwsi_items );

on_error:
	if( pyfwsi_items != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyfwsi_items );
	}
	return( NULL );
}
Exemplo n.º 5
0
	void PyIOCPBuffer_AddObject( PyObject* m )
	{
		Py_IncRef((PyObject*)&iocp_buffer_type);
		PyModule_AddObject( m, "buffer", (PyObject *)&iocp_buffer_type ) ;
	}
Exemplo n.º 6
0
/* Creates a new items object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pymsiecf_items_new(
           PyObject *parent_object,
           PyObject* (*get_item_by_index)(
                        PyObject *parent_object,
                        int index ),
           int number_of_items )
{
	pymsiecf_items_t *items_object = NULL;
	static char *function          = "pymsiecf_items_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 items values are initialized
	 */
	items_object = PyObject_New(
	                struct pymsiecf_items,
	                &pymsiecf_items_type_object );

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

		goto on_error;
	}
	if( pymsiecf_items_init(
	     items_object ) != 0 )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize items object.",
		 function );

		goto on_error;
	}
	items_object->parent_object     = parent_object;
	items_object->get_item_by_index = get_item_by_index;
	items_object->number_of_items   = number_of_items;

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

	return( (PyObject *) items_object );

on_error:
	if( items_object != NULL )
	{
		Py_DecRef(
		 (PyObject *) items_object );
	}
	return( NULL );
}
Exemplo n.º 7
0
PyObject *TuplesDefaultImpl::ubiquitous_caller
(
    exceptionHandler &h
  , PyObject *args
  , PyObject *kwds
  , const bool is_probe
  , const callerTypes ct
)
{
  const callVariants cv = m_data.cv;
  const modes mode = is_probe ? (_G_signature_hack_enabled ? modeInitHack : modeInit) : modeRun;
  TuplesData2DefaultImpl &data = dynamic_cast<TuplesData2DefaultImpl &>(m_data);

  if (mode == modeRun && !m_data.m_valid)
  {
    PyErr_Format(PyExc_AttributeError, "Tuple invalid due to one or more previous errors. Call impossible in any way (%s)", Container::container().context_by_address(data.m_address).c_str());
    return NULL;
  }

  if (ct == ctGetter)
  {
    TupleState::set_mode_getter();
  }
  else if (ct == ctSetter)
  {
    TupleState::set_mode_setter();
  }

  if (mode == modeRun)
  {
    m_exec = true;
    m_tuple = args;
    m_kw = kwds;
    m_retval = NULL;
  }

  if (mode == modeRun || mode == modeInitHack)
  {
    m_clear_before_execute();

    bool
        just_filled = false
      , exception_thrown
    ;

    try
    {
      exception_thrown = !exceptionHandler::call(h, data.m_address);
      just_filled = !exception_thrown;
    }
    catch (const ParseException &ex)
    {
      //Неверные аргументы Python; только в режиме исполнения
      PyErr_Format(PyExc_TypeError, "%s (%s)", ex.what(), Container::container().context_by_address(data.m_address).c_str());
      exception_thrown = true;
      just_filled = true;
    }

    /* NOTE
    Despite of exception thrown user call can leave return value inited
    Non null return value in case of not filled tuple is unbelievable internal error
    */
    if (m_retval && (exception_thrown || !TupleState::is_filled()))
    {
      Py_DecRef(m_retval);
      m_retval = NULL;
    }

    if (mode == modeInitHack && PyErr_Occurred())
    {
      PyErr_PrintEx(0);
      PyErr_Clear();
    }

    if (!TupleState::is_filled())
    {
      /* NOTE
      Tuple must be filled during first call in any way.
      Any exceptions or invalid actions inside (TuplesData::*call_t) whereby tuple not filled
      during first call causes inevitable invalidation. Any subsequent calls waved aside
      This in the same way as for v_getsetter calls: even if getter filled successfully, error in setter
      invalidates tuple at all and virce versa
      */
      m_data.m_valid = false;
      just_filled = false;
      if (!exception_thrown)
      {
        PyErr_Format(PyExc_AttributeError, "Tuple invalid due to unknown reason. Any further calls impossible in any way (%s)", Container::container().context_by_address(data.m_address).c_str());
      }
    }
    else if (just_filled)
    {
      //Here: user call executed successfully or caused parse error
      just_filled = false;
      try
      {
        just_filled = TupleState::just_filled();
      }
      catch (const CheckCalls::ForbiddenCall &ex)
      {
        PyErr_Format(PyExc_AttributeError, "%s (%s)", ex.what(), Container::container().context_by_address(data.m_address).c_str());
      }
    }

    if (just_filled || m_data.m_valid && (mode == modeInit || mode == modeInitHack))
    {
      m_generate_description();
    }
  }

  if (cv == v_getsetter && TupleState::mode() == TupleFillState::modSetter || cv == v_setter || cv == v_protof || cv == v_ctor)
  {
    return NULL;
  }

  if (!PyErr_Occurred() && !m_retval && mode == modeRun)
  {
    Py_IncRef(Py_None);
    m_retval = Py_None;
  }
  return m_retval;
}
Exemplo n.º 8
0
/* Creates a new blocks sequence and iterator object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyvshadow_blocks_new(
           PyObject *parent_object,
           PyObject* (*get_item_by_index)(
                        PyObject *parent_object,
                        int index ),
           int number_of_items )
{
	pyvshadow_blocks_t *sequence_object = NULL;
	static char *function               = "pyvshadow_blocks_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 blocks values are initialized
	 */
	sequence_object = PyObject_New(
	                   struct pyvshadow_blocks,
	                   &pyvshadow_blocks_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 );
}
Exemplo n.º 9
0
/* Creates a new physical volumes object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyvslvm_physical_volumes_new(
           pyvslvm_volume_group_t *volume_group_object,
           PyObject* (*get_physical_volume_by_index)(
                        pyvslvm_volume_group_t *volume_group_object,
                        int physical_volume_index ),
           int number_of_physical_volumes )
{
	pyvslvm_physical_volumes_t *pyvslvm_physical_volumes = NULL;
	static char *function                                = "pyvslvm_physical_volumes_new";

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

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

		return( NULL );
	}
	/* Make sure the physical volumes values are initialized
	 */
	pyvslvm_physical_volumes = PyObject_New(
	                            struct pyvslvm_physical_volumes,
	                            &pyvslvm_physical_volumes_type_object );

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

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

		goto on_error;
	}
	pyvslvm_physical_volumes->volume_group_object          = volume_group_object;
	pyvslvm_physical_volumes->get_physical_volume_by_index = get_physical_volume_by_index;
	pyvslvm_physical_volumes->number_of_physical_volumes   = number_of_physical_volumes;

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

	return( (PyObject *) pyvslvm_physical_volumes );

on_error:
	if( pyvslvm_physical_volumes != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyvslvm_physical_volumes );
	}
	return( NULL );
}
Exemplo n.º 10
0
static foreign_t python_apply(term_t tin, term_t targs, term_t keywds,
                              term_t tf) {
  PyObject *pF;
  PyObject *pArgs, *pKeywords;
  PyObject *pValue;
  int i, arity;
  atom_t aname;
  foreign_t out;
  term_t targ = PL_new_term_ref();

  pF = term_to_python(tin, true);
  PyErr_Clear();
  if (pF == NULL) {
    {
      return false;
    }
  }
  if (PL_is_atom(targs)) {
    pArgs = NULL;
  } else {

    if (!PL_get_name_arity(targs, &aname, &arity)) {
      {
        return false;
      }
    }
    if (arity == 1 && PL_get_arg(1, targs, targ) && PL_is_variable(targ)) {
      /* ignore (_) */
      pArgs = NULL;
    } else {

      pArgs = PyTuple_New(arity);
      if (!pArgs) {
        return false;
      }
      for (i = 0; i < arity; i++) {
        PyObject *pArg;
        if (!PL_get_arg(i + 1, targs, targ)) {
          return false;
        }
        pArg = term_to_python(targ, true);
        if (pArg == NULL) {
          return false;
        }
        /* pArg reference stolen here: */
        PyTuple_SetItem(pArgs, i, pArg);
      }
    }
  }
  if (PL_is_atom(keywds)) {
    pKeywords = NULL;
  } else {
    pKeywords = term_to_python(keywds, true);
  }
  if (PyCallable_Check(pF)) {
    pValue = PyEval_CallObjectWithKeywords(pF, pArgs, pKeywords);
    //   PyObject_Print(pF,stderr,0);fprintf(stderr, "\n");
    // PyObject_Print(pArgs,stderr,0);fprintf(stderr, " ");
    // PyObject_Print(pKeywords,stderr,0);fprintf(stderr, "\n");
    if (!pValue)
      PyErr_Print();
    else
      Py_IncRef(pValue);
  } else if (pArgs == NULL) {
    pValue = pF;

    if (pF) {
      Py_IncRef(pValue);
    }
  } else {
    PyErr_Print();
    {
      return false;
    }
  }
  if (pArgs)
    Py_DECREF(pArgs);
  Py_DECREF(pF);
  if (pValue == NULL) {
    return false;
  }
  out = python_to_ptr(pValue, tf);
  return out;
}
Exemplo n.º 11
0
/* Creates a new columns object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyesedb_columns_new(
           pyesedb_table_t *table_object,
           PyObject* (*get_column_by_index)(
                        pyesedb_table_t *table_object,
                        int column_entry ),
           int number_of_columns )
{
	pyesedb_columns_t *pyesedb_columns = NULL;
	static char *function              = "pyesedb_columns_new";

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

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

		return( NULL );
	}
	/* Make sure the columns values are initialized
	 */
	pyesedb_columns = PyObject_New(
	                  struct pyesedb_columns,
	                  &pyesedb_columns_type_object );

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

		goto on_error;
	}
	if( pyesedb_columns_init(
	     pyesedb_columns ) != 0 )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize columns.",
		 function );

		goto on_error;
	}
	pyesedb_columns->table_object        = table_object;
	pyesedb_columns->get_column_by_index = get_column_by_index;
	pyesedb_columns->number_of_columns   = number_of_columns;

	Py_IncRef(
	 (PyObject *) pyesedb_columns->table_object );

	return( (PyObject *) pyesedb_columns );

on_error:
	if( pyesedb_columns != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyesedb_columns );
	}
	return( NULL );
}
Exemplo n.º 12
0
/* Seeks a certain offset in the file entry data
 * Returns a Python object holding the offset if successful or NULL on error
 */
PyObject *pyewf_file_entry_seek_offset(
           pyewf_file_entry_t *pyewf_file_entry,
           PyObject *arguments,
           PyObject *keywords )
{
	libcerror_error_t *error    = NULL;
	static char *function       = "pyewf_file_entry_seek_offset";
	static char *keyword_list[] = { "offset", "whence", NULL };
	off64_t offset              = 0;
	int whence                  = 0;

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

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

		return( NULL );
	}
	if( PyArg_ParseTupleAndKeywords(
	     arguments,
	     keywords,
	     "L|i",
	     keyword_list,
	     &offset,
	     &whence ) == 0 )
	{
		return( NULL );
	}
	Py_BEGIN_ALLOW_THREADS

	offset = libewf_file_entry_seek_offset(
	          pyewf_file_entry->file_entry,
	          offset,
	          whence,
	          &error );

	Py_END_ALLOW_THREADS

	if( offset == -1 )
	{
		pyewf_error_raise(
		 error,
		 PyExc_IOError,
		 "%s: unable to seek offset.",
		 function );

		libcerror_error_free(
		 &error );

		return( NULL );
	}
	Py_IncRef(
	 Py_None );

	return( Py_None );
}
Exemplo n.º 13
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;
}
Exemplo n.º 14
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 );
}
Exemplo n.º 15
0
/* 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 );
}
Exemplo n.º 16
0
/* Open EWF file(s)
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyewf_handle_open(
           pyewf_handle_t *pyewf_handle,
           PyObject *arguments,
           PyObject *keywords )
{
	char error_string[ PYEWF_ERROR_STRING_SIZE ];

	libcerror_error_t *error    = NULL;
	char **filenames            = NULL;
	char *mode                  = NULL;
	static char *keyword_list[] = { "filenames", "mode", NULL };
	PyObject *sequence_object   = NULL;
	PyObject *string_object     = NULL;
	static char *function       = "pyewf_handle_open";
	size_t filename_length      = 0;
	int access_flags            = 0;
	int filename_index          = 0;
	int number_of_filenames     = 0;
	int result                  = 0;

	if( pyewf_handle == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid pyewf handle.",
		 function );

		return( NULL );
	}
	if( PyArg_ParseTupleAndKeywords(
	     arguments,
	      keywords,
	      "O|s",
	      keyword_list,
	      &sequence_object,
	      &mode ) == 0 )
	{
		return( NULL );
	}
	if( PySequence_Check(
	     sequence_object ) == 0 )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: argument: files must be a sequence object.",
		 function );

		return( NULL );
	}
        if( mode == NULL )
	{
		access_flags = LIBEWF_OPEN_READ;
	}
	else if( mode[ 0 ] == 'r' )
	{
		if( mode[ 1 ] == '+' )
		{
			if( ( mode[ 2 ] == 0 )
			 || ( ( mode[ 2 ] == 'b' )
			  &&  ( mode[ 3 ] == 0 ) ) )
			{
				access_flags = LIBEWF_OPEN_READ_WRITE;
			}
		}
		else if( ( mode[ 1 ] == 0 )
		      || ( ( mode[ 1 ] == 'b' )
		       &&  ( mode[ 2 ] == 0 ) ) )
		{
			access_flags = LIBEWF_OPEN_READ;
		}
	}
	else if( mode[ 0 ] == 'w' )
	{
		if( ( mode[ 1 ] == 0 )
		 || ( ( mode[ 1 ] == 'b' )
		  &&  ( mode[ 2 ] == 0 ) ) )
		{
			access_flags = LIBEWF_OPEN_WRITE;
		}
	}
	else if( mode[ 0 ] == 'a' )
	{
		if( ( mode[ 1 ] == 0 )
		 || ( ( mode[ 1 ] == 'b' )
		  &&  ( mode[ 2 ] == 0 ) ) )
		{
			access_flags = LIBEWF_OPEN_WRITE_RESUME;
		}
	}
	if( access_flags == 0 )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: unsupported mode: %s.",
		 function,
		 mode );

		return( NULL );
	}
	number_of_filenames = PySequence_Size(
	                       sequence_object );

	if( ( number_of_filenames <= 0 )
	 || ( number_of_filenames > (int) UINT16_MAX ) )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid number of files.",
		 function );

		goto on_error;
	}
	filenames = (char **) PyMem_Malloc(
	                       sizeof( char * ) * number_of_filenames );

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

		goto on_error;
	}
	if( memory_set(
	     filenames,
	     0,
	     sizeof( char * ) * number_of_filenames ) == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to clear filenames.",
		 function );

		PyMem_Free(
		 filenames );

		return( NULL );
	}
	for( filename_index = 0;
	     filename_index < number_of_filenames;
	     filename_index++ )
	{
		string_object = PySequence_GetItem(
		                 sequence_object,
		                 filename_index );

		filename_length = PyString_Size(
		                   string_object );

		filenames[ filename_index ] = (char *) PyMem_Malloc(
		                                        sizeof( char ) * ( filename_length + 1 ) );

		if( filenames[ filename_index ] == NULL )
		{
			PyErr_Format(
			 PyExc_MemoryError,
			 "%s: unable to create filename: %d.",
			 function,
			 filename_index );

			goto on_error;
		}
		if( libcstring_narrow_string_copy(
		     filenames[ filename_index ],
		     PyString_AsString(
		      string_object ),
		     filename_length ) == NULL )
		{
			PyErr_Format(
			 PyExc_MemoryError,
			 "%s: unable to set filename: %d.",
			 function,
			 filename_index );

			goto on_error;
		}
		( filenames[ filename_index ] )[ filename_length ] = 0;

		Py_DecRef(
		 string_object );
	}
	Py_BEGIN_ALLOW_THREADS

	result = libewf_handle_open(
	          pyewf_handle->handle,
                  filenames,
                  number_of_filenames,
                  access_flags,
	          &error );

	Py_END_ALLOW_THREADS

	if( result != 1 )
	{
		if( libcerror_error_backtrace_sprint(
		     error,
		     error_string,
		     PYEWF_ERROR_STRING_SIZE ) == -1 )
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to open handle.",
			 function );
		}
		else
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to open handle.\n%s",
			 function,
			 error_string );
		}
		libcerror_error_free(
		 &error );

		goto on_error;
	}
	for( filename_index = 0;
	     filename_index < number_of_filenames;
	     filename_index++ )
	{
		PyMem_Free(
		 filenames[ filename_index ] );
	}
	PyMem_Free(
	 filenames );

	Py_IncRef(
	 Py_None );

	return( Py_None );

on_error:
	if( filenames != NULL )
	{
		for( ; filename_index > 0; filename_index-- )
		{
			PyMem_Free(
			 filenames[ filename_index - 1 ] );
		}
		PyMem_Free(
		 filenames );
	}
	return( NULL );
}
Exemplo n.º 17
0
	// --------------------------------------------------
	//
	static PyObject *addData(PyObject *self, PyObject *args)
	{
		float f;
		long l;
		int sz;
		PyObj *p = (PyObj *)self;
		sz = (int)PyTuple_Size(args);
		bk3dlib::DataType dtype = p->p->GetDataType();
		switch(dtype)
		{
		case bk3dlib::FLOAT32:
		case bk3dlib::FLOAT16:
		case bk3dlib::UNKNOWN:
		default:
			for(int i=0; i<sz; i++)
			{
				PyObject *po = PyTuple_GetItem(args, i);
				if(!po) 
				{
					PyErr_SetString(PyExc_AttributeError, "Bad item");
					return NULL;
				}
				// case of a Blender vector
				// We don't know the implementation so let's use attributes with names
				if(PyObject_HasAttrString(po, "x"))
				{
					PyObject *oComp = PyObject_GetAttrString(po, "x");
					float fVal = (float)PyFloat_AsDouble(oComp);
					p->p->AddData(&fVal, 1);
					Py_DecRef(oComp);
					if(PyObject_HasAttrString(po, "y"))
					{
						oComp = PyObject_GetAttrString(po, "y");
						fVal = (float)PyFloat_AsDouble(oComp);
						p->p->AddData(&fVal, 1);
						Py_DecRef(oComp);
					}
					if(PyObject_HasAttrString(po, "z"))
					{
						oComp = PyObject_GetAttrString(po, "z");
						fVal = (float)PyFloat_AsDouble(oComp);
						p->p->AddData(&fVal, 1);
						Py_DecRef(oComp);
					}
					if(PyObject_HasAttrString(po, "w"))
					{
						oComp = PyObject_GetAttrString(po, "w");
						fVal = (float)PyFloat_AsDouble(oComp);
						p->p->AddData(&fVal, 1);
						Py_DecRef(oComp);
					}
				}
				// case of a sub-list
				else if(PyList_Check(po))
				{
					int lsz = (int)PyList_Size(po);
					for(int j=0; j<lsz; j++)
					{
						PyObject *plo = PyList_GetItem(po, j);
						// case of a sub-list
						if(PyList_Check(plo))
						{
							int lsz2 = (int)PyList_Size(plo);
							for(int j=0; j<lsz2; j++)
							{
								PyObject *plo2 = PyList_GetItem(plo, j);
								int n = PyArg_Parse(plo2, "f", &f);
								if(n>0) p->p->AddData(&f, 1);
								else { 
									PyErr_SetString(PyExc_AttributeError, "Couldn't add arg to buffer");
									return NULL;
								}
							}
						}
						else
						{
							int n = PyArg_Parse(plo, "f", &f);
							if(n>0) p->p->AddData(&f, 1);
							else {
								PyErr_SetString(PyExc_AttributeError, "Couldn't add arg to buffer");
								return NULL;
							}
						}
					}
				}
				else
				{
					int n = PyArg_Parse(po, "f", &f);
					if(n>0) p->p->AddData(&f, 1);
					else {
						PyErr_SetString(PyExc_AttributeError, "Couldn't add arg to buffer");
						return NULL;
					}
				}
			}
			break;
		case bk3dlib::UINT32:
		case bk3dlib::UINT16:
		case bk3dlib::UINT8:
			for(int i=0; i<sz; i++)
			{
				PyObject *po = PyTuple_GetItem(args, i);
				if(!po) {
					PyErr_SetString(PyExc_AttributeError, "Problem with Item argument");
					return NULL;
				}
				assert(po);
				// case of a sub-list
				if(PyList_Check(po))
				{
					int lsz = (int)PyList_Size(po);
					for(int j=0; j<lsz; j++)
					{
						PyObject *plo = PyList_GetItem(po, j);
						// case of a sub-list
						if(PyList_Check(plo))
						{
							int lsz2 = (int)PyList_Size(plo);
							for(int j=0; j<lsz2; j++)
							{
								PyObject *plo2 = PyList_GetItem(plo, j);
								int n = PyArg_Parse(plo2, "l", &l);
								if(n>0) p->p->AddData(&l, 1);
								else {
									PyErr_SetString(PyExc_AttributeError, "Couldn't add arg to buffer");
									return NULL;
								}
							}
						}
						else
						{
							int n = PyArg_Parse(plo, "l", &l);
							if(n>0) p->p->AddData(&l, 1);
							else {
								PyErr_SetString(PyExc_AttributeError, "Couldn't add arg to buffer");
								return NULL;
							}
						}
					}
				}
				else
				{
					int n = PyArg_Parse(po, "l", &l);
					if(n>0) p->p->AddData(&l, 1);
					else {
						PyErr_SetString(PyExc_AttributeError, "Couldn't add arg to buffer");
						return NULL;
					}
				}
			}
			break;
		}
		Py_IncRef(Py_None);
		return Py_None;
	}
Exemplo n.º 18
0
/**
 * Decode a chunk of samples.
 *
 * The calls to this function must provide the samples that shall be
 * used by the protocol decoder
 *  - in the correct order ([...]5, 6, 4, 7, 8[...] is a bug),
 *  - starting from sample zero (2, 3, 4, 5, 6[...] is a bug),
 *  - consecutively, with no gaps (0, 1, 2, 4, 5[...] is a bug).
 *
 * The start- and end-sample numbers are absolute sample numbers (relative
 * to the start of the whole capture/file/stream), i.e. they are not relative
 * sample numbers within the chunk specified by 'inbuf' and 'inbuflen'.
 *
 * Correct example (4096 samples total, 4 chunks @ 1024 samples each):
 *   srd_inst_decode(di, 0,    1023, inbuf, 1024, 1);
 *   srd_inst_decode(di, 1024, 2047, inbuf, 1024, 1);
 *   srd_inst_decode(di, 2048, 3071, inbuf, 1024, 1);
 *   srd_inst_decode(di, 3072, 4095, inbuf, 1024, 1);
 *
 * The chunk size ('inbuflen') can be arbitrary and can differ between calls.
 *
 * Correct example (4096 samples total, 7 chunks @ various samples each):
 *   srd_inst_decode(di, 0,    1023, inbuf, 1024, 1);
 *   srd_inst_decode(di, 1024, 1123, inbuf,  100, 1);
 *   srd_inst_decode(di, 1124, 1423, inbuf,  300, 1);
 *   srd_inst_decode(di, 1424, 1642, inbuf,  219, 1);
 *   srd_inst_decode(di, 1643, 2047, inbuf,  405, 1);
 *   srd_inst_decode(di, 2048, 3071, inbuf, 1024, 1);
 *   srd_inst_decode(di, 3072, 4095, inbuf, 1024, 1);
 *
 * INCORRECT example (4096 samples total, 4 chunks @ 1024 samples each, but
 * the start- and end-samplenumbers are not absolute):
 *   srd_inst_decode(di, 0,    1023, inbuf, 1024, 1);
 *   srd_inst_decode(di, 0,    1023, inbuf, 1024, 1);
 *   srd_inst_decode(di, 0,    1023, inbuf, 1024, 1);
 *   srd_inst_decode(di, 0,    1023, inbuf, 1024, 1);
 *
 * @param di The decoder instance to call. Must not be NULL.
 * @param abs_start_samplenum The absolute starting sample number for the
 * 		buffer's sample set, relative to the start of capture.
 * @param abs_end_samplenum The absolute ending sample number for the
 * 		buffer's sample set, relative to the start of capture.
 * @param inbuf The buffer to decode. Must not be NULL.
 * @param inbuflen Length of the buffer. Must be > 0.
 * @param unitsize The number of bytes per sample. Must be > 0.
 *
 * @return SRD_OK upon success, a (negative) error code otherwise.
 *
 * @private
 */
SRD_PRIV int srd_inst_decode(struct srd_decoder_inst *di,
		uint64_t abs_start_samplenum, uint64_t abs_end_samplenum,
		const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize)
{
	PyObject *py_res;
	srd_logic *logic;
	long apiver;

	/* Return an error upon unusable input. */
	if (!di) {
		srd_dbg("empty decoder instance");
		return SRD_ERR_ARG;
	}
	if (!inbuf) {
		srd_dbg("NULL buffer pointer");
		return SRD_ERR_ARG;
	}
	if (inbuflen == 0) {
		srd_dbg("empty buffer");
		return SRD_ERR_ARG;
	}
	if (unitsize == 0) {
		srd_dbg("unitsize 0");
		return SRD_ERR_ARG;
	}

	di->data_unitsize = unitsize;

	srd_dbg("Decoding: abs start sample %" PRIu64 ", abs end sample %"
		PRIu64 " (%" PRIu64 " samples, %" PRIu64 " bytes, unitsize = "
		"%d), instance %s.", abs_start_samplenum, abs_end_samplenum,
		abs_end_samplenum - abs_start_samplenum, inbuflen, di->data_unitsize,
		di->inst_id);

	apiver = srd_decoder_apiver(di->decoder);

	if (apiver == 2) {
		/*
		 * Create new srd_logic object. Each iteration around the PD's
		 * loop will fill one sample into this object.
		 */
		logic = PyObject_New(srd_logic, (PyTypeObject *)srd_logic_type);
		Py_INCREF(logic);
		logic->di = (struct srd_decoder_inst *)di;
		logic->abs_start_samplenum = abs_start_samplenum;
		logic->itercnt = 0;
		logic->inbuf = (uint8_t *)inbuf;
		logic->inbuflen = inbuflen;
		logic->sample = PyList_New(2);
		Py_INCREF(logic->sample);

		Py_IncRef(di->py_inst);
		if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
			"KKO", abs_start_samplenum, abs_end_samplenum, logic))) {
			srd_exception_catch("Protocol decoder instance %s",
					di->inst_id);
			return SRD_ERR_PYTHON;
		}
		Py_DecRef(py_res);
	} else {
		/* If this is the first call, start the worker thread. */
		if (!di->thread_handle)
			di->thread_handle = g_thread_new("di_thread",
							 di_thread, di);

		/* Push the new sample chunk to the worker thread. */
		g_mutex_lock(&di->data_mutex);
		di->abs_start_samplenum = abs_start_samplenum;
		di->abs_end_samplenum = abs_end_samplenum;
		di->inbuf = inbuf;
		di->inbuflen = inbuflen;
		di->got_new_samples = TRUE;
		di->handled_all_samples = FALSE;

		/* Signal the thread that we have new data. */
		g_cond_signal(&di->got_new_samples_cond);
		g_mutex_unlock(&di->data_mutex);

		/* When all samples in this chunk were handled, return. */
		g_mutex_lock(&di->data_mutex);
		while (!di->handled_all_samples)
			g_cond_wait(&di->handled_all_samples_cond, &di->data_mutex);
		g_mutex_unlock(&di->data_mutex);
	}

	return SRD_OK;
}
Exemplo n.º 19
0
/* Creates a new records object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyevtx_records_new(
           pyevtx_file_t *file_object,
           PyObject* (*get_record_by_index)(
                        pyevtx_file_t *file_object,
                        int record_index ),
           int number_of_records )
{
	pyevtx_records_t *pyevtx_records = NULL;
	static char *function            = "pyevtx_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
	 */
	pyevtx_records = PyObject_New(
	                  struct pyevtx_records,
	                  &pyevtx_records_type_object );

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

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

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

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

	return( (PyObject *) pyevtx_records );

on_error:
	if( pyevtx_records != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyevtx_records );
	}
	return( NULL );
}
Exemplo n.º 20
0
/* Initializes the pyewf module
 */
PyMODINIT_FUNC initpyewf(
                void )
{
	PyObject *module                       = NULL;
	PyTypeObject *file_entries_type_object = NULL;
	PyTypeObject *file_entry_type_object   = NULL;
	PyTypeObject *handle_type_object       = NULL;
	PyGILState_STATE gil_state             = 0;

        /* Create the module
	 * This function must be called before grabbing the GIL
	 * otherwise the module will segfault on a version mismatch
	 */
	module = Py_InitModule3(
	          "pyewf",
	          pyewf_module_methods,
	          "Python libewf module (pyewf)." );

	PyEval_InitThreads();

	gil_state = PyGILState_Ensure();

	/* Setup the handle type object
	 */
	pyewf_handle_type_object.tp_new = PyType_GenericNew;

	if( PyType_Ready(
	     &pyewf_handle_type_object ) < 0 )
	{
		goto on_error;
	}
	Py_IncRef(
	 (PyObject * ) &pyewf_handle_type_object );

	handle_type_object = &pyewf_handle_type_object;

	PyModule_AddObject(
	 module,
	 "handle",
	 (PyObject *) handle_type_object );

	/* Setup the file entry type object
	 */
	pyewf_file_entry_type_object.tp_new = PyType_GenericNew;

	if( PyType_Ready(
	     &pyewf_file_entry_type_object ) < 0 )
	{
		goto on_error;
	}
	Py_IncRef(
	 (PyObject *) &pyewf_file_entry_type_object );

	file_entry_type_object = &pyewf_file_entry_type_object;

	PyModule_AddObject(
	 module,
	"file_entry",
	(PyObject *) file_entry_type_object );

	/* Setup the file entries type object
	 */
	pyewf_file_entries_type_object.tp_new = PyType_GenericNew;

	if( PyType_Ready(
	     &pyewf_file_entries_type_object ) < 0 )
	{
		goto on_error;
	}
	Py_IncRef(
	 (PyObject *) &pyewf_file_entries_type_object );

	file_entries_type_object = &pyewf_file_entries_type_object;

	PyModule_AddObject(
	 module,
	"_file_entries",
	(PyObject *) file_entries_type_object );

on_error:
	PyGILState_Release(
	 gil_state );
}
Exemplo n.º 21
0
/** Convert a TValue from the Delphi RTTI system to a PyObject*.
 *  \param V: The value to convert.
 *  \return New reference to a converted object.
 *  \throw EPyVclError if the conversion fails.
 */
PyObject* ToPyObject(const Rtti::TValue &V)
{
	Rtti::TValue &Value = const_cast<Rtti::TValue&>(V);
	if(Value.IsEmpty)
		Py_RETURN_NONE;
	switch(Value.Kind)
	{
		case tkInteger:
			return ToPyObject(Value.AsInteger());

		case tkUString:
		case tkString:
		case tkLString:
		case tkWString:
			return ToPyObject(Value.AsString());

		case tkEnumeration:
		{
			if(AnsiString(Value.TypeInfo->Name) == "Boolean")
				return ToPyObject(static_cast<bool>(Value.AsOrdinal()));
			TRttiEnumerationType *Type = static_cast<TRttiEnumerationType*>(Context.GetType(Value.TypeInfo));
			int Ordinal = Value.AsOrdinal();
			if(Ordinal >= Type->MinValue && Ordinal <= Type->MaxValue)
			  //GetEnumName() lacks range check
				return ToPyObject(GetEnumName(Value.TypeInfo, Ordinal));
			return ToPyObject("0x" + IntToHex(Ordinal, 2));
		}

		case tkClass:
			return VclObject_Create(Value.AsObject(), false);

		case tkSet:
			return ToPyObject(SetToString(Value.TypeInfo, *static_cast<int*>(Value.GetReferenceToRawData()), false));

		case tkChar:
			return ToPyObject(Value.AsType<char>());

		case tkWChar:
			return ToPyObject(Value.AsType<wchar_t>());

		case tkFloat:
			return ToPyObject(Value.AsExtended());

		case tkRecord:
		{
			void *Data = Value.GetReferenceToRawData();
			TRttiType *Type = Context.GetType(Value.TypeInfo);
			DynamicArray<TRttiField*> Fields = Type->GetFields();
			PyObject *Tuple = PyTuple_New(Fields.Length);
			for(int I = 0; I < Fields.Length; I++)
				PyTuple_SET_ITEM(Tuple, I, ToPyObject(Fields[I]->GetValue(Data)));
			return Tuple;
		}

		case tkMethod: //Event
		{
			TMethod Method;
			Value.ExtractRawDataNoCopy(&Method);
			if(Method.Code == NULL)
				Py_RETURN_NONE;
			TObject *Object = static_cast<TObject*>(Method.Data);
			if(TMethodImplementation *Impl = dynamic_cast<TMethodImplementation*>(Object))
			{
				PyObject *Result = static_cast<PyObject*>(Impl->FUserData);
				Py_IncRef(Result);
				return Result;
			}
			String Name = Object->MethodName(Method.Code);
			TRttiType *Type = Context.GetType(Object->ClassType());
			return VclMethod_Create(NULL, Object, Type->GetMethods(Name));
		}

		case tkInt64:
			return PyLong_FromLongLong(Value.AsInt64());

		case tkVariant:
		case tkArray:
		case tkInterface:
		case tkDynArray:
		case tkClassRef:
		case tkPointer:
		case tkProcedure:
		case tkUnknown:
		default:
			throw EPyVclError("Unable to convert type '" + AnsiString(Value.TypeInfo->Name) + "'");
	}
}
Exemplo n.º 22
0
/* Sets the keys
 * Returns a Python object if successful or NULL on error
 */
PyObject *pycaes_tweaked_context_set_keys(
           pycaes_tweaked_context_t *pycaes_context,
           PyObject *arguments,
           PyObject *keywords )
{
	libcerror_error_t *error          = NULL;
	PyObject *key_string_object       = NULL;
	PyObject *tweak_key_string_object = NULL;
	static char *function             = "pycaes_tweaked_context_set_key";
	static char *keyword_list[]       = { "mode", "key", "tweak_key", NULL };
	char *key_data                    = NULL;
	char *tweak_key_data              = NULL;
        Py_ssize_t key_data_size          = 0;
        Py_ssize_t tweak_key_data_size    = 0;
	int mode                          = 0;
	int result                        = 0;

	if( PyArg_ParseTupleAndKeywords(
	     arguments,
	     keywords,
	     "iOO",
	     keyword_list,
	     &mode,
	     &key_string_object,
	     &tweak_key_string_object ) == 0 )
	{
		return( NULL );
	}
#if PY_MAJOR_VERSION >= 3
	key_data = PyBytes_AsString(
	            key_string_object );

	key_data_size = PyBytes_Size(
	                 key_string_object );
#else
	key_data = PyString_AsString(
	            key_string_object );

	key_data_size = PyString_Size(
	                 key_string_object );
#endif
	if( ( key_data_size < 0 )
	 || ( key_data_size > (Py_ssize_t) ( SSIZE_MAX / 8 ) ) )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid argument key data size value out of bounds.",
		 function );

		return( NULL );
	}
#if PY_MAJOR_VERSION >= 3
	tweak_key_data = PyBytes_AsString(
	                  tweak_key_string_object );

	tweak_key_data_size = PyBytes_Size(
	                       tweak_key_string_object );
#else
	tweak_key_data = PyString_AsString(
	                  tweak_key_string_object );

	tweak_key_data_size = PyString_Size(
	                       tweak_key_string_object );
#endif
	if( ( tweak_key_data_size < 0 )
	 || ( tweak_key_data_size > (Py_ssize_t) ( SSIZE_MAX / 8 ) ) )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid argument tweak key data size value out of bounds.",
		 function );

		return( NULL );
	}
	Py_BEGIN_ALLOW_THREADS

	result = libcaes_tweaked_context_set_keys(
	          pycaes_context->context,
	          mode,
	          (uint8_t *) key_data,
	          (size_t) ( key_data_size * 8 ),
	          (uint8_t *) tweak_key_data,
	          (size_t) ( tweak_key_data_size * 8 ),
	          &error );

	Py_END_ALLOW_THREADS

	if( result != 1 )
	{
		pycaes_error_raise(
		 error,
		 PyExc_IOError,
		 "%s: unable to set keys.",
		 function );

		libcerror_error_free(
		 &error );

		return( NULL );
	}
	Py_IncRef(
	 Py_None );

	return( Py_None );
}
Exemplo n.º 23
0
/**
 * Decode a chunk of samples.
 *
 * @param di The decoder instance to call. Must not be NULL.
 * @param start_samplenum The starting sample number for the buffer's sample
 * 			  set, relative to the start of capture.
 * @param end_samplenum The ending sample number for the buffer's sample
 * 			  set, relative to the start of capture.
 * @param inbuf The buffer to decode. Must not be NULL.
 * @param inbuflen Length of the buffer. Must be > 0.
 * @param unitsize The number of bytes per sample. Must be > 0.
 *
 * @return SRD_OK upon success, a (negative) error code otherwise.
 *
 * @private
 */
SRD_PRIV int srd_inst_decode(const struct srd_decoder_inst *di,
		uint64_t start_samplenum, uint64_t end_samplenum,
		const uint8_t *inbuf, uint64_t inbuflen, uint64_t unitsize)
{
	PyObject *py_res;
	srd_logic *logic;
	long apiver;

	/* Return an error upon unusable input. */
	if (!di) {
		srd_dbg("empty decoder instance");
		return SRD_ERR_ARG;
	}
	if (!inbuf) {
		srd_dbg("NULL buffer pointer");
		return SRD_ERR_ARG;
	}
	if (inbuflen == 0) {
		srd_dbg("empty buffer");
		return SRD_ERR_ARG;
	}
	if (unitsize == 0) {
		srd_dbg("unitsize 0");
		return SRD_ERR_ARG;
	}

	((struct srd_decoder_inst *)di)->data_unitsize = unitsize;

	srd_dbg("Decoding: start sample %" PRIu64 ", end sample %"
		PRIu64 " (%" PRIu64 " samples, %" PRIu64 " bytes, unitsize = "
		"%d), instance %s.", start_samplenum, end_samplenum,
		end_samplenum - start_samplenum, inbuflen, di->data_unitsize,
		di->inst_id);

	apiver = srd_decoder_apiver(di->decoder);

	if (apiver == 2) {
		/*
		 * Create new srd_logic object. Each iteration around the PD's
		 * loop will fill one sample into this object.
		 */
		logic = PyObject_New(srd_logic, (PyTypeObject *)srd_logic_type);
		Py_INCREF(logic);
		logic->di = (struct srd_decoder_inst *)di;
		logic->start_samplenum = start_samplenum;
		logic->itercnt = 0;
		logic->inbuf = (uint8_t *)inbuf;
		logic->inbuflen = inbuflen;
		logic->sample = PyList_New(2);
		Py_INCREF(logic->sample);

		Py_IncRef(di->py_inst);
		if (!(py_res = PyObject_CallMethod(di->py_inst, "decode",
			"KKO", start_samplenum, end_samplenum, logic))) {
			srd_exception_catch("Protocol decoder instance %s",
					di->inst_id);
			return SRD_ERR_PYTHON;
		}
		Py_DecRef(py_res);
	}

	return SRD_OK;
}
Exemplo n.º 24
0
PyObject* DetailView::loadDetail(PyObject *dict)
{
    static QString nameFmt = "<span style=\" font-size:16pt; font-weight:600;\">%1</span> (rating: %2)";
    if (!PyDict_Check(dict))
    {
        PyErr_SetString(PyExc_TypeError, "The argument is not a dict.");
        return NULL;
    }

    PyObject *item;
    QString name;
    //name
    if (NULL != (item = PyDict_GetItemString(dict, "name")))
    {
        name = PyString_AsQString(item);
        setWindowTitle(name + tr(" - Detail page"));
    }

    //rating
    if (NULL != (item = PyDict_GetItemString(dict, "rating")))
        ui->nameLabel->setText(nameFmt.arg(name, QString::number(PyFloat_AsDouble(item))));
    else
        ui->nameLabel->setText(nameFmt.arg(name, tr("Unknown")));

    //length
    if (NULL != (item = PyDict_GetItemString(dict, "length")))
        ui->lengthLabel->setText(PyString_AsQString(item));
    else
        ui->lengthLabel->setText(tr("Unknown"));

    //summary
    if (NULL != (item = PyDict_GetItemString(dict, "summary")))
        ui->summaryLabel->setText(PyString_AsQString(item));
    else
        ui->summaryLabel->setText(tr("Unknown"));

    //others
    struct Item {const char *item_name; QLabel *label;};
    struct Item items[] = {
        {"directors", ui->directorLabel},
        {"script_writers", ui->scriptwriterLabel},
        {"players", ui->playerLabel},
        {"types", ui->typeLabel},
        {"nations", ui->nationLabel},
        {"languages", ui->langLabel},
        {"dates", ui->dateLabel},
        {"alt_names", ui->alternameLabel},
        {NULL, NULL}
    };
    for (struct Item *i = items; i->item_name; i++) {
        item = PyDict_GetItemString(dict, i->item_name);
        if (item) {
            QStringList list = PyList_AsQStringList(item);
            i->label->setText(list.join(" / ").simplified());
        }
        else
            i->label->setText(tr("Unknown"));
    }


    // Source
    ui->sourceListWidget->clear();
    urls.clear();
    item = PyDict_GetItemString(dict, "source");
    if (item)
    {
        int n = PyList_Size(item);
        for (int i = 0; i < n; i += 2)
        {
            QString name = PyString_AsQString(PyList_GetItem(item, i));
            const char *url = PyString_AsString(PyList_GetItem(item, i+1));
            ui->sourceListWidget->addItem(name);
            urls.append(url);
        }
    }

    // Image
    item = PyDict_GetItemString(dict, "image");
    if (item)
    {
        QNetworkRequest request(QUrl(PyString_AsQString(item)));
        request.setRawHeader("User-Agent", "moonplayer");
        reply = access_manager->get(request);
        connect(reply, SIGNAL(finished()), this, SLOT(onImageLoaded()));
    }
    Py_IncRef(Py_None);
    return Py_None;
}
Exemplo n.º 25
0
int API_resultRowValue(void *result, int column, UMTypeInfo *ti, char *value, size_t cbValue)
{
  PyObject *valobj = NULL;

  PRINTMARK();
  //fprintf (stderr, "%s: Got %p (%08x) %08x\n", __FUNCTION__, value, ti->type, cbValue);

  if (value == NULL)
  {
    valobj = Py_None;
    Py_IncRef(valobj);
  }
  else
  {

    switch (ti->type)
    {
      //PyNone:
    case MFTYPE_NULL:
      valobj = Py_None;
      Py_IncRef(valobj);
      break;

      // Use PyLong for "INT UNSIGNED".
    case MFTYPE_LONG:
      if(isUnsigned(ti->flags)){
        // XXX: No overflow detected.
        valobj = PyLong_FromLongLong(parseINT64 (value, ((char *) value) + cbValue));
        break;
      }
      // "INT" only, let it fall through to PyInt.

      //PyInt
    case MFTYPE_TINY:
    case MFTYPE_SHORT:
    case MFTYPE_INT24:
      {
        valobj = PyInt_FromLong(parseINT32 (value, ((char *) value) + cbValue));
        break;
      }

      //PyLong
    case MFTYPE_LONGLONG:
      {
        if(isUnsigned(ti->flags)){
          valobj = PyLong_FromUnsignedLongLong(parseUINT64 (value, ((char *) value) + cbValue));
        }else{
          valobj = PyLong_FromLongLong(parseINT64 (value, ((char *) value) + cbValue));
        }
        break;
      }

      //PyFloat
    case MFTYPE_FLOAT:
    case MFTYPE_DOUBLE:
      {
        //FIXME: Too f*****g slow
        PyObject *sobj = PyString_FromStringAndSize((char *) value, cbValue);
        valobj = PyFloat_FromString (sobj, NULL);
        Py_DECREF(sobj);
        break;
      }

    case MFTYPE_DATE:
      {
        int year;
        int month;
        int day;

        year = parseINT32 (value, value + 4);

        if (year < 1)
        {
          valobj = Py_None;
          Py_IncRef(valobj);
          break;
        }

        value += 5;
        month = parseINT32 (value, value + 2);
        value += 3;
        day = parseINT32 (value, value + 2);
        value += 3;

        valobj = PyDate_FromDate (year, month, day);
        break;
      }

    case MFTYPE_TIMESTAMP:
    case MFTYPE_DATETIME:
      {
        int year;
        int month;
        int day;
        int hour;
        int minute;
        int second;

        //9999-12-31 23:59:59
        char temp[20];
        memcpy (temp, value, cbValue);
        temp[cbValue] = '\0';

        year = parseINT32 (value, value + 4);
        value += 5;
        month = parseINT32 (value, value + 2);
        value += 3;
        day = parseINT32 (value, value + 2);
        value += 3;
        hour = parseINT32 (value, value + 2);
        value += 3;
        minute = parseINT32 (value, value + 2);
        value += 3;
        second = parseINT32 (value, value + 2);
        value += 3;

        if (year < 1)
        {
          valobj = Py_None;
          Py_IncRef(valobj);
          break;
        }


        valobj = PyDateTime_FromDateAndTime (year, month, day, hour, minute, second, 0);
        break;
      }

      // We ignore these

    case MFTYPE_TIME:
    case MFTYPE_YEAR:
    case MFTYPE_NEWDATE:
      // Fall through for string encoding

      //Blob goes as String
    case MFTYPE_TINY_BLOB:
    case MFTYPE_MEDIUM_BLOB:
    case MFTYPE_LONG_BLOB:
    case MFTYPE_BLOB:
      if (ti->flags & MFFLAG_BINARY_FLAG) {
        valobj = PyString_FromStringAndSize( (const char *) value, cbValue);
      } else {
        valobj = DecodeString (ti, value, cbValue);
      }
      break;

      //PyString family
    case MFTYPE_VAR_STRING:
    case MFTYPE_VARCHAR:
    case MFTYPE_STRING:
      valobj = DecodeString (ti, value, cbValue);
      break;

    case MFTYPE_ENUM:
    case MFTYPE_GEOMETRY:
    case MFTYPE_BIT:
    case MFTYPE_NEWDECIMAL:
    case MFTYPE_SET:
    case MFTYPE_DECIMAL:
      // Fall through for string encoding
      valobj = PyString_FromStringAndSize( (const char *) value, cbValue);
      break;

    }
  }

  if (valobj == NULL)
  {
    if (PyErr_Occurred())
    {
      return FALSE;
    }

    PyErr_Format (umysql_Error, "Unable to convert field of type %d", ti->type);
    return FALSE;
  }

  PyTuple_SET_ITEM(((ResultSet *)result)->currRow, column, valobj);
  PRINTMARK();

  return TRUE;
}
Exemplo n.º 26
0
/* Creates a new strings object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyevtx_strings_new(
           pyevtx_record_t *record_object,
           PyObject* (*get_string_by_index)(
                        pyevtx_record_t *record_object,
                        int string_index ),
           int number_of_strings )
{
	pyevtx_strings_t *pyevtx_strings = NULL;
	static char *function            = "pyevtx_strings_new";

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

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

		return( NULL );
	}
	/* Make sure the strings values are initialized
	 */
	pyevtx_strings = PyObject_New(
	                  struct pyevtx_strings,
	                  &pyevtx_strings_type_object );

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

		goto on_error;
	}
	if( pyevtx_strings_init(
	     pyevtx_strings ) != 0 )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize strings.",
		 function );

		goto on_error;
	}
	pyevtx_strings->record_object       = record_object;
	pyevtx_strings->get_string_by_index = get_string_by_index;
	pyevtx_strings->number_of_strings   = number_of_strings;

	Py_IncRef(
	 (PyObject *) pyevtx_strings->record_object );

	return( (PyObject *) pyevtx_strings );

on_error:
	if( pyevtx_strings != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyevtx_strings );
	}
	return( NULL );
}
Exemplo n.º 27
0
/* Creates a new blocks object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyvshadow_blocks_new(
           pyvshadow_store_t *store_object,
           PyObject* (*get_block_by_index)(
                        pyvshadow_store_t *store_object,
                        int block_index ),
           int number_of_blocks )
{
	pyvshadow_blocks_t *pyvshadow_blocks = NULL;
	static char *function                = "pyvshadow_blocks_new";

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

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

		return( NULL );
	}
	/* Make sure the blocks values are initialized
	 */
	pyvshadow_blocks = PyObject_New(
	                    struct pyvshadow_blocks,
	                    &pyvshadow_blocks_type_object );

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

		goto on_error;
	}
	if( pyvshadow_blocks_init(
	     pyvshadow_blocks ) != 0 )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize blocks.",
		 function );

		goto on_error;
	}
	pyvshadow_blocks->store_object       = store_object;
	pyvshadow_blocks->get_block_by_index = get_block_by_index;
	pyvshadow_blocks->number_of_blocks   = number_of_blocks;

	Py_IncRef(
	 (PyObject *) pyvshadow_blocks->store_object );

	return( (PyObject *) pyvshadow_blocks );

on_error:
	if( pyvshadow_blocks != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyvshadow_blocks );
	}
	return( NULL );
}
Exemplo n.º 28
0
/* Seeks a certain offset in the media data
 * Returns a Python object holding the offset if successful or NULL on error
 */
PyObject *pyewf_handle_seek_offset(
           pyewf_handle_t *pyewf_handle,
           PyObject *arguments,
           PyObject *keywords )
{
	char error_string[ PYEWF_ERROR_STRING_SIZE ];

	libcerror_error_t *error    = NULL;
	static char *function       = "pyewf_handle_seek_offset";
	static char *keyword_list[] = { "offset", "whence", NULL };
	off64_t offset              = 0;
	int whence                  = 0;

	if( pyewf_handle == NULL )
	{
		PyErr_Format(
		 PyExc_TypeError,
		 "%s: invalid pyewf handle.",
		 function );

		return( NULL );
	}
	if( PyArg_ParseTupleAndKeywords(
	     arguments,
	     keywords,
	     "L|i",
	     keyword_list, 
	     &offset,
	     &whence ) == 0 )
	{
		return( NULL );
	}
	Py_BEGIN_ALLOW_THREADS

	offset = libewf_handle_seek_offset(
	          pyewf_handle->handle,
	          offset,
	          whence,
	          &error );

	Py_END_ALLOW_THREADS

 	if( offset == -1 )
	{
		if( libcerror_error_backtrace_sprint(
		     error,
		     error_string,
		     PYEWF_ERROR_STRING_SIZE ) == -1 )
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to seek offset.",
			 function );
		}
		else
		{
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to seek offset.\n%s",
			 function,
			 error_string );
		}
		libcerror_error_free(
		 &error );

		return( NULL );
	}
	Py_IncRef(
	 Py_None );

	return( Py_None );
}
Exemplo n.º 29
0
/* Creates a new file entries object
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyewf_file_entries_new(
           pyewf_file_entry_t *file_entry_object,
           PyObject* (*get_sub_file_entry_by_index)(
                        pyewf_file_entry_t *file_entry_object,
                        int sub_file_entry_index ),
           int number_of_sub_file_entries )
{
	pyewf_file_entries_t *pyewf_file_entries = NULL;
	static char *function                    = "pyewf_file_entries_new";

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

		return( NULL );
	}
	if( get_sub_file_entry_by_index == NULL )
	{
		PyErr_Format(
		 PyExc_ValueError,
		 "%s: invalid get sub file entry by index function.",
		 function );

		return( NULL );
	}
	/* Make sure the file entries values are initialized
	 */
	pyewf_file_entries = PyObject_New(
	                      struct pyewf_file_entries,
	                      &pyewf_file_entries_type_object );

	if( pyewf_file_entries == NULL )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize file entries.",
		 function );

		goto on_error;
	}
	if( pyewf_file_entries_init(
	     pyewf_file_entries ) != 0 )
	{
		PyErr_Format(
		 PyExc_MemoryError,
		 "%s: unable to initialize file entries.",
		 function );

		goto on_error;
	}
	pyewf_file_entries->file_entry_object           = file_entry_object;
	pyewf_file_entries->get_sub_file_entry_by_index = get_sub_file_entry_by_index;
	pyewf_file_entries->number_of_sub_file_entries  = number_of_sub_file_entries;

	Py_IncRef(
	 (PyObject *) pyewf_file_entries->file_entry_object );

	return( (PyObject *) pyewf_file_entries );

on_error:
	if( pyewf_file_entries != NULL )
	{
		Py_DecRef(
		 (PyObject *) pyewf_file_entries );
	}
	return( NULL );
}
Exemplo n.º 30
0
/* Retrieves the name
 * Returns a Python object if successful or NULL on error
 */
PyObject *pyewf_file_entry_get_name(
           pyewf_file_entry_t *pyewf_file_entry )
{
	char error_string[ PYEWF_ERROR_STRING_SIZE ];

	libcerror_error_t *error  = NULL;
	PyObject *string_object   = NULL;
	const char *errors        = NULL;
	uint8_t *name             = NULL;
	static char *function     = "pyewf_file_entry_get_name";
	size_t name_size          = 0;
	int result                = 0;

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

		return( NULL );
	}
	Py_BEGIN_ALLOW_THREADS

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

	Py_END_ALLOW_THREADS

	if( result == -1 )
	{
		if( libcerror_error_backtrace_sprint(
		     error,
		     error_string,
		     PYEWF_ERROR_STRING_SIZE ) == -1 )
                {
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to retrieve name size.",
			 function );
		}
		else
                {
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to retrieve name size.\n%s",
			 function,
			 error_string );
		}
		libcerror_error_free(
		 &error );

		goto on_error;
	}
	else if( ( result == 0 )
	      || ( name_size == 0 ) )
	{
		Py_IncRef(
		 Py_None );

		return( Py_None );
	}
	name = (uint8_t *) PyMem_Malloc(
	                    sizeof( uint8_t ) * name_size );

	if( name == NULL )
	{
		PyErr_Format(
		 PyExc_IOError,
		 "%s: unable to create name.",
		 function );

		goto on_error;
	}
	Py_BEGIN_ALLOW_THREADS

	result = libewf_file_entry_get_utf8_name(
		  pyewf_file_entry->file_entry,
		  name,
		  name_size,
		  &error );

	Py_END_ALLOW_THREADS

	if( result != 1 )
	{
		if( libcerror_error_backtrace_sprint(
		     error,
		     error_string,
		     PYEWF_ERROR_STRING_SIZE ) == -1 )
                {
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to retrieve name.",
			 function );
		}
		else
                {
			PyErr_Format(
			 PyExc_IOError,
			 "%s: unable to retrieve name.\n%s",
			 function,
			 error_string );
		}
		libcerror_error_free(
		 &error );

		goto on_error;
	}
	/* Pass the string length to PyUnicode_DecodeUTF8
	 * otherwise it makes the end of string character is part
	 * of the string
	 */
	string_object = PyUnicode_DecodeUTF8(
			 (char *) name,
			 (Py_ssize_t) name_size - 1,
			 errors );

	PyMem_Free(
	 name );

	return( string_object );

on_error:
	if( name != NULL )
	{
		PyMem_Free(
		 name );
	}
	return( NULL );
}