blob: 8cfae76a50faa855d7dc16c523fb799274cf2ad8 [file] [log] [blame]
Christian Heimes33fe8092008-04-13 13:53:33 +00001#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002#include "internal/pystate.h"
Christian Heimes33fe8092008-04-13 13:53:33 +00003#include "frameobject.h"
Victor Stinner22f18752016-12-09 18:08:18 +01004#include "clinic/_warnings.c.h"
Christian Heimes33fe8092008-04-13 13:53:33 +00005
6#define MODULE_NAME "_warnings"
Christian Heimes33fe8092008-04-13 13:53:33 +00007
8PyDoc_STRVAR(warnings__doc__,
9MODULE_NAME " provides basic warning filtering support.\n"
10"It is a helper module to speed up interpreter start-up.");
11
Victor Stinnerbd303c12013-11-07 23:07:29 +010012_Py_IDENTIFIER(argv);
13_Py_IDENTIFIER(stderr);
Christian Heimes33fe8092008-04-13 13:53:33 +000014
15static int
16check_matched(PyObject *obj, PyObject *arg)
17{
18 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020019 _Py_IDENTIFIER(match);
Christian Heimes33fe8092008-04-13 13:53:33 +000020 int rc;
21
22 if (obj == Py_None)
23 return 1;
Victor Stinner55ba38a2016-12-09 16:09:30 +010024 result = _PyObject_CallMethodIdObjArgs(obj, &PyId_match, arg, NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +000025 if (result == NULL)
26 return -1;
27
28 rc = PyObject_IsTrue(result);
29 Py_DECREF(result);
30 return rc;
31}
32
33/*
34 Returns a new reference.
35 A NULL return value can mean false or an error.
36*/
37static PyObject *
Victor Stinnere98445a2016-03-23 00:54:48 +010038get_warnings_attr(const char *attr, int try_import)
Christian Heimes33fe8092008-04-13 13:53:33 +000039{
40 static PyObject *warnings_str = NULL;
Victor Stinnere98445a2016-03-23 00:54:48 +010041 PyObject *warnings_module, *obj;
Christian Heimes33fe8092008-04-13 13:53:33 +000042
43 if (warnings_str == NULL) {
44 warnings_str = PyUnicode_InternFromString("warnings");
45 if (warnings_str == NULL)
46 return NULL;
47 }
48
Victor Stinnere98445a2016-03-23 00:54:48 +010049 /* don't try to import after the start of the Python finallization */
Eric Snow2ebc5ce2017-09-07 23:51:28 -060050 if (try_import && !_Py_IsFinalizing()) {
Victor Stinnere98445a2016-03-23 00:54:48 +010051 warnings_module = PyImport_Import(warnings_str);
52 if (warnings_module == NULL) {
53 /* Fallback to the C implementation if we cannot get
54 the Python implementation */
Serhiy Storchakad4f84802017-11-11 15:19:47 +020055 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
56 PyErr_Clear();
57 }
Christian Heimes33fe8092008-04-13 13:53:33 +000058 return NULL;
Victor Stinnere98445a2016-03-23 00:54:48 +010059 }
60 }
61 else {
Eric Snow3f9eee62017-09-15 16:35:20 -060062 warnings_module = PyImport_GetModule(warnings_str);
Victor Stinner023654f2016-03-23 17:48:22 +010063 if (warnings_module == NULL)
64 return NULL;
Victor Stinnere98445a2016-03-23 00:54:48 +010065 }
66
Victor Stinnere98445a2016-03-23 00:54:48 +010067 obj = PyObject_GetAttrString(warnings_module, attr);
68 Py_DECREF(warnings_module);
Serhiy Storchakad4f84802017-11-11 15:19:47 +020069 if (obj == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
70 PyErr_Clear();
71 }
Victor Stinnere98445a2016-03-23 00:54:48 +010072 return obj;
Christian Heimes33fe8092008-04-13 13:53:33 +000073}
74
75
Neal Norwitz32dde222008-04-15 06:43:13 +000076static PyObject *
Christian Heimes33fe8092008-04-13 13:53:33 +000077get_once_registry(void)
78{
79 PyObject *registry;
80
Victor Stinnere98445a2016-03-23 00:54:48 +010081 registry = get_warnings_attr("onceregistry", 0);
Christian Heimes33fe8092008-04-13 13:53:33 +000082 if (registry == NULL) {
83 if (PyErr_Occurred())
84 return NULL;
Serhiy Storchakad4f84802017-11-11 15:19:47 +020085 assert(_PyRuntime.warnings.once_registry);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060086 return _PyRuntime.warnings.once_registry;
Christian Heimes33fe8092008-04-13 13:53:33 +000087 }
Oren Milman252033d2017-09-11 09:28:39 +030088 if (!PyDict_Check(registry)) {
Serhiy Storchakad4f84802017-11-11 15:19:47 +020089 PyErr_Format(PyExc_TypeError,
90 MODULE_NAME ".onceregistry must be a dict, "
91 "not '%.200s'",
92 Py_TYPE(registry)->tp_name);
Oren Milman252033d2017-09-11 09:28:39 +030093 Py_DECREF(registry);
94 return NULL;
95 }
Serhiy Storchakad4f84802017-11-11 15:19:47 +020096 Py_SETREF(_PyRuntime.warnings.once_registry, registry);
Christian Heimes33fe8092008-04-13 13:53:33 +000097 return registry;
98}
99
100
Brett Cannon0759dd62009-04-01 18:13:07 +0000101static PyObject *
102get_default_action(void)
103{
104 PyObject *default_action;
105
Victor Stinnere98445a2016-03-23 00:54:48 +0100106 default_action = get_warnings_attr("defaultaction", 0);
Brett Cannon0759dd62009-04-01 18:13:07 +0000107 if (default_action == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 if (PyErr_Occurred()) {
109 return NULL;
110 }
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200111 assert(_PyRuntime.warnings.default_action);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600112 return _PyRuntime.warnings.default_action;
Brett Cannon0759dd62009-04-01 18:13:07 +0000113 }
Oren Milman9d984fd2017-09-12 00:18:09 +0300114 if (!PyUnicode_Check(default_action)) {
115 PyErr_Format(PyExc_TypeError,
116 MODULE_NAME ".defaultaction must be a string, "
117 "not '%.200s'",
118 Py_TYPE(default_action)->tp_name);
119 Py_DECREF(default_action);
120 return NULL;
121 }
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200122 Py_SETREF(_PyRuntime.warnings.default_action, default_action);
Brett Cannon0759dd62009-04-01 18:13:07 +0000123 return default_action;
124}
125
126
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400127/* The item is a new reference. */
Victor Stinnera4c704b2013-10-29 23:43:41 +0100128static PyObject*
Christian Heimes33fe8092008-04-13 13:53:33 +0000129get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
130 PyObject *module, PyObject **item)
131{
Brett Cannon0759dd62009-04-01 18:13:07 +0000132 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000133 Py_ssize_t i;
134 PyObject *warnings_filters;
135
Victor Stinnere98445a2016-03-23 00:54:48 +0100136 warnings_filters = get_warnings_attr("filters", 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000137 if (warnings_filters == NULL) {
138 if (PyErr_Occurred())
139 return NULL;
140 }
141 else {
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200142 Py_SETREF(_PyRuntime.warnings.filters, warnings_filters);
Christian Heimes33fe8092008-04-13 13:53:33 +0000143 }
144
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600145 PyObject *filters = _PyRuntime.warnings.filters;
146 if (filters == NULL || !PyList_Check(filters)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000147 PyErr_SetString(PyExc_ValueError,
148 MODULE_NAME ".filters must be a list");
149 return NULL;
150 }
151
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600152 /* _PyRuntime.warnings.filters could change while we are iterating over it. */
153 for (i = 0; i < PyList_GET_SIZE(filters); i++) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000154 PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj;
155 Py_ssize_t ln;
156 int is_subclass, good_msg, good_mod;
157
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600158 tmp_item = PyList_GET_ITEM(filters, i);
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400159 if (!PyTuple_Check(tmp_item) || PyTuple_GET_SIZE(tmp_item) != 5) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000160 PyErr_Format(PyExc_ValueError,
161 MODULE_NAME ".filters item %zd isn't a 5-tuple", i);
162 return NULL;
163 }
164
165 /* Python code: action, msg, cat, mod, ln = item */
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400166 Py_INCREF(tmp_item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000167 action = PyTuple_GET_ITEM(tmp_item, 0);
168 msg = PyTuple_GET_ITEM(tmp_item, 1);
169 cat = PyTuple_GET_ITEM(tmp_item, 2);
170 mod = PyTuple_GET_ITEM(tmp_item, 3);
171 ln_obj = PyTuple_GET_ITEM(tmp_item, 4);
172
Oren Milman9d984fd2017-09-12 00:18:09 +0300173 if (!PyUnicode_Check(action)) {
174 PyErr_Format(PyExc_TypeError,
175 "action must be a string, not '%.200s'",
176 Py_TYPE(action)->tp_name);
177 Py_DECREF(tmp_item);
178 return NULL;
179 }
180
Christian Heimes33fe8092008-04-13 13:53:33 +0000181 good_msg = check_matched(msg, text);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400182 if (good_msg == -1) {
183 Py_DECREF(tmp_item);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100184 return NULL;
Benjamin Peterson8c598162015-05-03 11:28:46 -0400185 }
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100186
Christian Heimes33fe8092008-04-13 13:53:33 +0000187 good_mod = check_matched(mod, module);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400188 if (good_mod == -1) {
189 Py_DECREF(tmp_item);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100190 return NULL;
Benjamin Peterson8c598162015-05-03 11:28:46 -0400191 }
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100192
Christian Heimes33fe8092008-04-13 13:53:33 +0000193 is_subclass = PyObject_IsSubclass(category, cat);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400194 if (is_subclass == -1) {
195 Py_DECREF(tmp_item);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100196 return NULL;
Benjamin Peterson8c598162015-05-03 11:28:46 -0400197 }
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100198
Christian Heimes33fe8092008-04-13 13:53:33 +0000199 ln = PyLong_AsSsize_t(ln_obj);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400200 if (ln == -1 && PyErr_Occurred()) {
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400201 Py_DECREF(tmp_item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000202 return NULL;
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400203 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000204
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400205 if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln)) {
206 *item = tmp_item;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100207 return action;
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400208 }
209
210 Py_DECREF(tmp_item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000211 }
212
Brett Cannon0759dd62009-04-01 18:13:07 +0000213 action = get_default_action();
214 if (action != NULL) {
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400215 Py_INCREF(Py_None);
216 *item = Py_None;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100217 return action;
Brett Cannon0759dd62009-04-01 18:13:07 +0000218 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000219
Christian Heimes33fe8092008-04-13 13:53:33 +0000220 return NULL;
221}
222
Brett Cannon0759dd62009-04-01 18:13:07 +0000223
Christian Heimes33fe8092008-04-13 13:53:33 +0000224static int
225already_warned(PyObject *registry, PyObject *key, int should_set)
226{
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200227 PyObject *version_obj, *already_warned;
228 _Py_IDENTIFIER(version);
Christian Heimes33fe8092008-04-13 13:53:33 +0000229
230 if (key == NULL)
231 return -1;
232
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200233 version_obj = _PyDict_GetItemId(registry, &PyId_version);
234 if (version_obj == NULL
235 || !PyLong_CheckExact(version_obj)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600236 || PyLong_AsLong(version_obj) != _PyRuntime.warnings.filters_version) {
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200237 PyDict_Clear(registry);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600238 version_obj = PyLong_FromLong(_PyRuntime.warnings.filters_version);
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200239 if (version_obj == NULL)
240 return -1;
241 if (_PyDict_SetItemId(registry, &PyId_version, version_obj) < 0) {
242 Py_DECREF(version_obj);
243 return -1;
244 }
245 Py_DECREF(version_obj);
246 }
247 else {
248 already_warned = PyDict_GetItem(registry, key);
249 if (already_warned != NULL) {
250 int rc = PyObject_IsTrue(already_warned);
251 if (rc != 0)
252 return rc;
253 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000254 }
255
256 /* This warning wasn't found in the registry, set it. */
257 if (should_set)
258 return PyDict_SetItem(registry, key, Py_True);
259 return 0;
260}
261
262/* New reference. */
263static PyObject *
264normalize_module(PyObject *filename)
265{
266 PyObject *module;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100267 int kind;
268 void *data;
Christian Heimes33fe8092008-04-13 13:53:33 +0000269 Py_ssize_t len;
270
Victor Stinner9e30aa52011-11-21 02:49:52 +0100271 len = PyUnicode_GetLength(filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000272 if (len < 0)
273 return NULL;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100274
275 if (len == 0)
276 return PyUnicode_FromString("<unknown>");
277
278 kind = PyUnicode_KIND(filename);
279 data = PyUnicode_DATA(filename);
280
281 /* if filename.endswith(".py"): */
Christian Heimes33fe8092008-04-13 13:53:33 +0000282 if (len >= 3 &&
Victor Stinnera4c704b2013-10-29 23:43:41 +0100283 PyUnicode_READ(kind, data, len-3) == '.' &&
284 PyUnicode_READ(kind, data, len-2) == 'p' &&
285 PyUnicode_READ(kind, data, len-1) == 'y')
286 {
Victor Stinner9e30aa52011-11-21 02:49:52 +0100287 module = PyUnicode_Substring(filename, 0, len-3);
Christian Heimes33fe8092008-04-13 13:53:33 +0000288 }
289 else {
290 module = filename;
291 Py_INCREF(module);
292 }
293 return module;
294}
295
296static int
297update_registry(PyObject *registry, PyObject *text, PyObject *category,
298 int add_zero)
299{
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300300 PyObject *altkey;
Christian Heimes33fe8092008-04-13 13:53:33 +0000301 int rc;
302
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300303 if (add_zero)
304 altkey = PyTuple_Pack(3, text, category, _PyLong_Zero);
Christian Heimes33fe8092008-04-13 13:53:33 +0000305 else
306 altkey = PyTuple_Pack(2, text, category);
307
308 rc = already_warned(registry, altkey, 1);
Christian Heimes33fe8092008-04-13 13:53:33 +0000309 Py_XDECREF(altkey);
310 return rc;
311}
312
313static void
Victor Stinner914cde82016-03-19 01:03:51 +0100314show_warning(PyObject *filename, int lineno, PyObject *text,
315 PyObject *category, PyObject *sourceline)
Christian Heimes33fe8092008-04-13 13:53:33 +0000316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 PyObject *f_stderr;
318 PyObject *name;
Christian Heimes33fe8092008-04-13 13:53:33 +0000319 char lineno_str[128];
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200320 _Py_IDENTIFIER(__name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000321
322 PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);
323
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200324 name = _PyObject_GetAttrId(category, &PyId___name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000325 if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */
Victor Stinnerae233ea2013-10-31 14:51:38 +0100326 goto error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000327
Victor Stinnerbd303c12013-11-07 23:07:29 +0100328 f_stderr = _PySys_GetObjectId(&PyId_stderr);
Christian Heimes33fe8092008-04-13 13:53:33 +0000329 if (f_stderr == NULL) {
330 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnerae233ea2013-10-31 14:51:38 +0100331 goto error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000332 }
333
334 /* Print "filename:lineno: category: text\n" */
Victor Stinnerae233ea2013-10-31 14:51:38 +0100335 if (PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW) < 0)
336 goto error;
337 if (PyFile_WriteString(lineno_str, f_stderr) < 0)
338 goto error;
339 if (PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW) < 0)
340 goto error;
341 if (PyFile_WriteString(": ", f_stderr) < 0)
342 goto error;
343 if (PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW) < 0)
344 goto error;
345 if (PyFile_WriteString("\n", f_stderr) < 0)
346 goto error;
347 Py_CLEAR(name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000348
349 /* Print " source_line\n" */
Christian Heimes33fe8092008-04-13 13:53:33 +0000350 if (sourceline) {
Victor Stinnera4c704b2013-10-29 23:43:41 +0100351 int kind;
352 void *data;
353 Py_ssize_t i, len;
354 Py_UCS4 ch;
355 PyObject *truncated;
Christian Heimes33fe8092008-04-13 13:53:33 +0000356
Victor Stinnera4c704b2013-10-29 23:43:41 +0100357 if (PyUnicode_READY(sourceline) < 1)
358 goto error;
359
360 kind = PyUnicode_KIND(sourceline);
361 data = PyUnicode_DATA(sourceline);
362 len = PyUnicode_GET_LENGTH(sourceline);
363 for (i=0; i<len; i++) {
364 ch = PyUnicode_READ(kind, data, i);
365 if (ch != ' ' && ch != '\t' && ch != '\014')
366 break;
367 }
368
369 truncated = PyUnicode_Substring(sourceline, i, len);
370 if (truncated == NULL)
371 goto error;
372
373 PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW);
374 Py_DECREF(truncated);
Christian Heimes33fe8092008-04-13 13:53:33 +0000375 PyFile_WriteString("\n", f_stderr);
376 }
Victor Stinner78e2c982013-07-16 01:54:37 +0200377 else {
378 _Py_DisplaySourceLine(f_stderr, filename, lineno, 2);
379 }
Victor Stinnera4c704b2013-10-29 23:43:41 +0100380
381error:
Victor Stinnerae233ea2013-10-31 14:51:38 +0100382 Py_XDECREF(name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000383 PyErr_Clear();
384}
385
Victor Stinner1231a462016-03-19 00:47:17 +0100386static int
387call_show_warning(PyObject *category, PyObject *text, PyObject *message,
388 PyObject *filename, int lineno, PyObject *lineno_obj,
Victor Stinner914cde82016-03-19 01:03:51 +0100389 PyObject *sourceline, PyObject *source)
Victor Stinner1231a462016-03-19 00:47:17 +0100390{
391 PyObject *show_fn, *msg, *res, *warnmsg_cls = NULL;
392
Victor Stinnere98445a2016-03-23 00:54:48 +0100393 /* If the source parameter is set, try to get the Python implementation.
394 The Python implementation is able to log the traceback where the source
luzpaza5293b42017-11-05 07:37:50 -0600395 was allocated, whereas the C implementation doesn't. */
Victor Stinnere98445a2016-03-23 00:54:48 +0100396 show_fn = get_warnings_attr("_showwarnmsg", source != NULL);
Victor Stinner1231a462016-03-19 00:47:17 +0100397 if (show_fn == NULL) {
398 if (PyErr_Occurred())
399 return -1;
400 show_warning(filename, lineno, text, category, sourceline);
401 return 0;
402 }
403
404 if (!PyCallable_Check(show_fn)) {
405 PyErr_SetString(PyExc_TypeError,
406 "warnings._showwarnmsg() must be set to a callable");
407 goto error;
408 }
409
Victor Stinnere98445a2016-03-23 00:54:48 +0100410 warnmsg_cls = get_warnings_attr("WarningMessage", 0);
Victor Stinner1231a462016-03-19 00:47:17 +0100411 if (warnmsg_cls == NULL) {
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200412 if (!PyErr_Occurred()) {
413 PyErr_SetString(PyExc_RuntimeError,
414 "unable to get warnings.WarningMessage");
415 }
Victor Stinner1231a462016-03-19 00:47:17 +0100416 goto error;
417 }
418
419 msg = PyObject_CallFunctionObjArgs(warnmsg_cls, message, category,
Victor Stinner914cde82016-03-19 01:03:51 +0100420 filename, lineno_obj, Py_None, Py_None, source,
Victor Stinner1231a462016-03-19 00:47:17 +0100421 NULL);
422 Py_DECREF(warnmsg_cls);
423 if (msg == NULL)
424 goto error;
425
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100426 res = PyObject_CallFunctionObjArgs(show_fn, msg, NULL);
Victor Stinner1231a462016-03-19 00:47:17 +0100427 Py_DECREF(show_fn);
428 Py_DECREF(msg);
429
430 if (res == NULL)
431 return -1;
432
433 Py_DECREF(res);
434 return 0;
435
436error:
437 Py_XDECREF(show_fn);
438 return -1;
439}
440
Christian Heimes33fe8092008-04-13 13:53:33 +0000441static PyObject *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442warn_explicit(PyObject *category, PyObject *message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000443 PyObject *filename, int lineno,
Victor Stinner914cde82016-03-19 01:03:51 +0100444 PyObject *module, PyObject *registry, PyObject *sourceline,
445 PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000446{
447 PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL;
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400448 PyObject *item = NULL;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100449 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000450 int rc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451
Victor Stinnerdcdd05b2013-11-01 00:55:30 +0100452 /* module can be None if a warning is emitted late during Python shutdown.
453 In this case, the Python warnings module was probably unloaded, filters
454 are no more available to choose as action. It is safer to ignore the
455 warning and do nothing. */
456 if (module == Py_None)
457 Py_RETURN_NONE;
458
Brett Cannondb734912008-06-27 00:52:15 +0000459 if (registry && !PyDict_Check(registry) && (registry != Py_None)) {
Oren Milman252033d2017-09-11 09:28:39 +0300460 PyErr_SetString(PyExc_TypeError, "'registry' must be a dict or None");
Brett Cannondb734912008-06-27 00:52:15 +0000461 return NULL;
462 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000463
464 /* Normalize module. */
465 if (module == NULL) {
466 module = normalize_module(filename);
467 if (module == NULL)
468 return NULL;
469 }
470 else
471 Py_INCREF(module);
472
473 /* Normalize message. */
474 Py_INCREF(message); /* DECREF'ed in cleanup. */
475 rc = PyObject_IsInstance(message, PyExc_Warning);
476 if (rc == -1) {
477 goto cleanup;
478 }
479 if (rc == 1) {
480 text = PyObject_Str(message);
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000481 if (text == NULL)
482 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000483 category = (PyObject*)message->ob_type;
484 }
485 else {
486 text = message;
Victor Stinner7bfb42d2016-12-05 17:04:32 +0100487 message = PyObject_CallFunctionObjArgs(category, message, NULL);
Brett Cannondb734912008-06-27 00:52:15 +0000488 if (message == NULL)
489 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000490 }
491
492 lineno_obj = PyLong_FromLong(lineno);
493 if (lineno_obj == NULL)
494 goto cleanup;
495
Victor Stinner22f18752016-12-09 18:08:18 +0100496 if (source == Py_None) {
497 source = NULL;
498 }
499
Christian Heimes33fe8092008-04-13 13:53:33 +0000500 /* Create key. */
501 key = PyTuple_Pack(3, text, category, lineno_obj);
502 if (key == NULL)
503 goto cleanup;
504
Brett Cannondb734912008-06-27 00:52:15 +0000505 if ((registry != NULL) && (registry != Py_None)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000506 rc = already_warned(registry, key, 0);
507 if (rc == -1)
508 goto cleanup;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 else if (rc == 1)
Christian Heimes33fe8092008-04-13 13:53:33 +0000510 goto return_none;
511 /* Else this warning hasn't been generated before. */
512 }
513
514 action = get_filter(category, text, lineno, module, &item);
515 if (action == NULL)
516 goto cleanup;
517
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200518 if (_PyUnicode_EqualToASCIIString(action, "error")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000519 PyErr_SetObject(category, message);
520 goto cleanup;
521 }
522
523 /* Store in the registry that we've been here, *except* when the action
524 is "always". */
525 rc = 0;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200526 if (!_PyUnicode_EqualToASCIIString(action, "always")) {
Brett Cannondb734912008-06-27 00:52:15 +0000527 if (registry != NULL && registry != Py_None &&
528 PyDict_SetItem(registry, key, Py_True) < 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000529 goto cleanup;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200530 else if (_PyUnicode_EqualToASCIIString(action, "ignore"))
Christian Heimes33fe8092008-04-13 13:53:33 +0000531 goto return_none;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200532 else if (_PyUnicode_EqualToASCIIString(action, "once")) {
Brett Cannondb734912008-06-27 00:52:15 +0000533 if (registry == NULL || registry == Py_None) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000534 registry = get_once_registry();
535 if (registry == NULL)
536 goto cleanup;
537 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600538 /* _PyRuntime.warnings.once_registry[(text, category)] = 1 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000540 }
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200541 else if (_PyUnicode_EqualToASCIIString(action, "module")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000542 /* registry[(text, category, 0)] = 1 */
Brett Cannondb734912008-06-27 00:52:15 +0000543 if (registry != NULL && registry != Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000545 }
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200546 else if (!_PyUnicode_EqualToASCIIString(action, "default")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000547 PyErr_Format(PyExc_RuntimeError,
Victor Stinnera4c704b2013-10-29 23:43:41 +0100548 "Unrecognized action (%R) in warnings.filters:\n %R",
549 action, item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000550 goto cleanup;
551 }
552 }
553
Christian Heimes1a8501c2008-10-02 19:56:01 +0000554 if (rc == 1) /* Already warned for this module. */
Christian Heimes33fe8092008-04-13 13:53:33 +0000555 goto return_none;
556 if (rc == 0) {
Victor Stinner1231a462016-03-19 00:47:17 +0100557 if (call_show_warning(category, text, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +0100558 lineno_obj, sourceline, source) < 0)
Victor Stinner1231a462016-03-19 00:47:17 +0100559 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000560 }
561 else /* if (rc == -1) */
562 goto cleanup;
563
564 return_none:
565 result = Py_None;
566 Py_INCREF(result);
567
568 cleanup:
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400569 Py_XDECREF(item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000570 Py_XDECREF(key);
571 Py_XDECREF(text);
572 Py_XDECREF(lineno_obj);
573 Py_DECREF(module);
Brett Cannondb734912008-06-27 00:52:15 +0000574 Py_XDECREF(message);
Christian Heimes33fe8092008-04-13 13:53:33 +0000575 return result; /* Py_None or NULL. */
576}
577
Larry Hastings714e4932015-09-06 00:39:37 -0700578static int
579is_internal_frame(PyFrameObject *frame)
580{
581 static PyObject *importlib_string = NULL;
582 static PyObject *bootstrap_string = NULL;
583 PyObject *filename;
584 int contains;
585
586 if (importlib_string == NULL) {
587 importlib_string = PyUnicode_FromString("importlib");
588 if (importlib_string == NULL) {
589 return 0;
590 }
591
592 bootstrap_string = PyUnicode_FromString("_bootstrap");
593 if (bootstrap_string == NULL) {
594 Py_DECREF(importlib_string);
595 return 0;
596 }
597 Py_INCREF(importlib_string);
598 Py_INCREF(bootstrap_string);
599 }
600
601 if (frame == NULL || frame->f_code == NULL ||
602 frame->f_code->co_filename == NULL) {
603 return 0;
604 }
605 filename = frame->f_code->co_filename;
606 if (!PyUnicode_Check(filename)) {
607 return 0;
608 }
609 contains = PyUnicode_Contains(filename, importlib_string);
610 if (contains < 0) {
611 return 0;
612 }
613 else if (contains > 0) {
614 contains = PyUnicode_Contains(filename, bootstrap_string);
615 if (contains < 0) {
616 return 0;
617 }
618 else if (contains > 0) {
619 return 1;
620 }
621 }
622
623 return 0;
624}
625
626static PyFrameObject *
627next_external_frame(PyFrameObject *frame)
628{
629 do {
630 frame = frame->f_back;
631 } while (frame != NULL && is_internal_frame(frame));
632
633 return frame;
634}
635
Christian Heimes33fe8092008-04-13 13:53:33 +0000636/* filename, module, and registry are new refs, globals is borrowed */
637/* Returns 0 on error (no new refs), 1 on success */
638static int
639setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
640 PyObject **module, PyObject **registry)
641{
642 PyObject *globals;
643
644 /* Setup globals and lineno. */
645 PyFrameObject *f = PyThreadState_GET()->frame;
Larry Hastings714e4932015-09-06 00:39:37 -0700646 // Stack level comparisons to Python code is off by one as there is no
647 // warnings-related stack level to avoid.
648 if (stack_level <= 0 || is_internal_frame(f)) {
649 while (--stack_level > 0 && f != NULL) {
650 f = f->f_back;
651 }
652 }
653 else {
654 while (--stack_level > 0 && f != NULL) {
655 f = next_external_frame(f);
656 }
657 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000658
659 if (f == NULL) {
660 globals = PyThreadState_Get()->interp->sysdict;
661 *lineno = 1;
662 }
663 else {
664 globals = f->f_globals;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000665 *lineno = PyFrame_GetLineNumber(f);
Christian Heimes33fe8092008-04-13 13:53:33 +0000666 }
667
668 *module = NULL;
669
670 /* Setup registry. */
671 assert(globals != NULL);
672 assert(PyDict_Check(globals));
673 *registry = PyDict_GetItemString(globals, "__warningregistry__");
674 if (*registry == NULL) {
675 int rc;
676
677 *registry = PyDict_New();
678 if (*registry == NULL)
679 return 0;
680
681 rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
682 if (rc < 0)
683 goto handle_error;
684 }
685 else
686 Py_INCREF(*registry);
687
688 /* Setup module. */
689 *module = PyDict_GetItemString(globals, "__name__");
Oren Milman5d3e8002017-09-24 21:28:42 +0300690 if (*module == Py_None || (*module != NULL && PyUnicode_Check(*module))) {
691 Py_INCREF(*module);
692 }
693 else {
Christian Heimes33fe8092008-04-13 13:53:33 +0000694 *module = PyUnicode_FromString("<string>");
695 if (*module == NULL)
696 goto handle_error;
697 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000698
699 /* Setup filename. */
700 *filename = PyDict_GetItemString(globals, "__file__");
Victor Stinner8b0508e2011-07-04 02:43:09 +0200701 if (*filename != NULL && PyUnicode_Check(*filename)) {
Victor Stinnerb62a7b22011-10-06 02:34:51 +0200702 Py_ssize_t len;
703 int kind;
704 void *data;
705
706 if (PyUnicode_READY(*filename))
707 goto handle_error;
708
Victor Stinner9e30aa52011-11-21 02:49:52 +0100709 len = PyUnicode_GetLength(*filename);
Victor Stinnerb62a7b22011-10-06 02:34:51 +0200710 kind = PyUnicode_KIND(*filename);
711 data = PyUnicode_DATA(*filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000712
Benjamin Peterson21e0da22012-01-11 21:00:42 -0500713#define ascii_lower(c) ((c <= 127) ? Py_TOLOWER(c) : 0)
Brett Cannonf299abd2015-04-13 14:21:02 -0400714 /* if filename.lower().endswith(".pyc"): */
Christian Heimes33fe8092008-04-13 13:53:33 +0000715 if (len >= 4 &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200716 PyUnicode_READ(kind, data, len-4) == '.' &&
Benjamin Peterson21e0da22012-01-11 21:00:42 -0500717 ascii_lower(PyUnicode_READ(kind, data, len-3)) == 'p' &&
718 ascii_lower(PyUnicode_READ(kind, data, len-2)) == 'y' &&
Brett Cannonf299abd2015-04-13 14:21:02 -0400719 ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'c')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000720 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200721 *filename = PyUnicode_Substring(*filename, 0,
722 PyUnicode_GET_LENGTH(*filename)-1);
Victor Stinner2e5f1172010-08-08 22:12:45 +0000723 if (*filename == NULL)
724 goto handle_error;
725 }
726 else
Christian Heimes33fe8092008-04-13 13:53:33 +0000727 Py_INCREF(*filename);
728 }
729 else {
Benjamin Petersonbb4a7472011-07-04 22:27:16 -0500730 *filename = NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200731 if (*module != Py_None && _PyUnicode_EqualToASCIIString(*module, "__main__")) {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100732 PyObject *argv = _PySys_GetObjectId(&PyId_argv);
Victor Stinnerce5f4fb2013-10-28 18:47:22 +0100733 /* PyList_Check() is needed because sys.argv is set to None during
734 Python finalization */
735 if (argv != NULL && PyList_Check(argv) && PyList_Size(argv) > 0) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000736 int is_true;
Christian Heimes33fe8092008-04-13 13:53:33 +0000737 *filename = PyList_GetItem(argv, 0);
738 Py_INCREF(*filename);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000739 /* If sys.argv[0] is false, then use '__main__'. */
740 is_true = PyObject_IsTrue(*filename);
741 if (is_true < 0) {
742 Py_DECREF(*filename);
743 goto handle_error;
744 }
745 else if (!is_true) {
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300746 Py_SETREF(*filename, PyUnicode_FromString("__main__"));
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000747 if (*filename == NULL)
748 goto handle_error;
749 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000750 }
751 else {
752 /* embedded interpreters don't have sys.argv, see bug #839151 */
753 *filename = PyUnicode_FromString("__main__");
Victor Stinner856f45f2013-10-30 00:04:59 +0100754 if (*filename == NULL)
755 goto handle_error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000756 }
757 }
758 if (*filename == NULL) {
759 *filename = *module;
760 Py_INCREF(*filename);
761 }
762 }
763
764 return 1;
765
766 handle_error:
767 /* filename not XDECREF'ed here as there is no way to jump here with a
768 dangling reference. */
769 Py_XDECREF(*registry);
770 Py_XDECREF(*module);
771 return 0;
772}
773
774static PyObject *
775get_category(PyObject *message, PyObject *category)
776{
777 int rc;
778
779 /* Get category. */
780 rc = PyObject_IsInstance(message, PyExc_Warning);
781 if (rc == -1)
782 return NULL;
783
784 if (rc == 1)
785 category = (PyObject*)message->ob_type;
Berker Peksagd8089e02014-07-11 19:50:25 +0300786 else if (category == NULL || category == Py_None)
Christian Heimes33fe8092008-04-13 13:53:33 +0000787 category = PyExc_UserWarning;
788
789 /* Validate category. */
790 rc = PyObject_IsSubclass(category, PyExc_Warning);
Berker Peksagd8089e02014-07-11 19:50:25 +0300791 /* category is not a subclass of PyExc_Warning or
792 PyObject_IsSubclass raised an error */
793 if (rc == -1 || rc == 0) {
794 PyErr_Format(PyExc_TypeError,
795 "category must be a Warning subclass, not '%s'",
796 Py_TYPE(category)->tp_name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000797 return NULL;
798 }
799
800 return category;
801}
802
803static PyObject *
Victor Stinner914cde82016-03-19 01:03:51 +0100804do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level,
805 PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000806{
807 PyObject *filename, *module, *registry, *res;
808 int lineno;
809
810 if (!setup_context(stack_level, &filename, &lineno, &module, &registry))
811 return NULL;
812
Victor Stinnerdcdd05b2013-11-01 00:55:30 +0100813 res = warn_explicit(category, message, filename, lineno, module, registry,
Victor Stinner914cde82016-03-19 01:03:51 +0100814 NULL, source);
Christian Heimes33fe8092008-04-13 13:53:33 +0000815 Py_DECREF(filename);
816 Py_DECREF(registry);
817 Py_DECREF(module);
818 return res;
819}
820
Victor Stinner22f18752016-12-09 18:08:18 +0100821/*[clinic input]
822warn as warnings_warn
823
824 message: object
825 category: object = None
826 stacklevel: Py_ssize_t = 1
827 source: object = None
828
829Issue a warning, or maybe ignore it or raise an exception.
830[clinic start generated code]*/
831
Christian Heimes33fe8092008-04-13 13:53:33 +0000832static PyObject *
Victor Stinner22f18752016-12-09 18:08:18 +0100833warnings_warn_impl(PyObject *module, PyObject *message, PyObject *category,
834 Py_ssize_t stacklevel, PyObject *source)
835/*[clinic end generated code: output=31ed5ab7d8d760b2 input=bfdf5cf99f6c4edd]*/
Christian Heimes33fe8092008-04-13 13:53:33 +0000836{
Christian Heimes33fe8092008-04-13 13:53:33 +0000837 category = get_category(message, category);
838 if (category == NULL)
839 return NULL;
Victor Stinner22f18752016-12-09 18:08:18 +0100840 return do_warn(message, category, stacklevel, source);
Christian Heimes33fe8092008-04-13 13:53:33 +0000841}
842
843static PyObject *
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200844get_source_line(PyObject *module_globals, int lineno)
845{
846 _Py_IDENTIFIER(get_source);
847 _Py_IDENTIFIER(__loader__);
848 _Py_IDENTIFIER(__name__);
849 PyObject *loader;
850 PyObject *module_name;
851 PyObject *get_source;
852 PyObject *source;
853 PyObject *source_list;
854 PyObject *source_line;
855
856 /* Check/get the requisite pieces needed for the loader. */
857 loader = _PyDict_GetItemIdWithError(module_globals, &PyId___loader__);
858 if (loader == NULL) {
859 return NULL;
860 }
861 Py_INCREF(loader);
862 module_name = _PyDict_GetItemIdWithError(module_globals, &PyId___name__);
863 if (!module_name) {
864 Py_DECREF(loader);
865 return NULL;
866 }
867 Py_INCREF(module_name);
868
869 /* Make sure the loader implements the optional get_source() method. */
870 get_source = _PyObject_GetAttrId(loader, &PyId_get_source);
871 Py_DECREF(loader);
872 if (!get_source) {
873 Py_DECREF(module_name);
874 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
875 PyErr_Clear();
876 }
877 return NULL;
878 }
879 /* Call get_source() to get the source code. */
880 source = PyObject_CallFunctionObjArgs(get_source, module_name, NULL);
881 Py_DECREF(get_source);
882 Py_DECREF(module_name);
883 if (!source) {
884 return NULL;
885 }
886 if (source == Py_None) {
887 Py_DECREF(source);
888 return NULL;
889 }
890
891 /* Split the source into lines. */
892 source_list = PyUnicode_Splitlines(source, 0);
893 Py_DECREF(source);
894 if (!source_list) {
895 return NULL;
896 }
897
898 /* Get the source line. */
899 source_line = PyList_GetItem(source_list, lineno-1);
900 Py_XINCREF(source_line);
901 Py_DECREF(source_list);
902 return source_line;
903}
904
905static PyObject *
Christian Heimes33fe8092008-04-13 13:53:33 +0000906warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
907{
908 static char *kwd_list[] = {"message", "category", "filename", "lineno",
Victor Stinner914cde82016-03-19 01:03:51 +0100909 "module", "registry", "module_globals",
910 "source", 0};
Christian Heimes33fe8092008-04-13 13:53:33 +0000911 PyObject *message;
912 PyObject *category;
913 PyObject *filename;
914 int lineno;
915 PyObject *module = NULL;
916 PyObject *registry = NULL;
917 PyObject *module_globals = NULL;
Victor Stinner914cde82016-03-19 01:03:51 +0100918 PyObject *sourceobj = NULL;
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200919 PyObject *source_line = NULL;
920 PyObject *returned;
Christian Heimes33fe8092008-04-13 13:53:33 +0000921
Victor Stinner914cde82016-03-19 01:03:51 +0100922 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOUi|OOOO:warn_explicit",
Christian Heimes33fe8092008-04-13 13:53:33 +0000923 kwd_list, &message, &category, &filename, &lineno, &module,
Victor Stinner914cde82016-03-19 01:03:51 +0100924 &registry, &module_globals, &sourceobj))
Christian Heimes33fe8092008-04-13 13:53:33 +0000925 return NULL;
926
927 if (module_globals) {
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200928 source_line = get_source_line(module_globals, lineno);
929 if (source_line == NULL && PyErr_Occurred()) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000930 return NULL;
931 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000932 }
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200933 returned = warn_explicit(category, message, filename, lineno, module,
934 registry, source_line, sourceobj);
935 Py_XDECREF(source_line);
936 return returned;
Christian Heimes33fe8092008-04-13 13:53:33 +0000937}
938
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200939static PyObject *
940warnings_filters_mutated(PyObject *self, PyObject *args)
941{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600942 _PyRuntime.warnings.filters_version++;
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200943 Py_RETURN_NONE;
944}
945
Christian Heimes33fe8092008-04-13 13:53:33 +0000946
947/* Function to issue a warning message; may raise an exception. */
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000948
949static int
950warn_unicode(PyObject *category, PyObject *message,
Victor Stinner914cde82016-03-19 01:03:51 +0100951 Py_ssize_t stack_level, PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000952{
953 PyObject *res;
Christian Heimes33fe8092008-04-13 13:53:33 +0000954
955 if (category == NULL)
956 category = PyExc_RuntimeWarning;
957
Victor Stinner914cde82016-03-19 01:03:51 +0100958 res = do_warn(message, category, stack_level, source);
Christian Heimes33fe8092008-04-13 13:53:33 +0000959 if (res == NULL)
960 return -1;
961 Py_DECREF(res);
962
963 return 0;
964}
965
Victor Stinner914cde82016-03-19 01:03:51 +0100966static int
967_PyErr_WarnFormatV(PyObject *source,
968 PyObject *category, Py_ssize_t stack_level,
969 const char *format, va_list vargs)
970{
971 PyObject *message;
972 int res;
973
974 message = PyUnicode_FromFormatV(format, vargs);
975 if (message == NULL)
976 return -1;
977
978 res = warn_unicode(category, message, stack_level, source);
979 Py_DECREF(message);
980 return res;
981}
982
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000983int
984PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level,
985 const char *format, ...)
986{
Victor Stinner914cde82016-03-19 01:03:51 +0100987 int res;
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000988 va_list vargs;
989
990#ifdef HAVE_STDARG_PROTOTYPES
991 va_start(vargs, format);
992#else
993 va_start(vargs);
994#endif
Victor Stinner914cde82016-03-19 01:03:51 +0100995 res = _PyErr_WarnFormatV(NULL, category, stack_level, format, vargs);
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000996 va_end(vargs);
Victor Stinner914cde82016-03-19 01:03:51 +0100997 return res;
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000998}
999
1000int
Victor Stinner914cde82016-03-19 01:03:51 +01001001PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level,
1002 const char *format, ...)
1003{
1004 int res;
1005 va_list vargs;
1006
1007#ifdef HAVE_STDARG_PROTOTYPES
1008 va_start(vargs, format);
1009#else
1010 va_start(vargs);
1011#endif
1012 res = _PyErr_WarnFormatV(source, PyExc_ResourceWarning,
1013 stack_level, format, vargs);
1014 va_end(vargs);
1015 return res;
1016}
1017
1018
1019int
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001020PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
1021{
1022 int ret;
1023 PyObject *message = PyUnicode_FromString(text);
1024 if (message == NULL)
1025 return -1;
Victor Stinner914cde82016-03-19 01:03:51 +01001026 ret = warn_unicode(category, message, stack_level, NULL);
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001027 Py_DECREF(message);
1028 return ret;
1029}
1030
Ezio Melotti42da6632011-03-15 05:18:48 +02001031/* PyErr_Warn is only for backwards compatibility and will be removed.
Christian Heimes33fe8092008-04-13 13:53:33 +00001032 Use PyErr_WarnEx instead. */
1033
1034#undef PyErr_Warn
1035
1036PyAPI_FUNC(int)
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001037PyErr_Warn(PyObject *category, const char *text)
Christian Heimes33fe8092008-04-13 13:53:33 +00001038{
1039 return PyErr_WarnEx(category, text, 1);
1040}
1041
1042/* Warning with explicit origin */
1043int
Victor Stinner14e461d2013-08-26 22:28:21 +02001044PyErr_WarnExplicitObject(PyObject *category, PyObject *message,
1045 PyObject *filename, int lineno,
1046 PyObject *module, PyObject *registry)
1047{
1048 PyObject *res;
1049 if (category == NULL)
1050 category = PyExc_RuntimeWarning;
1051 res = warn_explicit(category, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +01001052 module, registry, NULL, NULL);
Victor Stinner14e461d2013-08-26 22:28:21 +02001053 if (res == NULL)
1054 return -1;
1055 Py_DECREF(res);
1056 return 0;
1057}
1058
1059int
Christian Heimes33fe8092008-04-13 13:53:33 +00001060PyErr_WarnExplicit(PyObject *category, const char *text,
1061 const char *filename_str, int lineno,
1062 const char *module_str, PyObject *registry)
1063{
Christian Heimes33fe8092008-04-13 13:53:33 +00001064 PyObject *message = PyUnicode_FromString(text);
Victor Stinnercb428f02010-12-27 20:10:36 +00001065 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
Christian Heimes33fe8092008-04-13 13:53:33 +00001066 PyObject *module = NULL;
1067 int ret = -1;
1068
1069 if (message == NULL || filename == NULL)
1070 goto exit;
1071 if (module_str != NULL) {
1072 module = PyUnicode_FromString(module_str);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001073 if (module == NULL)
1074 goto exit;
Christian Heimes33fe8092008-04-13 13:53:33 +00001075 }
1076
Victor Stinner14e461d2013-08-26 22:28:21 +02001077 ret = PyErr_WarnExplicitObject(category, message, filename, lineno,
1078 module, registry);
Christian Heimes33fe8092008-04-13 13:53:33 +00001079
1080 exit:
1081 Py_XDECREF(message);
1082 Py_XDECREF(module);
1083 Py_XDECREF(filename);
1084 return ret;
1085}
1086
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001087int
1088PyErr_WarnExplicitFormat(PyObject *category,
1089 const char *filename_str, int lineno,
1090 const char *module_str, PyObject *registry,
1091 const char *format, ...)
1092{
1093 PyObject *message;
1094 PyObject *module = NULL;
1095 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
1096 int ret = -1;
1097 va_list vargs;
1098
1099 if (filename == NULL)
1100 goto exit;
1101 if (module_str != NULL) {
1102 module = PyUnicode_FromString(module_str);
1103 if (module == NULL)
1104 goto exit;
1105 }
1106
1107#ifdef HAVE_STDARG_PROTOTYPES
1108 va_start(vargs, format);
1109#else
1110 va_start(vargs);
1111#endif
1112 message = PyUnicode_FromFormatV(format, vargs);
1113 if (message != NULL) {
1114 PyObject *res;
1115 res = warn_explicit(category, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +01001116 module, registry, NULL, NULL);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001117 Py_DECREF(message);
1118 if (res != NULL) {
1119 Py_DECREF(res);
1120 ret = 0;
1121 }
1122 }
1123 va_end(vargs);
1124exit:
1125 Py_XDECREF(module);
1126 Py_XDECREF(filename);
1127 return ret;
1128}
1129
Christian Heimes33fe8092008-04-13 13:53:33 +00001130
Christian Heimes33fe8092008-04-13 13:53:33 +00001131PyDoc_STRVAR(warn_explicit_doc,
1132"Low-level inferface to warnings functionality.");
1133
1134static PyMethodDef warnings_functions[] = {
Victor Stinner22f18752016-12-09 18:08:18 +01001135 WARNINGS_WARN_METHODDEF
Christian Heimes33fe8092008-04-13 13:53:33 +00001136 {"warn_explicit", (PyCFunction)warnings_warn_explicit,
1137 METH_VARARGS | METH_KEYWORDS, warn_explicit_doc},
Antoine Pitroucb0a0062014-09-18 02:40:46 +02001138 {"_filters_mutated", (PyCFunction)warnings_filters_mutated, METH_NOARGS,
1139 NULL},
Christian Heimes1a8501c2008-10-02 19:56:01 +00001140 /* XXX(brett.cannon): add showwarning? */
1141 /* XXX(brett.cannon): Reasonable to add formatwarning? */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 {NULL, NULL} /* sentinel */
Christian Heimes33fe8092008-04-13 13:53:33 +00001143};
1144
1145
1146static PyObject *
1147create_filter(PyObject *category, const char *action)
1148{
1149 static PyObject *ignore_str = NULL;
1150 static PyObject *error_str = NULL;
1151 static PyObject *default_str = NULL;
Georg Brandl08be72d2010-10-24 15:11:22 +00001152 static PyObject *always_str = NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001153 PyObject *action_obj = NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001154
1155 if (!strcmp(action, "ignore")) {
1156 if (ignore_str == NULL) {
1157 ignore_str = PyUnicode_InternFromString("ignore");
1158 if (ignore_str == NULL)
1159 return NULL;
1160 }
1161 action_obj = ignore_str;
1162 }
1163 else if (!strcmp(action, "error")) {
1164 if (error_str == NULL) {
1165 error_str = PyUnicode_InternFromString("error");
1166 if (error_str == NULL)
1167 return NULL;
1168 }
1169 action_obj = error_str;
1170 }
1171 else if (!strcmp(action, "default")) {
1172 if (default_str == NULL) {
1173 default_str = PyUnicode_InternFromString("default");
1174 if (default_str == NULL)
1175 return NULL;
1176 }
1177 action_obj = default_str;
1178 }
Georg Brandl08be72d2010-10-24 15:11:22 +00001179 else if (!strcmp(action, "always")) {
1180 if (always_str == NULL) {
1181 always_str = PyUnicode_InternFromString("always");
1182 if (always_str == NULL)
1183 return NULL;
1184 }
1185 action_obj = always_str;
1186 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001187 else {
1188 Py_FatalError("unknown action");
1189 }
1190
1191 /* This assumes the line number is zero for now. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001192 return PyTuple_Pack(5, action_obj, Py_None,
1193 category, Py_None, _PyLong_Zero);
Christian Heimes33fe8092008-04-13 13:53:33 +00001194}
1195
1196static PyObject *
1197init_filters(void)
1198{
Victor Stinner895862a2017-11-20 09:47:03 -08001199#ifndef Py_DEBUG
Georg Brandl08be72d2010-10-24 15:11:22 +00001200 PyObject *filters = PyList_New(5);
Victor Stinner895862a2017-11-20 09:47:03 -08001201#else
1202 PyObject *filters = PyList_New(2);
1203#endif
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001204 unsigned int pos = 0; /* Post-incremented in each use. */
1205 unsigned int x;
Georg Brandl08be72d2010-10-24 15:11:22 +00001206 const char *bytes_action, *resource_action;
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001207
Christian Heimes33fe8092008-04-13 13:53:33 +00001208 if (filters == NULL)
1209 return NULL;
1210
Victor Stinner895862a2017-11-20 09:47:03 -08001211#ifndef Py_DEBUG
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001212 PyList_SET_ITEM(filters, pos++,
1213 create_filter(PyExc_DeprecationWarning, "ignore"));
1214 PyList_SET_ITEM(filters, pos++,
Christian Heimes33fe8092008-04-13 13:53:33 +00001215 create_filter(PyExc_PendingDeprecationWarning, "ignore"));
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001216 PyList_SET_ITEM(filters, pos++,
1217 create_filter(PyExc_ImportWarning, "ignore"));
Victor Stinner895862a2017-11-20 09:47:03 -08001218#endif
1219
Christian Heimes33fe8092008-04-13 13:53:33 +00001220 if (Py_BytesWarningFlag > 1)
1221 bytes_action = "error";
1222 else if (Py_BytesWarningFlag)
1223 bytes_action = "default";
1224 else
1225 bytes_action = "ignore";
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001226 PyList_SET_ITEM(filters, pos++, create_filter(PyExc_BytesWarning,
Christian Heimes33fe8092008-04-13 13:53:33 +00001227 bytes_action));
Georg Brandl08be72d2010-10-24 15:11:22 +00001228 /* resource usage warnings are enabled by default in pydebug mode */
1229#ifdef Py_DEBUG
1230 resource_action = "always";
1231#else
1232 resource_action = "ignore";
1233#endif
1234 PyList_SET_ITEM(filters, pos++, create_filter(PyExc_ResourceWarning,
1235 resource_action));
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001236 for (x = 0; x < pos; x += 1) {
1237 if (PyList_GET_ITEM(filters, x) == NULL) {
1238 Py_DECREF(filters);
1239 return NULL;
1240 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001241 }
1242
1243 return filters;
1244}
1245
Martin v. Löwis1a214512008-06-11 05:26:20 +00001246static struct PyModuleDef warningsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 PyModuleDef_HEAD_INIT,
1248 MODULE_NAME,
1249 warnings__doc__,
1250 0,
1251 warnings_functions,
1252 NULL,
1253 NULL,
1254 NULL,
1255 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001256};
1257
Christian Heimes33fe8092008-04-13 13:53:33 +00001258
1259PyMODINIT_FUNC
1260_PyWarnings_Init(void)
1261{
Brett Cannon0759dd62009-04-01 18:13:07 +00001262 PyObject *m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001263
Martin v. Löwis1a214512008-06-11 05:26:20 +00001264 m = PyModule_Create(&warningsmodule);
Christian Heimes33fe8092008-04-13 13:53:33 +00001265 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001266 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001267
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001268 if (_PyRuntime.warnings.filters == NULL) {
1269 _PyRuntime.warnings.filters = init_filters();
1270 if (_PyRuntime.warnings.filters == NULL)
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001271 return NULL;
1272 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001273 Py_INCREF(_PyRuntime.warnings.filters);
1274 if (PyModule_AddObject(m, "filters", _PyRuntime.warnings.filters) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001275 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001276
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001277 if (_PyRuntime.warnings.once_registry == NULL) {
1278 _PyRuntime.warnings.once_registry = PyDict_New();
1279 if (_PyRuntime.warnings.once_registry == NULL)
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001280 return NULL;
1281 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001282 Py_INCREF(_PyRuntime.warnings.once_registry);
1283 if (PyModule_AddObject(m, "_onceregistry",
1284 _PyRuntime.warnings.once_registry) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001285 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001286
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001287 if (_PyRuntime.warnings.default_action == NULL) {
1288 _PyRuntime.warnings.default_action = PyUnicode_FromString("default");
1289 if (_PyRuntime.warnings.default_action == NULL)
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001290 return NULL;
1291 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001292 Py_INCREF(_PyRuntime.warnings.default_action);
1293 if (PyModule_AddObject(m, "_defaultaction",
1294 _PyRuntime.warnings.default_action) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001295 return NULL;
Antoine Pitroucb0a0062014-09-18 02:40:46 +02001296
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001297 _PyRuntime.warnings.filters_version = 0;
Martin v. Löwis1a214512008-06-11 05:26:20 +00001298 return m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001299}