/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "environment.h" #include "qcontext2dcanvas.h" #include "context2d.h" #include #include struct FakeDomEvent { enum KeyCodes { DOM_VK_UNDEFINED = 0x0, DOM_VK_RIGHT_ALT = 0x12, DOM_VK_LEFT_ALT = 0x12, DOM_VK_LEFT_CONTROL = 0x11, DOM_VK_RIGHT_CONTROL = 0x11, DOM_VK_LEFT_SHIFT = 0x10, DOM_VK_RIGHT_SHIFT = 0x10, DOM_VK_META = 0x9D, DOM_VK_BACK_SPACE = 0x08, DOM_VK_CAPS_LOCK = 0x14, DOM_VK_DELETE = 0x7F, DOM_VK_END = 0x23, DOM_VK_ENTER = 0x0D, DOM_VK_ESCAPE = 0x1B, DOM_VK_HOME = 0x24, DOM_VK_NUM_LOCK = 0x90, DOM_VK_PAUSE = 0x13, DOM_VK_PRINTSCREEN = 0x9A, DOM_VK_SCROLL_LOCK = 0x91, DOM_VK_SPACE = 0x20, DOM_VK_TAB = 0x09, DOM_VK_LEFT = 0x25, DOM_VK_RIGHT = 0x27, DOM_VK_UP = 0x26, DOM_VK_DOWN = 0x28, DOM_VK_PAGE_DOWN = 0x22, DOM_VK_PAGE_UP = 0x21, DOM_VK_F1 = 0x70, DOM_VK_F2 = 0x71, DOM_VK_F3 = 0x72, DOM_VK_F4 = 0x73, DOM_VK_F5 = 0x74, DOM_VK_F6 = 0x75, DOM_VK_F7 = 0x76, DOM_VK_F8 = 0x77, DOM_VK_F9 = 0x78, DOM_VK_F10 = 0x79, DOM_VK_F11 = 0x7A, DOM_VK_F12 = 0x7B, DOM_VK_F13 = 0xF000, DOM_VK_F14 = 0xF001, DOM_VK_F15 = 0xF002, DOM_VK_F16 = 0xF003, DOM_VK_F17 = 0xF004, DOM_VK_F18 = 0xF005, DOM_VK_F19 = 0xF006, DOM_VK_F20 = 0xF007, DOM_VK_F21 = 0xF008, DOM_VK_F22 = 0xF009, DOM_VK_F23 = 0xF00A, DOM_VK_F24 = 0xF00B }; static int qtToDomKey(int keyCode); }; int FakeDomEvent::qtToDomKey(int keyCode) { switch (keyCode) { case Qt::Key_Backspace: return DOM_VK_BACK_SPACE; case Qt::Key_Enter: return DOM_VK_ENTER; case Qt::Key_Return: return DOM_VK_ENTER; case Qt::Key_NumLock: return DOM_VK_NUM_LOCK; case Qt::Key_Alt: return DOM_VK_RIGHT_ALT; case Qt::Key_Control: return DOM_VK_LEFT_CONTROL; case Qt::Key_Shift: return DOM_VK_LEFT_SHIFT; case Qt::Key_Meta: return DOM_VK_META; case Qt::Key_CapsLock: return DOM_VK_CAPS_LOCK; case Qt::Key_Delete: return DOM_VK_DELETE; case Qt::Key_End: return DOM_VK_END; case Qt::Key_Escape: return DOM_VK_ESCAPE; case Qt::Key_Home: return DOM_VK_HOME; case Qt::Key_Pause: return DOM_VK_PAUSE; case Qt::Key_Print: return DOM_VK_PRINTSCREEN; case Qt::Key_ScrollLock: return DOM_VK_SCROLL_LOCK; case Qt::Key_Left: return DOM_VK_LEFT; case Qt::Key_Right: return DOM_VK_RIGHT; case Qt::Key_Up: return DOM_VK_UP; case Qt::Key_Down: return DOM_VK_DOWN; case Qt::Key_PageDown: return DOM_VK_PAGE_DOWN; case Qt::Key_PageUp: return DOM_VK_PAGE_UP; case Qt::Key_F1: return DOM_VK_F1; case Qt::Key_F2: return DOM_VK_F2; case Qt::Key_F3: return DOM_VK_F3; case Qt::Key_F4: return DOM_VK_F4; case Qt::Key_F5: return DOM_VK_F5; case Qt::Key_F6: return DOM_VK_F6; case Qt::Key_F7: return DOM_VK_F7; case Qt::Key_F8: return DOM_VK_F8; case Qt::Key_F9: return DOM_VK_F9; case Qt::Key_F10: return DOM_VK_F10; case Qt::Key_F11: return DOM_VK_F11; case Qt::Key_F12: return DOM_VK_F12; case Qt::Key_F13: return DOM_VK_F13; case Qt::Key_F14: return DOM_VK_F14; case Qt::Key_F15: return DOM_VK_F15; case Qt::Key_F16: return DOM_VK_F16; case Qt::Key_F17: return DOM_VK_F17; case Qt::Key_F18: return DOM_VK_F18; case Qt::Key_F19: return DOM_VK_F19; case Qt::Key_F20: return DOM_VK_F20; case Qt::Key_F21: return DOM_VK_F21; case Qt::Key_F22: return DOM_VK_F22; case Qt::Key_F23: return DOM_VK_F23; case Qt::Key_F24: return DOM_VK_F24; } return keyCode; } //! [0] Environment::Environment(QObject *parent) : QObject(parent) { m_engine = new QScriptEngine(this); m_document = m_engine->newQObject( new Document(this), QScriptEngine::QtOwnership, QScriptEngine::ExcludeSuperClassContents); CanvasGradientPrototype::setup(m_engine); m_originalGlobalObject = m_engine->globalObject(); reset(); } //! [0] Environment::~Environment() { } QScriptEngine *Environment::engine() const { return m_engine; } QScriptValue Environment::document() const { return m_document; } int Environment::setTimeout(const QScriptValue &expression, int delay) { if (expression.isString() || expression.isFunction()) { int timerId = startTimer(delay); m_timeoutHash.insert(timerId, expression); return timerId; } return -1; } void Environment::clearTimeout(int timerId) { killTimer(timerId); m_timeoutHash.remove(timerId); } //! [1] int Environment::setInterval(const QScriptValue &expression, int delay) { if (expression.isString() || expression.isFunction()) { int timerId = startTimer(delay); m_intervalHash.insert(timerId, expression); return timerId; } return -1; } void Environment::clearInterval(int timerId) { killTimer(timerId); m_intervalHash.remove(timerId); } void Environment::timerEvent(QTimerEvent *event) { int id = event->timerId(); QScriptValue expression = m_intervalHash.value(id); if (!expression.isValid()) { expression = m_timeoutHash.value(id); if (expression.isValid()) killTimer(id); } if (expression.isString()) { evaluate(expression.toString()); } else if (expression.isFunction()) { expression.call(); } maybeEmitScriptError(); } //! [1] //! [5] void Environment::addCanvas(QContext2DCanvas *canvas) { m_canvases.append(canvas); } QContext2DCanvas *Environment::canvasByName(const QString &name) const { for (int i = 0; i < m_canvases.size(); ++i) { QContext2DCanvas *canvas = m_canvases.at(i); if (canvas->objectName() == name) return canvas; } return 0; } //! [5] QList Environment::canvases() const { return m_canvases; } void Environment::reset() { if (m_engine->isEvaluating()) m_engine->abortEvaluation(); { QHash::const_iterator it; for (it = m_intervalHash.constBegin(); it != m_intervalHash.constEnd(); ++it) killTimer(it.key()); m_intervalHash.clear(); for (it = m_timeoutHash.constBegin(); it != m_timeoutHash.constEnd(); ++it) killTimer(it.key()); m_timeoutHash.clear(); } for (int i = 0; i < m_canvases.size(); ++i) m_canvases.at(i)->reset(); QScriptValue self = m_engine->newQObject( this, QScriptEngine::QtOwnership, QScriptEngine::ExcludeSuperClassContents); { QScriptValueIterator it(m_originalGlobalObject); while (it.hasNext()) { it.next(); self.setProperty(it.scriptName(), it.value(), it.flags()); } } self.setProperty("self", self); self.setProperty("window", self); QScriptValue navigator = m_engine->newObject(); navigator.setProperty("appCodeName", "context2d"); navigator.setProperty("appMinorVersion", 1); navigator.setProperty("appVersion", 1); navigator.setProperty("browserLanguage", "en_US"); navigator.setProperty("cookieEnabled", false); navigator.setProperty("cpuClass", "i686"); navigator.setProperty("onLine", false); navigator.setProperty("platform", "bogus OS"); navigator.setProperty("systemLanguage", "en_US"); navigator.setProperty("userAgent", "Context2D/1.1"); navigator.setProperty("userLanguage", "en_US"); self.setProperty("navigator", navigator); m_engine->setGlobalObject(self); m_engine->collectGarbage(); } QScriptValue Environment::evaluate(const QString &code, const QString &fileName) { return m_engine->evaluate(code, fileName); } //! [2] QScriptValue Environment::toWrapper(QObject *object) { return m_engine->newQObject(object, QScriptEngine::QtOwnership, QScriptEngine::PreferExistingWrapperObject | QScriptEngine::ExcludeSuperClassContents); } //! [2] //! [3] void Environment::handleEvent(QContext2DCanvas *canvas, QMouseEvent *e) { QString type; switch (e->type()) { case QEvent::MouseButtonPress: type = "mousedown"; break; case QEvent::MouseButtonRelease: type = "mouseup"; break; case QEvent::MouseMove: type = "mousemove"; break; default: break; } if (type.isEmpty()) return; QScriptValue handlerObject; QScriptValue handler = eventHandler(canvas, type, &handlerObject); if (!handler.isFunction()) return; QScriptValue scriptEvent = newFakeDomEvent(type, toWrapper(canvas)); // MouseEvent scriptEvent.setProperty("screenX", e->globalX(), QScriptValue::ReadOnly); scriptEvent.setProperty("screenY", e->globalY(), QScriptValue::ReadOnly); scriptEvent.setProperty("clientX", e->x(), QScriptValue::ReadOnly); scriptEvent.setProperty("clientY", e->y(), QScriptValue::ReadOnly); scriptEvent.setProperty("layerX", e->x(), QScriptValue::ReadOnly); scriptEvent.setProperty("layerY", e->y(), QScriptValue::ReadOnly); scriptEvent.setProperty("pageX", e->x(), QScriptValue::ReadOnly); scriptEvent.setProperty("pageY", e->y(), QScriptValue::ReadOnly); scriptEvent.setProperty("altKey", (e->modifiers() & Qt::AltModifier) != 0, QScriptValue::ReadOnly); scriptEvent.setProperty("ctrlKey", (e->modifiers() & Qt::ControlModifier) != 0, QScriptValue::ReadOnly); scriptEvent.setProperty("metaKey", (e->modifiers() & Qt::MetaModifier) != 0, QScriptValue::ReadOnly); scriptEvent.setProperty("shiftKey", (e->modifiers() & Qt::ShiftModifier) != 0, QScriptValue::ReadOnly); int button = 0; if (e->button() == Qt::RightButton) button = 2; else if (e->button() == Qt::MidButton) button = 1; scriptEvent.setProperty("button", button); scriptEvent.setProperty("relatedTarget", m_engine->nullValue(), QScriptValue::ReadOnly); handler.call(handlerObject, QScriptValueList() << scriptEvent); maybeEmitScriptError(); } //! [3] void Environment::handleEvent(QContext2DCanvas *canvas, QKeyEvent *e) { QString type; switch (e->type()) { case QEvent::KeyPress: type = "keydown"; break; case QEvent::KeyRelease: type = "keyup"; break; default: break; } if (type.isEmpty()) return; QScriptValue handlerObject; QScriptValue handler = eventHandler(canvas, type, &handlerObject); if (!handler.isFunction()) return; QScriptValue scriptEvent = newFakeDomEvent(type, toWrapper(canvas)); // KeyEvent scriptEvent.setProperty("isChar", !e->text().isEmpty()); scriptEvent.setProperty("charCode", e->text()); scriptEvent.setProperty("keyCode", FakeDomEvent::qtToDomKey(e->key())); scriptEvent.setProperty("which", e->key()); handler.call(handlerObject, QScriptValueList() << scriptEvent); maybeEmitScriptError(); } QScriptValue Environment::eventHandler(QContext2DCanvas *canvas, const QString &type, QScriptValue *who) { QString handlerName = "on" + type; QScriptValue obj = toWrapper(canvas); QScriptValue handler = obj.property(handlerName); if (!handler.isValid()) { obj = m_document; handler = obj.property(handlerName); } if (who && handler.isFunction()) *who = obj; return handler; } //! [4] QScriptValue Environment::newFakeDomEvent(const QString &type, const QScriptValue &target) { QScriptValue e = m_engine->newObject(); // Event e.setProperty("type", type, QScriptValue::ReadOnly); e.setProperty("bubbles", true, QScriptValue::ReadOnly); e.setProperty("cancelable", false, QScriptValue::ReadOnly); e.setProperty("target", target, QScriptValue::ReadOnly); e.setProperty("currentTarget", target, QScriptValue::ReadOnly); e.setProperty("eventPhase", 3); // bubbling e.setProperty("timeStamp", QDateTime::currentDateTime().toTime_t()); // UIEvent e.setProperty("detail", 0, QScriptValue::ReadOnly); e.setProperty("view", m_engine->globalObject(), QScriptValue::ReadOnly); return e; } //! [4] void Environment::maybeEmitScriptError() { if (m_engine->hasUncaughtException()) emit scriptError(m_engine->uncaughtException()); } Document::Document(Environment *env) : QObject(env) { } Document::~Document() { } QScriptValue Document::getElementById(const QString &id) const { Environment *env = qobject_cast(parent()); QContext2DCanvas *canvas = env->canvasByName(id); if (!canvas) return QScriptValue(); return env->toWrapper(canvas); } QScriptValue Document::getElementsByTagName(const QString &name) const { if (name != "canvas") return QScriptValue(); Environment *env = qobject_cast(parent()); QList list = env->canvases(); QScriptValue result = env->engine()->newArray(list.size()); for (int i = 0; i < list.size(); ++i) result.setProperty(i, env->toWrapper(list.at(i))); return result; } void Document::addEventListener(const QString &type, const QScriptValue &listener, bool useCapture) { Q_UNUSED(useCapture); if (listener.isFunction()) { Environment *env = qobject_cast(parent()); QScriptValue self = env->toWrapper(this); self.setProperty("on" + type, listener); } } QColor colorFromString(const QString &name); CanvasGradientPrototype::CanvasGradientPrototype(QObject *parent) : QObject(parent) { } void CanvasGradientPrototype::addColorStop(qreal offset, const QString &color) { CanvasGradient *self = qscriptvalue_cast(thisObject()); if (!self || (self->value.type() == QGradient::NoGradient)) return; self->value.setColorAt(offset, colorFromString(color)); } void CanvasGradientPrototype::setup(QScriptEngine *engine) { CanvasGradientPrototype *proto = new CanvasGradientPrototype(); engine->setDefaultPrototype(qMetaTypeId(), engine->newQObject(proto, QScriptEngine::ScriptOwnership, QScriptEngine::ExcludeSuperClassContents)); } href='#n417'>417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
// Cyclic garbage collector implementation for free-threaded build.
#include "Python.h"
#include "pycore_brc.h"           // struct _brc_thread_state
#include "pycore_ceval.h"         // _Py_set_eval_breaker_bit()
#include "pycore_context.h"
#include "pycore_dict.h"          // _PyDict_MaybeUntrack()
#include "pycore_initconfig.h"
#include "pycore_interp.h"        // PyInterpreterState.gc
#include "pycore_object.h"
#include "pycore_object_alloc.h"  // _PyObject_MallocWithType()
#include "pycore_object_stack.h"
#include "pycore_pyerrors.h"
#include "pycore_pystate.h"       // _PyThreadState_GET()
#include "pycore_time.h"          // _PyTime_GetPerfCounter()
#include "pycore_tstate.h"        // _PyThreadStateImpl
#include "pycore_weakref.h"       // _PyWeakref_ClearRef()
#include "pydtrace.h"

