malloc.c 43.3 KB
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
// RUN: %clang_analyze_cc1 -analyzer-store=region -verify %s \
// RUN:   -analyzer-checker=core \
// RUN:   -analyzer-checker=alpha.deadcode.UnreachableCode \
// RUN:   -analyzer-checker=alpha.core.CastSize \
// RUN:   -analyzer-checker=unix \
// RUN:   -analyzer-checker=debug.ExprInspection

#include "Inputs/system-header-simulator.h"

void clang_analyzer_eval(int);

// Without -fms-compatibility, wchar_t isn't a builtin type. MSVC defines
// _WCHAR_T_DEFINED if wchar_t is available. Microsoft recommends that you use
// the builtin type: "Using the typedef version can cause portability
// problems", but we're ok here because we're not actually running anything.
// Also of note is this cryptic warning: "The wchar_t type is not supported
// when you compile C code".
//
// See the docs for more:
// https://msdn.microsoft.com/en-us/library/dh8che7s.aspx
#if !defined(_WCHAR_T_DEFINED)
// "Microsoft implements wchar_t as a two-byte unsigned value"
typedef unsigned short wchar_t;
#define _WCHAR_T_DEFINED
#endif // !defined(_WCHAR_T_DEFINED)

typedef __typeof(sizeof(int)) size_t;
void *malloc(size_t);
void *alloca(size_t);
void *valloc(size_t);
void free(void *);
void *realloc(void *ptr, size_t size);
void *reallocf(void *ptr, size_t size);
void *calloc(size_t nmemb, size_t size);
char *strdup(const char *s);
wchar_t *wcsdup(const wchar_t *s);
char *strndup(const char *s, size_t n);
int memcmp(const void *s1, const void *s2, size_t n);

// Windows variants
char *_strdup(const char *strSource);
wchar_t *_wcsdup(const wchar_t *strSource);
void *_alloca(size_t size);

void myfoo(int *p);
void myfooint(int p);
char *fooRetPtr();

void f1() {
  int *p = malloc(12);
  return; // expected-warning{{Potential leak of memory pointed to by 'p'}}
}

void f2() {
  int *p = malloc(12);
  free(p);
  free(p); // expected-warning{{Attempt to free released memory}}
}

void f2_realloc_0() {
  int *p = malloc(12);
  realloc(p,0);
  realloc(p,0); // expected-warning{{Attempt to free released memory}}
}

void f2_realloc_1() {
  int *p = malloc(12);
  int *q = realloc(p,0); // no-warning
}

void reallocNotNullPtr(unsigned sizeIn) {
  unsigned size = 12;
  char *p = (char*)malloc(size);
  if (p) {
    char *q = (char*)realloc(p, sizeIn);
    char x = *q; // expected-warning {{Potential leak of memory pointed to by 'q'}}
  }
}

void allocaTest() {
  int *p = alloca(sizeof(int));
} // no warn

void winAllocaTest() {
  int *p = _alloca(sizeof(int));
} // no warn

void allocaBuiltinTest() {
  int *p = __builtin_alloca(sizeof(int));
} // no warn

int *realloctest1() {
  int *q = malloc(12);
  q = realloc(q, 20);
  return q; // no warning - returning the allocated value
}

// p should be freed if realloc fails.
void reallocFails() {
  char *p = malloc(12);
  char *r = realloc(p, 12+1);
  if (!r) {
    free(p);
  } else {
    free(r);
  }
}

void reallocSizeZero1() {
  char *p = malloc(12);
  char *r = realloc(p, 0);
  if (!r) {
    free(p); // expected-warning {{Attempt to free released memory}}
  } else {
    free(r);
  }
}

void reallocSizeZero2() {
  char *p = malloc(12);
  char *r = realloc(p, 0);
  if (!r) {
    free(p); // expected-warning {{Attempt to free released memory}}
  } else {
    free(r);
  }
  free(p); // expected-warning {{Attempt to free released memory}}
}

void reallocSizeZero3() {
  char *p = malloc(12);
  char *r = realloc(p, 0);
  free(r);
}

void reallocSizeZero4() {
  char *r = realloc(0, 0);
  free(r);
}

void reallocSizeZero5() {
  char *r = realloc(0, 0);
}

void reallocPtrZero1() {
  char *r = realloc(0, 12);
} // expected-warning {{Potential leak of memory pointed to by 'r'}}

void reallocPtrZero2() {
  char *r = realloc(0, 12);
  if (r)
    free(r);
}

void reallocPtrZero3() {
  char *r = realloc(0, 12);
  free(r);
}

void reallocRadar6337483_1() {
    char *buf = malloc(100);
    buf = (char*)realloc(buf, 0x1000000);
    if (!buf) {
        return;// expected-warning {{Potential leak of memory pointed to by}}
    }
    free(buf);
}

void reallocRadar6337483_2() {
    char *buf = malloc(100);
    char *buf2 = (char*)realloc(buf, 0x1000000);
    if (!buf2) {
      ;
    } else {
      free(buf2);
    }
} // expected-warning {{Potential leak of memory pointed to by}}

void reallocRadar6337483_3() {
    char * buf = malloc(100);
    char * tmp;
    tmp = (char*)realloc(buf, 0x1000000);
    if (!tmp) {
        free(buf);
        return;
    }
    buf = tmp;
    free(buf);
}

void reallocRadar6337483_4() {
    char *buf = malloc(100);
    char *buf2 = (char*)realloc(buf, 0x1000000);
    if (!buf2) {
      return;  // expected-warning {{Potential leak of memory pointed to by}}
    } else {
      free(buf2);
    }
}

int *reallocfTest1() {
  int *q = malloc(12);
  q = reallocf(q, 20);
  return q; // no warning - returning the allocated value
}

void reallocfRadar6337483_4() {
    char *buf = malloc(100);
    char *buf2 = (char*)reallocf(buf, 0x1000000);
    if (!buf2) {
      return;  // no warning - reallocf frees even on failure
    } else {
      free(buf2);
    }
}

void reallocfRadar6337483_3() {
    char * buf = malloc(100);
    char * tmp;
    tmp = (char*)reallocf(buf, 0x1000000);
    if (!tmp) {
        free(buf); // expected-warning {{Attempt to free released memory}}
        return;
    }
    buf = tmp;
    free(buf);
}

void reallocfPtrZero1() {
  char *r = reallocf(0, 12);
} // expected-warning {{Potential leak of memory pointed to by}}

