blob: b8585d204787db0ca3cdff32e0eacea9bf3a376d [file] [log] [blame]
Christian Heimes33fe8092008-04-13 13:53:33 +00001#include "Python.h"
Victor Stinner4d231bc2019-11-14 13:36:21 +01002#include "pycore_pyerrors.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01003#include "pycore_pystate.h"
Christian Heimes33fe8092008-04-13 13:53:33 +00004#include "frameobject.h"
Victor Stinner22f18752016-12-09 18:08:18 +01005#include "clinic/_warnings.c.h"
Christian Heimes33fe8092008-04-13 13:53:33 +00006
7#define MODULE_NAME "_warnings"
Christian Heimes33fe8092008-04-13 13:53:33 +00008
9PyDoc_STRVAR(warnings__doc__,
10MODULE_NAME " provides basic warning filtering support.\n"
11"It is a helper module to speed up interpreter start-up.");
12
Victor Stinnerbd303c12013-11-07 23:07:29 +010013_Py_IDENTIFIER(stderr);
Victor Stinner747f48e2017-12-12 22:59:48 +010014#ifndef Py_DEBUG
Nick Coghlan9b997472018-01-08 12:45:02 +100015_Py_IDENTIFIER(default);
Victor Stinnerb98f1712017-11-23 17:13:44 +010016_Py_IDENTIFIER(ignore);
Victor Stinner747f48e2017-12-12 22:59:48 +010017#endif
Christian Heimes33fe8092008-04-13 13:53:33 +000018
Eric Snow86ea5812019-05-10 13:29:55 -040019
20/*************************************************************************/
21
22typedef struct _warnings_runtime_state WarningsState;
23
24/* Forward declaration of the _warnings module definition. */
25static struct PyModuleDef warningsmodule;
26
27/* Given a module object, get its per-module state. */
28static WarningsState *
29_Warnings_GetState()
30{
Victor Stinner4d231bc2019-11-14 13:36:21 +010031 PyThreadState *tstate = _PyThreadState_GET();
Eric Snow86ea5812019-05-10 13:29:55 -040032 if (tstate == NULL) {
Victor Stinner4d231bc2019-11-14 13:36:21 +010033 _PyErr_SetString(tstate, PyExc_RuntimeError,
34 "_Warnings_GetState: could not identify "
35 "current interpreter");
Eric Snow86ea5812019-05-10 13:29:55 -040036 return NULL;
37 }
38 return &tstate->interp->warnings;
39}
40
41/* Clear the given warnings module state. */
42static void
43_Warnings_ClearState(WarningsState *st)
44{
45 Py_CLEAR(st->filters);
46 Py_CLEAR(st->once_registry);
47 Py_CLEAR(st->default_action);
48}
49
50#ifndef Py_DEBUG
51static PyObject *
52create_filter(PyObject *category, _Py_Identifier *id, const char *modname)
53{
54 PyObject *modname_obj = NULL;
55 PyObject *action_str = _PyUnicode_FromId(id);
56 if (action_str == NULL) {
57 return NULL;
58 }
59
60 /* Default to "no module name" for initial filter set */
61 if (modname != NULL) {
62 modname_obj = PyUnicode_InternFromString(modname);
63 if (modname_obj == NULL) {
64 return NULL;
65 }
66 } else {
67 modname_obj = Py_None;
68 }
69
70 /* This assumes the line number is zero for now. */
71 return PyTuple_Pack(5, action_str, Py_None,
72 category, modname_obj, _PyLong_Zero);
73}
74#endif
75
76static PyObject *
77init_filters(void)
78{
79#ifdef Py_DEBUG
80 /* Py_DEBUG builds show all warnings by default */
81 return PyList_New(0);
82#else
83 /* Other builds ignore a number of warning categories by default */
84 PyObject *filters = PyList_New(5);
85 if (filters == NULL) {
86 return NULL;
87 }
88
89 size_t pos = 0; /* Post-incremented in each use. */
90 PyList_SET_ITEM(filters, pos++,
91 create_filter(PyExc_DeprecationWarning, &PyId_default, "__main__"));
92 PyList_SET_ITEM(filters, pos++,
93 create_filter(PyExc_DeprecationWarning, &PyId_ignore, NULL));
94 PyList_SET_ITEM(filters, pos++,
95 create_filter(PyExc_PendingDeprecationWarning, &PyId_ignore, NULL));
96 PyList_SET_ITEM(filters, pos++,
97 create_filter(PyExc_ImportWarning, &PyId_ignore, NULL));
98 PyList_SET_ITEM(filters, pos++,
99 create_filter(PyExc_ResourceWarning, &PyId_ignore, NULL));
100
101 for (size_t x = 0; x < pos; x++) {
102 if (PyList_GET_ITEM(filters, x) == NULL) {
103 Py_DECREF(filters);
104 return NULL;
105 }
106 }
107 return filters;
108#endif
109}
110
111/* Initialize the given warnings module state. */
112static int
113_Warnings_InitState(WarningsState *st)
114{
115 if (st->filters == NULL) {
116 st->filters = init_filters();
117 if (st->filters == NULL) {
118 goto error;
119 }
120 }
121
122 if (st->once_registry == NULL) {
123 st->once_registry = PyDict_New();
124 if (st->once_registry == NULL) {
125 goto error;
126 }
127 }
128
129 if (st->default_action == NULL) {
130 st->default_action = PyUnicode_FromString("default");
131 if (st->default_action == NULL) {
132 goto error;
133 }
134 }
135
136 st->filters_version = 0;
137
138 return 0;
139
140error:
141 _Warnings_ClearState(st);
142 return -1;
143}
144
145
146/*************************************************************************/
147
Christian Heimes33fe8092008-04-13 13:53:33 +0000148static int
149check_matched(PyObject *obj, PyObject *arg)
150{
151 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200152 _Py_IDENTIFIER(match);
Christian Heimes33fe8092008-04-13 13:53:33 +0000153 int rc;
154
Nick Coghlan9b997472018-01-08 12:45:02 +1000155 /* A 'None' filter always matches */
Christian Heimes33fe8092008-04-13 13:53:33 +0000156 if (obj == Py_None)
157 return 1;
Nick Coghlan9b997472018-01-08 12:45:02 +1000158
159 /* An internal plain text default filter must match exactly */
160 if (PyUnicode_CheckExact(obj)) {
161 int cmp_result = PyUnicode_Compare(obj, arg);
162 if (cmp_result == -1 && PyErr_Occurred()) {
163 return -1;
164 }
165 return !cmp_result;
166 }
167
168 /* Otherwise assume a regex filter and call its match() method */
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200169 result = _PyObject_CallMethodIdOneArg(obj, &PyId_match, arg);
Christian Heimes33fe8092008-04-13 13:53:33 +0000170 if (result == NULL)
171 return -1;
172
173 rc = PyObject_IsTrue(result);
174 Py_DECREF(result);
175 return rc;
176}
177
178/*
179 Returns a new reference.
180 A NULL return value can mean false or an error.
181*/
182static PyObject *
Victor Stinner82656272017-11-22 23:51:42 +0100183get_warnings_attr(_Py_Identifier *attr_id, int try_import)
Christian Heimes33fe8092008-04-13 13:53:33 +0000184{
Victor Stinner82656272017-11-22 23:51:42 +0100185 PyObject *warnings_str;
Victor Stinnere98445a2016-03-23 00:54:48 +0100186 PyObject *warnings_module, *obj;
Victor Stinner82656272017-11-22 23:51:42 +0100187 _Py_IDENTIFIER(warnings);
Christian Heimes33fe8092008-04-13 13:53:33 +0000188
Victor Stinner82656272017-11-22 23:51:42 +0100189 warnings_str = _PyUnicode_FromId(&PyId_warnings);
Christian Heimes33fe8092008-04-13 13:53:33 +0000190 if (warnings_str == NULL) {
Victor Stinner82656272017-11-22 23:51:42 +0100191 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000192 }
193
Victor Stinnere98445a2016-03-23 00:54:48 +0100194 /* don't try to import after the start of the Python finallization */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600195 if (try_import && !_Py_IsFinalizing()) {
Victor Stinnere98445a2016-03-23 00:54:48 +0100196 warnings_module = PyImport_Import(warnings_str);
197 if (warnings_module == NULL) {
198 /* Fallback to the C implementation if we cannot get
199 the Python implementation */
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200200 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
201 PyErr_Clear();
202 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000203 return NULL;
Victor Stinnere98445a2016-03-23 00:54:48 +0100204 }
205 }
206 else {
Nathaniel J. Smithdba976b2018-01-26 11:28:31 -0800207 /* if we're so late into Python finalization that the module dict is
208 gone, then we can't even use PyImport_GetModule without triggering
209 an interpreter abort.
210 */
Victor Stinnercaba55b2018-08-03 15:33:52 +0200211 if (!_PyInterpreterState_GET_UNSAFE()->modules) {
Nathaniel J. Smithdba976b2018-01-26 11:28:31 -0800212 return NULL;
213 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600214 warnings_module = PyImport_GetModule(warnings_str);
Victor Stinner023654f2016-03-23 17:48:22 +0100215 if (warnings_module == NULL)
216 return NULL;
Victor Stinnere98445a2016-03-23 00:54:48 +0100217 }
218
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200219 (void)_PyObject_LookupAttrId(warnings_module, attr_id, &obj);
Victor Stinnere98445a2016-03-23 00:54:48 +0100220 Py_DECREF(warnings_module);
221 return obj;
Christian Heimes33fe8092008-04-13 13:53:33 +0000222}
223
224
Neal Norwitz32dde222008-04-15 06:43:13 +0000225static PyObject *
Eric Snow86ea5812019-05-10 13:29:55 -0400226get_once_registry(WarningsState *st)
Christian Heimes33fe8092008-04-13 13:53:33 +0000227{
228 PyObject *registry;
Victor Stinner82656272017-11-22 23:51:42 +0100229 _Py_IDENTIFIER(onceregistry);
Christian Heimes33fe8092008-04-13 13:53:33 +0000230
Victor Stinner82656272017-11-22 23:51:42 +0100231 registry = get_warnings_attr(&PyId_onceregistry, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000232 if (registry == NULL) {
233 if (PyErr_Occurred())
234 return NULL;
Eric Snow86ea5812019-05-10 13:29:55 -0400235 assert(st->once_registry);
236 return st->once_registry;
Christian Heimes33fe8092008-04-13 13:53:33 +0000237 }
Oren Milman252033d2017-09-11 09:28:39 +0300238 if (!PyDict_Check(registry)) {
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200239 PyErr_Format(PyExc_TypeError,
240 MODULE_NAME ".onceregistry must be a dict, "
241 "not '%.200s'",
242 Py_TYPE(registry)->tp_name);
Oren Milman252033d2017-09-11 09:28:39 +0300243 Py_DECREF(registry);
244 return NULL;
245 }
Eric Snow86ea5812019-05-10 13:29:55 -0400246 Py_SETREF(st->once_registry, registry);
Christian Heimes33fe8092008-04-13 13:53:33 +0000247 return registry;
248}
249
250
Brett Cannon0759dd62009-04-01 18:13:07 +0000251static PyObject *
Eric Snow86ea5812019-05-10 13:29:55 -0400252get_default_action(WarningsState *st)
Brett Cannon0759dd62009-04-01 18:13:07 +0000253{
254 PyObject *default_action;
Victor Stinner82656272017-11-22 23:51:42 +0100255 _Py_IDENTIFIER(defaultaction);
Brett Cannon0759dd62009-04-01 18:13:07 +0000256
Victor Stinner82656272017-11-22 23:51:42 +0100257 default_action = get_warnings_attr(&PyId_defaultaction, 0);
Brett Cannon0759dd62009-04-01 18:13:07 +0000258 if (default_action == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 if (PyErr_Occurred()) {
260 return NULL;
261 }
Eric Snow86ea5812019-05-10 13:29:55 -0400262 assert(st->default_action);
263 return st->default_action;
Brett Cannon0759dd62009-04-01 18:13:07 +0000264 }
Oren Milman9d984fd2017-09-12 00:18:09 +0300265 if (!PyUnicode_Check(default_action)) {
266 PyErr_Format(PyExc_TypeError,
267 MODULE_NAME ".defaultaction must be a string, "
268 "not '%.200s'",
269 Py_TYPE(default_action)->tp_name);
270 Py_DECREF(default_action);
271 return NULL;
272 }
Eric Snow86ea5812019-05-10 13:29:55 -0400273 Py_SETREF(st->default_action, default_action);
Brett Cannon0759dd62009-04-01 18:13:07 +0000274 return default_action;
275}
276
277
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400278/* The item is a new reference. */
Victor Stinnera4c704b2013-10-29 23:43:41 +0100279static PyObject*
Christian Heimes33fe8092008-04-13 13:53:33 +0000280get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
281 PyObject *module, PyObject **item)
282{
Brett Cannon0759dd62009-04-01 18:13:07 +0000283 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000284 Py_ssize_t i;
285 PyObject *warnings_filters;
Victor Stinner82656272017-11-22 23:51:42 +0100286 _Py_IDENTIFIER(filters);
Eric Snow86ea5812019-05-10 13:29:55 -0400287 WarningsState *st = _Warnings_GetState();
288 if (st == NULL) {
289 return NULL;
290 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000291
Victor Stinner82656272017-11-22 23:51:42 +0100292 warnings_filters = get_warnings_attr(&PyId_filters, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000293 if (warnings_filters == NULL) {
294 if (PyErr_Occurred())
295 return NULL;
296 }
297 else {
Eric Snow86ea5812019-05-10 13:29:55 -0400298 Py_SETREF(st->filters, warnings_filters);
Christian Heimes33fe8092008-04-13 13:53:33 +0000299 }
300
Eric Snow86ea5812019-05-10 13:29:55 -0400301 PyObject *filters = st->filters;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600302 if (filters == NULL || !PyList_Check(filters)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000303 PyErr_SetString(PyExc_ValueError,
304 MODULE_NAME ".filters must be a list");
305 return NULL;
306 }
307
Eric Snow86ea5812019-05-10 13:29:55 -0400308 /* WarningsState.filters could change while we are iterating over it. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600309 for (i = 0; i < PyList_GET_SIZE(filters); i++) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000310 PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj;
311 Py_ssize_t ln;
312 int is_subclass, good_msg, good_mod;
313
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600314 tmp_item = PyList_GET_ITEM(filters, i);
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400315 if (!PyTuple_Check(tmp_item) || PyTuple_GET_SIZE(tmp_item) != 5) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000316 PyErr_Format(PyExc_ValueError,
317 MODULE_NAME ".filters item %zd isn't a 5-tuple", i);
318 return NULL;
319 }
320
321 /* Python code: action, msg, cat, mod, ln = item */
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400322 Py_INCREF(tmp_item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000323 action = PyTuple_GET_ITEM(tmp_item, 0);
324 msg = PyTuple_GET_ITEM(tmp_item, 1);
325 cat = PyTuple_GET_ITEM(tmp_item, 2);
326 mod = PyTuple_GET_ITEM(tmp_item, 3);
327 ln_obj = PyTuple_GET_ITEM(tmp_item, 4);
328
Oren Milman9d984fd2017-09-12 00:18:09 +0300329 if (!PyUnicode_Check(action)) {
330 PyErr_Format(PyExc_TypeError,
331 "action must be a string, not '%.200s'",
332 Py_TYPE(action)->tp_name);
333 Py_DECREF(tmp_item);
334 return NULL;
335 }
336
Christian Heimes33fe8092008-04-13 13:53:33 +0000337 good_msg = check_matched(msg, text);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400338 if (good_msg == -1) {
339 Py_DECREF(tmp_item);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100340 return NULL;
Benjamin Peterson8c598162015-05-03 11:28:46 -0400341 }
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100342
Christian Heimes33fe8092008-04-13 13:53:33 +0000343 good_mod = check_matched(mod, module);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400344 if (good_mod == -1) {
345 Py_DECREF(tmp_item);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100346 return NULL;
Benjamin Peterson8c598162015-05-03 11:28:46 -0400347 }
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100348
Christian Heimes33fe8092008-04-13 13:53:33 +0000349 is_subclass = PyObject_IsSubclass(category, cat);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400350 if (is_subclass == -1) {
351 Py_DECREF(tmp_item);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100352 return NULL;
Benjamin Peterson8c598162015-05-03 11:28:46 -0400353 }
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100354
Christian Heimes33fe8092008-04-13 13:53:33 +0000355 ln = PyLong_AsSsize_t(ln_obj);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400356 if (ln == -1 && PyErr_Occurred()) {
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400357 Py_DECREF(tmp_item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000358 return NULL;
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400359 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000360
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400361 if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln)) {
362 *item = tmp_item;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100363 return action;
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400364 }
365
366 Py_DECREF(tmp_item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000367 }
368
Eric Snow86ea5812019-05-10 13:29:55 -0400369 action = get_default_action(st);
Brett Cannon0759dd62009-04-01 18:13:07 +0000370 if (action != NULL) {
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400371 Py_INCREF(Py_None);
372 *item = Py_None;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100373 return action;
Brett Cannon0759dd62009-04-01 18:13:07 +0000374 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000375
Christian Heimes33fe8092008-04-13 13:53:33 +0000376 return NULL;
377}
378
Brett Cannon0759dd62009-04-01 18:13:07 +0000379
Christian Heimes33fe8092008-04-13 13:53:33 +0000380static int
381already_warned(PyObject *registry, PyObject *key, int should_set)
382{
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200383 PyObject *version_obj, *already_warned;
384 _Py_IDENTIFIER(version);
Christian Heimes33fe8092008-04-13 13:53:33 +0000385
386 if (key == NULL)
387 return -1;
388
Eric Snow86ea5812019-05-10 13:29:55 -0400389 WarningsState *st = _Warnings_GetState();
390 if (st == NULL) {
391 return -1;
392 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200393 version_obj = _PyDict_GetItemIdWithError(registry, &PyId_version);
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200394 if (version_obj == NULL
395 || !PyLong_CheckExact(version_obj)
Eric Snow86ea5812019-05-10 13:29:55 -0400396 || PyLong_AsLong(version_obj) != st->filters_version)
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +0200397 {
398 if (PyErr_Occurred()) {
399 return -1;
400 }
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200401 PyDict_Clear(registry);
Eric Snow86ea5812019-05-10 13:29:55 -0400402 version_obj = PyLong_FromLong(st->filters_version);
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200403 if (version_obj == NULL)
404 return -1;
405 if (_PyDict_SetItemId(registry, &PyId_version, version_obj) < 0) {
406 Py_DECREF(version_obj);
407 return -1;
408 }
409 Py_DECREF(version_obj);
410 }
411 else {
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200412 already_warned = PyDict_GetItemWithError(registry, key);
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200413 if (already_warned != NULL) {
414 int rc = PyObject_IsTrue(already_warned);
415 if (rc != 0)
416 return rc;
417 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200418 else if (PyErr_Occurred()) {
419 return -1;
420 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000421 }
422
423 /* This warning wasn't found in the registry, set it. */
424 if (should_set)
425 return PyDict_SetItem(registry, key, Py_True);
426 return 0;
427}
428
429/* New reference. */
430static PyObject *
431normalize_module(PyObject *filename)
432{
433 PyObject *module;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100434 int kind;
435 void *data;
Christian Heimes33fe8092008-04-13 13:53:33 +0000436 Py_ssize_t len;
437
Victor Stinner9e30aa52011-11-21 02:49:52 +0100438 len = PyUnicode_GetLength(filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000439 if (len < 0)
440 return NULL;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100441
442 if (len == 0)
443 return PyUnicode_FromString("<unknown>");
444
445 kind = PyUnicode_KIND(filename);
446 data = PyUnicode_DATA(filename);
447
448 /* if filename.endswith(".py"): */
Christian Heimes33fe8092008-04-13 13:53:33 +0000449 if (len >= 3 &&
Victor Stinnera4c704b2013-10-29 23:43:41 +0100450 PyUnicode_READ(kind, data, len-3) == '.' &&
451 PyUnicode_READ(kind, data, len-2) == 'p' &&
452 PyUnicode_READ(kind, data, len-1) == 'y')
453 {
Victor Stinner9e30aa52011-11-21 02:49:52 +0100454 module = PyUnicode_Substring(filename, 0, len-3);
Christian Heimes33fe8092008-04-13 13:53:33 +0000455 }
456 else {
457 module = filename;
458 Py_INCREF(module);
459 }
460 return module;
461}
462
463static int
464update_registry(PyObject *registry, PyObject *text, PyObject *category,
465 int add_zero)
466{
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300467 PyObject *altkey;
Christian Heimes33fe8092008-04-13 13:53:33 +0000468 int rc;
469
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300470 if (add_zero)
471 altkey = PyTuple_Pack(3, text, category, _PyLong_Zero);
Christian Heimes33fe8092008-04-13 13:53:33 +0000472 else
473 altkey = PyTuple_Pack(2, text, category);
474
475 rc = already_warned(registry, altkey, 1);
Christian Heimes33fe8092008-04-13 13:53:33 +0000476 Py_XDECREF(altkey);
477 return rc;
478}
479
480static void
Victor Stinner914cde82016-03-19 01:03:51 +0100481show_warning(PyObject *filename, int lineno, PyObject *text,
482 PyObject *category, PyObject *sourceline)
Christian Heimes33fe8092008-04-13 13:53:33 +0000483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 PyObject *f_stderr;
485 PyObject *name;
Christian Heimes33fe8092008-04-13 13:53:33 +0000486 char lineno_str[128];
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200487 _Py_IDENTIFIER(__name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000488
489 PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);
490
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200491 name = _PyObject_GetAttrId(category, &PyId___name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000492 if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */
Victor Stinnerae233ea2013-10-31 14:51:38 +0100493 goto error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000494
Victor Stinnerbd303c12013-11-07 23:07:29 +0100495 f_stderr = _PySys_GetObjectId(&PyId_stderr);
Christian Heimes33fe8092008-04-13 13:53:33 +0000496 if (f_stderr == NULL) {
497 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnerae233ea2013-10-31 14:51:38 +0100498 goto error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000499 }
500
501 /* Print "filename:lineno: category: text\n" */
Victor Stinnerae233ea2013-10-31 14:51:38 +0100502 if (PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW) < 0)
503 goto error;
504 if (PyFile_WriteString(lineno_str, f_stderr) < 0)
505 goto error;
506 if (PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW) < 0)
507 goto error;
508 if (PyFile_WriteString(": ", f_stderr) < 0)
509 goto error;
510 if (PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW) < 0)
511 goto error;
512 if (PyFile_WriteString("\n", f_stderr) < 0)
513 goto error;
514 Py_CLEAR(name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000515
516 /* Print " source_line\n" */
Christian Heimes33fe8092008-04-13 13:53:33 +0000517 if (sourceline) {
Victor Stinnera4c704b2013-10-29 23:43:41 +0100518 int kind;
519 void *data;
520 Py_ssize_t i, len;
521 Py_UCS4 ch;
522 PyObject *truncated;
Christian Heimes33fe8092008-04-13 13:53:33 +0000523
Victor Stinnera4c704b2013-10-29 23:43:41 +0100524 if (PyUnicode_READY(sourceline) < 1)
525 goto error;
526
527 kind = PyUnicode_KIND(sourceline);
528 data = PyUnicode_DATA(sourceline);
529 len = PyUnicode_GET_LENGTH(sourceline);
530 for (i=0; i<len; i++) {
531 ch = PyUnicode_READ(kind, data, i);
532 if (ch != ' ' && ch != '\t' && ch != '\014')
533 break;
534 }
535
536 truncated = PyUnicode_Substring(sourceline, i, len);
537 if (truncated == NULL)
538 goto error;
539
540 PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW);
541 Py_DECREF(truncated);
Christian Heimes33fe8092008-04-13 13:53:33 +0000542 PyFile_WriteString("\n", f_stderr);
543 }
Victor Stinner78e2c982013-07-16 01:54:37 +0200544 else {
545 _Py_DisplaySourceLine(f_stderr, filename, lineno, 2);
546 }
Victor Stinnera4c704b2013-10-29 23:43:41 +0100547
548error:
Victor Stinnerae233ea2013-10-31 14:51:38 +0100549 Py_XDECREF(name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000550 PyErr_Clear();
551}
552
Victor Stinner1231a462016-03-19 00:47:17 +0100553static int
554call_show_warning(PyObject *category, PyObject *text, PyObject *message,
555 PyObject *filename, int lineno, PyObject *lineno_obj,
Victor Stinner914cde82016-03-19 01:03:51 +0100556 PyObject *sourceline, PyObject *source)
Victor Stinner1231a462016-03-19 00:47:17 +0100557{
558 PyObject *show_fn, *msg, *res, *warnmsg_cls = NULL;
Victor Stinner82656272017-11-22 23:51:42 +0100559 _Py_IDENTIFIER(_showwarnmsg);
560 _Py_IDENTIFIER(WarningMessage);
Victor Stinner1231a462016-03-19 00:47:17 +0100561
Victor Stinnere98445a2016-03-23 00:54:48 +0100562 /* If the source parameter is set, try to get the Python implementation.
563 The Python implementation is able to log the traceback where the source
luzpaza5293b42017-11-05 07:37:50 -0600564 was allocated, whereas the C implementation doesn't. */
Victor Stinner82656272017-11-22 23:51:42 +0100565 show_fn = get_warnings_attr(&PyId__showwarnmsg, source != NULL);
Victor Stinner1231a462016-03-19 00:47:17 +0100566 if (show_fn == NULL) {
567 if (PyErr_Occurred())
568 return -1;
569 show_warning(filename, lineno, text, category, sourceline);
570 return 0;
571 }
572
573 if (!PyCallable_Check(show_fn)) {
574 PyErr_SetString(PyExc_TypeError,
575 "warnings._showwarnmsg() must be set to a callable");
576 goto error;
577 }
578
Victor Stinner82656272017-11-22 23:51:42 +0100579 warnmsg_cls = get_warnings_attr(&PyId_WarningMessage, 0);
Victor Stinner1231a462016-03-19 00:47:17 +0100580 if (warnmsg_cls == NULL) {
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200581 if (!PyErr_Occurred()) {
582 PyErr_SetString(PyExc_RuntimeError,
583 "unable to get warnings.WarningMessage");
584 }
Victor Stinner1231a462016-03-19 00:47:17 +0100585 goto error;
586 }
587
588 msg = PyObject_CallFunctionObjArgs(warnmsg_cls, message, category,
Victor Stinner914cde82016-03-19 01:03:51 +0100589 filename, lineno_obj, Py_None, Py_None, source,
Victor Stinner1231a462016-03-19 00:47:17 +0100590 NULL);
591 Py_DECREF(warnmsg_cls);
592 if (msg == NULL)
593 goto error;
594
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200595 res = _PyObject_CallOneArg(show_fn, msg);
Victor Stinner1231a462016-03-19 00:47:17 +0100596 Py_DECREF(show_fn);
597 Py_DECREF(msg);
598
599 if (res == NULL)
600 return -1;
601
602 Py_DECREF(res);
603 return 0;
604
605error:
606 Py_XDECREF(show_fn);
607 return -1;
608}
609
Christian Heimes33fe8092008-04-13 13:53:33 +0000610static PyObject *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611warn_explicit(PyObject *category, PyObject *message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000612 PyObject *filename, int lineno,
Victor Stinner914cde82016-03-19 01:03:51 +0100613 PyObject *module, PyObject *registry, PyObject *sourceline,
614 PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000615{
616 PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL;
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400617 PyObject *item = NULL;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100618 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000619 int rc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620
Victor Stinnerdcdd05b2013-11-01 00:55:30 +0100621 /* module can be None if a warning is emitted late during Python shutdown.
622 In this case, the Python warnings module was probably unloaded, filters
623 are no more available to choose as action. It is safer to ignore the
624 warning and do nothing. */
625 if (module == Py_None)
626 Py_RETURN_NONE;
627
Brett Cannondb734912008-06-27 00:52:15 +0000628 if (registry && !PyDict_Check(registry) && (registry != Py_None)) {
Oren Milman252033d2017-09-11 09:28:39 +0300629 PyErr_SetString(PyExc_TypeError, "'registry' must be a dict or None");
Brett Cannondb734912008-06-27 00:52:15 +0000630 return NULL;
631 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000632
633 /* Normalize module. */
634 if (module == NULL) {
635 module = normalize_module(filename);
636 if (module == NULL)
637 return NULL;
638 }
639 else
640 Py_INCREF(module);
641
642 /* Normalize message. */
643 Py_INCREF(message); /* DECREF'ed in cleanup. */
644 rc = PyObject_IsInstance(message, PyExc_Warning);
645 if (rc == -1) {
646 goto cleanup;
647 }
648 if (rc == 1) {
649 text = PyObject_Str(message);
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000650 if (text == NULL)
651 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000652 category = (PyObject*)message->ob_type;
653 }
654 else {
655 text = message;
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200656 message = _PyObject_CallOneArg(category, message);
Brett Cannondb734912008-06-27 00:52:15 +0000657 if (message == NULL)
658 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000659 }
660
661 lineno_obj = PyLong_FromLong(lineno);
662 if (lineno_obj == NULL)
663 goto cleanup;
664
Victor Stinner22f18752016-12-09 18:08:18 +0100665 if (source == Py_None) {
666 source = NULL;
667 }
668
Christian Heimes33fe8092008-04-13 13:53:33 +0000669 /* Create key. */
670 key = PyTuple_Pack(3, text, category, lineno_obj);
671 if (key == NULL)
672 goto cleanup;
673
Brett Cannondb734912008-06-27 00:52:15 +0000674 if ((registry != NULL) && (registry != Py_None)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000675 rc = already_warned(registry, key, 0);
676 if (rc == -1)
677 goto cleanup;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 else if (rc == 1)
Christian Heimes33fe8092008-04-13 13:53:33 +0000679 goto return_none;
680 /* Else this warning hasn't been generated before. */
681 }
682
683 action = get_filter(category, text, lineno, module, &item);
684 if (action == NULL)
685 goto cleanup;
686
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200687 if (_PyUnicode_EqualToASCIIString(action, "error")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000688 PyErr_SetObject(category, message);
689 goto cleanup;
690 }
691
Victor Stinnerc9758782017-11-27 16:57:07 +0100692 if (_PyUnicode_EqualToASCIIString(action, "ignore")) {
693 goto return_none;
694 }
695
Christian Heimes33fe8092008-04-13 13:53:33 +0000696 /* Store in the registry that we've been here, *except* when the action
697 is "always". */
698 rc = 0;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200699 if (!_PyUnicode_EqualToASCIIString(action, "always")) {
Brett Cannondb734912008-06-27 00:52:15 +0000700 if (registry != NULL && registry != Py_None &&
Victor Stinnerc9758782017-11-27 16:57:07 +0100701 PyDict_SetItem(registry, key, Py_True) < 0)
702 {
Christian Heimes33fe8092008-04-13 13:53:33 +0000703 goto cleanup;
Victor Stinnerc9758782017-11-27 16:57:07 +0100704 }
705
706 if (_PyUnicode_EqualToASCIIString(action, "once")) {
Brett Cannondb734912008-06-27 00:52:15 +0000707 if (registry == NULL || registry == Py_None) {
Eric Snow86ea5812019-05-10 13:29:55 -0400708 WarningsState *st = _Warnings_GetState();
709 if (st == NULL) {
710 goto cleanup;
711 }
712 registry = get_once_registry(st);
Christian Heimes33fe8092008-04-13 13:53:33 +0000713 if (registry == NULL)
714 goto cleanup;
715 }
Eric Snow86ea5812019-05-10 13:29:55 -0400716 /* WarningsState.once_registry[(text, category)] = 1 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000718 }
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200719 else if (_PyUnicode_EqualToASCIIString(action, "module")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000720 /* registry[(text, category, 0)] = 1 */
Brett Cannondb734912008-06-27 00:52:15 +0000721 if (registry != NULL && registry != Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000723 }
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200724 else if (!_PyUnicode_EqualToASCIIString(action, "default")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000725 PyErr_Format(PyExc_RuntimeError,
Victor Stinnera4c704b2013-10-29 23:43:41 +0100726 "Unrecognized action (%R) in warnings.filters:\n %R",
727 action, item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000728 goto cleanup;
729 }
730 }
731
Christian Heimes1a8501c2008-10-02 19:56:01 +0000732 if (rc == 1) /* Already warned for this module. */
Christian Heimes33fe8092008-04-13 13:53:33 +0000733 goto return_none;
734 if (rc == 0) {
Victor Stinner1231a462016-03-19 00:47:17 +0100735 if (call_show_warning(category, text, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +0100736 lineno_obj, sourceline, source) < 0)
Victor Stinner1231a462016-03-19 00:47:17 +0100737 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000738 }
739 else /* if (rc == -1) */
740 goto cleanup;
741
742 return_none:
743 result = Py_None;
744 Py_INCREF(result);
745
746 cleanup:
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400747 Py_XDECREF(item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000748 Py_XDECREF(key);
749 Py_XDECREF(text);
750 Py_XDECREF(lineno_obj);
751 Py_DECREF(module);
Brett Cannondb734912008-06-27 00:52:15 +0000752 Py_XDECREF(message);
Christian Heimes33fe8092008-04-13 13:53:33 +0000753 return result; /* Py_None or NULL. */
754}
755
Larry Hastings714e4932015-09-06 00:39:37 -0700756static int
757is_internal_frame(PyFrameObject *frame)
758{
759 static PyObject *importlib_string = NULL;
760 static PyObject *bootstrap_string = NULL;
761 PyObject *filename;
762 int contains;
763
764 if (importlib_string == NULL) {
765 importlib_string = PyUnicode_FromString("importlib");
766 if (importlib_string == NULL) {
767 return 0;
768 }
769
770 bootstrap_string = PyUnicode_FromString("_bootstrap");
771 if (bootstrap_string == NULL) {
772 Py_DECREF(importlib_string);
773 return 0;
774 }
775 Py_INCREF(importlib_string);
776 Py_INCREF(bootstrap_string);
777 }
778
779 if (frame == NULL || frame->f_code == NULL ||
780 frame->f_code->co_filename == NULL) {
781 return 0;
782 }
783 filename = frame->f_code->co_filename;
784 if (!PyUnicode_Check(filename)) {
785 return 0;
786 }
787 contains = PyUnicode_Contains(filename, importlib_string);
788 if (contains < 0) {
789 return 0;
790 }
791 else if (contains > 0) {
792 contains = PyUnicode_Contains(filename, bootstrap_string);
793 if (contains < 0) {
794 return 0;
795 }
796 else if (contains > 0) {
797 return 1;
798 }
799 }
800
801 return 0;
802}
803
804static PyFrameObject *
805next_external_frame(PyFrameObject *frame)
806{
807 do {
808 frame = frame->f_back;
809 } while (frame != NULL && is_internal_frame(frame));
810
811 return frame;
812}
813
Christian Heimes33fe8092008-04-13 13:53:33 +0000814/* filename, module, and registry are new refs, globals is borrowed */
815/* Returns 0 on error (no new refs), 1 on success */
816static int
817setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
818 PyObject **module, PyObject **registry)
819{
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200820 _Py_IDENTIFIER(__warningregistry__);
821 _Py_IDENTIFIER(__name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000822 PyObject *globals;
823
Thomas Kluyver11a89662018-06-08 21:28:37 +0200824 /* Setup globals, filename and lineno. */
Victor Stinner50b48572018-11-01 01:51:40 +0100825 PyFrameObject *f = _PyThreadState_GET()->frame;
Larry Hastings714e4932015-09-06 00:39:37 -0700826 // Stack level comparisons to Python code is off by one as there is no
827 // warnings-related stack level to avoid.
828 if (stack_level <= 0 || is_internal_frame(f)) {
829 while (--stack_level > 0 && f != NULL) {
830 f = f->f_back;
831 }
832 }
833 else {
834 while (--stack_level > 0 && f != NULL) {
835 f = next_external_frame(f);
836 }
837 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000838
839 if (f == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200840 globals = _PyInterpreterState_GET_UNSAFE()->sysdict;
Thomas Kluyver11a89662018-06-08 21:28:37 +0200841 *filename = PyUnicode_FromString("sys");
Christian Heimes33fe8092008-04-13 13:53:33 +0000842 *lineno = 1;
843 }
844 else {
845 globals = f->f_globals;
Thomas Kluyver11a89662018-06-08 21:28:37 +0200846 *filename = f->f_code->co_filename;
847 Py_INCREF(*filename);
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000848 *lineno = PyFrame_GetLineNumber(f);
Christian Heimes33fe8092008-04-13 13:53:33 +0000849 }
850
851 *module = NULL;
852
853 /* Setup registry. */
854 assert(globals != NULL);
855 assert(PyDict_Check(globals));
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200856 *registry = _PyDict_GetItemIdWithError(globals, &PyId___warningregistry__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000857 if (*registry == NULL) {
858 int rc;
859
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200860 if (PyErr_Occurred()) {
861 return 0;
862 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000863 *registry = PyDict_New();
864 if (*registry == NULL)
865 return 0;
866
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200867 rc = _PyDict_SetItemId(globals, &PyId___warningregistry__, *registry);
Christian Heimes33fe8092008-04-13 13:53:33 +0000868 if (rc < 0)
869 goto handle_error;
870 }
871 else
872 Py_INCREF(*registry);
873
874 /* Setup module. */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200875 *module = _PyDict_GetItemIdWithError(globals, &PyId___name__);
Oren Milman5d3e8002017-09-24 21:28:42 +0300876 if (*module == Py_None || (*module != NULL && PyUnicode_Check(*module))) {
877 Py_INCREF(*module);
878 }
Serhiy Storchakaa24107b2019-02-25 17:59:46 +0200879 else if (PyErr_Occurred()) {
880 goto handle_error;
881 }
Oren Milman5d3e8002017-09-24 21:28:42 +0300882 else {
Christian Heimes33fe8092008-04-13 13:53:33 +0000883 *module = PyUnicode_FromString("<string>");
884 if (*module == NULL)
885 goto handle_error;
886 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000887
Christian Heimes33fe8092008-04-13 13:53:33 +0000888 return 1;
889
890 handle_error:
891 /* filename not XDECREF'ed here as there is no way to jump here with a
892 dangling reference. */
893 Py_XDECREF(*registry);
894 Py_XDECREF(*module);
895 return 0;
896}
897
898static PyObject *
899get_category(PyObject *message, PyObject *category)
900{
901 int rc;
902
903 /* Get category. */
904 rc = PyObject_IsInstance(message, PyExc_Warning);
905 if (rc == -1)
906 return NULL;
907
908 if (rc == 1)
909 category = (PyObject*)message->ob_type;
Berker Peksagd8089e02014-07-11 19:50:25 +0300910 else if (category == NULL || category == Py_None)
Christian Heimes33fe8092008-04-13 13:53:33 +0000911 category = PyExc_UserWarning;
912
913 /* Validate category. */
914 rc = PyObject_IsSubclass(category, PyExc_Warning);
Berker Peksagd8089e02014-07-11 19:50:25 +0300915 /* category is not a subclass of PyExc_Warning or
916 PyObject_IsSubclass raised an error */
917 if (rc == -1 || rc == 0) {
918 PyErr_Format(PyExc_TypeError,
919 "category must be a Warning subclass, not '%s'",
920 Py_TYPE(category)->tp_name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000921 return NULL;
922 }
923
924 return category;
925}
926
927static PyObject *
Victor Stinner914cde82016-03-19 01:03:51 +0100928do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level,
929 PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000930{
931 PyObject *filename, *module, *registry, *res;
932 int lineno;
933
934 if (!setup_context(stack_level, &filename, &lineno, &module, &registry))
935 return NULL;
936
Victor Stinnerdcdd05b2013-11-01 00:55:30 +0100937 res = warn_explicit(category, message, filename, lineno, module, registry,
Victor Stinner914cde82016-03-19 01:03:51 +0100938 NULL, source);
Christian Heimes33fe8092008-04-13 13:53:33 +0000939 Py_DECREF(filename);
940 Py_DECREF(registry);
941 Py_DECREF(module);
942 return res;
943}
944
Victor Stinner22f18752016-12-09 18:08:18 +0100945/*[clinic input]
946warn as warnings_warn
947
948 message: object
949 category: object = None
950 stacklevel: Py_ssize_t = 1
951 source: object = None
952
953Issue a warning, or maybe ignore it or raise an exception.
954[clinic start generated code]*/
955
Christian Heimes33fe8092008-04-13 13:53:33 +0000956static PyObject *
Victor Stinner22f18752016-12-09 18:08:18 +0100957warnings_warn_impl(PyObject *module, PyObject *message, PyObject *category,
958 Py_ssize_t stacklevel, PyObject *source)
959/*[clinic end generated code: output=31ed5ab7d8d760b2 input=bfdf5cf99f6c4edd]*/
Christian Heimes33fe8092008-04-13 13:53:33 +0000960{
Christian Heimes33fe8092008-04-13 13:53:33 +0000961 category = get_category(message, category);
962 if (category == NULL)
963 return NULL;
Victor Stinner22f18752016-12-09 18:08:18 +0100964 return do_warn(message, category, stacklevel, source);
Christian Heimes33fe8092008-04-13 13:53:33 +0000965}
966
967static PyObject *
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200968get_source_line(PyObject *module_globals, int lineno)
969{
970 _Py_IDENTIFIER(get_source);
971 _Py_IDENTIFIER(__loader__);
972 _Py_IDENTIFIER(__name__);
973 PyObject *loader;
974 PyObject *module_name;
975 PyObject *get_source;
976 PyObject *source;
977 PyObject *source_list;
978 PyObject *source_line;
979
980 /* Check/get the requisite pieces needed for the loader. */
981 loader = _PyDict_GetItemIdWithError(module_globals, &PyId___loader__);
982 if (loader == NULL) {
983 return NULL;
984 }
985 Py_INCREF(loader);
986 module_name = _PyDict_GetItemIdWithError(module_globals, &PyId___name__);
987 if (!module_name) {
988 Py_DECREF(loader);
989 return NULL;
990 }
991 Py_INCREF(module_name);
992
993 /* Make sure the loader implements the optional get_source() method. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200994 (void)_PyObject_LookupAttrId(loader, &PyId_get_source, &get_source);
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200995 Py_DECREF(loader);
996 if (!get_source) {
997 Py_DECREF(module_name);
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200998 return NULL;
999 }
1000 /* Call get_source() to get the source code. */
Jeroen Demeyer196a5302019-07-04 12:31:34 +02001001 source = _PyObject_CallOneArg(get_source, module_name);
Serhiy Storchakad4f84802017-11-11 15:19:47 +02001002 Py_DECREF(get_source);
1003 Py_DECREF(module_name);
1004 if (!source) {
1005 return NULL;
1006 }
1007 if (source == Py_None) {
1008 Py_DECREF(source);
1009 return NULL;
1010 }
1011
1012 /* Split the source into lines. */
1013 source_list = PyUnicode_Splitlines(source, 0);
1014 Py_DECREF(source);
1015 if (!source_list) {
1016 return NULL;
1017 }
1018
1019 /* Get the source line. */
1020 source_line = PyList_GetItem(source_list, lineno-1);
1021 Py_XINCREF(source_line);
1022 Py_DECREF(source_list);
1023 return source_line;
1024}
1025
1026static PyObject *
Christian Heimes33fe8092008-04-13 13:53:33 +00001027warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
1028{
1029 static char *kwd_list[] = {"message", "category", "filename", "lineno",
Victor Stinner914cde82016-03-19 01:03:51 +01001030 "module", "registry", "module_globals",
1031 "source", 0};
Christian Heimes33fe8092008-04-13 13:53:33 +00001032 PyObject *message;
1033 PyObject *category;
1034 PyObject *filename;
1035 int lineno;
1036 PyObject *module = NULL;
1037 PyObject *registry = NULL;
1038 PyObject *module_globals = NULL;
Victor Stinner914cde82016-03-19 01:03:51 +01001039 PyObject *sourceobj = NULL;
Serhiy Storchakad4f84802017-11-11 15:19:47 +02001040 PyObject *source_line = NULL;
1041 PyObject *returned;
Christian Heimes33fe8092008-04-13 13:53:33 +00001042
Victor Stinner914cde82016-03-19 01:03:51 +01001043 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOUi|OOOO:warn_explicit",
Christian Heimes33fe8092008-04-13 13:53:33 +00001044 kwd_list, &message, &category, &filename, &lineno, &module,
Victor Stinner914cde82016-03-19 01:03:51 +01001045 &registry, &module_globals, &sourceobj))
Christian Heimes33fe8092008-04-13 13:53:33 +00001046 return NULL;
1047
Victor Stinnerb0565622018-05-15 20:42:12 +02001048 if (module_globals && module_globals != Py_None) {
1049 if (!PyDict_Check(module_globals)) {
1050 PyErr_Format(PyExc_TypeError,
1051 "module_globals must be a dict, not '%.200s'",
1052 Py_TYPE(module_globals)->tp_name);
1053 return NULL;
1054 }
1055
Serhiy Storchakad4f84802017-11-11 15:19:47 +02001056 source_line = get_source_line(module_globals, lineno);
1057 if (source_line == NULL && PyErr_Occurred()) {
Christian Heimes33fe8092008-04-13 13:53:33 +00001058 return NULL;
1059 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001060 }
Serhiy Storchakad4f84802017-11-11 15:19:47 +02001061 returned = warn_explicit(category, message, filename, lineno, module,
1062 registry, source_line, sourceobj);
1063 Py_XDECREF(source_line);
1064 return returned;
Christian Heimes33fe8092008-04-13 13:53:33 +00001065}
1066
Antoine Pitroucb0a0062014-09-18 02:40:46 +02001067static PyObject *
1068warnings_filters_mutated(PyObject *self, PyObject *args)
1069{
Eric Snow86ea5812019-05-10 13:29:55 -04001070 WarningsState *st = _Warnings_GetState();
1071 if (st == NULL) {
1072 return NULL;
1073 }
1074 st->filters_version++;
Antoine Pitroucb0a0062014-09-18 02:40:46 +02001075 Py_RETURN_NONE;
1076}
1077
Christian Heimes33fe8092008-04-13 13:53:33 +00001078
1079/* Function to issue a warning message; may raise an exception. */
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001080
1081static int
1082warn_unicode(PyObject *category, PyObject *message,
Victor Stinner914cde82016-03-19 01:03:51 +01001083 Py_ssize_t stack_level, PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +00001084{
1085 PyObject *res;
Christian Heimes33fe8092008-04-13 13:53:33 +00001086
1087 if (category == NULL)
1088 category = PyExc_RuntimeWarning;
1089
Victor Stinner914cde82016-03-19 01:03:51 +01001090 res = do_warn(message, category, stack_level, source);
Christian Heimes33fe8092008-04-13 13:53:33 +00001091 if (res == NULL)
1092 return -1;
1093 Py_DECREF(res);
1094
1095 return 0;
1096}
1097
Victor Stinner914cde82016-03-19 01:03:51 +01001098static int
1099_PyErr_WarnFormatV(PyObject *source,
1100 PyObject *category, Py_ssize_t stack_level,
1101 const char *format, va_list vargs)
1102{
1103 PyObject *message;
1104 int res;
1105
1106 message = PyUnicode_FromFormatV(format, vargs);
1107 if (message == NULL)
1108 return -1;
1109
1110 res = warn_unicode(category, message, stack_level, source);
1111 Py_DECREF(message);
1112 return res;
1113}
1114
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001115int
1116PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level,
1117 const char *format, ...)
1118{
Victor Stinner914cde82016-03-19 01:03:51 +01001119 int res;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001120 va_list vargs;
1121
1122#ifdef HAVE_STDARG_PROTOTYPES
1123 va_start(vargs, format);
1124#else
1125 va_start(vargs);
1126#endif
Victor Stinner914cde82016-03-19 01:03:51 +01001127 res = _PyErr_WarnFormatV(NULL, category, stack_level, format, vargs);
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001128 va_end(vargs);
Victor Stinner914cde82016-03-19 01:03:51 +01001129 return res;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001130}
1131
1132int
Victor Stinner914cde82016-03-19 01:03:51 +01001133PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level,
1134 const char *format, ...)
1135{
1136 int res;
1137 va_list vargs;
1138
1139#ifdef HAVE_STDARG_PROTOTYPES
1140 va_start(vargs, format);
1141#else
1142 va_start(vargs);
1143#endif
1144 res = _PyErr_WarnFormatV(source, PyExc_ResourceWarning,
1145 stack_level, format, vargs);
1146 va_end(vargs);
1147 return res;
1148}
1149
1150
1151int
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001152PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
1153{
1154 int ret;
1155 PyObject *message = PyUnicode_FromString(text);
1156 if (message == NULL)
1157 return -1;
Victor Stinner914cde82016-03-19 01:03:51 +01001158 ret = warn_unicode(category, message, stack_level, NULL);
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001159 Py_DECREF(message);
1160 return ret;
1161}
1162
Ezio Melotti42da6632011-03-15 05:18:48 +02001163/* PyErr_Warn is only for backwards compatibility and will be removed.
Christian Heimes33fe8092008-04-13 13:53:33 +00001164 Use PyErr_WarnEx instead. */
1165
1166#undef PyErr_Warn
1167
Benjamin Petersone5024512018-09-12 12:06:42 -07001168int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001169PyErr_Warn(PyObject *category, const char *text)
Christian Heimes33fe8092008-04-13 13:53:33 +00001170{
1171 return PyErr_WarnEx(category, text, 1);
1172}
1173
1174/* Warning with explicit origin */
1175int
Victor Stinner14e461d2013-08-26 22:28:21 +02001176PyErr_WarnExplicitObject(PyObject *category, PyObject *message,
1177 PyObject *filename, int lineno,
1178 PyObject *module, PyObject *registry)
1179{
1180 PyObject *res;
1181 if (category == NULL)
1182 category = PyExc_RuntimeWarning;
1183 res = warn_explicit(category, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +01001184 module, registry, NULL, NULL);
Victor Stinner14e461d2013-08-26 22:28:21 +02001185 if (res == NULL)
1186 return -1;
1187 Py_DECREF(res);
1188 return 0;
1189}
1190
1191int
Christian Heimes33fe8092008-04-13 13:53:33 +00001192PyErr_WarnExplicit(PyObject *category, const char *text,
1193 const char *filename_str, int lineno,
1194 const char *module_str, PyObject *registry)
1195{
Christian Heimes33fe8092008-04-13 13:53:33 +00001196 PyObject *message = PyUnicode_FromString(text);
Victor Stinnercb428f02010-12-27 20:10:36 +00001197 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
Christian Heimes33fe8092008-04-13 13:53:33 +00001198 PyObject *module = NULL;
1199 int ret = -1;
1200
1201 if (message == NULL || filename == NULL)
1202 goto exit;
1203 if (module_str != NULL) {
1204 module = PyUnicode_FromString(module_str);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001205 if (module == NULL)
1206 goto exit;
Christian Heimes33fe8092008-04-13 13:53:33 +00001207 }
1208
Victor Stinner14e461d2013-08-26 22:28:21 +02001209 ret = PyErr_WarnExplicitObject(category, message, filename, lineno,
1210 module, registry);
Christian Heimes33fe8092008-04-13 13:53:33 +00001211
1212 exit:
1213 Py_XDECREF(message);
1214 Py_XDECREF(module);
1215 Py_XDECREF(filename);
1216 return ret;
1217}
1218
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001219int
1220PyErr_WarnExplicitFormat(PyObject *category,
1221 const char *filename_str, int lineno,
1222 const char *module_str, PyObject *registry,
1223 const char *format, ...)
1224{
1225 PyObject *message;
1226 PyObject *module = NULL;
1227 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
1228 int ret = -1;
1229 va_list vargs;
1230
1231 if (filename == NULL)
1232 goto exit;
1233 if (module_str != NULL) {
1234 module = PyUnicode_FromString(module_str);
1235 if (module == NULL)
1236 goto exit;
1237 }
1238
1239#ifdef HAVE_STDARG_PROTOTYPES
1240 va_start(vargs, format);
1241#else
1242 va_start(vargs);
1243#endif
1244 message = PyUnicode_FromFormatV(format, vargs);
1245 if (message != NULL) {
1246 PyObject *res;
1247 res = warn_explicit(category, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +01001248 module, registry, NULL, NULL);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001249 Py_DECREF(message);
1250 if (res != NULL) {
1251 Py_DECREF(res);
1252 ret = 0;
1253 }
1254 }
1255 va_end(vargs);
1256exit:
1257 Py_XDECREF(module);
1258 Py_XDECREF(filename);
1259 return ret;
1260}
1261
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001262void
1263_PyErr_WarnUnawaitedCoroutine(PyObject *coro)
1264{
1265 /* First, we attempt to funnel the warning through
1266 warnings._warn_unawaited_coroutine.
1267
1268 This could raise an exception, due to:
1269 - a bug
1270 - some kind of shutdown-related brokenness
1271 - succeeding, but with an "error" warning filter installed, so the
1272 warning is converted into a RuntimeWarning exception
1273
1274 In the first two cases, we want to print the error (so we know what it
1275 is!), and then print a warning directly as a fallback. In the last
1276 case, we want to print the error (since it's the warning!), but *not*
1277 do a fallback. And after we print the error we can't check for what
1278 type of error it was (because PyErr_WriteUnraisable clears it), so we
1279 need a flag to keep track.
1280
1281 Since this is called from __del__ context, it's careful to never raise
1282 an exception.
1283 */
1284 _Py_IDENTIFIER(_warn_unawaited_coroutine);
1285 int warned = 0;
1286 PyObject *fn = get_warnings_attr(&PyId__warn_unawaited_coroutine, 1);
1287 if (fn) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +02001288 PyObject *res = _PyObject_CallOneArg(fn, coro);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001289 Py_DECREF(fn);
1290 if (res || PyErr_ExceptionMatches(PyExc_RuntimeWarning)) {
1291 warned = 1;
1292 }
1293 Py_XDECREF(res);
1294 }
1295
1296 if (PyErr_Occurred()) {
1297 PyErr_WriteUnraisable(coro);
1298 }
1299 if (!warned) {
Yury Selivanov35103342018-01-21 20:47:04 -05001300 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1301 "coroutine '%.50S' was never awaited",
1302 ((PyCoroObject *)coro)->cr_qualname) < 0)
1303 {
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001304 PyErr_WriteUnraisable(coro);
1305 }
1306 }
1307}
Christian Heimes33fe8092008-04-13 13:53:33 +00001308
Christian Heimes33fe8092008-04-13 13:53:33 +00001309PyDoc_STRVAR(warn_explicit_doc,
Hansraj Das5dfbb4d2019-10-08 14:26:07 +05301310"Low-level interface to warnings functionality.");
Christian Heimes33fe8092008-04-13 13:53:33 +00001311
1312static PyMethodDef warnings_functions[] = {
Victor Stinner22f18752016-12-09 18:08:18 +01001313 WARNINGS_WARN_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001314 {"warn_explicit", (PyCFunction)(void(*)(void))warnings_warn_explicit,
Christian Heimes33fe8092008-04-13 13:53:33 +00001315 METH_VARARGS | METH_KEYWORDS, warn_explicit_doc},
Antoine Pitroucb0a0062014-09-18 02:40:46 +02001316 {"_filters_mutated", (PyCFunction)warnings_filters_mutated, METH_NOARGS,
1317 NULL},
Christian Heimes1a8501c2008-10-02 19:56:01 +00001318 /* XXX(brett.cannon): add showwarning? */
1319 /* XXX(brett.cannon): Reasonable to add formatwarning? */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 {NULL, NULL} /* sentinel */
Christian Heimes33fe8092008-04-13 13:53:33 +00001321};
1322
1323
Martin v. Löwis1a214512008-06-11 05:26:20 +00001324static struct PyModuleDef warningsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 PyModuleDef_HEAD_INIT,
Eric Snow86ea5812019-05-10 13:29:55 -04001326 MODULE_NAME, /* m_name */
1327 warnings__doc__, /* m_doc */
1328 0, /* m_size */
1329 warnings_functions, /* m_methods */
1330 NULL, /* m_reload */
1331 NULL, /* m_traverse */
1332 NULL, /* m_clear */
1333 NULL /* m_free */
Martin v. Löwis1a214512008-06-11 05:26:20 +00001334};
1335
Christian Heimes33fe8092008-04-13 13:53:33 +00001336
Victor Stinner5d862462017-12-19 11:35:58 +01001337PyMODINIT_FUNC
1338_PyWarnings_Init(void)
Christian Heimes33fe8092008-04-13 13:53:33 +00001339{
Brett Cannon0759dd62009-04-01 18:13:07 +00001340 PyObject *m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001341
Martin v. Löwis1a214512008-06-11 05:26:20 +00001342 m = PyModule_Create(&warningsmodule);
Eric Snow86ea5812019-05-10 13:29:55 -04001343 if (m == NULL) {
Martin v. Löwis1a214512008-06-11 05:26:20 +00001344 return NULL;
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001345 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001346
Eric Snow86ea5812019-05-10 13:29:55 -04001347 WarningsState *st = _Warnings_GetState();
1348 if (st == NULL) {
1349 goto error;
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001350 }
Eric Snow86ea5812019-05-10 13:29:55 -04001351 if (_Warnings_InitState(st) < 0) {
1352 goto error;
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001353 }
Antoine Pitroucb0a0062014-09-18 02:40:46 +02001354
Eric Snow86ea5812019-05-10 13:29:55 -04001355 Py_INCREF(st->filters);
1356 if (PyModule_AddObject(m, "filters", st->filters) < 0) {
1357 goto error;
1358 }
1359
1360 Py_INCREF(st->once_registry);
1361 if (PyModule_AddObject(m, "_onceregistry", st->once_registry) < 0) {
1362 goto error;
1363 }
1364
1365 Py_INCREF(st->default_action);
1366 if (PyModule_AddObject(m, "_defaultaction", st->default_action) < 0) {
1367 goto error;
1368 }
1369
Martin v. Löwis1a214512008-06-11 05:26:20 +00001370 return m;
Eric Snow86ea5812019-05-10 13:29:55 -04001371
1372error:
1373 if (st != NULL) {
1374 _Warnings_ClearState(st);
1375 }
1376 Py_DECREF(m);
1377 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001378}
Victor Stinner87d23a02019-04-26 05:49:26 +02001379
Eric Snow86ea5812019-05-10 13:29:55 -04001380// We need this to ensure that warnings still work until late in finalization.
Victor Stinner87d23a02019-04-26 05:49:26 +02001381void
Eric Snow86ea5812019-05-10 13:29:55 -04001382_PyWarnings_Fini(PyInterpreterState *interp)
Victor Stinner87d23a02019-04-26 05:49:26 +02001383{
Eric Snow86ea5812019-05-10 13:29:55 -04001384 _Warnings_ClearState(&interp->warnings);
Victor Stinner87d23a02019-04-26 05:49:26 +02001385}