#ifdef Py_GIL_DISABLED

typedef struct _gc_runtime_state GCState;

#ifdef Py_DEBUG
#  define GC_DEBUG
#endif

// Each thread buffers the count of allocated objects in a thread-local
// variable up to +/- this amount to reduce the overhead of updating
// the global count.
#define LOCAL_ALLOC_COUNT_THRESHOLD 512

// Automatically choose the generation that needs collecting.
#define GENERATION_AUTO (-1)

// A linked list of objects using the `ob_tid` field as the next pointer.
// The linked list pointers are distinct from any real thread ids, because the
// thread ids returned by _Py_ThreadId() are also pointers to distinct objects.
// No thread will confuse its own id with a linked list pointer.
struct worklist {
    uintptr_t head;
};

struct worklist_iter {
    uintptr_t *ptr;   // pointer to current object
    uintptr_t *next;  // next value of ptr
};

struct visitor_args {
    size_t offset;  // offset of PyObject from start of block
};

// Per-collection state
struct collection_state {
    struct visitor_args base;
    PyInterpreterState *interp;
    GCState *gcstate;
    Py_ssize_t collected;
    Py_ssize_t uncollectable;
    Py_ssize_t long_lived_total;
    struct worklist unreachable;
    struct worklist legacy_finalizers;
    struct worklist wrcb_to_call;
    struct worklist objs_to_decref;
};

