_warnings.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481
  1. #include "Python.h"
  2. #include "pycore_initconfig.h"
  3. #include "pycore_interp.h" // PyInterpreterState.warnings
  4. #include "pycore_long.h" // _PyLong_GetZero()
  5. #include "pycore_pyerrors.h"
  6. #include "pycore_pystate.h" // _PyThreadState_GET()
  7. #include "pycore_frame.h"
  8. #include "clinic/_warnings.c.h"
  9. #define MODULE_NAME "_warnings"
  10. PyDoc_STRVAR(warnings__doc__,
  11. MODULE_NAME " provides basic warning filtering support.\n"
  12. "It is a helper module to speed up interpreter start-up.");
  13. /*************************************************************************/
  14. typedef struct _warnings_runtime_state WarningsState;
  15. static inline int
  16. check_interp(PyInterpreterState *interp)
  17. {
  18. if (interp == NULL) {
  19. PyErr_SetString(PyExc_RuntimeError,
  20. "warnings_get_state: could not identify "
  21. "current interpreter");
  22. return 0;
  23. }
  24. return 1;
  25. }
  26. static inline PyInterpreterState *
  27. get_current_interp(void)
  28. {
  29. PyInterpreterState *interp = _PyInterpreterState_GET();
  30. return check_interp(interp) ? interp : NULL;
  31. }
  32. static inline PyThreadState *
  33. get_current_tstate(void)
  34. {
  35. PyThreadState *tstate = _PyThreadState_GET();
  36. if (tstate == NULL) {
  37. (void)check_interp(NULL);
  38. return NULL;
  39. }
  40. return check_interp(tstate->interp) ? tstate : NULL;
  41. }
  42. /* Given a module object, get its per-module state. */
  43. static WarningsState *
  44. warnings_get_state(PyInterpreterState *interp)
  45. {
  46. return &interp->warnings;
  47. }
  48. /* Clear the given warnings module state. */
  49. static void
  50. warnings_clear_state(WarningsState *st)
  51. {
  52. Py_CLEAR(st->filters);
  53. Py_CLEAR(st->once_registry);
  54. Py_CLEAR(st->default_action);
  55. }
  56. #ifndef Py_DEBUG
  57. static PyObject *
  58. create_filter(PyObject *category, PyObject *action_str, const char *modname)
  59. {
  60. PyObject *modname_obj = NULL;
  61. /* Default to "no module name" for initial filter set */
  62. if (modname != NULL) {
  63. modname_obj = PyUnicode_InternFromString(modname);
  64. if (modname_obj == NULL) {
  65. return NULL;
  66. }
  67. } else {
  68. modname_obj = Py_NewRef(Py_None);
  69. }
  70. /* This assumes the line number is zero for now. */
  71. PyObject *filter = PyTuple_Pack(5, action_str, Py_None,
  72. category, modname_obj, _PyLong_GetZero());
  73. Py_DECREF(modname_obj);
  74. return filter;
  75. }
  76. #endif
  77. static PyObject *
  78. init_filters(PyInterpreterState *interp)
  79. {
  80. #ifdef Py_DEBUG
  81. /* Py_DEBUG builds show all warnings by default */
  82. return PyList_New(0);
  83. #else
  84. /* Other builds ignore a number of warning categories by default */
  85. PyObject *filters = PyList_New(5);
  86. if (filters == NULL) {
  87. return NULL;
  88. }
  89. size_t pos = 0; /* Post-incremented in each use. */
  90. #define ADD(TYPE, ACTION, MODNAME) \
  91. PyList_SET_ITEM(filters, pos++, \
  92. create_filter(TYPE, &_Py_ID(ACTION), MODNAME));
  93. ADD(PyExc_DeprecationWarning, default, "__main__");
  94. ADD(PyExc_DeprecationWarning, ignore, NULL);
  95. ADD(PyExc_PendingDeprecationWarning, ignore, NULL);
  96. ADD(PyExc_ImportWarning, ignore, NULL);
  97. ADD(PyExc_ResourceWarning, ignore, NULL);
  98. #undef ADD
  99. for (size_t x = 0; x < pos; x++) {
  100. if (PyList_GET_ITEM(filters, x) == NULL) {
  101. Py_DECREF(filters);
  102. return NULL;
  103. }
  104. }
  105. return filters;
  106. #endif
  107. }
  108. /* Initialize the given warnings module state. */
  109. int
  110. _PyWarnings_InitState(PyInterpreterState *interp)
  111. {
  112. WarningsState *st = &interp->warnings;
  113. if (st->filters == NULL) {
  114. st->filters = init_filters(interp);
  115. if (st->filters == NULL) {
  116. return -1;
  117. }
  118. }
  119. if (st->once_registry == NULL) {
  120. st->once_registry = PyDict_New();
  121. if (st->once_registry == NULL) {
  122. return -1;
  123. }
  124. }
  125. if (st->default_action == NULL) {
  126. st->default_action = PyUnicode_FromString("default");
  127. if (st->default_action == NULL) {
  128. return -1;
  129. }
  130. }
  131. st->filters_version = 0;
  132. return 0;
  133. }
  134. /*************************************************************************/
  135. static int
  136. check_matched(PyInterpreterState *interp, PyObject *obj, PyObject *arg)
  137. {
  138. PyObject *result;
  139. int rc;
  140. /* A 'None' filter always matches */
  141. if (obj == Py_None)
  142. return 1;
  143. /* An internal plain text default filter must match exactly */
  144. if (PyUnicode_CheckExact(obj)) {
  145. int cmp_result = PyUnicode_Compare(obj, arg);
  146. if (cmp_result == -1 && PyErr_Occurred()) {
  147. return -1;
  148. }
  149. return !cmp_result;
  150. }
  151. /* Otherwise assume a regex filter and call its match() method */
  152. result = PyObject_CallMethodOneArg(obj, &_Py_ID(match), arg);
  153. if (result == NULL)
  154. return -1;
  155. rc = PyObject_IsTrue(result);
  156. Py_DECREF(result);
  157. return rc;
  158. }
  159. #define GET_WARNINGS_ATTR(interp, ATTR, try_import) \
  160. get_warnings_attr(interp, &_Py_ID(ATTR), try_import)
  161. /*
  162. Returns a new reference.
  163. A NULL return value can mean false or an error.
  164. */
  165. static PyObject *
  166. get_warnings_attr(PyInterpreterState *interp, PyObject *attr, int try_import)
  167. {
  168. PyObject *warnings_module, *obj;
  169. /* don't try to import after the start of the Python finallization */
  170. if (try_import && !_Py_IsInterpreterFinalizing(interp)) {
  171. warnings_module = PyImport_Import(&_Py_ID(warnings));
  172. if (warnings_module == NULL) {
  173. /* Fallback to the C implementation if we cannot get
  174. the Python implementation */
  175. if (PyErr_ExceptionMatches(PyExc_ImportError)) {
  176. PyErr_Clear();
  177. }
  178. return NULL;
  179. }
  180. }
  181. else {
  182. /* if we're so late into Python finalization that the module dict is
  183. gone, then we can't even use PyImport_GetModule without triggering
  184. an interpreter abort.
  185. */
  186. if (!_PyImport_GetModules(interp)) {
  187. return NULL;
  188. }
  189. warnings_module = PyImport_GetModule(&_Py_ID(warnings));
  190. if (warnings_module == NULL)
  191. return NULL;
  192. }
  193. (void)_PyObject_LookupAttr(warnings_module, attr, &obj);
  194. Py_DECREF(warnings_module);
  195. return obj;
  196. }
  197. static PyObject *
  198. get_once_registry(PyInterpreterState *interp)
  199. {
  200. PyObject *registry;
  201. WarningsState *st = warnings_get_state(interp);
  202. if (st == NULL) {
  203. return NULL;
  204. }
  205. registry = GET_WARNINGS_ATTR(interp, onceregistry, 0);
  206. if (registry == NULL) {
  207. if (PyErr_Occurred())
  208. return NULL;
  209. assert(st->once_registry);
  210. return st->once_registry;
  211. }
  212. if (!PyDict_Check(registry)) {
  213. PyErr_Format(PyExc_TypeError,
  214. MODULE_NAME ".onceregistry must be a dict, "
  215. "not '%.200s'",
  216. Py_TYPE(registry)->tp_name);
  217. Py_DECREF(registry);
  218. return NULL;
  219. }
  220. Py_SETREF(st->once_registry, registry);
  221. return registry;
  222. }
  223. static PyObject *
  224. get_default_action(PyInterpreterState *interp)
  225. {
  226. PyObject *default_action;
  227. WarningsState *st = warnings_get_state(interp);
  228. if (st == NULL) {
  229. return NULL;
  230. }
  231. default_action = GET_WARNINGS_ATTR(interp, defaultaction, 0);
  232. if (default_action == NULL) {
  233. if (PyErr_Occurred()) {
  234. return NULL;
  235. }
  236. assert(st->default_action);
  237. return st->default_action;
  238. }
  239. if (!PyUnicode_Check(default_action)) {
  240. PyErr_Format(PyExc_TypeError,
  241. MODULE_NAME ".defaultaction must be a string, "
  242. "not '%.200s'",
  243. Py_TYPE(default_action)->tp_name);
  244. Py_DECREF(default_action);
  245. return NULL;
  246. }
  247. Py_SETREF(st->default_action, default_action);
  248. return default_action;
  249. }
  250. /* The item is a new reference. */
  251. static PyObject*
  252. get_filter(PyInterpreterState *interp, PyObject *category,
  253. PyObject *text, Py_ssize_t lineno,
  254. PyObject *module, PyObject **item)
  255. {
  256. PyObject *action;
  257. Py_ssize_t i;
  258. PyObject *warnings_filters;
  259. WarningsState *st = warnings_get_state(interp);
  260. if (st == NULL) {
  261. return NULL;
  262. }
  263. warnings_filters = GET_WARNINGS_ATTR(interp, filters, 0);
  264. if (warnings_filters == NULL) {
  265. if (PyErr_Occurred())
  266. return NULL;
  267. }
  268. else {
  269. Py_SETREF(st->filters, warnings_filters);
  270. }
  271. PyObject *filters = st->filters;
  272. if (filters == NULL || !PyList_Check(filters)) {
  273. PyErr_SetString(PyExc_ValueError,
  274. MODULE_NAME ".filters must be a list");
  275. return NULL;
  276. }
  277. /* WarningsState.filters could change while we are iterating over it. */
  278. for (i = 0; i < PyList_GET_SIZE(filters); i++) {
  279. PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj;
  280. Py_ssize_t ln;
  281. int is_subclass, good_msg, good_mod;
  282. tmp_item = PyList_GET_ITEM(filters, i);
  283. if (!PyTuple_Check(tmp_item) || PyTuple_GET_SIZE(tmp_item) != 5) {
  284. PyErr_Format(PyExc_ValueError,
  285. MODULE_NAME ".filters item %zd isn't a 5-tuple", i);
  286. return NULL;
  287. }
  288. /* Python code: action, msg, cat, mod, ln = item */
  289. Py_INCREF(tmp_item);
  290. action = PyTuple_GET_ITEM(tmp_item, 0);
  291. msg = PyTuple_GET_ITEM(tmp_item, 1);
  292. cat = PyTuple_GET_ITEM(tmp_item, 2);
  293. mod = PyTuple_GET_ITEM(tmp_item, 3);
  294. ln_obj = PyTuple_GET_ITEM(tmp_item, 4);
  295. if (!PyUnicode_Check(action)) {
  296. PyErr_Format(PyExc_TypeError,
  297. "action must be a string, not '%.200s'",
  298. Py_TYPE(action)->tp_name);
  299. Py_DECREF(tmp_item);
  300. return NULL;
  301. }
  302. good_msg = check_matched(interp, msg, text);
  303. if (good_msg == -1) {
  304. Py_DECREF(tmp_item);
  305. return NULL;
  306. }
  307. good_mod = check_matched(interp, mod, module);
  308. if (good_mod == -1) {
  309. Py_DECREF(tmp_item);
  310. return NULL;
  311. }
  312. is_subclass = PyObject_IsSubclass(category, cat);
  313. if (is_subclass == -1) {
  314. Py_DECREF(tmp_item);
  315. return NULL;
  316. }
  317. ln = PyLong_AsSsize_t(ln_obj);
  318. if (ln == -1 && PyErr_Occurred()) {
  319. Py_DECREF(tmp_item);
  320. return NULL;
  321. }
  322. if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln)) {
  323. *item = tmp_item;
  324. return action;
  325. }
  326. Py_DECREF(tmp_item);
  327. }
  328. action = get_default_action(interp);
  329. if (action != NULL) {
  330. *item = Py_NewRef(Py_None);
  331. return action;
  332. }
  333. return NULL;
  334. }
  335. static int
  336. already_warned(PyInterpreterState *interp, PyObject *registry, PyObject *key,
  337. int should_set)
  338. {
  339. PyObject *version_obj, *already_warned;
  340. if (key == NULL)
  341. return -1;
  342. WarningsState *st = warnings_get_state(interp);
  343. if (st == NULL) {
  344. return -1;
  345. }
  346. version_obj = _PyDict_GetItemWithError(registry, &_Py_ID(version));
  347. if (version_obj == NULL
  348. || !PyLong_CheckExact(version_obj)
  349. || PyLong_AsLong(version_obj) != st->filters_version)
  350. {
  351. if (PyErr_Occurred()) {
  352. return -1;
  353. }
  354. PyDict_Clear(registry);
  355. version_obj = PyLong_FromLong(st->filters_version);
  356. if (version_obj == NULL)
  357. return -1;
  358. if (PyDict_SetItem(registry, &_Py_ID(version), version_obj) < 0) {
  359. Py_DECREF(version_obj);
  360. return -1;
  361. }
  362. Py_DECREF(version_obj);
  363. }
  364. else {
  365. already_warned = PyDict_GetItemWithError(registry, key);
  366. if (already_warned != NULL) {
  367. int rc = PyObject_IsTrue(already_warned);
  368. if (rc != 0)
  369. return rc;
  370. }
  371. else if (PyErr_Occurred()) {
  372. return -1;
  373. }
  374. }
  375. /* This warning wasn't found in the registry, set it. */
  376. if (should_set)
  377. return PyDict_SetItem(registry, key, Py_True);
  378. return 0;
  379. }
  380. /* New reference. */
  381. static PyObject *
  382. normalize_module(PyObject *filename)
  383. {
  384. PyObject *module;
  385. int kind;
  386. const void *data;
  387. Py_ssize_t len;
  388. len = PyUnicode_GetLength(filename);
  389. if (len < 0)
  390. return NULL;
  391. if (len == 0)
  392. return PyUnicode_FromString("<unknown>");
  393. kind = PyUnicode_KIND(filename);
  394. data = PyUnicode_DATA(filename);
  395. /* if filename.endswith(".py"): */
  396. if (len >= 3 &&
  397. PyUnicode_READ(kind, data, len-3) == '.' &&
  398. PyUnicode_READ(kind, data, len-2) == 'p' &&
  399. PyUnicode_READ(kind, data, len-1) == 'y')
  400. {
  401. module = PyUnicode_Substring(filename, 0, len-3);
  402. }
  403. else {
  404. module = Py_NewRef(filename);
  405. }
  406. return module;
  407. }
  408. static int
  409. update_registry(PyInterpreterState *interp, PyObject *registry, PyObject *text,
  410. PyObject *category, int add_zero)
  411. {
  412. PyObject *altkey;
  413. int rc;
  414. if (add_zero)
  415. altkey = PyTuple_Pack(3, text, category, _PyLong_GetZero());
  416. else
  417. altkey = PyTuple_Pack(2, text, category);
  418. rc = already_warned(interp, registry, altkey, 1);
  419. Py_XDECREF(altkey);
  420. return rc;
  421. }
  422. static void
  423. show_warning(PyThreadState *tstate, PyObject *filename, int lineno,
  424. PyObject *text, PyObject *category, PyObject *sourceline)
  425. {
  426. PyObject *f_stderr;
  427. PyObject *name;
  428. char lineno_str[128];
  429. PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);
  430. name = PyObject_GetAttr(category, &_Py_ID(__name__));
  431. if (name == NULL) {
  432. goto error;
  433. }
  434. f_stderr = _PySys_GetAttr(tstate, &_Py_ID(stderr));
  435. if (f_stderr == NULL) {
  436. fprintf(stderr, "lost sys.stderr\n");
  437. goto error;
  438. }
  439. /* Print "filename:lineno: category: text\n" */
  440. if (PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW) < 0)
  441. goto error;
  442. if (PyFile_WriteString(lineno_str, f_stderr) < 0)
  443. goto error;
  444. if (PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW) < 0)
  445. goto error;
  446. if (PyFile_WriteString(": ", f_stderr) < 0)
  447. goto error;
  448. if (PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW) < 0)
  449. goto error;
  450. if (PyFile_WriteString("\n", f_stderr) < 0)
  451. goto error;
  452. Py_CLEAR(name);
  453. /* Print " source_line\n" */
  454. if (sourceline) {
  455. int kind;
  456. const void *data;
  457. Py_ssize_t i, len;
  458. Py_UCS4 ch;
  459. PyObject *truncated;
  460. if (PyUnicode_READY(sourceline) < 1)
  461. goto error;
  462. kind = PyUnicode_KIND(sourceline);
  463. data = PyUnicode_DATA(sourceline);
  464. len = PyUnicode_GET_LENGTH(sourceline);
  465. for (i=0; i<len; i++) {
  466. ch = PyUnicode_READ(kind, data, i);
  467. if (ch != ' ' && ch != '\t' && ch != '\014')
  468. break;
  469. }
  470. truncated = PyUnicode_Substring(sourceline, i, len);
  471. if (truncated == NULL)
  472. goto error;
  473. PyFile_WriteObject(sourceline, f_stderr, Py_PRINT_RAW);
  474. Py_DECREF(truncated);
  475. PyFile_WriteString("\n", f_stderr);
  476. }
  477. else {
  478. _Py_DisplaySourceLine(f_stderr, filename, lineno, 2, NULL, NULL);
  479. }
  480. error:
  481. Py_XDECREF(name);
  482. PyErr_Clear();
  483. }
  484. static int
  485. call_show_warning(PyThreadState *tstate, PyObject *category,
  486. PyObject *text, PyObject *message,
  487. PyObject *filename, int lineno, PyObject *lineno_obj,
  488. PyObject *sourceline, PyObject *source)
  489. {
  490. PyObject *show_fn, *msg, *res, *warnmsg_cls = NULL;
  491. PyInterpreterState *interp = tstate->interp;
  492. /* If the source parameter is set, try to get the Python implementation.
  493. The Python implementation is able to log the traceback where the source
  494. was allocated, whereas the C implementation doesn't. */
  495. show_fn = GET_WARNINGS_ATTR(interp, _showwarnmsg, source != NULL);
  496. if (show_fn == NULL) {
  497. if (PyErr_Occurred())
  498. return -1;
  499. show_warning(tstate, filename, lineno, text, category, sourceline);
  500. return 0;
  501. }
  502. if (!PyCallable_Check(show_fn)) {
  503. PyErr_SetString(PyExc_TypeError,
  504. "warnings._showwarnmsg() must be set to a callable");
  505. goto error;
  506. }
  507. warnmsg_cls = GET_WARNINGS_ATTR(interp, WarningMessage, 0);
  508. if (warnmsg_cls == NULL) {
  509. if (!PyErr_Occurred()) {
  510. PyErr_SetString(PyExc_RuntimeError,
  511. "unable to get warnings.WarningMessage");
  512. }
  513. goto error;
  514. }
  515. msg = PyObject_CallFunctionObjArgs(warnmsg_cls, message, category,
  516. filename, lineno_obj, Py_None, Py_None, source,
  517. NULL);
  518. Py_DECREF(warnmsg_cls);
  519. if (msg == NULL)
  520. goto error;
  521. res = PyObject_CallOneArg(show_fn, msg);
  522. Py_DECREF(show_fn);
  523. Py_DECREF(msg);
  524. if (res == NULL)
  525. return -1;
  526. Py_DECREF(res);
  527. return 0;
  528. error:
  529. Py_XDECREF(show_fn);
  530. return -1;
  531. }
  532. static PyObject *
  533. warn_explicit(PyThreadState *tstate, PyObject *category, PyObject *message,
  534. PyObject *filename, int lineno,
  535. PyObject *module, PyObject *registry, PyObject *sourceline,
  536. PyObject *source)
  537. {
  538. PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL;
  539. PyObject *item = NULL;
  540. PyObject *action;
  541. int rc;
  542. PyInterpreterState *interp = tstate->interp;
  543. /* module can be None if a warning is emitted late during Python shutdown.
  544. In this case, the Python warnings module was probably unloaded, filters
  545. are no more available to choose as action. It is safer to ignore the
  546. warning and do nothing. */
  547. if (module == Py_None)
  548. Py_RETURN_NONE;
  549. if (registry && !PyDict_Check(registry) && (registry != Py_None)) {
  550. PyErr_SetString(PyExc_TypeError, "'registry' must be a dict or None");
  551. return NULL;
  552. }
  553. /* Normalize module. */
  554. if (module == NULL) {
  555. module = normalize_module(filename);
  556. if (module == NULL)
  557. return NULL;
  558. }
  559. else
  560. Py_INCREF(module);
  561. /* Normalize message. */
  562. Py_INCREF(message); /* DECREF'ed in cleanup. */
  563. rc = PyObject_IsInstance(message, PyExc_Warning);
  564. if (rc == -1) {
  565. goto cleanup;
  566. }
  567. if (rc == 1) {
  568. text = PyObject_Str(message);
  569. if (text == NULL)
  570. goto cleanup;
  571. category = (PyObject*)Py_TYPE(message);
  572. }
  573. else {
  574. text = message;
  575. message = PyObject_CallOneArg(category, message);
  576. if (message == NULL)
  577. goto cleanup;
  578. }
  579. lineno_obj = PyLong_FromLong(lineno);
  580. if (lineno_obj == NULL)
  581. goto cleanup;
  582. if (source == Py_None) {
  583. source = NULL;
  584. }
  585. /* Create key. */
  586. key = PyTuple_Pack(3, text, category, lineno_obj);
  587. if (key == NULL)
  588. goto cleanup;
  589. if ((registry != NULL) && (registry != Py_None)) {
  590. rc = already_warned(interp, registry, key, 0);
  591. if (rc == -1)
  592. goto cleanup;
  593. else if (rc == 1)
  594. goto return_none;
  595. /* Else this warning hasn't been generated before. */
  596. }
  597. action = get_filter(interp, category, text, lineno, module, &item);
  598. if (action == NULL)
  599. goto cleanup;
  600. if (_PyUnicode_EqualToASCIIString(action, "error")) {
  601. PyErr_SetObject(category, message);
  602. goto cleanup;
  603. }
  604. if (_PyUnicode_EqualToASCIIString(action, "ignore")) {
  605. goto return_none;
  606. }
  607. /* Store in the registry that we've been here, *except* when the action
  608. is "always". */
  609. rc = 0;
  610. if (!_PyUnicode_EqualToASCIIString(action, "always")) {
  611. if (registry != NULL && registry != Py_None &&
  612. PyDict_SetItem(registry, key, Py_True) < 0)
  613. {
  614. goto cleanup;
  615. }
  616. if (_PyUnicode_EqualToASCIIString(action, "once")) {
  617. if (registry == NULL || registry == Py_None) {
  618. registry = get_once_registry(interp);
  619. if (registry == NULL)
  620. goto cleanup;
  621. }
  622. /* WarningsState.once_registry[(text, category)] = 1 */
  623. rc = update_registry(interp, registry, text, category, 0);
  624. }
  625. else if (_PyUnicode_EqualToASCIIString(action, "module")) {
  626. /* registry[(text, category, 0)] = 1 */
  627. if (registry != NULL && registry != Py_None)
  628. rc = update_registry(interp, registry, text, category, 0);
  629. }
  630. else if (!_PyUnicode_EqualToASCIIString(action, "default")) {
  631. PyErr_Format(PyExc_RuntimeError,
  632. "Unrecognized action (%R) in warnings.filters:\n %R",
  633. action, item);
  634. goto cleanup;
  635. }
  636. }
  637. if (rc == 1) /* Already warned for this module. */
  638. goto return_none;
  639. if (rc == 0) {
  640. if (call_show_warning(tstate, category, text, message, filename,
  641. lineno, lineno_obj, sourceline, source) < 0)
  642. goto cleanup;
  643. }
  644. else /* if (rc == -1) */
  645. goto cleanup;
  646. return_none:
  647. result = Py_NewRef(Py_None);
  648. cleanup:
  649. Py_XDECREF(item);
  650. Py_XDECREF(key);
  651. Py_XDECREF(text);
  652. Py_XDECREF(lineno_obj);
  653. Py_DECREF(module);
  654. Py_XDECREF(message);
  655. return result; /* Py_None or NULL. */
  656. }
  657. static PyObject *
  658. get_frame_filename(PyFrameObject *frame)
  659. {
  660. PyCodeObject *code = PyFrame_GetCode(frame);
  661. PyObject *filename = code->co_filename;
  662. Py_DECREF(code);
  663. return filename;
  664. }
  665. static bool
  666. is_internal_filename(PyObject *filename)
  667. {
  668. if (!PyUnicode_Check(filename)) {
  669. return false;
  670. }
  671. int contains = PyUnicode_Contains(filename, &_Py_ID(importlib));
  672. if (contains < 0) {
  673. return false;
  674. }
  675. else if (contains > 0) {
  676. contains = PyUnicode_Contains(filename, &_Py_ID(_bootstrap));
  677. if (contains < 0) {
  678. return false;
  679. }
  680. else if (contains > 0) {
  681. return true;
  682. }
  683. }
  684. return false;
  685. }
  686. static bool
  687. is_filename_to_skip(PyObject *filename, PyTupleObject *skip_file_prefixes)
  688. {
  689. if (skip_file_prefixes) {
  690. if (!PyUnicode_Check(filename)) {
  691. return false;
  692. }
  693. Py_ssize_t prefixes = PyTuple_GET_SIZE(skip_file_prefixes);
  694. for (Py_ssize_t idx = 0; idx < prefixes; ++idx)
  695. {
  696. PyObject *prefix = PyTuple_GET_ITEM(skip_file_prefixes, idx);
  697. Py_ssize_t found = PyUnicode_Tailmatch(filename, prefix, 0, -1, -1);
  698. if (found == 1) {
  699. return true;
  700. }
  701. if (found < 0) {
  702. return false;
  703. }
  704. }
  705. }
  706. return false;
  707. }
  708. static bool
  709. is_internal_frame(PyFrameObject *frame)
  710. {
  711. if (frame == NULL) {
  712. return false;
  713. }
  714. PyObject *filename = get_frame_filename(frame);
  715. if (filename == NULL) {
  716. return false;
  717. }
  718. return is_internal_filename(filename);
  719. }
  720. static PyFrameObject *
  721. next_external_frame(PyFrameObject *frame, PyTupleObject *skip_file_prefixes)
  722. {
  723. PyObject *frame_filename;
  724. do {
  725. PyFrameObject *back = PyFrame_GetBack(frame);
  726. Py_SETREF(frame, back);
  727. } while (frame != NULL && (frame_filename = get_frame_filename(frame)) &&
  728. (is_internal_filename(frame_filename) ||
  729. is_filename_to_skip(frame_filename, skip_file_prefixes)));
  730. return frame;
  731. }
  732. /* filename, module, and registry are new refs, globals is borrowed */
  733. /* skip_file_prefixes is either NULL or a tuple of strs. */
  734. /* Returns 0 on error (no new refs), 1 on success */
  735. static int
  736. setup_context(Py_ssize_t stack_level,
  737. PyTupleObject *skip_file_prefixes,
  738. PyObject **filename, int *lineno,
  739. PyObject **module, PyObject **registry)
  740. {
  741. PyObject *globals;
  742. /* Setup globals, filename and lineno. */
  743. PyThreadState *tstate = get_current_tstate();
  744. if (tstate == NULL) {
  745. return 0;
  746. }
  747. if (skip_file_prefixes) {
  748. /* Type check our data structure up front. Later code that uses it
  749. * isn't structured to report errors. */
  750. Py_ssize_t prefixes = PyTuple_GET_SIZE(skip_file_prefixes);
  751. for (Py_ssize_t idx = 0; idx < prefixes; ++idx)
  752. {
  753. PyObject *prefix = PyTuple_GET_ITEM(skip_file_prefixes, idx);
  754. if (!PyUnicode_Check(prefix)) {
  755. PyErr_Format(PyExc_TypeError,
  756. "Found non-str '%s' in skip_file_prefixes.",
  757. Py_TYPE(prefix)->tp_name);
  758. return 0;
  759. }
  760. }
  761. }
  762. PyInterpreterState *interp = tstate->interp;
  763. PyFrameObject *f = PyThreadState_GetFrame(tstate);
  764. // Stack level comparisons to Python code is off by one as there is no
  765. // warnings-related stack level to avoid.
  766. if (stack_level <= 0 || is_internal_frame(f)) {
  767. while (--stack_level > 0 && f != NULL) {
  768. PyFrameObject *back = PyFrame_GetBack(f);
  769. Py_SETREF(f, back);
  770. }
  771. }
  772. else {
  773. while (--stack_level > 0 && f != NULL) {
  774. f = next_external_frame(f, skip_file_prefixes);
  775. }
  776. }
  777. if (f == NULL) {
  778. globals = interp->sysdict;
  779. *filename = PyUnicode_FromString("sys");
  780. *lineno = 1;
  781. }
  782. else {
  783. globals = f->f_frame->f_globals;
  784. *filename = Py_NewRef(f->f_frame->f_code->co_filename);
  785. *lineno = PyFrame_GetLineNumber(f);
  786. Py_DECREF(f);
  787. }
  788. *module = NULL;
  789. /* Setup registry. */
  790. assert(globals != NULL);
  791. assert(PyDict_Check(globals));
  792. *registry = _PyDict_GetItemWithError(globals, &_Py_ID(__warningregistry__));
  793. if (*registry == NULL) {
  794. int rc;
  795. if (_PyErr_Occurred(tstate)) {
  796. goto handle_error;
  797. }
  798. *registry = PyDict_New();
  799. if (*registry == NULL)
  800. goto handle_error;
  801. rc = PyDict_SetItem(globals, &_Py_ID(__warningregistry__), *registry);
  802. if (rc < 0)
  803. goto handle_error;
  804. }
  805. else
  806. Py_INCREF(*registry);
  807. /* Setup module. */
  808. *module = _PyDict_GetItemWithError(globals, &_Py_ID(__name__));
  809. if (*module == Py_None || (*module != NULL && PyUnicode_Check(*module))) {
  810. Py_INCREF(*module);
  811. }
  812. else if (_PyErr_Occurred(tstate)) {
  813. goto handle_error;
  814. }
  815. else {
  816. *module = PyUnicode_FromString("<string>");
  817. if (*module == NULL)
  818. goto handle_error;
  819. }
  820. return 1;
  821. handle_error:
  822. Py_XDECREF(*registry);
  823. Py_XDECREF(*module);
  824. Py_DECREF(*filename);
  825. return 0;
  826. }
  827. static PyObject *
  828. get_category(PyObject *message, PyObject *category)
  829. {
  830. int rc;
  831. /* Get category. */
  832. rc = PyObject_IsInstance(message, PyExc_Warning);
  833. if (rc == -1)
  834. return NULL;
  835. if (rc == 1)
  836. category = (PyObject*)Py_TYPE(message);
  837. else if (category == NULL || category == Py_None)
  838. category = PyExc_UserWarning;
  839. /* Validate category. */
  840. rc = PyObject_IsSubclass(category, PyExc_Warning);
  841. /* category is not a subclass of PyExc_Warning or
  842. PyObject_IsSubclass raised an error */
  843. if (rc == -1 || rc == 0) {
  844. PyErr_Format(PyExc_TypeError,
  845. "category must be a Warning subclass, not '%s'",
  846. Py_TYPE(category)->tp_name);
  847. return NULL;
  848. }
  849. return category;
  850. }
  851. static PyObject *
  852. do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level,
  853. PyObject *source, PyTupleObject *skip_file_prefixes)
  854. {
  855. PyObject *filename, *module, *registry, *res;
  856. int lineno;
  857. PyThreadState *tstate = get_current_tstate();
  858. if (tstate == NULL) {
  859. return NULL;
  860. }
  861. if (!setup_context(stack_level, skip_file_prefixes,
  862. &filename, &lineno, &module, &registry))
  863. return NULL;
  864. res = warn_explicit(tstate, category, message, filename, lineno, module, registry,
  865. NULL, source);
  866. Py_DECREF(filename);
  867. Py_DECREF(registry);
  868. Py_DECREF(module);
  869. return res;
  870. }
  871. /*[clinic input]
  872. warn as warnings_warn
  873. message: object
  874. Text of the warning message.
  875. category: object = None
  876. The Warning category subclass. Defaults to UserWarning.
  877. stacklevel: Py_ssize_t = 1
  878. How far up the call stack to make this warning appear. A value of 2 for
  879. example attributes the warning to the caller of the code calling warn().
  880. source: object = None
  881. If supplied, the destroyed object which emitted a ResourceWarning
  882. *
  883. skip_file_prefixes: object(type='PyTupleObject *', subclass_of='&PyTuple_Type') = NULL
  884. An optional tuple of module filename prefixes indicating frames to skip
  885. during stacklevel computations for stack frame attribution.
  886. Issue a warning, or maybe ignore it or raise an exception.
  887. [clinic start generated code]*/
  888. static PyObject *
  889. warnings_warn_impl(PyObject *module, PyObject *message, PyObject *category,
  890. Py_ssize_t stacklevel, PyObject *source,
  891. PyTupleObject *skip_file_prefixes)
  892. /*[clinic end generated code: output=a68e0f6906c65f80 input=eb37c6a18bec4ea1]*/
  893. {
  894. category = get_category(message, category);
  895. if (category == NULL)
  896. return NULL;
  897. if (skip_file_prefixes) {
  898. if (PyTuple_GET_SIZE(skip_file_prefixes) > 0) {
  899. if (stacklevel < 2) {
  900. stacklevel = 2;
  901. }
  902. } else {
  903. Py_DECREF((PyObject *)skip_file_prefixes);
  904. skip_file_prefixes = NULL;
  905. }
  906. }
  907. return do_warn(message, category, stacklevel, source, skip_file_prefixes);
  908. }
  909. static PyObject *
  910. get_source_line(PyInterpreterState *interp, PyObject *module_globals, int lineno)
  911. {
  912. PyObject *loader;
  913. PyObject *module_name;
  914. PyObject *get_source;
  915. PyObject *source;
  916. PyObject *source_list;
  917. PyObject *source_line;
  918. /* stolen from import.c */
  919. loader = _PyImport_BlessMyLoader(interp, module_globals);
  920. if (loader == NULL) {
  921. return NULL;
  922. }
  923. module_name = _PyDict_GetItemWithError(module_globals, &_Py_ID(__name__));
  924. if (!module_name) {
  925. Py_DECREF(loader);
  926. return NULL;
  927. }
  928. Py_INCREF(module_name);
  929. /* Make sure the loader implements the optional get_source() method. */
  930. (void)_PyObject_LookupAttr(loader, &_Py_ID(get_source), &get_source);
  931. Py_DECREF(loader);
  932. if (!get_source) {
  933. Py_DECREF(module_name);
  934. return NULL;
  935. }
  936. /* Call get_source() to get the source code. */
  937. source = PyObject_CallOneArg(get_source, module_name);
  938. Py_DECREF(get_source);
  939. Py_DECREF(module_name);
  940. if (!source) {
  941. return NULL;
  942. }
  943. if (source == Py_None) {
  944. Py_DECREF(source);
  945. return NULL;
  946. }
  947. /* Split the source into lines. */
  948. source_list = PyUnicode_Splitlines(source, 0);
  949. Py_DECREF(source);
  950. if (!source_list) {
  951. return NULL;
  952. }
  953. /* Get the source line. */
  954. source_line = PyList_GetItem(source_list, lineno-1);
  955. Py_XINCREF(source_line);
  956. Py_DECREF(source_list);
  957. return source_line;
  958. }
  959. /*[clinic input]
  960. warn_explicit as warnings_warn_explicit
  961. message: object
  962. category: object
  963. filename: unicode
  964. lineno: int
  965. module as mod: object = NULL
  966. registry: object = None
  967. module_globals: object = None
  968. source as sourceobj: object = None
  969. Issue a warning, or maybe ignore it or raise an exception.
  970. [clinic start generated code]*/
  971. static PyObject *
  972. warnings_warn_explicit_impl(PyObject *module, PyObject *message,
  973. PyObject *category, PyObject *filename,
  974. int lineno, PyObject *mod, PyObject *registry,
  975. PyObject *module_globals, PyObject *sourceobj)
  976. /*[clinic end generated code: output=c49c62b15a49a186 input=df6eeb8b45e712f1]*/
  977. {
  978. PyObject *source_line = NULL;
  979. PyObject *returned;
  980. PyThreadState *tstate = get_current_tstate();
  981. if (tstate == NULL) {
  982. return NULL;
  983. }
  984. if (module_globals && module_globals != Py_None) {
  985. if (!PyDict_Check(module_globals)) {
  986. PyErr_Format(PyExc_TypeError,
  987. "module_globals must be a dict, not '%.200s'",
  988. Py_TYPE(module_globals)->tp_name);
  989. return NULL;
  990. }
  991. source_line = get_source_line(tstate->interp, module_globals, lineno);
  992. if (source_line == NULL && PyErr_Occurred()) {
  993. return NULL;
  994. }
  995. }
  996. returned = warn_explicit(tstate, category, message, filename, lineno,
  997. mod, registry, source_line, sourceobj);
  998. Py_XDECREF(source_line);
  999. return returned;
  1000. }
  1001. /*[clinic input]
  1002. _filters_mutated as warnings_filters_mutated
  1003. [clinic start generated code]*/
  1004. static PyObject *
  1005. warnings_filters_mutated_impl(PyObject *module)
  1006. /*[clinic end generated code: output=8ce517abd12b88f4 input=35ecbf08ee2491b2]*/
  1007. {
  1008. PyInterpreterState *interp = get_current_interp();
  1009. if (interp == NULL) {
  1010. return NULL;
  1011. }
  1012. WarningsState *st = warnings_get_state(interp);
  1013. if (st == NULL) {
  1014. return NULL;
  1015. }
  1016. st->filters_version++;
  1017. Py_RETURN_NONE;
  1018. }
  1019. /* Function to issue a warning message; may raise an exception. */
  1020. static int
  1021. warn_unicode(PyObject *category, PyObject *message,
  1022. Py_ssize_t stack_level, PyObject *source)
  1023. {
  1024. PyObject *res;
  1025. if (category == NULL)
  1026. category = PyExc_RuntimeWarning;
  1027. res = do_warn(message, category, stack_level, source, NULL);
  1028. if (res == NULL)
  1029. return -1;
  1030. Py_DECREF(res);
  1031. return 0;
  1032. }
  1033. static int
  1034. _PyErr_WarnFormatV(PyObject *source,
  1035. PyObject *category, Py_ssize_t stack_level,
  1036. const char *format, va_list vargs)
  1037. {
  1038. PyObject *message;
  1039. int res;
  1040. message = PyUnicode_FromFormatV(format, vargs);
  1041. if (message == NULL)
  1042. return -1;
  1043. res = warn_unicode(category, message, stack_level, source);
  1044. Py_DECREF(message);
  1045. return res;
  1046. }
  1047. int
  1048. PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level,
  1049. const char *format, ...)
  1050. {
  1051. int res;
  1052. va_list vargs;
  1053. va_start(vargs, format);
  1054. res = _PyErr_WarnFormatV(NULL, category, stack_level, format, vargs);
  1055. va_end(vargs);
  1056. return res;
  1057. }
  1058. static int
  1059. _PyErr_WarnFormat(PyObject *source, PyObject *category, Py_ssize_t stack_level,
  1060. const char *format, ...)
  1061. {
  1062. int res;
  1063. va_list vargs;
  1064. va_start(vargs, format);
  1065. res = _PyErr_WarnFormatV(source, category, stack_level, format, vargs);
  1066. va_end(vargs);
  1067. return res;
  1068. }
  1069. int
  1070. PyErr_ResourceWarning(PyObject *source, Py_ssize_t stack_level,
  1071. const char *format, ...)
  1072. {
  1073. int res;
  1074. va_list vargs;
  1075. va_start(vargs, format);
  1076. res = _PyErr_WarnFormatV(source, PyExc_ResourceWarning,
  1077. stack_level, format, vargs);
  1078. va_end(vargs);
  1079. return res;
  1080. }
  1081. int
  1082. PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
  1083. {
  1084. int ret;
  1085. PyObject *message = PyUnicode_FromString(text);
  1086. if (message == NULL)
  1087. return -1;
  1088. ret = warn_unicode(category, message, stack_level, NULL);
  1089. Py_DECREF(message);
  1090. return ret;
  1091. }
  1092. /* PyErr_Warn is only for backwards compatibility and will be removed.
  1093. Use PyErr_WarnEx instead. */
  1094. #undef PyErr_Warn
  1095. int
  1096. PyErr_Warn(PyObject *category, const char *text)
  1097. {
  1098. return PyErr_WarnEx(category, text, 1);
  1099. }
  1100. /* Warning with explicit origin */
  1101. int
  1102. PyErr_WarnExplicitObject(PyObject *category, PyObject *message,
  1103. PyObject *filename, int lineno,
  1104. PyObject *module, PyObject *registry)
  1105. {
  1106. PyObject *res;
  1107. if (category == NULL)
  1108. category = PyExc_RuntimeWarning;
  1109. PyThreadState *tstate = get_current_tstate();
  1110. if (tstate == NULL) {
  1111. return -1;
  1112. }
  1113. res = warn_explicit(tstate, category, message, filename, lineno,
  1114. module, registry, NULL, NULL);
  1115. if (res == NULL)
  1116. return -1;
  1117. Py_DECREF(res);
  1118. return 0;
  1119. }
  1120. int
  1121. PyErr_WarnExplicit(PyObject *category, const char *text,
  1122. const char *filename_str, int lineno,
  1123. const char *module_str, PyObject *registry)
  1124. {
  1125. PyObject *message = PyUnicode_FromString(text);
  1126. if (message == NULL) {
  1127. return -1;
  1128. }
  1129. PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
  1130. if (filename == NULL) {
  1131. Py_DECREF(message);
  1132. return -1;
  1133. }
  1134. PyObject *module = NULL;
  1135. if (module_str != NULL) {
  1136. module = PyUnicode_FromString(module_str);
  1137. if (module == NULL) {
  1138. Py_DECREF(filename);
  1139. Py_DECREF(message);
  1140. return -1;
  1141. }
  1142. }
  1143. int ret = PyErr_WarnExplicitObject(category, message, filename, lineno,
  1144. module, registry);
  1145. Py_XDECREF(module);
  1146. Py_DECREF(filename);
  1147. Py_DECREF(message);
  1148. return ret;
  1149. }
  1150. int
  1151. PyErr_WarnExplicitFormat(PyObject *category,
  1152. const char *filename_str, int lineno,
  1153. const char *module_str, PyObject *registry,
  1154. const char *format, ...)
  1155. {
  1156. PyObject *message;
  1157. PyObject *module = NULL;
  1158. PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
  1159. int ret = -1;
  1160. va_list vargs;
  1161. if (filename == NULL)
  1162. goto exit;
  1163. if (module_str != NULL) {
  1164. module = PyUnicode_FromString(module_str);
  1165. if (module == NULL)
  1166. goto exit;
  1167. }
  1168. va_start(vargs, format);
  1169. message = PyUnicode_FromFormatV(format, vargs);
  1170. if (message != NULL) {
  1171. PyObject *res;
  1172. PyThreadState *tstate = get_current_tstate();
  1173. if (tstate != NULL) {
  1174. res = warn_explicit(tstate, category, message, filename, lineno,
  1175. module, registry, NULL, NULL);
  1176. Py_DECREF(message);
  1177. if (res != NULL) {
  1178. Py_DECREF(res);
  1179. ret = 0;
  1180. }
  1181. }
  1182. }
  1183. va_end(vargs);
  1184. exit:
  1185. Py_XDECREF(module);
  1186. Py_XDECREF(filename);
  1187. return ret;
  1188. }
  1189. void
  1190. _PyErr_WarnUnawaitedCoroutine(PyObject *coro)
  1191. {
  1192. /* First, we attempt to funnel the warning through
  1193. warnings._warn_unawaited_coroutine.
  1194. This could raise an exception, due to:
  1195. - a bug
  1196. - some kind of shutdown-related brokenness
  1197. - succeeding, but with an "error" warning filter installed, so the
  1198. warning is converted into a RuntimeWarning exception
  1199. In the first two cases, we want to print the error (so we know what it
  1200. is!), and then print a warning directly as a fallback. In the last
  1201. case, we want to print the error (since it's the warning!), but *not*
  1202. do a fallback. And after we print the error we can't check for what
  1203. type of error it was (because PyErr_WriteUnraisable clears it), so we
  1204. need a flag to keep track.
  1205. Since this is called from __del__ context, it's careful to never raise
  1206. an exception.
  1207. */
  1208. int warned = 0;
  1209. PyInterpreterState *interp = _PyInterpreterState_GET();
  1210. assert(interp != NULL);
  1211. PyObject *fn = GET_WARNINGS_ATTR(interp, _warn_unawaited_coroutine, 1);
  1212. if (fn) {
  1213. PyObject *res = PyObject_CallOneArg(fn, coro);
  1214. Py_DECREF(fn);
  1215. if (res || PyErr_ExceptionMatches(PyExc_RuntimeWarning)) {
  1216. warned = 1;
  1217. }
  1218. Py_XDECREF(res);
  1219. }
  1220. if (PyErr_Occurred()) {
  1221. PyErr_WriteUnraisable(coro);
  1222. }
  1223. if (!warned) {
  1224. if (_PyErr_WarnFormat(coro, PyExc_RuntimeWarning, 1,
  1225. "coroutine '%S' was never awaited",
  1226. ((PyCoroObject *)coro)->cr_qualname) < 0)
  1227. {
  1228. PyErr_WriteUnraisable(coro);
  1229. }
  1230. }
  1231. }
  1232. static PyMethodDef warnings_functions[] = {
  1233. WARNINGS_WARN_METHODDEF
  1234. WARNINGS_WARN_EXPLICIT_METHODDEF
  1235. WARNINGS_FILTERS_MUTATED_METHODDEF
  1236. /* XXX(brett.cannon): add showwarning? */
  1237. /* XXX(brett.cannon): Reasonable to add formatwarning? */
  1238. {NULL, NULL} /* sentinel */
  1239. };
  1240. static int
  1241. warnings_module_exec(PyObject *module)
  1242. {
  1243. PyInterpreterState *interp = get_current_interp();
  1244. if (interp == NULL) {
  1245. return -1;
  1246. }
  1247. WarningsState *st = warnings_get_state(interp);
  1248. if (st == NULL) {
  1249. return -1;
  1250. }
  1251. if (PyModule_AddObjectRef(module, "filters", st->filters) < 0) {
  1252. return -1;
  1253. }
  1254. if (PyModule_AddObjectRef(module, "_onceregistry", st->once_registry) < 0) {
  1255. return -1;
  1256. }
  1257. if (PyModule_AddObjectRef(module, "_defaultaction", st->default_action) < 0) {
  1258. return -1;
  1259. }
  1260. return 0;
  1261. }
  1262. static PyModuleDef_Slot warnings_slots[] = {
  1263. {Py_mod_exec, warnings_module_exec},
  1264. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1265. {0, NULL}
  1266. };
  1267. static struct PyModuleDef warnings_module = {
  1268. PyModuleDef_HEAD_INIT,
  1269. .m_name = MODULE_NAME,
  1270. .m_doc = warnings__doc__,
  1271. .m_size = 0,
  1272. .m_methods = warnings_functions,
  1273. .m_slots = warnings_slots,
  1274. };
  1275. PyMODINIT_FUNC
  1276. _PyWarnings_Init(void)
  1277. {
  1278. return PyModuleDef_Init(&warnings_module);
  1279. }
  1280. // We need this to ensure that warnings still work until late in finalization.
  1281. void
  1282. _PyWarnings_Fini(PyInterpreterState *interp)
  1283. {
  1284. warnings_clear_state(&interp->warnings);
  1285. }