blob: e5631079a96737c87d1caa54f605da848997ff4f [file] [log] [blame]
Christian Heimes33fe8092008-04-13 13:53:33 +00001#include "Python.h"
2#include "frameobject.h"
3
4#define MODULE_NAME "_warnings"
Christian Heimes33fe8092008-04-13 13:53:33 +00005
6PyDoc_STRVAR(warnings__doc__,
7MODULE_NAME " provides basic warning filtering support.\n"
8"It is a helper module to speed up interpreter start-up.");
9
10/* Both 'filters' and 'onceregistry' can be set in warnings.py;
11 get_warnings_attr() will reset these variables accordingly. */
12static PyObject *_filters; /* List */
13static PyObject *_once_registry; /* Dict */
Brett Cannon0759dd62009-04-01 18:13:07 +000014static PyObject *_default_action; /* String */
Christian Heimes33fe8092008-04-13 13:53:33 +000015
16
17static int
18check_matched(PyObject *obj, PyObject *arg)
19{
20 PyObject *result;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020021 _Py_identifier(match);
Christian Heimes33fe8092008-04-13 13:53:33 +000022 int rc;
23
24 if (obj == Py_None)
25 return 1;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020026 result = _PyObject_CallMethodId(obj, &PyId_match, "O", arg);
Christian Heimes33fe8092008-04-13 13:53:33 +000027 if (result == NULL)
28 return -1;
29
30 rc = PyObject_IsTrue(result);
31 Py_DECREF(result);
32 return rc;
33}
34
35/*
36 Returns a new reference.
37 A NULL return value can mean false or an error.
38*/
39static PyObject *
40get_warnings_attr(const char *attr)
41{
42 static PyObject *warnings_str = NULL;
43 PyObject *all_modules;
44 PyObject *warnings_module;
45 int result;
46
47 if (warnings_str == NULL) {
48 warnings_str = PyUnicode_InternFromString("warnings");
49 if (warnings_str == NULL)
50 return NULL;
51 }
52
53 all_modules = PyImport_GetModuleDict();
54 result = PyDict_Contains(all_modules, warnings_str);
55 if (result == -1 || result == 0)
56 return NULL;
57
58 warnings_module = PyDict_GetItem(all_modules, warnings_str);
59 if (!PyObject_HasAttrString(warnings_module, attr))
60 return NULL;
61 return PyObject_GetAttrString(warnings_module, attr);
62}
63
64
Neal Norwitz32dde222008-04-15 06:43:13 +000065static PyObject *
Christian Heimes33fe8092008-04-13 13:53:33 +000066get_once_registry(void)
67{
68 PyObject *registry;
69
70 registry = get_warnings_attr("onceregistry");
71 if (registry == NULL) {
72 if (PyErr_Occurred())
73 return NULL;
74 return _once_registry;
75 }
76 Py_DECREF(_once_registry);
77 _once_registry = registry;
78 return registry;
79}
80
81
Brett Cannon0759dd62009-04-01 18:13:07 +000082static PyObject *
83get_default_action(void)
84{
85 PyObject *default_action;
86
87 default_action = get_warnings_attr("defaultaction");
88 if (default_action == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 if (PyErr_Occurred()) {
90 return NULL;
91 }
92 return _default_action;
Brett Cannon0759dd62009-04-01 18:13:07 +000093 }
94
95 Py_DECREF(_default_action);
96 _default_action = default_action;
97 return default_action;
98}
99
100
Christian Heimes33fe8092008-04-13 13:53:33 +0000101/* The item is a borrowed reference. */
102static const char *
103get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
104 PyObject *module, PyObject **item)
105{
Brett Cannon0759dd62009-04-01 18:13:07 +0000106 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000107 Py_ssize_t i;
108 PyObject *warnings_filters;
109
110 warnings_filters = get_warnings_attr("filters");
111 if (warnings_filters == NULL) {
112 if (PyErr_Occurred())
113 return NULL;
114 }
115 else {
116 Py_DECREF(_filters);
117 _filters = warnings_filters;
118 }
119
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000120 if (_filters == NULL || !PyList_Check(_filters)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000121 PyErr_SetString(PyExc_ValueError,
122 MODULE_NAME ".filters must be a list");
123 return NULL;
124 }
125
126 /* _filters could change while we are iterating over it. */
127 for (i = 0; i < PyList_GET_SIZE(_filters); i++) {
128 PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj;
129 Py_ssize_t ln;
130 int is_subclass, good_msg, good_mod;
131
132 tmp_item = *item = PyList_GET_ITEM(_filters, i);
133 if (PyTuple_Size(tmp_item) != 5) {
134 PyErr_Format(PyExc_ValueError,
135 MODULE_NAME ".filters item %zd isn't a 5-tuple", i);
136 return NULL;
137 }
138
139 /* Python code: action, msg, cat, mod, ln = item */
140 action = PyTuple_GET_ITEM(tmp_item, 0);
141 msg = PyTuple_GET_ITEM(tmp_item, 1);
142 cat = PyTuple_GET_ITEM(tmp_item, 2);
143 mod = PyTuple_GET_ITEM(tmp_item, 3);
144 ln_obj = PyTuple_GET_ITEM(tmp_item, 4);
145
146 good_msg = check_matched(msg, text);
147 good_mod = check_matched(mod, module);
148 is_subclass = PyObject_IsSubclass(category, cat);
149 ln = PyLong_AsSsize_t(ln_obj);
150 if (good_msg == -1 || good_mod == -1 || is_subclass == -1 ||
151 (ln == -1 && PyErr_Occurred()))
152 return NULL;
153
154 if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000155 return _PyUnicode_AsString(action);
Christian Heimes33fe8092008-04-13 13:53:33 +0000156 }
157
Brett Cannon0759dd62009-04-01 18:13:07 +0000158 action = get_default_action();
159 if (action != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000160 return _PyUnicode_AsString(action);
Brett Cannon0759dd62009-04-01 18:13:07 +0000161 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000162
163 PyErr_SetString(PyExc_ValueError,
Brett Cannon0759dd62009-04-01 18:13:07 +0000164 MODULE_NAME ".defaultaction not found");
Christian Heimes33fe8092008-04-13 13:53:33 +0000165 return NULL;
166}
167
Brett Cannon0759dd62009-04-01 18:13:07 +0000168
Christian Heimes33fe8092008-04-13 13:53:33 +0000169static int
170already_warned(PyObject *registry, PyObject *key, int should_set)
171{
172 PyObject *already_warned;
173
174 if (key == NULL)
175 return -1;
176
177 already_warned = PyDict_GetItem(registry, key);
178 if (already_warned != NULL) {
179 int rc = PyObject_IsTrue(already_warned);
180 if (rc != 0)
181 return rc;
182 }
183
184 /* This warning wasn't found in the registry, set it. */
185 if (should_set)
186 return PyDict_SetItem(registry, key, Py_True);
187 return 0;
188}
189
190/* New reference. */
191static PyObject *
192normalize_module(PyObject *filename)
193{
194 PyObject *module;
195 const char *mod_str;
196 Py_ssize_t len;
197
198 int rc = PyObject_IsTrue(filename);
199 if (rc == -1)
200 return NULL;
201 else if (rc == 0)
202 return PyUnicode_FromString("<unknown>");
203
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000204 mod_str = _PyUnicode_AsString(filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000205 if (mod_str == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000207 len = PyUnicode_GetSize(filename);
208 if (len < 0)
209 return NULL;
210 if (len >= 3 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 strncmp(mod_str + (len - 3), ".py", 3) == 0) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000212 module = PyUnicode_FromStringAndSize(mod_str, len-3);
213 }
214 else {
215 module = filename;
216 Py_INCREF(module);
217 }
218 return module;
219}
220
221static int
222update_registry(PyObject *registry, PyObject *text, PyObject *category,
223 int add_zero)
224{
225 PyObject *altkey, *zero = NULL;
226 int rc;
227
228 if (add_zero) {
229 zero = PyLong_FromLong(0);
230 if (zero == NULL)
231 return -1;
232 altkey = PyTuple_Pack(3, text, category, zero);
233 }
234 else
235 altkey = PyTuple_Pack(2, text, category);
236
237 rc = already_warned(registry, altkey, 1);
238 Py_XDECREF(zero);
239 Py_XDECREF(altkey);
240 return rc;
241}
242
243static void
244show_warning(PyObject *filename, int lineno, PyObject *text, PyObject
245 *category, PyObject *sourceline)
246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyObject *f_stderr;
248 PyObject *name;
Christian Heimes33fe8092008-04-13 13:53:33 +0000249 char lineno_str[128];
250
251 PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);
252
253 name = PyObject_GetAttrString(category, "__name__");
254 if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000255 return;
Christian Heimes33fe8092008-04-13 13:53:33 +0000256
257 f_stderr = PySys_GetObject("stderr");
258 if (f_stderr == NULL) {
259 fprintf(stderr, "lost sys.stderr\n");
260 Py_DECREF(name);
261 return;
262 }
263
264 /* Print "filename:lineno: category: text\n" */
265 PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW);
266 PyFile_WriteString(lineno_str, f_stderr);
267 PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW);
268 PyFile_WriteString(": ", f_stderr);
269 PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW);
270 PyFile_WriteString("\n", f_stderr);
271 Py_XDECREF(name);
272
273 /* Print " source_line\n" */
Christian Heimes33fe8092008-04-13 13:53:33 +0000274 if (sourceline) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000275 char *source_line_str = _PyUnicode_AsString(sourceline);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 if (source_line_str == NULL)
277 return;
Christian Heimes33fe8092008-04-13 13:53:33 +0000278 while (*source_line_str == ' ' || *source_line_str == '\t' ||
279 *source_line_str == '\014')
280 source_line_str++;
281
282 PyFile_WriteString(source_line_str, f_stderr);
283 PyFile_WriteString("\n", f_stderr);
284 }
285 else
Victor Stinner0fe25a42010-06-17 23:08:50 +0000286 if (_Py_DisplaySourceLine(f_stderr, filename, lineno, 2) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return;
Christian Heimes33fe8092008-04-13 13:53:33 +0000288 PyErr_Clear();
289}
290
291static PyObject *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292warn_explicit(PyObject *category, PyObject *message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000293 PyObject *filename, int lineno,
294 PyObject *module, PyObject *registry, PyObject *sourceline)
295{
296 PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL;
297 PyObject *item = Py_None;
298 const char *action;
299 int rc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300
Brett Cannondb734912008-06-27 00:52:15 +0000301 if (registry && !PyDict_Check(registry) && (registry != Py_None)) {
302 PyErr_SetString(PyExc_TypeError, "'registry' must be a dict");
303 return NULL;
304 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000305
306 /* Normalize module. */
307 if (module == NULL) {
308 module = normalize_module(filename);
309 if (module == NULL)
310 return NULL;
311 }
312 else
313 Py_INCREF(module);
314
315 /* Normalize message. */
316 Py_INCREF(message); /* DECREF'ed in cleanup. */
317 rc = PyObject_IsInstance(message, PyExc_Warning);
318 if (rc == -1) {
319 goto cleanup;
320 }
321 if (rc == 1) {
322 text = PyObject_Str(message);
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000323 if (text == NULL)
324 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000325 category = (PyObject*)message->ob_type;
326 }
327 else {
328 text = message;
329 message = PyObject_CallFunction(category, "O", message);
Brett Cannondb734912008-06-27 00:52:15 +0000330 if (message == NULL)
331 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000332 }
333
334 lineno_obj = PyLong_FromLong(lineno);
335 if (lineno_obj == NULL)
336 goto cleanup;
337
338 /* Create key. */
339 key = PyTuple_Pack(3, text, category, lineno_obj);
340 if (key == NULL)
341 goto cleanup;
342
Brett Cannondb734912008-06-27 00:52:15 +0000343 if ((registry != NULL) && (registry != Py_None)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000344 rc = already_warned(registry, key, 0);
345 if (rc == -1)
346 goto cleanup;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 else if (rc == 1)
Christian Heimes33fe8092008-04-13 13:53:33 +0000348 goto return_none;
349 /* Else this warning hasn't been generated before. */
350 }
351
352 action = get_filter(category, text, lineno, module, &item);
353 if (action == NULL)
354 goto cleanup;
355
356 if (strcmp(action, "error") == 0) {
357 PyErr_SetObject(category, message);
358 goto cleanup;
359 }
360
361 /* Store in the registry that we've been here, *except* when the action
362 is "always". */
363 rc = 0;
364 if (strcmp(action, "always") != 0) {
Brett Cannondb734912008-06-27 00:52:15 +0000365 if (registry != NULL && registry != Py_None &&
366 PyDict_SetItem(registry, key, Py_True) < 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000367 goto cleanup;
368 else if (strcmp(action, "ignore") == 0)
369 goto return_none;
370 else if (strcmp(action, "once") == 0) {
Brett Cannondb734912008-06-27 00:52:15 +0000371 if (registry == NULL || registry == Py_None) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000372 registry = get_once_registry();
373 if (registry == NULL)
374 goto cleanup;
375 }
376 /* _once_registry[(text, category)] = 1 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000378 }
379 else if (strcmp(action, "module") == 0) {
380 /* registry[(text, category, 0)] = 1 */
Brett Cannondb734912008-06-27 00:52:15 +0000381 if (registry != NULL && registry != Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000383 }
384 else if (strcmp(action, "default") != 0) {
385 PyObject *to_str = PyObject_Str(item);
386 const char *err_str = "???";
387
Brett Cannon54bd41d2008-09-02 04:01:42 +0000388 if (to_str != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000389 err_str = _PyUnicode_AsString(to_str);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 if (err_str == NULL)
391 goto cleanup;
392 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000393 PyErr_Format(PyExc_RuntimeError,
394 "Unrecognized action (%s) in warnings.filters:\n %s",
395 action, err_str);
396 Py_XDECREF(to_str);
397 goto cleanup;
398 }
399 }
400
Christian Heimes1a8501c2008-10-02 19:56:01 +0000401 if (rc == 1) /* Already warned for this module. */
Christian Heimes33fe8092008-04-13 13:53:33 +0000402 goto return_none;
403 if (rc == 0) {
404 PyObject *show_fxn = get_warnings_attr("showwarning");
405 if (show_fxn == NULL) {
406 if (PyErr_Occurred())
407 goto cleanup;
408 show_warning(filename, lineno, text, category, sourceline);
409 }
410 else {
Brett Cannonec92e182008-09-02 02:46:59 +0000411 PyObject *res;
Christian Heimes8dc226f2008-05-06 23:45:46 +0000412
Brett Cannon52a7d982011-07-17 19:17:55 -0700413 if (!PyCallable_Check(show_fxn)) {
Brett Cannonec92e182008-09-02 02:46:59 +0000414 PyErr_SetString(PyExc_TypeError,
415 "warnings.showwarning() must be set to a "
Brett Cannon52a7d982011-07-17 19:17:55 -0700416 "callable");
Christian Heimes8dc226f2008-05-06 23:45:46 +0000417 Py_DECREF(show_fxn);
Brett Cannonec92e182008-09-02 02:46:59 +0000418 goto cleanup;
Christian Heimes8dc226f2008-05-06 23:45:46 +0000419 }
Brett Cannonec92e182008-09-02 02:46:59 +0000420
421 res = PyObject_CallFunctionObjArgs(show_fxn, message, category,
422 filename, lineno_obj,
423 NULL);
424 Py_DECREF(show_fxn);
425 Py_XDECREF(res);
426 if (res == NULL)
427 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000428 }
429 }
430 else /* if (rc == -1) */
431 goto cleanup;
432
433 return_none:
434 result = Py_None;
435 Py_INCREF(result);
436
437 cleanup:
438 Py_XDECREF(key);
439 Py_XDECREF(text);
440 Py_XDECREF(lineno_obj);
441 Py_DECREF(module);
Brett Cannondb734912008-06-27 00:52:15 +0000442 Py_XDECREF(message);
Christian Heimes33fe8092008-04-13 13:53:33 +0000443 return result; /* Py_None or NULL. */
444}
445
446/* filename, module, and registry are new refs, globals is borrowed */
447/* Returns 0 on error (no new refs), 1 on success */
448static int
449setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
450 PyObject **module, PyObject **registry)
451{
452 PyObject *globals;
453
454 /* Setup globals and lineno. */
455 PyFrameObject *f = PyThreadState_GET()->frame;
Christian Heimes5d8da202008-05-06 13:58:24 +0000456 while (--stack_level > 0 && f != NULL)
Christian Heimes33fe8092008-04-13 13:53:33 +0000457 f = f->f_back;
Christian Heimes33fe8092008-04-13 13:53:33 +0000458
459 if (f == NULL) {
460 globals = PyThreadState_Get()->interp->sysdict;
461 *lineno = 1;
462 }
463 else {
464 globals = f->f_globals;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000465 *lineno = PyFrame_GetLineNumber(f);
Christian Heimes33fe8092008-04-13 13:53:33 +0000466 }
467
468 *module = NULL;
469
470 /* Setup registry. */
471 assert(globals != NULL);
472 assert(PyDict_Check(globals));
473 *registry = PyDict_GetItemString(globals, "__warningregistry__");
474 if (*registry == NULL) {
475 int rc;
476
477 *registry = PyDict_New();
478 if (*registry == NULL)
479 return 0;
480
481 rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
482 if (rc < 0)
483 goto handle_error;
484 }
485 else
486 Py_INCREF(*registry);
487
488 /* Setup module. */
489 *module = PyDict_GetItemString(globals, "__name__");
490 if (*module == NULL) {
491 *module = PyUnicode_FromString("<string>");
492 if (*module == NULL)
493 goto handle_error;
494 }
495 else
496 Py_INCREF(*module);
497
498 /* Setup filename. */
499 *filename = PyDict_GetItemString(globals, "__file__");
Victor Stinner8b0508e2011-07-04 02:43:09 +0200500 if (*filename != NULL && PyUnicode_Check(*filename)) {
Victor Stinnerb62a7b22011-10-06 02:34:51 +0200501 Py_ssize_t len;
502 int kind;
503 void *data;
504
505 if (PyUnicode_READY(*filename))
506 goto handle_error;
507
508 len = PyUnicode_GetSize(*filename);
509 kind = PyUnicode_KIND(*filename);
510 data = PyUnicode_DATA(*filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000511
512 /* if filename.lower().endswith((".pyc", ".pyo")): */
513 if (len >= 4 &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200514 PyUnicode_READ(kind, data, len-4) == '.' &&
515 Py_UNICODE_TOLOWER(PyUnicode_READ(kind, data, len-3)) == 'p' &&
516 Py_UNICODE_TOLOWER(PyUnicode_READ(kind, data, len-2)) == 'y' &&
517 (Py_UNICODE_TOLOWER(PyUnicode_READ(kind, data, len-1)) == 'c' ||
518 Py_UNICODE_TOLOWER(PyUnicode_READ(kind, data, len-1)) == 'o'))
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000519 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200520 *filename = PyUnicode_Substring(*filename, 0,
521 PyUnicode_GET_LENGTH(*filename)-1);
Victor Stinner2e5f1172010-08-08 22:12:45 +0000522 if (*filename == NULL)
523 goto handle_error;
524 }
525 else
Christian Heimes33fe8092008-04-13 13:53:33 +0000526 Py_INCREF(*filename);
527 }
528 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000529 const char *module_str = _PyUnicode_AsString(*module);
Benjamin Petersonbb4a7472011-07-04 22:27:16 -0500530 *filename = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (module_str == NULL)
532 goto handle_error;
Brett Cannon54bd41d2008-09-02 04:01:42 +0000533 if (strcmp(module_str, "__main__") == 0) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000534 PyObject *argv = PySys_GetObject("argv");
535 if (argv != NULL && PyList_Size(argv) > 0) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000536 int is_true;
Christian Heimes33fe8092008-04-13 13:53:33 +0000537 *filename = PyList_GetItem(argv, 0);
538 Py_INCREF(*filename);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000539 /* If sys.argv[0] is false, then use '__main__'. */
540 is_true = PyObject_IsTrue(*filename);
541 if (is_true < 0) {
542 Py_DECREF(*filename);
543 goto handle_error;
544 }
545 else if (!is_true) {
546 Py_DECREF(*filename);
Benjamin Peterson9f4bf1d2008-05-04 23:22:13 +0000547 *filename = PyUnicode_FromString("__main__");
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000548 if (*filename == NULL)
549 goto handle_error;
550 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000551 }
552 else {
553 /* embedded interpreters don't have sys.argv, see bug #839151 */
554 *filename = PyUnicode_FromString("__main__");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (*filename == NULL)
556 goto handle_error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000557 }
558 }
559 if (*filename == NULL) {
560 *filename = *module;
561 Py_INCREF(*filename);
562 }
563 }
564
565 return 1;
566
567 handle_error:
568 /* filename not XDECREF'ed here as there is no way to jump here with a
569 dangling reference. */
570 Py_XDECREF(*registry);
571 Py_XDECREF(*module);
572 return 0;
573}
574
575static PyObject *
576get_category(PyObject *message, PyObject *category)
577{
578 int rc;
579
580 /* Get category. */
581 rc = PyObject_IsInstance(message, PyExc_Warning);
582 if (rc == -1)
583 return NULL;
584
585 if (rc == 1)
586 category = (PyObject*)message->ob_type;
587 else if (category == NULL)
588 category = PyExc_UserWarning;
589
590 /* Validate category. */
591 rc = PyObject_IsSubclass(category, PyExc_Warning);
592 if (rc == -1)
593 return NULL;
594 if (rc == 0) {
595 PyErr_SetString(PyExc_ValueError,
596 "category is not a subclass of Warning");
597 return NULL;
598 }
599
600 return category;
601}
602
603static PyObject *
604do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level)
605{
606 PyObject *filename, *module, *registry, *res;
607 int lineno;
608
609 if (!setup_context(stack_level, &filename, &lineno, &module, &registry))
610 return NULL;
611
612 res = warn_explicit(category, message, filename, lineno, module, registry,
613 NULL);
614 Py_DECREF(filename);
615 Py_DECREF(registry);
616 Py_DECREF(module);
617 return res;
618}
619
620static PyObject *
621warnings_warn(PyObject *self, PyObject *args, PyObject *kwds)
622{
623 static char *kw_list[] = { "message", "category", "stacklevel", 0 };
624 PyObject *message, *category = NULL;
625 Py_ssize_t stack_level = 1;
626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list,
Christian Heimes33fe8092008-04-13 13:53:33 +0000628 &message, &category, &stack_level))
629 return NULL;
630
631 category = get_category(message, category);
632 if (category == NULL)
633 return NULL;
634 return do_warn(message, category, stack_level);
635}
636
637static PyObject *
638warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
639{
640 static char *kwd_list[] = {"message", "category", "filename", "lineno",
641 "module", "registry", "module_globals", 0};
642 PyObject *message;
643 PyObject *category;
644 PyObject *filename;
645 int lineno;
646 PyObject *module = NULL;
647 PyObject *registry = NULL;
648 PyObject *module_globals = NULL;
649
650 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOi|OOO:warn_explicit",
651 kwd_list, &message, &category, &filename, &lineno, &module,
652 &registry, &module_globals))
653 return NULL;
654
655 if (module_globals) {
656 static PyObject *get_source_name = NULL;
657 static PyObject *splitlines_name = NULL;
658 PyObject *loader;
659 PyObject *module_name;
660 PyObject *source;
661 PyObject *source_list;
662 PyObject *source_line;
663 PyObject *returned;
664
665 if (get_source_name == NULL) {
666 get_source_name = PyUnicode_InternFromString("get_source");
667 if (!get_source_name)
668 return NULL;
669 }
670 if (splitlines_name == NULL) {
671 splitlines_name = PyUnicode_InternFromString("splitlines");
672 if (!splitlines_name)
673 return NULL;
674 }
675
676 /* Check/get the requisite pieces needed for the loader. */
677 loader = PyDict_GetItemString(module_globals, "__loader__");
678 module_name = PyDict_GetItemString(module_globals, "__name__");
679
680 if (loader == NULL || module_name == NULL)
681 goto standard_call;
682
683 /* Make sure the loader implements the optional get_source() method. */
684 if (!PyObject_HasAttrString(loader, "get_source"))
685 goto standard_call;
686 /* Call get_source() to get the source code. */
687 source = PyObject_CallMethodObjArgs(loader, get_source_name,
688 module_name, NULL);
689 if (!source)
690 return NULL;
691 else if (source == Py_None) {
692 Py_DECREF(Py_None);
693 goto standard_call;
694 }
695
696 /* Split the source into lines. */
697 source_list = PyObject_CallMethodObjArgs(source, splitlines_name,
698 NULL);
699 Py_DECREF(source);
700 if (!source_list)
701 return NULL;
702
703 /* Get the source line. */
704 source_line = PyList_GetItem(source_list, lineno-1);
705 if (!source_line) {
706 Py_DECREF(source_list);
707 return NULL;
708 }
709
710 /* Handle the warning. */
711 returned = warn_explicit(category, message, filename, lineno, module,
712 registry, source_line);
713 Py_DECREF(source_list);
714 return returned;
715 }
716
717 standard_call:
718 return warn_explicit(category, message, filename, lineno, module,
719 registry, NULL);
720}
721
722
723/* Function to issue a warning message; may raise an exception. */
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000724
725static int
726warn_unicode(PyObject *category, PyObject *message,
727 Py_ssize_t stack_level)
Christian Heimes33fe8092008-04-13 13:53:33 +0000728{
729 PyObject *res;
Christian Heimes33fe8092008-04-13 13:53:33 +0000730
731 if (category == NULL)
732 category = PyExc_RuntimeWarning;
733
734 res = do_warn(message, category, stack_level);
Christian Heimes33fe8092008-04-13 13:53:33 +0000735 if (res == NULL)
736 return -1;
737 Py_DECREF(res);
738
739 return 0;
740}
741
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000742int
743PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level,
744 const char *format, ...)
745{
746 int ret;
747 PyObject *message;
748 va_list vargs;
749
750#ifdef HAVE_STDARG_PROTOTYPES
751 va_start(vargs, format);
752#else
753 va_start(vargs);
754#endif
755 message = PyUnicode_FromFormatV(format, vargs);
756 if (message != NULL) {
757 ret = warn_unicode(category, message, stack_level);
758 Py_DECREF(message);
759 }
760 else
761 ret = -1;
762 va_end(vargs);
763 return ret;
764}
765
766int
767PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
768{
769 int ret;
770 PyObject *message = PyUnicode_FromString(text);
771 if (message == NULL)
772 return -1;
773 ret = warn_unicode(category, message, stack_level);
774 Py_DECREF(message);
775 return ret;
776}
777
Ezio Melotti42da6632011-03-15 05:18:48 +0200778/* PyErr_Warn is only for backwards compatibility and will be removed.
Christian Heimes33fe8092008-04-13 13:53:33 +0000779 Use PyErr_WarnEx instead. */
780
781#undef PyErr_Warn
782
783PyAPI_FUNC(int)
784PyErr_Warn(PyObject *category, char *text)
785{
786 return PyErr_WarnEx(category, text, 1);
787}
788
789/* Warning with explicit origin */
790int
791PyErr_WarnExplicit(PyObject *category, const char *text,
792 const char *filename_str, int lineno,
793 const char *module_str, PyObject *registry)
794{
795 PyObject *res;
796 PyObject *message = PyUnicode_FromString(text);
Victor Stinnercb428f02010-12-27 20:10:36 +0000797 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
Christian Heimes33fe8092008-04-13 13:53:33 +0000798 PyObject *module = NULL;
799 int ret = -1;
800
801 if (message == NULL || filename == NULL)
802 goto exit;
803 if (module_str != NULL) {
804 module = PyUnicode_FromString(module_str);
805 if (module == NULL)
806 goto exit;
807 }
808
809 if (category == NULL)
810 category = PyExc_RuntimeWarning;
811 res = warn_explicit(category, message, filename, lineno, module, registry,
812 NULL);
813 if (res == NULL)
814 goto exit;
815 Py_DECREF(res);
816 ret = 0;
817
818 exit:
819 Py_XDECREF(message);
820 Py_XDECREF(module);
821 Py_XDECREF(filename);
822 return ret;
823}
824
825
826PyDoc_STRVAR(warn_doc,
827"Issue a warning, or maybe ignore it or raise an exception.");
828
829PyDoc_STRVAR(warn_explicit_doc,
830"Low-level inferface to warnings functionality.");
831
832static PyMethodDef warnings_functions[] = {
833 {"warn", (PyCFunction)warnings_warn, METH_VARARGS | METH_KEYWORDS,
834 warn_doc},
835 {"warn_explicit", (PyCFunction)warnings_warn_explicit,
836 METH_VARARGS | METH_KEYWORDS, warn_explicit_doc},
Christian Heimes1a8501c2008-10-02 19:56:01 +0000837 /* XXX(brett.cannon): add showwarning? */
838 /* XXX(brett.cannon): Reasonable to add formatwarning? */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 {NULL, NULL} /* sentinel */
Christian Heimes33fe8092008-04-13 13:53:33 +0000840};
841
842
843static PyObject *
844create_filter(PyObject *category, const char *action)
845{
846 static PyObject *ignore_str = NULL;
847 static PyObject *error_str = NULL;
848 static PyObject *default_str = NULL;
Georg Brandl08be72d2010-10-24 15:11:22 +0000849 static PyObject *always_str = NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000850 PyObject *action_obj = NULL;
851 PyObject *lineno, *result;
852
853 if (!strcmp(action, "ignore")) {
854 if (ignore_str == NULL) {
855 ignore_str = PyUnicode_InternFromString("ignore");
856 if (ignore_str == NULL)
857 return NULL;
858 }
859 action_obj = ignore_str;
860 }
861 else if (!strcmp(action, "error")) {
862 if (error_str == NULL) {
863 error_str = PyUnicode_InternFromString("error");
864 if (error_str == NULL)
865 return NULL;
866 }
867 action_obj = error_str;
868 }
869 else if (!strcmp(action, "default")) {
870 if (default_str == NULL) {
871 default_str = PyUnicode_InternFromString("default");
872 if (default_str == NULL)
873 return NULL;
874 }
875 action_obj = default_str;
876 }
Georg Brandl08be72d2010-10-24 15:11:22 +0000877 else if (!strcmp(action, "always")) {
878 if (always_str == NULL) {
879 always_str = PyUnicode_InternFromString("always");
880 if (always_str == NULL)
881 return NULL;
882 }
883 action_obj = always_str;
884 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000885 else {
886 Py_FatalError("unknown action");
887 }
888
889 /* This assumes the line number is zero for now. */
890 lineno = PyLong_FromLong(0);
891 if (lineno == NULL)
892 return NULL;
893 result = PyTuple_Pack(5, action_obj, Py_None, category, Py_None, lineno);
894 Py_DECREF(lineno);
895 return result;
896}
897
898static PyObject *
899init_filters(void)
900{
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000901 /* Don't silence DeprecationWarning if -3 was used. */
Georg Brandl08be72d2010-10-24 15:11:22 +0000902 PyObject *filters = PyList_New(5);
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000903 unsigned int pos = 0; /* Post-incremented in each use. */
904 unsigned int x;
Georg Brandl08be72d2010-10-24 15:11:22 +0000905 const char *bytes_action, *resource_action;
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000906
Christian Heimes33fe8092008-04-13 13:53:33 +0000907 if (filters == NULL)
908 return NULL;
909
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000910 PyList_SET_ITEM(filters, pos++,
911 create_filter(PyExc_DeprecationWarning, "ignore"));
912 PyList_SET_ITEM(filters, pos++,
Christian Heimes33fe8092008-04-13 13:53:33 +0000913 create_filter(PyExc_PendingDeprecationWarning, "ignore"));
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000914 PyList_SET_ITEM(filters, pos++,
915 create_filter(PyExc_ImportWarning, "ignore"));
Christian Heimes33fe8092008-04-13 13:53:33 +0000916 if (Py_BytesWarningFlag > 1)
917 bytes_action = "error";
918 else if (Py_BytesWarningFlag)
919 bytes_action = "default";
920 else
921 bytes_action = "ignore";
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000922 PyList_SET_ITEM(filters, pos++, create_filter(PyExc_BytesWarning,
Christian Heimes33fe8092008-04-13 13:53:33 +0000923 bytes_action));
Georg Brandl08be72d2010-10-24 15:11:22 +0000924 /* resource usage warnings are enabled by default in pydebug mode */
925#ifdef Py_DEBUG
926 resource_action = "always";
927#else
928 resource_action = "ignore";
929#endif
930 PyList_SET_ITEM(filters, pos++, create_filter(PyExc_ResourceWarning,
931 resource_action));
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000932 for (x = 0; x < pos; x += 1) {
933 if (PyList_GET_ITEM(filters, x) == NULL) {
934 Py_DECREF(filters);
935 return NULL;
936 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000937 }
938
939 return filters;
940}
941
Martin v. Löwis1a214512008-06-11 05:26:20 +0000942static struct PyModuleDef warningsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 PyModuleDef_HEAD_INIT,
944 MODULE_NAME,
945 warnings__doc__,
946 0,
947 warnings_functions,
948 NULL,
949 NULL,
950 NULL,
951 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +0000952};
953
Christian Heimes33fe8092008-04-13 13:53:33 +0000954
955PyMODINIT_FUNC
956_PyWarnings_Init(void)
957{
Brett Cannon0759dd62009-04-01 18:13:07 +0000958 PyObject *m;
Christian Heimes33fe8092008-04-13 13:53:33 +0000959
Martin v. Löwis1a214512008-06-11 05:26:20 +0000960 m = PyModule_Create(&warningsmodule);
Christian Heimes33fe8092008-04-13 13:53:33 +0000961 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000962 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000963
964 _filters = init_filters();
965 if (_filters == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000966 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000967 Py_INCREF(_filters);
968 if (PyModule_AddObject(m, "filters", _filters) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000969 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000970
971 _once_registry = PyDict_New();
972 if (_once_registry == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000973 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000974 Py_INCREF(_once_registry);
Brett Cannonef0e6c32010-09-04 18:24:04 +0000975 if (PyModule_AddObject(m, "_onceregistry", _once_registry) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000976 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000977
Brett Cannon0759dd62009-04-01 18:13:07 +0000978 _default_action = PyUnicode_FromString("default");
979 if (_default_action == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000980 return NULL;
Brett Cannonef0e6c32010-09-04 18:24:04 +0000981 if (PyModule_AddObject(m, "_defaultaction", _default_action) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000982 return NULL;
983 return m;
Christian Heimes33fe8092008-04-13 13:53:33 +0000984}