// iterate over a worklist
#define WORKSTACK_FOR_EACH(stack, op) \
    for ((op) = (PyObject *)(stack)->head; (op) != NULL; (op) = (PyObject *)(op)->ob_tid)

// iterate over a worklist with support for removing the current object
#define WORKSTACK_FOR_EACH_ITER(stack, iter, op) \
    for (worklist_iter_init((iter), &(stack)->head), (op) = (PyObject *)(*(iter)->ptr); \
         (op) != NULL; \
         worklist_iter_init((iter), (iter)->next), (op) = (PyObject *)(*(iter)->ptr))

static void
worklist_push(struct worklist *worklist, PyObject *op)
{
    assert(op->ob_tid == 0);
    op->ob_tid = worklist->head;
    worklist->head = (uintptr_t)op;
}

static PyObject *
worklist_pop(struct worklist *worklist)
{
    PyObject *op = (PyObject *)worklist->head;
    if (op != NULL) {
        worklist->head = op->ob_tid;
        op->ob_tid = 0;
    }
    return op;
}

static void
worklist_iter_init(struct worklist_iter *iter, uintptr_t *next)
{
    iter->ptr = next;
    PyObject *op = (PyObject *)*(iter->ptr);
    if (op) {
        iter->next = &op->ob_tid;
    }
}

static void
worklist_remove(struct worklist_iter *iter)
{
    PyObject *op = (PyObject *)*(iter->ptr);
    *(iter->ptr) = op->ob_tid;
    op->ob_tid = 0;
    iter->next = iter->ptr;
}

static inline int
gc_is_unreachable(PyObject *op)
{
    return (op->ob_gc_bits & _PyGC_BITS_UNREACHABLE) != 0;
}

static void
gc_set_unreachable(PyObject *op)
{
    op->ob_gc_bits |= _PyGC_BITS_UNREACHABLE;
}

static void
gc_clear_unreachable(PyObject *op)
{
    op->ob_gc_bits &= ~_PyGC_BITS_UNREACHABLE;
}

// Initialize the `ob_tid` field to zero if the object is not already
// initialized as unreachable.
static void
gc_maybe_init_refs(PyObject *op)
{
    if (!gc_is_unreachable(op)) {
        gc_set_unreachable(op);
        op->ob_tid = 0;
    }
}

static inline Py_ssize_t
gc_get_refs(PyObject *op)
{
    return (Py_ssize_t)op->ob_tid;
}

static inline void
gc_add_refs(PyObject *op, Py_ssize_t refs)
{
    assert(_PyObject_GC_IS_TRACKED(op));
    op->ob_tid += refs;
}

static inline void
gc_decref(PyObject *op)
{
    op->ob_tid -= 1;
}

static Py_ssize_t
merge_refcount(PyObject *op, Py_ssize_t extra)
{
    assert(_PyInterpreterState_GET()->stoptheworld.world_stopped);

    Py_ssize_t refcount = Py_REFCNT(op);
    refcount += extra;

#ifdef Py_REF_DEBUG
    _Py_AddRefTotal(_PyInterpreterState_GET(), extra);
#endif

    // No atomics necessary; all other threads in this interpreter are paused.
    op->ob_tid = 0;
    op->ob_ref_local = 0;
    op->ob_ref_shared = _Py_REF_SHARED(refcount, _Py_REF_MERGED);
    return refcount;
}

static void
gc_restore_tid(PyObject *op)
{
    mi_segment_t *segment = _mi_ptr_segment(op);
    if (_Py_REF_IS_MERGED(op->ob_ref_shared)) {
        op->ob_tid = 0;
    }
    else {
        // NOTE: may change ob_tid if the object was re-initialized by
        // a different thread or its segment was abandoned and reclaimed.
        // The segment thread id might be zero, in which case we should
        // ensure the refcounts are now merged.
        op->ob_tid = segment->thread_id;
        if (op->ob_tid == 0) {
            merge_refcount(op, 0);
        }
    }
}

static void
gc_restore_refs(PyObject *op)
{
    if (gc_is_unreachable(op)) {
        gc_restore_tid(op);
        gc_clear_unreachable(op);
    }
}

// Given a mimalloc memory block return the PyObject stored in it or NULL if
// the block is not allocated or the object is not tracked or is immortal.
static PyObject *
op_from_block(void *block, void *arg, bool include_frozen)
{
    struct visitor_args *a = arg;
    if (block == NULL) {
        return NULL;
    }
    PyObject *op = (PyObject *)((char*)block + a->offset);
    assert(PyObject_IS_GC(op));
    if (!_PyObject_GC_IS_TRACKED(op)) {
        return NULL;
    }
    if (!include_frozen && (op->ob_gc_bits & _PyGC_BITS_FROZEN) != 0) {
        return NULL;
    }
    return op;
}

static int
gc_visit_heaps_lock_held(PyInterpreterState *interp, mi_block_visit_fun *visitor,
                         struct visitor_args *arg)
{
    // Offset of PyObject header from start of memory block.
    Py_ssize_t offset_base = 0;
    if (_PyMem_DebugEnabled()) {
        // The debug allocator adds two words at the beginning of each block.
        offset_base += 2 * sizeof(size_t);
    }

    // Objects with Py_TPFLAGS_PREHEADER have two extra fields
    Py_ssize_t offset_pre = offset_base + 2 * sizeof(PyObject*);

    // visit each thread's heaps for GC objects
    for (PyThreadState *p = interp->threads.head; p != NULL; p = p->next) {
        struct _mimalloc_thread_state *m = &((_PyThreadStateImpl *)p)->mimalloc;

        arg->offset = offset_base;
        if (!mi_heap_visit_blocks(&m->heaps[_Py_MIMALLOC_HEAP_GC], true,
                                  visitor, arg)) {
            return -1;
        }
        arg->offset = offset_pre;
        if (!mi_heap_visit_blocks(&m->heaps[_Py_MIMALLOC_HEAP_GC_PRE], true,
                                  visitor, arg)) {
            return -1;
        }
    }

    // visit blocks in the per-interpreter abandoned pool (from dead threads)
    mi_abandoned_pool_t *pool = &interp->mimalloc.abandoned_pool;
    arg->offset = offset_base;
    if (!_mi_abandoned_pool_visit_blocks(pool, _Py_MIMALLOC_HEAP_GC, true,
                                         visitor, arg)) {
        return -1;
    }
    arg->offset = offset_pre;
    if (!_mi_abandoned_pool_visit_blocks(pool, _Py_MIMALLOC_HEAP_GC_PRE, true,
                                         visitor, arg)) {
        return -1;
    }
    return 0;
}

// Visits all GC objects in the interpreter's heaps.
// NOTE: It is not safe to allocate or free any mimalloc managed memory while
// this function is running.
static int
gc_visit_heaps(PyInterpreterState *interp, mi_block_visit_fun *visitor,
               struct visitor_args *arg)
{
    // Other threads in the interpreter must be paused so that we can safely
    // traverse their heaps.
    assert(interp->stoptheworld.world_stopped);

    int err;
    HEAD_LOCK(&_PyRuntime);
    err = gc_visit_heaps_lock_held(interp, visitor, arg);
    HEAD_UNLOCK(&_PyRuntime);
    return err;
}

static void
merge_queued_objects(_PyThreadStateImpl *tstate, struct collection_state *state)
{
    struct _brc_thread_state *brc = &tstate->brc;
    _PyObjectStack_Merge(&brc->local_objects_to_merge, &brc->objects_to_merge);

    PyObject *op;
    while ((op = _PyObjectStack_Pop(&brc->local_objects_to_merge)) != NULL) {
        // Subtract one when merging because the queue had a reference.
        Py_ssize_t refcount = merge_refcount(op, -1);

        if (!_PyObject_GC_IS_TRACKED(op) && refcount == 0) {
            // GC objects with zero refcount are handled subsequently by the
            // GC as if they were cyclic trash, but we have to handle dead
            // non-GC objects here. Add one to the refcount so that we can
            // decref and deallocate the object once we start the world again.
            op->ob_ref_shared += (1 << _Py_REF_SHARED_SHIFT);
#ifdef Py_REF_DEBUG
            _Py_IncRefTotal(_PyInterpreterState_GET());
#endif
            worklist_push(&state->objs_to_decref, op);
        }
    }
}

static void
merge_all_queued_objects(PyInterpreterState *interp, struct collection_state *state)
{
    HEAD_LOCK(&_PyRuntime);
    for (PyThreadState *p = interp->threads.head; p != NULL; p = p->next) {
        merge_queued_objects((_PyThreadStateImpl *)p, state);
    }
    HEAD_UNLOCK(&_PyRuntime);
}

static void
process_delayed_frees(PyInterpreterState *interp)
{
    // In STW status, we can observe the latest write sequence by
    // advancing the write sequence immediately.
    _Py_qsbr_advance(&interp->qsbr);
    _PyThreadStateImpl *current_tstate = (_PyThreadStateImpl *)_PyThreadState_GET();
    _Py_qsbr_quiescent_state(current_tstate->qsbr);
    HEAD_LOCK(&_PyRuntime);
    PyThreadState *tstate = interp->threads.head;
    while (tstate != NULL) {
        _PyMem_ProcessDelayed(tstate);
        tstate = (PyThreadState *)tstate->next;
    }
    HEAD_UNLOCK(&_PyRuntime);
}

// Subtract an incoming reference from the computed "gc_refs" refcount.
static int
visit_decref(PyObject *op, void *arg)
{
    if (_PyObject_GC_IS_TRACKED(op) && !_Py_IsImmortal(op)) {
        // If update_refs hasn't reached this object yet, mark it
        // as (tentatively) unreachable and initialize ob_tid to zero.
        gc_maybe_init_refs(op);
        gc_decref(op);
    }
    return 0;
}

// Compute the number of external references to objects in the heap
// by subtracting internal references from the refcount. The difference is
// computed in the ob_tid field (we restore it later).
static bool
update_refs(const mi_heap_t *heap, const mi_heap_area_t *area,
            void *block, size_t block_size, void *args)
{
    PyObject *op = op_from_block(block, args, false);
    if (op == NULL) {
        return true;
    }

    // Exclude immortal objects from garbage collection
    if (_Py_IsImmortal(op)) {
        op->ob_tid = 0;
        _PyObject_GC_UNTRACK(op);
        gc_clear_unreachable(op);
        return true;
    }

    // Untrack tuples and dicts as necessary in this pass.
    if (PyTuple_CheckExact(op)) {
        _PyTuple_MaybeUntrack(op);
        if (!_PyObject_GC_IS_TRACKED(op)) {
            gc_restore_refs(op);
            return true;
        }
    }
    else if (PyDict_CheckExact(op)) {
        _PyDict_MaybeUntrack(op);
        if (!_PyObject_GC_IS_TRACKED(op)) {
            gc_restore_refs(op);
            return true;
        }
    }

    Py_ssize_t refcount = Py_REFCNT(op);
    _PyObject_ASSERT(op, refcount >= 0);

    // We repurpose ob_tid to compute "gc_refs", the number of external
    // references to the object (i.e., from outside the GC heaps). This means
    // that ob_tid is no longer a valid thread id until it is restored by
    // scan_heap_visitor(). Until then, we cannot use the standard reference
    // counting functions or allow other threads to run Python code.
    gc_maybe_init_refs(op);

    // Add the actual refcount to ob_tid.
    gc_add_refs(op, refcount);

    // Subtract internal references from ob_tid. Objects with ob_tid > 0
    // are directly reachable from outside containers, and so can't be
    // collected.
    Py_TYPE(op)->tp_traverse(op, visit_decref, NULL);
    return true;
}

static int
visit_clear_unreachable(PyObject *op, _PyObjectStack *stack)
{
    if (gc_is_unreachable(op)) {
        _PyObject_ASSERT(op, _PyObject_GC_IS_TRACKED(op));
        gc_clear_unreachable(op);
        return _PyObjectStack_Push(stack, op);
    }
    return 0;
}

// Transitively clear the unreachable bit on all objects reachable from op.
static int
mark_reachable(PyObject *op)
{
    _PyObjectStack stack = { NULL };
    do {
        traverseproc traverse = Py_TYPE(op)->tp_traverse;
        if (traverse(op, (visitproc)&visit_clear_unreachable, &stack) < 0) {
            _PyObjectStack_Clear(&stack);
            return -1;
        }
        op = _PyObjectStack_Pop(&stack);
    } while (op != NULL);
    return 0;
}

#ifdef GC_DEBUG
static bool
validate_gc_objects(const mi_heap_t *heap, const mi_heap_area_t *area,
                    void *block, size_t block_size, void *args)
{
    PyObject *op = op_from_block(block, args, false);
    if (op == NULL) {
        return true;
    }

    _PyObject_ASSERT(op, gc_is_unreachable(op));
    _PyObject_ASSERT_WITH_MSG(op, gc_get_refs(op) >= 0,
                                  "refcount is too small");
    return true;
}
#endif

