VirtualBox

source: vbox/trunk/src/libs/xpcom18a4/python/src/ErrorUtils.cpp@ 98262

Last change on this file since 98262 was 73153, checked in by vboxsync, 7 years ago

xpcom18a4: fix ErrorUtils.cpp for Python 3.7, where PyUnicode_AsUTF8() returns const char *. Thank you Gianfranco Costamagna.

  • Property svn:eol-style set to native
File size: 14.6 KB
Line 
1/* ***** BEGIN LICENSE BLOCK *****
2 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
3 *
4 * The contents of this file are subject to the Mozilla Public License Version
5 * 1.1 (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
7 * http://www.mozilla.org/MPL/
8 *
9 * Software distributed under the License is distributed on an "AS IS" basis,
10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
11 * for the specific language governing rights and limitations under the
12 * License.
13 *
14 * The Original Code is the Python XPCOM language bindings.
15 *
16 * The Initial Developer of the Original Code is
17 * ActiveState Tool Corp.
18 * Portions created by the Initial Developer are Copyright (C) 2000
19 * the Initial Developer. All Rights Reserved.
20 *
21 * Contributor(s):
22 * Mark Hammond <MarkH@ActiveState.com> (original author)
23 *
24 * Alternatively, the contents of this file may be used under the terms of
25 * either the GNU General Public License Version 2 or later (the "GPL"), or
26 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
35 *
36 * ***** END LICENSE BLOCK ***** */
37
38//
39// This code is part of the XPCOM extensions for Python.
40//
41// Written May 2000 by Mark Hammond.
42//
43// Based heavily on the Python COM support, which is
44// (c) Mark Hammond and Greg Stein.
45//
46// (c) 2000, ActiveState corp.
47
48#include "PyXPCOM_std.h"
49#include "nsReadableUtils.h"
50#include <nsIConsoleService.h>
51#ifdef VBOX
52# include <nsIExceptionService.h>
53# include <iprt/err.h>
54# include <iprt/string.h>
55#endif
56#include "nspr.h" // PR_fprintf
57
58static char *PyTraceback_AsString(PyObject *exc_tb);
59
60// The internal helper that actually moves the
61// formatted string to the target!
62
63// Only used in really bad situations!
64static void _PanicErrorWrite(const char *msg)
65{
66 nsCOMPtr<nsIConsoleService> consoleService = do_GetService(NS_CONSOLESERVICE_CONTRACTID);
67 if (consoleService)
68 consoleService->LogStringMessage(NS_ConvertASCIItoUCS2(msg).get());
69 PR_fprintf(PR_STDERR,"%s\n", msg);
70}
71
72// Called when our "normal" error logger fails.
73static void HandleLogError(const char *pszMessageText)
74{
75 nsCAutoString streamout;
76
77 _PanicErrorWrite("Failed to log an error record");
78 if (PyXPCOM_FormatCurrentException(streamout))
79 _PanicErrorWrite(streamout.get());
80 _PanicErrorWrite("Original error follows:");
81 _PanicErrorWrite(pszMessageText);
82}
83
84static const char *LOGGER_WARNING = "warning";
85static const char *LOGGER_ERROR = "error";
86static const char *LOGGER_DEBUG = "debug";
87
88// Our "normal" error logger - calls back to the logging module.
89void DoLogMessage(const char *methodName, const char *pszMessageText)
90{
91 // We use the logging module now. Originally this code called
92 // the logging module directly by way of the C API's
93 // PyImport_ImportModule/PyObject_CallMethod etc. However, this
94 // causes problems when there is no Python caller on the stack -
95 // the logging module's findCaller method fails with a None frame.
96 // We now work around this by calling PyRun_SimpleString - this
97 // causes a new frame to be created for executing the compiled
98 // string, and the logging module no longer fails.
99 // XXX - this implementation is less than ideal - findCaller now
100 // returns ("<string>", 2). Ideally we would compile with a
101 // filename something similar to "<pydom error reporter>".
102
103 // But this also means we need a clear error state...
104 PyObject *exc_typ = NULL, *exc_val = NULL, *exc_tb = NULL;
105 PyErr_Fetch(&exc_typ, &exc_val, &exc_tb);
106// We will execute:
107// import logging
108// logging.getLogger('xpcom').{warning/error/etc}("%s", {msg_text})
109 nsCAutoString c("import logging\nlogging.getLogger('xpcom').");
110 c += methodName;
111 c += "('%s', ";
112 // Pull a trick to ensure a valid string - use Python repr!
113#if PY_MAJOR_VERSION <= 2
114 PyObject *obMessage = PyString_FromString(pszMessageText);
115#else
116 PyObject *obMessage = PyUnicode_FromString(pszMessageText);
117#endif
118 if (obMessage) {
119 PyObject *repr = PyObject_Repr(obMessage);
120 if (repr) {
121#if PY_MAJOR_VERSION <= 2
122 c += PyString_AsString(repr);
123#else
124 c += PyUnicode_AsUTF8(repr);
125#endif
126 Py_DECREF(repr);
127 }
128 Py_DECREF(obMessage);
129 }
130 c += ")\n";
131 if (PyRun_SimpleString(c.get()) != 0) {
132 HandleLogError(pszMessageText);
133 }
134 PyErr_Restore(exc_typ, exc_val, exc_tb);
135}
136
137void LogMessage(const char *methodName, const char *pszMessageText)
138{
139 // Be careful to save and restore the Python exception state
140 // before calling back to Python, or we lose the original error.
141 PyObject *exc_typ = NULL, *exc_val = NULL, *exc_tb = NULL;
142 PyErr_Fetch( &exc_typ, &exc_val, &exc_tb);
143 DoLogMessage(methodName, pszMessageText);
144 PyErr_Restore(exc_typ, exc_val, exc_tb);
145}
146
147
148void LogMessage(const char *methodName, nsACString &text)
149{
150 char *c = ToNewCString(text);
151 LogMessage(methodName, c);
152 nsCRT::free(c);
153}
154
155// A helper for the various logging routines.
156static void VLogF(const char *methodName, const char *fmt, va_list argptr)
157{
158 char buff[512];
159#ifdef VBOX /* Enable the use of VBox formatting types. */
160 RTStrPrintfV(buff, sizeof(buff), fmt, argptr);
161#else
162 // Use safer NS_ functions.
163 PR_vsnprintf(buff, sizeof(buff), fmt, argptr);
164#endif
165
166 LogMessage(methodName, buff);
167}
168
169PRBool PyXPCOM_FormatCurrentException(nsCString &streamout)
170{
171 PRBool ok = PR_FALSE;
172 PyObject *exc_typ = NULL, *exc_val = NULL, *exc_tb = NULL;
173 PyErr_Fetch( &exc_typ, &exc_val, &exc_tb);
174 PyErr_NormalizeException( &exc_typ, &exc_val, &exc_tb);
175 if (exc_typ) {
176 ok = PyXPCOM_FormatGivenException(streamout, exc_typ, exc_val,
177 exc_tb);
178 }
179 PyErr_Restore(exc_typ, exc_val, exc_tb);
180 return ok;
181}
182
183PRBool PyXPCOM_FormatGivenException(nsCString &streamout,
184 PyObject *exc_typ, PyObject *exc_val,
185 PyObject *exc_tb)
186{
187 if (!exc_typ)
188 return PR_FALSE;
189 streamout += "\n";
190
191 if (exc_tb) {
192 const char *szTraceback = PyTraceback_AsString(exc_tb);
193 if (szTraceback == NULL)
194 streamout += "Can't get the traceback info!";
195 else {
196 streamout += "Traceback (most recent call last):\n";
197 streamout += szTraceback;
198 PyMem_Free((void *)szTraceback);
199 }
200 }
201 PyObject *temp = PyObject_Str(exc_typ);
202 if (temp) {
203#if PY_MAJOR_VERSION <= 2
204 streamout += PyString_AsString(temp);
205#else
206 streamout += PyUnicode_AsUTF8(temp);
207#endif
208 Py_DECREF(temp);
209 } else
210 streamout += "Can't convert exception to a string!";
211 streamout += ": ";
212 if (exc_val != NULL) {
213 temp = PyObject_Str(exc_val);
214 if (temp) {
215#if PY_MAJOR_VERSION <= 2
216 streamout += PyString_AsString(temp);
217#else
218 streamout += PyUnicode_AsUTF8(temp);
219#endif
220 Py_DECREF(temp);
221 } else
222 streamout += "Can't convert exception value to a string!";
223 }
224 return PR_TRUE;
225}
226
227void PyXPCOM_LogError(const char *fmt, ...)
228{
229 va_list marker;
230 va_start(marker, fmt);
231 // NOTE: It is tricky to use logger.exception here - the exception
232 // state when called back from the C code is clear. Only Python 2.4
233 // and later allows an explicit exc_info tuple().
234
235 // Don't use VLogF here, instead arrange for exception info and
236 // traceback to be in the same buffer.
237 char buff[512];
238 PR_vsnprintf(buff, sizeof(buff), fmt, marker);
239 // If we have a Python exception, also log that:
240 nsCAutoString streamout(buff);
241 if (PyXPCOM_FormatCurrentException(streamout)) {
242 LogMessage(LOGGER_ERROR, streamout);
243 }
244 va_end(marker);
245}
246
247void PyXPCOM_LogWarning(const char *fmt, ...)
248{
249 va_list marker;
250 va_start(marker, fmt);
251 VLogF(LOGGER_WARNING, fmt, marker);
252 va_end(marker);
253}
254
255void PyXPCOM_Log(const char *level, const nsCString &msg)
256{
257 DoLogMessage(level, msg.get());
258}
259
260#ifdef DEBUG
261void PyXPCOM_LogDebug(const char *fmt, ...)
262{
263 va_list marker;
264 va_start(marker, fmt);
265 VLogF(LOGGER_DEBUG, fmt, marker);
266 va_end(marker);
267}
268#endif
269
270#ifdef VBOX
271PyObject *PyXPCOM_BuildErrorMessage(nsresult r)
272{
273 char msg[512];
274 bool gotMsg = false;
275
276 if (!gotMsg)
277 {
278 nsresult rc;
279 nsCOMPtr <nsIExceptionService> es;
280 es = do_GetService (NS_EXCEPTIONSERVICE_CONTRACTID, &rc);
281 if (NS_SUCCEEDED (rc))
282 {
283 nsCOMPtr <nsIExceptionManager> em;
284 rc = es->GetCurrentExceptionManager (getter_AddRefs (em));
285 if (NS_SUCCEEDED (rc))
286 {
287 nsCOMPtr <nsIException> ex;
288 rc = em->GetExceptionFromProvider(r, NULL, getter_AddRefs (ex));
289 if (NS_SUCCEEDED (rc) && ex)
290 {
291 nsXPIDLCString emsg;
292 ex->GetMessage(getter_Copies(emsg));
293 PR_snprintf(msg, sizeof(msg), "%s",
294 emsg.get());
295 gotMsg = true;
296 }
297 }
298 }
299 }
300
301 if (!gotMsg)
302 {
303 const RTCOMERRMSG* pMsg = RTErrCOMGet(r);
304 if (strncmp(pMsg->pszMsgFull, "Unknown", 7) != 0)
305 {
306 PR_snprintf(msg, sizeof(msg), "%s (%s)",
307 pMsg->pszMsgFull, pMsg->pszDefine);
308 gotMsg = true;
309 }
310 }
311
312 if (!gotMsg)
313 {
314 PR_snprintf(msg, sizeof(msg), "Error 0x%x in module 0x%x",
315 NS_ERROR_GET_CODE(r), NS_ERROR_GET_MODULE(r));
316 }
317 PyObject *evalue = Py_BuildValue("is", r, msg);
318 return evalue;
319}
320#endif
321
322PyObject *PyXPCOM_BuildPyException(nsresult r)
323{
324#ifndef VBOX
325 // Need the message etc.
326 PyObject *evalue = Py_BuildValue("i", r);
327#else
328 PyObject *evalue = PyXPCOM_BuildErrorMessage(r);
329#endif
330 PyErr_SetObject(PyXPCOM_Error, evalue);
331 Py_XDECREF(evalue);
332 return NULL;
333}
334
335nsresult PyXPCOM_SetCOMErrorFromPyException()
336{
337 if (!PyErr_Occurred())
338 // No error occurred
339 return NS_OK;
340 nsresult rv = NS_ERROR_FAILURE;
341 if (PyErr_ExceptionMatches(PyExc_MemoryError))
342 rv = NS_ERROR_OUT_OF_MEMORY;
343 // todo:
344 // * Set an exception using the exception service.
345
346 // Once we have returned to the xpcom caller, we don't want to leave a
347 // Python exception pending - it may get noticed when the next call
348 // is made on the same thread.
349 PyErr_Clear();
350 return rv;
351}
352
353/* Obtains a string from a Python traceback.
354 This is the exact same string as "traceback.print_exc" would return.
355
356 Pass in a Python traceback object (probably obtained from PyErr_Fetch())
357 Result is a string which must be free'd using PyMem_Free()
358*/
359#define TRACEBACK_FETCH_ERROR(what) {errMsg = what; goto done;}
360
361char *PyTraceback_AsString(PyObject *exc_tb)
362{
363 const char *errMsg = NULL; /* holds a local error message */
364 char *result = NULL; /* a valid, allocated result. */
365 PyObject *modStringIO = NULL;
366 PyObject *modTB = NULL;
367 PyObject *obFuncStringIO = NULL;
368 PyObject *obStringIO = NULL;
369 PyObject *obFuncTB = NULL;
370 PyObject *argsTB = NULL;
371 PyObject *obResult = NULL;
372
373#if PY_MAJOR_VERSION <= 2
374 /* Import the modules we need - cStringIO and traceback */
375 modStringIO = PyImport_ImportModule("cStringIO");
376 if (modStringIO==NULL)
377 TRACEBACK_FETCH_ERROR("cant import cStringIO\n");
378
379 modTB = PyImport_ImportModule("traceback");
380 if (modTB==NULL)
381 TRACEBACK_FETCH_ERROR("cant import traceback\n");
382 /* Construct a cStringIO object */
383 obFuncStringIO = PyObject_GetAttrString(modStringIO, "StringIO");
384 if (obFuncStringIO==NULL)
385 TRACEBACK_FETCH_ERROR("cant find cStringIO.StringIO\n");
386 obStringIO = PyObject_CallObject(obFuncStringIO, NULL);
387 if (obStringIO==NULL)
388 TRACEBACK_FETCH_ERROR("cStringIO.StringIO() failed\n");
389#else
390 /* Import the modules we need - io and traceback */
391 modStringIO = PyImport_ImportModule("io");
392 if (modStringIO==NULL)
393 TRACEBACK_FETCH_ERROR("cant import io\n");
394
395 modTB = PyImport_ImportModule("traceback");
396 if (modTB==NULL)
397 TRACEBACK_FETCH_ERROR("cant import traceback\n");
398 /* Construct a StringIO object */
399 obFuncStringIO = PyObject_GetAttrString(modStringIO, "StringIO");
400 if (obFuncStringIO==NULL)
401 TRACEBACK_FETCH_ERROR("cant find io.StringIO\n");
402 obStringIO = PyObject_CallObject(obFuncStringIO, NULL);
403 if (obStringIO==NULL)
404 TRACEBACK_FETCH_ERROR("io.StringIO() failed\n");
405#endif
406 /* Get the traceback.print_exception function, and call it. */
407 obFuncTB = PyObject_GetAttrString(modTB, "print_tb");
408 if (obFuncTB==NULL)
409 TRACEBACK_FETCH_ERROR("cant find traceback.print_tb\n");
410
411 argsTB = Py_BuildValue("OOO",
412 exc_tb ? exc_tb : Py_None,
413 Py_None,
414 obStringIO);
415 if (argsTB==NULL)
416 TRACEBACK_FETCH_ERROR("cant make print_tb arguments\n");
417
418 obResult = PyObject_CallObject(obFuncTB, argsTB);
419 if (obResult==NULL)
420 TRACEBACK_FETCH_ERROR("traceback.print_tb() failed\n");
421 /* Now call the getvalue() method in the StringIO instance */
422 Py_DECREF(obFuncStringIO);
423 obFuncStringIO = PyObject_GetAttrString(obStringIO, "getvalue");
424 if (obFuncStringIO==NULL)
425 TRACEBACK_FETCH_ERROR("cant find getvalue function\n");
426 Py_DECREF(obResult);
427 obResult = PyObject_CallObject(obFuncStringIO, NULL);
428 if (obResult==NULL)
429 TRACEBACK_FETCH_ERROR("getvalue() failed.\n");
430
431 /* And it should be a string all ready to go - duplicate it. */
432#if PY_MAJOR_VERSION <= 2
433 if (!PyString_Check(obResult))
434#else
435 if (!PyUnicode_Check(obResult))
436#endif
437 TRACEBACK_FETCH_ERROR("getvalue() did not return a string\n");
438
439 { // a temp scope so I can use temp locals.
440#if PY_MAJOR_VERSION <= 2
441 char *tempResult = PyString_AsString(obResult);
442#else
443 /* PyUnicode_AsUTF8() is const char * as of Python 3.7, char * earlier. */
444 const char *tempResult = (const char *)PyUnicode_AsUTF8(obResult);
445#endif
446 result = (char *)PyMem_Malloc(strlen(tempResult)+1);
447 if (result==NULL)
448 TRACEBACK_FETCH_ERROR("memory error duplicating the traceback string\n");
449
450 strcpy(result, tempResult);
451 } // end of temp scope.
452done:
453 /* All finished - first see if we encountered an error */
454 if (result==NULL && errMsg != NULL) {
455 result = (char *)PyMem_Malloc(strlen(errMsg)+1);
456 if (result != NULL)
457 /* if it does, not much we can do! */
458 strcpy(result, errMsg);
459 }
460 Py_XDECREF(modStringIO);
461 Py_XDECREF(modTB);
462 Py_XDECREF(obFuncStringIO);
463 Py_XDECREF(obStringIO);
464 Py_XDECREF(obFuncTB);
465 Py_XDECREF(argsTB);
466 Py_XDECREF(obResult);
467 return result;
468}
469
470// See comments in PyXPCOM.h for why we need this!
471void PyXPCOM_MakePendingCalls()
472{
473 while (1) {
474 int rc = Py_MakePendingCalls();
475 if (rc == 0)
476 break;
477 // An exception - just report it as normal.
478 // Note that a traceback is very unlikely!
479 PyXPCOM_LogError("Unhandled exception detected before entering Python.\n");
480 PyErr_Clear();
481 // And loop around again until we are told everything is done!
482 }
483}
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette