/* Retrieves the current offset within the file object
 * Make sure to hold the GIL state before calling this function
 * Returns 1 if successful or -1 on error
 */
int pyolecf_file_object_get_offset(
     PyObject *file_object,
     off64_t *offset,
     libcerror_error_t **error )
{
	PyObject *method_name   = NULL;
	PyObject *method_result = NULL;
	static char *function   = "pyolecf_file_object_get_offset";
	int result              = 0;

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

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

		return( -1 );
	}
#if PY_MAJOR_VERSION >= 3
	method_name = PyUnicode_FromString(
	               "get_offset" );
#else
	method_name = PyString_FromString(
	               "get_offset" );
#endif
	PyErr_Clear();

	/* Determine if the file object has the get_offset method
	 */
	result = PyObject_HasAttr(
	          file_object,
	          method_name );

	if( result == 0 )
	{
		Py_DecRef(
		 method_name );

		/* Fall back to the tell method
		 */
#if PY_MAJOR_VERSION >= 3
		method_name = PyUnicode_FromString(
		               "tell" );
#else
		method_name = PyString_FromString(
		               "tell" );
#endif
	}
	PyErr_Clear();

	method_result = PyObject_CallMethodObjArgs(
	                 file_object,
	                 method_name,
	                 NULL );

	if( PyErr_Occurred() )
	{
		pyolecf_error_fetch(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
		 "%s: unable to retrieve current offset in file object.",
		 function );

		goto on_error;
	}
	if( method_result == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_VALUE_MISSING,
		 "%s: missing method result.",
		 function );

		goto on_error;
	}
	if( pyolecf_integer_signed_copy_to_64bit(
	     method_result,
	     offset,
	     error ) != 1 )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
		 "%s: unable to convert method result into current offset of file object.",
		 function );

		goto on_error;
	}
	Py_DecRef(
	 method_result );

	Py_DecRef(
	 method_name );

	return( 1 );

on_error:
	if( method_result != NULL )
	{
		Py_DecRef(
		 method_result );
	}
	if( method_name != NULL )
	{
		Py_DecRef(
		 method_name );
	}
	return( -1 );
}
/* Retrieves the file size
 * Returns 1 if successful or -1 on error
 */
int pyolecf_file_object_io_handle_get_size(
     pyolecf_file_object_io_handle_t *file_object_io_handle,
     size64_t *size,
     libcerror_error_t **error )
{
	PyObject *method_name      = NULL;
	static char *function      = "pyolecf_file_object_io_handle_get_size";
	off64_t current_offset     = 0;
	PyGILState_STATE gil_state = 0;
	int result                 = 0;

	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->file_object == NULL )
	{
		libcerror_error_set(
		 error,
		 LIBCERROR_ERROR_DOMAIN_RUNTIME,
		 LIBCERROR_RUNTIME_ERROR_VALUE_MISSING,
		 "%s: invalid file object IO handle - missing file object.",
		 function );

		return( -1 );
	}
	gil_state = PyGILState_Ensure();

#if PY_MAJOR_VERSION >= 3
	method_name = PyUnicode_FromString(
	               "get_size" );
#else
	method_name = PyString_FromString(
	               "get_size" );
#endif
	PyErr_Clear();

	/* Determine if the file object has the get_size method
	 */
	result = PyObject_HasAttr(
	          file_object_io_handle->file_object,
	          method_name );

	if( result != 0 )
	{
		if( pyolecf_file_object_get_size(
		     file_object_io_handle->file_object,
		     size,
		     error ) != 1 )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_RUNTIME,
			 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
			 "%s: unable to retrieve size of file object.",
			 function );

			goto on_error;
		}
	}
	else
	{
		if( pyolecf_file_object_get_offset(
		     file_object_io_handle->file_object,
		     &current_offset,
		     error ) != 1 )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_RUNTIME,
			 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
			 "%s: unable to retrieve current offset in file object.",
			 function );

			goto on_error;
		}
		if( pyolecf_file_object_seek_offset(
		     file_object_io_handle->file_object,
		     0,
		     SEEK_END,
		     error ) != 1 )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_IO,
			 LIBCERROR_IO_ERROR_SEEK_FAILED,
			 "%s: unable to seek end of file object.",
			 function );

			goto on_error;
		}
		if( pyolecf_file_object_get_offset(
		     file_object_io_handle->file_object,
		     (off64_t *) size,
		     error ) != 1 )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_RUNTIME,
			 LIBCERROR_RUNTIME_ERROR_GET_FAILED,
			 "%s: unable to retrieve end offset in file object.",
			 function );

			pyolecf_file_object_seek_offset(
			 file_object_io_handle->file_object,
			 current_offset,
			 SEEK_SET,
			 NULL );

			goto on_error;
		}
		if( pyolecf_file_object_seek_offset(
		     file_object_io_handle->file_object,
		     current_offset,
		     SEEK_SET,
		     error ) != 1 )
		{
			libcerror_error_set(
			 error,
			 LIBCERROR_ERROR_DOMAIN_IO,
			 LIBCERROR_IO_ERROR_SEEK_FAILED,
			 "%s: unable to seek current offset in file object.",
			 function );

			goto on_error;
		}
	}
	Py_DecRef(
	 method_name );

	PyGILState_Release(
	 gil_state );

	return( 1 );