static bool
mark_heap_visitor(const mi_heap_t *heap, const mi_heap_area_t *area,
                  void *block, size_t block_size, void *args)
{
    PyObject *op = op_from_block(block, args, false);
    if (op == NULL) {
        return true;
    }

    if (gc_is_unreachable(op) && gc_get_refs(op) != 0) {
        // Object is reachable but currently marked as unreachable.
        // Mark it as reachable and traverse its pointers to find
        // any other object that may be directly reachable from it.
        gc_clear_unreachable(op);

        // Transitively mark reachable objects by clearing the unreachable flag.
        if (mark_reachable(op) < 0) {
            return false;
        }
    }

    return true;
}

/* Return true if object has a pre-PEP 442 finalization method. */
static int
has_legacy_finalizer(PyObject *op)
{
    return Py_TYPE(op)->tp_del != NULL;
}

static bool
scan_heap_visitor(const mi_heap_t *heap, const mi_heap_area_t *area,
                  void *block, size_t block_size, void *args)
{
    PyObject *op = op_from_block(block, args, false);
    if (op == NULL) {
        return true;
    }

    struct collection_state *state = (struct collection_state *)args;
    if (gc_is_unreachable(op)) {
        // Merge and add one to the refcount to prevent deallocation while we
        // are holding on to it in a worklist.
        merge_refcount(op, 1);

        if (has_legacy_finalizer(op)) {
            // would be unreachable, but has legacy finalizer
            gc_clear_unreachable(op);
            worklist_push(&state->legacy_finalizers, op);
        }
        else {
            worklist_push(&state->unreachable, op);
        }
    }
    else {
        // object is reachable, restore `ob_tid`; we're done with these objects
        gc_restore_tid(op);
        state->long_lived_total++;
    }

    return true;
}

static int
move_legacy_finalizer_reachable(struct collection_state *state);

static int
deduce_unreachable_heap(PyInterpreterState *interp,
                        struct collection_state *state)
{
    // Identify objects that are directly reachable from outside the GC heap
    // by computing the difference between the refcount and the number of
    // incoming references.
    gc_visit_heaps(interp, &update_refs, &state->base);

#ifdef GC_DEBUG
    // Check that all objects are marked as unreachable and that the computed
    // reference count difference (stored in `ob_tid`) is non-negative.
    gc_visit_heaps(interp, &validate_gc_objects, &state->base);
#endif

    // Transitively mark reachable objects by clearing the
    // _PyGC_BITS_UNREACHABLE flag.
    if (gc_visit_heaps(interp, &mark_heap_visitor, &state->base) < 0) {
        return -1;
    }

    // Identify remaining unreachable objects and push them onto a stack.
    // Restores ob_tid for reachable objects.
    gc_visit_heaps(interp, &scan_heap_visitor, &state->base);

    if (state->legacy_finalizers.head) {
        // There may be objects reachable from legacy finalizers that are in
        // the unreachable set. We need to mark them as reachable.
        if (move_legacy_finalizer_reachable(state) < 0) {
            return -1;
        }
    }

    return 0;
}

static int
move_legacy_finalizer_reachable(struct collection_state *state)
{
    // Clear the reachable bit on all objects transitively reachable
    // from the objects with legacy finalizers.
    PyObject *op;
    WORKSTACK_FOR_EACH(&state->legacy_finalizers, op) {
        if (mark_reachable(op) < 0) {
            return -1;
        }
    }

    // Move the reachable objects from the unreachable worklist to the legacy
    // finalizer worklist.
    struct worklist_iter iter;
    WORKSTACK_FOR_EACH_ITER(&state->unreachable, &iter, op) {
        if (!gc_is_unreachable(op)) {
            worklist_remove(&iter);
            worklist_push(&state->legacy_finalizers, op);
        }
    }

    return 0;
}

// Clear all weakrefs to unreachable objects. Weakrefs with callbacks are
// enqueued in `wrcb_to_call`, but not invoked yet.
static void
clear_weakrefs(struct collection_state *state)
{
    PyObject *op;
    WORKSTACK_FOR_EACH(&state->unreachable, op) {
        if (PyWeakref_Check(op)) {
            // Clear weakrefs that are themselves unreachable to ensure their
            // callbacks will not be executed later from a `tp_clear()`
            // inside delete_garbage(). That would be unsafe: it could
            // resurrect a dead object or access a an already cleared object.
            // See bpo-38006 for one example.
            _PyWeakref_ClearRef((PyWeakReference *)op);
        }

        if (!_PyType_SUPPORTS_WEAKREFS(Py_TYPE(op))) {
            continue;
        }

        // NOTE: This is never triggered for static types so we can avoid the
        // (slightly) more costly _PyObject_GET_WEAKREFS_LISTPTR().
        PyWeakReference **wrlist = _PyObject_GET_WEAKREFS_LISTPTR_FROM_OFFSET(op);

        // `op` may have some weakrefs.  March over the list, clear
        // all the weakrefs, and enqueue the weakrefs with callbacks
        // that must be called into wrcb_to_call.
        for (PyWeakReference *wr = *wrlist; wr != NULL; wr = *wrlist) {
            // _PyWeakref_ClearRef clears the weakref but leaves
            // the callback pointer intact.  Obscure: it also
            // changes *wrlist.
            _PyObject_ASSERT((PyObject *)wr, wr->wr_object == op);
            _PyWeakref_ClearRef(wr);
            _PyObject_ASSERT((PyObject *)wr, wr->wr_object == Py_None);

            // We do not invoke callbacks for weakrefs that are themselves
            // unreachable. This is partly for historical reasons: weakrefs
            // predate safe object finalization, and a weakref that is itself
            // unreachable may have a callback that resurrects other
            // unreachable objects.
            if (wr->wr_callback == NULL || gc_is_unreachable((PyObject *)wr)) {
                continue;
            }

            // Create a new reference so that wr can't go away before we can
            // process it again.
            merge_refcount((PyObject *)wr, 1);

            // Enqueue weakref to be called later.
            worklist_push(&state->wrcb_to_call, (PyObject *)wr);
        }
    }
}

