1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 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 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
|
/** Implementation of NSObject for GNUStep
Copyright (C) 1994-2017 Free Software Foundation, Inc.
Written by: Andrew Kachites McCallum <mccallum@gnu.ai.mit.edu>
Date: August 1994
This file is part of the GNUstep Base Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 31 Milk Street #960789 Boston, MA 02196 USA.
<title>NSObject class reference</title>
$Date$ $Revision$
*/
/* On some versions of mingw we need to work around bad function declarations
* by defining them away and doing the declarations ourself later.
*/
#ifndef _WIN64
#define InterlockedIncrement BadInterlockedIncrement
#define InterlockedDecrement BadInterlockedDecrement
#endif
#import "common.h"
#include <objc/Protocol.h>
#include <objc/message.h>
#import "Foundation/NSMethodSignature.h"
#import "Foundation/NSInvocation.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSAutoreleasePool.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSException.h"
#import "Foundation/NSHashTable.h"
#import "Foundation/NSPortCoder.h"
#import "Foundation/NSDistantObject.h"
#import "Foundation/NSThread.h"
#import "Foundation/NSNotification.h"
#import "Foundation/NSMapTable.h"
#import "Foundation/NSUserDefaults.h"
#import "GNUstepBase/GSLocale.h"
#ifdef HAVE_LOCALE_H
#include <locale.h>
#endif
#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif
#import "GSPThread.h"
#if defined(HAVE_SYS_SIGNAL_H)
# include <sys/signal.h>
#elif defined(HAVE_SIGNAL_H)
# include <signal.h>
#endif
#if __GNUC__ >= 4
#if defined(__FreeBSD__)
#include <fenv.h>
#endif
#endif // __GNUC__
#define IN_NSOBJECT_M 1
#import "GSPrivate.h"
#ifdef __GNUSTEP_RUNTIME__
#include <objc/capabilities.h>
#include <objc/hooks.h>
#ifdef OBJC_CAP_ARC
#include <objc/objc-arc.h>
#endif
#endif
/* objc_enumerationMutation() is called whenever a collection mutates in the
* middle of fast enumeration. We need to have this defined and linked into
* any code that uses fast enumeration, so we define it in NSObject.h
* This symbol is exported to take precedence over the weak symbol provided
* by the runtime library.
*/
GS_EXPORT void objc_enumerationMutation(id obj)
{
[NSException raise: NSGenericException
format: @"Collection %@ was mutated while being enumerated", obj];
}
/* platforms which do not support weak */
#if defined (__WIN32)
#define WEAK_ATTRIBUTE
#else
/* all platforms which support weak */
#define WEAK_ATTRIBUTE __attribute__((weak))
#endif
/* When this is `YES', every call to release/autorelease, checks to
make sure isn't being set up to release itself too many times.
This does not need mutex protection. */
static BOOL double_release_check_enabled = NO;
/* The Class responsible for handling autorelease's. This does not
need mutex protection, since it is simply a pointer that gets read
and set. */
static id autorelease_class = nil;
static SEL autorelease_sel;
static IMP autorelease_imp;
static SEL finalize_sel;
static IMP finalize_imp;
static Class NSConstantStringClass;
@class NSDataMalloc;
@class NSMutableDataMalloc;
GS_ROOT_CLASS @interface NSZombie
{
Class isa;
}
- (Class) class;
- (void) forwardInvocation: (NSInvocation*)anInvocation;
- (NSMethodSignature*) methodSignatureForSelector: (SEL)aSelector;
@end
@interface GSContentAccessingProxy : NSProxy
{
NSObject<NSDiscardableContent> *object;
}
- (id) initWithObject: (id)anObject;
@end
/* allocationLock is needed when for protecting the map table of zombie
* information and if atomic operations are not available.
*/
static gs_mutex_t allocationLock = GS_MUTEX_INIT_STATIC;
BOOL NSZombieEnabled = NO;
BOOL NSDeallocateZombies = NO;
@class NSZombie;
static Class zombieClass = Nil;
static NSMapTable *zombieMap = 0;
static void GSMakeZombie(NSObject *o, Class c)
{
object_setClass(o, zombieClass);
if (0 != zombieMap)
{
GS_MUTEX_LOCK(allocationLock);
if (0 != zombieMap)
{
NSMapInsert(zombieMap, (void*)o, (void*)c);
}
GS_MUTEX_UNLOCK(allocationLock);
}
}
extern void GSLogZombie(id o, SEL sel)
{
Class c = 0;
if (0 != zombieMap)
{
GS_MUTEX_LOCK(allocationLock);
if (0 != zombieMap)
{
c = NSMapGet(zombieMap, (void*)o);
}
GS_MUTEX_UNLOCK(allocationLock);
}
if (c == 0)
{
fprintf(stderr, "*** -[??? %s]: message sent to deallocated instance %p",
sel_getName(sel), o);
}
else
{
fprintf(stderr, "*** -[%s %s]: message sent to deallocated instance %p",
class_getName(c), sel_getName(sel), o);
}
if (GSPrivateEnvironmentFlag("CRASH_ON_ZOMBIE", NO) == YES)
{
abort();
}
}
/*
* Reference count and memory management
* Reference counts for object are stored
* with the object.
* The zone in which an object has been
* allocated is stored with the object.
*/
/* Now, if we are on a platform where we know how to do atomic
* read, increment, and decrement, then we define the GSATOMICREAD
* macro and macros or functions to increment/decrement.
* The presence of the GSATOMICREAD macro is used later to determine
* whether to attempt atomic operations or to use locking for the
* retain/release mechanism.
* The GSAtomicIncrement() and GSAtomicDecrement() functions take a
* pointer to a 32bit integer as an argument, increment/decrement the
* value pointed to, and return the result.
*/
#ifdef GSATOMICREAD
#undef GSATOMICREAD
#endif
#ifdef OBJC_CAP_ARC
typedef intptr_t volatile *gsatomic_t;
typedef intptr_t gsrefcount_t;
#define GSATOMICREAD(X) (*(X))
#define GSAtomicIncrement(X) __sync_add_and_fetch(X, 1)
#define GSAtomicDecrement(X) __sync_sub_and_fetch(X, 1)
#elif (defined(USE_ATOMIC_BUILTINS) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)))
/* Use the GCC atomic operations with recent GCC versions */
typedef int32_t volatile *gsatomic_t;
typedef int32_t gsrefcount_t;
#define GSATOMICREAD(X) (*(X))
#define GSAtomicIncrement(X) __sync_add_and_fetch(X, 1)
#define GSAtomicDecrement(X) __sync_sub_and_fetch(X, 1)
#elif defined(_WIN32)
/* Set up atomic read, increment and decrement for mswindows
*/
typedef int32_t volatile *gsatomic_t;
typedef int32_t gsrefcount_t;
#ifndef _WIN64
#undef InterlockedIncrement
#undef InterlockedDecrement
LONG WINAPI InterlockedIncrement(LONG volatile *);
LONG WINAPI InterlockedDecrement(LONG volatile *);
#endif
#define GSATOMICREAD(X) (*(X))
#define GSAtomicIncrement(X) InterlockedIncrement(X)
#define GSAtomicDecrement(X) InterlockedDecrement(X)
#elif defined(__linux__) && (defined(__i386__) || defined(__x86_64__))
/* Set up atomic read, increment and decrement for intel style linux
*/
typedef int32_t volatile *gsatomic_t;
typedef int32_t gsrefcount_t;
#define GSATOMICREAD(X) (*(X))
static __inline__ int32_t
GSAtomicIncrement(gsatomic_t X)
{
register int32_t tmp;
__asm__ __volatile__ (
"movl $1, %0\n"
"lock xaddl %0, %1"
:"=r" (tmp), "=m" (*X)
:"r" (tmp), "m" (*X)
:"memory" );
return tmp + 1;
}
static __inline__ int32_t
GSAtomicDecrement(gsatomic_t X)
{
register int32_t tmp;
__asm__ __volatile__ (
"movl $1, %0\n"
"negl %0\n"
"lock xaddl %0, %1"
:"=r" (tmp), "=m" (*X)
:"r" (tmp), "m" (*X)
:"memory" );
return tmp - 1;
}
#elif defined(__PPC__) || defined(__POWERPC__)
typedef int32_t volatile *gsatomic_t;
typedef int32_t gsrefcount_t;
#define GSATOMICREAD(X) (*(X))
static __inline__ int32_t
GSAtomicIncrement(gsatomic_t X)
{
int32_t tmp;
__asm__ __volatile__ (
"0:"
"lwarx %0,0,%1 \n"
"addic %0,%0,1 \n"
"stwcx. %0,0,%1 \n"
"bne- 0b \n"
:"=&r" (tmp)
:"r" (X)
:"cc", "memory");
return tmp;
}
static __inline__ int32_t
GSAtomicDecrement(gsatomic_t X)
{
int32_t tmp;
__asm__ __volatile__ (
"0:"
"lwarx %0,0,%1 \n"
"addic %0,%0,-1 \n"
"stwcx. %0,0,%1 \n"
"bne- 0b \n"
:"=&r" (tmp)
:"r" (X)
:"cc", "memory");
return tmp;
}
#elif defined(__m68k__)
typedef int32_t volatile *gsatomic_t;
typedef int32_t gsrefcount_t;
#define GSATOMICREAD(X) (*(X))
static __inline__ int32_t
GSAtomicIncrement(gsatomic_t X)
{
__asm__ __volatile__ (
"addq%.l %#1, %0"
:"=m" (*X));
return *X;
}
static __inline__ int32_t
GSAtomicDecrement(gsatomic_t X)
{
__asm__ __volatile__ (
"subq%.l %#1, %0"
:"=m" (*X));
return *X;
}
#elif defined(__mips__)
typedef int32_t volatile *gsatomic_t;
typedef int32_t gsrefcount_t;
#define GSATOMICREAD(X) (*(X))
static __inline__ int32_t
GSAtomicIncrement(gsatomic_t X)
{
int32_t tmp;
__asm__ __volatile__ (
#if !defined(__mips64)
" .set mips2 \n"
#endif
"0: ll %0, %1 \n"
" addiu %0, 1 \n"
" sc %0, %1 \n"
" beqz %0, 0b \n"
:"=&r" (tmp), "=m" (*X));
return tmp;
}
static __inline__ int32_t
GSAtomicDecrement(gsatomic_t X)
{
int32_t tmp;
__asm__ __volatile__ (
#if !defined(__mips64)
" .set mips2 \n"
#endif
"0: ll %0, %1 \n"
" addiu %0, -1 \n"
" sc %0, %1 \n"
" beqz %0, 0b \n"
:"=&r" (tmp), "=m" (*X));
return tmp;
}
#endif
#if !defined(GSATOMICREAD)
#include <pthread.h>
typedef int32_t gsrefcount_t; // No atomics, use a simple integer
/* Having just one allocationLock for all leads to lock contention
* if there are lots of threads doing lots of retain/release calls.
* To alleviate this, instead of a single
* allocationLock for all objects, we divide the object space into
* chunks, each with its own lock. The chunk is selected by shifting
* off the low-order ALIGNBITS of the object's pointer (these bits
* are presumably always zero) and take
* the low-order LOCKBITS of the result to index into a table of locks.
*/
#define LOCKBITS 5
#define LOCKCOUNT (1<<LOCKBITS)
#define LOCKMASK (LOCKCOUNT-1)
#define ALIGNBITS 3
static pthread_mutex_t allocationLocks[LOCKCOUNT];
static inline pthread_mutex_t *GSAllocationLockForObject(id p)
{
NSUInteger i = ((((NSUInteger)(uintptr_t)p) >> ALIGNBITS) & LOCKMASK);
return &allocationLocks[i];
}
#endif
#if defined(__GNUC__) && __GNUC__ < 4
#define __builtin_offsetof(s, f) (uintptr_t)(&(((s*)0)->f))
#endif
#define alignof(type) __builtin_offsetof(struct { const char c; type member; }, member)
#ifndef OBJC_CAP_ARC
typedef struct {
BOOL hadWeakReference: 1; // set if the instance ever had a weak reference
} gsinstinfo_t;
#endif
/*
* Define a structure to hold information that is held locally
* (before the start) in each object.
*/
typedef struct obj_layout_unpadded {
gsrefcount_t retained;
#ifndef OBJC_CAP_ARC
gsinstinfo_t extra;
#endif
} unp;
#define UNP sizeof(unp)
/* GCC provides a defined value for the largest alignment required on a
* machine, and we must lay objects out to that alignment.
* For compilers that don't define it, we try to pick a likely value.
*/
#ifndef __BIGGEST_ALIGNMENT__
#define __BIGGEST_ALIGNMENT__ (SIZEOF_VOIDP * 2)
#endif
/*
* Now do the REAL version - using the other version to determine
* what padding (if any) is required to get the alignment of the
* structure correct.
*/
struct obj_layout {
char padding[__BIGGEST_ALIGNMENT__ - ((UNP % __BIGGEST_ALIGNMENT__)
? (UNP % __BIGGEST_ALIGNMENT__) : __BIGGEST_ALIGNMENT__)];
gsrefcount_t retained;
#ifndef OBJC_CAP_ARC
gsinstinfo_t extra;
#endif
};
typedef struct obj_layout *obj;
#ifndef OBJC_CAP_ARC
BOOL
GSPrivateMarkedWeak(id anObject, BOOL mark)
{
BOOL wasMarked = ((obj)anObject)[-1].extra.hadWeakReference;
if (mark)
{
((obj)anObject)[-1].extra.hadWeakReference = YES;
}
return wasMarked;
}
#endif
/*
* These symbols are provided by newer versions of the GNUstep Objective-C
* runtime. When linked against an older version, we will use our internal
* versions.
*/
GS_IMPORT WEAK_ATTRIBUTE
BOOL objc_release_fast_no_destroy_np(id anObject);
GS_IMPORT WEAK_ATTRIBUTE
void objc_release_fast_np(id anObject);
GS_IMPORT WEAK_ATTRIBUTE
size_t object_getRetainCount_np(id anObject);
GS_IMPORT WEAK_ATTRIBUTE
id objc_retain_fast_np(id anObject);
static BOOL objc_release_fast_no_destroy_internal(id anObject)
{
if (double_release_check_enabled)
{
NSUInteger release_count;
NSUInteger retain_count = [anObject retainCount];
release_count = [autorelease_class autoreleaseCountForObject: anObject];
if (release_count >= retain_count)
[NSException raise: NSGenericException
format: @"Release would release object too many times."];
}
{
#if defined(GSATOMICREAD)
gsrefcount_t result;
result = GSAtomicDecrement((gsatomic_t)&(((obj)anObject)[-1].retained));
if (result < 0)
{
if (result != -1)
{
[NSException raise: NSInternalInconsistencyException
format: @"NSDecrementExtraRefCount() decremented too far"];
}
/* The counter has become negative so it must have been zero.
* We reset it and return YES ... in a correctly operating
* process we know we can safely reset back to zero without
* worrying about atomicity, since there can be no other
* thread accessing the object (or its reference count would
* have been greater than zero)
*/
(((obj)anObject)[-1].retained) = 0;
objc_delete_weak_refs(anObject);
return YES;
}
#else /* GSATOMICREAD */
pthread_mutex_t *theLock = GSAllocationLockForObject(anObject);
pthread_mutex_lock(theLock);
if (((obj)anObject)[-1].retained == 0)
{
objc_delete_weak_refs(anObject);
pthread_mutex_unlock(theLock);
return YES;
}
else
{
((obj)anObject)[-1].retained--;
pthread_mutex_unlock(theLock);
return NO;
}
#endif /* GSATOMICREAD */
}
return NO;
}
static BOOL release_fast_no_destroy(id anObject)
{
#ifdef __GNUSTEP_RUNTIME__
if (objc_release_fast_no_destroy_np)
{
return objc_release_fast_no_destroy_np(anObject);
}
else
#endif
{
return objc_release_fast_no_destroy_internal(anObject);
}
}
static void objc_release_fast_np_internal(id anObject)
{
if (release_fast_no_destroy(anObject))
{
[anObject dealloc];
}
}
static void release_fast(id anObject)
{
#ifdef __GNUSTEP_RUNTIME__
if (objc_release_fast_np)
{
objc_release_fast_np(anObject);
}
else
#endif
{
objc_release_fast_np_internal(anObject);
}
}
/**
* Examines the extra reference count for the object and, if non-zero
* decrements it, otherwise leaves it unchanged.<br />
* Returns a flag to say whether the count was zero
* (and hence whether the extra reference count was decremented).<br />
*/
inline BOOL
NSDecrementExtraRefCountWasZero(id anObject)
{
return release_fast_no_destroy(anObject);
}
static size_t object_getRetainCount_np_internal(id anObject)
{
return ((obj)anObject)[-1].retained + 1;
}
static size_t getRetainCount(id anObject)
{
#ifdef __GNUSTEP_RUNTIME__
if (object_getRetainCount_np)
{
return object_getRetainCount_np(anObject);
}
else
#endif
{
return object_getRetainCount_np_internal(anObject);
}
}
/**
* Return the extra reference count of anObject (a value in the range
* from 0 to the maximum unsigned integer value minus one).<br />
* The retain count for an object is this value plus one.
*/
inline NSUInteger
NSExtraRefCount(id anObject)
{
return getRetainCount(anObject) - 1;
}
/**
* Increments the extra reference count for anObject.<br />
* The GNUstep version raises an exception if the reference count
* would be incremented to too large a value.<br />
* This is used by the [NSObject-retain] method.
*/
static id objc_retain_fast_np_internal(id anObject)
{
BOOL tooFar = NO;
#if defined(GSATOMICREAD)
/* I've seen comments saying that some platforms only support up to
* 24 bits in atomic locking, so raise an exception if we try to
* go beyond 0xfffffe.
*/
if (GSAtomicIncrement((gsatomic_t)&(((obj)anObject)[-1].retained))
> 0xfffffe)
{
tooFar = YES;
}
#else /* GSATOMICREAD */
pthread_mutex_t *theLock = GSAllocationLockForObject(anObject);
pthread_mutex_lock(theLock);
if (((obj)anObject)[-1].retained > 0xfffffe)
{
tooFar = YES;
}
else
{
((obj)anObject)[-1].retained++;
}
pthread_mutex_unlock(theLock);
#endif /* GSATOMICREAD */
if (YES == tooFar)
{
static NSHashTable *overrun = nil;
static gs_mutex_t countLock = GS_MUTEX_INIT_STATIC;
/* We store this instance in a hash table so that we will only raise
* an exception for it once (and can therefore expect to log the instance
* as part of the exception derscription without recursion).
* NB. The hash table does not retain the object, so the code in the
* lock protected region below should be safe anyway.
*/
GS_MUTEX_LOCK(countLock);
if (nil == overrun)
{
overrun = NSCreateHashTable(NSNonRetainedObjectHashCallBacks, 0);
}
if (0 == NSHashGet(overrun, anObject))
{
NSHashInsert(overrun, anObject);
}
else
{
tooFar = NO;
}
GS_MUTEX_UNLOCK(countLock);
if (YES == tooFar)
{
NSString *base;
base = [NSString stringWithFormat: @"<%s: %p>",
class_getName([anObject class]), anObject];
[NSException raise: NSInternalInconsistencyException
format: @"NSIncrementExtraRefCount() asked to increment too far"
@" for %@ - %@", base, anObject];
}
}
return anObject;
}
static id retain_fast(id anObject)
{
#ifdef __GNUSTEP_RUNTIME__
if (objc_retain_fast_np)
{
return objc_retain_fast_np(anObject);
}
else
#endif
{
return objc_retain_fast_np_internal(anObject);
}
}
/**
* Increments the extra reference count for anObject.<br />
* The GNUstep version raises an exception if the reference count
* would be incremented to too large a value.<br />
* This is used by the [NSObject-retain] method.
*/
inline void
NSIncrementExtraRefCount(id anObject)
{
retain_fast(anObject);
}
#ifndef NDEBUG
#define AADD(c, o) GSDebugAllocationAdd(c, o)
#define AREM(c, o) GSDebugAllocationRemove(c, o)
#else
#define AADD(c, o)
#define AREM(c, o)
#endif
#ifndef OBJC_CAP_ARC
static SEL cxx_construct, cxx_destruct;
/**
* Calls the C++ constructors for this object, starting with the ones declared
* in aClass. The compiler generates two methods on Objective-C++ classes that
* static instances of C++ classes as ivars. These are -.cxx_construct and
* -.cxx_destruct. The -.cxx_construct methods must be called in order from
* the root class to all subclasses, to ensure that subclass ivars are
* initialised after superclass ones. This must be done in reverse for
* destruction.
*
* This function first calls itself recursively on the superclass, to get the
* IMP for the constructor function in the superclass. It then compares the
* construct method for this class with the one that's already been called,
* and calls it if it's new.
*/
static IMP
callCXXConstructors(Class aClass, id anObject)
{
IMP constructor = 0;
if (class_respondsToSelector(aClass, cxx_construct))
{
IMP calledConstructor =
callCXXConstructors(class_getSuperclass(aClass), anObject);
constructor = class_getMethodImplementation(aClass, cxx_construct);
if (calledConstructor != constructor)
{
constructor(anObject, cxx_construct);
}
}
return constructor;
}
#endif
/*
* Now do conditional compilation of memory allocation functions
* depending on what information (if any) we are storing before
* the start of each object.
*/
// FIXME rewrite object allocation to use class_createInstance when we
// are using libobjc2.
inline id
NSAllocateObject(Class aClass, NSUInteger extraBytes, NSZone *zone)
{
id new;
#ifdef OBJC_CAP_ARC
if ((new = class_createInstance(aClass, extraBytes)) != nil)
{
AADD(aClass, new);
}
#else
int size;
NSCAssert((!class_isMetaClass(aClass)), @"Bad class for new object");
size = class_getInstanceSize(aClass) + extraBytes + sizeof(struct obj_layout);
if (zone == 0)
{
zone = NSDefaultMallocZone();
}
new = NSZoneMalloc(zone, size);
if (new != nil)
{
memset (new, 0, size);
new = (id)&((obj)new)[1];
object_setClass(new, aClass);
AADD(aClass, new);
}
/* Don't bother doing this in a thread-safe way, because the cost of locking
* will be a lot more than the cost of doing the same call in two threads.
* The returned selector will persist and the runtime will ensure that both
* calls return the same selector, so we don't need to bother doing it
* ourselves.
*/
if (0 == cxx_construct)
{
cxx_construct = sel_registerName(".cxx_construct");
cxx_destruct = sel_registerName(".cxx_destruct");
}
callCXXConstructors(aClass, new);
#endif
return new;
}
inline void
NSDeallocateObject(id anObject)
{
Class aClass = object_getClass(anObject);
if ((anObject != nil) && !class_isMetaClass(aClass))
{
#ifndef OBJC_CAP_ARC
obj o = &((obj)anObject)[-1];
NSZone *z = NSZoneFromPointer(o);
#endif
/* Call the default finalizer to handle C++ destructors.
*/
(*finalize_imp)(anObject, finalize_sel);
AREM(aClass, (id)anObject);
if (NSZombieEnabled)
{
/* Replace the isa pointer etc to turn the object into a zombie.
*/
GSMakeZombie(anObject, aClass);
if (NSDeallocateZombies)
{
#if defined(OBJC_CAP_ARC)
/* On the modern runtime object_dispose() is called to free
* an instance, but that needs to look at the isa pointer
* and that is now the zombie class so we cant use it.
* So NSDeallocateZombies does nothing.
*/
#else
/* On the classic runtime it makes sense to have an option to
* free memory as the isa pointer in the freed memory may let
* it work as a zombie until it is overwritten.
*/
NSZoneFree(z, o);
#endif
}
}
else
{
#ifdef OBJC_CAP_ARC
object_dispose(anObject);
#else
object_setClass((id)anObject, (Class)(void*)0xdeadface);
NSZoneFree(z, o);
#endif
}
}
return;
}
BOOL
NSShouldRetainWithZone (NSObject *anObject, NSZone *requestedZone)
{
return (!requestedZone || requestedZone == NSDefaultMallocZone()
|| [anObject zone] == requestedZone);
}
/**
* <p>
* <code>NSObject</code> is the root class (a root class is
* a class with no superclass) of the GNUstep base library
* class hierarchy, so all classes normally inherit from
* <code>NSObject</code>. There is an exception though:
* <code>NSProxy</code> (which is used for remote messaging)
* does not inherit from <code>NSObject</code>.
* </p>
* <p>
* Unless you are really sure of what you are doing, all
* your own classes should inherit (directly or indirectly)
* from <code>NSObject</code> (or in special cases from
* <code>NSProxy</code>). <code>NSObject</code> provides
* the basic common functionality shared by all GNUstep
* classes and objects.
* </p>
* <p>
* The essential methods which must be implemented by all
* classes for their instances to be usable within GNUstep
* are declared in a separate protocol, which is the
* <code>NSObject</code> protocol. Both
* <code>NSObject</code> and <code>NSProxy</code> conform to
* this protocol, which means all objects in a GNUstep
* application will conform to this protocol (btw, if you
* don't find a method of <code>NSObject</code> you are
* looking for in this documentation, make sure you also
* look into the documentation for the <code>NSObject</code>
* protocol).
* </p>
* <p>
* Theoretically, in special cases you might need to
* implement a new root class. If you do, you need to make
* sure that your root class conforms (at least) to the
* <code>NSObject</code> protocol, otherwise it will not
* interact correctly with the GNUstep framework. Said
* that, I must note that I have never seen a case in which
* a new root class is needed.
* </p>
* <p>
* <code>NSObject</code> is a root class, which implies that
* instance methods of <code>NSObject</code> are treated in
* a special way by the Objective-C runtime. This is an
* exception to the normal way messaging works with class
* and instance methods: if the Objective-C runtime can't
* find a class method for a class object, as a last resort
* it looks for an instance method of the root class with
* the same name, and executes it if it finds it. This
* means that instance methods of the root class (such as
* <code>NSObject</code>) can be performed by class objects
* which inherit from that root class ! This can only
* happen if the class doesn't have a class method with the
* same name, otherwise that method - of course - takes the
* precedence. Because of this exception,
* <code>NSObject</code>'s instance methods are written in
* such a way that they work both on <code>NSObject</code>'s
* instances and on class objects.
* </p>
*/
@implementation NSObject
#ifdef OBJC_CAP_ARC
+ (void) _TrivialAllocInit {}
- (void) _ARCCompliantRetainRelease {}
#endif
/**
* Semi-private function in libobjc2 that initialises the classes used for
* blocks.
*/
extern BOOL
objc_create_block_classes_as_subclasses_of(Class super);
#ifdef OBJC_CAP_ARC
static id gs_weak_load(id obj)
{
return [obj retainCount] > 0 ? obj : nil;
}
#endif
+ (void) load
{
#ifdef OBJC_CAP_ARC
_objc_weak_load = gs_weak_load;
#else
GSWeakInit();
#endif
objc_create_block_classes_as_subclasses_of(self);
}
+ (void) initialize
{
if (self == [NSObject class])
{
#ifdef _WIN32
/* Start of sockets so we can get host name and other info */
WORD wVersionRequested = MAKEWORD(2, 2);
WSADATA wsaData;
int wsaResult = WSAStartup(wVersionRequested, &wsaData);
if (wsaResult != 0)
{
fprintf(stderr, "Error %d initializing Windows Sockets\n", wsaResult);
}
#else /* _WIN32 */
#ifdef SIGPIPE
/*
* If SIGPIPE is not handled or ignored, we will abort on any attempt
* to write to a pipe/socket that has been closed by the other end!
* We therefore need to ignore the signal if nothing else is already
* handling it.
*/
#ifdef HAVE_SIGACTION
{
struct sigaction act;
if (sigaction(SIGPIPE, 0, &act) == 0)
{
if (act.sa_handler == SIG_DFL)
{
// Not ignored or handled ... so we ignore it.
act.sa_handler = SIG_IGN;
if (sigaction(SIGPIPE, &act, 0) != 0)
{
fprintf(stderr, "Unable to ignore SIGPIPE\n");
}
}
}
else
{
fprintf(stderr, "Unable to retrieve information about SIGPIPE\n");
}
}
#else /* HAVE_SIGACTION */
{
void (*handler)(NSInteger);
handler = signal(SIGPIPE, SIG_IGN);
if (handler != SIG_DFL)
{
signal(SIGPIPE, handler);
}
}
#endif /* HAVE_SIGACTION */
#endif /* SIGPIPE */
#endif /* _WIN32 */
finalize_sel = @selector(finalize);
finalize_imp = class_getMethodImplementation(self, finalize_sel);
#if defined(__FreeBSD__) && defined(__i386__)
// Manipulate the FPU to add the exception mask. (Fixes SIGFPE
// problems on *BSD)
// Note this only works on x86
# if defined(FE_INVALID)
fedisableexcept(FE_INVALID);
# else
{
volatile short cw;
__asm__ volatile ("fstcw (%0)" : : "g" (&cw));
cw |= 1; /* Mask 'invalid' exception */
__asm__ volatile ("fldcw (%0)" : : "g" (&cw));
}
# endif
#endif
/* Initialize the locks for allocation when atomic
* operations are not available.
*/
#if !defined(GSATOMICREAD)
{
NSUInteger i;
for (i = 0; i < LOCKCOUNT; i++)
{
pthread_mutex_init(&allocationLocks[i], NULL);
}
}
#endif
/* Behavior debugging ... enable with environment variable if needed.
*/
GSObjCBehaviorDebug(GSPrivateEnvironmentFlag("GNUSTEP_BEHAVIOR_DEBUG",
GSObjCBehaviorDebug(-1)));
/* See if we should cleanup at process exit.
*/
if (YES == GSPrivateEnvironmentFlag("GNUSTEP_SHOULD_CLEAN_UP", NO))
{
[self setShouldCleanUp: YES];
[self registerAtExit: @selector(_atExit)];
}
/* Set up the autorelease system ... we must do this before using any
* other class whose +initialize might autorelease something.
*/
autorelease_class = [NSAutoreleasePool class];
autorelease_sel = @selector(addObject:);
autorelease_imp = [autorelease_class methodForSelector: autorelease_sel];
/* Make sure the constant string class works.
*/
NSConstantStringClass = [NSString constantStringClass];
/* Determine zombie management flags and set up a map to store
* information about zombie objects.
*/
NSZombieEnabled = GSPrivateEnvironmentFlag("NSZombieEnabled", NO);
if (NSZombieEnabled)
{
NSDeallocateZombies
= GSPrivateEnvironmentFlag("NSDeallocateZombies", NO);
#ifdef OBJC_CAP_ARC
if (NSDeallocateZombies)
{
fprintf(stderr, "WARNING the NSDeallocateZombies environment"
" setting has no effect with this Objective-C runtime.\n");
}
#endif
}
zombieMap = NSCreateMapTable(NSNonOwnedPointerMapKeyCallBacks,
NSNonOwnedPointerMapValueCallBacks, 0);
/* We need to cache the zombie class.
* We can't call +class because NSZombie doesn't have that method.
* We can't use NSClassFromString() because that would use an NSString
* object, and that class hasn't been initialized yet ...
*/
zombieClass = objc_lookUpClass("NSZombie");
}
return;
}
+ (void) _atExit
{
/*
NSMapTable *m = nil;
GS_MUTEX_LOCK(allocationLock);
m = zombieMap;
zombieMap = nil;
GS_MUTEX_UNLOCK(allocationLock);
DESTROY(m);
*/
}
/**
* Allocates a new instance of the receiver from the default
* zone, by invoking +allocWithZone: with
* <code>NSDefaultMallocZone()</code> as the zone argument.<br />
* Returns the created instance.
*/
+ (id) alloc
{
return [self allocWithZone: NSDefaultMallocZone()];
}
/**
* This is the basic method to create a new instance. It
* allocates a new instance of the receiver from the specified
* memory zone.
* <p>
* Memory for an instance of the receiver is allocated; a
* pointer to this newly created instance is returned. All
* instance variables are set to 0. No initialization of the
* instance is performed apart from setup to be an instance of
* the correct class: it is your responsibility to initialize the
* instance by calling an appropriate <code>init</code>
* method. If you are not using ARC, it is
* also your responsibility to make sure the returned
* instance is destroyed when you finish using it, by calling
* the <code>release</code> method to destroy the instance
* directly, or by using <code>autorelease</code> and
* autorelease pools.
* </p>
* <p>
* You do not normally need to override this method in
* subclasses, unless you are implementing a class which for
* some reasons silently allocates instances of another class
* (this is typically needed to implement class clusters and
* similar design schemes).
* </p>
* <p>
* If you have turned on debugging of object allocation (by
* calling the <code>GSDebugAllocationActive</code>
* function), this method will also update the various
* debugging counts and monitors of allocated objects, which
* you can access using the <code>GSDebugAllocation...</code>
* functions.
* </p>
*/
+ (id) allocWithZone: (NSZone*)z
{
return NSAllocateObject(self, 0, z);
}
/**
* Returns the receiver.
*/
+ (id) copyWithZone: (NSZone*)z
{
return self;
}
/**
* <p>
* This method is a short-hand for alloc followed by init, that is,
* </p>
* <p><code>
* NSObject *object = [NSObject new];
* </code></p>
* is exactly the same as
* <p><code>
* NSObject *object = [[NSObject alloc] init];
* </code></p>
* <p>
* This is a general convention: all <code>new...</code>
* methods are supposed to return a newly allocated and
* initialized instance, as would be generated by an
* <code>alloc</code> method followed by a corresponding
* <code>init...</code> method. Please note that if you are
* not using ARC, this means that instances
* generated by the <code>new...</code> methods are not
* autoreleased, that is, you are responsible for releasing
* (autoreleasing) the instances yourself. So when you use
* <code>new</code> you typically do something like:
* </p>
* <p>
* <code>
* NSMutableArray *array = AUTORELEASE ([NSMutableArray new]);
* </code>
* </p>
* <p>
* You do not normally need to override <code>new</code> in
* subclasses, because if you override <code>init</code> (and
* optionally <code>allocWithZone:</code> if you really
* need), <code>new</code> will automatically use your
* subclass methods.
* </p>
* <p>
* You might need instead to define new <code>new...</code>
* methods specific to your subclass to match any
* <code>init...</code> specific to your subclass. For
* example, if your subclass defines an instance method
* </p>
* <p>
* <code>initWithName:</code>
* </p>
* <p>
* it might be handy for you to have a class method
* </p>
* <p>
* <code>newWithName:</code>
* </p>
* <p>
* which combines <code>alloc</code> and
* <code>initWithName:</code>. You would implement it as follows:
* </p>
* <p>
* <code>
* + (id) newWithName: (NSString *)aName
* {
* return [[self alloc] initWithName: aName];
* }
* </code>
* </p>
*/
+ (id) new
{
return [[self alloc] init];
}
/**
* Returns the class of which the receiver is an instance.<br />
* The default implementation returns the actual class that the
* receiver is an instance of.<br />
* NB. When NSZombie is enabled (see NSDebug.h) this is changed
* to be the NSZombie class upon object deallocation.
*/
- (Class) class
{
return object_getClass(self);
}
/**
* Returns the name of the class of the receiving object by using
* the NSStringFromClass() function.<br />
* This is a MacOS-X addition for apple scripting, which is also
* generally useful.
*/
- (NSString*) className
{
return NSStringFromClass([self class]);
}
/**
* Creates and returns a copy of the receiver by calling -copyWithZone:
* passing NSDefaultMallocZone()
*/
- (id) copy
{
return [(id)self copyWithZone: NSDefaultMallocZone()];
}
/**
* Deallocates the receiver by calling NSDeallocateObject() with self
* as the argument.<br />
* <p>
* You should normally call the superclass implementation of this method
* when you override it in a subclass, or the memory occupied by your
* object will not be released.
* </p>
* <p>
* <code>NSObject</code>'s implementation of this method
* destroys the receiver, by returning the memory allocated
* to the receiver to the system. After this method has been
* called on an instance, you must not refer the instance in
* any way, because it does not exist any longer. If you do,
* it is a bug and your program might even crash with a
* segmentation fault.
* </p>
* <p>
* If you have turned on the debugging facilities for
* instance allocation, <code>NSObject</code>'s
* implementation of this method will also update the various
* counts and monitors of allocated instances (see the
* <code>GSDebugAllocation...</code> functions for more
* info).
* </p>
* <p>
* Normally you are supposed to manage the memory taken by
* objects by using the high level interface provided by the
* <code>retain</code>, <code>release</code> and
* <code>autorelease</code> methods (or better by the
* corresponding macros <code>RETAIN</code>,
* <code>RELEASE</code> and <code>AUTORELEASE</code>), and by
* autorelease pools and such; whenever the
* release/autorelease mechanism determines that an object is
* no longer needed (which happens when its retain count
* reaches 0), it will call the <code>dealloc</code> method
* to actually deallocate the object. This means that normally,
* you should not need to call <code>dealloc</code> directly as
* the gnustep base library automatically calls it for you when
* the retain count of an object reaches 0.
* </p>
* <p>
* Because the <code>dealloc</code> method will be called
* when an instance is being destroyed, if instances of your
* subclass use objects or resources (as it happens for most
* useful classes), you must override <code>dealloc</code> in
* subclasses to release all objects and resources which are
* used by the instance, otherwise these objects and
* resources would be leaked. In the subclass
* implementation, you should first release all your subclass
* specific objects and resources, and then invoke super's
* implementation (which will do the same, and so on up in
* the class hierarchy to <code>NSObject</code>'s
* implementation, which finally destroys the object). Here
* is an example of the implementation of
* <code>dealloc</code> for a subclass whose instances have a
* single instance variable <code>name</code> which needs to
* be released when an instance is deallocated:
* </p>
* <p>
* <code>
* - (void) dealloc
* {
* RELEASE (name);
* [super dealloc];
* }
* </code>
* </p>
* <p>
* <code>dealloc</code> might contain code to release not
* only objects, but also other resources, such as open
* files, network connections, raw memory allocated in other
* ways, etc.
* </p>
* <p>
* If you have allocated the memory using a non-standard mechanism, you
* will not call the superclass (NSObject) implementation of the method
* as you will need to handle the deallocation specially.<br />
* In some circumstances, an object may wish to prevent itself from
* being deallocated, it can do this simply be refraining from calling
* the superclass implementation.
* </p>
*/
- (void) dealloc
{
NSDeallocateObject(self);
}
- (void) finalize
{
#ifndef OBJC_CAP_ARC
Class destructorClass = Nil;
IMP destructor = 0;
/*
* We're pretending to be the Objective-C runtime here, so we have to do some
* unsafe things (i.e. access the class directly, and not via the
* object_getClass() so that hidden classes get their destructors called. If
* the runtime supports small objects (those embedded in a pointer), then we
* must use object_getClass() for them, because they do not have an isa
* pointer (but can not have a hidden class interposed).
*/
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-objc-pointer-introspection"
#pragma clang diagnostic ignored "-Wdeprecated-objc-isa-usage"
#endif
#ifdef OBJC_SMALL_OBJECT_MASK
if (((NSUInteger)self & OBJC_SMALL_OBJECT_MASK) == 0)
{
destructorClass = isa; // Potentially hidden class
}
else
{
destructorClass = object_getClass(self); // Small object
}
#else
destructorClass = isa;
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
/* C++ destructors must be called in the opposite order to their
* creators, so start at the leaf class and then go up the tree until we
* get to the root class. As a small optimisation, we don't bother
* visiting any classes that don't have an implementation of this method
* (including one inherited from a superclass).
*
* Care must be taken not to call inherited .cxx_destruct methods.
*/
while (class_respondsToSelector(destructorClass, cxx_destruct))
{
IMP newDestructor;
newDestructor
= class_getMethodImplementation(destructorClass, cxx_destruct);
destructorClass = class_getSuperclass(destructorClass);
if (newDestructor != destructor)
{
newDestructor(self, cxx_destruct);
destructor = newDestructor;
}
}
return;
#endif
}
/**
* This method is an anachronism. Do not use it.
*/
- (id) free
{
[NSException raise: NSGenericException
format: @"Use `dealloc' instead of `free' for %@.", self];
return nil;
}
/**
* Initialises the receiver ... the NSObject implementation simply returns self.
*/
- (id) init
{
return self;
}
/**
* Creates and returns a mutable copy of the receiver by calling
* -mutableCopyWithZone: passing NSDefaultMallocZone().
*/
- (id) mutableCopy
{
return [(id)self mutableCopyWithZone: NSDefaultMallocZone()];
}
/**
* Returns the super class from which the receiver was derived.
*/
+ (Class) superclass
{
return class_getSuperclass(self);
}
/**
* Returns the super class from which the receivers class was derived.
*/
- (Class) superclass
{
return class_getSuperclass(object_getClass(self));
}
/**
* Returns a flag to say if instances of the receiver class will
* respond to the specified selector. This ignores situations
* where a subclass implements -forwardInvocation: to respond to
* selectors not normally handled ... in these cases the subclass
* may override this method to handle it.
* <br />If given a null selector, raises NSInvalidArgumentException when
* in MacOS-X compatibility more, or returns NO otherwise.
*/
+ (BOOL) instancesRespondToSelector: (SEL)aSelector
{
if (aSelector == 0)
{
if (GSPrivateDefaultsFlag(GSMacOSXCompatible))
{
[NSException raise: NSInvalidArgumentException
format: @"%@ null selector given",
NSStringFromSelector(_cmd)];
}
return NO;
}
if (class_respondsToSelector(self, aSelector))
{
return YES;
}
if (class_isMetaClass(self))
{
/* It seems convoluted to attempt to access the class from the
metaclass just to call +resolveClassMethod: in this rare case. */
return NO;
}
else
{
return [self resolveInstanceMethod: aSelector];
}
}
/**
* Returns a flag to say whether the receiving class conforms to aProtocol
*/
+ (BOOL) conformsToProtocol: (Protocol*)aProtocol
{
#ifdef __GNU_LIBOBJC__
Class c;
/* Iterate over the current class and all the superclasses. */
for (c = self; c != Nil; c = class_getSuperclass (c))
{
if (class_conformsToProtocol(c, aProtocol))
{
return YES;
}
}
return NO;
#else
/* libobjc2 and ObjectiveC2/ have an implementation of
class_conformsToProtocol() which automatically looks up the
protocol in superclasses (unlike the Apple and GNU Objective-C
runtime ones). */
return class_conformsToProtocol(self, aProtocol);
#endif
}
/**
* Returns a flag to say whether the class of the receiver conforms
* to aProtocol.
*/
- (BOOL) conformsToProtocol: (Protocol*)aProtocol
{
return [[self class] conformsToProtocol: aProtocol];
}
/**
* Returns a pointer to the C function implementing the method used
* to respond to messages with aSelector by instances of the receiving
* class.
* <br />Raises NSInvalidArgumentException if given a null selector.
*/
+ (IMP) instanceMethodForSelector: (SEL)aSelector
{
if (aSelector == 0)
[NSException raise: NSInvalidArgumentException
format: @"%@ null selector given", NSStringFromSelector(_cmd)];
/*
* Since 'self' is an class, class_getMethodImplementation() will get
* the instance method.
*/
return class_getMethodImplementation((Class)self, aSelector);
}
/**
* Returns a pointer to the C function implementing the method used
* to respond to messages with aSelector.
* <br />Raises NSInvalidArgumentException if given a null selector.
*/
- (IMP) methodForSelector: (SEL)aSelector
{
if (aSelector == 0)
[NSException raise: NSInvalidArgumentException
format: @"%@ null selector given", NSStringFromSelector(_cmd)];
/* The Apple runtime API would do:
* return class_getMethodImplementation(object_getClass(self), aSelector);
* but this cannot ask self for information about any method reached by
* forwarding, so the returned forwarding function would ge a generic one
* rather than one aware of hardware issues with returning structures
* and floating points. We therefore prefer the GNU API which is able to
* use forwarding callbacks to get better type information.
*/
return objc_msg_lookup(self, aSelector);
}
/**
* Returns a pointer to the C function implementing the method used
* to respond to messages with aSelector which are sent to instances
* of the receiving class.
* <br />Raises NSInvalidArgumentException if given a null selector.
*/
+ (NSMethodSignature*) instanceMethodSignatureForSelector: (SEL)aSelector
{
struct objc_method *mth;
if (aSelector == 0)
[NSException raise: NSInvalidArgumentException
format: @"%@ null selector given", NSStringFromSelector(_cmd)];
mth = GSGetMethod(self, aSelector, YES, YES);
if (0 == mth)
return nil;
return [NSMethodSignature
signatureWithObjCTypes: method_getTypeEncoding(mth)];
}
/**
* Returns the method signature describing how the receiver would handle
* a message with aSelector.
* <br />Returns nil if given a null selector.
*/
- (NSMethodSignature*) methodSignatureForSelector: (SEL)aSelector
{
const char *types = NULL;
Class c;
unsigned int count;
Protocol **protocols;
if (0 == aSelector)
{
return nil;
}
c = object_getClass(self);
/* Do a fast lookup to see if the method is implemented at all. If it isn't,
* we can give up without doing a very expensive linear search through every
* method list in the class hierarchy.
*/
if (!class_respondsToSelector(c, aSelector))
{
return nil; // Method not implemented
}
/* If there are protocols that this class conforms to,
* the method may be listed in a protocol with more
* detailed type information than in the class itself
* and we must therefore use the information from the
* protocol.
* This is because protocols also carry information
* used by the Distributed Objects system, which the
* runtime does not maintain in classes.
*/
protocols = class_copyProtocolList(c, &count);
if (NULL != protocols)
{
struct objc_method_description mth;
int i;
for (i = 0 ; i < count ; i++)
{
mth = GSProtocolGetMethodDescriptionRecursive(protocols[i],
aSelector, YES, YES);
if (NULL == mth.types)
{
// Search for class method
mth = GSProtocolGetMethodDescriptionRecursive(protocols[i],
aSelector, YES, NO);
// FIXME: We should probably search optional methods here too.
}
if (NULL != mth.types)
{
break;
}
}
free(protocols);
}
if (types == 0)
{
#ifdef __GNUSTEP_RUNTIME__
struct objc_slot *objc_get_slot(Class cls, SEL selector);
struct objc_slot *slot = objc_get_slot(object_getClass(self), aSelector);
types = slot->types;
#else
struct objc_method *mth;
if (GSObjCIsInstance(self))
{
mth = GSGetMethod(object_getClass(self), aSelector, YES, YES);
}
else
{
mth = GSGetMethod((Class)self, aSelector, NO, YES);
}
types = method_getTypeEncoding (mth);
#endif
}
if (types == 0)
{
return nil;
}
return [NSMethodSignature signatureWithObjCTypes: types];
}
/**
* Returns a string describing the receiver. The default implementation
* gives the class and memory location of the receiver.
*/
- (NSString*) description
{
return [NSString stringWithFormat: @"<%s: %p>",
class_getName([self class]), self];
}
/**
* Returns a string describing the receiving class. The default implementation
* gives the name of the class by calling NSStringFromClass().
*/
+ (NSString*) description
{
return NSStringFromClass(self);
}
/**
* Sets up the ObjC runtime so that the receiver is used wherever code
* calls for aClassObject to be used.
*/
+ (void) poseAsClass: (Class)aClassObject
{
[NSException raise: NSInternalInconsistencyException
format: @"Class posing is not supported"];
}
/**
* Raises an invalid argument exception providing information about
* the receivers inability to handle aSelector.
*/
- (void) doesNotRecognizeSelector: (SEL)aSelector
{
[NSException raise: NSInvalidArgumentException
format: @"%s(%s) does not recognize %s",
GSClassNameFromObject(self),
GSObjCIsInstance(self) ? "instance" : "class",
aSelector ? sel_getName(aSelector) : "(null)"];
}
/**
* This method is called automatically to handle a message sent to
* the receiver for which the receivers class has no method.<br />
* The default implementation calls -doesNotRecognizeSelector:
*/
- (void) forwardInvocation: (NSInvocation*)anInvocation
{
id target = [self forwardingTargetForSelector: [anInvocation selector]];
if (nil != target)
{
[anInvocation invokeWithTarget: target];
return;
}
[self doesNotRecognizeSelector: [anInvocation selector]];
return;
}
/**
* Called after the receiver has been created by decoding some sort
* of archive. Returns self. Subclasses may override this to perform
* some special initialisation upon being decoded.
*/
- (id) awakeAfterUsingCoder: (NSCoder*)aDecoder
{
return self;
}
// FIXME - should this be added (as in OS X) now that we have NSKeyedArchiver?
// - (Class) classForKeyedArchiver
// {
// return [self classForArchiver];
// }
/**
* Override to substitute class when an instance is being archived by an
* [NSArchiver]. Default implementation returns -classForCoder.
*/
- (Class) classForArchiver
{
return [self classForCoder];
}
/**
* Override to substitute class when an instance is being serialized by an
* [NSCoder]. Default implementation returns <code>[self class]</code> (no
* substitution).
*/
- (Class) classForCoder
{
return [self class];
}
// FIXME - should this be added (as in OS X) now that we have NSKeyedArchiver?
// - (id) replacementObjectForKeyedArchiver: (NSKeyedArchiver *)keyedArchiver
// {
// return [self replacementObjectForCoder: (NSArchiver *)keyedArchiver];
// }
/**
* Override to substitute another object for this instance when being archived
* by given [NSArchiver]. Default implementation returns
* -replacementObjectForCoder:.
*/
- (id) replacementObjectForArchiver: (NSArchiver*)anArchiver
{
return [self replacementObjectForCoder: (NSCoder*)anArchiver];
}
/**
* Override to substitute another object for this instance when being
* serialized by given [NSCoder]. Default implementation returns
* <code>self</code>.
*/
- (id) replacementObjectForCoder: (NSCoder*)anEncoder
{
return self;
}
/* NSObject protocol */
/**
* Adds the receiver to the current autorelease pool, so that it will be
* sent a -release message when the pool is destroyed.<br />
* Returns the receiver.<br />
* In GNUstep, the [NSObject+enableDoubleReleaseCheck:] method may be used
* to turn on checking for retain/release errors in this method.
*/
- (id) autorelease
{
if (double_release_check_enabled)
{
NSUInteger release_count;
NSUInteger retain_count = [self retainCount];
release_count = [autorelease_class autoreleaseCountForObject:self];
if (release_count > retain_count)
[NSException
raise: NSGenericException
format: @"Autorelease would release object too many times.\n"
@"%"PRIuPTR" release(s) versus %"PRIuPTR" retain(s)",
release_count, retain_count];
}
(*autorelease_imp)(autorelease_class, autorelease_sel, self);
return self;
}
/**
* Dummy method returning the receiver.
*/
+ (id) autorelease
{
return self;
}
/**
* Returns the receiver.
*/
+ (Class) class
{
return self;
}
/**
* Returns the hash of the receiver. Subclasses should ensure that their
* implementations of this method obey the rule that if the -isEqual: method
* returns YES for two instances of the class, the -hash method returns the
* same value for both instances.<br />
* The default implementation returns a value based on the address
* of the instance.
*/
- (NSUInteger) hash
{
/*
* malloc() must return pointers aligned to point to any data type
*/
#define MAXALIGN (__alignof__(_Complex long double))
static int shift = MAXALIGN==16 ? 4 : (MAXALIGN==8 ? 3 : 2);
/* We shift left to lose any zero bits produced by the
* alignment of the object in memory.
*/
return (NSUInteger)((uintptr_t)self >> shift);
}
/**
* Tests anObject and the receiver for equality. The default implementation
* considers two objects to be equal only if they are the same object
* (ie occupy the same memory location).<br />
* If a subclass overrides this method, it should also override the -hash
* method so that if two objects are equal they both have the same hash.
*/
- (BOOL) isEqual: (id)anObject
{
return (self == anObject);
}
/**
* Returns YES if aClass is the NSObject class
*/
+ (BOOL) isKindOfClass: (Class)aClass
{
if (aClass == [NSObject class])
return YES;
return NO;
}
/**
* Returns YES if the class of the receiver is either the same as aClass
* or is derived from (a subclass of) aClass.
*/
- (BOOL) isKindOfClass: (Class)aClass
{
Class class = object_getClass(self);
return GSObjCIsKindOf(class, aClass);
}
/**
* Returns YES if aClass is the same as the receiving class.
*/
+ (BOOL) isMemberOfClass: (Class)aClass
{
return (self == aClass) ? YES : NO;
}
/**
* Returns YES if the class of the receiver is aClass
*/
- (BOOL) isMemberOfClass: (Class)aClass
{
return ([self class] == aClass) ? YES : NO;
}
/**
* Returns a flag to differentiate between 'true' objects, and objects
* which are proxies for other objects (ie they forward messages to the
* other objects).<br />
* The default implementation returns NO.
*/
- (BOOL) isProxy
{
return NO;
}
/**
* Returns YES if the receiver is aClass or a subclass of aClass.
*/
+ (BOOL) isSubclassOfClass: (Class)aClass
{
return GSObjCIsKindOf(self, aClass);
}
/**
* Causes the receiver to execute the method implementation corresponding
* to aSelector and returns the result.<br />
* The method must be one which takes no arguments and returns an object.
* <br />Raises NSInvalidArgumentException if given a null selector.
*/
- (id) performSelector: (SEL)aSelector
{
IMP msg;
if (aSelector == 0)
[NSException raise: NSInvalidArgumentException
format: @"%@ null selector given", NSStringFromSelector(_cmd)];
/* The Apple runtime API would do:
* msg = class_getMethodImplementation(object_getClass(self), aSelector);
* but this cannot ask self for information about any method reached by
* forwarding, so the returned forwarding function would ge a generic one
* rather than one aware of hardware issues with returning structures
* and floating points. We therefore prefer the GNU API which is able to
* use forwarding callbacks to get better type information.
*/
msg = objc_msg_lookup(self, aSelector);
if (!msg)
{
[NSException raise: NSGenericException
format: @"invalid selector '%s' passed to %s",
sel_getName(aSelector), sel_getName(_cmd)];
return nil;
}
return (*msg)(self, aSelector);
}
/**
* Causes the receiver to execute the method implementation corresponding
* to aSelector and returns the result.<br />
* The method must be one which takes one argument and returns an object.
* <br />Raises NSInvalidArgumentException if given a null selector.
*/
- (id) performSelector: (SEL)aSelector withObject: (id)anObject
{
IMP msg;
if (aSelector == 0)
[NSException raise: NSInvalidArgumentException
format: @"%@ null selector given", NSStringFromSelector(_cmd)];
/* The Apple runtime API would do:
* msg = class_getMethodImplementation(object_getClass(self), aSelector);
* but this cannot ask self for information about any method reached by
* forwarding, so the returned forwarding function would be a generic one
* rather than one aware of hardware issues with returning structures
* and floating points. We therefore prefer the GNU API which is able to
* use forwarding callbacks to get better type information.
*/
msg = objc_msg_lookup(self, aSelector);
if (!msg)
{
[NSException raise: NSGenericException
format: @"invalid selector '%s' passed to %s",
sel_getName(aSelector), sel_getName(_cmd)];
return nil;
}
return (*msg)(self, aSelector, anObject);
}
/**
* Causes the receiver to execute the method implementation corresponding
* to aSelector and returns the result.<br />
* The method must be one which takes two arguments and returns an object.
* <br />Raises NSInvalidArgumentException if given a null selector.
*/
- (id) performSelector: (SEL)aSelector
withObject: (id) object1
withObject: (id) object2
{
IMP msg;
if (aSelector == 0)
[NSException raise: NSInvalidArgumentException
format: @"%@ null selector given", NSStringFromSelector(_cmd)];
/* The Apple runtime API would do:
* msg = class_getMethodImplementation(object_getClass(self), aSelector);
* but this cannot ask self for information about any method reached by
* forwarding, so the returned forwarding function would ge a generic one
* rather than one aware of hardware issues with returning structures
* and floating points. We therefore prefer the GNU API which is able to
* use forwarding callbacks to get better type information.
*/
msg = objc_msg_lookup(self, aSelector);
if (!msg)
{
[NSException raise: NSGenericException
format: @"invalid selector '%s' passed to %s",
sel_getName(aSelector), sel_getName(_cmd)];
return nil;
}
return (*msg)(self, aSelector, object1, object2);
}
/**
* Decrements the retain count for the receiver if greater than zero,
* otherwise calls the dealloc method instead.<br />
* The default implementation calls the NSDecrementExtraRefCountWasZero()
* function to test the extra reference count for the receiver (and
* decrement it if non-zero) - if the extra reference count is zero then
* the retain count is one, and the dealloc method is called.<br />
* In GNUstep, the [NSObject+enableDoubleReleaseCheck:] method may be used
* to turn on checking for ratain/release errors in this method.
*/
- (oneway void) release
{
release_fast(self);
}
/**
* The class implementation of the release method is a dummy method
* having no effect. It is present so that class objects can be stored
* in containers (such as NSArray) which will send them retain and
* release messages.
*/
+ (oneway void) release
{
return;
}
/**
* Returns a flag to say if the receiver will
* respond to the specified selector. This ignores situations
* where a subclass implements -forwardInvocation: to respond to
* selectors not normally handled ... in these cases the subclass
* may override this method to handle it.
* <br />If given a null selector, raises NSInvalidArgumentException when
* in MacOS-X compatibility more, or returns NO otherwise.
*/
- (BOOL) respondsToSelector: (SEL)aSelector
{
Class cls = object_getClass(self);
if (aSelector == 0)
{
return NO;
}
if (class_respondsToSelector(cls, aSelector))
{
return YES;
}
if (class_isMetaClass(cls))
{
return [(Class)self resolveClassMethod: aSelector];
}
else
{
return [cls resolveInstanceMethod: aSelector];
}
}
/**
* Increments the reference count and returns the receiver.<br />
* The default implementation does this by calling NSIncrementExtraRefCount()
*/
- (id) retain
{
return retain_fast(self);
}
/**
* The class implementation of the retain method is a dummy method
* having no effect. It is present so that class objects can be stored
* in containers (such as NSArray) which will send them retain and
* release messages.
*/
+ (id) retain
{
return self;
}
/**
* Returns the reference count for the receiver. Each instance has an
* implicit reference count of 1, and has an 'extra reference count'
* returned by the NSExtraRefCount() function, so the value returned by
* this method is always greater than zero.<br />
* By convention, objects which should (or can) never be deallocated
* return the maximum unsigned integer value.
*/
- (NSUInteger) retainCount
{
return getRetainCount(self);
}
/**
* The class implementation of the retainCount method always returns
* the maximum unsigned integer value, as classes can not be deallocated
* the retain count mechanism is a dummy system for them.
*/
+ (NSUInteger) retainCount
{
return UINT_MAX;
}
/**
* Returns the receiver.
*/
- (id) self
{
return self;
}
/**
* Returns the memory allocation zone in which the receiver is located.
*/
- (NSZone*) zone
{
return NSZoneFromPointer(self);
}
+ (NSZone *) zone
{
return NSDefaultMallocZone();
}
+ (BOOL) resolveClassMethod: (SEL)name
{
return NO;
}
+ (BOOL) resolveInstanceMethod: (SEL)name
{
return NO;
}
/**
* Sets the version number of the receiving class. Should be nonnegative.
*/
+ (void) setVersion: (NSInteger)aVersion
{
if (aVersion < 0)
[NSException raise: NSInvalidArgumentException
format: @"%s +setVersion: may not set a negative version",
GSClassNameFromObject(self)];
class_setVersion(self, aVersion);
}
/**
* Returns the version number of the receiving class. This will default to
* a number assigned by the Objective C compiler if [NSObject -setVersion] has
* not been called.
*/
+ (NSInteger) version
{
return class_getVersion(self);
}
- (id) autoContentAccessingProxy
{
return AUTORELEASE([[GSContentAccessingProxy alloc] initWithObject: self]);
}
- (id) forwardingTargetForSelector:(SEL)aSelector
{
return nil;
}
@end
/**
* Methods for compatibility with the NEXTSTEP (pre-OpenStep) 'Object' class.
*/
@implementation NSObject (NEXTSTEP)
/* NEXTSTEP Object class compatibility */
/**
* Logs a message. <em>Deprecated.</em> Use NSLog() in new code.
*/
- (id) error: (const char *)aString, ...
{
#define FMT "error: %s (%s)\n%s\n"
char fmt[(strlen((char*)FMT)+strlen((char*)GSClassNameFromObject(self))
+((aString!=NULL)?strlen((char*)aString):0)+8)];
va_list ap;
snprintf(fmt, sizeof(fmt), FMT, GSClassNameFromObject(self),
GSObjCIsInstance(self) ? "instance" : "class",
(aString != NULL) ? aString : "");
va_start(ap, aString);
vfprintf (stderr, fmt, ap);
abort ();
va_end(ap);
#undef FMT
return nil;
}
/*
- (const char *) name
{
return GSClassNameFromObject(self);
}
*/
- (BOOL) isKindOf: (Class)aClassObject
{
return [self isKindOfClass: aClassObject];
}
- (BOOL) isMemberOf: (Class)aClassObject
{
return [self isMemberOfClass: aClassObject];
}
+ (BOOL) instancesRespondTo: (SEL)aSel
{
return [self instancesRespondToSelector: aSel];
}
- (BOOL) respondsTo: (SEL)aSel
{
return [self respondsToSelector: aSel];
}
+ (BOOL) conformsTo: (Protocol*)aProtocol
{
return [self conformsToProtocol: aProtocol];
}
- (BOOL) conformsTo: (Protocol*)aProtocol
{
return [self conformsToProtocol: aProtocol];
}
+ (IMP) instanceMethodFor: (SEL)aSel
{
return [self instanceMethodForSelector:aSel];
}
- (IMP) methodFor: (SEL)aSel
{
return [self methodForSelector: aSel];
}
+ (id) poseAs: (Class)aClassObject
{
[self poseAsClass: aClassObject];
return self;
}
- (id) doesNotRecognize: (SEL)aSel
{
[NSException raise: NSGenericException
format: @"%s(%s) does not recognize %s",
GSClassNameFromObject(self),
GSObjCIsInstance(self) ? "instance" : "class",
aSel ? sel_getName(aSel) : "(null)"];
return nil;
}
- (id) perform: (SEL)sel with: (id)anObject
{
return [self performSelector: sel withObject: anObject];
}
- (id) perform: (SEL)sel with: (id)anObject with: (id)anotherObject
{
return [self performSelector: sel withObject: anObject
withObject: anotherObject];
}
@end
/**
* Some non-standard extensions mainly needed for backwards compatibility
* and internal utility reasons.
*/
@implementation NSObject (GNUstep)
/**
* Enables runtime checking of retain/release/autorelease operations.<br />
* <p>Whenever either -autorelease or -release is called, the contents of any
* autorelease pools will be checked to see if there are more outstanding
* release operations than the objects retain count. In which case an
* exception is raised to say that the object is released too many times.
* </p>
* <p><strong>Beware</strong>, since this feature entails examining all active
* autorelease pools every time an object is released or autoreleased, it
* can cause a massive performance degradation ... it should only be enabled
* for debugging.
* </p>
* <p>
* When you are having memory allocation problems, it may make more sense
* to look at the memory allocation debugging functions documented in
* NSDebug.h, or use the NSZombie features.
* </p>
*/
+ (void) enableDoubleReleaseCheck: (BOOL)enable
{
double_release_check_enabled = enable;
}
/**
* The default (NSObject) implementation of this method simply calls
* the -description method and discards the locale
* information.
*/
- (NSString*) descriptionWithLocale: (id)aLocale
{
return [self description];
}
+ (NSString*) descriptionWithLocale: (id)aLocale
{
return [self description];
}
/**
* The default (NSObject) implementation of this method simply calls
* the -descriptionWithLocale: method and discards the
* level information.
*/
- (NSString*) descriptionWithLocale: (id)aLocale
indent: (NSUInteger)level
{
return [self descriptionWithLocale: aLocale];
}
+ (NSString*) descriptionWithLocale: (id)aLocale
indent: (NSUInteger)level
{
return [self descriptionWithLocale: aLocale];
}
- (BOOL) _dealloc
{
return YES;
}
- (BOOL) isMetaClass
{
return NO;
}
- (BOOL) isClass
{
return class_isMetaClass(object_getClass(self));
}
- (BOOL) isMemberOfClassNamed: (const char*)aClassName
{
return ((aClassName!=NULL)
&&!strcmp(class_getName(object_getClass(self)), aClassName));
}
+ (struct objc_method_description *) descriptionForInstanceMethod: (SEL)aSel
{
if (aSel == 0)
[NSException raise: NSInvalidArgumentException
format: @"%@ null selector given", NSStringFromSelector(_cmd)];
return ((struct objc_method_description *)
GSGetMethod(self, aSel, YES, YES));
}
- (struct objc_method_description *) descriptionForMethod: (SEL)aSel
{
if (aSel == 0)
[NSException raise: NSInvalidArgumentException
format: @"%@ null selector given", NSStringFromSelector(_cmd)];
return ((struct objc_method_description *)
GSGetMethod((GSObjCIsInstance(self)
? object_getClass(self) : (Class)self),
aSel,
GSObjCIsInstance(self),
YES));
}
+ (NSInteger) streamVersion: (void*)aStream
{
GSOnceMLog(@"[NSObject+streamVersion:] is deprecated ... do not use");
return class_getVersion (self);
}
- (id) read: (void*)aStream
{
GSOnceMLog(@"[NSObject-read:] is deprecated ... do not use");
return self;
}
- (id) write: (void*)aStream
{
GSOnceMLog(@"[NSObject-write:] is deprecated ... do not use");
return self;
}
- (id) awake
{
GSOnceMLog(@"[NSObject-awake] is deprecated ... do not use");
return self;
}
@end
@implementation NSZombie
- (Class) class
{
return object_getClass(self);
}
- (Class) originalClass
{
Class c = Nil;
if (0 != zombieMap)
{
GS_MUTEX_LOCK(allocationLock);
if (0 != zombieMap)
{
c = NSMapGet(zombieMap, (void*)self);
}
GS_MUTEX_UNLOCK(allocationLock);
}
return c;
}
- (NSUInteger) retainCount
{
return 0; // So that gs_weak_load() knows the object was deallocated
}
- (void) logZombie: (SEL)selector
{
GSLogZombie(self, selector);
}
- (void) forwardInvocation: (NSInvocation*)anInvocation
{
NSUInteger size = [[anInvocation methodSignature] methodReturnLength];
unsigned char v[size];
memset(v, '\0', size);
[self logZombie: [anInvocation selector]];
[anInvocation setReturnValue: (void*)v];
return;
}
- (NSMethodSignature*) methodSignatureForSelector: (SEL)aSelector
{
Class c;
if (0 == aSelector)
{
return nil;
}
GS_MUTEX_LOCK(allocationLock);
c = zombieMap ? NSMapGet(zombieMap, (void*)self) : Nil;
GS_MUTEX_UNLOCK(allocationLock);
return [c instanceMethodSignatureForSelector: aSelector];
}
@end
@implementation GSContentAccessingProxy
- (void) dealloc
{
[object endContentAccess];
[super dealloc];
}
- (void) finalize
{
[object endContentAccess];
}
- (id) forwardingTargetForSelector: (SEL)aSelector
{
return object;
}
/* Support for legacy runtimes... */
- (void) forwardInvocation: (NSInvocation*)anInvocation
{
[anInvocation invokeWithTarget: object];
}
- (id) initWithObject: (id)anObject
{
ASSIGN(object, anObject);
[object beginContentAccess];
return self;
}
- (NSMethodSignature*) methodSignatureForSelector: (SEL)aSelector
{
return [object methodSignatureForSelector: aSelector];
}
@end
NSUInteger
GSPrivateMemorySize(NSObject *self, NSHashTable *exclude)
{
if (0 == NSHashGet(exclude, self))
{
NSHashInsert(exclude, self);
return class_getInstanceSize(object_getClass(self));
}
return 0;
}
@implementation NSObject (MemoryFootprint)
+ (NSUInteger) contentSizeOf: (NSObject*)obj
excluding: (NSHashTable*)exclude
{
Class cls = object_getClass(obj);
NSUInteger size = 0;
while (cls != Nil)
{
unsigned count;
Ivar *vars;
if (0 != (vars = class_copyIvarList(cls, &count)))
{
while (count-- > 0)
{
const char *type = ivar_getTypeEncoding(vars[count]);
type = GSSkipTypeQualifierAndLayoutInfo(type);
if ('@' == *type)
{
NSObject *content = object_getIvar(obj, vars[count]);
if (content != nil)
{
size += [content sizeInBytesExcluding: exclude];
}
}
}
free(vars);
}
cls = class_getSuperclass(cls);
}
return size;
}
+ (NSUInteger) sizeInBytes
{
return 0;
}
+ (NSUInteger) sizeInBytesExcluding: (NSHashTable*)exclude
{
return 0;
}
+ (NSUInteger) sizeOfContentExcluding: (NSHashTable*)exclude
{
return 0;
}
- (NSUInteger) sizeInBytes
{
NSUInteger bytes;
NSHashTable *exclude;
exclude = NSCreateHashTable(NSNonOwnedPointerHashCallBacks, 0);
bytes = [self sizeInBytesExcluding: exclude];
NSFreeHashTable(exclude);
return bytes;
}
- (NSUInteger) sizeInBytesExcluding: (NSHashTable*)exclude
{
if (0 == NSHashGet(exclude, self))
{
NSUInteger size = [self sizeOfInstance];
NSHashInsert(exclude, self);
if (size > 0)
{
size += [self sizeOfContentExcluding: exclude];
}
return size;
}
return 0;
}
- (NSUInteger) sizeOfContentExcluding: (NSHashTable*)exclude
{
return 0;
}
- (NSUInteger) sizeOfInstance
{
NSUInteger size;
#if GS_SIZEOF_VOIDP > 4
NSUInteger u = (NSUInteger)self;
if (u & 0x07)
{
return 0; // Small object has no size
}
#endif
#if HAVE_MALLOC_USABLE_SIZE
size = malloc_usable_size((void*)self - sizeof(intptr_t));
#else
size = class_getInstanceSize(object_getClass(self));
#endif
return size;
}
@end
|