on_error:
	if( method_name != NULL )
	{
		Py_DecRef(
		 method_name );
	}
	PyGILState_Release(
	 gil_state );

	return( 1 );
}
Example #3
0
/* Helper for gdbpy_apply_val_pretty_printer that formats children of the
   printer, if any exist.  If is_py_none is true, then nothing has
   been printed by to_string, and format output accordingly. */
static void
print_children (PyObject *printer, const char *hint,
		struct ui_file *stream, int recurse,
		const struct value_print_options *options,
		const struct language_defn *language,
		int is_py_none)
{
  int is_map, is_array, done_flag, pretty;
  unsigned int i;

  if (! PyObject_HasAttr (printer, gdbpy_children_cst))
    return;

  /* If we are printing a map or an array, we want some special
     formatting.  */
  is_map = hint && ! strcmp (hint, "map");
  is_array = hint && ! strcmp (hint, "array");

  gdbpy_ref<> children (PyObject_CallMethodObjArgs (printer, gdbpy_children_cst,
						    NULL));
  if (children == NULL)
    {
      print_stack_unless_memory_error (stream);
      return;
    }

  gdbpy_ref<> iter (PyObject_GetIter (children.get ()));
  if (iter == NULL)
    {
      print_stack_unless_memory_error (stream);
      return;
    }

  /* Use the prettyformat_arrays option if we are printing an array,
     and the pretty option otherwise.  */
  if (is_array)
    pretty = options->prettyformat_arrays;
  else
    {
      if (options->prettyformat == Val_prettyformat)
	pretty = 1;
      else
	pretty = options->prettyformat_structs;
    }

  /* Manufacture a dummy Python frame to work around Python 2.4 bug,
     where it insists on having a non-NULL tstate->frame when
     a generator is called.  */
#ifndef IS_PY3K
  dummy_python_frame frame;
  if (frame.failed ())
    {
      gdbpy_print_stack ();
      return;
    }
#endif

  done_flag = 0;
  for (i = 0; i < options->print_max; ++i)
    {
      PyObject *py_v;
      const char *name;

      gdbpy_ref<> item (PyIter_Next (iter.get ()));
      if (item == NULL)
	{
	  if (PyErr_Occurred ())
	    print_stack_unless_memory_error (stream);
	  /* Set a flag so we can know whether we printed all the
	     available elements.  */
	  else	
	    done_flag = 1;
	  break;
	}

      if (! PyTuple_Check (item.get ()) || PyTuple_Size (item.get ()) != 2)
	{
	  PyErr_SetString (PyExc_TypeError,
			   _("Result of children iterator not a tuple"
			     " of two elements."));
	  gdbpy_print_stack ();
	  continue;
	}
      if (! PyArg_ParseTuple (item.get (), "sO", &name, &py_v))
	{
	  /* The user won't necessarily get a stack trace here, so provide
	     more context.  */
	  if (gdbpy_print_python_errors_p ())
	    fprintf_unfiltered (gdb_stderr,
				_("Bad result from children iterator.\n"));
	  gdbpy_print_stack ();
	  continue;
	}

      /* Print initial "{".  For other elements, there are three
	 cases:
	 1. Maps.  Print a "," after each value element.
	 2. Arrays.  Always print a ",".
	 3. Other.  Always print a ",".  */
      if (i == 0)
	{
         if (is_py_none)
           fputs_filtered ("{", stream);
         else
           fputs_filtered (" = {", stream);
       }

      else if (! is_map || i % 2 == 0)
	fputs_filtered (pretty ? "," : ", ", stream);

      /* In summary mode, we just want to print "= {...}" if there is
	 a value.  */
      if (options->summary)
	{
	  /* This increment tricks the post-loop logic to print what
	     we want.  */
	  ++i;
	  /* Likewise.  */
	  pretty = 0;
	  break;
	}

      if (! is_map || i % 2 == 0)
	{
	  if (pretty)
	    {
	      fputs_filtered ("\n", stream);
	      print_spaces_filtered (2 + 2 * recurse, stream);
	    }
	  else
	    wrap_here (n_spaces (2 + 2 *recurse));
	}

      if (is_map && i % 2 == 0)
	fputs_filtered ("[", stream);
      else if (is_array)
	{
	  /* We print the index, not whatever the child method
	     returned as the name.  */
	  if (options->print_array_indexes)
	    fprintf_filtered (stream, "[%d] = ", i);
	}
      else if (! is_map)
	{
	  fputs_filtered (name, stream);
	  fputs_filtered (" = ", stream);
	}

      if (gdbpy_is_lazy_string (py_v))
	{
	  CORE_ADDR addr;
	  struct type *type;
	  long length;
	  gdb::unique_xmalloc_ptr<char> encoding;
	  struct value_print_options local_opts = *options;

	  gdbpy_extract_lazy_string (py_v, &addr, &type, &length, &encoding);

	  local_opts.addressprint = 0;
	  val_print_string (type, encoding.get (), addr, (int) length, stream,
			    &local_opts);
	}
      else if (gdbpy_is_string (py_v))
	{
	  gdb::unique_xmalloc_ptr<char> output;

	  output = python_string_to_host_string (py_v);
	  if (!output)
	    gdbpy_print_stack ();
	  else
	    fputs_filtered (output.get (), stream);
	}
      else
	{
	  struct value *value = convert_value_from_python (py_v);

	  if (value == NULL)
	    {
	      gdbpy_print_stack ();
	      error (_("Error while executing Python code."));
	    }
	  else
	    common_val_print (value, stream, recurse + 1, options, language);
	}

      if (is_map && i % 2 == 0)
	fputs_filtered ("] = ", stream);
    }

  if (i)
    {
      if (!done_flag)
	{
	  if (pretty)
	    {
	      fputs_filtered ("\n", stream);
	      print_spaces_filtered (2 + 2 * recurse, stream);
	    }
	  fputs_filtered ("...", stream);
	}
      if (pretty)
	{
	  fputs_filtered ("\n", stream);
	  print_spaces_filtered (2 * recurse, stream);
	}
      fputs_filtered ("}", stream);
    }
}
Example #4
0
bool PythonTransform::loadModuleAttributes()
{
    if (pModule == NULL) {
        Q_EMIT error(tr("The module object is NULL for %1, could not (re)load the configuration").arg(moduleFileName),id);
        return false;
    }

    qDebug() << "Loading module attributes" << moduleName;

    bool ret = true;
    bool oldtwoWays = twoWays;
    twoWays = false; // setting default

    PyGILState_STATE lgstate;
    lgstate = PyGILState_Ensure();

    // checking if the two ways attribute is there
    PyObject * twoWayAttr = PyUnicode_FromString(ISTWOWAY_ATTR_NAME); // New ref
    if (pythonmgm->checkPyError()) {
        if (PyObject_HasAttr(pModule,twoWayAttr) == 1) {  // does the module has the attribute?
            PyObject * pyTwoWay = PyObject_GetAttr(pModule,twoWayAttr); // New ref
            if (pythonmgm->checkPyError()) {
                twoWays =  pyTwoWay == Py_True;
            } else {
                logError(tr("T_T Error while getting attribute value ISTWOWAY_ATTR_NAME for %1:\n%2").arg(moduleFileName).arg(pythonmgm->getLastError()),id);
            }
            Py_XDECREF(pyTwoWay);
        } else {
            qDebug() << moduleFileName << "has no attribute" << ISTWOWAY_ATTR_NAME;
        }
    } else {
        logError(tr("T_T Error while converting to Unicode string:\n%1").arg(pythonmgm->getLastError()),id);
    }
    Py_XDECREF(twoWayAttr);

    bool parametersChanged = false;
    // checking if some default parameters names were defined
    PyObject * paramsNamesAttr = PyUnicode_FromString(PARAMS_NAMES_ATTR_NAME); // New ref
    if (pythonmgm->checkPyError()) {
        if (PyObject_HasAttr(pModule,paramsNamesAttr) == 1) { // does the module has the attribute?
            PyObject * pyNamesList = PyObject_GetAttr(pModule,paramsNamesAttr); // New ref
            if (pythonmgm->checkPyError()) {
                if (PyList_Check(pyNamesList)) {
                    Py_ssize_t listSize = PyList_Size(pyNamesList);
                    if (listSize > 0) { // if list size is null then nothing to do
                        for (int i = 0; i < listSize; i++) {
                            QByteArray val;
                            PyObject *pyName = PyList_GetItem(pyNamesList, i); // borrowed ref
                            if (pythonmgm->checkPyError()) { // error or invalid?
#ifdef BUILD_PYTHON_3
                                if (PyUnicode_Check(pyName)) { // is this a unicode string?
                                    PyObject * nameutf8 = PyUnicode_AsUTF8String(pyName); // new ref
                                    if (pythonmgm->checkPyError() && nameutf8 != NULL) {
                                        val = QByteArray(PyBytes_AsString(nameutf8), PyBytes_Size(nameutf8));
                                    } else {
                                        logError(tr("Error while encoding a parameter to UTF-8:%1").arg(pythonmgm->getLastError()),id);
                                    }
                                    Py_XDECREF(nameutf8);
#else
                                if (PyString_Check(pyName)) { // is this a string?
                                    val = QByteArray(PyString_AsString(pyName), PyString_Size(pyName));
#endif
                                    if (val.isEmpty()) { // if the parameter name is empty, we skip
                                        logWarning(tr("The Python object %1[%2] is an empty string, ignoring.").arg(PARAMS_NAMES_ATTR_NAME).arg(i),id);
                                    } else if (!parameters.contains(val)) { // we don't want to erase any pre-existing configuration
                                        parameters.insert(val, QByteArray());
                                        parametersChanged = true;
                                    }
                                } else {
                                    logWarning(tr("The Python object %1[%2] is not a string, ignoring.").arg(PARAMS_NAMES_ATTR_NAME).arg(i),id);
                                }
                            } else {
                                logError(tr("T_T Error while getting the item from attribute list:\n%1").arg(pythonmgm->getLastError()),id);
                            }
                        }
                    } else {
                        logWarning(tr("The Python object for attribute names (%1) is empty, ignoring.").arg(PARAMS_NAMES_ATTR_NAME),id);
                    }
                } else {
                    logWarning(tr("The Python object for attribute names (%1) is not a list, ignoring.").arg(PARAMS_NAMES_ATTR_NAME),id);
                }

            } else {
Example #5
0
static void mip_callback(glp_tree *tree, void *info)
{
	struct mip_callback_object *obj = (struct mip_callback_object *)info;
	PyObject *method_name = NULL;
	// Choose the method name for the callback object that is appropriate.
	switch (glp_ios_reason(tree)) {
#if GLPK_VERSION(4, 21)
	case GLP_ISELECT:
		method_name = PyString_FromString("select");
		break;
	case GLP_IPREPRO:
		method_name = PyString_FromString("prepro");
		break;
	case GLP_IBRANCH:
		method_name = PyString_FromString("branch");
		break;
#endif
	case GLP_IROWGEN:
		method_name = PyString_FromString("rowgen");
		break;
	case GLP_IHEUR:
		method_name = PyString_FromString("heur");
		break;
	case GLP_ICUTGEN:
		method_name = PyString_FromString("cutgen");
		break;
	case GLP_IBINGO:
		method_name = PyString_FromString("bingo");
		break;
	default:
		// This should never happen.
		PyErr_SetString(PyExc_RuntimeError, "unrecognized reason for callback");
		glp_ios_terminate(tree);
		return;
	}
	// If there is no method with that name.
	if (!PyObject_HasAttr(obj->callback, method_name)) {
		Py_DECREF(method_name);
		method_name=PyString_FromString("default");
		if (!PyObject_HasAttr(obj->callback, method_name)) {
			Py_DECREF(method_name);
			method_name = NULL;
			return;
		}
	}
	// Try calling the method.
	TreeObject *py_tree = Tree_New(tree, obj->py_lp);
	if (py_tree == NULL) {
		Py_DECREF(method_name);
		glp_ios_terminate(tree);
		return;
	}
	PyObject *retval = NULL;
	retval = PyObject_CallMethodObjArgs(obj->callback, method_name, py_tree, NULL);
	py_tree->tree = NULL; // Invalidate the Tree object.
	Py_DECREF(py_tree);
	Py_XDECREF(method_name);
	if (retval == NULL) {
		/* This could have failed for any number of reasons. Perhaps the
		 * code within the method failed, perhaps the method does not
		 * accept the tree argument, or perhaps the 'method' is not
		 * really even a callable method at all.
		 */
		glp_ios_terminate(tree);
		return;
	}
	Py_DECREF(retval);
}
static PyObject *
providedBy(PyObject *ignored, PyObject *ob)
{
  PyObject *result, *cls, *cp;
  
  result = PyObject_GetAttr(ob, str__providedBy__);
  if (result == NULL)
    {
      PyErr_Clear();
      return getObjectSpecification(NULL, ob);
    } 


  /* We want to make sure we have a spec. We can't do a type check
     because we may have a proxy, so we'll just try to get the
     only attribute.
  */
  if (PyObject_TypeCheck(result, &SpecType)
      || 
      PyObject_HasAttr(result, strextends)
      )
    return result;
    
  /*
    The object's class doesn't understand descriptors.
    Sigh. We need to get an object descriptor, but we have to be
    careful.  We want to use the instance's __provides__,l if
    there is one, but only if it didn't come from the class.
  */
  Py_DECREF(result);

  cls = PyObject_GetAttr(ob, str__class__);
  if (cls == NULL)
    return NULL;

  result = PyObject_GetAttr(ob, str__provides__);
  if (result == NULL)
    {      
      /* No __provides__, so just fall back to implementedBy */
      PyErr_Clear();
      result = implementedBy(NULL, cls);
      Py_DECREF(cls);
      return result;
    } 

  cp = PyObject_GetAttr(cls, str__provides__);
  if (cp == NULL)
    {
      /* The the class has no provides, assume we're done: */
      PyErr_Clear();
      Py_DECREF(cls);
      return result;
    }

  if (cp == result)
    {
      /*
        Oops, we got the provides from the class. This means
        the object doesn't have it's own. We should use implementedBy
      */
      Py_DECREF(result);
      result = implementedBy(NULL, cls);
    }

  Py_DECREF(cls);
  Py_DECREF(cp);

  return result;
}
Example #7
0
static int
ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, int buflen,
		int recursive)
{
	int i;

	if (!PyObject_HasAttrString(mod, "__path__"))
		return 1;

	for (i = 0; ; i++) {
		PyObject *item = PySequence_GetItem(fromlist, i);
		int hasit;
		if (item == NULL) {
			if (PyErr_ExceptionMatches(PyExc_IndexError)) {
				PyErr_Clear();
				return 1;
			}
			return 0;
		}
		if (!PyString_Check(item)) {
			PyErr_SetString(PyExc_TypeError,
					"Item in ``from list'' not a string");
			Py_DECREF(item);
			return 0;
		}
		if (PyString_AS_STRING(item)[0] == '*') {
			PyObject *all;
			Py_DECREF(item);
			/* See if the package defines __all__ */
			if (recursive)
				continue; /* Avoid endless recursion */
			all = PyObject_GetAttrString(mod, "__all__");
			if (all == NULL)
				PyErr_Clear();
			else {
				if (!ensure_fromlist(mod, all, buf, buflen, 1))
					return 0;
				Py_DECREF(all);
			}
			continue;
		}
		hasit = PyObject_HasAttr(mod, item);
		if (!hasit) {
			char *subname = PyString_AS_STRING(item);
			PyObject *submod;
			char *p;
			if (buflen + strlen(subname) >= MAXPATHLEN) {
				PyErr_SetString(PyExc_ValueError,
						"Module name too long");
				Py_DECREF(item);
				return 0;
			}
			p = buf + buflen;
			*p++ = '.';
			strcpy(p, subname);
			submod = import_submodule(mod, subname, buf);
			Py_XDECREF(submod);
			if (submod == NULL) {
				Py_DECREF(item);
				return 0;
			}
		}
		Py_DECREF(item);
	}

	/* NOTREACHED */
}