static void
call_weakref_callbacks(struct collection_state *state)
{
    // Invoke the callbacks we decided to honor.
    PyObject *op;
    while ((op = worklist_pop(&state->wrcb_to_call)) != NULL) {
        _PyObject_ASSERT(op, PyWeakref_Check(op));

        PyWeakReference *wr = (PyWeakReference *)op;
        PyObject *callback = wr->wr_callback;
        _PyObject_ASSERT(op, callback != NULL);

        /* copy-paste of weakrefobject.c's handle_callback() */
        PyObject *temp = PyObject_CallOneArg(callback, (PyObject *)wr);
        if (temp == NULL) {
            PyErr_WriteUnraisable(callback);
        }
        else {
            Py_DECREF(temp);
        }

        gc_restore_tid(op);
        Py_DECREF(op);  // drop worklist reference
    }
}


static GCState *
get_gc_state(void)
{
    PyInterpreterState *interp = _PyInterpreterState_GET();
    return &interp->gc;
}


void
_PyGC_InitState(GCState *gcstate)
{
    // TODO: move to pycore_runtime_init.h once the incremental GC lands.
    gcstate->generations[0].threshold = 2000;
}


PyStatus
_PyGC_Init(PyInterpreterState *interp)
{
    GCState *gcstate = &interp->gc;

    gcstate->garbage = PyList_New(0);
    if (gcstate->garbage == NULL) {
        return _PyStatus_NO_MEMORY();
    }

    gcstate->callbacks = PyList_New(0);
    if (gcstate->callbacks == NULL) {
        return _PyStatus_NO_MEMORY();
    }

    return _PyStatus_OK();
}

static void
debug_cycle(const char *msg, PyObject *op)
{
    PySys_FormatStderr("gc: %s <%s %p>\n",
                       msg, Py_TYPE(op)->tp_name, op);
}

/* Run first-time finalizers (if any) on all the objects in collectable.
 * Note that this may remove some (or even all) of the objects from the
 * list, due to refcounts falling to 0.
 */
static void
finalize_garbage(struct collection_state *state)
{
    // NOTE: the unreachable worklist holds a strong reference to the object
    // to prevent it from being deallocated while we are holding on to it.
    PyObject *op;
    WORKSTACK_FOR_EACH(&state->unreachable, op) {
        if (!_PyGC_FINALIZED(op)) {
            destructor finalize = Py_TYPE(op)->tp_finalize;
            if (finalize != NULL) {
                _PyGC_SET_FINALIZED(op);
                finalize(op);
                assert(!_PyErr_Occurred(_PyThreadState_GET()));
            }
        }
    }
}

// Break reference cycles by clearing the containers involved.
static void
delete_garbage(struct collection_state *state)
{
    PyThreadState *tstate = _PyThreadState_GET();
    GCState *gcstate = state->gcstate;

    assert(!_PyErr_Occurred(tstate));

    PyObject *op;
    while ((op = worklist_pop(&state->objs_to_decref)) != NULL) {
        Py_DECREF(op);
    }

    while ((op = worklist_pop(&state->unreachable)) != NULL) {
        _PyObject_ASSERT(op, gc_is_unreachable(op));

        // Clear the unreachable flag.
        gc_clear_unreachable(op);

        if (!_PyObject_GC_IS_TRACKED(op)) {
            // Object might have been untracked by some other tp_clear() call.
            Py_DECREF(op);  // drop the reference from the worklist
            continue;
        }

        state->collected++;

        if (gcstate->debug & _PyGC_DEBUG_SAVEALL) {
            assert(gcstate->garbage != NULL);
            if (PyList_Append(gcstate->garbage, op) < 0) {
                _PyErr_Clear(tstate);
            }
        }
        else {
            inquiry clear = Py_TYPE(op)->tp_clear;
            if (clear != NULL) {
                (void) clear(op);
                if (_PyErr_Occurred(tstate)) {
                    PyErr_FormatUnraisable("Exception ignored in tp_clear of %s",
                                           Py_TYPE(op)->tp_name);
                }
            }
        }

        Py_DECREF(op);  // drop the reference from the worklist
    }
}

static void
handle_legacy_finalizers(struct collection_state *state)
{
    GCState *gcstate = state->gcstate;
    assert(gcstate->garbage != NULL);

    PyObject *op;
    while ((op = worklist_pop(&state->legacy_finalizers)) != NULL) {
        state->uncollectable++;

        if (gcstate->debug & _PyGC_DEBUG_UNCOLLECTABLE) {
            debug_cycle("uncollectable", op);
        }