blob: 6013d7d7d48c055da3d8fdabc313469efe4f3a8d [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;
622 else if (category == NULL)
623 category = PyExc_UserWarning;
624
625 /* Validate category. */
626 rc = PyObject_IsSubclass(category, PyExc_Warning);
627 if (rc == -1)
628 return NULL;
629 if (rc == 0) {
630 PyErr_SetString(PyExc_ValueError,
631 "category is not a subclass of Warning");
632 return NULL;
633 }
634
635 return category;
636}
637
638static PyObject *
639do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level)
640{
641 PyObject *filename, *module, *registry, *res;
642 int lineno;
643
644 if (!setup_context(stack_level, &filename, &lineno, &module, &registry))
645 return NULL;
646
Victor Stinnerdcdd05b2013-11-01 00:55:30 +0100647 res = warn_explicit(category, message, filename, lineno, module, registry,
648 NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +0000649 Py_DECREF(filename);
650 Py_DECREF(registry);
651 Py_DECREF(module);
652 return res;
653}
654
655static PyObject *
656warnings_warn(PyObject *self, PyObject *args, PyObject *kwds)
657{
658 static char *kw_list[] = { "message", "category", "stacklevel", 0 };
659 PyObject *message, *category = NULL;
660 Py_ssize_t stack_level = 1;
661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list,
Christian Heimes33fe8092008-04-13 13:53:33 +0000663 &message, &category, &stack_level))
664 return NULL;
665
666 category = get_category(message, category);
667 if (category == NULL)
668 return NULL;
669 return do_warn(message, category, stack_level);
670}
671
672static PyObject *
673warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
674{
675 static char *kwd_list[] = {"message", "category", "filename", "lineno",
676 "module", "registry", "module_globals", 0};
677 PyObject *message;
678 PyObject *category;
679 PyObject *filename;
680 int lineno;
681 PyObject *module = NULL;
682 PyObject *registry = NULL;
683 PyObject *module_globals = NULL;
684
Victor Stinnera4c704b2013-10-29 23:43:41 +0100685 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOUi|OOO:warn_explicit",
Christian Heimes33fe8092008-04-13 13:53:33 +0000686 kwd_list, &message, &category, &filename, &lineno, &module,
687 &registry, &module_globals))
688 return NULL;
689
690 if (module_globals) {
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200691 _Py_IDENTIFIER(get_source);
692 _Py_IDENTIFIER(splitlines);
693 PyObject *tmp;
Christian Heimes33fe8092008-04-13 13:53:33 +0000694 PyObject *loader;
695 PyObject *module_name;
696 PyObject *source;
697 PyObject *source_list;
698 PyObject *source_line;
699 PyObject *returned;
700
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200701 if ((tmp = _PyUnicode_FromId(&PyId_get_source)) == NULL)
702 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200703 if ((tmp = _PyUnicode_FromId(&PyId_splitlines)) == NULL)
704 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000705
706 /* Check/get the requisite pieces needed for the loader. */
707 loader = PyDict_GetItemString(module_globals, "__loader__");
708 module_name = PyDict_GetItemString(module_globals, "__name__");
709
710 if (loader == NULL || module_name == NULL)
711 goto standard_call;
712
713 /* Make sure the loader implements the optional get_source() method. */
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200714 if (!_PyObject_HasAttrId(loader, &PyId_get_source))
Christian Heimes33fe8092008-04-13 13:53:33 +0000715 goto standard_call;
716 /* Call get_source() to get the source code. */
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200717 source = PyObject_CallMethodObjArgs(loader, PyId_get_source.object,
718 module_name, NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +0000719 if (!source)
720 return NULL;
721 else if (source == Py_None) {
722 Py_DECREF(Py_None);
723 goto standard_call;
724 }
725
726 /* Split the source into lines. */
Victor Stinner9e30aa52011-11-21 02:49:52 +0100727 source_list = PyObject_CallMethodObjArgs(source,
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200728 PyId_splitlines.object,
729 NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +0000730 Py_DECREF(source);
731 if (!source_list)
732 return NULL;
733
734 /* Get the source line. */
735 source_line = PyList_GetItem(source_list, lineno-1);
736 if (!source_line) {
737 Py_DECREF(source_list);
738 return NULL;
739 }
740
741 /* Handle the warning. */
742 returned = warn_explicit(category, message, filename, lineno, module,
Victor Stinner14e461d2013-08-26 22:28:21 +0200743 registry, source_line);
Christian Heimes33fe8092008-04-13 13:53:33 +0000744 Py_DECREF(source_list);
745 return returned;
746 }
747
748 standard_call:
749 return warn_explicit(category, message, filename, lineno, module,
Victor Stinner14e461d2013-08-26 22:28:21 +0200750 registry, NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +0000751}
752
753
754/* Function to issue a warning message; may raise an exception. */
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000755
756static int
757warn_unicode(PyObject *category, PyObject *message,
758 Py_ssize_t stack_level)
Christian Heimes33fe8092008-04-13 13:53:33 +0000759{
760 PyObject *res;
Christian Heimes33fe8092008-04-13 13:53:33 +0000761
762 if (category == NULL)
763 category = PyExc_RuntimeWarning;
764
765 res = do_warn(message, category, stack_level);
Christian Heimes33fe8092008-04-13 13:53:33 +0000766 if (res == NULL)
767 return -1;
768 Py_DECREF(res);
769
770 return 0;
771}
772
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000773int
774PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level,
775 const char *format, ...)
776{
777 int ret;
778 PyObject *message;
779 va_list vargs;
780
781#ifdef HAVE_STDARG_PROTOTYPES
782 va_start(vargs, format);
783#else
784 va_start(vargs);
785#endif
786 message = PyUnicode_FromFormatV(format, vargs);
787 if (message != NULL) {
788 ret = warn_unicode(category, message, stack_level);
789 Py_DECREF(message);
790 }
791 else
792 ret = -1;
793 va_end(vargs);
794 return ret;
795}
796
797int
798PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
799{
800 int ret;
801 PyObject *message = PyUnicode_FromString(text);
802 if (message == NULL)
803 return -1;
804 ret = warn_unicode(category, message, stack_level);
805 Py_DECREF(message);
806 return ret;
807}
808
Ezio Melotti42da6632011-03-15 05:18:48 +0200809/* PyErr_Warn is only for backwards compatibility and will be removed.
Christian Heimes33fe8092008-04-13 13:53:33 +0000810 Use PyErr_WarnEx instead. */
811
812#undef PyErr_Warn
813
814PyAPI_FUNC(int)
815PyErr_Warn(PyObject *category, char *text)
816{
817 return PyErr_WarnEx(category, text, 1);
818}
819
820/* Warning with explicit origin */
821int
Victor Stinner14e461d2013-08-26 22:28:21 +0200822PyErr_WarnExplicitObject(PyObject *category, PyObject *message,
823 PyObject *filename, int lineno,
824 PyObject *module, PyObject *registry)
825{
826 PyObject *res;
827 if (category == NULL)
828 category = PyExc_RuntimeWarning;
829 res = warn_explicit(category, message, filename, lineno,
830 module, registry, NULL);
831 if (res == NULL)
832 return -1;
833 Py_DECREF(res);
834 return 0;
835}
836
837int
Christian Heimes33fe8092008-04-13 13:53:33 +0000838PyErr_WarnExplicit(PyObject *category, const char *text,
839 const char *filename_str, int lineno,
840 const char *module_str, PyObject *registry)
841{
Christian Heimes33fe8092008-04-13 13:53:33 +0000842 PyObject *message = PyUnicode_FromString(text);
Victor Stinnercb428f02010-12-27 20:10:36 +0000843 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
Christian Heimes33fe8092008-04-13 13:53:33 +0000844 PyObject *module = NULL;
845 int ret = -1;
846
847 if (message == NULL || filename == NULL)
848 goto exit;
849 if (module_str != NULL) {
850 module = PyUnicode_FromString(module_str);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200851 if (module == NULL)
852 goto exit;
Christian Heimes33fe8092008-04-13 13:53:33 +0000853 }
854
Victor Stinner14e461d2013-08-26 22:28:21 +0200855 ret = PyErr_WarnExplicitObject(category, message, filename, lineno,
856 module, registry);
Christian Heimes33fe8092008-04-13 13:53:33 +0000857
858 exit:
859 Py_XDECREF(message);
860 Py_XDECREF(module);
861 Py_XDECREF(filename);
862 return ret;
863}
864
Antoine Pitrou070cb3c2013-05-08 13:23:25 +0200865int
866PyErr_WarnExplicitFormat(PyObject *category,
867 const char *filename_str, int lineno,
868 const char *module_str, PyObject *registry,
869 const char *format, ...)
870{
871 PyObject *message;
872 PyObject *module = NULL;
873 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
874 int ret = -1;
875 va_list vargs;
876
877 if (filename == NULL)
878 goto exit;
879 if (module_str != NULL) {
880 module = PyUnicode_FromString(module_str);
881 if (module == NULL)
882 goto exit;
883 }
884
885#ifdef HAVE_STDARG_PROTOTYPES
886 va_start(vargs, format);
887#else
888 va_start(vargs);
889#endif
890 message = PyUnicode_FromFormatV(format, vargs);
891 if (message != NULL) {
892 PyObject *res;
893 res = warn_explicit(category, message, filename, lineno,
894 module, registry, NULL);
895 Py_DECREF(message);
896 if (res != NULL) {
897 Py_DECREF(res);
898 ret = 0;
899 }
900 }
901 va_end(vargs);
902exit:
903 Py_XDECREF(module);
904 Py_XDECREF(filename);
905 return ret;
906}
907
Christian Heimes33fe8092008-04-13 13:53:33 +0000908
909PyDoc_STRVAR(warn_doc,
910"Issue a warning, or maybe ignore it or raise an exception.");
911
912PyDoc_STRVAR(warn_explicit_doc,
913"Low-level inferface to warnings functionality.");
914
915static PyMethodDef warnings_functions[] = {
916 {"warn", (PyCFunction)warnings_warn, METH_VARARGS | METH_KEYWORDS,
917 warn_doc},
918 {"warn_explicit", (PyCFunction)warnings_warn_explicit,
919 METH_VARARGS | METH_KEYWORDS, warn_explicit_doc},
Christian Heimes1a8501c2008-10-02 19:56:01 +0000920 /* XXX(brett.cannon): add showwarning? */
921 /* XXX(brett.cannon): Reasonable to add formatwarning? */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 {NULL, NULL} /* sentinel */
Christian Heimes33fe8092008-04-13 13:53:33 +0000923};
924
925
926static PyObject *
927create_filter(PyObject *category, const char *action)
928{
929 static PyObject *ignore_str = NULL;
930 static PyObject *error_str = NULL;
931 static PyObject *default_str = NULL;
Georg Brandl08be72d2010-10-24 15:11:22 +0000932 static PyObject *always_str = NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000933 PyObject *action_obj = NULL;
934 PyObject *lineno, *result;
935
936 if (!strcmp(action, "ignore")) {
937 if (ignore_str == NULL) {
938 ignore_str = PyUnicode_InternFromString("ignore");
939 if (ignore_str == NULL)
940 return NULL;
941 }
942 action_obj = ignore_str;
943 }
944 else if (!strcmp(action, "error")) {
945 if (error_str == NULL) {
946 error_str = PyUnicode_InternFromString("error");
947 if (error_str == NULL)
948 return NULL;
949 }
950 action_obj = error_str;
951 }
952 else if (!strcmp(action, "default")) {
953 if (default_str == NULL) {
954 default_str = PyUnicode_InternFromString("default");
955 if (default_str == NULL)
956 return NULL;
957 }
958 action_obj = default_str;
959 }
Georg Brandl08be72d2010-10-24 15:11:22 +0000960 else if (!strcmp(action, "always")) {
961 if (always_str == NULL) {
962 always_str = PyUnicode_InternFromString("always");
963 if (always_str == NULL)
964 return NULL;
965 }
966 action_obj = always_str;
967 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000968 else {
969 Py_FatalError("unknown action");
970 }
971
972 /* This assumes the line number is zero for now. */
973 lineno = PyLong_FromLong(0);
974 if (lineno == NULL)
975 return NULL;
976 result = PyTuple_Pack(5, action_obj, Py_None, category, Py_None, lineno);
977 Py_DECREF(lineno);
978 return result;
979}
980
981static PyObject *
982init_filters(void)
983{
Georg Brandl08be72d2010-10-24 15:11:22 +0000984 PyObject *filters = PyList_New(5);
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000985 unsigned int pos = 0; /* Post-incremented in each use. */
986 unsigned int x;
Georg Brandl08be72d2010-10-24 15:11:22 +0000987 const char *bytes_action, *resource_action;
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000988
Christian Heimes33fe8092008-04-13 13:53:33 +0000989 if (filters == NULL)
990 return NULL;
991
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000992 PyList_SET_ITEM(filters, pos++,
993 create_filter(PyExc_DeprecationWarning, "ignore"));
994 PyList_SET_ITEM(filters, pos++,
Christian Heimes33fe8092008-04-13 13:53:33 +0000995 create_filter(PyExc_PendingDeprecationWarning, "ignore"));
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +0000996 PyList_SET_ITEM(filters, pos++,
997 create_filter(PyExc_ImportWarning, "ignore"));
Christian Heimes33fe8092008-04-13 13:53:33 +0000998 if (Py_BytesWarningFlag > 1)
999 bytes_action = "error";
1000 else if (Py_BytesWarningFlag)
1001 bytes_action = "default";
1002 else
1003 bytes_action = "ignore";
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001004 PyList_SET_ITEM(filters, pos++, create_filter(PyExc_BytesWarning,
Christian Heimes33fe8092008-04-13 13:53:33 +00001005 bytes_action));
Georg Brandl08be72d2010-10-24 15:11:22 +00001006 /* resource usage warnings are enabled by default in pydebug mode */
1007#ifdef Py_DEBUG
1008 resource_action = "always";
1009#else
1010 resource_action = "ignore";
1011#endif
1012 PyList_SET_ITEM(filters, pos++, create_filter(PyExc_ResourceWarning,
1013 resource_action));
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001014 for (x = 0; x < pos; x += 1) {
1015 if (PyList_GET_ITEM(filters, x) == NULL) {
1016 Py_DECREF(filters);
1017 return NULL;
1018 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001019 }
1020
1021 return filters;
1022}
1023
Martin v. Löwis1a214512008-06-11 05:26:20 +00001024static struct PyModuleDef warningsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 PyModuleDef_HEAD_INIT,
1026 MODULE_NAME,
1027 warnings__doc__,
1028 0,
1029 warnings_functions,
1030 NULL,
1031 NULL,
1032 NULL,
1033 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001034};
1035
Christian Heimes33fe8092008-04-13 13:53:33 +00001036
1037PyMODINIT_FUNC
1038_PyWarnings_Init(void)
1039{
Brett Cannon0759dd62009-04-01 18:13:07 +00001040 PyObject *m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001041
Martin v. Löwis1a214512008-06-11 05:26:20 +00001042 m = PyModule_Create(&warningsmodule);
Christian Heimes33fe8092008-04-13 13:53:33 +00001043 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001044 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001045
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001046 if (_filters == NULL) {
1047 _filters = init_filters();
1048 if (_filters == NULL)
1049 return NULL;
1050 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001051 Py_INCREF(_filters);
1052 if (PyModule_AddObject(m, "filters", _filters) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001053 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001054
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001055 if (_once_registry == NULL) {
1056 _once_registry = PyDict_New();
1057 if (_once_registry == NULL)
1058 return NULL;
1059 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001060 Py_INCREF(_once_registry);
Brett Cannonef0e6c32010-09-04 18:24:04 +00001061 if (PyModule_AddObject(m, "_onceregistry", _once_registry) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001062 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001063
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001064 if (_default_action == NULL) {
1065 _default_action = PyUnicode_FromString("default");
1066 if (_default_action == NULL)
1067 return NULL;
1068 }
1069 Py_INCREF(_default_action);
Brett Cannonef0e6c32010-09-04 18:24:04 +00001070 if (PyModule_AddObject(m, "_defaultaction", _default_action) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001071 return NULL;
1072 return m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001073}