blob: 0568af4df5a80b200c5d91ba8c1f5d435f27f3a6 [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)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600259 || PyLong_AsLong(version_obj) != _PyRuntime.warnings.filters_version) {
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200260 PyDict_Clear(registry);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600261 version_obj = PyLong_FromLong(_PyRuntime.warnings.filters_version);
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200262 if (version_obj == NULL)
263 return -1;
264 if (_PyDict_SetItemId(registry, &PyId_version, version_obj) < 0) {
265 Py_DECREF(version_obj);
266 return -1;
267 }
268 Py_DECREF(version_obj);
269 }
270 else {
271 already_warned = PyDict_GetItem(registry, key);
272 if (already_warned != NULL) {
273 int rc = PyObject_IsTrue(already_warned);
274 if (rc != 0)
275 return rc;
276 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000277 }
278
279 /* This warning wasn't found in the registry, set it. */
280 if (should_set)
281 return PyDict_SetItem(registry, key, Py_True);
282 return 0;
283}
284
285/* New reference. */
286static PyObject *
287normalize_module(PyObject *filename)
288{
289 PyObject *module;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100290 int kind;
291 void *data;
Christian Heimes33fe8092008-04-13 13:53:33 +0000292 Py_ssize_t len;
293
Victor Stinner9e30aa52011-11-21 02:49:52 +0100294 len = PyUnicode_GetLength(filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000295 if (len < 0)
296 return NULL;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100297
298 if (len == 0)
299 return PyUnicode_FromString("<unknown>");
300
301 kind = PyUnicode_KIND(filename);
302 data = PyUnicode_DATA(filename);
303
304 /* if filename.endswith(".py"): */
Christian Heimes33fe8092008-04-13 13:53:33 +0000305 if (len >= 3 &&
Victor Stinnera4c704b2013-10-29 23:43:41 +0100306 PyUnicode_READ(kind, data, len-3) == '.' &&
307 PyUnicode_READ(kind, data, len-2) == 'p' &&
308 PyUnicode_READ(kind, data, len-1) == 'y')
309 {
Victor Stinner9e30aa52011-11-21 02:49:52 +0100310 module = PyUnicode_Substring(filename, 0, len-3);
Christian Heimes33fe8092008-04-13 13:53:33 +0000311 }
312 else {
313 module = filename;
314 Py_INCREF(module);
315 }
316 return module;
317}
318
319static int
320update_registry(PyObject *registry, PyObject *text, PyObject *category,
321 int add_zero)
322{
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300323 PyObject *altkey;
Christian Heimes33fe8092008-04-13 13:53:33 +0000324 int rc;
325
Serhiy Storchakaba85d692017-03-30 09:09:41 +0300326 if (add_zero)
327 altkey = PyTuple_Pack(3, text, category, _PyLong_Zero);
Christian Heimes33fe8092008-04-13 13:53:33 +0000328 else
329 altkey = PyTuple_Pack(2, text, category);
330
331 rc = already_warned(registry, altkey, 1);
Christian Heimes33fe8092008-04-13 13:53:33 +0000332 Py_XDECREF(altkey);
333 return rc;
334}
335
336static void
Victor Stinner914cde82016-03-19 01:03:51 +0100337show_warning(PyObject *filename, int lineno, PyObject *text,
338 PyObject *category, PyObject *sourceline)
Christian Heimes33fe8092008-04-13 13:53:33 +0000339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 PyObject *f_stderr;
341 PyObject *name;
Christian Heimes33fe8092008-04-13 13:53:33 +0000342 char lineno_str[128];
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200343 _Py_IDENTIFIER(__name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000344
345 PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);
346
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200347 name = _PyObject_GetAttrId(category, &PyId___name__);
Christian Heimes33fe8092008-04-13 13:53:33 +0000348 if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */
Victor Stinnerae233ea2013-10-31 14:51:38 +0100349 goto error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000350
Victor Stinnerbd303c12013-11-07 23:07:29 +0100351 f_stderr = _PySys_GetObjectId(&PyId_stderr);
Christian Heimes33fe8092008-04-13 13:53:33 +0000352 if (f_stderr == NULL) {
353 fprintf(stderr, "lost sys.stderr\n");
Victor Stinnerae233ea2013-10-31 14:51:38 +0100354 goto error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000355 }
356
357 /* Print "filename:lineno: category: text\n" */
Victor Stinnerae233ea2013-10-31 14:51:38 +0100358 if (PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW) < 0)
359 goto error;
360 if (PyFile_WriteString(lineno_str, f_stderr) < 0)
361 goto error;
362 if (PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW) < 0)
363 goto error;
364 if (PyFile_WriteString(": ", f_stderr) < 0)
365 goto error;
366 if (PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW) < 0)
367 goto error;
368 if (PyFile_WriteString("\n", f_stderr) < 0)
369 goto error;
370 Py_CLEAR(name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000371
372 /* Print " source_line\n" */
Christian Heimes33fe8092008-04-13 13:53:33 +0000373 if (sourceline) {
Victor Stinnera4c704b2013-10-29 23:43:41 +0100374 int kind;
375 void *data;
376 Py_ssize_t i, len;
377 Py_UCS4 ch;
378 PyObject *truncated;
Christian Heimes33fe8092008-04-13 13:53:33 +0000379
Victor Stinnera4c704b2013-10-29 23:43:41 +0100380 if (PyUnicode_READY(sourceline) < 1)
381 goto error;
382
383 kind = PyUnicode_KIND(sourceline);
384 data = PyUnicode_DATA(sourceline);
385 len = PyUnicode_GET_LENGTH(sourceline);
386 for (i=0; i<len; i++) {
387 ch = PyUnicode_READ(kind, data, i);
388 if (ch != ' ' && ch != '\t' && ch != '\014')
389 break;
390 }
391
392 truncated = PyUnicode_Substring(sourceline, i, len);
393 if (truncated == NULL)
394 goto error;
395
396 PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW);
397 Py_DECREF(truncated);
Christian Heimes33fe8092008-04-13 13:53:33 +0000398 PyFile_WriteString("\n", f_stderr);
399 }
Victor Stinner78e2c982013-07-16 01:54:37 +0200400 else {
401 _Py_DisplaySourceLine(f_stderr, filename, lineno, 2);
402 }
Victor Stinnera4c704b2013-10-29 23:43:41 +0100403
404error:
Victor Stinnerae233ea2013-10-31 14:51:38 +0100405 Py_XDECREF(name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000406 PyErr_Clear();
407}
408
Victor Stinner1231a462016-03-19 00:47:17 +0100409static int
410call_show_warning(PyObject *category, PyObject *text, PyObject *message,
411 PyObject *filename, int lineno, PyObject *lineno_obj,
Victor Stinner914cde82016-03-19 01:03:51 +0100412 PyObject *sourceline, PyObject *source)
Victor Stinner1231a462016-03-19 00:47:17 +0100413{
414 PyObject *show_fn, *msg, *res, *warnmsg_cls = NULL;
Victor Stinner82656272017-11-22 23:51:42 +0100415 _Py_IDENTIFIER(_showwarnmsg);
416 _Py_IDENTIFIER(WarningMessage);
Victor Stinner1231a462016-03-19 00:47:17 +0100417
Victor Stinnere98445a2016-03-23 00:54:48 +0100418 /* If the source parameter is set, try to get the Python implementation.
419 The Python implementation is able to log the traceback where the source
luzpaza5293b42017-11-05 07:37:50 -0600420 was allocated, whereas the C implementation doesn't. */
Victor Stinner82656272017-11-22 23:51:42 +0100421 show_fn = get_warnings_attr(&PyId__showwarnmsg, source != NULL);
Victor Stinner1231a462016-03-19 00:47:17 +0100422 if (show_fn == NULL) {
423 if (PyErr_Occurred())
424 return -1;
425 show_warning(filename, lineno, text, category, sourceline);
426 return 0;
427 }
428
429 if (!PyCallable_Check(show_fn)) {
430 PyErr_SetString(PyExc_TypeError,
431 "warnings._showwarnmsg() must be set to a callable");
432 goto error;
433 }
434
Victor Stinner82656272017-11-22 23:51:42 +0100435 warnmsg_cls = get_warnings_attr(&PyId_WarningMessage, 0);
Victor Stinner1231a462016-03-19 00:47:17 +0100436 if (warnmsg_cls == NULL) {
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200437 if (!PyErr_Occurred()) {
438 PyErr_SetString(PyExc_RuntimeError,
439 "unable to get warnings.WarningMessage");
440 }
Victor Stinner1231a462016-03-19 00:47:17 +0100441 goto error;
442 }
443
444 msg = PyObject_CallFunctionObjArgs(warnmsg_cls, message, category,
Victor Stinner914cde82016-03-19 01:03:51 +0100445 filename, lineno_obj, Py_None, Py_None, source,
Victor Stinner1231a462016-03-19 00:47:17 +0100446 NULL);
447 Py_DECREF(warnmsg_cls);
448 if (msg == NULL)
449 goto error;
450
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100451 res = PyObject_CallFunctionObjArgs(show_fn, msg, NULL);
Victor Stinner1231a462016-03-19 00:47:17 +0100452 Py_DECREF(show_fn);
453 Py_DECREF(msg);
454
455 if (res == NULL)
456 return -1;
457
458 Py_DECREF(res);
459 return 0;
460
461error:
462 Py_XDECREF(show_fn);
463 return -1;
464}
465
Christian Heimes33fe8092008-04-13 13:53:33 +0000466static PyObject *
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467warn_explicit(PyObject *category, PyObject *message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000468 PyObject *filename, int lineno,
Victor Stinner914cde82016-03-19 01:03:51 +0100469 PyObject *module, PyObject *registry, PyObject *sourceline,
470 PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000471{
472 PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL;
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400473 PyObject *item = NULL;
Victor Stinnera4c704b2013-10-29 23:43:41 +0100474 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000475 int rc;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476
Victor Stinnerdcdd05b2013-11-01 00:55:30 +0100477 /* module can be None if a warning is emitted late during Python shutdown.
478 In this case, the Python warnings module was probably unloaded, filters
479 are no more available to choose as action. It is safer to ignore the
480 warning and do nothing. */
481 if (module == Py_None)
482 Py_RETURN_NONE;
483
Brett Cannondb734912008-06-27 00:52:15 +0000484 if (registry && !PyDict_Check(registry) && (registry != Py_None)) {
Oren Milman252033d2017-09-11 09:28:39 +0300485 PyErr_SetString(PyExc_TypeError, "'registry' must be a dict or None");
Brett Cannondb734912008-06-27 00:52:15 +0000486 return NULL;
487 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000488
489 /* Normalize module. */
490 if (module == NULL) {
491 module = normalize_module(filename);
492 if (module == NULL)
493 return NULL;
494 }
495 else
496 Py_INCREF(module);
497
498 /* Normalize message. */
499 Py_INCREF(message); /* DECREF'ed in cleanup. */
500 rc = PyObject_IsInstance(message, PyExc_Warning);
501 if (rc == -1) {
502 goto cleanup;
503 }
504 if (rc == 1) {
505 text = PyObject_Str(message);
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000506 if (text == NULL)
507 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000508 category = (PyObject*)message->ob_type;
509 }
510 else {
511 text = message;
Victor Stinner7bfb42d2016-12-05 17:04:32 +0100512 message = PyObject_CallFunctionObjArgs(category, message, NULL);
Brett Cannondb734912008-06-27 00:52:15 +0000513 if (message == NULL)
514 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000515 }
516
517 lineno_obj = PyLong_FromLong(lineno);
518 if (lineno_obj == NULL)
519 goto cleanup;
520
Victor Stinner22f18752016-12-09 18:08:18 +0100521 if (source == Py_None) {
522 source = NULL;
523 }
524
Christian Heimes33fe8092008-04-13 13:53:33 +0000525 /* Create key. */
526 key = PyTuple_Pack(3, text, category, lineno_obj);
527 if (key == NULL)
528 goto cleanup;
529
Brett Cannondb734912008-06-27 00:52:15 +0000530 if ((registry != NULL) && (registry != Py_None)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000531 rc = already_warned(registry, key, 0);
532 if (rc == -1)
533 goto cleanup;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 else if (rc == 1)
Christian Heimes33fe8092008-04-13 13:53:33 +0000535 goto return_none;
536 /* Else this warning hasn't been generated before. */
537 }
538
539 action = get_filter(category, text, lineno, module, &item);
540 if (action == NULL)
541 goto cleanup;
542
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200543 if (_PyUnicode_EqualToASCIIString(action, "error")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000544 PyErr_SetObject(category, message);
545 goto cleanup;
546 }
547
Victor Stinnerc9758782017-11-27 16:57:07 +0100548 if (_PyUnicode_EqualToASCIIString(action, "ignore")) {
549 goto return_none;
550 }
551
Christian Heimes33fe8092008-04-13 13:53:33 +0000552 /* Store in the registry that we've been here, *except* when the action
553 is "always". */
554 rc = 0;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200555 if (!_PyUnicode_EqualToASCIIString(action, "always")) {
Brett Cannondb734912008-06-27 00:52:15 +0000556 if (registry != NULL && registry != Py_None &&
Victor Stinnerc9758782017-11-27 16:57:07 +0100557 PyDict_SetItem(registry, key, Py_True) < 0)
558 {
Christian Heimes33fe8092008-04-13 13:53:33 +0000559 goto cleanup;
Victor Stinnerc9758782017-11-27 16:57:07 +0100560 }
561
562 if (_PyUnicode_EqualToASCIIString(action, "once")) {
Brett Cannondb734912008-06-27 00:52:15 +0000563 if (registry == NULL || registry == Py_None) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000564 registry = get_once_registry();
565 if (registry == NULL)
566 goto cleanup;
567 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600568 /* _PyRuntime.warnings.once_registry[(text, category)] = 1 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000570 }
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200571 else if (_PyUnicode_EqualToASCIIString(action, "module")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000572 /* registry[(text, category, 0)] = 1 */
Brett Cannondb734912008-06-27 00:52:15 +0000573 if (registry != NULL && registry != Py_None)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 rc = update_registry(registry, text, category, 0);
Christian Heimes33fe8092008-04-13 13:53:33 +0000575 }
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200576 else if (!_PyUnicode_EqualToASCIIString(action, "default")) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000577 PyErr_Format(PyExc_RuntimeError,
Victor Stinnera4c704b2013-10-29 23:43:41 +0100578 "Unrecognized action (%R) in warnings.filters:\n %R",
579 action, item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000580 goto cleanup;
581 }
582 }
583
Christian Heimes1a8501c2008-10-02 19:56:01 +0000584 if (rc == 1) /* Already warned for this module. */
Christian Heimes33fe8092008-04-13 13:53:33 +0000585 goto return_none;
586 if (rc == 0) {
Victor Stinner1231a462016-03-19 00:47:17 +0100587 if (call_show_warning(category, text, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +0100588 lineno_obj, sourceline, source) < 0)
Victor Stinner1231a462016-03-19 00:47:17 +0100589 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000590 }
591 else /* if (rc == -1) */
592 goto cleanup;
593
594 return_none:
595 result = Py_None;
596 Py_INCREF(result);
597
598 cleanup:
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400599 Py_XDECREF(item);
Christian Heimes33fe8092008-04-13 13:53:33 +0000600 Py_XDECREF(key);
601 Py_XDECREF(text);
602 Py_XDECREF(lineno_obj);
603 Py_DECREF(module);
Brett Cannondb734912008-06-27 00:52:15 +0000604 Py_XDECREF(message);
Christian Heimes33fe8092008-04-13 13:53:33 +0000605 return result; /* Py_None or NULL. */
606}
607
Larry Hastings714e4932015-09-06 00:39:37 -0700608static int
609is_internal_frame(PyFrameObject *frame)
610{
611 static PyObject *importlib_string = NULL;
612 static PyObject *bootstrap_string = NULL;
613 PyObject *filename;
614 int contains;
615
616 if (importlib_string == NULL) {
617 importlib_string = PyUnicode_FromString("importlib");
618 if (importlib_string == NULL) {
619 return 0;
620 }
621
622 bootstrap_string = PyUnicode_FromString("_bootstrap");
623 if (bootstrap_string == NULL) {
624 Py_DECREF(importlib_string);
625 return 0;
626 }
627 Py_INCREF(importlib_string);
628 Py_INCREF(bootstrap_string);
629 }
630
631 if (frame == NULL || frame->f_code == NULL ||
632 frame->f_code->co_filename == NULL) {
633 return 0;
634 }
635 filename = frame->f_code->co_filename;
636 if (!PyUnicode_Check(filename)) {
637 return 0;
638 }
639 contains = PyUnicode_Contains(filename, importlib_string);
640 if (contains < 0) {
641 return 0;
642 }
643 else if (contains > 0) {
644 contains = PyUnicode_Contains(filename, bootstrap_string);
645 if (contains < 0) {
646 return 0;
647 }
648 else if (contains > 0) {
649 return 1;
650 }
651 }
652
653 return 0;
654}
655
656static PyFrameObject *
657next_external_frame(PyFrameObject *frame)
658{
659 do {
660 frame = frame->f_back;
661 } while (frame != NULL && is_internal_frame(frame));
662
663 return frame;
664}
665
Christian Heimes33fe8092008-04-13 13:53:33 +0000666/* filename, module, and registry are new refs, globals is borrowed */
667/* Returns 0 on error (no new refs), 1 on success */
668static int
669setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
670 PyObject **module, PyObject **registry)
671{
672 PyObject *globals;
673
674 /* Setup globals and lineno. */
675 PyFrameObject *f = PyThreadState_GET()->frame;
Larry Hastings714e4932015-09-06 00:39:37 -0700676 // Stack level comparisons to Python code is off by one as there is no
677 // warnings-related stack level to avoid.
678 if (stack_level <= 0 || is_internal_frame(f)) {
679 while (--stack_level > 0 && f != NULL) {
680 f = f->f_back;
681 }
682 }
683 else {
684 while (--stack_level > 0 && f != NULL) {
685 f = next_external_frame(f);
686 }
687 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000688
689 if (f == NULL) {
690 globals = PyThreadState_Get()->interp->sysdict;
691 *lineno = 1;
692 }
693 else {
694 globals = f->f_globals;
Alexandre Vassalotti7b82b402009-07-21 04:30:03 +0000695 *lineno = PyFrame_GetLineNumber(f);
Christian Heimes33fe8092008-04-13 13:53:33 +0000696 }
697
698 *module = NULL;
699
700 /* Setup registry. */
701 assert(globals != NULL);
702 assert(PyDict_Check(globals));
703 *registry = PyDict_GetItemString(globals, "__warningregistry__");
704 if (*registry == NULL) {
705 int rc;
706
707 *registry = PyDict_New();
708 if (*registry == NULL)
709 return 0;
710
711 rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
712 if (rc < 0)
713 goto handle_error;
714 }
715 else
716 Py_INCREF(*registry);
717
718 /* Setup module. */
719 *module = PyDict_GetItemString(globals, "__name__");
Oren Milman5d3e8002017-09-24 21:28:42 +0300720 if (*module == Py_None || (*module != NULL && PyUnicode_Check(*module))) {
721 Py_INCREF(*module);
722 }
723 else {
Christian Heimes33fe8092008-04-13 13:53:33 +0000724 *module = PyUnicode_FromString("<string>");
725 if (*module == NULL)
726 goto handle_error;
727 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000728
729 /* Setup filename. */
730 *filename = PyDict_GetItemString(globals, "__file__");
Victor Stinner8b0508e2011-07-04 02:43:09 +0200731 if (*filename != NULL && PyUnicode_Check(*filename)) {
Victor Stinnerb62a7b22011-10-06 02:34:51 +0200732 Py_ssize_t len;
733 int kind;
734 void *data;
735
736 if (PyUnicode_READY(*filename))
737 goto handle_error;
738
Victor Stinner9e30aa52011-11-21 02:49:52 +0100739 len = PyUnicode_GetLength(*filename);
Victor Stinnerb62a7b22011-10-06 02:34:51 +0200740 kind = PyUnicode_KIND(*filename);
741 data = PyUnicode_DATA(*filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000742
Benjamin Peterson21e0da22012-01-11 21:00:42 -0500743#define ascii_lower(c) ((c <= 127) ? Py_TOLOWER(c) : 0)
Brett Cannonf299abd2015-04-13 14:21:02 -0400744 /* if filename.lower().endswith(".pyc"): */
Christian Heimes33fe8092008-04-13 13:53:33 +0000745 if (len >= 4 &&
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200746 PyUnicode_READ(kind, data, len-4) == '.' &&
Benjamin Peterson21e0da22012-01-11 21:00:42 -0500747 ascii_lower(PyUnicode_READ(kind, data, len-3)) == 'p' &&
748 ascii_lower(PyUnicode_READ(kind, data, len-2)) == 'y' &&
Brett Cannonf299abd2015-04-13 14:21:02 -0400749 ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'c')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000750 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200751 *filename = PyUnicode_Substring(*filename, 0,
752 PyUnicode_GET_LENGTH(*filename)-1);
Victor Stinner2e5f1172010-08-08 22:12:45 +0000753 if (*filename == NULL)
754 goto handle_error;
755 }
756 else
Christian Heimes33fe8092008-04-13 13:53:33 +0000757 Py_INCREF(*filename);
758 }
759 else {
Benjamin Petersonbb4a7472011-07-04 22:27:16 -0500760 *filename = NULL;
Serhiy Storchakaf4934ea2016-11-16 10:17:58 +0200761 if (*module != Py_None && _PyUnicode_EqualToASCIIString(*module, "__main__")) {
Victor Stinnerbd303c12013-11-07 23:07:29 +0100762 PyObject *argv = _PySys_GetObjectId(&PyId_argv);
Victor Stinnerce5f4fb2013-10-28 18:47:22 +0100763 /* PyList_Check() is needed because sys.argv is set to None during
764 Python finalization */
765 if (argv != NULL && PyList_Check(argv) && PyList_Size(argv) > 0) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000766 int is_true;
Christian Heimes33fe8092008-04-13 13:53:33 +0000767 *filename = PyList_GetItem(argv, 0);
768 Py_INCREF(*filename);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000769 /* If sys.argv[0] is false, then use '__main__'. */
770 is_true = PyObject_IsTrue(*filename);
771 if (is_true < 0) {
772 Py_DECREF(*filename);
773 goto handle_error;
774 }
775 else if (!is_true) {
Serhiy Storchaka57a01d32016-04-10 18:05:40 +0300776 Py_SETREF(*filename, PyUnicode_FromString("__main__"));
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000777 if (*filename == NULL)
778 goto handle_error;
779 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000780 }
781 else {
782 /* embedded interpreters don't have sys.argv, see bug #839151 */
783 *filename = PyUnicode_FromString("__main__");
Victor Stinner856f45f2013-10-30 00:04:59 +0100784 if (*filename == NULL)
785 goto handle_error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000786 }
787 }
788 if (*filename == NULL) {
789 *filename = *module;
790 Py_INCREF(*filename);
791 }
792 }
793
794 return 1;
795
796 handle_error:
797 /* filename not XDECREF'ed here as there is no way to jump here with a
798 dangling reference. */
799 Py_XDECREF(*registry);
800 Py_XDECREF(*module);
801 return 0;
802}
803
804static PyObject *
805get_category(PyObject *message, PyObject *category)
806{
807 int rc;
808
809 /* Get category. */
810 rc = PyObject_IsInstance(message, PyExc_Warning);
811 if (rc == -1)
812 return NULL;
813
814 if (rc == 1)
815 category = (PyObject*)message->ob_type;
Berker Peksagd8089e02014-07-11 19:50:25 +0300816 else if (category == NULL || category == Py_None)
Christian Heimes33fe8092008-04-13 13:53:33 +0000817 category = PyExc_UserWarning;
818
819 /* Validate category. */
820 rc = PyObject_IsSubclass(category, PyExc_Warning);
Berker Peksagd8089e02014-07-11 19:50:25 +0300821 /* category is not a subclass of PyExc_Warning or
822 PyObject_IsSubclass raised an error */
823 if (rc == -1 || rc == 0) {
824 PyErr_Format(PyExc_TypeError,
825 "category must be a Warning subclass, not '%s'",
826 Py_TYPE(category)->tp_name);
Christian Heimes33fe8092008-04-13 13:53:33 +0000827 return NULL;
828 }
829
830 return category;
831}
832
833static PyObject *
Victor Stinner914cde82016-03-19 01:03:51 +0100834do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level,
835 PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000836{
837 PyObject *filename, *module, *registry, *res;
838 int lineno;
839
840 if (!setup_context(stack_level, &filename, &lineno, &module, &registry))
841 return NULL;
842
Victor Stinnerdcdd05b2013-11-01 00:55:30 +0100843 res = warn_explicit(category, message, filename, lineno, module, registry,
Victor Stinner914cde82016-03-19 01:03:51 +0100844 NULL, source);
Christian Heimes33fe8092008-04-13 13:53:33 +0000845 Py_DECREF(filename);
846 Py_DECREF(registry);
847 Py_DECREF(module);
848 return res;
849}
850
Victor Stinner22f18752016-12-09 18:08:18 +0100851/*[clinic input]
852warn as warnings_warn
853
854 message: object
855 category: object = None
856 stacklevel: Py_ssize_t = 1
857 source: object = None
858
859Issue a warning, or maybe ignore it or raise an exception.
860[clinic start generated code]*/
861
Christian Heimes33fe8092008-04-13 13:53:33 +0000862static PyObject *
Victor Stinner22f18752016-12-09 18:08:18 +0100863warnings_warn_impl(PyObject *module, PyObject *message, PyObject *category,
864 Py_ssize_t stacklevel, PyObject *source)
865/*[clinic end generated code: output=31ed5ab7d8d760b2 input=bfdf5cf99f6c4edd]*/
Christian Heimes33fe8092008-04-13 13:53:33 +0000866{
Christian Heimes33fe8092008-04-13 13:53:33 +0000867 category = get_category(message, category);
868 if (category == NULL)
869 return NULL;
Victor Stinner22f18752016-12-09 18:08:18 +0100870 return do_warn(message, category, stacklevel, source);
Christian Heimes33fe8092008-04-13 13:53:33 +0000871}
872
873static PyObject *
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200874get_source_line(PyObject *module_globals, int lineno)
875{
876 _Py_IDENTIFIER(get_source);
877 _Py_IDENTIFIER(__loader__);
878 _Py_IDENTIFIER(__name__);
879 PyObject *loader;
880 PyObject *module_name;
881 PyObject *get_source;
882 PyObject *source;
883 PyObject *source_list;
884 PyObject *source_line;
885
886 /* Check/get the requisite pieces needed for the loader. */
887 loader = _PyDict_GetItemIdWithError(module_globals, &PyId___loader__);
888 if (loader == NULL) {
889 return NULL;
890 }
891 Py_INCREF(loader);
892 module_name = _PyDict_GetItemIdWithError(module_globals, &PyId___name__);
893 if (!module_name) {
894 Py_DECREF(loader);
895 return NULL;
896 }
897 Py_INCREF(module_name);
898
899 /* Make sure the loader implements the optional get_source() method. */
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200900 (void)_PyObject_LookupAttrId(loader, &PyId_get_source, &get_source);
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200901 Py_DECREF(loader);
902 if (!get_source) {
903 Py_DECREF(module_name);
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200904 return NULL;
905 }
906 /* Call get_source() to get the source code. */
907 source = PyObject_CallFunctionObjArgs(get_source, module_name, NULL);
908 Py_DECREF(get_source);
909 Py_DECREF(module_name);
910 if (!source) {
911 return NULL;
912 }
913 if (source == Py_None) {
914 Py_DECREF(source);
915 return NULL;
916 }
917
918 /* Split the source into lines. */
919 source_list = PyUnicode_Splitlines(source, 0);
920 Py_DECREF(source);
921 if (!source_list) {
922 return NULL;
923 }
924
925 /* Get the source line. */
926 source_line = PyList_GetItem(source_list, lineno-1);
927 Py_XINCREF(source_line);
928 Py_DECREF(source_list);
929 return source_line;
930}
931
932static PyObject *
Christian Heimes33fe8092008-04-13 13:53:33 +0000933warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
934{
935 static char *kwd_list[] = {"message", "category", "filename", "lineno",
Victor Stinner914cde82016-03-19 01:03:51 +0100936 "module", "registry", "module_globals",
937 "source", 0};
Christian Heimes33fe8092008-04-13 13:53:33 +0000938 PyObject *message;
939 PyObject *category;
940 PyObject *filename;
941 int lineno;
942 PyObject *module = NULL;
943 PyObject *registry = NULL;
944 PyObject *module_globals = NULL;
Victor Stinner914cde82016-03-19 01:03:51 +0100945 PyObject *sourceobj = NULL;
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200946 PyObject *source_line = NULL;
947 PyObject *returned;
Christian Heimes33fe8092008-04-13 13:53:33 +0000948
Victor Stinner914cde82016-03-19 01:03:51 +0100949 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOUi|OOOO:warn_explicit",
Christian Heimes33fe8092008-04-13 13:53:33 +0000950 kwd_list, &message, &category, &filename, &lineno, &module,
Victor Stinner914cde82016-03-19 01:03:51 +0100951 &registry, &module_globals, &sourceobj))
Christian Heimes33fe8092008-04-13 13:53:33 +0000952 return NULL;
953
954 if (module_globals) {
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200955 source_line = get_source_line(module_globals, lineno);
956 if (source_line == NULL && PyErr_Occurred()) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000957 return NULL;
958 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000959 }
Serhiy Storchakad4f84802017-11-11 15:19:47 +0200960 returned = warn_explicit(category, message, filename, lineno, module,
961 registry, source_line, sourceobj);
962 Py_XDECREF(source_line);
963 return returned;
Christian Heimes33fe8092008-04-13 13:53:33 +0000964}
965
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200966static PyObject *
967warnings_filters_mutated(PyObject *self, PyObject *args)
968{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600969 _PyRuntime.warnings.filters_version++;
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200970 Py_RETURN_NONE;
971}
972
Christian Heimes33fe8092008-04-13 13:53:33 +0000973
974/* Function to issue a warning message; may raise an exception. */
Victor Stinner4a2b7a12010-08-13 14:03:48 +0000975
976static int
977warn_unicode(PyObject *category, PyObject *message,
Victor Stinner914cde82016-03-19 01:03:51 +0100978 Py_ssize_t stack_level, PyObject *source)
Christian Heimes33fe8092008-04-13 13:53:33 +0000979{
980 PyObject *res;
Christian Heimes33fe8092008-04-13 13:53:33 +0000981
982 if (category == NULL)
983 category = PyExc_RuntimeWarning;
984
Victor Stinner914cde82016-03-19 01:03:51 +0100985 res = do_warn(message, category, stack_level, source);
Christian Heimes33fe8092008-04-13 13:53:33 +0000986 if (res == NULL)
987 return -1;
988 Py_DECREF(res);
989
990 return 0;
991}
992
Victor Stinner914cde82016-03-19 01:03:51 +0100993static int
994_PyErr_WarnFormatV(PyObject *source,
995 PyObject *category, Py_ssize_t stack_level,
996 const char *format, va_list vargs)
997{
998 PyObject *message;
999 int res;
1000
1001 message = PyUnicode_FromFormatV(format, vargs);
1002 if (message == NULL)
1003 return -1;
1004
1005 res = warn_unicode(category, message, stack_level, source);
1006 Py_DECREF(message);
1007 return res;
1008}
1009
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001010int
1011PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level,
1012 const char *format, ...)
1013{
Victor Stinner914cde82016-03-19 01:03:51 +01001014 int res;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001015 va_list vargs;
1016
1017#ifdef HAVE_STDARG_PROTOTYPES
1018 va_start(vargs, format);
1019#else
1020 va_start(vargs);
1021#endif
Victor Stinner914cde82016-03-19 01:03:51 +01001022 res = _PyErr_WarnFormatV(NULL, category, stack_level, format, vargs);
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001023 va_end(vargs);
Victor Stinner914cde82016-03-19 01:03:51 +01001024 return res;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001025}
1026
1027int
Victor Stinner914cde82016-03-19 01:03:51 +01001028PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level,
1029 const char *format, ...)
1030{
1031 int res;
1032 va_list vargs;
1033
1034#ifdef HAVE_STDARG_PROTOTYPES
1035 va_start(vargs, format);
1036#else
1037 va_start(vargs);
1038#endif
1039 res = _PyErr_WarnFormatV(source, PyExc_ResourceWarning,
1040 stack_level, format, vargs);
1041 va_end(vargs);
1042 return res;
1043}
1044
1045
1046int
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001047PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
1048{
1049 int ret;
1050 PyObject *message = PyUnicode_FromString(text);
1051 if (message == NULL)
1052 return -1;
Victor Stinner914cde82016-03-19 01:03:51 +01001053 ret = warn_unicode(category, message, stack_level, NULL);
Victor Stinner4a2b7a12010-08-13 14:03:48 +00001054 Py_DECREF(message);
1055 return ret;
1056}
1057
Ezio Melotti42da6632011-03-15 05:18:48 +02001058/* PyErr_Warn is only for backwards compatibility and will be removed.
Christian Heimes33fe8092008-04-13 13:53:33 +00001059 Use PyErr_WarnEx instead. */
1060
1061#undef PyErr_Warn
1062
1063PyAPI_FUNC(int)
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001064PyErr_Warn(PyObject *category, const char *text)
Christian Heimes33fe8092008-04-13 13:53:33 +00001065{
1066 return PyErr_WarnEx(category, text, 1);
1067}
1068
1069/* Warning with explicit origin */
1070int
Victor Stinner14e461d2013-08-26 22:28:21 +02001071PyErr_WarnExplicitObject(PyObject *category, PyObject *message,
1072 PyObject *filename, int lineno,
1073 PyObject *module, PyObject *registry)
1074{
1075 PyObject *res;
1076 if (category == NULL)
1077 category = PyExc_RuntimeWarning;
1078 res = warn_explicit(category, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +01001079 module, registry, NULL, NULL);
Victor Stinner14e461d2013-08-26 22:28:21 +02001080 if (res == NULL)
1081 return -1;
1082 Py_DECREF(res);
1083 return 0;
1084}
1085
1086int
Christian Heimes33fe8092008-04-13 13:53:33 +00001087PyErr_WarnExplicit(PyObject *category, const char *text,
1088 const char *filename_str, int lineno,
1089 const char *module_str, PyObject *registry)
1090{
Christian Heimes33fe8092008-04-13 13:53:33 +00001091 PyObject *message = PyUnicode_FromString(text);
Victor Stinnercb428f02010-12-27 20:10:36 +00001092 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
Christian Heimes33fe8092008-04-13 13:53:33 +00001093 PyObject *module = NULL;
1094 int ret = -1;
1095
1096 if (message == NULL || filename == NULL)
1097 goto exit;
1098 if (module_str != NULL) {
1099 module = PyUnicode_FromString(module_str);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001100 if (module == NULL)
1101 goto exit;
Christian Heimes33fe8092008-04-13 13:53:33 +00001102 }
1103
Victor Stinner14e461d2013-08-26 22:28:21 +02001104 ret = PyErr_WarnExplicitObject(category, message, filename, lineno,
1105 module, registry);
Christian Heimes33fe8092008-04-13 13:53:33 +00001106
1107 exit:
1108 Py_XDECREF(message);
1109 Py_XDECREF(module);
1110 Py_XDECREF(filename);
1111 return ret;
1112}
1113
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001114int
1115PyErr_WarnExplicitFormat(PyObject *category,
1116 const char *filename_str, int lineno,
1117 const char *module_str, PyObject *registry,
1118 const char *format, ...)
1119{
1120 PyObject *message;
1121 PyObject *module = NULL;
1122 PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
1123 int ret = -1;
1124 va_list vargs;
1125
1126 if (filename == NULL)
1127 goto exit;
1128 if (module_str != NULL) {
1129 module = PyUnicode_FromString(module_str);
1130 if (module == NULL)
1131 goto exit;
1132 }
1133
1134#ifdef HAVE_STDARG_PROTOTYPES
1135 va_start(vargs, format);
1136#else
1137 va_start(vargs);
1138#endif
1139 message = PyUnicode_FromFormatV(format, vargs);
1140 if (message != NULL) {
1141 PyObject *res;
1142 res = warn_explicit(category, message, filename, lineno,
Victor Stinner914cde82016-03-19 01:03:51 +01001143 module, registry, NULL, NULL);
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001144 Py_DECREF(message);
1145 if (res != NULL) {
1146 Py_DECREF(res);
1147 ret = 0;
1148 }
1149 }
1150 va_end(vargs);
1151exit:
1152 Py_XDECREF(module);
1153 Py_XDECREF(filename);
1154 return ret;
1155}
1156
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001157void
1158_PyErr_WarnUnawaitedCoroutine(PyObject *coro)
1159{
1160 /* First, we attempt to funnel the warning through
1161 warnings._warn_unawaited_coroutine.
1162
1163 This could raise an exception, due to:
1164 - a bug
1165 - some kind of shutdown-related brokenness
1166 - succeeding, but with an "error" warning filter installed, so the
1167 warning is converted into a RuntimeWarning exception
1168
1169 In the first two cases, we want to print the error (so we know what it
1170 is!), and then print a warning directly as a fallback. In the last
1171 case, we want to print the error (since it's the warning!), but *not*
1172 do a fallback. And after we print the error we can't check for what
1173 type of error it was (because PyErr_WriteUnraisable clears it), so we
1174 need a flag to keep track.
1175
1176 Since this is called from __del__ context, it's careful to never raise
1177 an exception.
1178 */
1179 _Py_IDENTIFIER(_warn_unawaited_coroutine);
1180 int warned = 0;
1181 PyObject *fn = get_warnings_attr(&PyId__warn_unawaited_coroutine, 1);
1182 if (fn) {
1183 PyObject *res = PyObject_CallFunctionObjArgs(fn, coro, NULL);
1184 Py_DECREF(fn);
1185 if (res || PyErr_ExceptionMatches(PyExc_RuntimeWarning)) {
1186 warned = 1;
1187 }
1188 Py_XDECREF(res);
1189 }
1190
1191 if (PyErr_Occurred()) {
1192 PyErr_WriteUnraisable(coro);
1193 }
1194 if (!warned) {
Yury Selivanov35103342018-01-21 20:47:04 -05001195 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1196 "coroutine '%.50S' was never awaited",
1197 ((PyCoroObject *)coro)->cr_qualname) < 0)
1198 {
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001199 PyErr_WriteUnraisable(coro);
1200 }
1201 }
1202}
Christian Heimes33fe8092008-04-13 13:53:33 +00001203
Christian Heimes33fe8092008-04-13 13:53:33 +00001204PyDoc_STRVAR(warn_explicit_doc,
1205"Low-level inferface to warnings functionality.");
1206
1207static PyMethodDef warnings_functions[] = {
Victor Stinner22f18752016-12-09 18:08:18 +01001208 WARNINGS_WARN_METHODDEF
Christian Heimes33fe8092008-04-13 13:53:33 +00001209 {"warn_explicit", (PyCFunction)warnings_warn_explicit,
1210 METH_VARARGS | METH_KEYWORDS, warn_explicit_doc},
Antoine Pitroucb0a0062014-09-18 02:40:46 +02001211 {"_filters_mutated", (PyCFunction)warnings_filters_mutated, METH_NOARGS,
1212 NULL},
Christian Heimes1a8501c2008-10-02 19:56:01 +00001213 /* XXX(brett.cannon): add showwarning? */
1214 /* XXX(brett.cannon): Reasonable to add formatwarning? */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 {NULL, NULL} /* sentinel */
Christian Heimes33fe8092008-04-13 13:53:33 +00001216};
1217
1218
Victor Stinner747f48e2017-12-12 22:59:48 +01001219#ifndef Py_DEBUG
Christian Heimes33fe8092008-04-13 13:53:33 +00001220static PyObject *
Nick Coghlan9b997472018-01-08 12:45:02 +10001221create_filter(PyObject *category, _Py_Identifier *id, const char *modname)
Christian Heimes33fe8092008-04-13 13:53:33 +00001222{
Nick Coghlan9b997472018-01-08 12:45:02 +10001223 PyObject *modname_obj = NULL;
Victor Stinner82656272017-11-22 23:51:42 +01001224 PyObject *action_str = _PyUnicode_FromId(id);
1225 if (action_str == NULL) {
1226 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001227 }
1228
Nick Coghlan9b997472018-01-08 12:45:02 +10001229 /* Default to "no module name" for initial filter set */
1230 if (modname != NULL) {
1231 modname_obj = PyUnicode_InternFromString(modname);
1232 if (modname_obj == NULL) {
1233 return NULL;
1234 }
1235 } else {
1236 modname_obj = Py_None;
1237 }
1238
Christian Heimes33fe8092008-04-13 13:53:33 +00001239 /* This assumes the line number is zero for now. */
Victor Stinner82656272017-11-22 23:51:42 +01001240 return PyTuple_Pack(5, action_str, Py_None,
Nick Coghlan9b997472018-01-08 12:45:02 +10001241 category, modname_obj, _PyLong_Zero);
Christian Heimes33fe8092008-04-13 13:53:33 +00001242}
Victor Stinner747f48e2017-12-12 22:59:48 +01001243#endif
1244
Christian Heimes33fe8092008-04-13 13:53:33 +00001245
1246static PyObject *
Victor Stinner5d862462017-12-19 11:35:58 +01001247init_filters(void)
Christian Heimes33fe8092008-04-13 13:53:33 +00001248{
Victor Stinner747f48e2017-12-12 22:59:48 +01001249#ifdef Py_DEBUG
1250 /* Py_DEBUG builds show all warnings by default */
1251 return PyList_New(0);
1252#else
1253 /* Other builds ignore a number of warning categories by default */
Nick Coghlan9b997472018-01-08 12:45:02 +10001254 PyObject *filters = PyList_New(5);
Victor Stinner747f48e2017-12-12 22:59:48 +01001255 if (filters == NULL) {
Christian Heimes33fe8092008-04-13 13:53:33 +00001256 return NULL;
Victor Stinner747f48e2017-12-12 22:59:48 +01001257 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001258
Victor Stinnerb98f1712017-11-23 17:13:44 +01001259 size_t pos = 0; /* Post-incremented in each use. */
Victor Stinner747f48e2017-12-12 22:59:48 +01001260 PyList_SET_ITEM(filters, pos++,
Nick Coghlan9b997472018-01-08 12:45:02 +10001261 create_filter(PyExc_DeprecationWarning, &PyId_default, "__main__"));
Victor Stinner747f48e2017-12-12 22:59:48 +01001262 PyList_SET_ITEM(filters, pos++,
Nick Coghlan9b997472018-01-08 12:45:02 +10001263 create_filter(PyExc_DeprecationWarning, &PyId_ignore, NULL));
Victor Stinner747f48e2017-12-12 22:59:48 +01001264 PyList_SET_ITEM(filters, pos++,
Nick Coghlan9b997472018-01-08 12:45:02 +10001265 create_filter(PyExc_PendingDeprecationWarning, &PyId_ignore, NULL));
Victor Stinner747f48e2017-12-12 22:59:48 +01001266 PyList_SET_ITEM(filters, pos++,
Nick Coghlan9b997472018-01-08 12:45:02 +10001267 create_filter(PyExc_ImportWarning, &PyId_ignore, NULL));
1268 PyList_SET_ITEM(filters, pos++,
1269 create_filter(PyExc_ResourceWarning, &PyId_ignore, NULL));
Victor Stinner09f3a8a2017-11-20 17:32:40 -08001270
Victor Stinnerb98f1712017-11-23 17:13:44 +01001271 for (size_t x = 0; x < pos; x++) {
Benjamin Peterson7ab4b8d2010-06-28 00:01:59 +00001272 if (PyList_GET_ITEM(filters, x) == NULL) {
1273 Py_DECREF(filters);
1274 return NULL;
1275 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001276 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001277 return filters;
Victor Stinner747f48e2017-12-12 22:59:48 +01001278#endif
Christian Heimes33fe8092008-04-13 13:53:33 +00001279}
1280
Martin v. Löwis1a214512008-06-11 05:26:20 +00001281static struct PyModuleDef warningsmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 PyModuleDef_HEAD_INIT,
1283 MODULE_NAME,
1284 warnings__doc__,
1285 0,
1286 warnings_functions,
1287 NULL,
1288 NULL,
1289 NULL,
1290 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001291};
1292
Christian Heimes33fe8092008-04-13 13:53:33 +00001293
Victor Stinner5d862462017-12-19 11:35:58 +01001294PyMODINIT_FUNC
1295_PyWarnings_Init(void)
Christian Heimes33fe8092008-04-13 13:53:33 +00001296{
Brett Cannon0759dd62009-04-01 18:13:07 +00001297 PyObject *m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001298
Martin v. Löwis1a214512008-06-11 05:26:20 +00001299 m = PyModule_Create(&warningsmodule);
Christian Heimes33fe8092008-04-13 13:53:33 +00001300 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001301 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001302
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001303 if (_PyRuntime.warnings.filters == NULL) {
Victor Stinner5d862462017-12-19 11:35:58 +01001304 _PyRuntime.warnings.filters = init_filters();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001305 if (_PyRuntime.warnings.filters == NULL)
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001306 return NULL;
1307 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001308 Py_INCREF(_PyRuntime.warnings.filters);
1309 if (PyModule_AddObject(m, "filters", _PyRuntime.warnings.filters) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001310 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001311
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001312 if (_PyRuntime.warnings.once_registry == NULL) {
1313 _PyRuntime.warnings.once_registry = PyDict_New();
1314 if (_PyRuntime.warnings.once_registry == NULL)
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001315 return NULL;
1316 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001317 Py_INCREF(_PyRuntime.warnings.once_registry);
1318 if (PyModule_AddObject(m, "_onceregistry",
1319 _PyRuntime.warnings.once_registry) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001320 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +00001321
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001322 if (_PyRuntime.warnings.default_action == NULL) {
1323 _PyRuntime.warnings.default_action = PyUnicode_FromString("default");
1324 if (_PyRuntime.warnings.default_action == NULL)
Antoine Pitrouaa5c5c62012-01-18 21:45:15 +01001325 return NULL;
1326 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001327 Py_INCREF(_PyRuntime.warnings.default_action);
1328 if (PyModule_AddObject(m, "_defaultaction",
1329 _PyRuntime.warnings.default_action) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +00001330 return NULL;
Antoine Pitroucb0a0062014-09-18 02:40:46 +02001331
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001332 _PyRuntime.warnings.filters_version = 0;
Martin v. Löwis1a214512008-06-11 05:26:20 +00001333 return m;
Christian Heimes33fe8092008-04-13 13:53:33 +00001334}