Exemple #1
0
static PyObject*
pending_and_restore(PyObject *self, PyObject *arg)
{
    if (sigpending(&pendmask) != 0) {
        Py_Exit(1);
    }
    if (sigprocmask(SIG_SETMASK, &oldmask, NULL) != 0) {
        Py_Exit(1);
    }

    Py_RETURN_NONE;
}
void        init_struct_model(SAMPLE sample, STRUCTMODEL *sm, 
			      STRUCT_LEARN_PARM *sparm, LEARN_PARM *lparm, 
			      KERNEL_PARM *kparm)
{
  /* Initialize structmodel sm. The weight vector w does not need to
     be initialized, but you need to provide the maximum size of the
     feature space in sizePsi. This is the maximum number of different
     weights that can be learned. Later, the weight vector w will
     contain the learned weights for the model. */
  PyObject *pFunc, *pValue;
  // Make sure these are not invalid values.
  sm->sizePsi=-1; /* replace by appropriate number of features */
  sm->lin_reduce = 1;
  sm->pydict = (void*)PyDict_New();
  sm->w = NULL;
  sm->svm_model = NULL;
  // Call the relevant Python function.
  pFunc = getFunction(PYTHON_INIT_MODEL);
  pValue = PyObject_CallFunction(pFunc, "NNN", Sample_FromSample(sample),
				 StructModel_FromStructModel(sm),
				 Sparm_FromSparm(sparm));
  PY_RUNCHECK;
  Py_DECREF(pValue);

  if (sm->sizePsi < 0) {
    fprintf(stderr, "%s did not specify sm.size_psi\n", PYTHON_INIT_MODEL);
    Py_Exit(1);
  }
}
static PyObject *
MatrixPointer_setY(MatrixPointer *self, PyObject *arg)
{
	PyObject *tmp, *streamtmp;
	
	if (arg == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	}
    
	int isNumber = PyNumber_Check(arg);
	if (isNumber == 1) {
		PySys_WriteStderr("MatrixPointer y attributes must be a PyoObject.\n");
        if (PyInt_AsLong(PyObject_CallMethod(self->server, "getIsBooted", NULL))) {
            PyObject_CallMethod(self->server, "shutdown", NULL);
        }
        Py_Exit(1);
	}
	
	tmp = arg;
	Py_INCREF(tmp);
	Py_XDECREF(self->y);
    
    self->y = tmp;
    streamtmp = PyObject_CallMethod((PyObject *)self->y, "_getStream", NULL);
    Py_INCREF(streamtmp);
    Py_XDECREF(self->y_stream);
    self->y_stream = (Stream *)streamtmp;
    
	Py_INCREF(Py_None);
	return Py_None;
}	
STRUCTMODEL read_struct_model(char *file, STRUCT_LEARN_PARM *sparm)
{
  /* Reads structural model sm from file file. This function is used
     only in the prediction module, not in the learning module. */

  PyObject *pFunc, *pValue;
  
  // This is our first opportunity to initialize the structured
  // learning parameter object.
  bzero(sparm, sizeof(STRUCT_LEARN_PARM));
  sparm->pydict = (void*)PyDict_New();
  // Try to get the Python reading file.
  pFunc = getFunction(PYTHON_READ_MODEL);
  // We have a function!  Call the deserialization procedure.
  pValue = PyObject_CallFunction(pFunc, "sN", file, Sparm_FromSparm(sparm));
  PY_RUNCHECK;

  // No matter how we got it, we have some sort of object.
  if (!StructModel_Check(pValue)) {
    fprintf(stderr, "%s did not return a %s!\n", PYTHON_READ_MODEL,
	    svms_StructModelType.tp_name);
    Py_DECREF(pValue);
    Py_Exit(1);
  }
  // Now, we know we retrieved some sort of structure model.
  svms_StructModelObject *smo = (svms_StructModelObject*)pValue;
  smo->ifree = 0;
  STRUCTMODEL *sm = smo->sm;
  Py_XDECREF(pValue);
  return *sm; // We are leaking, yes, but relatively little, and only once...
}
Exemple #5
0
PyMODINIT_FUNC
initfltime(void)
{
    PyObject *m;
    
    event_module = ImportModule("flamingo.event");
    if (event_module == NULL)
        Py_Exit(0);
        
    POST = PyObject_GetAttrString(event_module, "post");
    if (POST == NULL)
        return;
    
    ACTIVE_TIMERS = PyList_New(0);
    if (ACTIVE_TIMERS == NULL)
        return;

    if (PyType_Ready(&Clock_Type) < 0)
        return;
    if (PyType_Ready(&Timer_Type) < 0)
        return;

    m = Py_InitModule3("fltime", fltime_methods, NULL);
    if (m == NULL)
        return;

    Py_INCREF(&Clock_Type);
    PyModule_AddObject(m, "Clock", (PyObject *)&Clock_Type);
    Py_INCREF(&Timer_Type);
    PyModule_AddObject(m, "Timer", (PyObject *)&Timer_Type);
    
    Py_DECREF(event_module);
}
SAMPLE      read_struct_examples(char *file, STRUCT_LEARN_PARM *sparm)
{
  /* Reads struct examples and returns them in sample. The number of
     examples must be written into sample.n */
  SAMPLE   sample;  /* sample */
  EXAMPLE  *examples;
  PyObject *pFunc,*pValue,*pSeq;
  int i;

  // Call the relevant Python function.
  pFunc = getFunction(PYTHON_READ_EXAMPLES);
  pValue = PyObject_CallFunction(pFunc, "sN", file, Sparm_FromSparm(sparm));

  PY_RUNCHECK;
  
  // Convert this into a sequence.
  pSeq = PySequence_Fast(pValue, "examples not a sequence");
  Py_DECREF(pValue);
  if (pSeq == NULL) {
    PyErr_Print();
    Py_Exit(1);
  }

  // Read the examples from the sequence.
  sample.n = PySequence_Size(pSeq);
  examples=(EXAMPLE *)my_malloc(sizeof(EXAMPLE)*sample.n);
  for (i=0; i<sample.n; ++i) {
    PyObject *pExample = PySequence_Fast_GET_ITEM(pSeq, i);
    if (!pExample || !PySequence_Check(pExample) ||
        PySequence_Size(pExample)<2){
      fprintf(stderr, "%s's item %d is not a sequence element of "
              "at least two items!\n", PYTHON_READ_EXAMPLES, i);
      free(examples);
      Py_DECREF(pSeq);
      Py_Exit(1);
    }
    examples[i].x.py_x = PySequence_GetItem(pExample, 0);
    examples[i].y.py_y = PySequence_GetItem(pExample, 1);
    Py_DECREF(pExample);
  }
  Py_DECREF(pSeq);

  /* fill in your code here */
  sample.examples=examples;
  return(sample);
}
void
NS(ProcessExit) (
  int num
)
{
//MqDLogX(context,__func__,0,"self<%p>, refCount<%li>\n", context->self, ((PyObject*)context->self)->ob_refcnt);
  Py_Exit(num);
}
Exemple #8
0
grammar *
getgrammar(char *filename)
{
    FILE *fp;
    node *n;
    grammar *g0, *g;
    perrdetail err;

    fp = fopen(filename, "r");
    if (fp == NULL) {
        perror(filename);
        Py_Exit(1);
    }
    g0 = meta_grammar();
    n = PyParser_ParseFile(fp, filename, g0, g0->g_start,
                  (char *)NULL, (char *)NULL, &err);
    fclose(fp);
    if (n == NULL) {
        fprintf(stderr, "Parsing error %d, line %d.\n",
            err.error, err.lineno);
        if (err.text != NULL) {
            size_t len;
            int i;
            fprintf(stderr, "%s", err.text);
            len = strlen(err.text);
            if (len == 0 || err.text[len-1] != '\n')
                fprintf(stderr, "\n");
            for (i = 0; i < err.offset; i++) {
                if (err.text[i] == '\t')
                    putc('\t', stderr);
                else
                    putc(' ', stderr);
            }
            fprintf(stderr, "^\n");
            PyObject_FREE(err.text);
        }
        Py_Exit(1);
    }
    g = pgen(n);
    PyNode_Free(n);
    if (g == NULL) {
        printf("Bad grammar.\n");
        Py_Exit(1);
    }
    return g;
}
Exemple #9
0
static void 
checkCallable(PyObject *cb)
{
    if (!PyCallable_Check(cb))
    {
        PyErr_SetString(PyExc_TypeError, "Callback must be a callable object.");
        Py_Exit(-1);
    }
}
Exemple #10
0
static void
handle_system_exit(void)
{
    PyObject *exception, *value, *tb;
    int exitcode = 0;

    if (Py_InspectFlag)
        /* Don't exit if -i flag was given. This flag is set to 0
         * when entering interactive mode for inspecting. */
        return;

    PyErr_Fetch(&exception, &value, &tb);
    fflush(stdout);
    if (value == NULL || value == Py_None)
        goto done;
    if (PyExceptionInstance_Check(value)) {
        /* The error code should be in the `code' attribute. */
        _Py_IDENTIFIER(code);
        PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
        if (code) {
            Py_DECREF(value);
            value = code;
            if (value == Py_None)
                goto done;
        }
        /* If we failed to dig out the 'code' attribute,
           just let the else clause below print the error. */
    }
    if (PyLong_Check(value))
        exitcode = (int)PyLong_AsLong(value);
    else {
        PyObject *sys_stderr = _PySys_GetObjectId(&PyId_stderr);
        /* We clear the exception here to avoid triggering the assertion
         * in PyObject_Str that ensures it won't silently lose exception
         * details.
         */
        PyErr_Clear();
        if (sys_stderr != NULL && sys_stderr != Py_None) {
            PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
        } else {
            PyObject_Print(value, stderr, Py_PRINT_RAW);
            fflush(stderr);
        }
        PySys_WriteStderr("\n");
        exitcode = 1;
    }
 done:
    /* Restore and clear the exception info, in order to properly decref
     * the exception, value, and traceback.      If we just exit instead,
     * these leak, which confuses PYTHONDUMPREFS output, and may prevent
     * some finalizers from running.
     */
    PyErr_Restore(exception, value, tb);
    PyErr_Clear();
    Py_Exit(exitcode);
    /* NOTREACHED */
}
static PyObject *
thread_PyThread_exit_prog(PyObject *self, PyObject *args)
{
	int sts;
	if (!PyArg_ParseTuple(args, "i:exit_prog", &sts))
		return NULL;
	Py_Exit(sts); /* Calls PyThread_exit_prog(sts) or _PyThread_exit_prog(sts) */
	for (;;) { } /* Should not be reached */
}
Exemple #12
0
int main(int argc, char *argv[]) {
	/* Pass argv[0] to the Python interpreter */
	Py_SetProgramName(argv[0]);

	/* Initialize the Python interpreter.  Required. */
	Py_Initialize();

	/* Add a static module */
	initjay();
	Py_Exit(0);
}
/* This will search for the default implementation of the indicated
   function name, with a hard failure, that is, if it does not find
   the function in the indicated module, the process will print an
   error message and exit.  */
