blob: 363c1f29bb5ab813c7dfb61437ac039ca55fdce9 [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
Victor Stinnerbd303c12013-11-07 23:07:29 +010016_Py_IDENTIFIER(argv);
17_Py_IDENTIFIER(stderr);
Christian Heimes33fe8092008-04-13 13:53:33 +000018
19static int
20check_matched(PyObject *obj, PyObject *arg)
21{
22 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020023 _Py_IDENTIFIER(match);
Christian Heimes33fe8092008-04-13 13:53:33 +000024 int rc;
25
26 if (obj == Py_None)
27 return 1;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020028 result = _PyObject_CallMethodId(obj, &PyId_match, "O", arg);
Christian Heimes33fe8092008-04-13 13:53:33 +000029 if (result == NULL)
30 return -1;
31
32 rc = PyObject_IsTrue(result);
33 Py_DECREF(result);
34 return rc;
35}
36
37/*
38 Returns a new reference.
39 A NULL return value can mean false or an error.
40*/
41static PyObject *
42get_warnings_attr(const char *attr)
43{
44 static PyObject *warnings_str = NULL;
45 PyObject *all_modules;
46 PyObject *warnings_module;
47 int result;
48
49 if (warnings_str == NULL) {
50 warnings_str = PyUnicode_InternFromString("warnings");
51 if (warnings_str == NULL)
52 return NULL;
53 }
54
55 all_modules = PyImport_GetModuleDict();
56 result = PyDict_Contains(all_modules, warnings_str);
57 if (result == -1 || result == 0)
58 return NULL;
59
60 warnings_module = PyDict_GetItem(all_modules, warnings_str);
61 if (!PyObject_HasAttrString(warnings_module, attr))
62 return NULL;
63 return PyObject_GetAttrString(warnings_module, attr);
64}
65
66
Neal Norwitz32dde222008-04-15 06:43:13 +000067static PyObject *
Christian Heimes33fe8092008-04-13 13:53:33 +000068get_once_registry(void)
69{
70 PyObject *registry;
71
72 registry = get_warnings_attr("onceregistry");
73 if (registry == NULL) {
74 if (PyErr_Occurred())
75 return NULL;
76 return _once_registry;
77 }
78 Py_DECREF(_once_registry);
79 _once_registry = registry;
80 return registry;
81}
82
83
Brett Cannon0759dd62009-04-01 18:13:07 +000084static PyObject *
85get_default_action(void)
86{
87 PyObject *default_action;
88
89 default_action = get_warnings_attr("defaultaction");
90 if (default_action == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 if (PyErr_Occurred()) {
92 return NULL;
93 }
94 return _default_action;
Brett Cannon0759dd62009-04-01 18:13:07 +000095 }
96
97 Py_DECREF(_default_action);
98 _default_action = default_action;
99 return default_action;
100}
101
102
Christian Heimes33fe8092008-04-13 13:53:33 +0000103/* The item is a borrowed reference. */
Victor Stinnera4c704b2013-10-29 23:43:41 +0100104static PyObject*
Christian Heimes33fe8092008-04-13 13:53:33 +0000105get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
106 PyObject *module, PyObject **item)
107{
Brett Cannon0759dd62009-04-01 18:13:07 +0000108 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000109 Py_ssize_t i;
110 PyObject *warnings_filters;
111
112 warnings_filters = get_warnings_attr("filters");
113 if (warnings_filters == NULL) {
114 if (PyErr_Occurred())
115 return NULL;
116 }
117 else {
118 Py_DECREF(_filters);
119 _filters = warnings_filters;
120 }
121
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000122 if (_filters == NULL || !PyList_Check(_filters)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000123 PyErr_SetString(PyExc_ValueError,
124 MODULE_NAME ".filters must be a list");
125 return NULL;
126 }
127
128 /* _filters could change while we are iterating over it. */
129 for (i = 0; i < PyList_GET_SIZE(_filters); i++) {
130 PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj;
131 Py_ssize_t ln;
132 int is_subclass, good_msg, good_mod;
133
134 tmp_item = *item = PyList_GET_ITEM(_filters, i);
135 if (PyTuple_Size(tmp_item) != 5) {
136 PyErr_Format(PyExc_ValueError,
137 MODULE_NAME ".filters item %zd isn't a 5-tuple", i);
138 return NULL;
139 }
140
141 /* Python code: action, msg, cat, mod, ln = item */
142 action = PyTuple_GET_ITEM(tmp_item, 0);
143 msg = PyTuple_GET_ITEM(tmp_item, 1);
144 cat = PyTuple_GET_ITEM(tmp_item, 2);
145 mod = PyTuple_GET_ITEM(tmp_item, 3);
146 ln_obj = PyTuple_GET_ITEM(tmp_item, 4);
147
148 good_msg = check_matched(msg, text);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100149 if (good_msg == -1)
150 return NULL;
151
Christian Heimes33fe8092008-04-13 13:53:33 +0000152 good_mod = check_matched(mod, module);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100153 if (good_mod == -1)
154 return NULL;
155
Christian Heimes33fe8092008-04-13 13:53:33 +0000156 is_subclass = PyObject_IsSubclass(category, cat);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100157 if (is_subclass == -1)
158 return NULL;
159
Christian Heimes33fe8092008-04-13 13:53:33 +0000160 ln = PyLong_AsSsize_t(ln_obj);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100161 if (ln == -1 && PyErr_Occurred())
Christian Heimes33fe8092008-04-13 13:53:33 +0000162 return NULL;
163
164 if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln))
Victor Stinnera4c704b2013-10-29 23:43:41 +0100165 return action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000166 }
167
Brett Cannon0759dd62009-04-01 18:13:07 +0000168 action = get_default_action();
Victor Stinnera4c704b2013-10-29 23:43:41 +0100169 if (action != NULL)
170 return action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000171
172 PyErr_SetString(PyExc_ValueError,
Brett Cannon0759dd62009-04-01 18:13:07 +0000173 MODULE_NAME ".defaultaction not found");
Christian Heimes33fe8092008-04-13 13:53:33 +0000174 return NULL;
175}
176
Brett Cannon0759dd62009-04-01 18:13:07 +0000177
Christian Heimes33fe8092008-04-13 13:53:33 +0000178static int
179already_warned(PyObject *registry, PyObject *key, int should_set)
180{
181 PyObject *already_warned;
182
183 if (key == NULL)
184 return -1;
185
186 already_warned = PyDict_GetItem(registry, key);
187 if (already_warned != NULL) {
188 int rc = PyObject_IsTrue(already_warned);
189 if (rc != 0)
190 return rc;
191 }
192
193 /* This warning wasn't found in the registry, set it. */
194 if (should_set)
195 return PyDict_SetItem(registry, key, Py_True);
196 return 0;
197}
198
199/* New reference. */
200static PyObject *
201normalize_module(PyObject *filename)
202{
203 PyObject *module;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100204 int kind;
205 void *data;
Christian Heimes33fe8092008-04-13 13:53:33 +0000206 Py_ssize_t len;
207
Victor Stinner9e30aa52011-11-21 02:49:52 +0100208 len = PyUnicode_GetLength(filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000209 if (len < 0)
210 return NULL;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100211
212 if (len == 0)
213 return PyUnicode_FromString("<unknown>");
214
215 kind = PyUnicode_KIND(filename);
216 data = PyUnicode_DATA(filename);
217
218 /* if filename.endswith(".py"): */
Christian Heimes33fe8092008-04-13 13:53:33 +0000219 if (len >= 3 &&
Victor Stinnera4c704b2013-10-29 23:43:41 +0100220 PyUnicode_READ(kind, data, len-3) == '.' &&
221 PyUnicode_READ(kind, data, len-2) == 'p' &&
222 PyUnicode_READ(kind, data, len-1) == 'y')
223 {
Victor Stinner9e30aa52011-11-21 02:49:52 +0100224 module = PyUnicode_Substring(filename, 0, len-3);
Christian Heimes33fe8092008-04-13 13:53:33 +0000225 }
226 else {
227 module = filename;
228 Py_INCREF(module);
229 }
230 return module;
231}
232
233static int
234update_registry(PyObject *registry, PyObject *text, PyObject *category,
235 int add_zero)
236{
237 PyObject *altkey, *zero = NULL;
238 int rc;
239
240 if (add_zero) {
241 zero = PyLong_FromLong(0);
242 if (zero == NULL)
243 return -1;
244 altkey = PyTuple_Pack(3, text, category, zero);
245 }
246 else
247 altkey = PyTuple_Pack(2, text, category);
248
249 rc = already_warned(registry, altkey, 1);
250 Py_XDECREF(zero);
251 Py_XDECREF(altkey);
252 return rc;
253}
254
255static void
256show_warning(PyObject *filename, int lineno, PyObject *text, PyObject
257 *category, PyObject *sourceline)
258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 PyObject *f_stderr;
260 PyObject *name;
Christian Heimes33fe8092008-04-13 13:53:33 +0000261 char lineno_str[128];
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200262 _Py_IDENTIFIER(__name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000263
264 PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);
265
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200266 name = _PyObject_GetAttrId(category, &PyId___name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000267 if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */
Victor Stinnerae233ea2013-10-31 14:51:38 +0100268 goto error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000269
Victor Stinnerbd303c12013-11-07 23:07:29 +0100270 f_stderr = _PySys_GetObjectId(&PyId_stderr);
Christian Heimes33fe8092008-04-13 13:53:33 +0000271 if (f_stderr == NULL) {
272 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnerae233ea2013-10-31 14:51:38 +0100273 goto error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000274 }
275
276 /* Print "filename:lineno: category: text\n" */
Victor Stinnerae233ea2013-10-31 14:51:38 +0100277 if (PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW) < 0)
278 goto error;
279 if (PyFile_WriteString(lineno_str, f_stderr) < 0)
280 goto error;
281 if (PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW) < 0)
282 goto error;
283 if (PyFile_WriteString(": ", f_stderr) < 0)
284 goto error;
285 if (PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW) < 0)
286 goto error;
287 if (PyFile_WriteString("\n", f_stderr) < 0)
288 goto error;
289 Py_CLEAR(name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000290
291 /* Print " source_line\n" */
Christian Heimes33fe8092008-04-13 13:53:33 +0000292 if (sourceline) {
Victor Stinnera4c704b2013-10-29 23:43:41 +0100293 int kind;
294 void *data;
295 Py_ssize_t i, len;
296 Py_UCS4 ch;
297 PyObject *truncated;
Christian Heimes33fe8092008-04-13 13:53:33 +0000298
Victor Stinnera4c704b2013-10-29 23:43:41 +0100299 if (PyUnicode_READY(sourceline) < 1)
300 goto error;
301
302 kind = PyUnicode_KIND(sourceline);
303 data = PyUnicode_DATA(sourceline);
304 len = PyUnicode_GET_LENGTH(sourceline);
305 for (i=0; i<len; i++) {
306 ch = PyUnicode_READ(kind, data, i);
307 if (ch != ' ' && ch != '\t' && ch != '\014')
308 break;
309 }
310
311 truncated = PyUnicode_Substring(sourceline, i, len);
312 if (truncated == NULL)
313 goto error;
314
315 PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW);
316 Py_DECREF(truncated);
Christian Heimes33fe8092008-04-13 13:53:33 +0000317 PyFile_WriteString("\n", f_stderr);
318 }
Victor Stinner78e2c982013-07-16 01:54:37 +0200319 else {
320 _Py_DisplaySourceLine(f_stderr, filename, lineno, 2);
321 }
Victor Stinnera4c704b2013-10-29 23:43:41 +0100322
323error:
Victor Stinnerae233ea2013-10-31 14:51:38 +0100324 Py_XDECREF(name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000325 PyErr_Clear();
326}
327
328static PyObject *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329warn_explicit(PyObject *category, PyObject *message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000330 PyObject *filename, int lineno,
331 PyObject *module, PyObject *registry, PyObject *sourceline)
332{
333 PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL;
334 PyObject *item = Py_None;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100335 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000336 int rc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337
Victor Stinnerdcdd05b2013-11-01 00:55:30 +0100338 /* module can be None if a warning is emitted late during Python shutdown.
339 In this case, the Python warnings module was probably unloaded, filters
340 are no more available to choose as action. It is safer to ignore the
341 warning and do nothing. */
342 if (module == Py_None)
343 Py_RETURN_NONE;
344
Brett Cannondb734912008-06-27 00:52:15 +0000345 if (registry && !PyDict_Check(registry) && (registry != Py_None)) {
346 PyErr_SetString(PyExc_TypeError, "'registry' must be a dict");
347 return NULL;
348 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000349
350 /* Normalize module. */
351 if (module == NULL) {
352 module = normalize_module(filename);
353 if (module == NULL)
354 return NULL;
355 }
356 else
357 Py_INCREF(module);
358
359 /* Normalize message. */
360 Py_INCREF(message); /* DECREF'ed in cleanup. */
361 rc = PyObject_IsInstance(message, PyExc_Warning);
362 if (rc == -1) {
363 goto cleanup;
364 }
365 if (rc == 1) {
366 text = PyObject_Str(message);
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000367 if (text == NULL)
368 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000369 category = (PyObject*)message->ob_type;
370 }
371 else {
372 text = message;
373 message = PyObject_CallFunction(category, "O", message);
Brett Cannondb734912008-06-27 00:52:15 +0000374 if (message == NULL)
375 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000376 }
377
378 lineno_obj = PyLong_FromLong(lineno);
379 if (lineno_obj == NULL)
380 goto cleanup;
381
382 /* Create key. */
383 key = PyTuple_Pack(3, text, category, lineno_obj);
384 if (key == NULL)
385 goto cleanup;
386
Brett Cannondb734912008-06-27 00:52:15 +0000387 if ((registry != NULL) && (registry != Py_None)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000388 rc = already_warned(registry, key, 0);
389 if (rc == -1)
390 goto cleanup;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 else if (rc == 1)
Christian Heimes33fe8092008-04-13 13:53:33 +0000392 goto return_none;
393 /* Else this warning hasn't been generated before. */
394 }
395
396 action = get_filter(category, text, lineno, module, &item);
397 if (action == NULL)
398 goto cleanup;
399
Victor Stinnera4c704b2013-10-29 23:43:41 +0100400 if (PyUnicode_CompareWithASCIIString(action, "error") == 0) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000401 PyErr_SetObject(category, message);
402 goto cleanup;
403 }
404
405 /* Store in the registry that we've been here, *except* when the action
406 is "always". */
407 rc = 0;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100408 if (PyUnicode_CompareWithASCIIString(action, "always") != 0) {
Brett Cannondb734912008-06-27 00:52:15 +0000409 if (registry != NULL && registry != Py_None &&
410 PyDict_SetItem(registry, key, Py_True) < 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000411 goto cleanup;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100412 else if (PyUnicode_CompareWithASCIIString(action, "ignore") == 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000413 goto return_none;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100414 else if (PyUnicode_CompareWithASCIIString(action, "once") == 0) {
Brett Cannondb734912008-06-27 00:52:15 +0000415 if (registry == NULL || registry == Py_None) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000416 registry = get_once_registry();
417 if (registry == NULL)
418 goto cleanup;
419 }
420 /* _once_registry[(text, category)] = 1 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000422 }
Victor Stinnera4c704b2013-10-29 23:43:41 +0100423 else if (PyUnicode_CompareWithASCIIString(action, "module") == 0) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000424 /* registry[(text, category, 0)] = 1 */
Brett Cannondb734912008-06-27 00:52:15 +0000425 if (registry != NULL && registry != Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000427 }
Victor Stinnera4c704b2013-10-29 23:43:41 +0100428 else if (PyUnicode_CompareWithASCIIString(action, "default") != 0) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000429 PyErr_Format(PyExc_RuntimeError,
Victor Stinnera4c704b2013-10-29 23:43:41 +0100430 "Unrecognized action (%R) in warnings.filters:\n %R",
431 action, item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000432 goto cleanup;
433 }
434 }
435
Christian Heimes1a8501c2008-10-02 19:56:01 +0000436 if (rc == 1) /* Already warned for this module. */
Christian Heimes33fe8092008-04-13 13:53:33 +0000437 goto return_none;
438 if (rc == 0) {
439 PyObject *show_fxn = get_warnings_attr("showwarning");
440 if (show_fxn == NULL) {
441 if (PyErr_Occurred())
442 goto cleanup;
443 show_warning(filename, lineno, text, category, sourceline);
444 }
445 else {
Brett Cannonec92e182008-09-02 02:46:59 +0000446 PyObject *res;
Christian Heimes8dc226f2008-05-06 23:45:46 +0000447
Brett Cannon52a7d982011-07-17 19:17:55 -0700448 if (!PyCallable_Check(show_fxn)) {
Brett Cannonec92e182008-09-02 02:46:59 +0000449 PyErr_SetString(PyExc_TypeError,
450 "warnings.showwarning() must be set to a "
Brett Cannon52a7d982011-07-17 19:17:55 -0700451 "callable");
Christian Heimes8dc226f2008-05-06 23:45:46 +0000452 Py_DECREF(show_fxn);
Brett Cannonec92e182008-09-02 02:46:59 +0000453 goto cleanup;
Christian Heimes8dc226f2008-05-06 23:45:46 +0000454 }
Brett Cannonec92e182008-09-02 02:46:59 +0000455
456 res = PyObject_CallFunctionObjArgs(show_fxn, message, category,
457 filename, lineno_obj,
458 NULL);
459 Py_DECREF(show_fxn);
460 Py_XDECREF(res);
461 if (res == NULL)
462 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000463 }
464 }
465 else /* if (rc == -1) */
466 goto cleanup;
467
468 return_none:
469 result = Py_None;
470 Py_INCREF(result);
471
472 cleanup:
473 Py_XDECREF(key);
474 Py_XDECREF(text);
475 Py_XDECREF(lineno_obj);
476 Py_DECREF(module);
Brett Cannondb734912008-06-27 00:52:15 +0000477 Py_XDECREF(message);
Christian Heimes33fe8092008-04-13 13:53:33 +0000478 return result; /* Py_None or NULL. */
479}
480
481/* filename, module, and registry are new refs, globals is borrowed */
482/* Returns 0 on error (no new refs), 1 on success */
483static int
484setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
485 PyObject **module, PyObject **registry)
486{
487 PyObject *globals;
488
489 /* Setup globals and lineno. */
490 PyFrameObject *f = PyThreadState_GET()->frame;
Christian Heimes5d8da202008-05-06 13:58:24 +0000491 while (--stack_level > 0 && f != NULL)
Christian Heimes33fe8092008-04-13 13:53:33 +0000492 f = f->f_back;
Christian Heimes33fe8092008-04-13 13:53:33 +0000493
494 if (f == NULL) {
495 globals = PyThreadState_Get()->interp->sysdict;
496 *lineno = 1;
497 }
498 else {
499 globals = f->f_globals;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000500 *lineno = PyFrame_GetLineNumber(f);
Christian Heimes33fe8092008-04-13 13:53:33 +0000501 }
502
503 *module = NULL;
504
505 /* Setup registry. */
506 assert(globals != NULL);
507 assert(PyDict_Check(globals));
508 *registry = PyDict_GetItemString(globals, "__warningregistry__");
509 if (*registry == NULL) {
510 int rc;
511
512 *registry = PyDict_New();
513 if (*registry == NULL)
514 return 0;
515
516 rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
517 if (rc < 0)
518 goto handle_error;
519 }
520 else
521 Py_INCREF(*registry);
522
523 /* Setup module. */
524 *module = PyDict_GetItemString(globals, "__name__");
525 if (*module == NULL) {
526 *module = PyUnicode_FromString("<string>");
527 if (*module == NULL)
528 goto handle_error;
529 }
530 else
531 Py_INCREF(*module);
532
533 /* Setup filename. */
534 *filename = PyDict_GetItemString(globals, "__file__");
Victor Stinner8b0508e2011-07-04 02:43:09 +0200535 if (*filename != NULL && PyUnicode_Check(*filename)) {
Victor Stinnerb62a7b22011-10-06 02:34:51 +0200536 Py_ssize_t len;
537 int kind;
538 void *data;
539
540 if (PyUnicode_READY(*filename))
541 goto handle_error;
542
Victor Stinner9e30aa52011-11-21 02:49:52 +0100543 len = PyUnicode_GetLength(*filename);
Victor Stinnerb62a7b22011-10-06 02:34:51 +0200544 kind = PyUnicode_KIND(*filename);
545 data = PyUnicode_DATA(*filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000546
Benjamin Peterson21e0da22012-01-11 21:00:42 -0500547#define ascii_lower(c) ((c <= 127) ? Py_TOLOWER(c) : 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000548 /* if filename.lower().endswith((".pyc", ".pyo")): */
549 if (len >= 4 &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200550 PyUnicode_READ(kind, data, len-4) == '.' &&
Benjamin Peterson21e0da22012-01-11 21:00:42 -0500551 ascii_lower(PyUnicode_READ(kind, data, len-3)) == 'p' &&
552 ascii_lower(PyUnicode_READ(kind, data, len-2)) == 'y' &&
553 (ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'c' ||
554 ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'o'))
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000555 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200556 *filename = PyUnicode_Substring(*filename, 0,
557 PyUnicode_GET_LENGTH(*filename)-1);
Victor Stinner2e5f1172010-08-08 22:12:45 +0000558 if (*filename == NULL)
559 goto handle_error;
560 }
561 else
Christian Heimes33fe8092008-04-13 13:53:33 +0000562 Py_INCREF(*filename);
563 }
564 else {
Benjamin Petersonbb4a7472011-07-04 22:27:16 -0500565 *filename = NULL;
Victor Stinner856f45f2013-10-30 00:04:59 +0100566 if (*module != Py_None && PyUnicode_CompareWithASCIIString(*module, "__main__") == 0) {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100567 PyObject *argv = _PySys_GetObjectId(&PyId_argv);
Victor Stinnerce5f4fb2013-10-28 18:47:22 +0100568 /* PyList_Check() is needed because sys.argv is set to None during
569 Python finalization */
570 if (argv != NULL && PyList_Check(argv) && PyList_Size(argv) > 0) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000571 int is_true;
Christian Heimes33fe8092008-04-13 13:53:33 +0000572 *filename = PyList_GetItem(argv, 0);
573 Py_INCREF(*filename);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000574 /* If sys.argv[0] is false, then use '__main__'. */
575 is_true = PyObject_IsTrue(*filename);
576 if (is_true < 0) {
577 Py_DECREF(*filename);
578 goto handle_error;
579 }
580 else if (!is_true) {
581 Py_DECREF(*filename);
Benjamin Peterson9f4bf1d2008-05-04 23:22:13 +0000582 *filename = PyUnicode_FromString("__main__");
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000583 if (*filename == NULL)
584 goto handle_error;
585 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000586 }
587 else {
588 /* embedded interpreters don't have sys.argv, see bug #839151 */
589 *filename = PyUnicode_FromString("__main__");
Victor Stinner856f45f2013-10-30 00:04:59 +0100590 if (*filename == NULL)
591 goto handle_error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000592 }
593 }
594 if (*filename == NULL) {
595 *filename = *module;
596 Py_INCREF(*filename);
597 }
598 }
599
600 return 1;
601
602 handle_error:
603 /* filename not XDECREF'ed here as there is no way to jump here with a
604 dangling reference. */
605 Py_XDECREF(*registry);
606 Py_XDECREF(*module);
607 return 0;
608}
609
610static PyObject *
611get_category(PyObject *message, PyObject *category)
612{
613 int rc;
614
615 /* Get category. */
616 rc = PyObject_IsInstance(message, PyExc_Warning);
617 if (rc == -1)
618 return NULL;
619
620 if (rc == 1)
621 category = (PyObject*)message->ob_type;
Berker Peksagd8089e02014-07-11 19:50:25 +0300622 else if (category == NULL || category == Py_None)
Christian Heimes33fe8092008-04-13 13:53:33 +0000623 category = PyExc_UserWarning;
624
625 /* Validate category. */
626 rc = PyObject_IsSubclass(category, PyExc_Warning);
Berker Peksagd8089e02014-07-11 19:50:25 +0300627 /* category is not a subclass of PyExc_Warning or
628 PyObject_IsSubclass raised an error */
629 if (rc == -1 || rc == 0) {
630 PyErr_Format(PyExc_TypeError,
631 "category must be a Warning subclass, not '%s'",
632 Py_TYPE(category)->tp_name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000633 return NULL;
634 }
635
636 return category;
637}
638
639static PyObject *
640do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level)
641{
642 PyObject *filename, *module, *registry, *res;
643 int lineno;
644
645 if (!setup_context(stack_level, &filename, &lineno, &module, &registry))
646 return NULL;
647
Victor Stinnerdcdd05b2013-11-01 00:55:30 +0100648 res = warn_explicit(category, message, filename, lineno, module, registry,
649 NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +0000650 Py_DECREF(filename);
651 Py_DECREF(registry);
652 Py_DECREF(module);
653 return res;
654}
655
656static PyObject *
657warnings_warn(PyObject *self, PyObject *args, PyObject *kwds)
658{
659 static char *kw_list[] = { "message", "category", "stacklevel", 0 };
660 PyObject *message, *category = NULL;
661 Py_ssize_t stack_level = 1;
662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list,
Christian Heimes33fe8092008-04-13 13:53:33 +0000664 &message, &category, &stack_level))
665 return NULL;
666
667 category = get_category(message, category);
668 if (category == NULL)
669 return NULL;
670 return do_warn(message, category, stack_level);
671}
672
673static PyObject *
674warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
675{
676 static char *kwd_list[] = {"message", "category", "filename", "lineno",
677 "module", "registry", "module_globals", 0};
678 PyObject *message;
679 PyObject *category;
680 PyObject *filename;
681 int lineno;
682 PyObject *module = NULL;
683 PyObject *registry = NULL;
684 PyObject *module_globals = NULL;
685
Victor Stinnera4c704b2013-10-29 23:43:41 +0100686 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOUi|OOO:warn_explicit",
Christian Heimes33fe8092008-04-13 13:53:33 +0000687 kwd_list, &message, &category, &filename, &lineno, &module,
688 &registry, &module_globals))
689 return NULL;
690
691 if (module_globals) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200692 _Py_IDENTIFIER(get_source);
693 _Py_IDENTIFIER(splitlines);
694 PyObject *tmp;
Christian Heimes33fe8092008-04-13 13:53:33 +0000695 PyObject *loader;
696 PyObject *module_name;
697 PyObject *source;
698 PyObject *source_list;
699 PyObject *source_line;
700 PyObject *returned;
701
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200702 if ((tmp = _PyUnicode_FromId(&PyId_get_source)) == NULL)
703 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200704 if ((tmp = _PyUnicode_FromId(&PyId_splitlines)) == NULL)
705 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000706
707 /* Check/get the requisite pieces needed for the loader. */
708 loader = PyDict_GetItemString(module_globals, "__loader__");
709 module_name = PyDict_GetItemString(module_globals, "__name__");
710
711 if (loader == NULL || module_name == NULL)
712 goto standard_call;
713
714 /* Make sure the loader implements the optional get_source() method. */
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200715 if (!_PyObject_HasAttrId(loader, &PyId_get_source))
Christian Heimes33fe8092008-04-13 13:53:33 +0000716 goto standard_call;
717 /* Call get_source() to get the source code. */
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200718 source = PyObject_CallMethodObjArgs(loader, PyId_get_source.object,
719 module_name, NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +0000720 if (!source)
721 return NULL;
722 else if (source == Py_None) {
723 Py_DECREF(Py_None);
724 goto standard_call;
725 }
726
727 /* Split the source into lines. */
Victor Stinner9e30aa52011-11-21 02:49:52 +0100728 source_list = PyObject_CallMethodObjArgs(source,
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200729 PyId_splitlines.object,
730 NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +0000731 Py_DECREF(source);
732 if (!source_list)
733 return NULL;
734
735 /* Get the source line. */
736 source_line = PyList_GetItem(source_list, lineno-1);
737 if (!source_line) {
738 Py_DECREF(source_list);
739 return NULL;
740 }
741
742 /* Handle the warning. */
743 returned = warn_explicit(category, message, filename, lineno, module,
Victor Stinner14e461d2013-08-26 22:28:21 +0200744 registry, source_line);
Christian Heimes33fe8092008-04-13 13:53:33 +0000745 Py_DECREF(source_list);
746 return returned;
747 }
748
749 standard_call:
750 return warn_explicit(category, message, filename, lineno, module,
Victor Stinner14e461d2013-08-26 22:28:21 +0200751 registry, NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +0000752}
753
754
755/* Function to issue a warning message; may raise an exception. */
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000756
757static int
758warn_unicode(PyObject *category, PyObject *message,
759 Py_ssize_t stack_level)
Christian Heimes33fe8092008-04-13 13:53:33 +0000760{
761 PyObject *res;
Christian Heimes33fe8092008-04-13 13:53:33 +0000762
763 if (category == NULL)
764 category = PyExc_RuntimeWarning;
765
766 res = do_warn(message, category, stack_level);
Christian Heimes33fe8092008-04-13 13:53:33 +0000767 if (res == NULL)
768 return -1;
769 Py_DECREF(res);
770
771 return 0;
772}
773
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000774int
775PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level,
776 const char *format, ...)
777{
778 int ret;
779 PyObject *message;
780 va_list vargs;
781
782#ifdef HAVE_STDARG_PROTOTYPES
783 va_start(vargs, format);
784#else
785 va_start(vargs);
786#endif
787 message = PyUnicode_FromFormatV(format, vargs);
788 if (message != NULL) {
789 ret = warn_unicode(category, message, stack_level);
790 Py_DECREF(message);
791 }
792 else
793 ret = -1;
794 va_end(vargs);
795 return ret;
796}
797
798int
799PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
800{
801 int ret;
802 PyObject *message = PyUnicode_FromString(text);
803 if (message == NULL)
804 return -1;
805 ret = warn_unicode(category, message, stack_level);
806 Py_DECREF(message);
807 return ret;
808}
809
Ezio Melotti42da6632011-03-15 05:18:48 +0200810/* PyErr_Warn is only for backwards compatibility and will be removed.
Christian Heimes33fe8092008-04-13 13:53:33 +0000811 Use PyErr_WarnEx instead. */
812
813#undef PyErr_Warn
814
815PyAPI_FUNC(int)
816PyErr_Warn(PyObject *category, char *text)
817{
818 return PyErr_WarnEx(category, text, 1);
819}
820
821/* Warning with explicit origin */
822int
Victor Stinner14e461d2013-08-26 22:28:21 +0200823PyErr_WarnExplicitObject(PyObject *category, PyObject *message,
824 PyObject *filename, int lineno,
825 PyObject *module, PyObject *registry)
826{
827 PyObject *res;
828 if (category == NULL)
829 category = PyExc_RuntimeWarning;
830 res = warn_explicit(category, message, filename, lineno,
831 module, registry, NULL);
832 if (res == NULL)
833 return -1;
834 Py_DECREF(res);
835 return 0;
836}
837
838int
Christian Heimes33fe8092008-04-13 13:53:33 +0000839PyErr_WarnExplicit(PyObject *category, const char *text,
840 const char *filename_str, int lineno,
841 const char *module_str, PyObject *registry)
842{
Christian Heimes33fe8092008-04-13 13:53:33 +0000843 PyObject *message = PyUnicode_FromString(text);
Victor Stinnercb428f02010-12-27 20:10:36 +0000844 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
Christian Heimes33fe8092008-04-13 13:53:33 +0000845 PyObject *module = NULL;
846 int ret = -1;
847
848 if (message == NULL || filename == NULL)
849 goto exit;
850 if (module_str != NULL) {
851 module = PyUnicode_FromString(module_str);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200852 if (module == NULL)
853 goto exit;
Christian Heimes33fe8092008-04-13 13:53:33 +0000854 }
855
Victor Stinner14e461d2013-08-26 22:28:21 +0200856 ret = PyErr_WarnExplicitObject(category, message, filename, lineno,
857 module, registry);
Christian Heimes33fe8092008-04-13 13:53:33 +0000858
859 exit:
860 Py_XDECREF(message);
861 Py_XDECREF(module);
862 Py_XDECREF(filename);
863 return ret;
864}
865
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200866int
867PyErr_WarnExplicitFormat(PyObject *category,
868 const char *filename_str, int lineno,
869 const char *module_str, PyObject *registry,
870 const char *format, ...)
871{
872 PyObject *message;
873 PyObject *module = NULL;
874 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
875 int ret = -1;
876 va_list vargs;
877
878 if (filename == NULL)
879 goto exit;
880 if (module_str != NULL) {
881 module = PyUnicode_FromString(module_str);
882 if (module == NULL)
883 goto exit;
884 }
885
886#ifdef HAVE_STDARG_PROTOTYPES
887 va_start(vargs, format);
888#else
889 va_start(vargs);
890#endif
891 message = PyUnicode_FromFormatV(format, vargs);
892 if (message != NULL) {
893 PyObject *res;
894 res = warn_explicit(category, message, filename, lineno,
895 module, registry, NULL);
896 Py_DECREF(message);
897 if (res != NULL) {
898 Py_DECREF(res);
899 ret = 0;
900 }
901 }
902 va_end(vargs);
903exit:
904 Py_XDECREF(module);
905 Py_XDECREF(filename);
906 return ret;
907}
908
Christian Heimes33fe8092008-04-13 13:53:33 +0000909
910PyDoc_STRVAR(warn_doc,
911"Issue a warning, or maybe ignore it or raise an exception.");
912
913PyDoc_STRVAR(warn_explicit_doc,
914"Low-level inferface to warnings functionality.");
915
916static PyMethodDef warnings_functions[] = {
917 {"warn", (PyCFunction)warnings_warn, METH_VARARGS | METH_KEYWORDS,
918 warn_doc},
919 {"warn_explicit", (PyCFunction)warnings_warn_explicit,
920 METH_VARARGS | METH_KEYWORDS, warn_explicit_doc},
Christian Heimes1a8501c2008-10-02 19:56:01 +0000921 /* XXX(brett.cannon): add showwarning? */
922 /* XXX(brett.cannon): Reasonable to add formatwarning? */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 {NULL, NULL} /* sentinel */
Christian Heimes33fe8092008-04-13 13:53:33 +0000924};
925
926
927static PyObject *
928create_filter(PyObject *category, const char *action)
929{
930 static PyObject *ignore_str = NULL;
931 static PyObject *error_str = NULL;
932 static PyObject *default_str = NULL;
Georg Brandl08be72d2010-10-24 15:11:22 +0000933 static PyObject *always_str = NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000934 PyObject *action_obj = NULL;
935 PyObject *lineno, *result;
936
937 if (!strcmp(action, "ignore")) {
938 if (ignore_str == NULL) {
939 ignore_str = PyUnicode_InternFromString("ignore");
940 if (ignore_str == NULL)
941 return NULL;
942 }
943 action_obj = ignore_str;
944 }
945 else if (!strcmp(action, "error")) {
946 if (error_str == NULL) {
947 error_str = PyUnicode_InternFromString("error");
948 if (error_str == NULL)
949 return NULL;
950 }
951 action_obj = error_str;
952 }
953 else if (!strcmp(action, "default")) {
954 if (default_str == NULL) {
955 default_str = PyUnicode_InternFromString("default");
956 if (default_str == NULL)
957 return NULL;
958 }
959 action_obj = default_str;
960 }
Georg Brandl08be72d2010-10-24 15:11:22 +0000961 else if (!strcmp(action, "always")) {
962 if (always_str == NULL) {
963 always_str = PyUnicode_InternFromString("always");
964 if (always_str == NULL)
965 return NULL;
966 }
967 action_obj = always_str;
968 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000969 else {
970 Py_FatalError("unknown action");
971 }
972
973 /* This assumes the line number is zero for now. */
974 lineno = PyLong_FromLong(0);
975 if (lineno == NULL)
976 return NULL;
977 result = PyTuple_Pack(5, action_obj, Py_None, category, Py_None, lineno);
978 Py_DECREF(lineno);
979 return result;
980}
981
982static PyObject *
983init_filters(void)
984{
Georg Brandl08be72d2010-10-24 15:11:22 +0000985 PyObject *filters = PyList_New(5);
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000986 unsigned int pos = 0; /* Post-incremented in each use. */
987 unsigned int x;
Georg Brandl08be72d2010-10-24 15:11:22 +0000988 const char *bytes_action, *resource_action;
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000989
Christian Heimes33fe8092008-04-13 13:53:33 +0000990 if (filters == NULL)
991 return NULL;
992
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000993 PyList_SET_ITEM(filters, pos++,
994 create_filter(PyExc_DeprecationWarning, "ignore"));
995 PyList_SET_ITEM(filters, pos++,
Christian Heimes33fe8092008-04-13 13:53:33 +0000996 create_filter(PyExc_PendingDeprecationWarning, "ignore"));
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000997 PyList_SET_ITEM(filters, pos++,
998 create_filter(PyExc_ImportWarning, "ignore"));
Christian Heimes33fe8092008-04-13 13:53:33 +0000999 if (Py_BytesWarningFlag > 1)
1000 bytes_action = "error";
1001 else if (Py_BytesWarningFlag)
1002 bytes_action = "default";
1003 else
1004 bytes_action = "ignore";
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001005 PyList_SET_ITEM(filters, pos++, create_filter(PyExc_BytesWarning,
Christian Heimes33fe8092008-04-13 13:53:33 +00001006 bytes_action));
Georg Brandl08be72d2010-10-24 15:11:22 +00001007 /* resource usage warnings are enabled by default in pydebug mode */
1008#ifdef Py_DEBUG
1009 resource_action = "always";
1010#else
1011 resource_action = "ignore";
1012#endif
1013 PyList_SET_ITEM(filters, pos++, create_filter(PyExc_ResourceWarning,
1014 resource_action));
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001015 for (x = 0; x < pos; x += 1) {
1016 if (PyList_GET_ITEM(filters, x) == NULL) {
1017 Py_DECREF(filters);
1018 return NULL;
1019 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001020 }
1021
1022 return filters;
1023}
1024
Martin v. Löwis1a214512008-06-11 05:26:20 +00001025static struct PyModuleDef warningsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 PyModuleDef_HEAD_INIT,
1027 MODULE_NAME,
1028 warnings__doc__,
1029 0,
1030 warnings_functions,
1031 NULL,
1032 NULL,
1033 NULL,
1034 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001035};
1036
Christian Heimes33fe8092008-04-13 13:53:33 +00001037
1038PyMODINIT_FUNC
1039_PyWarnings_Init(void)
1040{
Brett Cannon0759dd62009-04-01 18:13:07 +00001041 PyObject *m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001042
Martin v. Löwis1a214512008-06-11 05:26:20 +00001043 m = PyModule_Create(&warningsmodule);
Christian Heimes33fe8092008-04-13 13:53:33 +00001044 if (m == NULL)
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 (_filters == NULL) {
1048 _filters = init_filters();
1049 if (_filters == NULL)
1050 return NULL;
1051 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001052 Py_INCREF(_filters);
1053 if (PyModule_AddObject(m, "filters", _filters) < 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 (_once_registry == NULL) {
1057 _once_registry = PyDict_New();
1058 if (_once_registry == NULL)
1059 return NULL;
1060 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001061 Py_INCREF(_once_registry);
Brett Cannonef0e6c32010-09-04 18:24:04 +00001062 if (PyModule_AddObject(m, "_onceregistry", _once_registry) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001063 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001064
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001065 if (_default_action == NULL) {
1066 _default_action = PyUnicode_FromString("default");
1067 if (_default_action == NULL)
1068 return NULL;
1069 }
1070 Py_INCREF(_default_action);
Brett Cannonef0e6c32010-09-04 18:24:04 +00001071 if (PyModule_AddObject(m, "_defaultaction", _default_action) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001072 return NULL;
1073 return m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001074}