blob: 74ac8c65bffffcb75f50bd64a21dec16a6521457 [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öwisbd928fe2011-10-14 10:20:37 +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. */
Victor Stinnera4c704b2013-10-29 23:43:41 +0100102static PyObject*
Christian Heimes33fe8092008-04-13 13:53:33 +0000103get_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);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100147 if (good_msg == -1)
148 return NULL;
149
Christian Heimes33fe8092008-04-13 13:53:33 +0000150 good_mod = check_matched(mod, module);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100151 if (good_mod == -1)
152 return NULL;
153
Christian Heimes33fe8092008-04-13 13:53:33 +0000154 is_subclass = PyObject_IsSubclass(category, cat);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100155 if (is_subclass == -1)
156 return NULL;
157
Christian Heimes33fe8092008-04-13 13:53:33 +0000158 ln = PyLong_AsSsize_t(ln_obj);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100159 if (ln == -1 && PyErr_Occurred())
Christian Heimes33fe8092008-04-13 13:53:33 +0000160 return NULL;
161
162 if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln))
Victor Stinnera4c704b2013-10-29 23:43:41 +0100163 return action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000164 }
165
Brett Cannon0759dd62009-04-01 18:13:07 +0000166 action = get_default_action();
Victor Stinnera4c704b2013-10-29 23:43:41 +0100167 if (action != NULL)
168 return action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000169
170 PyErr_SetString(PyExc_ValueError,
Brett Cannon0759dd62009-04-01 18:13:07 +0000171 MODULE_NAME ".defaultaction not found");
Christian Heimes33fe8092008-04-13 13:53:33 +0000172 return NULL;
173}
174
Brett Cannon0759dd62009-04-01 18:13:07 +0000175
Christian Heimes33fe8092008-04-13 13:53:33 +0000176static int
177already_warned(PyObject *registry, PyObject *key, int should_set)
178{
179 PyObject *already_warned;
180
181 if (key == NULL)
182 return -1;
183
184 already_warned = PyDict_GetItem(registry, key);
185 if (already_warned != NULL) {
186 int rc = PyObject_IsTrue(already_warned);
187 if (rc != 0)
188 return rc;
189 }
190
191 /* This warning wasn't found in the registry, set it. */
192 if (should_set)
193 return PyDict_SetItem(registry, key, Py_True);
194 return 0;
195}
196
197/* New reference. */
198static PyObject *
199normalize_module(PyObject *filename)
200{
201 PyObject *module;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100202 int kind;
203 void *data;
Christian Heimes33fe8092008-04-13 13:53:33 +0000204 Py_ssize_t len;
205
Victor Stinner9e30aa52011-11-21 02:49:52 +0100206 len = PyUnicode_GetLength(filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000207 if (len < 0)
208 return NULL;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100209
210 if (len == 0)
211 return PyUnicode_FromString("<unknown>");
212
213 kind = PyUnicode_KIND(filename);
214 data = PyUnicode_DATA(filename);
215
216 /* if filename.endswith(".py"): */
Christian Heimes33fe8092008-04-13 13:53:33 +0000217 if (len >= 3 &&
Victor Stinnera4c704b2013-10-29 23:43:41 +0100218 PyUnicode_READ(kind, data, len-3) == '.' &&
219 PyUnicode_READ(kind, data, len-2) == 'p' &&
220 PyUnicode_READ(kind, data, len-1) == 'y')
221 {
Victor Stinner9e30aa52011-11-21 02:49:52 +0100222 module = PyUnicode_Substring(filename, 0, len-3);
Christian Heimes33fe8092008-04-13 13:53:33 +0000223 }
224 else {
225 module = filename;
226 Py_INCREF(module);
227 }
228 return module;
229}
230
231static int
232update_registry(PyObject *registry, PyObject *text, PyObject *category,
233 int add_zero)
234{
235 PyObject *altkey, *zero = NULL;
236 int rc;
237
238 if (add_zero) {
239 zero = PyLong_FromLong(0);
240 if (zero == NULL)
241 return -1;
242 altkey = PyTuple_Pack(3, text, category, zero);
243 }
244 else
245 altkey = PyTuple_Pack(2, text, category);
246
247 rc = already_warned(registry, altkey, 1);
248 Py_XDECREF(zero);
249 Py_XDECREF(altkey);
250 return rc;
251}
252
253static void
254show_warning(PyObject *filename, int lineno, PyObject *text, PyObject
255 *category, PyObject *sourceline)
256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 PyObject *f_stderr;
258 PyObject *name;
Christian Heimes33fe8092008-04-13 13:53:33 +0000259 char lineno_str[128];
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200260 _Py_IDENTIFIER(__name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000261
262 PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);
263
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200264 name = _PyObject_GetAttrId(category, &PyId___name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000265 if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000266 return;
Christian Heimes33fe8092008-04-13 13:53:33 +0000267
268 f_stderr = PySys_GetObject("stderr");
269 if (f_stderr == NULL) {
270 fprintf(stderr, "lost sys.stderr\n");
271 Py_DECREF(name);
272 return;
273 }
274
275 /* Print "filename:lineno: category: text\n" */
276 PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW);
277 PyFile_WriteString(lineno_str, f_stderr);
278 PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW);
279 PyFile_WriteString(": ", f_stderr);
280 PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW);
281 PyFile_WriteString("\n", f_stderr);
282 Py_XDECREF(name);
283
284 /* Print " source_line\n" */
Christian Heimes33fe8092008-04-13 13:53:33 +0000285 if (sourceline) {
Victor Stinnera4c704b2013-10-29 23:43:41 +0100286 int kind;
287 void *data;
288 Py_ssize_t i, len;
289 Py_UCS4 ch;
290 PyObject *truncated;
Christian Heimes33fe8092008-04-13 13:53:33 +0000291
Victor Stinnera4c704b2013-10-29 23:43:41 +0100292 if (PyUnicode_READY(sourceline) < 1)
293 goto error;
294
295 kind = PyUnicode_KIND(sourceline);
296 data = PyUnicode_DATA(sourceline);
297 len = PyUnicode_GET_LENGTH(sourceline);
298 for (i=0; i<len; i++) {
299 ch = PyUnicode_READ(kind, data, i);
300 if (ch != ' ' && ch != '\t' && ch != '\014')
301 break;
302 }
303
304 truncated = PyUnicode_Substring(sourceline, i, len);
305 if (truncated == NULL)
306 goto error;
307
308 PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW);
309 Py_DECREF(truncated);
Christian Heimes33fe8092008-04-13 13:53:33 +0000310 PyFile_WriteString("\n", f_stderr);
311 }
Victor Stinner78e2c982013-07-16 01:54:37 +0200312 else {
313 _Py_DisplaySourceLine(f_stderr, filename, lineno, 2);
314 }
Victor Stinnera4c704b2013-10-29 23:43:41 +0100315
316error:
Christian Heimes33fe8092008-04-13 13:53:33 +0000317 PyErr_Clear();
318}
319
320static PyObject *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321warn_explicit(PyObject *category, PyObject *message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000322 PyObject *filename, int lineno,
323 PyObject *module, PyObject *registry, PyObject *sourceline)
324{
325 PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL;
326 PyObject *item = Py_None;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100327 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000328 int rc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329
Brett Cannondb734912008-06-27 00:52:15 +0000330 if (registry && !PyDict_Check(registry) && (registry != Py_None)) {
331 PyErr_SetString(PyExc_TypeError, "'registry' must be a dict");
332 return NULL;
333 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000334
335 /* Normalize module. */
336 if (module == NULL) {
337 module = normalize_module(filename);
338 if (module == NULL)
339 return NULL;
340 }
341 else
342 Py_INCREF(module);
343
344 /* Normalize message. */
345 Py_INCREF(message); /* DECREF'ed in cleanup. */
346 rc = PyObject_IsInstance(message, PyExc_Warning);
347 if (rc == -1) {
348 goto cleanup;
349 }
350 if (rc == 1) {
351 text = PyObject_Str(message);
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000352 if (text == NULL)
353 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000354 category = (PyObject*)message->ob_type;
355 }
356 else {
357 text = message;
358 message = PyObject_CallFunction(category, "O", message);
Brett Cannondb734912008-06-27 00:52:15 +0000359 if (message == NULL)
360 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000361 }
362
363 lineno_obj = PyLong_FromLong(lineno);
364 if (lineno_obj == NULL)
365 goto cleanup;
366
367 /* Create key. */
368 key = PyTuple_Pack(3, text, category, lineno_obj);
369 if (key == NULL)
370 goto cleanup;
371
Brett Cannondb734912008-06-27 00:52:15 +0000372 if ((registry != NULL) && (registry != Py_None)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000373 rc = already_warned(registry, key, 0);
374 if (rc == -1)
375 goto cleanup;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 else if (rc == 1)
Christian Heimes33fe8092008-04-13 13:53:33 +0000377 goto return_none;
378 /* Else this warning hasn't been generated before. */
379 }
380
381 action = get_filter(category, text, lineno, module, &item);
382 if (action == NULL)
383 goto cleanup;
384
Victor Stinnera4c704b2013-10-29 23:43:41 +0100385 if (PyUnicode_CompareWithASCIIString(action, "error") == 0) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000386 PyErr_SetObject(category, message);
387 goto cleanup;
388 }
389
390 /* Store in the registry that we've been here, *except* when the action
391 is "always". */
392 rc = 0;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100393 if (PyUnicode_CompareWithASCIIString(action, "always") != 0) {
Brett Cannondb734912008-06-27 00:52:15 +0000394 if (registry != NULL && registry != Py_None &&
395 PyDict_SetItem(registry, key, Py_True) < 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000396 goto cleanup;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100397 else if (PyUnicode_CompareWithASCIIString(action, "ignore") == 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000398 goto return_none;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100399 else if (PyUnicode_CompareWithASCIIString(action, "once") == 0) {
Brett Cannondb734912008-06-27 00:52:15 +0000400 if (registry == NULL || registry == Py_None) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000401 registry = get_once_registry();
402 if (registry == NULL)
403 goto cleanup;
404 }
405 /* _once_registry[(text, category)] = 1 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000407 }
Victor Stinnera4c704b2013-10-29 23:43:41 +0100408 else if (PyUnicode_CompareWithASCIIString(action, "module") == 0) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000409 /* registry[(text, category, 0)] = 1 */
Brett Cannondb734912008-06-27 00:52:15 +0000410 if (registry != NULL && registry != Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000412 }
Victor Stinnera4c704b2013-10-29 23:43:41 +0100413 else if (PyUnicode_CompareWithASCIIString(action, "default") != 0) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000414 PyErr_Format(PyExc_RuntimeError,
Victor Stinnera4c704b2013-10-29 23:43:41 +0100415 "Unrecognized action (%R) in warnings.filters:\n %R",
416 action, item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000417 goto cleanup;
418 }
419 }
420
Christian Heimes1a8501c2008-10-02 19:56:01 +0000421 if (rc == 1) /* Already warned for this module. */
Christian Heimes33fe8092008-04-13 13:53:33 +0000422 goto return_none;
423 if (rc == 0) {
424 PyObject *show_fxn = get_warnings_attr("showwarning");
425 if (show_fxn == NULL) {
426 if (PyErr_Occurred())
427 goto cleanup;
428 show_warning(filename, lineno, text, category, sourceline);
429 }
430 else {
Brett Cannonec92e182008-09-02 02:46:59 +0000431 PyObject *res;
Christian Heimes8dc226f2008-05-06 23:45:46 +0000432
Brett Cannon52a7d982011-07-17 19:17:55 -0700433 if (!PyCallable_Check(show_fxn)) {
Brett Cannonec92e182008-09-02 02:46:59 +0000434 PyErr_SetString(PyExc_TypeError,
435 "warnings.showwarning() must be set to a "
Brett Cannon52a7d982011-07-17 19:17:55 -0700436 "callable");
Christian Heimes8dc226f2008-05-06 23:45:46 +0000437 Py_DECREF(show_fxn);
Brett Cannonec92e182008-09-02 02:46:59 +0000438 goto cleanup;
Christian Heimes8dc226f2008-05-06 23:45:46 +0000439 }
Brett Cannonec92e182008-09-02 02:46:59 +0000440
441 res = PyObject_CallFunctionObjArgs(show_fxn, message, category,
442 filename, lineno_obj,
443 NULL);
444 Py_DECREF(show_fxn);
445 Py_XDECREF(res);
446 if (res == NULL)
447 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000448 }
449 }
450 else /* if (rc == -1) */
451 goto cleanup;
452
453 return_none:
454 result = Py_None;
455 Py_INCREF(result);
456
457 cleanup:
458 Py_XDECREF(key);
459 Py_XDECREF(text);
460 Py_XDECREF(lineno_obj);
461 Py_DECREF(module);
Brett Cannondb734912008-06-27 00:52:15 +0000462 Py_XDECREF(message);
Christian Heimes33fe8092008-04-13 13:53:33 +0000463 return result; /* Py_None or NULL. */
464}
465
466/* filename, module, and registry are new refs, globals is borrowed */
467/* Returns 0 on error (no new refs), 1 on success */
468static int
469setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
470 PyObject **module, PyObject **registry)
471{
472 PyObject *globals;
473
474 /* Setup globals and lineno. */
475 PyFrameObject *f = PyThreadState_GET()->frame;
Christian Heimes5d8da202008-05-06 13:58:24 +0000476 while (--stack_level > 0 && f != NULL)
Christian Heimes33fe8092008-04-13 13:53:33 +0000477 f = f->f_back;
Christian Heimes33fe8092008-04-13 13:53:33 +0000478
479 if (f == NULL) {
480 globals = PyThreadState_Get()->interp->sysdict;
481 *lineno = 1;
482 }
483 else {
484 globals = f->f_globals;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000485 *lineno = PyFrame_GetLineNumber(f);
Christian Heimes33fe8092008-04-13 13:53:33 +0000486 }
487
488 *module = NULL;
489
490 /* Setup registry. */
491 assert(globals != NULL);
492 assert(PyDict_Check(globals));
493 *registry = PyDict_GetItemString(globals, "__warningregistry__");
494 if (*registry == NULL) {
495 int rc;
496
497 *registry = PyDict_New();
498 if (*registry == NULL)
499 return 0;
500
501 rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
502 if (rc < 0)
503 goto handle_error;
504 }
505 else
506 Py_INCREF(*registry);
507
508 /* Setup module. */
509 *module = PyDict_GetItemString(globals, "__name__");
510 if (*module == NULL) {
511 *module = PyUnicode_FromString("<string>");
512 if (*module == NULL)
513 goto handle_error;
514 }
515 else
516 Py_INCREF(*module);
517
518 /* Setup filename. */
519 *filename = PyDict_GetItemString(globals, "__file__");
Victor Stinner8b0508e2011-07-04 02:43:09 +0200520 if (*filename != NULL && PyUnicode_Check(*filename)) {
Victor Stinnerb62a7b22011-10-06 02:34:51 +0200521 Py_ssize_t len;
522 int kind;
523 void *data;
524
525 if (PyUnicode_READY(*filename))
526 goto handle_error;
527
Victor Stinner9e30aa52011-11-21 02:49:52 +0100528 len = PyUnicode_GetLength(*filename);
Victor Stinnerb62a7b22011-10-06 02:34:51 +0200529 kind = PyUnicode_KIND(*filename);
530 data = PyUnicode_DATA(*filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000531
Benjamin Peterson21e0da22012-01-11 21:00:42 -0500532#define ascii_lower(c) ((c <= 127) ? Py_TOLOWER(c) : 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000533 /* if filename.lower().endswith((".pyc", ".pyo")): */
534 if (len >= 4 &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200535 PyUnicode_READ(kind, data, len-4) == '.' &&
Benjamin Peterson21e0da22012-01-11 21:00:42 -0500536 ascii_lower(PyUnicode_READ(kind, data, len-3)) == 'p' &&
537 ascii_lower(PyUnicode_READ(kind, data, len-2)) == 'y' &&
538 (ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'c' ||
539 ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'o'))
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000540 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200541 *filename = PyUnicode_Substring(*filename, 0,
542 PyUnicode_GET_LENGTH(*filename)-1);
Victor Stinner2e5f1172010-08-08 22:12:45 +0000543 if (*filename == NULL)
544 goto handle_error;
545 }
546 else
Christian Heimes33fe8092008-04-13 13:53:33 +0000547 Py_INCREF(*filename);
548 }
549 else {
Benjamin Petersonbb4a7472011-07-04 22:27:16 -0500550 *filename = NULL;
Victor Stinner856f45f2013-10-30 00:04:59 +0100551 if (*module != Py_None && PyUnicode_CompareWithASCIIString(*module, "__main__") == 0) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000552 PyObject *argv = PySys_GetObject("argv");
Victor Stinnerce5f4fb2013-10-28 18:47:22 +0100553 /* PyList_Check() is needed because sys.argv is set to None during
554 Python finalization */
555 if (argv != NULL && PyList_Check(argv) && PyList_Size(argv) > 0) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000556 int is_true;
Christian Heimes33fe8092008-04-13 13:53:33 +0000557 *filename = PyList_GetItem(argv, 0);
558 Py_INCREF(*filename);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000559 /* If sys.argv[0] is false, then use '__main__'. */
560 is_true = PyObject_IsTrue(*filename);
561 if (is_true < 0) {
562 Py_DECREF(*filename);
563 goto handle_error;
564 }
565 else if (!is_true) {
566 Py_DECREF(*filename);
Benjamin Peterson9f4bf1d2008-05-04 23:22:13 +0000567 *filename = PyUnicode_FromString("__main__");
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000568 if (*filename == NULL)
569 goto handle_error;
570 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000571 }
572 else {
573 /* embedded interpreters don't have sys.argv, see bug #839151 */
574 *filename = PyUnicode_FromString("__main__");
Victor Stinner856f45f2013-10-30 00:04:59 +0100575 if (*filename == NULL)
576 goto handle_error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000577 }
578 }
579 if (*filename == NULL) {
580 *filename = *module;
581 Py_INCREF(*filename);
582 }
583 }
584
585 return 1;
586
587 handle_error:
588 /* filename not XDECREF'ed here as there is no way to jump here with a
589 dangling reference. */
590 Py_XDECREF(*registry);
591 Py_XDECREF(*module);
592 return 0;
593}
594
595static PyObject *
596get_category(PyObject *message, PyObject *category)
597{
598 int rc;
599
600 /* Get category. */
601 rc = PyObject_IsInstance(message, PyExc_Warning);
602 if (rc == -1)
603 return NULL;
604
605 if (rc == 1)
606 category = (PyObject*)message->ob_type;
607 else if (category == NULL)
608 category = PyExc_UserWarning;
609
610 /* Validate category. */
611 rc = PyObject_IsSubclass(category, PyExc_Warning);
612 if (rc == -1)
613 return NULL;
614 if (rc == 0) {
615 PyErr_SetString(PyExc_ValueError,
616 "category is not a subclass of Warning");
617 return NULL;
618 }
619
620 return category;
621}
622
623static PyObject *
624do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level)
625{
626 PyObject *filename, *module, *registry, *res;
627 int lineno;
628
629 if (!setup_context(stack_level, &filename, &lineno, &module, &registry))
630 return NULL;
631
Victor Stinner856f45f2013-10-30 00:04:59 +0100632 if (module != Py_None) {
633 res = warn_explicit(category, message, filename, lineno, module, registry,
634 NULL);
635 }
636 else {
637 /* FIXME: emitting warnings at exit does crash Python */
638 res = Py_None;
639 Py_INCREF(res);
640 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000641 Py_DECREF(filename);
642 Py_DECREF(registry);
643 Py_DECREF(module);
644 return res;
645}
646
647static PyObject *
648warnings_warn(PyObject *self, PyObject *args, PyObject *kwds)
649{
650 static char *kw_list[] = { "message", "category", "stacklevel", 0 };
651 PyObject *message, *category = NULL;
652 Py_ssize_t stack_level = 1;
653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list,
Christian Heimes33fe8092008-04-13 13:53:33 +0000655 &message, &category, &stack_level))
656 return NULL;
657
658 category = get_category(message, category);
659 if (category == NULL)
660 return NULL;
661 return do_warn(message, category, stack_level);
662}
663
664static PyObject *
665warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
666{
667 static char *kwd_list[] = {"message", "category", "filename", "lineno",
668 "module", "registry", "module_globals", 0};
669 PyObject *message;
670 PyObject *category;
671 PyObject *filename;
672 int lineno;
673 PyObject *module = NULL;
674 PyObject *registry = NULL;
675 PyObject *module_globals = NULL;
676
Victor Stinnera4c704b2013-10-29 23:43:41 +0100677 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOUi|OOO:warn_explicit",
Christian Heimes33fe8092008-04-13 13:53:33 +0000678 kwd_list, &message, &category, &filename, &lineno, &module,
679 &registry, &module_globals))
680 return NULL;
681
682 if (module_globals) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200683 _Py_IDENTIFIER(get_source);
684 _Py_IDENTIFIER(splitlines);
685 PyObject *tmp;
Christian Heimes33fe8092008-04-13 13:53:33 +0000686 PyObject *loader;
687 PyObject *module_name;
688 PyObject *source;
689 PyObject *source_list;
690 PyObject *source_line;
691 PyObject *returned;
692
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200693 if ((tmp = _PyUnicode_FromId(&PyId_get_source)) == NULL)
694 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200695 if ((tmp = _PyUnicode_FromId(&PyId_splitlines)) == NULL)
696 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000697
698 /* Check/get the requisite pieces needed for the loader. */
699 loader = PyDict_GetItemString(module_globals, "__loader__");
700 module_name = PyDict_GetItemString(module_globals, "__name__");
701
702 if (loader == NULL || module_name == NULL)
703 goto standard_call;
704
705 /* Make sure the loader implements the optional get_source() method. */
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200706 if (!_PyObject_HasAttrId(loader, &PyId_get_source))
Christian Heimes33fe8092008-04-13 13:53:33 +0000707 goto standard_call;
708 /* Call get_source() to get the source code. */
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200709 source = PyObject_CallMethodObjArgs(loader, PyId_get_source.object,
710 module_name, NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +0000711 if (!source)
712 return NULL;
713 else if (source == Py_None) {
714 Py_DECREF(Py_None);
715 goto standard_call;
716 }
717
718 /* Split the source into lines. */
Victor Stinner9e30aa52011-11-21 02:49:52 +0100719 source_list = PyObject_CallMethodObjArgs(source,
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200720 PyId_splitlines.object,
721 NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +0000722 Py_DECREF(source);
723 if (!source_list)
724 return NULL;
725
726 /* Get the source line. */
727 source_line = PyList_GetItem(source_list, lineno-1);
728 if (!source_line) {
729 Py_DECREF(source_list);
730 return NULL;
731 }
732
733 /* Handle the warning. */
734 returned = warn_explicit(category, message, filename, lineno, module,
Victor Stinner14e461d2013-08-26 22:28:21 +0200735 registry, source_line);
Christian Heimes33fe8092008-04-13 13:53:33 +0000736 Py_DECREF(source_list);
737 return returned;
738 }
739
740 standard_call:
741 return warn_explicit(category, message, filename, lineno, module,
Victor Stinner14e461d2013-08-26 22:28:21 +0200742 registry, NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +0000743}
744
745
746/* Function to issue a warning message; may raise an exception. */
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000747
748static int
749warn_unicode(PyObject *category, PyObject *message,
750 Py_ssize_t stack_level)
Christian Heimes33fe8092008-04-13 13:53:33 +0000751{
752 PyObject *res;
Christian Heimes33fe8092008-04-13 13:53:33 +0000753
754 if (category == NULL)
755 category = PyExc_RuntimeWarning;
756
757 res = do_warn(message, category, stack_level);
Christian Heimes33fe8092008-04-13 13:53:33 +0000758 if (res == NULL)
759 return -1;
760 Py_DECREF(res);
761
762 return 0;
763}
764
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000765int
766PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level,
767 const char *format, ...)
768{
769 int ret;
770 PyObject *message;
771 va_list vargs;
772
773#ifdef HAVE_STDARG_PROTOTYPES
774 va_start(vargs, format);
775#else
776 va_start(vargs);
777#endif
778 message = PyUnicode_FromFormatV(format, vargs);
779 if (message != NULL) {
780 ret = warn_unicode(category, message, stack_level);
781 Py_DECREF(message);
782 }
783 else
784 ret = -1;
785 va_end(vargs);
786 return ret;
787}
788
789int
790PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
791{
792 int ret;
793 PyObject *message = PyUnicode_FromString(text);
794 if (message == NULL)
795 return -1;
796 ret = warn_unicode(category, message, stack_level);
797 Py_DECREF(message);
798 return ret;
799}
800
Ezio Melotti42da6632011-03-15 05:18:48 +0200801/* PyErr_Warn is only for backwards compatibility and will be removed.
Christian Heimes33fe8092008-04-13 13:53:33 +0000802 Use PyErr_WarnEx instead. */
803
804#undef PyErr_Warn
805
806PyAPI_FUNC(int)
807PyErr_Warn(PyObject *category, char *text)
808{
809 return PyErr_WarnEx(category, text, 1);
810}
811
812/* Warning with explicit origin */
813int
Victor Stinner14e461d2013-08-26 22:28:21 +0200814PyErr_WarnExplicitObject(PyObject *category, PyObject *message,
815 PyObject *filename, int lineno,
816 PyObject *module, PyObject *registry)
817{
818 PyObject *res;
819 if (category == NULL)
820 category = PyExc_RuntimeWarning;
821 res = warn_explicit(category, message, filename, lineno,
822 module, registry, NULL);
823 if (res == NULL)
824 return -1;
825 Py_DECREF(res);
826 return 0;
827}
828
829int
Christian Heimes33fe8092008-04-13 13:53:33 +0000830PyErr_WarnExplicit(PyObject *category, const char *text,
831 const char *filename_str, int lineno,
832 const char *module_str, PyObject *registry)
833{
Christian Heimes33fe8092008-04-13 13:53:33 +0000834 PyObject *message = PyUnicode_FromString(text);
Victor Stinnercb428f02010-12-27 20:10:36 +0000835 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
Christian Heimes33fe8092008-04-13 13:53:33 +0000836 PyObject *module = NULL;
837 int ret = -1;
838
839 if (message == NULL || filename == NULL)
840 goto exit;
841 if (module_str != NULL) {
842 module = PyUnicode_FromString(module_str);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200843 if (module == NULL)
844 goto exit;
Christian Heimes33fe8092008-04-13 13:53:33 +0000845 }
846
Victor Stinner14e461d2013-08-26 22:28:21 +0200847 ret = PyErr_WarnExplicitObject(category, message, filename, lineno,
848 module, registry);
Christian Heimes33fe8092008-04-13 13:53:33 +0000849
850 exit:
851 Py_XDECREF(message);
852 Py_XDECREF(module);
853 Py_XDECREF(filename);
854 return ret;
855}
856
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200857int
858PyErr_WarnExplicitFormat(PyObject *category,
859 const char *filename_str, int lineno,
860 const char *module_str, PyObject *registry,
861 const char *format, ...)
862{
863 PyObject *message;
864 PyObject *module = NULL;
865 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
866 int ret = -1;
867 va_list vargs;
868
869 if (filename == NULL)
870 goto exit;
871 if (module_str != NULL) {
872 module = PyUnicode_FromString(module_str);
873 if (module == NULL)
874 goto exit;
875 }
876
877#ifdef HAVE_STDARG_PROTOTYPES
878 va_start(vargs, format);
879#else
880 va_start(vargs);
881#endif
882 message = PyUnicode_FromFormatV(format, vargs);
883 if (message != NULL) {
884 PyObject *res;
885 res = warn_explicit(category, message, filename, lineno,
886 module, registry, NULL);
887 Py_DECREF(message);
888 if (res != NULL) {
889 Py_DECREF(res);
890 ret = 0;
891 }
892 }
893 va_end(vargs);
894exit:
895 Py_XDECREF(module);
896 Py_XDECREF(filename);
897 return ret;
898}
899
Christian Heimes33fe8092008-04-13 13:53:33 +0000900
901PyDoc_STRVAR(warn_doc,
902"Issue a warning, or maybe ignore it or raise an exception.");
903
904PyDoc_STRVAR(warn_explicit_doc,
905"Low-level inferface to warnings functionality.");
906
907static PyMethodDef warnings_functions[] = {
908 {"warn", (PyCFunction)warnings_warn, METH_VARARGS | METH_KEYWORDS,
909 warn_doc},
910 {"warn_explicit", (PyCFunction)warnings_warn_explicit,
911 METH_VARARGS | METH_KEYWORDS, warn_explicit_doc},
Christian Heimes1a8501c2008-10-02 19:56:01 +0000912 /* XXX(brett.cannon): add showwarning? */
913 /* XXX(brett.cannon): Reasonable to add formatwarning? */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 {NULL, NULL} /* sentinel */
Christian Heimes33fe8092008-04-13 13:53:33 +0000915};
916
917
918static PyObject *
919create_filter(PyObject *category, const char *action)
920{
921 static PyObject *ignore_str = NULL;
922 static PyObject *error_str = NULL;
923 static PyObject *default_str = NULL;
Georg Brandl08be72d2010-10-24 15:11:22 +0000924 static PyObject *always_str = NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000925 PyObject *action_obj = NULL;
926 PyObject *lineno, *result;
927
928 if (!strcmp(action, "ignore")) {
929 if (ignore_str == NULL) {
930 ignore_str = PyUnicode_InternFromString("ignore");
931 if (ignore_str == NULL)
932 return NULL;
933 }
934 action_obj = ignore_str;
935 }
936 else if (!strcmp(action, "error")) {
937 if (error_str == NULL) {
938 error_str = PyUnicode_InternFromString("error");
939 if (error_str == NULL)
940 return NULL;
941 }
942 action_obj = error_str;
943 }
944 else if (!strcmp(action, "default")) {
945 if (default_str == NULL) {
946 default_str = PyUnicode_InternFromString("default");
947 if (default_str == NULL)
948 return NULL;
949 }
950 action_obj = default_str;
951 }
Georg Brandl08be72d2010-10-24 15:11:22 +0000952 else if (!strcmp(action, "always")) {
953 if (always_str == NULL) {
954 always_str = PyUnicode_InternFromString("always");
955 if (always_str == NULL)
956 return NULL;
957 }
958 action_obj = always_str;
959 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000960 else {
961 Py_FatalError("unknown action");
962 }
963
964 /* This assumes the line number is zero for now. */
965 lineno = PyLong_FromLong(0);
966 if (lineno == NULL)
967 return NULL;
968 result = PyTuple_Pack(5, action_obj, Py_None, category, Py_None, lineno);
969 Py_DECREF(lineno);
970 return result;
971}
972
973static PyObject *
974init_filters(void)
975{
Georg Brandl08be72d2010-10-24 15:11:22 +0000976 PyObject *filters = PyList_New(5);
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000977 unsigned int pos = 0; /* Post-incremented in each use. */
978 unsigned int x;
Georg Brandl08be72d2010-10-24 15:11:22 +0000979 const char *bytes_action, *resource_action;
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000980
Christian Heimes33fe8092008-04-13 13:53:33 +0000981 if (filters == NULL)
982 return NULL;
983
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000984 PyList_SET_ITEM(filters, pos++,
985 create_filter(PyExc_DeprecationWarning, "ignore"));
986 PyList_SET_ITEM(filters, pos++,
Christian Heimes33fe8092008-04-13 13:53:33 +0000987 create_filter(PyExc_PendingDeprecationWarning, "ignore"));
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000988 PyList_SET_ITEM(filters, pos++,
989 create_filter(PyExc_ImportWarning, "ignore"));
Christian Heimes33fe8092008-04-13 13:53:33 +0000990 if (Py_BytesWarningFlag > 1)
991 bytes_action = "error";
992 else if (Py_BytesWarningFlag)
993 bytes_action = "default";
994 else
995 bytes_action = "ignore";
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000996 PyList_SET_ITEM(filters, pos++, create_filter(PyExc_BytesWarning,
Christian Heimes33fe8092008-04-13 13:53:33 +0000997 bytes_action));
Georg Brandl08be72d2010-10-24 15:11:22 +0000998 /* resource usage warnings are enabled by default in pydebug mode */
999#ifdef Py_DEBUG
1000 resource_action = "always";
1001#else
1002 resource_action = "ignore";
1003#endif
1004 PyList_SET_ITEM(filters, pos++, create_filter(PyExc_ResourceWarning,
1005 resource_action));
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001006 for (x = 0; x < pos; x += 1) {
1007 if (PyList_GET_ITEM(filters, x) == NULL) {
1008 Py_DECREF(filters);
1009 return NULL;
1010 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001011 }
1012
1013 return filters;
1014}
1015
Martin v. Löwis1a214512008-06-11 05:26:20 +00001016static struct PyModuleDef warningsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 PyModuleDef_HEAD_INIT,
1018 MODULE_NAME,
1019 warnings__doc__,
1020 0,
1021 warnings_functions,
1022 NULL,
1023 NULL,
1024 NULL,
1025 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001026};
1027
Christian Heimes33fe8092008-04-13 13:53:33 +00001028
1029PyMODINIT_FUNC
1030_PyWarnings_Init(void)
1031{
Brett Cannon0759dd62009-04-01 18:13:07 +00001032 PyObject *m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001033
Martin v. Löwis1a214512008-06-11 05:26:20 +00001034 m = PyModule_Create(&warningsmodule);
Christian Heimes33fe8092008-04-13 13:53:33 +00001035 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001036 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001037
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001038 if (_filters == NULL) {
1039 _filters = init_filters();
1040 if (_filters == NULL)
1041 return NULL;
1042 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001043 Py_INCREF(_filters);
1044 if (PyModule_AddObject(m, "filters", _filters) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001045 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001046
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001047 if (_once_registry == NULL) {
1048 _once_registry = PyDict_New();
1049 if (_once_registry == NULL)
1050 return NULL;
1051 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001052 Py_INCREF(_once_registry);
Brett Cannonef0e6c32010-09-04 18:24:04 +00001053 if (PyModule_AddObject(m, "_onceregistry", _once_registry) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001054 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001055
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001056 if (_default_action == NULL) {
1057 _default_action = PyUnicode_FromString("default");
1058 if (_default_action == NULL)
1059 return NULL;
1060 }
1061 Py_INCREF(_default_action);
Brett Cannonef0e6c32010-09-04 18:24:04 +00001062 if (PyModule_AddObject(m, "_defaultaction", _default_action) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001063 return NULL;
1064 return m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001065}