//------------------- Check usage of zero-allocated memory ---------------------
void CheckUseZeroAllocatedNoWarn1() {
  int *p = malloc(0);
  free(p); // no warning
}

void CheckUseZeroAllocatedNoWarn2() {
  int *p = alloca(0); // no warning
}

void CheckUseZeroWinAllocatedNoWarn2() {
  int *p = _alloca(0); // no warning
}


void CheckUseZeroAllocatedNoWarn3() {
  int *p = malloc(0);
  int *q = realloc(p, 8); // no warning
  free(q);
}

void CheckUseZeroAllocatedNoWarn4() {
  int *p = realloc(0, 8);
  *p = 1; // no warning
  free(p);
}

void CheckUseZeroAllocated1() {
  int *p = malloc(0);
  *p = 1; // expected-warning {{Use of zero-allocated memory}}
  free(p);
}

char CheckUseZeroAllocated2() {
  char *p = alloca(0);
  return *p; // expected-warning {{Use of zero-allocated memory}}
}

char CheckUseZeroWinAllocated2() {
  char *p = _alloca(0);
  return *p; // expected-warning {{Use of zero-allocated memory}}
}

void UseZeroAllocated(int *p) {
  if (p)
    *p = 7; // expected-warning {{Use of zero-allocated memory}}
}
void CheckUseZeroAllocated3() {
  int *p = malloc(0);
  UseZeroAllocated(p);
}

void f(char);
void CheckUseZeroAllocated4() {
  char *p = valloc(0);
  f(*p); // expected-warning {{Use of zero-allocated memory}}
  free(p);
}

void CheckUseZeroAllocated5() {
  int *p = calloc(0, 2);
  *p = 1; // expected-warning {{Use of zero-allocated memory}}
  free(p);
}

void CheckUseZeroAllocated6() {
  int *p = calloc(2, 0);
  *p = 1; // expected-warning {{Use of zero-allocated memory}}
  free(p);
}

void CheckUseZeroAllocated7() {
  int *p = realloc(0, 0);
  *p = 1; // expected-warning {{Use of zero-allocated memory}}
  free(p);
}

void CheckUseZeroAllocated8() {
  int *p = malloc(8);
  int *q = realloc(p, 0);
  *q = 1; // expected-warning {{Use of zero-allocated memory}}
  free(q);
}

void CheckUseZeroAllocated9() {
  int *p = realloc(0, 0);
  int *q = realloc(p, 0);
  *q = 1; // expected-warning {{Use of zero-allocated memory}}
  free(q);
}

void CheckUseZeroAllocatedPathNoWarn(_Bool b) {
  int s = 0;
  if (b)
    s= 10;

  char *p = malloc(s);

  if (b)
    *p = 1; // no warning

  free(p);
}

void CheckUseZeroAllocatedPathWarn(_Bool b) {
  int s = 10;
  if (b)
    s= 0;

  char *p = malloc(s);

  if (b)
    *p = 1; // expected-warning {{Use of zero-allocated memory}}

  free(p);
}

void CheckUseZeroReallocatedPathNoWarn(_Bool b) {
  int s = 0;
  if (b)
    s= 10;

  char *p = malloc(8);
  char *q = realloc(p, s);

  if (b)
    *q = 1; // no warning

  free(q);
}

void CheckUseZeroReallocatedPathWarn(_Bool b) {
  int s = 10;
  if (b)
    s= 0;

  char *p = malloc(8);
  char *q = realloc(p, s);

  if (b)
    *q = 1; // expected-warning {{Use of zero-allocated memory}}

  free(q);
}

// This case tests that storing malloc'ed memory to a static variable which is
// then returned is not leaked.  In the absence of known contracts for functions
// or inter-procedural analysis, this is a conservative answer.
int *f3() {
  static int *p = 0;
  p = malloc(12);
  return p; // no-warning
}

// This case tests that storing malloc'ed memory to a static global variable
// which is then returned is not leaked.  In the absence of known contracts for
// functions or inter-procedural analysis, this is a conservative answer.
static int *p_f4 = 0;
int *f4() {
  p_f4 = malloc(12);
  return p_f4; // no-warning
}

int *f5() {
  int *q = malloc(12);
  q = realloc(q, 20);
  return q; // no-warning
}

void f6() {
  int *p = malloc(12);
  if (!p)
    return; // no-warning
  else
    free(p);
}

void f6_realloc() {
  int *p = malloc(12);
  if (!p)
    return; // no-warning
  else
    realloc(p,0);
}


char *doit2();
void pr6069() {
  char *buf = doit2();
  free(buf);
}

void pr6293() {
  free(0);
}

