blob: 80dca65fd353f84e2df2fe6ee4222fe028a19334 [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);
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
19static int
20check_matched(PyObject *obj, PyObject *arg)
21{
22 PyObject *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +020023 _Py_IDENTIFIER(match);
Christian Heimes33fe8092008-04-13 13:53:33 +000024 int rc;
25
Nick Coghlan9b997472018-01-08 12:45:02 +100026 /* A 'None' filter always matches */
Christian Heimes33fe8092008-04-13 13:53:33 +000027 if (obj == Py_None)
28 return 1;
Nick Coghlan9b997472018-01-08 12:45:02 +100029
30 /* An internal plain text default filter must match exactly */
31 if (PyUnicode_CheckExact(obj)) {
32 int cmp_result = PyUnicode_Compare(obj, arg);
33 if (cmp_result == -1 && PyErr_Occurred()) {
34 return -1;
35 }
36 return !cmp_result;
37 }
38
39 /* Otherwise assume a regex filter and call its match() method */
Victor Stinner55ba38a2016-12-09 16:09:30 +010040 result = _PyObject_CallMethodIdObjArgs(obj, &PyId_match, arg, NULL);
Christian Heimes33fe8092008-04-13 13:53:33 +000041 if (result == NULL)
42 return -1;
43
44 rc = PyObject_IsTrue(result);
45 Py_DECREF(result);
46 return rc;
47}
48
49/*
50 Returns a new reference.
51 A NULL return value can mean false or an error.
52*/
53static PyObject *
Victor Stinner82656272017-11-22 23:51:42 +010054get_warnings_attr(_Py_Identifier *attr_id, int try_import)
Christian Heimes33fe8092008-04-13 13:53:33 +000055{
Victor Stinner82656272017-11-22 23:51:42 +010056 PyObject *warnings_str;
Victor Stinnere98445a2016-03-23 00:54:48 +010057 PyObject *warnings_module, *obj;
Victor Stinner82656272017-11-22 23:51:42 +010058 _Py_IDENTIFIER(warnings);
Christian Heimes33fe8092008-04-13 13:53:33 +000059
Victor Stinner82656272017-11-22 23:51:42 +010060 warnings_str = _PyUnicode_FromId(&PyId_warnings);
Christian Heimes33fe8092008-04-13 13:53:33 +000061 if (warnings_str == NULL) {
Victor Stinner82656272017-11-22 23:51:42 +010062 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +000063 }
64
Victor Stinnere98445a2016-03-23 00:54:48 +010065 /* don't try to import after the start of the Python finallization */
Eric Snow2ebc5ce2017-09-07 23:51:28 -060066 if (try_import && !_Py_IsFinalizing()) {
Victor Stinnere98445a2016-03-23 00:54:48 +010067 warnings_module = PyImport_Import(warnings_str);
68 if (warnings_module == NULL) {
69 /* Fallback to the C implementation if we cannot get
70 the Python implementation */
Serhiy Storchakad4f84802017-11-11 15:19:47 +020071 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
72 PyErr_Clear();
73 }
Christian Heimes33fe8092008-04-13 13:53:33 +000074 return NULL;
Victor Stinnere98445a2016-03-23 00:54:48 +010075 }
76 }
77 else {
Nathaniel J. Smithdba976b2018-01-26 11:28:31 -080078 /* if we're so late into Python finalization that the module dict is
79 gone, then we can't even use PyImport_GetModule without triggering
80 an interpreter abort.
81 */
82 if (!PyThreadState_GET()->interp->modules) {
83 return NULL;
84 }
Eric Snow3f9eee62017-09-15 16:35:20 -060085 warnings_module = PyImport_GetModule(warnings_str);
Victor Stinner023654f2016-03-23 17:48:22 +010086 if (warnings_module == NULL)
87 return NULL;
Victor Stinnere98445a2016-03-23 00:54:48 +010088 }
89
Serhiy Storchakaf320be72018-01-25 10:49:40 +020090 (void)_PyObject_LookupAttrId(warnings_module, attr_id, &obj);
Victor Stinnere98445a2016-03-23 00:54:48 +010091 Py_DECREF(warnings_module);
92 return obj;
Christian Heimes33fe8092008-04-13 13:53:33 +000093}
94
95
Neal Norwitz32dde222008-04-15 06:43:13 +000096static PyObject *
Christian Heimes33fe8092008-04-13 13:53:33 +000097get_once_registry(void)
98{
99 PyObject *registry;
Victor Stinner82656272017-11-22 23:51:42 +0100100 _Py_IDENTIFIER(onceregistry);
Christian Heimes33fe8092008-04-13 13:53:33 +0000101
Victor Stinner82656272017-11-22 23:51:42 +0100102 registry = get_warnings_attr(&PyId_onceregistry, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000103 if (registry == NULL) {
104 if (PyErr_Occurred())
105 return NULL;
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200106 assert(_PyRuntime.warnings.once_registry);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600107 return _PyRuntime.warnings.once_registry;
Christian Heimes33fe8092008-04-13 13:53:33 +0000108 }
Oren Milman252033d2017-09-11 09:28:39 +0300109 if (!PyDict_Check(registry)) {
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200110 PyErr_Format(PyExc_TypeError,
111 MODULE_NAME ".onceregistry must be a dict, "
112 "not '%.200s'",
113 Py_TYPE(registry)->tp_name);
Oren Milman252033d2017-09-11 09:28:39 +0300114 Py_DECREF(registry);
115 return NULL;
116 }
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200117 Py_SETREF(_PyRuntime.warnings.once_registry, registry);
Christian Heimes33fe8092008-04-13 13:53:33 +0000118 return registry;
119}
120
121
Brett Cannon0759dd62009-04-01 18:13:07 +0000122static PyObject *
123get_default_action(void)
124{
125 PyObject *default_action;
Victor Stinner82656272017-11-22 23:51:42 +0100126 _Py_IDENTIFIER(defaultaction);
Brett Cannon0759dd62009-04-01 18:13:07 +0000127
Victor Stinner82656272017-11-22 23:51:42 +0100128 default_action = get_warnings_attr(&PyId_defaultaction, 0);
Brett Cannon0759dd62009-04-01 18:13:07 +0000129 if (default_action == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 if (PyErr_Occurred()) {
131 return NULL;
132 }
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200133 assert(_PyRuntime.warnings.default_action);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600134 return _PyRuntime.warnings.default_action;
Brett Cannon0759dd62009-04-01 18:13:07 +0000135 }
Oren Milman9d984fd2017-09-12 00:18:09 +0300136 if (!PyUnicode_Check(default_action)) {
137 PyErr_Format(PyExc_TypeError,
138 MODULE_NAME ".defaultaction must be a string, "
139 "not '%.200s'",
140 Py_TYPE(default_action)->tp_name);
141 Py_DECREF(default_action);
142 return NULL;
143 }
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200144 Py_SETREF(_PyRuntime.warnings.default_action, default_action);
Brett Cannon0759dd62009-04-01 18:13:07 +0000145 return default_action;
146}
147
148
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400149/* The item is a new reference. */
Victor Stinnera4c704b2013-10-29 23:43:41 +0100150static PyObject*
Christian Heimes33fe8092008-04-13 13:53:33 +0000151get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
152 PyObject *module, PyObject **item)
153{
Brett Cannon0759dd62009-04-01 18:13:07 +0000154 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000155 Py_ssize_t i;
156 PyObject *warnings_filters;
Victor Stinner82656272017-11-22 23:51:42 +0100157 _Py_IDENTIFIER(filters);
Christian Heimes33fe8092008-04-13 13:53:33 +0000158
Victor Stinner82656272017-11-22 23:51:42 +0100159 warnings_filters = get_warnings_attr(&PyId_filters, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000160 if (warnings_filters == NULL) {
161 if (PyErr_Occurred())
162 return NULL;
163 }
164 else {
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200165 Py_SETREF(_PyRuntime.warnings.filters, warnings_filters);
Christian Heimes33fe8092008-04-13 13:53:33 +0000166 }
167
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600168 PyObject *filters = _PyRuntime.warnings.filters;
169 if (filters == NULL || !PyList_Check(filters)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000170 PyErr_SetString(PyExc_ValueError,
171 MODULE_NAME ".filters must be a list");
172 return NULL;
173 }
174
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600175 /* _PyRuntime.warnings.filters could change while we are iterating over it. */
176 for (i = 0; i < PyList_GET_SIZE(filters); i++) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000177 PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj;
178 Py_ssize_t ln;
179 int is_subclass, good_msg, good_mod;
180
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600181 tmp_item = PyList_GET_ITEM(filters, i);
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400182 if (!PyTuple_Check(tmp_item) || PyTuple_GET_SIZE(tmp_item) != 5) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000183 PyErr_Format(PyExc_ValueError,
184 MODULE_NAME ".filters item %zd isn't a 5-tuple", i);
185 return NULL;
186 }
187
188 /* Python code: action, msg, cat, mod, ln = item */
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400189 Py_INCREF(tmp_item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000190 action = PyTuple_GET_ITEM(tmp_item, 0);
191 msg = PyTuple_GET_ITEM(tmp_item, 1);
192 cat = PyTuple_GET_ITEM(tmp_item, 2);
193 mod = PyTuple_GET_ITEM(tmp_item, 3);
194 ln_obj = PyTuple_GET_ITEM(tmp_item, 4);
195
Oren Milman9d984fd2017-09-12 00:18:09 +0300196 if (!PyUnicode_Check(action)) {
197 PyErr_Format(PyExc_TypeError,
198 "action must be a string, not '%.200s'",
199 Py_TYPE(action)->tp_name);
200 Py_DECREF(tmp_item);
201 return NULL;
202 }
203
Christian Heimes33fe8092008-04-13 13:53:33 +0000204 good_msg = check_matched(msg, text);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400205 if (good_msg == -1) {
206 Py_DECREF(tmp_item);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100207 return NULL;
Benjamin Peterson8c598162015-05-03 11:28:46 -0400208 }
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100209
Christian Heimes33fe8092008-04-13 13:53:33 +0000210 good_mod = check_matched(mod, module);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400211 if (good_mod == -1) {
212 Py_DECREF(tmp_item);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100213 return NULL;
Benjamin Peterson8c598162015-05-03 11:28:46 -0400214 }
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100215
Christian Heimes33fe8092008-04-13 13:53:33 +0000216 is_subclass = PyObject_IsSubclass(category, cat);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400217 if (is_subclass == -1) {
218 Py_DECREF(tmp_item);
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100219 return NULL;
Benjamin Peterson8c598162015-05-03 11:28:46 -0400220 }
Victor Stinner3cd04aa2013-10-31 14:46:00 +0100221
Christian Heimes33fe8092008-04-13 13:53:33 +0000222 ln = PyLong_AsSsize_t(ln_obj);
Benjamin Peterson8c598162015-05-03 11:28:46 -0400223 if (ln == -1 && PyErr_Occurred()) {
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400224 Py_DECREF(tmp_item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000225 return NULL;
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400226 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000227
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400228 if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln)) {
229 *item = tmp_item;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100230 return action;
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400231 }
232
233 Py_DECREF(tmp_item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000234 }
235
Brett Cannon0759dd62009-04-01 18:13:07 +0000236 action = get_default_action();
237 if (action != NULL) {
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400238 Py_INCREF(Py_None);
239 *item = Py_None;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100240 return action;
Brett Cannon0759dd62009-04-01 18:13:07 +0000241 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000242
Christian Heimes33fe8092008-04-13 13:53:33 +0000243 return NULL;
244}
245
Brett Cannon0759dd62009-04-01 18:13:07 +0000246
Christian Heimes33fe8092008-04-13 13:53:33 +0000247static int
248already_warned(PyObject *registry, PyObject *key, int should_set)
249{
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200250 PyObject *version_obj, *already_warned;
251 _Py_IDENTIFIER(version);
Christian Heimes33fe8092008-04-13 13:53:33 +0000252
253 if (key == NULL)
254 return -1;
255
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200256 version_obj = _PyDict_GetItemId(registry, &PyId_version);
257 if (version_obj == NULL
258 || !PyLong_CheckExact(version_obj)
Miss Islington (bot)62674f32018-12-10 23:05:13 -0800259 || PyLong_AsLong(version_obj) != _PyRuntime.warnings.filters_version)
260 {
261 if (PyErr_Occurred()) {
262 return -1;
263 }
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200264 PyDict_Clear(registry);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600265 version_obj = PyLong_FromLong(_PyRuntime.warnings.filters_version);
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200266 if (version_obj == NULL)
267 return -1;
268 if (_PyDict_SetItemId(registry, &PyId_version, version_obj) < 0) {
269 Py_DECREF(version_obj);
270 return -1;
271 }
272 Py_DECREF(version_obj);
273 }
274 else {
275 already_warned = PyDict_GetItem(registry, key);
276 if (already_warned != NULL) {
277 int rc = PyObject_IsTrue(already_warned);
278 if (rc != 0)
279 return rc;
280 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000281 }
282
283 /* This warning wasn't found in the registry, set it. */
284 if (should_set)
285 return PyDict_SetItem(registry, key, Py_True);
286 return 0;
287}
288
289/* New reference. */
290static PyObject *
291normalize_module(PyObject *filename)
292{
293 PyObject *module;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100294 int kind;
295 void *data;
Christian Heimes33fe8092008-04-13 13:53:33 +0000296 Py_ssize_t len;
297
Victor Stinner9e30aa52011-11-21 02:49:52 +0100298 len = PyUnicode_GetLength(filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000299 if (len < 0)
300 return NULL;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100301
302 if (len == 0)
303 return PyUnicode_FromString("<unknown>");
304
305 kind = PyUnicode_KIND(filename);
306 data = PyUnicode_DATA(filename);
307
308 /* if filename.endswith(".py"): */
Christian Heimes33fe8092008-04-13 13:53:33 +0000309 if (len >= 3 &&
Victor Stinnera4c704b2013-10-29 23:43:41 +0100310 PyUnicode_READ(kind, data, len-3) == '.' &&
311 PyUnicode_READ(kind, data, len-2) == 'p' &&
312 PyUnicode_READ(kind, data, len-1) == 'y')
313 {
Victor Stinner9e30aa52011-11-21 02:49:52 +0100314 module = PyUnicode_Substring(filename, 0, len-3);
Christian Heimes33fe8092008-04-13 13:53:33 +0000315 }
316 else {
317 module = filename;
318 Py_INCREF(module);
319 }
320 return module;
321}
322
323static int
324update_registry(PyObject *registry, PyObject *text, PyObject *category,
325 int add_zero)
326{
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300327 PyObject *altkey;
Christian Heimes33fe8092008-04-13 13:53:33 +0000328 int rc;
329
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300330 if (add_zero)
331 altkey = PyTuple_Pack(3, text, category, _PyLong_Zero);
Christian Heimes33fe8092008-04-13 13:53:33 +0000332 else
333 altkey = PyTuple_Pack(2, text, category);
334
335 rc = already_warned(registry, altkey, 1);
Christian Heimes33fe8092008-04-13 13:53:33 +0000336 Py_XDECREF(altkey);
337 return rc;
338}
339
340static void
Victor Stinner914cde82016-03-19 01:03:51 +0100341show_warning(PyObject *filename, int lineno, PyObject *text,
342 PyObject *category, PyObject *sourceline)
Christian Heimes33fe8092008-04-13 13:53:33 +0000343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 PyObject *f_stderr;
345 PyObject *name;
Christian Heimes33fe8092008-04-13 13:53:33 +0000346 char lineno_str[128];
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200347 _Py_IDENTIFIER(__name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000348
349 PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);
350
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200351 name = _PyObject_GetAttrId(category, &PyId___name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000352 if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */
Victor Stinnerae233ea2013-10-31 14:51:38 +0100353 goto error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000354
Victor Stinnerbd303c12013-11-07 23:07:29 +0100355 f_stderr = _PySys_GetObjectId(&PyId_stderr);
Christian Heimes33fe8092008-04-13 13:53:33 +0000356 if (f_stderr == NULL) {
357 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnerae233ea2013-10-31 14:51:38 +0100358 goto error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000359 }
360
361 /* Print "filename:lineno: category: text\n" */
Victor Stinnerae233ea2013-10-31 14:51:38 +0100362 if (PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW) < 0)
363 goto error;
364 if (PyFile_WriteString(lineno_str, f_stderr) < 0)
365 goto error;
366 if (PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW) < 0)
367 goto error;
368 if (PyFile_WriteString(": ", f_stderr) < 0)
369 goto error;
370 if (PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW) < 0)
371 goto error;
372 if (PyFile_WriteString("\n", f_stderr) < 0)
373 goto error;
374 Py_CLEAR(name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000375
376 /* Print " source_line\n" */
Christian Heimes33fe8092008-04-13 13:53:33 +0000377 if (sourceline) {
Victor Stinnera4c704b2013-10-29 23:43:41 +0100378 int kind;
379 void *data;
380 Py_ssize_t i, len;
381 Py_UCS4 ch;
382 PyObject *truncated;
Christian Heimes33fe8092008-04-13 13:53:33 +0000383
Victor Stinnera4c704b2013-10-29 23:43:41 +0100384 if (PyUnicode_READY(sourceline) < 1)
385 goto error;
386
387 kind = PyUnicode_KIND(sourceline);
388 data = PyUnicode_DATA(sourceline);
389 len = PyUnicode_GET_LENGTH(sourceline);
390 for (i=0; i<len; i++) {
391 ch = PyUnicode_READ(kind, data, i);
392 if (ch != ' ' && ch != '\t' && ch != '\014')
393 break;
394 }
395
396 truncated = PyUnicode_Substring(sourceline, i, len);
397 if (truncated == NULL)
398 goto error;
399
400 PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW);
401 Py_DECREF(truncated);
Christian Heimes33fe8092008-04-13 13:53:33 +0000402 PyFile_WriteString("\n", f_stderr);
403 }
Victor Stinner78e2c982013-07-16 01:54:37 +0200404 else {
405 _Py_DisplaySourceLine(f_stderr, filename, lineno, 2);
406 }
Victor Stinnera4c704b2013-10-29 23:43:41 +0100407
408error:
Victor Stinnerae233ea2013-10-31 14:51:38 +0100409 Py_XDECREF(name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000410 PyErr_Clear();
411}
412
Victor Stinner1231a462016-03-19 00:47:17 +0100413static int
414call_show_warning(PyObject *category, PyObject *text, PyObject *message,
415 PyObject *filename, int lineno, PyObject *lineno_obj,
Victor Stinner914cde82016-03-19 01:03:51 +0100416 PyObject *sourceline, PyObject *source)
Victor Stinner1231a462016-03-19 00:47:17 +0100417{
418 PyObject *show_fn, *msg, *res, *warnmsg_cls = NULL;
Victor Stinner82656272017-11-22 23:51:42 +0100419 _Py_IDENTIFIER(_showwarnmsg);
420 _Py_IDENTIFIER(WarningMessage);
Victor Stinner1231a462016-03-19 00:47:17 +0100421
Victor Stinnere98445a2016-03-23 00:54:48 +0100422 /* If the source parameter is set, try to get the Python implementation.
423 The Python implementation is able to log the traceback where the source
luzpaza5293b42017-11-05 07:37:50 -0600424 was allocated, whereas the C implementation doesn't. */
Victor Stinner82656272017-11-22 23:51:42 +0100425 show_fn = get_warnings_attr(&PyId__showwarnmsg, source != NULL);
Victor Stinner1231a462016-03-19 00:47:17 +0100426 if (show_fn == NULL) {
427 if (PyErr_Occurred())
428 return -1;
429 show_warning(filename, lineno, text, category, sourceline);
430 return 0;
431 }
432
433 if (!PyCallable_Check(show_fn)) {
434 PyErr_SetString(PyExc_TypeError,
435 "warnings._showwarnmsg() must be set to a callable");
436 goto error;
437 }
438
Victor Stinner82656272017-11-22 23:51:42 +0100439 warnmsg_cls = get_warnings_attr(&PyId_WarningMessage, 0);
Victor Stinner1231a462016-03-19 00:47:17 +0100440 if (warnmsg_cls == NULL) {
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200441 if (!PyErr_Occurred()) {
442 PyErr_SetString(PyExc_RuntimeError,
443 "unable to get warnings.WarningMessage");
444 }
Victor Stinner1231a462016-03-19 00:47:17 +0100445 goto error;
446 }
447
448 msg = PyObject_CallFunctionObjArgs(warnmsg_cls, message, category,
Victor Stinner914cde82016-03-19 01:03:51 +0100449 filename, lineno_obj, Py_None, Py_None, source,
Victor Stinner1231a462016-03-19 00:47:17 +0100450 NULL);
451 Py_DECREF(warnmsg_cls);
452 if (msg == NULL)
453 goto error;
454
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100455 res = PyObject_CallFunctionObjArgs(show_fn, msg, NULL);
Victor Stinner1231a462016-03-19 00:47:17 +0100456 Py_DECREF(show_fn);
457 Py_DECREF(msg);
458
459 if (res == NULL)
460 return -1;
461
462 Py_DECREF(res);
463 return 0;
464
465error:
466 Py_XDECREF(show_fn);
467 return -1;
468}
469
Christian Heimes33fe8092008-04-13 13:53:33 +0000470static PyObject *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471warn_explicit(PyObject *category, PyObject *message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000472 PyObject *filename, int lineno,
Victor Stinner914cde82016-03-19 01:03:51 +0100473 PyObject *module, PyObject *registry, PyObject *sourceline,
474 PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000475{
476 PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL;
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400477 PyObject *item = NULL;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100478 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000479 int rc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480
Victor Stinnerdcdd05b2013-11-01 00:55:30 +0100481 /* module can be None if a warning is emitted late during Python shutdown.
482 In this case, the Python warnings module was probably unloaded, filters
483 are no more available to choose as action. It is safer to ignore the
484 warning and do nothing. */
485 if (module == Py_None)
486 Py_RETURN_NONE;
487
Brett Cannondb734912008-06-27 00:52:15 +0000488 if (registry && !PyDict_Check(registry) && (registry != Py_None)) {
Oren Milman252033d2017-09-11 09:28:39 +0300489 PyErr_SetString(PyExc_TypeError, "'registry' must be a dict or None");
Brett Cannondb734912008-06-27 00:52:15 +0000490 return NULL;
491 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000492
493 /* Normalize module. */
494 if (module == NULL) {
495 module = normalize_module(filename);
496 if (module == NULL)
497 return NULL;
498 }
499 else
500 Py_INCREF(module);
501
502 /* Normalize message. */
503 Py_INCREF(message); /* DECREF'ed in cleanup. */
504 rc = PyObject_IsInstance(message, PyExc_Warning);
505 if (rc == -1) {
506 goto cleanup;
507 }
508 if (rc == 1) {
509 text = PyObject_Str(message);
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000510 if (text == NULL)
511 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000512 category = (PyObject*)message->ob_type;
513 }
514 else {
515 text = message;
Victor Stinner7bfb42d2016-12-05 17:04:32 +0100516 message = PyObject_CallFunctionObjArgs(category, message, NULL);
Brett Cannondb734912008-06-27 00:52:15 +0000517 if (message == NULL)
518 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000519 }
520
521 lineno_obj = PyLong_FromLong(lineno);
522 if (lineno_obj == NULL)
523 goto cleanup;
524
Victor Stinner22f18752016-12-09 18:08:18 +0100525 if (source == Py_None) {
526 source = NULL;
527 }
528
Christian Heimes33fe8092008-04-13 13:53:33 +0000529 /* Create key. */
530 key = PyTuple_Pack(3, text, category, lineno_obj);
531 if (key == NULL)
532 goto cleanup;
533
Brett Cannondb734912008-06-27 00:52:15 +0000534 if ((registry != NULL) && (registry != Py_None)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000535 rc = already_warned(registry, key, 0);
536 if (rc == -1)
537 goto cleanup;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 else if (rc == 1)
Christian Heimes33fe8092008-04-13 13:53:33 +0000539 goto return_none;
540 /* Else this warning hasn't been generated before. */
541 }
542
543 action = get_filter(category, text, lineno, module, &item);
544 if (action == NULL)
545 goto cleanup;
546
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200547 if (_PyUnicode_EqualToASCIIString(action, "error")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000548 PyErr_SetObject(category, message);
549 goto cleanup;
550 }
551
Victor Stinnerc9758782017-11-27 16:57:07 +0100552 if (_PyUnicode_EqualToASCIIString(action, "ignore")) {
553 goto return_none;
554 }
555
Christian Heimes33fe8092008-04-13 13:53:33 +0000556 /* Store in the registry that we've been here, *except* when the action
557 is "always". */
558 rc = 0;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200559 if (!_PyUnicode_EqualToASCIIString(action, "always")) {
Brett Cannondb734912008-06-27 00:52:15 +0000560 if (registry != NULL && registry != Py_None &&
Victor Stinnerc9758782017-11-27 16:57:07 +0100561 PyDict_SetItem(registry, key, Py_True) < 0)
562 {
Christian Heimes33fe8092008-04-13 13:53:33 +0000563 goto cleanup;
Victor Stinnerc9758782017-11-27 16:57:07 +0100564 }
565
566 if (_PyUnicode_EqualToASCIIString(action, "once")) {
Brett Cannondb734912008-06-27 00:52:15 +0000567 if (registry == NULL || registry == Py_None) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000568 registry = get_once_registry();
569 if (registry == NULL)
570 goto cleanup;
571 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600572 /* _PyRuntime.warnings.once_registry[(text, category)] = 1 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000574 }
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200575 else if (_PyUnicode_EqualToASCIIString(action, "module")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000576 /* registry[(text, category, 0)] = 1 */
Brett Cannondb734912008-06-27 00:52:15 +0000577 if (registry != NULL && registry != Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000579 }
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200580 else if (!_PyUnicode_EqualToASCIIString(action, "default")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000581 PyErr_Format(PyExc_RuntimeError,
Victor Stinnera4c704b2013-10-29 23:43:41 +0100582 "Unrecognized action (%R) in warnings.filters:\n %R",
583 action, item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000584 goto cleanup;
585 }
586 }
587
Christian Heimes1a8501c2008-10-02 19:56:01 +0000588 if (rc == 1) /* Already warned for this module. */
Christian Heimes33fe8092008-04-13 13:53:33 +0000589 goto return_none;
590 if (rc == 0) {
Victor Stinner1231a462016-03-19 00:47:17 +0100591 if (call_show_warning(category, text, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +0100592 lineno_obj, sourceline, source) < 0)
Victor Stinner1231a462016-03-19 00:47:17 +0100593 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000594 }
595 else /* if (rc == -1) */
596 goto cleanup;
597
598 return_none:
599 result = Py_None;
600 Py_INCREF(result);
601
602 cleanup:
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400603 Py_XDECREF(item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000604 Py_XDECREF(key);
605 Py_XDECREF(text);
606 Py_XDECREF(lineno_obj);
607 Py_DECREF(module);
Brett Cannondb734912008-06-27 00:52:15 +0000608 Py_XDECREF(message);
Christian Heimes33fe8092008-04-13 13:53:33 +0000609 return result; /* Py_None or NULL. */
610}
611
Larry Hastings714e4932015-09-06 00:39:37 -0700612static int
613is_internal_frame(PyFrameObject *frame)
614{
615 static PyObject *importlib_string = NULL;
616 static PyObject *bootstrap_string = NULL;
617 PyObject *filename;
618 int contains;
619
620 if (importlib_string == NULL) {
621 importlib_string = PyUnicode_FromString("importlib");
622 if (importlib_string == NULL) {
623 return 0;
624 }
625
626 bootstrap_string = PyUnicode_FromString("_bootstrap");
627 if (bootstrap_string == NULL) {
628 Py_DECREF(importlib_string);
629 return 0;
630 }
631 Py_INCREF(importlib_string);
632 Py_INCREF(bootstrap_string);
633 }
634
635 if (frame == NULL || frame->f_code == NULL ||
636 frame->f_code->co_filename == NULL) {
637 return 0;
638 }
639 filename = frame->f_code->co_filename;
640 if (!PyUnicode_Check(filename)) {
641 return 0;
642 }
643 contains = PyUnicode_Contains(filename, importlib_string);
644 if (contains < 0) {
645 return 0;
646 }
647 else if (contains > 0) {
648 contains = PyUnicode_Contains(filename, bootstrap_string);
649 if (contains < 0) {
650 return 0;
651 }
652 else if (contains > 0) {
653 return 1;
654 }
655 }
656
657 return 0;
658}
659
660static PyFrameObject *
661next_external_frame(PyFrameObject *frame)
662{
663 do {
664 frame = frame->f_back;
665 } while (frame != NULL && is_internal_frame(frame));
666
667 return frame;
668}
669
Christian Heimes33fe8092008-04-13 13:53:33 +0000670/* filename, module, and registry are new refs, globals is borrowed */
671/* Returns 0 on error (no new refs), 1 on success */
672static int
673setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
674 PyObject **module, PyObject **registry)
675{
676 PyObject *globals;
677
678 /* Setup globals and lineno. */
679 PyFrameObject *f = PyThreadState_GET()->frame;
Larry Hastings714e4932015-09-06 00:39:37 -0700680 // Stack level comparisons to Python code is off by one as there is no
681 // warnings-related stack level to avoid.
682 if (stack_level <= 0 || is_internal_frame(f)) {
683 while (--stack_level > 0 && f != NULL) {
684 f = f->f_back;
685 }
686 }
687 else {
688 while (--stack_level > 0 && f != NULL) {
689 f = next_external_frame(f);
690 }
691 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000692
693 if (f == NULL) {
694 globals = PyThreadState_Get()->interp->sysdict;
695 *lineno = 1;
696 }
697 else {
698 globals = f->f_globals;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000699 *lineno = PyFrame_GetLineNumber(f);
Christian Heimes33fe8092008-04-13 13:53:33 +0000700 }
701
702 *module = NULL;
703
704 /* Setup registry. */
705 assert(globals != NULL);
706 assert(PyDict_Check(globals));
707 *registry = PyDict_GetItemString(globals, "__warningregistry__");
708 if (*registry == NULL) {
709 int rc;
710
711 *registry = PyDict_New();
712 if (*registry == NULL)
713 return 0;
714
715 rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
716 if (rc < 0)
717 goto handle_error;
718 }
719 else
720 Py_INCREF(*registry);
721
722 /* Setup module. */
723 *module = PyDict_GetItemString(globals, "__name__");
Oren Milman5d3e8002017-09-24 21:28:42 +0300724 if (*module == Py_None || (*module != NULL && PyUnicode_Check(*module))) {
725 Py_INCREF(*module);
726 }
727 else {
Christian Heimes33fe8092008-04-13 13:53:33 +0000728 *module = PyUnicode_FromString("<string>");
729 if (*module == NULL)
730 goto handle_error;
731 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000732
733 /* Setup filename. */
734 *filename = PyDict_GetItemString(globals, "__file__");
Victor Stinner8b0508e2011-07-04 02:43:09 +0200735 if (*filename != NULL && PyUnicode_Check(*filename)) {
Victor Stinnerb62a7b22011-10-06 02:34:51 +0200736 Py_ssize_t len;
737 int kind;
738 void *data;
739
740 if (PyUnicode_READY(*filename))
741 goto handle_error;
742
Victor Stinner9e30aa52011-11-21 02:49:52 +0100743 len = PyUnicode_GetLength(*filename);
Victor Stinnerb62a7b22011-10-06 02:34:51 +0200744 kind = PyUnicode_KIND(*filename);
745 data = PyUnicode_DATA(*filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000746
Benjamin Peterson21e0da22012-01-11 21:00:42 -0500747#define ascii_lower(c) ((c <= 127) ? Py_TOLOWER(c) : 0)
Brett Cannonf299abd2015-04-13 14:21:02 -0400748 /* if filename.lower().endswith(".pyc"): */
Christian Heimes33fe8092008-04-13 13:53:33 +0000749 if (len >= 4 &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200750 PyUnicode_READ(kind, data, len-4) == '.' &&
Benjamin Peterson21e0da22012-01-11 21:00:42 -0500751 ascii_lower(PyUnicode_READ(kind, data, len-3)) == 'p' &&
752 ascii_lower(PyUnicode_READ(kind, data, len-2)) == 'y' &&
Brett Cannonf299abd2015-04-13 14:21:02 -0400753 ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'c')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000754 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200755 *filename = PyUnicode_Substring(*filename, 0,
756 PyUnicode_GET_LENGTH(*filename)-1);
Victor Stinner2e5f1172010-08-08 22:12:45 +0000757 if (*filename == NULL)
758 goto handle_error;
759 }
760 else
Christian Heimes33fe8092008-04-13 13:53:33 +0000761 Py_INCREF(*filename);
762 }
763 else {
Benjamin Petersonbb4a7472011-07-04 22:27:16 -0500764 *filename = NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200765 if (*module != Py_None && _PyUnicode_EqualToASCIIString(*module, "__main__")) {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100766 PyObject *argv = _PySys_GetObjectId(&PyId_argv);
Victor Stinnerce5f4fb2013-10-28 18:47:22 +0100767 /* PyList_Check() is needed because sys.argv is set to None during
768 Python finalization */
769 if (argv != NULL && PyList_Check(argv) && PyList_Size(argv) > 0) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000770 int is_true;
Christian Heimes33fe8092008-04-13 13:53:33 +0000771 *filename = PyList_GetItem(argv, 0);
772 Py_INCREF(*filename);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000773 /* If sys.argv[0] is false, then use '__main__'. */
774 is_true = PyObject_IsTrue(*filename);
775 if (is_true < 0) {
776 Py_DECREF(*filename);
777 goto handle_error;
778 }
779 else if (!is_true) {
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300780 Py_SETREF(*filename, PyUnicode_FromString("__main__"));
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000781 if (*filename == NULL)
782 goto handle_error;
783 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000784 }
785 else {
786 /* embedded interpreters don't have sys.argv, see bug #839151 */
787 *filename = PyUnicode_FromString("__main__");
Victor Stinner856f45f2013-10-30 00:04:59 +0100788 if (*filename == NULL)
789 goto handle_error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000790 }
791 }
792 if (*filename == NULL) {
793 *filename = *module;
794 Py_INCREF(*filename);
795 }
796 }
797
798 return 1;
799
800 handle_error:
801 /* filename not XDECREF'ed here as there is no way to jump here with a
802 dangling reference. */
803 Py_XDECREF(*registry);
804 Py_XDECREF(*module);
805 return 0;
806}
807
808static PyObject *
809get_category(PyObject *message, PyObject *category)
810{
811 int rc;
812
813 /* Get category. */
814 rc = PyObject_IsInstance(message, PyExc_Warning);
815 if (rc == -1)
816 return NULL;
817
818 if (rc == 1)
819 category = (PyObject*)message->ob_type;
Berker Peksagd8089e02014-07-11 19:50:25 +0300820 else if (category == NULL || category == Py_None)
Christian Heimes33fe8092008-04-13 13:53:33 +0000821 category = PyExc_UserWarning;
822
823 /* Validate category. */
824 rc = PyObject_IsSubclass(category, PyExc_Warning);
Berker Peksagd8089e02014-07-11 19:50:25 +0300825 /* category is not a subclass of PyExc_Warning or
826 PyObject_IsSubclass raised an error */
827 if (rc == -1 || rc == 0) {
828 PyErr_Format(PyExc_TypeError,
829 "category must be a Warning subclass, not '%s'",
830 Py_TYPE(category)->tp_name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000831 return NULL;
832 }
833
834 return category;
835}
836
837static PyObject *
Victor Stinner914cde82016-03-19 01:03:51 +0100838do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level,
839 PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000840{
841 PyObject *filename, *module, *registry, *res;
842 int lineno;
843
844 if (!setup_context(stack_level, &filename, &lineno, &module, &registry))
845 return NULL;
846
Victor Stinnerdcdd05b2013-11-01 00:55:30 +0100847 res = warn_explicit(category, message, filename, lineno, module, registry,
Victor Stinner914cde82016-03-19 01:03:51 +0100848 NULL, source);
Christian Heimes33fe8092008-04-13 13:53:33 +0000849 Py_DECREF(filename);
850 Py_DECREF(registry);
851 Py_DECREF(module);
852 return res;
853}
854
Victor Stinner22f18752016-12-09 18:08:18 +0100855/*[clinic input]
856warn as warnings_warn
857
858 message: object
859 category: object = None
860 stacklevel: Py_ssize_t = 1
861 source: object = None
862
863Issue a warning, or maybe ignore it or raise an exception.
864[clinic start generated code]*/
865
Christian Heimes33fe8092008-04-13 13:53:33 +0000866static PyObject *
Victor Stinner22f18752016-12-09 18:08:18 +0100867warnings_warn_impl(PyObject *module, PyObject *message, PyObject *category,
868 Py_ssize_t stacklevel, PyObject *source)
869/*[clinic end generated code: output=31ed5ab7d8d760b2 input=bfdf5cf99f6c4edd]*/
Christian Heimes33fe8092008-04-13 13:53:33 +0000870{
Christian Heimes33fe8092008-04-13 13:53:33 +0000871 category = get_category(message, category);
872 if (category == NULL)
873 return NULL;
Victor Stinner22f18752016-12-09 18:08:18 +0100874 return do_warn(message, category, stacklevel, source);
Christian Heimes33fe8092008-04-13 13:53:33 +0000875}
876
877static PyObject *
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200878get_source_line(PyObject *module_globals, int lineno)
879{
880 _Py_IDENTIFIER(get_source);
881 _Py_IDENTIFIER(__loader__);
882 _Py_IDENTIFIER(__name__);
883 PyObject *loader;
884 PyObject *module_name;
885 PyObject *get_source;
886 PyObject *source;
887 PyObject *source_list;
888 PyObject *source_line;
889
890 /* Check/get the requisite pieces needed for the loader. */
891 loader = _PyDict_GetItemIdWithError(module_globals, &PyId___loader__);
892 if (loader == NULL) {
893 return NULL;
894 }
895 Py_INCREF(loader);
896 module_name = _PyDict_GetItemIdWithError(module_globals, &PyId___name__);
897 if (!module_name) {
898 Py_DECREF(loader);
899 return NULL;
900 }
901 Py_INCREF(module_name);
902
903 /* Make sure the loader implements the optional get_source() method. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200904 (void)_PyObject_LookupAttrId(loader, &PyId_get_source, &get_source);
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200905 Py_DECREF(loader);
906 if (!get_source) {
907 Py_DECREF(module_name);
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200908 return NULL;
909 }
910 /* Call get_source() to get the source code. */
911 source = PyObject_CallFunctionObjArgs(get_source, module_name, NULL);
912 Py_DECREF(get_source);
913 Py_DECREF(module_name);
914 if (!source) {
915 return NULL;
916 }
917 if (source == Py_None) {
918 Py_DECREF(source);
919 return NULL;
920 }
921
922 /* Split the source into lines. */
923 source_list = PyUnicode_Splitlines(source, 0);
924 Py_DECREF(source);
925 if (!source_list) {
926 return NULL;
927 }
928
929 /* Get the source line. */
930 source_line = PyList_GetItem(source_list, lineno-1);
931 Py_XINCREF(source_line);
932 Py_DECREF(source_list);
933 return source_line;
934}
935
936static PyObject *
Christian Heimes33fe8092008-04-13 13:53:33 +0000937warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
938{
939 static char *kwd_list[] = {"message", "category", "filename", "lineno",
Victor Stinner914cde82016-03-19 01:03:51 +0100940 "module", "registry", "module_globals",
941 "source", 0};
Christian Heimes33fe8092008-04-13 13:53:33 +0000942 PyObject *message;
943 PyObject *category;
944 PyObject *filename;
945 int lineno;
946 PyObject *module = NULL;
947 PyObject *registry = NULL;
948 PyObject *module_globals = NULL;
Victor Stinner914cde82016-03-19 01:03:51 +0100949 PyObject *sourceobj = NULL;
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200950 PyObject *source_line = NULL;
951 PyObject *returned;
Christian Heimes33fe8092008-04-13 13:53:33 +0000952
Victor Stinner914cde82016-03-19 01:03:51 +0100953 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOUi|OOOO:warn_explicit",
Christian Heimes33fe8092008-04-13 13:53:33 +0000954 kwd_list, &message, &category, &filename, &lineno, &module,
Victor Stinner914cde82016-03-19 01:03:51 +0100955 &registry, &module_globals, &sourceobj))
Christian Heimes33fe8092008-04-13 13:53:33 +0000956 return NULL;
957
Miss Islington (bot)820219f2018-05-15 13:56:28 -0700958 if (module_globals && module_globals != Py_None) {
959 if (!PyDict_Check(module_globals)) {
960 PyErr_Format(PyExc_TypeError,
961 "module_globals must be a dict, not '%.200s'",
962 Py_TYPE(module_globals)->tp_name);
963 return NULL;
964 }
965
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200966 source_line = get_source_line(module_globals, lineno);
967 if (source_line == NULL && PyErr_Occurred()) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000968 return NULL;
969 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000970 }
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200971 returned = warn_explicit(category, message, filename, lineno, module,
972 registry, source_line, sourceobj);
973 Py_XDECREF(source_line);
974 return returned;
Christian Heimes33fe8092008-04-13 13:53:33 +0000975}
976
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200977static PyObject *
978warnings_filters_mutated(PyObject *self, PyObject *args)
979{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600980 _PyRuntime.warnings.filters_version++;
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200981 Py_RETURN_NONE;
982}
983
Christian Heimes33fe8092008-04-13 13:53:33 +0000984
985/* Function to issue a warning message; may raise an exception. */
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000986
987static int
988warn_unicode(PyObject *category, PyObject *message,
Victor Stinner914cde82016-03-19 01:03:51 +0100989 Py_ssize_t stack_level, PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000990{
991 PyObject *res;
Christian Heimes33fe8092008-04-13 13:53:33 +0000992
993 if (category == NULL)
994 category = PyExc_RuntimeWarning;
995
Victor Stinner914cde82016-03-19 01:03:51 +0100996 res = do_warn(message, category, stack_level, source);
Christian Heimes33fe8092008-04-13 13:53:33 +0000997 if (res == NULL)
998 return -1;
999 Py_DECREF(res);
1000
1001 return 0;
1002}
1003
Victor Stinner914cde82016-03-19 01:03:51 +01001004static int
1005_PyErr_WarnFormatV(PyObject *source,
1006 PyObject *category, Py_ssize_t stack_level,
1007 const char *format, va_list vargs)
1008{
1009 PyObject *message;
1010 int res;
1011
1012 message = PyUnicode_FromFormatV(format, vargs);
1013 if (message == NULL)
1014 return -1;
1015
1016 res = warn_unicode(category, message, stack_level, source);
1017 Py_DECREF(message);
1018 return res;
1019}
1020
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001021int
1022PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level,
1023 const char *format, ...)
1024{
Victor Stinner914cde82016-03-19 01:03:51 +01001025 int res;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001026 va_list vargs;
1027
1028#ifdef HAVE_STDARG_PROTOTYPES
1029 va_start(vargs, format);
1030#else
1031 va_start(vargs);
1032#endif
Victor Stinner914cde82016-03-19 01:03:51 +01001033 res = _PyErr_WarnFormatV(NULL, category, stack_level, format, vargs);
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001034 va_end(vargs);
Victor Stinner914cde82016-03-19 01:03:51 +01001035 return res;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001036}
1037
1038int
Victor Stinner914cde82016-03-19 01:03:51 +01001039PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level,
1040 const char *format, ...)
1041{
1042 int res;
1043 va_list vargs;
1044
1045#ifdef HAVE_STDARG_PROTOTYPES
1046 va_start(vargs, format);
1047#else
1048 va_start(vargs);
1049#endif
1050 res = _PyErr_WarnFormatV(source, PyExc_ResourceWarning,
1051 stack_level, format, vargs);
1052 va_end(vargs);
1053 return res;
1054}
1055
1056
1057int
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001058PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
1059{
1060 int ret;
1061 PyObject *message = PyUnicode_FromString(text);
1062 if (message == NULL)
1063 return -1;
Victor Stinner914cde82016-03-19 01:03:51 +01001064 ret = warn_unicode(category, message, stack_level, NULL);
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001065 Py_DECREF(message);
1066 return ret;
1067}
1068
Ezio Melotti42da6632011-03-15 05:18:48 +02001069/* PyErr_Warn is only for backwards compatibility and will be removed.
Christian Heimes33fe8092008-04-13 13:53:33 +00001070 Use PyErr_WarnEx instead. */
1071
1072#undef PyErr_Warn
1073
1074PyAPI_FUNC(int)
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001075PyErr_Warn(PyObject *category, const char *text)
Christian Heimes33fe8092008-04-13 13:53:33 +00001076{
1077 return PyErr_WarnEx(category, text, 1);
1078}
1079
1080/* Warning with explicit origin */
1081int
Victor Stinner14e461d2013-08-26 22:28:21 +02001082PyErr_WarnExplicitObject(PyObject *category, PyObject *message,
1083 PyObject *filename, int lineno,
1084 PyObject *module, PyObject *registry)
1085{
1086 PyObject *res;
1087 if (category == NULL)
1088 category = PyExc_RuntimeWarning;
1089 res = warn_explicit(category, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +01001090 module, registry, NULL, NULL);
Victor Stinner14e461d2013-08-26 22:28:21 +02001091 if (res == NULL)
1092 return -1;
1093 Py_DECREF(res);
1094 return 0;
1095}
1096
1097int
Christian Heimes33fe8092008-04-13 13:53:33 +00001098PyErr_WarnExplicit(PyObject *category, const char *text,
1099 const char *filename_str, int lineno,
1100 const char *module_str, PyObject *registry)
1101{
Christian Heimes33fe8092008-04-13 13:53:33 +00001102 PyObject *message = PyUnicode_FromString(text);
Victor Stinnercb428f02010-12-27 20:10:36 +00001103 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
Christian Heimes33fe8092008-04-13 13:53:33 +00001104 PyObject *module = NULL;
1105 int ret = -1;
1106
1107 if (message == NULL || filename == NULL)
1108 goto exit;
1109 if (module_str != NULL) {
1110 module = PyUnicode_FromString(module_str);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001111 if (module == NULL)
1112 goto exit;
Christian Heimes33fe8092008-04-13 13:53:33 +00001113 }
1114
Victor Stinner14e461d2013-08-26 22:28:21 +02001115 ret = PyErr_WarnExplicitObject(category, message, filename, lineno,
1116 module, registry);
Christian Heimes33fe8092008-04-13 13:53:33 +00001117
1118 exit:
1119 Py_XDECREF(message);
1120 Py_XDECREF(module);
1121 Py_XDECREF(filename);
1122 return ret;
1123}
1124
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001125int
1126PyErr_WarnExplicitFormat(PyObject *category,
1127 const char *filename_str, int lineno,
1128 const char *module_str, PyObject *registry,
1129 const char *format, ...)
1130{
1131 PyObject *message;
1132 PyObject *module = NULL;
1133 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
1134 int ret = -1;
1135 va_list vargs;
1136
1137 if (filename == NULL)
1138 goto exit;
1139 if (module_str != NULL) {
1140 module = PyUnicode_FromString(module_str);
1141 if (module == NULL)
1142 goto exit;
1143 }
1144
1145#ifdef HAVE_STDARG_PROTOTYPES
1146 va_start(vargs, format);
1147#else
1148 va_start(vargs);
1149#endif
1150 message = PyUnicode_FromFormatV(format, vargs);
1151 if (message != NULL) {
1152 PyObject *res;
1153 res = warn_explicit(category, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +01001154 module, registry, NULL, NULL);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001155 Py_DECREF(message);
1156 if (res != NULL) {
1157 Py_DECREF(res);
1158 ret = 0;
1159 }
1160 }
1161 va_end(vargs);
1162exit:
1163 Py_XDECREF(module);
1164 Py_XDECREF(filename);
1165 return ret;
1166}
1167
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001168void
1169_PyErr_WarnUnawaitedCoroutine(PyObject *coro)
1170{
1171 /* First, we attempt to funnel the warning through
1172 warnings._warn_unawaited_coroutine.
1173
1174 This could raise an exception, due to:
1175 - a bug
1176 - some kind of shutdown-related brokenness
1177 - succeeding, but with an "error" warning filter installed, so the
1178 warning is converted into a RuntimeWarning exception
1179
1180 In the first two cases, we want to print the error (so we know what it
1181 is!), and then print a warning directly as a fallback. In the last
1182 case, we want to print the error (since it's the warning!), but *not*
1183 do a fallback. And after we print the error we can't check for what
1184 type of error it was (because PyErr_WriteUnraisable clears it), so we
1185 need a flag to keep track.
1186
1187 Since this is called from __del__ context, it's careful to never raise
1188 an exception.
1189 */
1190 _Py_IDENTIFIER(_warn_unawaited_coroutine);
1191 int warned = 0;
1192 PyObject *fn = get_warnings_attr(&PyId__warn_unawaited_coroutine, 1);
1193 if (fn) {
1194 PyObject *res = PyObject_CallFunctionObjArgs(fn, coro, NULL);
1195 Py_DECREF(fn);
1196 if (res || PyErr_ExceptionMatches(PyExc_RuntimeWarning)) {
1197 warned = 1;
1198 }
1199 Py_XDECREF(res);
1200 }
1201
1202 if (PyErr_Occurred()) {
1203 PyErr_WriteUnraisable(coro);
1204 }
1205 if (!warned) {
Yury Selivanov35103342018-01-21 20:47:04 -05001206 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1207 "coroutine '%.50S' was never awaited",
1208 ((PyCoroObject *)coro)->cr_qualname) < 0)
1209 {
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001210 PyErr_WriteUnraisable(coro);
1211 }
1212 }
1213}
Christian Heimes33fe8092008-04-13 13:53:33 +00001214
Christian Heimes33fe8092008-04-13 13:53:33 +00001215PyDoc_STRVAR(warn_explicit_doc,
1216"Low-level inferface to warnings functionality.");
1217
1218static PyMethodDef warnings_functions[] = {
Victor Stinner22f18752016-12-09 18:08:18 +01001219 WARNINGS_WARN_METHODDEF
Christian Heimes33fe8092008-04-13 13:53:33 +00001220 {"warn_explicit", (PyCFunction)warnings_warn_explicit,
1221 METH_VARARGS | METH_KEYWORDS, warn_explicit_doc},
Antoine Pitroucb0a0062014-09-18 02:40:46 +02001222 {"_filters_mutated", (PyCFunction)warnings_filters_mutated, METH_NOARGS,
1223 NULL},
Christian Heimes1a8501c2008-10-02 19:56:01 +00001224 /* XXX(brett.cannon): add showwarning? */
1225 /* XXX(brett.cannon): Reasonable to add formatwarning? */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 {NULL, NULL} /* sentinel */
Christian Heimes33fe8092008-04-13 13:53:33 +00001227};
1228
1229
Victor Stinner747f48e2017-12-12 22:59:48 +01001230#ifndef Py_DEBUG
Christian Heimes33fe8092008-04-13 13:53:33 +00001231static PyObject *
Nick Coghlan9b997472018-01-08 12:45:02 +10001232create_filter(PyObject *category, _Py_Identifier *id, const char *modname)
Christian Heimes33fe8092008-04-13 13:53:33 +00001233{
Nick Coghlan9b997472018-01-08 12:45:02 +10001234 PyObject *modname_obj = NULL;
Victor Stinner82656272017-11-22 23:51:42 +01001235 PyObject *action_str = _PyUnicode_FromId(id);
1236 if (action_str == NULL) {
1237 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001238 }
1239
Nick Coghlan9b997472018-01-08 12:45:02 +10001240 /* Default to "no module name" for initial filter set */
1241 if (modname != NULL) {
1242 modname_obj = PyUnicode_InternFromString(modname);
1243 if (modname_obj == NULL) {
1244 return NULL;
1245 }
1246 } else {
1247 modname_obj = Py_None;
1248 }
1249
Christian Heimes33fe8092008-04-13 13:53:33 +00001250 /* This assumes the line number is zero for now. */
Victor Stinner82656272017-11-22 23:51:42 +01001251 return PyTuple_Pack(5, action_str, Py_None,
Nick Coghlan9b997472018-01-08 12:45:02 +10001252 category, modname_obj, _PyLong_Zero);
Christian Heimes33fe8092008-04-13 13:53:33 +00001253}
Victor Stinner747f48e2017-12-12 22:59:48 +01001254#endif
1255
Christian Heimes33fe8092008-04-13 13:53:33 +00001256
1257static PyObject *
Victor Stinner5d862462017-12-19 11:35:58 +01001258init_filters(void)
Christian Heimes33fe8092008-04-13 13:53:33 +00001259{
Victor Stinner747f48e2017-12-12 22:59:48 +01001260#ifdef Py_DEBUG
1261 /* Py_DEBUG builds show all warnings by default */
1262 return PyList_New(0);
1263#else
1264 /* Other builds ignore a number of warning categories by default */
Nick Coghlan9b997472018-01-08 12:45:02 +10001265 PyObject *filters = PyList_New(5);
Victor Stinner747f48e2017-12-12 22:59:48 +01001266 if (filters == NULL) {
Christian Heimes33fe8092008-04-13 13:53:33 +00001267 return NULL;
Victor Stinner747f48e2017-12-12 22:59:48 +01001268 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001269
Victor Stinnerb98f1712017-11-23 17:13:44 +01001270 size_t pos = 0; /* Post-incremented in each use. */
Victor Stinner747f48e2017-12-12 22:59:48 +01001271 PyList_SET_ITEM(filters, pos++,
Nick Coghlan9b997472018-01-08 12:45:02 +10001272 create_filter(PyExc_DeprecationWarning, &PyId_default, "__main__"));
Victor Stinner747f48e2017-12-12 22:59:48 +01001273 PyList_SET_ITEM(filters, pos++,
Nick Coghlan9b997472018-01-08 12:45:02 +10001274 create_filter(PyExc_DeprecationWarning, &PyId_ignore, NULL));
Victor Stinner747f48e2017-12-12 22:59:48 +01001275 PyList_SET_ITEM(filters, pos++,
Nick Coghlan9b997472018-01-08 12:45:02 +10001276 create_filter(PyExc_PendingDeprecationWarning, &PyId_ignore, NULL));
Victor Stinner747f48e2017-12-12 22:59:48 +01001277 PyList_SET_ITEM(filters, pos++,
Nick Coghlan9b997472018-01-08 12:45:02 +10001278 create_filter(PyExc_ImportWarning, &PyId_ignore, NULL));
1279 PyList_SET_ITEM(filters, pos++,
1280 create_filter(PyExc_ResourceWarning, &PyId_ignore, NULL));
Victor Stinner09f3a8a2017-11-20 17:32:40 -08001281
Victor Stinnerb98f1712017-11-23 17:13:44 +01001282 for (size_t x = 0; x < pos; x++) {
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001283 if (PyList_GET_ITEM(filters, x) == NULL) {
1284 Py_DECREF(filters);
1285 return NULL;
1286 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001287 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001288 return filters;
Victor Stinner747f48e2017-12-12 22:59:48 +01001289#endif
Christian Heimes33fe8092008-04-13 13:53:33 +00001290}
1291
Martin v. Löwis1a214512008-06-11 05:26:20 +00001292static struct PyModuleDef warningsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 PyModuleDef_HEAD_INIT,
1294 MODULE_NAME,
1295 warnings__doc__,
1296 0,
1297 warnings_functions,
1298 NULL,
1299 NULL,
1300 NULL,
1301 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001302};
1303
Christian Heimes33fe8092008-04-13 13:53:33 +00001304
Victor Stinner5d862462017-12-19 11:35:58 +01001305PyMODINIT_FUNC
1306_PyWarnings_Init(void)
Christian Heimes33fe8092008-04-13 13:53:33 +00001307{
Brett Cannon0759dd62009-04-01 18:13:07 +00001308 PyObject *m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001309
Martin v. Löwis1a214512008-06-11 05:26:20 +00001310 m = PyModule_Create(&warningsmodule);
Christian Heimes33fe8092008-04-13 13:53:33 +00001311 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001312 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001313
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001314 if (_PyRuntime.warnings.filters == NULL) {
Victor Stinner5d862462017-12-19 11:35:58 +01001315 _PyRuntime.warnings.filters = init_filters();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001316 if (_PyRuntime.warnings.filters == NULL)
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001317 return NULL;
1318 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001319 Py_INCREF(_PyRuntime.warnings.filters);
1320 if (PyModule_AddObject(m, "filters", _PyRuntime.warnings.filters) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001321 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001322
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001323 if (_PyRuntime.warnings.once_registry == NULL) {
1324 _PyRuntime.warnings.once_registry = PyDict_New();
1325 if (_PyRuntime.warnings.once_registry == NULL)
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001326 return NULL;
1327 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001328 Py_INCREF(_PyRuntime.warnings.once_registry);
1329 if (PyModule_AddObject(m, "_onceregistry",
1330 _PyRuntime.warnings.once_registry) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001331 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001332
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001333 if (_PyRuntime.warnings.default_action == NULL) {
1334 _PyRuntime.warnings.default_action = PyUnicode_FromString("default");
1335 if (_PyRuntime.warnings.default_action == NULL)
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001336 return NULL;
1337 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001338 Py_INCREF(_PyRuntime.warnings.default_action);
1339 if (PyModule_AddObject(m, "_defaultaction",
1340 _PyRuntime.warnings.default_action) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001341 return NULL;
Antoine Pitroucb0a0062014-09-18 02:40:46 +02001342
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001343 _PyRuntime.warnings.filters_version = 0;
Martin v. Löwis1a214512008-06-11 05:26:20 +00001344 return m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001345}