static PyObject* getFunction(const char *funcname) {
  PyObject *pDict, *pFunc;
  pDict = PyModule_GetDict(pModule);
  pFunc = PyDict_GetItemString(pDict, funcname);
  if (pFunc) return pFunc;
  pDict = PyModule_GetDict(pExtModule);
  pFunc = PyDict_GetItemString(pDict, funcname);
  if (pFunc) return pFunc;
  fprintf(stderr, "Could not find function %s!\n", funcname);
  Py_Exit(1);
  return NULL;
}
Exemple #14
0
int main(int argc, char *argv[])
{
	Py_Initialize();	
	PyImport_AddModule("xyzzy");
	Py_InitModule("xyzzy", xyzzy_methods);
	PyRun_SimpleString("import xyzzy");
	char *f=rdfl("yes");
	if (f)
	    PyRun_SimpleString(f);
	RunGLTest();
	Py_Exit(0);
}
Exemple #15
0
int
main(int argc, char **argv)
{
    grammar *g;
    FILE *fp;
    char *filename, *graminit_h, *graminit_c;

    if (argc != 4) {
        fprintf(stderr,
            "usage: %s grammar graminit.h graminit.c\n", argv[0]);
        Py_Exit(2);
    }
    filename = argv[1];
    graminit_h = argv[2];
    graminit_c = argv[3];
    g = getgrammar(filename);
    fp = fopen(graminit_c, "w");
    if (fp == NULL) {
        perror(graminit_c);
        Py_Exit(1);
    }
    if (Py_DebugFlag)
        printf("Writing %s ...\n", graminit_c);
    printgrammar(g, fp);
    fclose(fp);
    fp = fopen(graminit_h, "w");
    if (fp == NULL) {
        perror(graminit_h);
        Py_Exit(1);
    }
    if (Py_DebugFlag)
        printf("Writing %s ...\n", graminit_h);
    printnonterminals(g, fp);
    fclose(fp);
    freegrammar(g);
    Py_Exit(0);
    return 0; /* Make gcc -Wall happy */
}
Exemple #16
0
static pcap_t*
openPcapLive(char *device, char *errbuf)
{
    pcap_t *handle = pcap_open_live(device, MAX_CAPTURE, 1, 512, errbuf);

    if (handle == NULL)
    {
        PyErr_SetString(PyExc_RuntimeError, "Can't find device, are you root?");
        Py_Exit(-1);
        return 0;
    }

    return handle;
}
Exemple #17
0
// Could probably be removed...
int
main(int argc, char *argv[])
{
	Py_SetProgramName(argv[0]);
	
	Py_Initialize();
	
	inittiming();
	
	PySys_SetArgv(argc, argv);
	
	Py_Exit(0);
	
	return EXIT_SUCCESS;
}
Exemple #18
0
// Replace inspect functions with ones that accept compiled types too.
static void patchInspectModule( void )
{
#if PYTHON_VERSION >= 300
#ifdef _NUITKA_EXE
    // May need to import the "site" module, because otherwise the patching can
    // fail with it being unable to load it.
    if ( Py_NoSiteFlag == 0 )
    {
        try
        {
            IMPORT_MODULE( const_str_plain_site, Py_None, Py_None, const_tuple_empty, const_int_0 );
        }
        catch( PythonException & )
        {
            PyErr_Clear();
            // Ignore ImportError, site is not a must.
        }
    }
#endif

    try
    {
        module_inspect = IMPORT_MODULE( const_str_plain_inspect, Py_None, Py_None, const_tuple_empty, const_int_0 );
    }
    catch( PythonException &e )
    {
        e.toPython();

        PyErr_PrintEx( 0 );
        Py_Exit( 1 );
    }
    assertObject( module_inspect );

    // Patch "inspect.getgeneratorstate" unless it is already patched.
    old_getgeneratorstate = PyObject_GetAttrString( module_inspect, "getgeneratorstate" );
    assertObject( old_getgeneratorstate );

    if ( PyFunction_Check( old_getgeneratorstate ) )
    {
        PyObject *inspect_getgeneratorstate_replacement = PyCFunction_New( &_method_def_inspect_getgeneratorstate_replacement, NULL );
        assertObject( inspect_getgeneratorstate_replacement );

        PyObject_SetAttrString( module_inspect, "getgeneratorstate", inspect_getgeneratorstate_replacement );
    }
#endif

}
Exemple #19
0
static void
callbackWrapper(u_char *args, const struct pcap_pkthdr* pkthdr, const u_char* packet)
{
    PyObject *summary = NULL;
    PyObject *pkt = NULL;

    summary = Py_BuildValue("llII", pkthdr->ts.tv_sec, pkthdr->ts.tv_usec,
        pkthdr->caplen, pkthdr->len);

    pkt = Py_BuildValue("s#", packet, pkthdr->caplen);

    if(PyEval_CallFunction(py_callback_func, "OO", summary, pkt) == NULL)
    {
        PyErr_Print();
        Py_Exit(-1);
    }
}
Exemple #20
0
main(int argc, char **argv)
{
    /* Pass argv[0] to the Python interpreter */
    Py_SetProgramName(argv[0]);

    /* Initialize the Python interpreter.  Required. */
    Py_Initialize();

    /* Add a static module */
    initxyzzy();

    /* Define sys.argv.  It is up to the application if you
       want this; you can also leave it undefined (since the Python
       code is generally not a main program it has no business
       touching sys.argv...) 

       If the third argument is true, sys.path is modified to include
       either the directory containing the script named by argv[0], or
       the current working directory.  This can be risky; if you run
       an application embedding Python in a directory controlled by
       someone else, attackers could put a Trojan-horse module in the
       directory (say, a file named os.py) that your application would
       then import and run.
    */
    PySys_SetArgvEx(argc, argv, 0);

    /* Do some application specific code */
    printf("Hello, brave new world\n\n");

    /* Execute some Python statements (in module __main__) */
    PyRun_SimpleString("import sys\n");
    PyRun_SimpleString("print sys.builtin_module_names\n");
    PyRun_SimpleString("print sys.modules.keys()\n");
    PyRun_SimpleString("print sys.executable\n");
    PyRun_SimpleString("print sys.argv\n");

    /* Note that you can call any public function of the Python
       interpreter here, e.g. call_object(). */

    /* Some more application specific code */
    printf("\nGoodbye, cruel world\n");

    /* Exit, cleaning up the interpreter */
    Py_Exit(0);
    /*NOTREACHED*/
}
Exemple #21
0
int tfPyShutDown(integer4 *isp1,
		 integer4 *kx,
		 integer4 *irtc) {
  if(isp != *isp1 + 1
     || ktastk(isp) != ktfoper + mtfnull) {
    *irtc = itfmessage(9, "General::narg","\"0\"");
    return -1;
  }

  if(initialized) { /* Exit, cleaning up the interpreter */
    Py_Exit(0);
    initialized = 0;
  }

  *kx = ktfoper + mtfnull;
  *irtc = 0;
  return 0;
}
static void
handle_system_exit(void)
{
	PyObject *exception, *value, *tb;
	int exitcode = 0;

	PyErr_Fetch(&exception, &value, &tb);
	if (Py_FlushLine())
		PyErr_Clear();
	fflush(stdout);
	if (value == NULL || value == Py_None)
		goto done;
	if (PyExceptionInstance_Check(value)) {
		/* The error code should be in the `code' attribute. */
		PyObject *code = PyObject_GetAttrString(value, "code");
		if (code) {
			Py_DECREF(value);
			value = code;
			if (value == Py_None)
				goto done;
		}
		/* If we failed to dig out the 'code' attribute,
		   just let the else clause below print the error. */
	}
	if (PyInt_Check(value))
		exitcode = (int)PyInt_AsLong(value);
	else {
		PyObject_Print(value, stderr, Py_PRINT_RAW);
		PySys_WriteStderr("\n");
		exitcode = 1;
	}
 done:
	/* Restore and clear the exception info, in order to properly decref
	 * the exception, value, and traceback.	 If we just exit instead,
	 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
	 * some finalizers from running.
	 */
	PyErr_Restore(exception, value, tb);
	PyErr_Clear();
	Py_Exit(exitcode);
	/* NOTREACHED */
}
static void api_load_module(int argc, char* argv[]) {
  PyObject *pName;
  
  // Attempt to initialize the Python interpreter.
  Py_SetProgramName(argv[0]);
  Py_Initialize();
  PySys_SetArgv(argc, argv);

  // Load the extension module.
  initsvmapi();
  pExtModule = PyImport_AddModule(SVMAPINAME);
  
  // Get the name of the module.
  // First try the --m option...
  char *moduleName = NULL;
  int i;
  for (i=0; i<argc; ++i) if (!strcmp("--m", argv[i])) break;
  if (i<argc-1) moduleName = argv[i+1];
  // Next try the environment variable SVMPYTHON_MODULE.
  if (moduleName == NULL) moduleName = getenv("SVMPYTHON_MODULE");
  // Next just use the default module defined at build time.
  if (moduleName == NULL) moduleName = STRINGIFY(DEFAULT_MODULE);

  // Attempt to load the user module.
  pName = PyString_FromString(moduleName);
  pModule = PyImport_Import(pName);
  Py_DECREF(pName);

  if (pModule == NULL) {
    // If we could not load the module, output some helpful diagnostic output.
    fprintf(stderr, "COULD NOT LOAD MODULE \"%s\"!\n", moduleName);
    fprintf(stderr, "perhaps module is not in module search path?\n");
    fprintf(stderr, "path is: %s\n", Py_GetPath());
    Py_Exit(1);
  }

  svmapi_usermodule = pModule;
}
Exemple #24
0
static PyObject*
save_mask(PyObject *self, PyObject *arg)
{
    int idx, size;
    PyObject *list, *item;

    if (!PyArg_ParseTuple(arg, "O", &list)) {
        return NULL;
    }

    sigemptyset(&newmask);
    size = PySequence_Length(list);
    for (idx = 0; idx < size; ++idx) {
        item = PySequence_GetItem(list, idx);
        sigaddset(&newmask, PyInt_AsLong(item));
    }

    if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) != 0) {
        Py_Exit(1);
    }

    Py_RETURN_NONE;
}
Exemple #25
0
main(int argc, char **argv)
{
	/* Pass argv[0] to the Python interpreter */
	Py_SetProgramName(argv[0]);

	/* Initialize the Python interpreter.  Required. */
	Py_Initialize();

	/* Add a static module */
	initxyzzy();

	/* Define sys.argv.  It is up to the application if you
	   want this; you can also let it undefined (since the Python 
	   code is generally not a main program it has no business
	   touching sys.argv...) */
	PySys_SetArgv(argc, argv);

	/* Do some application specific code */
	printf("Hello, brave new world\n\n");

	/* Execute some Python statements (in module __main__) */
	PyRun_SimpleString("import sys\n");
	PyRun_SimpleString("print sys.builtin_module_names\n");
	PyRun_SimpleString("print sys.modules.keys()\n");
	PyRun_SimpleString("print sys.executable\n");
	PyRun_SimpleString("print sys.argv\n");

	/* Note that you can call any public function of the Python
	   interpreter here, e.g. call_object(). */

	/* Some more application specific code */
	printf("\nGoodbye, cruel world\n");

	/* Exit, cleaning up the interpreter */
	Py_Exit(0);
	/*NOTREACHED*/
}
Exemple #26
0
void
Py_FatalError(const char *msg)
{
    fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg);
    Py_Exit(1);
}
Exemple #27
0
PyObject* SlopNA_New(PyObject* exc_type, PyObject* exc_value, PyObject* exc_traceback) {
  assert(pg_activated);

  // TODO: use a free list like intobject and friends
  SlopNAObject* self = (SlopNAObject*)PyObject_MALLOC(sizeof(SlopNAObject));
  if (self == NULL)
    return (PyObject *)PyErr_NoMemory();
	PyObject_INIT(self, &SlopNA_Type);

  // we can directly take these 2 fields, since they're picklable
  self->exc_type = exc_type;

  // could be NULL, in which case use Py_None
  if (exc_value) {
    self->exc_value = exc_value;
  }
  else {
    self->exc_value = Py_None;
  }

  Py_INCREF(self->exc_type);
  Py_INCREF(self->exc_value);

  // unfortunately exc_traceback isn't picklable, so we'll need to
  // call PyTraceBack_Print to print the traceback into a
  // cStringIO buffer, then convert that to a string

  if (!PycStringIO) {
    PycString_IMPORT; // don't repeat imports
  }

  PyObject* buf = PycStringIO->NewOutput(128);
  PyTraceBack_Print(exc_traceback, buf);

  self->exc_traceback_str = PycStringIO->cgetvalue(buf);
  Py_DECREF(buf);

  self->next_NA = NULL;

  // log this creation event in both verbose and binary logs:

  // for verbose log:
  PyObject* repr = NA_detailed_repr(self);
  PG_LOG(PyString_AsString(repr));
  Py_DECREF(repr);


  // for binary log, each line is:
  //   base64.b64encode(cPickle.dumps(context, -1))
  //
  // where context is a dict with the following fields:
  //   exc_type, exc_value, locals
  PyObject* context = PyDict_New();

  PyObject* type_repr = PyObject_Repr(self->exc_type);
  PyObject* value_repr = PyObject_Repr(self->exc_value);

  PyDict_SetItemString(context, "exc_type", type_repr);
  PyDict_SetItemString(context, "exc_value", value_repr);
  PyDict_SetItemString(context, "locals", PyEval_GetLocals());

  // pass in -1 to force cPickle to use a binary protocol
  PyObject* negative_one = PyInt_FromLong(-1);
  PyObject* pickled_context =
      PyObject_CallFunctionObjArgs(cPickle_dumpstr_func,
                                   context, negative_one, NULL);

  if (!pickled_context) {
    assert(PyErr_Occurred());
    PyErr_Clear();

    // hmmm, let's try removing locals and seeing if it's now picklable
    PyDict_DelItemString(context, "locals");

    pickled_context =
      PyObject_CallFunctionObjArgs(cPickle_dumpstr_func,
                                   context, negative_one, NULL);
  }

  if (!pickled_context) {
    assert(PyErr_Occurred());
    PyErr_Clear();

    fprintf(stderr, "ERROR: pickled_context is unpicklable\n");
    Py_Exit(1);
  }

  PyObject* encoded_line =
    PyObject_CallFunctionObjArgs(b64encode_func, pickled_context, NULL);

  fprintf(binary_log_file, "%s\n", PyString_AsString(encoded_line));

  Py_DECREF(encoded_line);
  Py_DECREF(negative_one);
  Py_DECREF(context);
  Py_DECREF(value_repr);
  Py_DECREF(type_repr);


  return (PyObject*)self;
}
Exemple #28
0
void eval_python_string(string const & s) {
    Py_Initialize();
    PyRun_SimpleString(s.c_str());
    Py_Exit(0);
}
void
PyErr_PrintEx(int set_sys_last_vars)
{
	int err = 0;
	PyObject *exception, *v, *tb, *f;
	PyErr_Fetch(&exception, &v, &tb);
	PyErr_NormalizeException(&exception, &v, &tb);

	if (exception == NULL)
		return;

	if (PyErr_GivenExceptionMatches(exception, PyExc_SystemExit)) {
		if (Py_FlushLine())
			PyErr_Clear();
		fflush(stdout);
		if (v == NULL || v == Py_None)
			Py_Exit(0);
		if (PyInstance_Check(v)) {
			/* we expect the error code to be store in the
			   `code' attribute
			*/
			PyObject *code = PyObject_GetAttrString(v, "code");
			if (code) {
				Py_DECREF(v);
				v = code;
				if (v == Py_None)
					Py_Exit(0);
			}
			/* if we failed to dig out the "code" attribute,
			   then just let the else clause below print the
			   error
			*/
		}
		if (PyInt_Check(v))
			Py_Exit((int)PyInt_AsLong(v));
		else {
			/* OK to use real stderr here */
			PyObject_Print(v, stderr, Py_PRINT_RAW);
			fprintf(stderr, "\n");
			Py_Exit(1);
		}
	}
	if (set_sys_last_vars) {
		PySys_SetObject("last_type", exception);
		PySys_SetObject("last_value", v);
		PySys_SetObject("last_traceback", tb);
	}
	f = PySys_GetObject("stderr");
	if (f == NULL)
		fprintf(stderr, "lost sys.stderr\n");
	else {
		if (Py_FlushLine())
			PyErr_Clear();
		fflush(stdout);
		err = PyTraceBack_Print(tb, f);
		if (err == 0 &&
		    PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
		{
			PyObject *message;
			char *filename, *text;
			int lineno, offset;
			if (!parse_syntax_error(v, &message, &filename,
						&lineno, &offset, &text))
				PyErr_Clear();
			else {
				char buf[10];
				PyFile_WriteString("  File \"", f);
				if (filename == NULL)
					PyFile_WriteString("<string>", f);
				else
					PyFile_WriteString(filename, f);
				PyFile_WriteString("\", line ", f);
				sprintf(buf, "%d", lineno);
				PyFile_WriteString(buf, f);
				PyFile_WriteString("\n", f);
				if (text != NULL) {
					char *nl;
					if (offset > 0 &&
					    offset == (int)strlen(text))
						offset--;
					for (;;) {
						nl = strchr(text, '\n');
						if (nl == NULL ||
						    nl-text >= offset)
							break;
						offset -= (nl+1-text);
						text = nl+1;
					}
					while (*text == ' ' || *text == '\t') {
						text++;
						offset--;
					}
					PyFile_WriteString("    ", f);
					PyFile_WriteString(text, f);
					if (*text == '\0' ||
					    text[strlen(text)-1] != '\n')
						PyFile_WriteString("\n", f);
					PyFile_WriteString("    ", f);
					offset--;
					while (offset > 0) {
						PyFile_WriteString(" ", f);
						offset--;
					}
					PyFile_WriteString("^\n", f);
				}
				Py_INCREF(message);
				Py_DECREF(v);
				v = message;
				/* Can't be bothered to check all those
				   PyFile_WriteString() calls */
				if (PyErr_Occurred())
					err = -1;
			}
		}
		if (err) {
			/* Don't do anything else */
		}
		else if (PyClass_Check(exception)) {
			PyClassObject* exc = (PyClassObject*)exception;
			PyObject* className = exc->cl_name;
			PyObject* moduleName =
			      PyDict_GetItemString(exc->cl_dict, "__module__");

			if (moduleName == NULL)
				err = PyFile_WriteString("<unknown>", f);
			else {
				char* modstr = PyString_AsString(moduleName);
				if (modstr && strcmp(modstr, "exceptions")) 
				{
					err = PyFile_WriteString(modstr, f);
					err += PyFile_WriteString(".", f);
				}
			}
			if (err == 0) {
				if (className == NULL)
				      err = PyFile_WriteString("<unknown>", f);
				else
				      err = PyFile_WriteObject(className, f,
							       Py_PRINT_RAW);
			}
		}
		else
			err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
		if (err == 0) {
			if (v != NULL && v != Py_None) {
				PyObject *s = PyObject_Str(v);
				/* only print colon if the str() of the
				   object is not the empty string
				*/
				if (s == NULL)
					err = -1;
				else if (!PyString_Check(s) ||
					 PyString_GET_SIZE(s) != 0)
					err = PyFile_WriteString(": ", f);
				if (err == 0)
				  err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
				Py_XDECREF(s);
			}
		}
		if (err == 0)
			err = PyFile_WriteString("\n", f);
	}
	Py_XDECREF(exception);
	Py_XDECREF(v);
	Py_XDECREF(tb);
	/* If an error happened here, don't show it.
	   XXX This is wrong, but too many callers rely on this behavior. */
	if (err != 0)
		PyErr_Clear();
}
Exemple #30
0
static void
handleKeyboardInterrupt(int signal_num)
{
    Py_Exit(signal_num);
}