void f7() {
  char *x = (char*) malloc(4);
  free(x);
  x[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
}

void f8() {
  char *x = (char*) malloc(4);
  free(x);
  char *y = strndup(x, 4); // expected-warning{{Use of memory after it is freed}}
}

void f7_realloc() {
  char *x = (char*) malloc(4);
  realloc(x,0);
  x[0] = 'a'; // expected-warning{{Use of memory after it is freed}}
}

void PR6123() {
  int *x = malloc(11); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
}

void PR7217() {
  int *buf = malloc(2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
  buf[1] = 'c'; // not crash
}

void cast_emtpy_struct() {
  struct st {
  };

  struct st *s = malloc(sizeof(struct st)); // no-warning
  free(s);
}

void cast_struct_1() {
  struct st {
    int i[100];
    char j[];
  };

  struct st *s = malloc(sizeof(struct st)); // no-warning
  free(s);
}

void cast_struct_2() {
  struct st {
    int i[100];
    char j[0];
  };

  struct st *s = malloc(sizeof(struct st)); // no-warning
  free(s);
}

void cast_struct_3() {
  struct st {
    int i[100];
    char j[1];
  };

  struct st *s = malloc(sizeof(struct st)); // no-warning
  free(s);
}

void cast_struct_4() {
  struct st {
    int i[100];
    char j[2];
  };

  struct st *s = malloc(sizeof(struct st)); // no-warning
  free(s);
}

void cast_struct_5() {
  struct st {
    char i[200];
    char j[1];
  };

  struct st *s = malloc(sizeof(struct st) - sizeof(char)); // no-warning
  free(s);
}

void cast_struct_warn_1() {
  struct st {
    int i[100];
    char j[2];
  };

  struct st *s = malloc(sizeof(struct st) + 2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
  free(s);
}

void cast_struct_warn_2() {
  struct st {
    int i[100];
    char j[2];
  };

  struct st *s = malloc(2); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
  free(s);
}

void cast_struct_flex_array_1() {
  struct st {
    int i[100];
    char j[];
  };

  struct st *s = malloc(sizeof(struct st) + 3); // no-warning
  free(s);
}

void cast_struct_flex_array_2() {
  struct st {
    int i[100];
    char j[0];
  };

  struct st *s = malloc(sizeof(struct st) + 3); // no-warning
  free(s);
}

void cast_struct_flex_array_3() {
  struct st {
    int i[100];
    char j[1];
  };

  struct st *s = malloc(sizeof(struct st) + 3); // no-warning
  free(s);
}

void cast_struct_flex_array_4() {
  struct foo {
    char f[32];
  };
  struct st {
    char i[100];
    struct foo data[];
  };

  struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
  free(s);
}

void cast_struct_flex_array_5() {
  struct foo {
    char f[32];
  };
  struct st {
    char i[100];
    struct foo data[0];
  };

  struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
  free(s);
}

void cast_struct_flex_array_6() {
  struct foo {
    char f[32];
  };
  struct st {
    char i[100];
    struct foo data[1];
  };

  struct st *s = malloc(sizeof(struct st) + 3 * sizeof(struct foo)); // no-warning
  free(s);
}

void cast_struct_flex_array_warn_1() {
  struct foo {
    char f[32];
  };
  struct st {
    char i[100];
    struct foo data[];
  };

  struct st *s = malloc(3 * sizeof(struct st) + 3 * sizeof(struct foo)); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
  free(s);
}

void cast_struct_flex_array_warn_2() {
  struct foo {
    char f[32];
  };
  struct st {
    char i[100];
    struct foo data[0];
  };

  struct st *s = malloc(3 * sizeof(struct st) + 3 * sizeof(struct foo)); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
  free(s);
}

void cast_struct_flex_array_warn_3() {
  struct foo {
    char f[32];
  };
  struct st {
    char i[100];
    struct foo data[1];
  };

  struct st *s = malloc(3 * sizeof(struct st) + 3 * sizeof(struct foo)); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
  free(s);
}

void cast_struct_flex_array_warn_4() {
  struct st {
    int i[100];
    int j[];
  };

  struct st *s = malloc(sizeof(struct st) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
  free(s);
}

void cast_struct_flex_array_warn_5() {
  struct st {
    int i[100];
    int j[0];
  };

  struct st *s = malloc(sizeof(struct st) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
  free(s);
}

void cast_struct_flex_array_warn_6() {
  struct st {
    int i[100];
    int j[1];
  };

  struct st *s = malloc(sizeof(struct st) + 3); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
  free(s);
}

void mallocCastToVoid() {
  void *p = malloc(2);
  const void *cp = p; // not crash
  free(p);
}

void mallocCastToFP() {
  void *p = malloc(2);
  void (*fp)() = p; // not crash
  free(p);
}

// This tests that malloc() buffers are undefined by default
char mallocGarbage () {
	char *buf = malloc(2);
	char result = buf[1]; // expected-warning{{undefined}}
	free(buf);
	return result;
}

// This tests that calloc() buffers need to be freed
void callocNoFree () {
  char *buf = calloc(2,2);
  return; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
}

// These test that calloc() buffers are zeroed by default
char callocZeroesGood () {
	char *buf = calloc(2,2);
	char result = buf[3]; // no-warning
	if (buf[1] == 0) {
	  free(buf);
	}
	return result; // no-warning
}

char callocZeroesBad () {
	char *buf = calloc(2,2);
	char result = buf[3]; // no-warning
	if (buf[1] != 0) {
	  free(buf); // expected-warning{{never executed}}
	}
	return result; // expected-warning{{Potential leak of memory pointed to by 'buf'}}
}

void nullFree() {
  int *p = 0;
  free(p); // no warning - a nop
}

void paramFree(int *p) {
  myfoo(p);
  free(p); // no warning
  myfoo(p); // expected-warning {{Use of memory after it is freed}}
}

int* mallocEscapeRet() {
  int *p = malloc(12);
  return p; // no warning
}

void mallocEscapeFoo() {
  int *p = malloc(12);
  myfoo(p);
  return; // no warning
}

void mallocEscapeFree() {
  int *p = malloc(12);
  myfoo(p);
  free(p);
}

void mallocEscapeFreeFree() {
  int *p = malloc(12);
  myfoo(p);
  free(p);
  free(p); // expected-warning{{Attempt to free released memory}}
}

void mallocEscapeFreeUse() {
  int *p = malloc(12);
  myfoo(p);
  free(p);
  myfoo(p); // expected-warning{{Use of memory after it is freed}}
}

int *myalloc();
void myalloc2(int **p);

void mallocEscapeFreeCustomAlloc() {
  int *p = malloc(12);
  myfoo(p);
  free(p);
  p = myalloc();
  free(p); // no warning
}

void mallocEscapeFreeCustomAlloc2() {
  int *p = malloc(12);
  myfoo(p);
  free(p);
  myalloc2(&p);
  free(p); // no warning
}

void mallocBindFreeUse() {
  int *x = malloc(12);
  int *y = x;
  free(y);
  myfoo(x); // expected-warning{{Use of memory after it is freed}}
}

void mallocEscapeMalloc() {
  int *p = malloc(12);
  myfoo(p);
  p = malloc(12);
} // expected-warning{{Potential leak of memory pointed to by}}

void mallocMalloc() {
  int *p = malloc(12);
  p = malloc(12);
} // expected-warning {{Potential leak of memory pointed to by}}\
  // expected-warning {{Potential leak of memory pointed to by}}

void mallocFreeMalloc() {
  int *p = malloc(12);
  free(p);
  p = malloc(12);
  free(p);
}

void mallocFreeUse_params() {
  int *p = malloc(12);
  free(p);
  myfoo(p); //expected-warning{{Use of memory after it is freed}}
}

void mallocFreeUse_params2() {
  int *p = malloc(12);
  free(p);
  myfooint(*p); //expected-warning{{Use of memory after it is freed}}
}

void mallocFailedOrNot() {
  int *p = malloc(12);
  if (!p)
    free(p);
  else
    free(p);
}

struct StructWithInt {
  int g;
};

int *mallocReturnFreed() {
  int *p = malloc(12);
  free(p);
  return p; // expected-warning {{Use of memory after it is freed}}
}

int useAfterFreeStruct() {
  struct StructWithInt *px= malloc(sizeof(struct StructWithInt));
  px->g = 5;
  free(px);
  return px->g; // expected-warning {{Use of memory after it is freed}}
}

void nonSymbolAsFirstArg(int *pp, struct StructWithInt *p);

void mallocEscapeFooNonSymbolArg() {
  struct StructWithInt *p = malloc(sizeof(struct StructWithInt));
  nonSymbolAsFirstArg(&p->g, p);
  return; // no warning
}

void mallocFailedOrNotLeak() {
  int *p = malloc(12);
  if (p == 0)
    return; // no warning
  else
    return; // expected-warning {{Potential leak of memory pointed to by}}
}

void mallocAssignment() {
  char *p = malloc(12);
  p = fooRetPtr();
} // expected-warning {{leak}}

int vallocTest() {
  char *mem = valloc(12);
  return 0; // expected-warning {{Potential leak of memory pointed to by}}
}

void vallocEscapeFreeUse() {
  int *p = valloc(12);
  myfoo(p);
  free(p);
  myfoo(p); // expected-warning{{Use of memory after it is freed}}
}

int *Gl;
struct GlStTy {
  int *x;
};

struct GlStTy GlS = {0};

void GlobalFree() {
  free(Gl);
}

void GlobalMalloc() {
  Gl = malloc(12);
}

void GlobalStructMalloc() {
  int *a = malloc(12);
  GlS.x = a;
}

void GlobalStructMallocFree() {
  int *a = malloc(12);
  GlS.x = a;
  free(GlS.x);
}

char *ArrayG[12];

void globalArrayTest() {
  char *p = (char*)malloc(12);
  ArrayG[0] = p;
}

// Make sure that we properly handle a pointer stored into a local struct/array.
typedef struct _StructWithPtr {
  int *memP;
} StructWithPtr;

static StructWithPtr arrOfStructs[10];

void testMalloc() {
  int *x = malloc(12);
  StructWithPtr St;
  St.memP = x;
  arrOfStructs[0] = St; // no-warning
}

StructWithPtr testMalloc2() {
  int *x = malloc(12);
  StructWithPtr St;
  St.memP = x;
  return St; // no-warning
}

int *testMalloc3() {
  int *x = malloc(12);
  int *y = x;
  return y; // no-warning
}

void testStructLeak() {
  StructWithPtr St;
  St.memP = malloc(12);
  return; // expected-warning {{Potential leak of memory pointed to by 'St.memP'}}
}

void testElemRegion1() {
  char *x = (void*)malloc(2);
  int *ix = (int*)x;
  free(&(x[0]));
}

void testElemRegion2(int **pp) {
  int *p = malloc(12);
  *pp = p;
  free(pp[0]);
}

void testElemRegion3(int **pp) {
  int *p = malloc(12);
  *pp = p;
  free(*pp);
}
// Region escape testing.

unsigned takePtrToPtr(int **p);
void PassTheAddrOfAllocatedData(int f) {
  int *p = malloc(12);
  // We don't know what happens after the call. Should stop tracking here.
  if (takePtrToPtr(&p))
    f++;
  free(p); // no warning
}

struct X {
  int *p;
};
unsigned takePtrToStruct(struct X *s);
int ** foo2(int *g, int f) {
  int *p = malloc(12);
  struct X *px= malloc(sizeof(struct X));
  px->p = p;
  // We don't know what happens after this call. Should not track px nor p.
  if (takePtrToStruct(px))
    f++;
  free(p);
  return 0;
}

struct X* RegInvalidationDetect1(struct X *s2) {
  struct X *px= malloc(sizeof(struct X));
  px->p = 0;
  px = s2;
  return px; // expected-warning {{Potential leak of memory pointed to by}}
}

struct X* RegInvalidationGiveUp1() {
  int *p = malloc(12);
  struct X *px= malloc(sizeof(struct X));
  px->p = p;
  return px;
}

int **RegInvalidationDetect2(int **pp) {
  int *p = malloc(12);
  pp = &p;
  pp++;
  return 0;// expected-warning {{Potential leak of memory pointed to by}}
}

extern void exit(int) __attribute__ ((__noreturn__));
void mallocExit(int *g) {
  struct xx *p = malloc(12);
  if (g != 0)
    exit(1);
  free(p);
  return;
}

extern void __assert_fail (__const char *__assertion, __const char *__file,
    unsigned int __line, __const char *__function)
     __attribute__ ((__noreturn__));
#define assert(expr) \
  ((expr)  ? (void)(0)  : __assert_fail (#expr, __FILE__, __LINE__, __func__))
void mallocAssert(int *g) {
  struct xx *p = malloc(12);

  assert(g != 0);
  free(p);
  return;
}

void doNotInvalidateWhenPassedToSystemCalls(char *s) {
  char *p = malloc(12);
  strlen(p);
  strcpy(p, s);
  strcpy(s, p);
  strcpy(p, p);
  memcpy(p, s, 1);
  memcpy(s, p, 1);
  memcpy(p, p, 1);
} // expected-warning {{leak}}

// Treat source buffer contents as escaped.
void escapeSourceContents(char *s) {
  char *p = malloc(12);
  memcpy(s, &p, 12); // no warning

  void *p1 = malloc(7);
  char *a;
  memcpy(&a, &p1, sizeof a);
  // FIXME: No warning due to limitations imposed by current modelling of
  // 'memcpy' (regions metadata is not copied).

  int *ptrs[2];
  int *allocated = (int *)malloc(4);
  memcpy(&ptrs[0], &allocated, sizeof(int *));
  // FIXME: No warning due to limitations imposed by current modelling of
  // 'memcpy' (regions metadata is not copied).
}

void invalidateDestinationContents() {
  int *null = 0;
  int *p = (int *)malloc(4);
  memcpy(&p, &null, sizeof(int *));

  int *ptrs1[2]; // expected-warning {{Potential leak of memory pointed to by}}
  ptrs1[0] = (int *)malloc(4);
  memcpy(ptrs1,  &null, sizeof(int *));

  int *ptrs2[2]; // expected-warning {{Potential memory leak}}
  ptrs2[0] = (int *)malloc(4);
  memcpy(&ptrs2[1],  &null, sizeof(int *));

  int *ptrs3[2]; // expected-warning {{Potential memory leak}}
  ptrs3[0] = (int *)malloc(4);
  memcpy(&ptrs3[0],  &null, sizeof(int *));
} // expected-warning {{Potential memory leak}}

// Rely on the CString checker evaluation of the strcpy API to convey that the result of strcpy is equal to p.
void symbolLostWithStrcpy(char *s) {
  char *p = malloc(12);
  p = strcpy(p, s);
  free(p);
}


// The same test as the one above, but with what is actually generated on a mac.
static __inline char *
__inline_strcpy_chk (char *restrict __dest, const char *restrict __src)
{
  return __builtin___strcpy_chk (__dest, __src, __builtin_object_size (__dest, 2 > 1));
}

void symbolLostWithStrcpy_InlineStrcpyVersion(char *s) {
  char *p = malloc(12);
  p = ((__builtin_object_size (p, 0) != (size_t) -1) ? __builtin___strcpy_chk (p, s, __builtin_object_size (p, 2 > 1)) : __inline_strcpy_chk (p, s));
  free(p);
}

// Here we are returning a pointer one past the allocated value. An idiom which
// can be used for implementing special malloc. The correct uses of this might
// be rare enough so that we could keep this as a warning.
static void *specialMalloc(int n){
  int *p;
  p = malloc( n+8 );
  if( p ){
    p[0] = n;
    p++;
  }
  return p;
}

// Potentially, the user could free the struct by performing pointer arithmetic on the return value.
// This is a variation of the specialMalloc issue, though probably would be more rare in correct code.
int *specialMallocWithStruct() {
  struct StructWithInt *px= malloc(sizeof(struct StructWithInt));
  return &(px->g);
}

// Test various allocation/deallocation functions.
void testStrdup(const char *s, unsigned validIndex) {
  char *s2 = strdup(s);
  s2[validIndex + 1] = 'b';
} // expected-warning {{Potential leak of memory pointed to by}}

void testWinStrdup(const char *s, unsigned validIndex) {
  char *s2 = _strdup(s);
  s2[validIndex + 1] = 'b';
} // expected-warning {{Potential leak of memory pointed to by}}

void testWcsdup(const wchar_t *s, unsigned validIndex) {
  wchar_t *s2 = wcsdup(s);
  s2[validIndex + 1] = 'b';
} // expected-warning {{Potential leak of memory pointed to by}}

void testWinWcsdup(const wchar_t *s, unsigned validIndex) {
  wchar_t *s2 = _wcsdup(s);
  s2[validIndex + 1] = 'b';
} // expected-warning {{Potential leak of memory pointed to by}}

int testStrndup(const char *s, unsigned validIndex, unsigned size) {
  char *s2 = strndup(s, size);
  s2 [validIndex + 1] = 'b';
  if (s2[validIndex] != 'a')
    return 0;
  else
    return 1;// expected-warning {{Potential leak of memory pointed to by}}
}

void testStrdupContentIsDefined(const char *s, unsigned validIndex) {
  char *s2 = strdup(s);
  char result = s2[1];// no warning
  free(s2);
}

void testWinStrdupContentIsDefined(const char *s, unsigned validIndex) {
  char *s2 = _strdup(s);
  char result = s2[1];// no warning
  free(s2);
}

void testWcsdupContentIsDefined(const wchar_t *s, unsigned validIndex) {
  wchar_t *s2 = wcsdup(s);
  wchar_t result = s2[1];// no warning
  free(s2);
}

void testWinWcsdupContentIsDefined(const wchar_t *s, unsigned validIndex) {
  wchar_t *s2 = _wcsdup(s);
  wchar_t result = s2[1];// no warning
  free(s2);
}

// ----------------------------------------------------------------------------
// Test the system library functions to which the pointer can escape.
// This tests false positive suppression.

// For now, we assume memory passed to pthread_specific escapes.
// TODO: We could check that if a new pthread binding is set, the existing
// binding must be freed; otherwise, a memory leak can occur.
void testPthereadSpecificEscape(pthread_key_t key) {
  void *buf = malloc(12);
  pthread_setspecific(key, buf); // no warning
}

// PR12101: Test funopen().
static int releasePtr(void *_ctx) {
    free(_ctx);
    return 0;
}
FILE *useFunOpen() {
    void *ctx = malloc(sizeof(int));
    FILE *f = funopen(ctx, 0, 0, 0, releasePtr); // no warning
    if (f == 0) {
        free(ctx);
    }
    return f;
}
FILE *useFunOpenNoReleaseFunction() {
    void *ctx = malloc(sizeof(int));
    FILE *f = funopen(ctx, 0, 0, 0, 0);
    if (f == 0) {
        free(ctx);
    }
    return f; // expected-warning{{leak}}
}

static int readNothing(void *_ctx, char *buf, int size) {
  return 0;
}
FILE *useFunOpenReadNoRelease() {
  void *ctx = malloc(sizeof(int));
  FILE *f = funopen(ctx, readNothing, 0, 0, 0);
  if (f == 0) {
    free(ctx);
  }
  return f; // expected-warning{{leak}}
}

// Test setbuf, setvbuf.
int my_main_no_warning() {
    char *p = malloc(100);
    setvbuf(stdout, p, 0, 100);
    return 0;
}
int my_main_no_warning2() {
    char *p = malloc(100);
    setbuf(__stdoutp, p);
    return 0;
}
int my_main_warn(FILE *f) {
    char *p = malloc(100);
    setvbuf(f, p, 0, 100);
    return 0;// expected-warning {{leak}}
}

// <rdar://problem/10978247>.
// some people use stack allocated memory as an optimization to avoid
// a heap allocation for small work sizes.  This tests the analyzer's
// understanding that the malloc'ed memory is not the same as stackBuffer.
void radar10978247(int myValueSize) {
  char stackBuffer[128];
  char *buffer;

  if (myValueSize <= sizeof(stackBuffer))
    buffer = stackBuffer;
  else
    buffer = malloc(myValueSize);

  // do stuff with the buffer
  if (buffer != stackBuffer)
    free(buffer);
}

void radar10978247_positive(int myValueSize) {
  char stackBuffer[128];
  char *buffer;

  if (myValueSize <= sizeof(stackBuffer))
    buffer = stackBuffer;
  else
    buffer = malloc(myValueSize);

  // do stuff with the buffer
  if (buffer == stackBuffer)
    return;
  else
    return; // expected-warning {{leak}}
}
// <rdar://problem/11269741> Previously this triggered a false positive
// because malloc() is known to return uninitialized memory and the binding
// of 'o' to 'p->n' was not getting propertly handled.  Now we report a leak.
struct rdar11269741_a_t {
  struct rdar11269741_b_t {
    int m;
  } n;
};

int rdar11269741(struct rdar11269741_b_t o)
{
  struct rdar11269741_a_t *p = (struct rdar11269741_a_t *) malloc(sizeof(*p));
  p->n = o;
  return p->n.m; // expected-warning {{leak}}
}

// Pointer arithmetic, returning an ElementRegion.
void *radar11329382(unsigned bl) {
  void *ptr = malloc (16);
  ptr = ptr + (2 - bl);
  return ptr; // no warning
}

void __assert_rtn(const char *, const char *, int, const char *) __attribute__((__noreturn__));
int strcmp(const char *, const char *);
char *a (void);
void radar11270219(void) {
  char *x = a(), *y = a();
  (__builtin_expect(!(x && y), 0) ? __assert_rtn(__func__, "/Users/zaks/tmp/ex.c", 24, "x && y") : (void)0);
  strcmp(x, y); // no warning
}

void radar_11358224_test_double_assign_ints_positive_2()
{
  void *ptr = malloc(16);
  ptr = ptr;
} // expected-warning {{leak}}

// Assume that functions which take a function pointer can free memory even if
// they are defined in system headers and take the const pointer to the
// allocated memory. (radar://11160612)
int const_ptr_and_callback(int, const char*, int n, void(*)(void*));
void r11160612_1() {
  char *x = malloc(12);
  const_ptr_and_callback(0, x, 12, free); // no - warning
}

// Null is passed as callback.
void r11160612_2() {
  char *x = malloc(12);
  const_ptr_and_callback(0, x, 12, 0);
} // expected-warning {{leak}}

// Callback is passed to a function defined in a system header.
void r11160612_4() {
  char *x = malloc(12);
  sqlite3_bind_text_my(0, x, 12, free); // no - warning
}

// Passing callbacks in a struct.
void r11160612_5(StWithCallback St) {
  void *x = malloc(12);
  dealocateMemWhenDoneByVal(x, St);
}
void r11160612_6(StWithCallback St) {
  void *x = malloc(12);
  dealocateMemWhenDoneByRef(&St, x);
}

int mySub(int, int);
int myAdd(int, int);
int fPtr(unsigned cond, int x) {
  return (cond ? mySub : myAdd)(x, x);
}

// Test anti-aliasing.

void dependsOnValueOfPtr(int *g, unsigned f) {
  int *p;

  if (f) {
    p = g;
  } else {
    p = malloc(12);
  }

  if (p != g)
    free(p);
  else
    return; // no warning
  return;
}

int CMPRegionHeapToStack() {
  int x = 0;
  int *x1 = malloc(8);
  int *x2 = &x;
  clang_analyzer_eval(x1 == x2); // expected-warning{{FALSE}}
  free(x1);
  return x;
}

int CMPRegionHeapToHeap2() {
  int x = 0;
  int *x1 = malloc(8);
  int *x2 = malloc(8);
  int *x4 = x1;
  int *x5 = x2;
  clang_analyzer_eval(x4 == x5); // expected-warning{{FALSE}}
  free(x1);
  free(x2);
  return x;
}

int CMPRegionHeapToHeap() {
  int x = 0;
  int *x1 = malloc(8);
  int *x4 = x1;
  if (x1 == x4) {
    free(x1);
    return 5/x; // expected-warning{{Division by zero}}
  }
  return x;// expected-warning{{This statement is never executed}}
}

int HeapAssignment() {
  int m = 0;
  int *x = malloc(4);
  int *y = x;
  *x = 5;
  clang_analyzer_eval(*x != *y); // expected-warning{{FALSE}}
  free(x);
  return 0;
}

int *retPtr();
int *retPtrMightAlias(int *x);
int cmpHeapAllocationToUnknown() {
  int zero = 0;
  int *yBefore = retPtr();
  int *m = malloc(8);
  int *yAfter = retPtrMightAlias(m);
  clang_analyzer_eval(yBefore == m); // expected-warning{{FALSE}}
  clang_analyzer_eval(yAfter == m); // expected-warning{{FALSE}}
  free(m);
  return 0;
}

void localArrayTest() {
  char *p = (char*)malloc(12);
  char *ArrayL[12];
  ArrayL[0] = p;
} // expected-warning {{leak}}

void localStructTest() {
  StructWithPtr St;
  StructWithPtr *pSt = &St;
  pSt->memP = malloc(12);
} // expected-warning{{Potential leak of memory pointed to by}}

#ifdef __INTPTR_TYPE__
// Test double assignment through integers.
typedef __INTPTR_TYPE__ intptr_t;
typedef unsigned __INTPTR_TYPE__ uintptr_t;

static intptr_t glob;
void test_double_assign_ints()
{
  void *ptr = malloc (16);  // no-warning
  glob = (intptr_t)(uintptr_t)ptr;
}

void test_double_assign_ints_positive()
{
  void *ptr = malloc(16);
  (void*)(intptr_t)(uintptr_t)ptr; // expected-warning {{unused}}
} // expected-warning {{leak}}
#endif

void testCGContextNoLeak()
{
  void *ptr = malloc(16);
  CGContextRef context = CGBitmapContextCreate(ptr);

  // Because you can get the data back out like this, even much later,
  // CGBitmapContextCreate is one of our "stop-tracking" exceptions.
  free(CGBitmapContextGetData(context));
}

void testCGContextLeak()
{
  void *ptr = malloc(16);
  CGContextRef context = CGBitmapContextCreate(ptr);
  // However, this time we're just leaking the data, because the context
  // object doesn't escape and it hasn't been freed in this function.
}

// Allow xpc context to escape. radar://11635258
// TODO: Would be great if we checked that the finalize_connection_context actually releases it.
static void finalize_connection_context(void *ctx) {
  int *context = ctx;
  free(context);
}
void foo (xpc_connection_t peer) {
  int *ctx = calloc(1, sizeof(int));
  xpc_connection_set_context(peer, ctx);
  xpc_connection_set_finalizer_f(peer, finalize_connection_context);
  xpc_connection_resume(peer);
}

// Make sure we catch errors when we free in a function which does not allocate memory.
void freeButNoMalloc(int *p, int x){
  if (x) {
    free(p);
    //user forgot a return here.
  }
  free(p); // expected-warning {{Attempt to free released memory}}
}

struct HasPtr {
  char *p;
};

char* reallocButNoMalloc(struct HasPtr *a, int c, int size) {
  int *s;
  char *b = realloc(a->p, size);
  char *m = realloc(a->p, size); // expected-warning {{Attempt to free released memory}}
  // We don't expect a use-after-free for a->P here because the warning above
  // is a sink.
  return a->p; // no-warning
}

// We should not warn in this case since the caller will presumably free a->p in all cases.
int reallocButNoMallocPR13674(struct HasPtr *a, int c, int size) {
  int *s;
  char *b = realloc(a->p, size);
  if (b == 0)
    return -1;
  a->p = b;
  return 0;
}

// Test realloc with no visible malloc.
void *test(void *ptr) {
  void *newPtr = realloc(ptr, 4);
  if (newPtr == 0) {
    if (ptr)
      free(ptr); // no-warning
  }
  return newPtr;
}


char *testLeakWithinReturn(char *str) {
  return strdup(strdup(str)); // expected-warning{{leak}}
}

char *testWinLeakWithinReturn(char *str) {
  return _strdup(_strdup(str)); // expected-warning{{leak}}
}

wchar_t *testWinWideLeakWithinReturn(wchar_t *str) {
  return _wcsdup(_wcsdup(str)); // expected-warning{{leak}}
}

void passConstPtr(const char * ptr);

void testPassConstPointer() {
  char * string = malloc(sizeof(char)*10);
  passConstPtr(string);
  return; // expected-warning {{leak}}
}

void testPassConstPointerIndirectly() {
  char *p = malloc(1);
  p++;
  memcmp(p, p, sizeof(&p));
  return; // expected-warning {{leak}}
}

void testPassConstPointerIndirectlyStruct() {
  struct HasPtr hp;
  hp.p = malloc(10);
  memcmp(&hp, &hp, sizeof(hp));
  return; // expected-warning {{Potential leak of memory pointed to by 'hp.p'}}
}

void testPassToSystemHeaderFunctionIndirectlyStruct() {
  SomeStruct ss;
  ss.p = malloc(1);
  fakeSystemHeaderCall(&ss); // invalidates ss, making ss.p unreachable
  // Technically a false negative here -- we know the system function won't free
  // ss.p, but nothing else will either!
} // no-warning

void testPassToSystemHeaderFunctionIndirectlyStructFree() {
  SomeStruct ss;
  ss.p = malloc(1);
  fakeSystemHeaderCall(&ss); // invalidates ss, making ss.p unreachable
  free(ss.p);
} // no-warning

void testPassToSystemHeaderFunctionIndirectlyArray() {
  int *p[1];
  p[0] = malloc(sizeof(int));
  fakeSystemHeaderCallIntPtr(p); // invalidates p, making p[0] unreachable
  // Technically a false negative here -- we know the system function won't free
  // p[0], but nothing else will either!
} // no-warning

void testPassToSystemHeaderFunctionIndirectlyArrayFree() {
  int *p[1];
  p[0] = malloc(sizeof(int));
  fakeSystemHeaderCallIntPtr(p); // invalidates p, making p[0] unreachable
  free(p[0]);
} // no-warning

int *testOffsetAllocate(size_t size) {
  int *memoryBlock = (int *)malloc(size + sizeof(int));
  return &memoryBlock[1]; // no-warning
}

void testOffsetDeallocate(int *memoryBlock) {
  free(&memoryBlock[-1]);  // no-warning
}

void testOffsetOfRegionFreed() {
  __int64_t * array = malloc(sizeof(__int64_t)*2);
  array += 1;
  free(&array[0]); // expected-warning{{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
}

void testOffsetOfRegionFreed2() {
  __int64_t *p = malloc(sizeof(__int64_t)*2);
  p += 1;
  free(p); // expected-warning{{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
}

void testOffsetOfRegionFreed3() {
  char *r = malloc(sizeof(char));
  r = r - 10;
  free(r); // expected-warning {{Argument to free() is offset by -10 bytes from the start of memory allocated by malloc()}}
}

void testOffsetOfRegionFreedAfterFunctionCall() {
  int *p = malloc(sizeof(int)*2);
  p += 1;
  myfoo(p);
  free(p); // expected-warning{{Argument to free() is offset by 4 bytes from the start of memory allocated by malloc()}}
}

void testFixManipulatedPointerBeforeFree() {
  int * array = malloc(sizeof(int)*2);
  array += 1;
  free(&array[-1]); // no-warning
}

void testFixManipulatedPointerBeforeFree2() {
  char *r = malloc(sizeof(char));
  r = r + 10;
  free(r-10); // no-warning
}

void freeOffsetPointerPassedToFunction() {
  __int64_t *p = malloc(sizeof(__int64_t)*2);
  p[1] = 0;
  p += 1;
  myfooint(*p); // not passing the pointer, only a value pointed by pointer
  free(p); // expected-warning {{Argument to free() is offset by 8 bytes from the start of memory allocated by malloc()}}
}

int arbitraryInt();
void freeUnknownOffsetPointer() {
  char *r = malloc(sizeof(char));
  r = r + arbitraryInt(); // unable to reason about what the offset might be
  free(r); // no-warning
}

void testFreeNonMallocPointerWithNoOffset() {
  char c;
  char *r = &c;
  r = r + 10;
  free(r-10); // expected-warning {{Argument to free() is the address of the local variable 'c', which is not memory allocated by malloc()}}
}

void testFreeNonMallocPointerWithOffset() {
  char c;
  char *r = &c;
  free(r+1); // expected-warning {{Argument to free() is the address of the local variable 'c', which is not memory allocated by malloc()}}
}

void testOffsetZeroDoubleFree() {
  int *array = malloc(sizeof(int)*2);
  int *p = &array[0];
  free(p);
  free(&array[0]); // expected-warning{{Attempt to free released memory}}
}

void testOffsetPassedToStrlen() {
  char * string = malloc(sizeof(char)*10);
  string += 1;
  int length = strlen(string); // expected-warning {{Potential leak of memory pointed to by 'string'}}
}

void testOffsetPassedToStrlenThenFree() {
  char * string = malloc(sizeof(char)*10);
  string += 1;
  int length = strlen(string);
  free(string); // expected-warning {{Argument to free() is offset by 1 byte from the start of memory allocated by malloc()}}
}

void testOffsetPassedAsConst() {
  char * string = malloc(sizeof(char)*10);
  string += 1;
  passConstPtr(string);
  free(string); // expected-warning {{Argument to free() is offset by 1 byte from the start of memory allocated by malloc()}}
}

char **_vectorSegments;
int _nVectorSegments;

void poolFreeC(void* s) {
  free(s); // no-warning
}
void freeMemory() {
  while (_nVectorSegments) {
    poolFreeC(_vectorSegments[_nVectorSegments++]);
  }
}

// PR16730
void testReallocEscaped(void **memory) {
  *memory = malloc(47);
  char *new_memory = realloc(*memory, 47);
  if (new_memory != 0) {
    *memory = new_memory;
  }
}

// PR16558
void *smallocNoWarn(size_t size) {
  if (size == 0) {
    return malloc(1); // this branch is never called
  }
  else {
    return malloc(size);
  }
}

char *dupstrNoWarn(const char *s) {
  const int len = strlen(s);
  char *p = (char*) smallocNoWarn(len + 1);
  strcpy(p, s); // no-warning
  return p;
}

void *smallocWarn(size_t size) {
  if (size == 2) {
    return malloc(1);
  }
  else {
    return malloc(size);
  }
}

int *radar15580979() {
  int *data = (int *)malloc(32);
  int *p = data ?: (int*)malloc(32); // no warning
  return p;
}

// Some data structures may hold onto the pointer and free it later.
void testEscapeThroughSystemCallTakingVoidPointer1(void *queue) {
  int *data = (int *)malloc(32);
  fake_insque(queue, data); // no warning
}

void testEscapeThroughSystemCallTakingVoidPointer2(fake_rb_tree_t *rbt) {
  int *data = (int *)malloc(32);
  fake_rb_tree_init(rbt, data);
} //expected-warning{{Potential leak}}

void testEscapeThroughSystemCallTakingVoidPointer3(fake_rb_tree_t *rbt) {
  int *data = (int *)malloc(32);
  fake_rb_tree_init(rbt, data);
  fake_rb_tree_insert_node(rbt, data); // no warning
}

struct IntAndPtr {
  int x;
  int *p;
};

void constEscape(const void *ptr);

void testConstEscapeThroughAnotherField() {
  struct IntAndPtr s;
  s.p = malloc(sizeof(int));
  constEscape(&(s.x)); // could free s->p!
} // no-warning

// PR15623
int testNoCheckerDataPropogationFromLogicalOpOperandToOpResult(void) {
   char *param = malloc(10);
   char *value = malloc(10);
   int ok = (param && value);
   free(param);
   free(value);
   // Previously we ended up with 'Use of memory after it is freed' on return.
   return ok; // no warning
}

void (*fnptr)(int);
void freeIndirectFunctionPtr() {
  void *p = (void *)fnptr;
  free(p); // expected-warning {{Argument to free() is a function pointer}}
}

void freeFunctionPtr() {
  free((void *)fnptr); // expected-warning {{Argument to free() is a function pointer}}
}

void allocateSomeMemory(void *offendingParameter, void **ptr) {
  *ptr = malloc(1);
}

void testNoCrashOnOffendingParameter() {
  // "extern" is necessary to avoid unrelated warnings
  // on passing uninitialized value.
  extern void *offendingParameter;
  void* ptr;
  allocateSomeMemory(offendingParameter, &ptr);
} // expected-warning {{Potential leak of memory pointed to by 'ptr'}}


// Test a false positive caused by a bug in liveness analysis.
struct A {
  int *buf;
};
struct B {
  struct A *a;
};
void livenessBugRealloc(struct A *a) {
  a->buf = realloc(a->buf, sizeof(int)); // no-warning
}
void testLivenessBug(struct B *in_b) {
  struct B *b = in_b;
  livenessBugRealloc(b->a);
 ((void) 0); // An attempt to trick liveness analysis.
  livenessBugRealloc(b->a);
}

struct ListInfo {
  struct ListInfo *next;
};

struct ConcreteListItem {
  struct ListInfo li;
  int i;
};

void list_add(struct ListInfo *list, struct ListInfo *item);

void testCStyleListItems(struct ListInfo *list) {
  struct ConcreteListItem *x = malloc(sizeof(struct ConcreteListItem));
  list_add(list, &x->li); // will free 'x'.
}

// MEM34-C. Only free memory allocated dynamically
// Second non-compliant example.
// https://wiki.sei.cmu.edu/confluence/display/c/MEM34-C.+Only+free+memory+allocated+dynamically
enum { BUFSIZE = 256 };

void MEM34_C(void) {
  char buf[BUFSIZE];
  char *p = (char *)realloc(buf, 2 * BUFSIZE);
  // expected-warning@-1{{Argument to realloc() is the address of the local \
variable 'buf', which is not memory allocated by malloc() [unix.Malloc]}}
  if (p == NULL) {
    /* Handle error */
  }
}

(*crash_a)(); // expected-warning{{type specifier missing}}
// A CallEvent without a corresponding FunctionDecl.
crash_b() { crash_a(); } // no-crash
// expected-warning@-1{{type specifier missing}} expected-warning@-1{{non-void}}

long *global_a;
void realloc_crash() {
  long *c = global_a;
  c--;
  realloc(c, 8); // no-crash
} // expected-warning{{Potential memory leak [unix.Malloc]}}

// ----------------------------------------------------------------------------
// False negatives.

void testMallocWithParam(int **p) {
  *p = (int*) malloc(sizeof(int));
  *p = 0; // FIXME: should warn here
}

void testMallocWithParam_2(int **p) {
  *p = (int*) malloc(sizeof(int)); // no-warning
}

void testPassToSystemHeaderFunctionIndirectly() {
  int *p = malloc(4);
  p++;
  fakeSystemHeaderCallInt(p);
  // FIXME: This is a leak: if we think a system function won't free p, it
  // won't free (p-1) either.
}

void testMallocIntoMalloc() {
  StructWithPtr *s = malloc(sizeof(StructWithPtr));
  s->memP = malloc(sizeof(int));
  free(s);
} // FIXME: should warn here