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 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557
|
# some common utilities for lcov-related scripts
use strict;
use warnings;
require Exporter;
package lcovutil;
use File::Path qw(rmtree);
use File::Basename qw(basename dirname);
use File::Temp qw /tempdir/;
use File::Spec;
use Scalar::Util qw/looks_like_number/;
use Cwd qw/abs_path getcwd/;
use Storable qw(dclone);
use Capture::Tiny;
use Module::Load::Conditional qw(check_install);
use Digest::MD5 qw(md5_base64);
use FindBin;
use Getopt::Long;
use DateTime;
use Config;
use POSIX;
use Fcntl qw(:flock SEEK_END);
our @ISA = qw(Exporter);
our @EXPORT_OK = qw($tool_name $tool_dir $lcov_version $lcov_url $VERSION
@temp_dirs set_tool_name
info warn_once set_info_callback init_verbose_flag $verbose
debug $debug
append_tempdir create_temp_dir temp_cleanup folder_is_empty $tmp_dir $preserve_intermediates
summarize_messages define_errors
parse_ignore_errors ignorable_error ignorable_warning
is_ignored message_count explain_once
die_handler warn_handler abort_handler
$maxParallelism $maxMemory init_parallel_params current_process_size
$memoryPercentage $max_fork_fails $fork_fail_timeout
save_profile merge_child_profile save_cmd_line
@opt_rc apply_rc_params $split_char parseOptions
strip_directories
@file_subst_patterns subst_file_name
@comments
$br_coverage $func_coverage $mcdc_coverage
@cpp_demangle do_mangle_check $demangle_cpp_cmd
$cpp_demangle_tool $cpp_demangle_params
get_overall_line rate
$FILTER_BRANCH_NO_COND $FILTER_FUNCTION_ALIAS
$FILTER_EXCLUDE_REGION $FILTER_EXCLUDE_BRANCH $FILTER_LINE
$FILTER_LINE_CLOSE_BRACE $FILTER_BLANK_LINE $FILTER_LINE_RANGE
$FILTER_TRIVIAL_FUNCTION $FILTER_DIRECTIVE
$FILTER_MISSING_FILE $FILTER_INITIALIZER_LIST
$FILTER_EXCEPTION_BRANCH $FILTER_ORPHAN_BRANCH
@cov_filter
$EXCL_START $EXCL_STOP $EXCL_BR_START $EXCL_BR_STOP
$EXCL_EXCEPTION_BR_START $EXCL_EXCEPTION_BR_STOP
$EXCL_LINE $EXCL_BR_LINE $EXCL_EXCEPTION_LINE
@exclude_file_patterns @include_file_patterns %excluded_files
@omit_line_patterns @exclude_function_patterns $case_insensitive
munge_file_patterns warn_file_patterns transform_pattern
parse_cov_filters summarize_cov_filters
disable_cov_filters reenable_cov_filters is_filter_enabled
filterStringsAndComments simplifyCode balancedParens
set_extensions
$source_filter_lookahead $source_filter_bitwise_are_conditional
$exclude_exception_branch
$derive_function_end_line $derive_function_end_line_all_files
$trivial_function_threshold
$filter_blank_aggressive
$lcov_filter_parallel $lcov_filter_chunk_size
%lcovErrors $ERROR_GCOV $ERROR_SOURCE $ERROR_GRAPH $ERROR_MISMATCH
$ERROR_BRANCH $ERROR_EMPTY $ERROR_FORMAT $ERROR_VERSION $ERROR_UNUSED
$ERROR_PACKAGE $ERROR_CORRUPT $ERROR_NEGATIVE $ERROR_COUNT $ERROR_PATH
$ERROR_UNSUPPORTED $ERROR_DEPRECATED $ERROR_INCONSISTENT_DATA
$ERROR_CALLBACK $ERROR_RANGE $ERROR_UTILITY $ERROR_USAGE $ERROR_INTERNAL
$ERROR_PARALLEL $ERROR_PARENT $ERROR_CHILD $ERROR_FORK
$ERROR_EXCESSIVE_COUNT $ERROR_MISSING
report_parallel_error report_exit_status check_parent_process
report_unknown_child
$ERROR_UNMAPPED_LINE $ERROR_UNKNOWN_CATEGORY $ERROR_ANNOTATE_SCRIPT
$stop_on_error
@extractVersionScript $verify_checksum $compute_file_version
configure_callback cleanup_callbacks
is_external @internal_dirs $opt_no_external @build_directory
$default_precision check_precision
system_no_output $devnull $dirseparator
%tlaColor %tlaTextColor use_vanilla_color %pngChar %pngMap
%dark_palette %normal_palette parse_w3cdtf
);
our @ignore;
our @message_count;
our @expected_message_count;
our %message_types;
our $message_log;
our $message_filename;
our $suppressAfter = 100; # stop warning after this number of messages
our %ERROR_ID;
our %ERROR_NAME;
our $tool_dir = "$FindBin::RealBin";
our $tool_name = basename($0); # import from lcovutil module
our $VERSION = `"$tool_dir"/get_version.sh --full`;
chomp($VERSION);
our $lcov_version = 'LCOV version ' . $VERSION;
our $lcov_url = "https://github.com//linux-test-project/lcov";
our @temp_dirs;
our $tmp_dir = '/tmp'; # where to put temporary/intermediate files
our $preserve_intermediates; # this is useful only for debugging
our $sort_inputs; # sort input file lists - to reduce unpredictability
our $devnull = File::Spec->devnull(); # portable way to do it
our $dirseparator = ($^O =~ /Win/) ? '\\' : '/';
our $interp = ($^O =~ /Win/) ? $^X : undef;
our $debug = 0; # if set, emit debug messages
our $verbose = 0; # default level - higher to enable additional logging
our $split_char = ','; # by default: split on comma
# share common definition for all error types.
# Note that geninfo cannot produce some types produced by genhtml, and vice
# versa. Easier to maintain a common definition.
our $ERROR_GCOV;
our $ERROR_SOURCE;
our $ERROR_GRAPH;
our $ERROR_FORMAT; # bad record in .info file
our $ERROR_EMPTY; # no records found in info file
our $ERROR_VERSION;
our $ERROR_UNUSED; # exclude/include/substitute pattern not used
our $ERROR_MISMATCH;
our $ERROR_BRANCH; # branch numbering is not correct
our $ERROR_PACKAGE; # missing utility package
our $ERROR_CORRUPT; # corrupt file
our $ERROR_NEGATIVE; # unexpected negative count in coverage data
our $ERROR_COUNT; # too many messages of type
our $ERROR_UNSUPPORTED; # some unsupported feature or usage
our $ERROR_PARALLEL; # error in fork/join
our $ERROR_DEPRECATED; # deprecated feature
our $ERROR_CALLBACK; # callback produced an error
our $ERROR_INCONSISTENT_DATA; # something wrong with .info
our $ERROR_RANGE; # line number out of range
our $ERROR_UTILITY; # some tool failed - e.g., 'find'
our $ERROR_USAGE; # misusing some feature
our $ERROR_PATH; # path issues
our $ERROR_INTERNAL; # tool issue
our $ERROR_PARENT; # parent went away so child should die
our $ERROR_CHILD; # nonzero child exit status
our $ERROR_FORK; # fork failed
our $ERROR_EXCESSIVE_COUNT; # suspiciously large hit count
our $ERROR_MISSING; # file missing/not found
# genhtml errors
our $ERROR_UNMAPPED_LINE; # inconsistent coverage data
our $ERROR_UNKNOWN_CATEGORY; # we did something wrong with inconsistent data
our $ERROR_ANNOTATE_SCRIPT; # annotation failed somehow
my @lcovErrs = (["annotate", \$ERROR_ANNOTATE_SCRIPT],
["branch", \$ERROR_BRANCH],
["callback", \$ERROR_CALLBACK],
["category", \$ERROR_UNKNOWN_CATEGORY],
["child", \$ERROR_CHILD],
["corrupt", \$ERROR_CORRUPT],
["count", \$ERROR_COUNT],
["deprecated", \$ERROR_DEPRECATED],
["empty", \$ERROR_EMPTY],
['excessive', \$ERROR_EXCESSIVE_COUNT],
["format", \$ERROR_FORMAT],
["fork", \$ERROR_FORK],
["gcov", \$ERROR_GCOV],
["graph", \$ERROR_GRAPH],
["inconsistent", \$ERROR_INCONSISTENT_DATA],
["internal", \$ERROR_INTERNAL],
["mismatch", \$ERROR_MISMATCH],
["missing", \$ERROR_MISSING],
["negative", \$ERROR_NEGATIVE],
["package", \$ERROR_PACKAGE],
["parallel", \$ERROR_PARALLEL],
["parent", \$ERROR_PARENT],
["path", \$ERROR_PATH],
["range", \$ERROR_RANGE],
["source", \$ERROR_SOURCE],
["unmapped", \$ERROR_UNMAPPED_LINE],
["unsupported", \$ERROR_UNSUPPORTED],
["unused", \$ERROR_UNUSED],
['usage', \$ERROR_USAGE],
['utility', \$ERROR_UTILITY],
["version", \$ERROR_VERSION],);
our %lcovErrors;
our $stop_on_error; # attempt to keep going
our $treat_warning_as_error = 0;
our $warn_once_per_file = 1;
our $excessive_count_threshold; # default not set: don't check
our $br_coverage = 0; # If set, generate branch coverage statistics
our $mcdc_coverage = 0; # MC/DC
our $func_coverage = 1; # If set, generate function coverage statistics
# for external file filtering
our @internal_dirs;
our $opt_no_external;
# Where code was built/where .gcno files can be found
# (if .gcno files are in a different place than the .gcda files)
# also used by genhtml to match diff file entries to .info file
our @build_directory;
our @configured_callbacks;
# optional callback to keep track of whatever user decides is important
our @contextCallback;
our $contextCallback;
# filename substitutions
our @file_subst_patterns;
# resolve callback
our @resolveCallback;
our $resolveCallback;
our %resolveCache;
# C++ demangling
our @cpp_demangle; # the options passed in
our $demangle_cpp_cmd; # the computed command string
# deprecated: demangler for C++ function names is c++filt
our $cpp_demangle_tool;
# Deprecated: prefer -Xlinker approach with @cpp_dmangle_tool
our $cpp_demangle_params;
# version extract may be expensive - so only do it once
our %versionCache;
our @extractVersionScript; # script/callback to find version ID of file
our $versionCallback;
our $verify_checksum; # compute and/or check MD5 sum of source code lines
our $check_file_existence_before_callback = 1;
our $check_data_consistency = 1;
# Specify coverage rate default precision
our $default_precision = 1;
# undef indicates not set by command line or RC option - so default to
# sequential processing
our $maxParallelism;
our $max_fork_fails = 5; # consecutive failures
our $fork_fail_timeout = 10; # how long to wait, in seconds
our $maxMemory; # zero indicates no memory limit to parallelism
our $memoryPercentage;
our $in_child_process = 0;
our $max_tasks_per_core = 20; # maybe default to 0?
our $lcov_filter_parallel = 1; # enable by default
our $lcov_filter_chunk_size;
our $fail_under_lines;
our $fail_under_branches;
our $fix_inconsistency = 1;
sub default_info_impl(@);
our $info_callback = \&default_info_impl;
# filter classes that may be requested
# don't report BRDA data for line which seem to have no conditionals
# These may be from C++ exception handling (for example) - and are not
# interesting to users.
our $FILTER_BRANCH_NO_COND;
# don't report line coverage for closing brace of a function
# or basic block, if the immediate predecessor line has the same count.
our $FILTER_LINE_CLOSE_BRACE;
# merge functions which appear on same file/line - guess that that
# they are all the same
our $FILTER_FUNCTION_ALIAS;
# region between LCOV EXCL_START/STOP
our $FILTER_EXCLUDE_REGION;
# region between LCOV EXCL_BR_START/STOP
our $FILTER_EXCLUDE_BRANCH;
# empty line
our $FILTER_BLANK_LINE;
# out of range line - beyond end of file
our $FILTER_LINE_RANGE;
# backward compatibility: empty line, close brace
our $FILTER_LINE;
# filter initializer list-like stuff
our $FILTER_INITIALIZER_LIST;
# remove functions which have only a single line
our $FILTER_TRIVIAL_FUNCTION;
# remove compiler directive lines which llvm-cov seems to generate
our $FILTER_DIRECTIVE;
# remove missing source file
our $FILTER_MISSING_FILE;
# remove branches marked as related to exceptions
our $FILTER_EXCEPTION_BRANCH;
# remove lone branch in block - it can't be an actual conditional
our $FILTER_ORPHAN_BRANCH;
# MC/DC with single expression is identical to branch
our $FILTER_MCDC_SINGLE;
our $FILTER_OMIT_PATTERNS; # special/somewhat faked filter
our %COVERAGE_FILTERS = ("branch" => \$FILTER_BRANCH_NO_COND,
'brace' => \$FILTER_LINE_CLOSE_BRACE,
'blank' => \$FILTER_BLANK_LINE,
'directive' => \$FILTER_DIRECTIVE,
'range' => \$FILTER_LINE_RANGE,
'line' => \$FILTER_LINE,
'initializer' => \$FILTER_INITIALIZER_LIST,
'function' => \$FILTER_FUNCTION_ALIAS,
'missing' => \$FILTER_MISSING_FILE,
'region' => \$FILTER_EXCLUDE_REGION,
'branch_region' => \$FILTER_EXCLUDE_BRANCH,
'exception' => \$FILTER_EXCEPTION_BRANCH,
'orphan' => \$FILTER_ORPHAN_BRANCH,
'mcdc' => \$FILTER_MCDC_SINGLE,
"trivial" => \$FILTER_TRIVIAL_FUNCTION,);
our @cov_filter; # 'undef' if filter is not enabled,
# [line_count, coverpoint_count] histogram if
# filter is enabled: number of applications
# of this filter
our $EXCL_START = "LCOV_EXCL_START";
our $EXCL_STOP = "LCOV_EXCL_STOP";
# Marker to exclude branch coverage but keep function and line coverage
our $EXCL_BR_START = "LCOV_EXCL_BR_START";
our $EXCL_BR_STOP = "LCOV_EXCL_BR_STOP";
# marker to exclude exception branches but keep other branches
our $EXCL_EXCEPTION_BR_START = 'LCOV_EXCL_EXCEPTION_BR_START';
our $EXCL_EXCEPTION_BR_STOP = 'LCOV_EXCL_EXCEPTION_BR_STOP';
# exclude on this line
our $EXCL_LINE = 'LCOV_EXCL_LINE';
our $EXCL_BR_LINE = 'LCOV_EXCL_BR_LINE';
our $EXCL_EXCEPTION_LINE = 'LCOV_EXCL_EXCEPTION_BR_LINE';
our @exclude_file_patterns;
our @include_file_patterns;
our %excluded_files;
our $case_insensitive = 0;
our $exclude_exception_branch = 0;
our $derive_function_end_line = 1;
our $derive_function_end_line_all_files = 0; # by default, C only
our $trivial_function_threshold = 5;
# list of regexps applied to line text - if exclude if matched
our @omit_line_patterns;
our @exclude_function_patterns;
# need a pattern copy that we don't disable for function message suppressions
our @suppress_function_patterns;
our %languageExtensions = ('c' => 'c|h|i|C|H|I|icc|cpp|cc|cxx|hh|hpp|hxx',
'rtl' => 'v|vh|sv|vhdl?',
'perl' => 'pl|pm',
'python' => 'py',
'java' => 'java');
our $info_file_pattern = '*.info';
# don't look more than 10 lines ahead when filtering (default)
our $source_filter_lookahead = 10;
# by default, don't treat expressions containing bitwise operators '|', '&', '~'
# as conditional in bogus branch filtering
our $source_filter_bitwise_are_conditional = 0;
# filter out blank lines whether they are hit or not
our $filter_blank_aggressive = 0;
our %dark_palette = ('COLOR_00' => "e4e4e4",
'COLOR_01' => "58a6ff",
'COLOR_02' => "8b949e",
'COLOR_03' => "3b4c71",
'COLOR_04' => "006600",
'COLOR_05' => "4b6648",
'COLOR_06' => "495366",
'COLOR_07' => "143e4f",
'COLOR_08' => "1c1e23",
'COLOR_09' => "202020",
'COLOR_10' => "801b18",
'COLOR_11' => "66001a",
'COLOR_12' => "772d16",
'COLOR_13' => "796a25",
'COLOR_14' => "000000",
'COLOR_15' => "58a6ff",
'COLOR_16' => "eeeeee",
'COLOR_17' => "E5DBDB",
'COLOR_18' => "82E0AA",
'COLOR_19' => 'F9E79F',
'COLOR_20' => 'EC7063',);
our %normal_palette = ('COLOR_00' => "000000",
'COLOR_01' => "00cb40",
'COLOR_02' => "284fa8",
'COLOR_03' => "6688d4",
'COLOR_04' => "a7fc9d",
'COLOR_05' => "b5f7af",
'COLOR_06' => "b8d0ff",
'COLOR_07' => "cad7fe",
'COLOR_08' => "dae7fe",
'COLOR_09' => "efe383",
'COLOR_10' => "ff0000",
'COLOR_11' => "ff0040",
'COLOR_12' => "ff6230",
'COLOR_13' => "ffea20",
'COLOR_14' => "ffffff",
'COLOR_15' => "284fa8",
'COLOR_16' => "ffffff",
'COLOR_17' => "E5DBDB", # very light pale grey/blue
'COLOR_18' => "82E0AA", # light green
'COLOR_19' => 'F9E79F', # light yellow
'COLOR_20' => 'EC7063', # lighter red
);
our %tlaColor = ("UBC" => "#FDE007",
"GBC" => "#448844",
"LBC" => "#CC6666",
"CBC" => "#CAD7FE",
"GNC" => "#B5F7AF",
"UNC" => "#FF6230",
"ECB" => "#CC66FF",
"EUB" => "#DDDDDD",
"GIC" => "#30CC37",
"UIC" => "#EEAA30",
# we don't actually use a color for deleted code.
# ... it is deleted. Does not appear
"DUB" => "#FFFFFF",
"DCB" => "#FFFFFF",);
# colors for the text in the PNG image of the corresponding TLA line
our %tlaTextColor = ("UBC" => "#aaa005",
"GBC" => "#336633",
"LBC" => "#994444",
"CBC" => "#98a0aa",
"GNC" => "#90a380",
"UNC" => "#aa4020",
"ECB" => "#663388",
"EUB" => "#777777",
"GIC" => "#18661c",
"UIC" => "#aa7718",
# we don't actually use a color for deleted code.
# ... it is deleted. Does not appear
"DUB" => "#FFFFFF",
"DCB" => "#FFFFFF",);
our %pngChar = ('CBC' => '=',
'LBC' => '=',
'GBC' => '-',
'UBC' => '-',
'ECB' => '<',
'EUB' => '<',
'GIC' => '>',
'UIC' => '>',
'GNC' => '+',
'UNC' => '+',);
our %pngMap = ('=' => ['CBC', 'LBC']
, # 0th element 'covered', 1st element 'not covered
'-' => ['GBC', 'UBC'],
'<' => ['ECB', 'EUB'],
'>' => ['GIC', 'UIC'],
'+' => ['GNC', 'UNC'],);
our @opt_rc; # list of command line RC overrides
our %profileData;
our $profile; # the 'enable' flag/name of output file
# need to defer any errors until after the options have been
# processed as user might have suppressed the error we were
# trying to emit
my @deferred_rc_errors; # ([err|warn, key, string])
sub set_tool_name($)
{
$tool_name = shift;
}
#
# system_no_output(mode, parameters)
#
# Call an external program using PARAMETERS while suppressing depending on
# the value of MODE:
#
# MODE & 1: suppress STDOUT (return empty string)
# MODE & 2: suppress STDERR (return empty string)
# MODE & 4: redirect to string
#
# Return (stdout, stderr, rc):
# stdout: stdout string or ''
# stderr: stderr string or ''
# 0 on success, non-zero otherwise
#
sub system_no_output($@)
{
my $mode = shift;
# all current uses redirect both stdout and stderr
my @args = @_;
my ($stdout, $stderr, $code) = Capture::Tiny::capture {
system(@args);
};
if (0 == ($mode & 4)) {
$stdout = '' if $mode & 0x1;
$stderr = '' if $mode & 0x2;
} else {
print(STDOUT $stdout) unless $mode & 0x1;
print(STDERR $stderr) unless $mode & 0x2;
}
return ($stdout, $stderr, $code);
}
#
# info(printf_parameter)
#
# Use printf to write PRINTF_PARAMETER to stdout only when not --quiet
#
sub default_info_impl(@)
{
# Print info string
printf(@_);
}
sub set_info_callback($)
{
$info_callback = shift;
}
sub init_verbose_flag($)
{
my $quiet = shift;
$lcovutil::verbose -= $quiet;
}
sub info(@)
{
my $level = 0;
if ($_[0] =~ /^-?[0-9]+$/) {
$level = shift;
}
&{$info_callback}(@_)
if ($level <= $lcovutil::verbose);
}
sub debug
{
my $level = 0;
if ($_[0] =~ /^[0-9]+$/) {
$level = shift;
}
my $msg = shift;
print(STDERR "DEBUG: $msg")
if ($level < $lcovutil::debug);
}
sub temp_cleanup()
{
if (@temp_dirs) {
# Ensure temp directory is not in use by current process
my $cwd = Cwd::getcwd();
chdir(File::Spec->rootdir());
info("Removing temporary directories.\n");
foreach (@temp_dirs) {
rmtree($_);
}
@temp_dirs = ();
chdir($cwd);
}
}
#
# create_temp_dir()
#
# Create a temporary directory and return its path.
#
# Die on error.
#
sub create_temp_dir()
{
my $dir = tempdir(DIR => $lcovutil::tmp_dir,
CLEANUP => !defined($lcovutil::preserve_intermediates));
if (!defined($dir)) {
die("cannot create temporary directory\n");
}
append_tempdir($dir);
return $dir;
}
sub append_tempdir($)
{
push(@temp_dirs, @_);
}
sub _msg_handler
{
my ($msg, $error) = @_;
if (!($debug || $verbose > 0 || exists($ENV{LCOV_SHOW_LOCATION}))) {
$msg =~ s/ at \S+ line \d+\.$//;
}
# Enforce consistent "WARNING/ERROR:" message prefix
$msg =~ s/^(error|warning):\s+//i;
my $type = $error ? 'ERROR' : 'WARNING';
my $txt = "$tool_name: $type: $msg";
if ($message_log && 'GLOB' eq ref($message_log)) {
flock($message_log, LOCK_EX);
# don't bother to seek...assume modern O_APPEND semantics
#seek($message_log, 0, SEEK_END);
print $message_log $txt;
flock($message_log, LOCK_UN);
}
return $txt;
}
sub warn_handler($$)
{
print(STDERR _msg_handler(@_));
}
sub die_handler($)
{
die(_msg_handler(@_, 1));
}
sub abort_handler($)
{
temp_cleanup();
exit(1);
}
sub count_cores()
{
# how many cores?
$maxParallelism = 1;
#linux solution...
if (open my $handle, '/proc/cpuinfo') {
$maxParallelism = scalar(map /^processor/, <$handle>);
close($handle) or die("unable to close /proc/cpuinfo: $!\n");
}
}
our $use_MemoryProcess;
sub read_proc_vmsize
{
if (open(PROC, "<", '/proc/self/stat')) {
my $str = do { local $/; <PROC> }; # slurp whole thing
close(PROC) or die("unable to close /proc/self/stat: $!\n");
my @data = split(' ', $str);
return $data[23 - 1]; # man proc - vmsize is at index 22
} else {
lcovutil::ignorable_error($lcovutil::ERROR_PACKAGE,
"unable to open: $!");
return 0;
}
}
sub read_system_memory
{
# NOTE: not sure how to do this on windows...
my $total = 0;
eval {
my $f = InOutFile->in('/proc/meminfo');
my $h = $f->hdl();
while (<$h>) {
if (/MemTotal:\s+(\d+) kB/) {
$total = $1 * 1024; # read #kB
last;
}
}
};
if ($@) {
lcovutil::ignorable_error($lcovutil::ERROR_PACKAGE, $@);
}
return $total;
}
sub init_parallel_params()
{
if (!defined($lcovutil::maxParallelism)) {
$lcovutil::maxParallelism = 1;
} elsif (0 == $lcovutil::maxParallelism) {
lcovutil::count_cores();
info("Found $maxParallelism cores.\n");
}
if (1 != $lcovutil::maxParallelism &&
(defined($lcovutil::maxMemory) ||
defined($lcovutil::memoryPercentage))
) {
# need Memory::Process to enable the maxMemory feature
my $cwd = Cwd::getcwd();
#debug("init: CWD is $cwd\n");
eval {
require Memory::Process;
Memory::Process->import();
$use_MemoryProcess = 1;
};
# will have done 'cd /' in the die_handler - if Mem::Process not found
#debug("init: chdir back to $cwd\n");
chdir($cwd);
if ($@) {
push(
@deferred_rc_errors,
[ 1,
$lcovutil::ERROR_PACKAGE,
"package Memory::Process is required to control memory consumption during parallel operations: $@"
]);
$use_MemoryProcess = 0;
}
}
if (defined($lcovutil::maxMemory)) {
$lcovutil::maxMemory *= 1 << 20;
} elsif (defined($lcovutil::memoryPercentage)) {
if ($lcovutil::memoryPercentage !~ /^\d+\.?\d*$/ ||
$lcovutil::memoryPercentage <= 0) {
push(
@deferred_rc_errors,
[ 1,
$lcovutil::ERROR_USAGE,
"memory_percentage '$lcovutil::memoryPercentage' is not a valid value"
]);
$lcovutil::memoryPercentage = 100;
}
$lcovutil::maxMemory =
read_system_memory() * ($lcovutil::memoryPercentage / 100.0);
if ($maxMemory) {
my $v = $maxMemory / ((1 << 30) * 1.0);
my $unit = 'Gb';
if ($v < 1.0) {
$unit = 'Mb';
$v = $maxMemory / ((1 << 20) * 1.0);
}
info(sprintf("Setting memory throttle limit to %0.1f %s.\n",
$v, $unit
));
}
} else {
$lcovutil::maxMemory = 0;
}
if (1 != $lcovutil::maxParallelism && # no memory limits if not parallel
0 != $lcovutil::maxMemory
) {
if (!$use_MemoryProcess) {
lcovutil::info(
"Attempting to retrieve memory size from /proc instead\n");
# check if we can get this from /proc (i.e., are we on linux?)
if (0 == read_proc_vmsize()) {
$lcovutil::maxMemory = 0; # turn off that feature
lcovutil::info(
"Continuing execution without Memory::Process or /proc. Note that your maximum memory constraint will be ignored\n"
);
}
}
}
InOutFile::checkGzip() # we know we are going to use gzip for intermediates
if 1 != $lcovutil::maxParallelism;
}
our $memoryObj;
sub current_process_size
{
if ($use_MemoryProcess) {
$memoryObj = Memory::Process->new
unless defined($memoryObj);
$memoryObj->record('size');
my $arr = $memoryObj->state;
$memoryObj->reset();
# current vmsize in kB is element 2 of array
return $arr->[0]->[2] * 1024; # return total in bytes
} else {
# assume we are on linux - and get it from /proc
return read_proc_vmsize();
}
}
sub merge_child_profile($)
{
my $profile = shift;
while (my ($key, $d) = each(%$profile)) {
if ('HASH' eq ref($d)) {
while (my ($f, $t) = each(%$d)) {
if ('HASH' eq ref($t)) {
while (my ($x, $y) = each(%$t)) {
lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
"unexpected duplicate key $x=$y at $key->$f")
if exists($lcovutil::profileData{$key}{$f}{$x});
$lcovutil::profileData{$key}{$f}{$x} = $y;
}
} else {
# 'total' key appears in genhtml report
# the others in geninfo.
if (exists($lcovutil::profileData{$key}{$f})
&&
grep(/^$key$/,
( 'version', 'parse',
'append', 'total',
'resolve', 'derive_end',
'check_consistency'))
) {
$lcovutil::profileData{$key}{$f} += $t;
} else {
lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
"unexpected duplicate key $f=$t in $key:$lcovutil::profileData{$key}{$f}"
) if exists($lcovutil::profileData{$key}{$f});
$lcovutil::profileData{$key}{$f} = $t;
}
}
}
} else {
lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
"unexpected duplicate key $key=$d in profileData")
if exists($lcovutil::profileData{$key});
$lcovutil::profileData{$key} = $d;
}
}
}
sub save_cmd_line($$)
{
my ($argv, $bin) = @_;
my $cmd = $lcovutil::tool_name;
$lcovutil::profileData{config}{bin} = "$FindBin::RealBin";
foreach my $arg (@$argv) {
$cmd .= ' ';
if ($arg =~ /\s/) {
$cmd .= "'$arg'";
} else {
$cmd .= $arg;
}
}
$lcovutil::profileData{config}{cmdLine} = $cmd;
$lcovutil::profileData{config}{buildDir} = Cwd::getcwd();
}
sub save_profile($@)
{
my ($dest, $html) = @_;
if (defined($lcovutil::profile)) {
$lcovutil::profileData{config}{maxParallel} = $maxParallelism;
$lcovutil::profileData{config}{tool} = $lcovutil::tool_name;
$lcovutil::profileData{config}{version} = $lcovutil::lcov_version;
$lcovutil::profileData{config}{tool_dir} = $lcovutil::tool_dir;
$lcovutil::profileData{config}{url} = $lcovutil::lcov_url;
foreach my $t ('date', 'uname -a', 'hostname') {
my $v = `$t`;
chomp($v);
$lcovutil::profileData{config}{(split(' ', $t))[0]} = $v;
}
my $save = $maxParallelism;
count_cores();
$lcovutil::profileData{config}{cores} = $maxParallelism;
$maxParallelism = $save;
my $json = JsonSupport::encode(\%lcovutil::profileData);
if ('' ne $lcovutil::profile) {
$dest = $lcovutil::profile;
} else {
$dest .= ".json";
}
if (open(JSON, ">", "$dest")) {
print(JSON $json);
close(JSON) or die("unable to close $dest: $!\n");
} else {
warn("unable to open profile output $dest: '$!'\n");
}
# only generate the extra data if profile enabled
if ($html) {
my $leader =
'<object data="https://www.w3.org/TR/PNG/iso_8859-1.txt" width="300" height="200">'
. "\n";
my $tail = "</object>\n";
my $outDir = File::Basename::dirname($html);
open(CMD, '>', File::Spec->catfile($outDir, 'cmdline.html')) or
die("unable to create cmdline.html: $!");
print(CMD $leader, $lcovutil::profileData{config}{cmdLine},
"\n", $tail);
close(CMD) or die("unable to close cmdline.html: $!");
# and the profile data
open(PROF, '>', $html) or die("unable to create $html: $!");
print(PROF $leader);
open(IN, '<', $dest) or die("unable to open $dest: $!");
while (<IN>) {
print(PROF $_);
}
close(IN) or die("unable to close $dest: $!");
print(PROF "\n", $tail);
close(PROF) or die("unable to close cmdline.html: $!");
}
}
}
sub set_extensions
{
my ($type, $str) = @_;
die("unknown language '$type'") unless exists($languageExtensions{$type});
$languageExtensions{$type} = join('|', split($split_char, $str));
}
sub do_mangle_check
{
return unless @lcovutil::cpp_demangle;
if (1 == scalar(@lcovutil::cpp_demangle)) {
if ('' eq $lcovutil::cpp_demangle[0]) {
# no demangler specified - use c++filt by default
if (defined($lcovutil::cpp_demangle_tool)) {
$lcovutil::cpp_demangle[0] = $lcovutil::cpp_demangle_tool;
} else {
$lcovutil::cpp_demangle[0] = 'c++filt';
}
}
} elsif (1 < scalar(@lcovutil::cpp_demangle)) {
die("unsupported usage: --demangle-cpp with genhtml_demangle_cpp_tool")
if (defined($lcovutil::cpp_demangle_tool));
die(
"unsupported usage: --demangle-cpp with genhtml_demangle_cpp_params")
if (defined($lcovutil::cpp_demangle_params));
}
if ($lcovutil::cpp_demangle_params) {
# deprecated usage
push(@lcovutil::cpp_demangle,
split(' ', $lcovutil::cpp_demangle_params));
}
# Extra flag necessary on OS X so that symbols listed by gcov get demangled
# properly.
push(@lcovutil::cpp_demangle, '--no-strip-underscores')
if ($^ eq "darwin");
$lcovutil::demangle_cpp_cmd = '';
foreach my $e (@lcovutil::cpp_demangle) {
$lcovutil::demangle_cpp_cmd .= (($e =~ /\s/) ? "'$e'" : $e) . ' ';
}
my $tool = $lcovutil::cpp_demangle[0];
die("could not find $tool tool needed for --demangle-cpp")
if (lcovutil::system_no_output(3, "echo \"\" | '$tool'"));
}
sub configure_callback
{
# if there is just one argument, then assume it might be a
# concatenation - otherwise, just use straight.
my $cb = shift;
my @args =
1 == scalar(@_) ?
split($lcovutil::split_char, join($lcovutil::split_char, @_)) :
@_;
my $script = $args[0];
if ($script =~ /\.pm$/) {
my $dir = File::Basename::dirname($script);
my $package = File::Basename::basename($script);
my $class = $package;
$class =~ s/\.pm$//;
unshift(@INC, $dir);
eval {
require $package;
#$package->import(qw(new));
# the first value in @_ is the script name
$$cb = $class->new(@args);
};
if ($@ ||
!defined($$cb)) {
lcovutil::ignorable_error($lcovutil::ERROR_PACKAGE,
"unable to create callback from module '$script'" .
(defined($@) ? ": $@" : ''));
}
shift(@INC);
} else {
# not module
$$cb = ScriptCaller->new(@args);
}
push(@configured_callbacks, $cb);
}
sub cleanup_callbacks
{
if ($lcovutil::contextCallback) {
my $ctx;
eval { $ctx = $lcovutil::contextCallback->context(); };
if ($@) {
lcovutil::ignorable_error($lcovutil::ERROR_CALLBACK,
"context callback '" .
$lcovutil::contextCallback[0] .
" ...' failed: $@");
} else {
die('unexpect context callback result: expected hash ref')
unless 'HASH' eq ref($ctx);
$lcovutil::profileData{context} = $ctx;
}
}
foreach my $cb (@configured_callbacks) {
undef $$cb;
}
}
# use these list values from the RC file unless the option is
# passed on the command line
my (@rc_filter, @rc_ignore, @rc_exclude_patterns,
@rc_include_patterns, @rc_subst_patterns, @rc_omit_patterns,
@rc_erase_patterns, @rc_version_script, @unsupported_config,
@rc_source_directories, @rc_build_dir, %unsupported_rc,
$keepGoing, $help, @rc_resolveCallback,
@rc_expected_msg_counts, @rc_criteria_script, @rc_contextCallback,
$rc_no_branch_coverage, $rc_no_func_coverage, $rc_no_checksum,
$version);
my $quiet = 0;
our $tempdirname;
# these options used only by lcov - but moved here so that we can
# share arg parsing
our ($lcov_remove, # If set, removes parts of tracefile
$lcov_capture, # If set, capture data
$lcov_extract); # If set, extracts parts of tracefile
our @opt_config_files;
our @opt_ignore_errors;
our @opt_expected_message_counts;
our @opt_filter;
our @comments;
my %deprecated_rc = ("genhtml_demangle_cpp" => "demangle_cpp",
"genhtml_demangle_cpp_tool" => "demangle_cpp",
"genhtml_demangle_cpp_params" => "demangle_cpp",
"geninfo_checksum" => "checksum",
"geninfo_no_exception_branch" => "no_exception_branch",
'geninfo_adjust_src_path' => 'substitute',
"lcov_branch_coverage" => "branch_coverage",
"lcov_function_coverage" => "function_coverage",
"genhtml_function_coverage" => "function_coverage",
"genhtml_branch_coverage" => "branch_coverage",
'genhtml_criteria_script' => 'criteria_script',
"lcov_fail_under_lines" => 'fail_under_lines',
'genhtml_highlight' => undef,);
my ($cExtensions, $rtlExtensions, $javaExtensions,
$perlExtensions, $pythonExtensions);
my %rc_common = (
'derive_function_end_line' => \$lcovutil::derive_function_end_line,
'derive_function_end_line_all_files' =>
\$derive_function_end_line_all_files,
'trivial_function_threshold' => \$lcovutil::trivial_function_threshold,
"lcov_tmp_dir" => \$lcovutil::tmp_dir,
"lcov_json_module" => \$JsonSupport::rc_json_module,
"branch_coverage" => \$lcovutil::br_coverage,
'mcdc_coverage' => \$lcovutil::mcdc_coverage,
"function_coverage" => \$lcovutil::func_coverage,
"lcov_excl_line" => \$lcovutil::EXCL_LINE,
"lcov_excl_br_line" => \$lcovutil::EXCL_BR_LINE,
"lcov_excl_exception_br_line" => \$lcovutil::EXCL_EXCEPTION_LINE,
"lcov_excl_start" => \$lcovutil::EXCL_START,
"lcov_excl_stop" => \$lcovutil::EXCL_STOP,
"lcov_excl_br_start" => \$lcovutil::EXCL_BR_START,
"lcov_excl_br_stop" => \$lcovutil::EXCL_BR_STOP,
"lcov_excl_exception_br_start" => \$lcovutil::EXCL_EXCEPTION_BR_START,
"lcov_excl_exception_br_stop" => \$lcovutil::EXCL_EXCEPTION_BR_STOP,
"lcov_function_coverage" => \$lcovutil::func_coverage,
"lcov_branch_coverage" => \$lcovutil::br_coverage,
"ignore_errors" => \@rc_ignore,
"max_message_count" => \$lcovutil::suppressAfter,
'expected_message_count' => \@rc_expected_msg_counts,
'stop_on_error' => \$lcovutil::stop_on_error,
'treat_warning_as_error' => \$lcovutil::treat_warning_as_error,
'warn_once_per_file' => \$lcovutil::warn_once_per_file,
'check_data_consistency' => \$lcovutil::check_data_consistency,
"rtl_file_extensions" => \$rtlExtensions,
"c_file_extensions" => \$cExtensions,
"perl_file_extensions" => \$perlExtensions,
"python_file_extensions" => \$pythonExtensions,
"java_file_extensions" => \$javaExtensions,
'info_file_pattern' => \$info_file_pattern,
"filter_lookahead" => \$lcovutil::source_filter_lookahead,
"filter_bitwise_conditional" =>
\$lcovutil::source_filter_bitwise_are_conditional,
'filter_blank_aggressive' => \$filter_blank_aggressive,
"profile" => \$lcovutil::profile,
"parallel" => \$lcovutil::maxParallelism,
"memory" => \$lcovutil::maxMemory,
"memory_percentage" => \$lcovutil::memoryPercentage,
"max_fork_fails" => \$lcovutil::max_fork_fails,
"max_tasks_per_core" => \$lcovutil::max_tasks_per_core,
"fork_fail_timeout" => \$lcovutil::fork_fail_timeout,
'source_directory' => \@rc_source_directories,
'build_directory' => \@rc_build_dir,
"no_exception_branch" => \$lcovutil::exclude_exception_branch,
'filter' => \@rc_filter,
'exclude' => \@rc_exclude_patterns,
'include' => \@rc_include_patterns,
'substitute' => \@rc_subst_patterns,
'omit_lines' => \@rc_omit_patterns,
'erase_functions' => \@rc_erase_patterns,
'context_script' => \@rc_contextCallback,
"version_script" => \@rc_version_script,
'resolve_script' => \@rc_resolveCallback,
'criteria_callback_data' =>
\@CoverageCriteria::criteriaCallbackTypes,
'criteria_callback_levels' =>
\@CoverageCriteria::criteriaCallbackLevels,
'criteria_script' => \@rc_criteria_script,
"checksum" => \$lcovutil::verify_checksum,
'compute_file_version' => \$lcovutil::compute_file_version,
"case_insensitive" => \$lcovutil::case_insensitive,
"forget_testcase_names" => \$TraceFile::ignore_testcase_name,
"split_char" => \$lcovutil::split_char,
'check_existence_before_callback' =>
\$check_file_existence_before_callback,
"demangle_cpp" => \@lcovutil::cpp_demangle,
'excessive_count_threshold' => \$excessive_count_threshold,
'sort_input' => \$lcovutil::sort_inputs,
"fail_under_lines" => \$fail_under_lines,
"fail_under_branches" => \$fail_under_branches,
'lcov_filter_parallel' => \$lcovutil::lcov_filter_parallel,
'lcov_filter_chunk_size' => \$lcovutil::lcov_filter_chunk_size,);
# lcov needs to know the options which might get passed to geninfo in --capture mode
our $defaultChunkSize; # for performance tweaking
our $defaultInterval; # for performance tweaking
our @rc_gcov_tool;
our $geninfo_adjust_testname;
our $opt_external;
our $opt_follow = 0;
our $opt_follow_file_links = 0;
our $opt_compat_libtool;
our $opt_gcov_all_blocks = 1;
our $opt_adjust_unexecuted_blocks = 0;
our $geninfo_opt_compat;
our $rc_adjust_src_path; # Regexp specifying parts to remove from source path
our $rc_auto_base = 1;
our $rc_intermediate = "auto";
our $geninfo_captureAll; # look for both .gcda and lone .gcno files
our %geninfo_rc_opts = (
"geninfo_gcov_tool" => \@rc_gcov_tool,
"geninfo_adjust_testname" => \$geninfo_adjust_testname,
"geninfo_checksum" => \$lcovutil::verify_checksum,
"geninfo_compat_libtool" => \$opt_compat_libtool,
"geninfo_external" => \$opt_external,
"geninfo_follow_symlinks" => \$opt_follow,
"geninfo_follow_file_links" => \$opt_follow_file_links,
"geninfo_gcov_all_blocks" => \$opt_gcov_all_blocks,
"geninfo_unexecuted_blocks" => \$opt_adjust_unexecuted_blocks,
"geninfo_compat" => \$geninfo_opt_compat,
"geninfo_adjust_src_path" => \$rc_adjust_src_path,
"geninfo_auto_base" => \$rc_auto_base,
"geninfo_intermediate" => \$rc_intermediate,
"geninfo_no_exception_branch" => \$lcovutil::exclude_exception_branch,
'geninfo_chunk_size' => \$defaultChunkSize,
'geninfo_interval_update' => \$defaultInterval,
'geninfo_capture_all' => \$geninfo_captureAll);
our %argCommon = ("tempdir=s" => \$tempdirname,
"version-script=s" => \@lcovutil::extractVersionScript,
"criteria-script=s" =>
\@CoverageCriteria::coverageCriteriaScript,
"checksum" => \$lcovutil::verify_checksum,
"no-checksum" => \$rc_no_checksum,
"quiet|q+" => \$quiet,
"verbose|v+" => \$lcovutil::verbose,
"debug+" => \$lcovutil::debug,
"help|h|?" => \$help,
"version" => \$version,
'comment=s' => \@comments,
'toolname=s' => \$lcovutil::tool_name,
"function-coverage" => \$lcovutil::func_coverage,
"branch-coverage" => \$lcovutil::br_coverage,
'mcdc-coverage' => \$lcovutil::mcdc_coverage,
"no-function-coverage" => \$rc_no_func_coverage,
"no-branch-coverage" => \$rc_no_branch_coverage,
"fail-under-lines=s" => \$fail_under_lines,
"fail-under-branches=s" => \$fail_under_branches,
'source-directory=s' =>
\@ReadCurrentSource::source_directories,
'build-directory=s' => \@lcovutil::build_directory,
'resolve-script=s' => \@lcovutil::resolveCallback,
'context-script=s' => \@lcovutil::contextCallback,
"filter=s" => \@opt_filter,
"demangle-cpp:s" => \@lcovutil::cpp_demangle,
"ignore-errors=s" => \@opt_ignore_errors,
"expect-message-count=s" => \@opt_expected_message_counts,
'msg-log:s' => \$message_log,
"keep-going" => \$keepGoing,
"config-file=s" => \@unsupported_config,
"rc=s%" => \%unsupported_rc,
"profile:s" => \$lcovutil::profile,
"exclude=s" => \@lcovutil::exclude_file_patterns,
"include=s" => \@lcovutil::include_file_patterns,
"erase-functions=s" => \@lcovutil::exclude_function_patterns,
"omit-lines=s" => \@lcovutil::omit_line_patterns,
"substitute=s" => \@lcovutil::file_subst_patterns,
"parallel|j:i" => \$lcovutil::maxParallelism,
"memory=i" => \$lcovutil::maxMemory,
"forget-test-names" => \$TraceFile::ignore_testcase_name,
"preserve" => \$lcovutil::preserve_intermediates,
'sort-input' => \$lcovutil::sort_inputs,);
sub warnDeprecated
{
my ($key, $replacement) = @_;
my $opt_used = defined($replacement);
my $suffix =
$opt_used ?
". Consider using '$replacement'. instead. (Backward-compatible support will be removed in the future.)"
:
' and ignored.';
push(@deferred_rc_errors,
[0, $lcovutil::ERROR_DEPRECATED,
"RC option '$key' is deprecated$suffix"
]);
return $opt_used;
}
sub _set_config($$$)
{
# write an RC configuration value - array or scalar
my ($ref, $key, $value) = @_;
my $r = $ref->{$key};
my $t = ref($r);
if ('ARRAY' eq $t) {
info(2, " append $value to list $key\n");
if ('ARRAY' eq ref($value)) {
push(@$r, @$value);
} else {
push(@$r, $value);
}
} else {
# opt is a scalar or not defined
# only way for $value to NOT be an array is if there is a bug in
# the caller such that a scalar ref was passed where a prior call
# had passed a list ref for the same RC option name
die("unexpected ARRAY for $key value")
if ('ARRAY' eq ref($value));
$$r = $value;
info(2, " assign $$r to $key\n");
}
}
#
# read_config(filename, $optionsHash)
#
# Read configuration file FILENAME and write supported key/values into
# RC options hash
# Return: 1 if some config value was set, 0 if not (used for error messaging)
sub read_config($$); # forward decl, to make perl happy about recursive call
my %included_config_files;
my @include_stack;
sub read_config($$)
{
my ($filename, $opts) = @_;
my $key;
my $value;
local *HANDLE;
my $set_value = 0;
info(1, "read_config: $filename\n");
if (exists($included_config_files{abs_path($filename)})) {
lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
'config file inclusion loop detected: "' .
join('" -> "', @include_stack) .
'" -> "' . $filename . '"');
return 0;
}
if (!open(HANDLE, "<", $filename)) {
lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
"cannot read configuration file '$filename': $!");
return 0; # didn't set anything
}
$included_config_files{abs_path($filename)} = 1;
push(@include_stack, $filename);
VAR: while (<HANDLE>) {
chomp;
# Skip comments
s/#.*//;
# Remove leading blanks
s/^\s+//;
# Remove trailing blanks
s/\s+$//;
next unless length;
($key, $value) = split(/\s*=\s*/, $_, 2);
# is this an environment variable?
while (defined($value) &&
$value =~ /\$ENV\{([^}]+)\}/) {
my $varname = $1;
if (!exists($ENV{$varname})) {
push(
@deferred_rc_errors,
[ 1,
$lcovutil::ERROR_USAGE,
"\"$filename\": $.: variable '$key' uses environment variable '$varname' - which is not set (ignoring '$_')."
]);
next VAR;
}
$value =~ s/^\$ENV\{$varname\}/$ENV{$varname}/g;
}
if (defined($key) &&
exists($deprecated_rc{$key})) {
next unless warnDeprecated($key, $deprecated_rc{$key});
$key = $deprecated_rc{$key};
}
if (defined($key) && defined($value)) {
info(2, " set: $key = $value\n");
# special case: read included file
if ($key eq 'config_file') {
$set_value |= read_config($value, $opts);
next;
}
# skip if application doesn't use this setting
next unless exists($opts->{$key});
_set_config($opts, $key, $value);
$set_value = 1;
} else {
my $context = MessageContext::context();
push(
@deferred_rc_errors,
[ 1,
$lcovutil::ERROR_FORMAT,
"\"$filename\": $.: malformed configuration file statement '$_': expected \"key = value\"/"
]);
}
}
close(HANDLE) or die("unable to close $filename: $!\n");
delete $included_config_files{abs_path($filename)};
pop(@include_stack);
return $set_value;
}
# common utility used by genhtml, geninfo, lcov to clean up RC options,
# check for various possible system-wide RC files, and apply the result
# return 1 if we set something
sub apply_rc_params($)
{
my $rcHash = shift;
# merge common RC values with the ones passed in
my %rcHash = (%$rcHash, %rc_common);
# Check command line for a configuration file name
# have to set 'verbosity' flag from environment - otherwise, it isn't
# set (from GetOpt) when we parse the RC file
Getopt::Long::Configure("pass_through", "no_auto_abbrev");
my $quiet = 0;
Getopt::Long::GetOptions("config-file=s" => \@opt_config_files,
"rc=s%" => \@opt_rc,
"quiet|q+" => \$quiet,
"verbose|v+" => \$lcovutil::verbose,
"debug+" => \$lcovutil::debug,);
init_verbose_flag($quiet);
Getopt::Long::Configure("default");
my $set_value = 0;
if (0 != scalar(@opt_config_files)) {
foreach my $f (@opt_config_files) {
$set_value |= read_config($f, \%rcHash);
}
} else {
foreach my $v (['HOME', '.lcovrc'], ['LCOV_HOME', 'etc', 'lcovrc']) {
next unless exists($ENV{$v->[0]});
my $f = File::Spec->catfile($ENV{$v->[0]}, splice(@$v, 1));
if (-r $f) {
$set_value |= read_config($f, \%rcHash);
last;
}
}
}
my $first;
foreach my $v (@opt_rc) {
my $index = index($v, '=');
if ($index == -1) {
push(@deferred_rc_errors,
[1, $lcovutil::ERROR_USAGE,
"malformed --rc option '$v' - should be 'key=value'"
]);
next;
}
my $key = substr($v, 0, $index);
my $value = substr($v, $index + 1);
$key =~ s/^\s+|\s+$//g;
unless (exists($rcHash{$key})) {
push(
@deferred_rc_errors,
[ 1,
$lcovutil::ERROR_USAGE,
"unknown/unsupported key '$key' found in '--rc $v' - see 'man lcovrc(5)' for the list of valid options"
]);
next;
}
info(1, "apply --rc overrides\n")
unless defined($first);
$first = 1;
# can't complain about deprecated uses here because the user
# might have suppressed that message - but we haven't looked at
# the suppressions in the parameter list yet.
if (exists($deprecated_rc{$key})) {
next unless warnDeprecated($key, $deprecated_rc{$key});
}
# strip spaces
$value =~ s/^\s+|\s+$//g;
_set_config(\%rcHash, $key, $value);
$set_value = 1;
}
foreach my $d (['rtl', $rtlExtensions],
['c', $cExtensions],
['perl', $perlExtensions],
['python', $pythonExtensions],
['java', $javaExtensions]
) {
lcovutil::set_extensions(@$d) if $d->[1];
}
return $set_value;
}
sub parseOptions
{
my ($rcOptions, $cmdLineOpts, $output_arg) = @_;
apply_rc_params($rcOptions);
my %options = (%argCommon, %$cmdLineOpts);
if (!GetOptions(%options)) {
return 0;
}
foreach my $d (['--config-file', scalar(@unsupported_config)],
['--rc', scalar(%unsupported_rc)]) {
die("'" . $d->[0] . "' option name cannot be abbreviated\n")
if ($d->[1]);
}
if ($help) {
main::print_usage(*STDOUT);
exit(0);
}
# Check for version option
if ($version) {
print("$tool_name: $lcov_version\n");
exit(0);
}
if (defined($message_log)) {
if (!$message_log) {
# base log file name on output arg (if specified) or tool name otherwise
$message_log = (
defined($$output_arg) ?
substr($$output_arg, 0, rindex($$output_arg, '.')) :
$tool_name) .
".msg";
}
$message_filename = $message_log;
open(LOG, ">", $message_log) or
die("unable to write message log '$message_log': $!");
$message_log = \*LOG;
}
lcovutil::init_verbose_flag($quiet);
# apply the RC file settings if no command line arg
foreach my $rc ([\@opt_filter, \@rc_filter],
[\@opt_ignore_errors, \@rc_ignore],
[\@opt_expected_message_counts, \@rc_expected_msg_counts],
[\@lcovutil::exclude_file_patterns, \@rc_exclude_patterns],
[\@lcovutil::include_file_patterns, \@rc_include_patterns],
[\@lcovutil::file_subst_patterns, \@rc_subst_patterns],
[\@lcovutil::omit_line_patterns, \@rc_omit_patterns],
[\@lcovutil::exclude_function_patterns, \@rc_erase_patterns
],
[\@lcovutil::extractVersionScript, \@rc_version_script],
[\@CoverageCriteria::coverageCriteriaScript,
\@rc_criteria_script
],
[\@ReadCurrentSource::source_directories,
\@rc_source_directories
],
[\@lcovutil::build_directory, \@rc_build_dir],
[\@lcovutil::resolveCallback, \@rc_resolveCallback],
[\@lcovutil::contextCallback, \@rc_contextCallback],
) {
@{$rc->[0]} = @{$rc->[1]} unless (@{$rc->[0]});
}
$ReadCurrentSource::searchPath =
SearchPath->new('source directory',
@ReadCurrentSource::source_directories);
$lcovutil::stop_on_error = 0
if (defined $keepGoing);
push(@lcovutil::exclude_file_patterns, @ARGV)
if $lcov_remove;
push(@lcovutil::include_file_patterns, @ARGV)
if $lcov_extract;
# Merge options
$lcovutil::func_coverage = 0
if ($rc_no_func_coverage);
$lcovutil::br_coverage = 0
if ($rc_no_branch_coverage);
$lcovutil::verify_checksum = 0
if (defined($rc_no_checksum));
foreach my $cb ([\$versionCallback, \@lcovutil::extractVersionScript],
[\$resolveCallback, \@lcovutil::resolveCallback],
[\$CoverageCriteria::criteriaCallback,
\@CoverageCriteria::coverageCriteriaScript
],
[\$contextCallback, \@lcovutil::contextCallback],
) {
lcovutil::configure_callback($cb->[0], @{$cb->[1]})
if (@{$cb->[1]});
}
# perhaps warn that date/owner and directory are only supported by genhtml?
foreach my $data (['criteria_callback_levels',
\@CoverageCriteria::criteriaCallbackLevels,
['top', 'directory', 'file']
],
['criteria_callback_data',
\@CoverageCriteria::criteriaCallbackTypes,
['date', 'owner']
]
) {
my ($rc, $user, $valid) = @$data;
@$user = split(',', join(',', @$user));
foreach my $x (@$user) {
die("invalid '$rc' value \"$x\" - expected (" .
join(", ", @$valid) . ")")
unless grep(/^$x$/, @$valid);
}
}
# context only gets grabbed/stored with '--profile'
$lcovutil::profile = ''
if ($contextCallback && !defined($lcovutil::profile));
if (!$lcov_capture) {
if ($lcovutil::compute_file_version &&
!defined($versionCallback)) {
lcovutil::ignorable_warning($lcovutil::ERROR_USAGE,
"'compute_file_version=1' option has no effect without either '--version-script' or 'version_script=...'."
);
}
lcovutil::munge_file_patterns();
lcovutil::init_parallel_params();
# Determine which errors the user wants us to ignore
parse_ignore_errors(@opt_ignore_errors);
parse_expected_message_counts(@opt_expected_message_counts);
# Determine what coverpoints the user wants to filter
push(@opt_filter, 'exception') if $lcovutil::exclude_exception_branch;
parse_cov_filters(@opt_filter);
# Ensure that the c++filt tool is available when using --demangle-cpp
lcovutil::do_mangle_check();
foreach my $entry (@deferred_rc_errors) {
my ($isErr, $type, $msg) = @$entry;
if ($isErr) {
lcovutil::ignorable_error($type, $msg);
} else {
lcovutil::ignorable_warning($type, $msg);
}
}
}
return 1;
}
#
# transform_pattern(pattern)
#
# Transform shell wildcard expression to equivalent Perl regular expression.
# Return transformed pattern.
#
sub transform_pattern($)
{
my $pattern = $_[0];
# Escape special chars
$pattern =~ s/\\/\\\\/g;
$pattern =~ s/\//\\\//g;
$pattern =~ s/\^/\\\^/g;
$pattern =~ s/\$/\\\$/g;
$pattern =~ s/\(/\\\(/g;
$pattern =~ s/\)/\\\)/g;
$pattern =~ s/\[/\\\[/g;
$pattern =~ s/\]/\\\]/g;
$pattern =~ s/\{/\\\{/g;
$pattern =~ s/\}/\\\}/g;
$pattern =~ s/\./\\\./g;
$pattern =~ s/\,/\\\,/g;
$pattern =~ s/\|/\\\|/g;
$pattern =~ s/\+/\\\+/g;
$pattern =~ s/\!/\\\!/g;
# Transform ? => (.) and * => (.*)
$pattern =~ s/\*/\(\.\*\)/g;
$pattern =~ s/\?/\(\.\)/g;
$pattern = "/$pattern/i"
if ($lcovutil::case_insensitive);
return qr($pattern);
}
sub munge_file_patterns
{
# Need perlreg expressions instead of shell pattern
if (@exclude_file_patterns) {
@exclude_file_patterns =
map({ [transform_pattern($_), $_, 0]; } @exclude_file_patterns);
}
if (@include_file_patterns) {
@include_file_patterns =
map({ [transform_pattern($_), $_, 0]; } @include_file_patterns);
}
# precompile match patterns and check for validity
foreach my $p (['omit-lines', \@omit_line_patterns],
['exclude-functions', \@exclude_function_patterns]) {
my ($flag, $list) = @$p;
next unless (@$list);
# keep track of number of times pattern was applied
# regexp compile will die if pattern is invalid
eval {
@$list = map({ [qr($_), $_, 0]; } @$list);
};
die("Invalid $flag regexp in ('" . join('\' \'', @$list) . "'):\n$@")
if $@;
}
# sadly, substitutions aren't regexps and can't be precompiled
foreach my $p (['substitute', \@file_subst_patterns]) {
my ($flag, $list) = @$p;
next unless @$list;
PAT: foreach my $pat (@$list) {
my $text = 'abc';
my $str = eval { '$test =~ ' . $pat . ';' };
die("Invalid regexp \"$flag $pat\":\n$@")
if $@;
if ($lcovutil::case_insensitive) {
for (my $i = length($pat) - 1; $i >= 0; --$i) {
my $char = substr($pat, $i, 1);
next PAT
if ($char eq 'i');
last # didn't see the 'i' character
if ($char =~ /[\/#!@%]/);
}
lcovutil::ignorable_warning($lcovutil::ERROR_USAGE,
"--$flag pattern '$pat' does not seem to be case insensitive - but you asked for case insensitive matching"
);
}
}
# keep track of number of times this was applied
@$list = map({ [$_, 0]; } @$list);
}
# and check for valid region patterns
for my $regexp (['lcov_excl_line', $lcovutil::EXCL_LINE],
['lcov_excl_br_line', $lcovutil::EXCL_BR_LINE],
['lcov_excl_exception_br_line',
$lcovutil::EXCL_EXCEPTION_LINE
],
["lcov_excl_start", \$lcovutil::EXCL_START],
["lcov_excl_stop", \$lcovutil::EXCL_STOP],
["lcov_excl_br_start", \$lcovutil::EXCL_BR_START],
["lcov_excl_br_stop", \$lcovutil::EXCL_BR_STOP],
["lcov_excl_exception_br_start",
\$lcovutil::EXCL_EXCEPTION_BR_START
],
["lcov_excl_exception_br_stop",
\$lcovutil::EXCL_EXCEPTION_BR_STOP
]
) {
eval 'qr/' . $regexp->[1] . '/';
my $error = $@;
chomp($error);
$error =~ s/at \(eval.*$//;
die("invalid '" . $regexp->[0] . "' exclude pattern: $error")
if $error;
}
@suppress_function_patterns = map({ $_->[0] } @exclude_function_patterns);
}
sub warn_file_patterns
{
foreach my $p (['include', \@include_file_patterns],
['exclude', \@exclude_file_patterns],
['substitute', \@file_subst_patterns],
['omit-lines', \@omit_line_patterns],
['exclude-functions', \@exclude_function_patterns]
) {
my ($type, $patterns) = @$p;
foreach my $pat (@$patterns) {
my $count = $pat->[scalar(@$pat) - 1];
if (0 == $count) {
my $str = $pat->[scalar(@$pat) - 2];
lcovutil::ignorable_error($ERROR_UNUSED,
"'$type' pattern '$str' is unused.");
}
}
}
}
#
# subst_file_name($path)
#
# apply @file_subst_patterns to $path and return
#
sub subst_file_name($)
{
my $name = shift;
foreach my $p (@file_subst_patterns) {
my $old = $name;
# sadly, no support for pre-compiled patterns
eval '$name =~ ' . $p->[0] . ';'; # apply pattern that user provided...
# $@ should never match: we already checked pattern validity during
# initialization - above. Still: belt and braces.
die("invalid 'subst' regexp '" . $p->[0] . "': $@")
if ($@);
$p->[-1] += 1
if $old ne $name;
}
return $name;
}
#
# strip_directories($path, $depth)
#
# Remove DEPTH leading directory levels from PATH.
#
sub strip_directories($$)
{
my $filename = $_[0];
my $depth = $_[1];
my $i;
if (!defined($depth) || ($depth < 1)) {
return $filename;
}
my $d = $lcovutil::dirseparator;
for ($i = 0; $i < $depth; $i++) {
if ($lcovutil::case_insensitive) {
$filename =~ s/^[^$d]*$d+(.*)$/$1/i;
} else {
$filename =~ s/^[^$d]*$d+(.*)$/$1/;
}
}
return $filename;
}
sub define_errors()
{
my $id = 0;
foreach my $d (@lcovErrs) {
my ($k, $ref) = @$d;
$$ref = $id;
$lcovErrors{$k} = $id;
$ERROR_ID{$k} = $id;
$ERROR_NAME{$id} = $k;
$ignore[$id] = 0;
$message_count[$id] = 0;
$expected_message_count[$id] = undef; # no expected count, by default
++$id;
}
}
sub summarize_messages
{
my $silent = shift;
return if $lcovutil::in_child_process;
# first check for expected message count constraints
for (my $idx = 0; $idx <= $#expected_message_count; ++$idx) {
my $expr = $expected_message_count[$idx];
next unless defined($expr);
my $t = $message_count[$idx];
$expr =~ s/%C/$t/g;
my $v;
eval { $v = eval $expr; };
if ($@ || !defined($v)) {
# we checked the syntax of the message - so should not be able to fail
lcovutil::ignorable_error($lcovutil::ERROR_CALLBACK,
"evaluation of '$expr' failed: $@");
next;
}
unless ($v) {
my $type = $ERROR_NAME{$idx};
lcovutil::ignorable_error($lcovutil::ERROR_COUNT,
"'$type' constraint '$expr' is not true (see '--expect_message_count' for details)."
);
}
}
# now summarize
my %total = ('error' => 0,
'warning' => 0,
'ignore' => 0,);
# use verbosity level -1: so print unless user says "-q -q"...really quiet
my $found = 0;
while (my ($type, $hash) = each(%message_types)) {
while (my ($name, $count) = each(%$hash)) {
$total{$type} += $count;
$found = 1;
}
}
my $header = "Message summary:\n";
foreach my $type ('error', 'warning', 'ignore') {
next unless $total{$type};
$found = 1;
my $leader = $header . ' ' . $total{$type} . " $type message" .
($total{$type} > 1 ? 's' : '') . ":\n";
my $h = $message_types{$type};
foreach my $k (sort keys %$h) {
info(-1, $leader . ' ' . $k . ": " . $h->{$k} . "\n");
$leader = '';
}
$header = '';
}
info(-1, "$header no messages were reported\n") unless $found || $silent;
}
sub parse_ignore_errors(@)
{
my @ignore_errors = split($split_char, join($split_char, @_));
# first, mark that all known errors are not ignored
foreach my $item (keys(%ERROR_ID)) {
my $id = $ERROR_ID{$item};
$ignore[$id] = 0
unless defined($ignore[$id]);
}
return if (!@ignore_errors);
foreach my $item (@ignore_errors) {
die("unknown argument for --ignore-errors: '$item'")
unless exists($ERROR_ID{lc($item)});
my $item_id = $ERROR_ID{lc($item)};
$ignore[$item_id] += 1;
}
}
sub parse_expected_message_counts(@)
{
my @constraints = split($split_char, join($split_char, @_));
# parse the list and look for errors..
foreach my $c (@constraints) {
if ($c =~ /^s*(\S+?)\s*:\s*((\d+)|(.+?))\s*$/) {
unless (exists($ERROR_ID{lc($1)})) {
lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
"unknown 'expected-message-count' message type \"$1\".");
next;
}
my $id = $ERROR_ID{lc($1)};
if (defined($expected_message_count[$id])) {
my $ignore = $lcovutil::ignore[$lcovutil::ERROR_USAGE];
lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
"duplicate 'expected' constraint '$c'" .
($ignore ? ': ignoring.' : ''));
next;
}
# check if syntax look reasonable
my $expr = $2;
if (Scalar::Util::looks_like_number($expr)) {
$expected_message_count[$id] = "%C == $expr";
next;
}
lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
"expect-message-count constraint '$c' does not appear to depend on message count: '%C' substitution not found."
) unless ($expr =~ /%C/);
# now lets try an eval
my $v = $expr;
$v =~ s/%C/0/g;
$v = eval $v;
if (defined($v)) {
$expected_message_count[$id] = $expr;
} else {
my $ignore = $lcovutil::ignore[$lcovutil::ERROR_USAGE];
lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
"eval error in 'expect-message-count' constraint '$c': $@"
. ($ignore ? ': ignoring.' : ''));
}
} else {
lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
"malformed expected-message-count constraint \"$c\". Expected 'msg_type = expr'."
);
}
}
}
sub message_count($)
{
my $code = shift;
return $message_count[$code];
}
sub is_ignored($)
{
my $code = shift;
die("invalid error code $code")
unless 0 <= $code && $code < scalar(@ignore);
return $ignore[$code] || (defined($stop_on_error) && 0 == $stop_on_error);
}
our %explainOnce; # append explanation to first error/warning message (only)
sub explain_once
{
# NOTE: in parallel execution, the explanations may appear more than
# once - e.g., when two or more child processes generate them
# simultaneously.
# They will eventually update the parent process state such that
# subsequent children won't report the issues.
my $key = shift;
if (!exists($explainOnce{$key})) {
$explainOnce{$key} = 1;
my $msg = '';
# each element is either a string or a pair of [string, predicate]
foreach my $e (@_) {
if ('ARRAY' eq ref($e)) {
$msg .= $e->[0] if defined($e->[1]) && $e->[1];
} else {
$msg .= $e;
}
}
return $msg;
}
return '';
}
our %warnOnlyOnce;
our $deferWarnings = 0;
# if 'stop_on_error' is false, then certain errors should be emitted at most once
# (not relevant if stop_on_error is true - as we will exit after the error.
sub warn_once
{
my ($msgType, $key) = @_;
return 0
if (exists($warnOnlyOnce{$msgType}) &&
exists($warnOnlyOnce{$msgType}{$key}));
$warnOnlyOnce{$msgType}{$key} = 1;
return 1;
}
sub store_deferred_message
{
my ($msgType, $isError, $key, $msg) = @_;
die(
"unexpected deferred value of $msg->$key: $warnOnlyOnce{$msgType}{$key}")
unless 1 == $warnOnlyOnce{$msgType}{$key};
if ($deferWarnings) {
$warnOnlyOnce{$msgType}{$key} = [$msg, $isError];
} else {
if ($isError) {
lcovutil::ignorable_error($msgType, $msg);
} else {
lcovutil::ignorable_warning($msgType, $msg);
}
}
}
sub merge_deferred_warnings
{
my $hash = shift;
while (my ($type, $d) = each(%$hash)) {
while (my ($key, $m) = each(%$d)) {
if (!(exists($warnOnlyOnce{$type}) &&
exists($warnOnlyOnce{$type}{$key}))) {
if ('ARRAY' eq ref($m)) {
# this is a
my ($msg, $isError) = @$m;
if ($isError) {
lcovutil::ignorable_error($type, $msg);
} else {
lcovutil::ignorable_warning($type, $msg);
}
}
$warnOnlyOnce{$type}{$key} = 1;
}
}
}
}
sub initial_state
{
# a bit of a hack: this method is called at the start of each
# child process - so use it to record that we are executing in a
# child.
# The flag is used to reduce verbosity from children - and possibly
# for other things later
$lcovutil::in_child_process = 1;
# keep track of number of warnings, etc. generated in child -
# so we can merge back into parent. This may prevent us from
# complaining about the same thing in multiple children - but only
# if those children don't execute in parallel.
%message_types = (); #reset
$ReadCurrentSource::searchPath->reset();
# clear profile - want only my contribution
%lcovutil::profileData = ();
%lcovutil::warnOnlyOnce = ();
# clear pattern counts so we can update number found in children
foreach my $patType (\@lcovutil::exclude_file_patterns,
\@lcovutil::include_file_patterns,
\@lcovutil::file_subst_patterns,
\@lcovutil::omit_line_patterns,
\@lcovutil::exclude_function_patterns
) {
foreach my $p (@$patType) {
$p->[-1] = 0;
}
}
return Storable::dclone([\@message_count, \%versionCache, \%resolveCache]);
}
sub compute_update
{
my $state = shift;
my @new_count;
my ($initialCount, $initialVersionCache, $initialResolveCache) = @$state;
my $id = 0;
foreach my $count (@message_count) {
my $v = $count - $initialCount->[$id++];
push(@new_count, $v);
}
my %versionUpdate;
while (my ($f, $v) = each(%versionCache)) {
$versionUpdate{$f} = $v
unless exists($initialVersionCache->{$f});
}
my %resolveUpdate;
while (my ($f, $v) = each(%resolveCache)) {
$resolveUpdate{$f} = $v
unless exists($initialResolveCache->{$f});
}
my @rtn = (\@new_count,
\%versionUpdate,
\%resolveUpdate,
\%message_types,
$ReadCurrentSource::searchPath->current_count(),
\%lcovutil::profileData,
\%lcovutil::warnOnlyOnce,
\%lcovutil::explainOnce);
foreach my $patType (\@lcovutil::exclude_file_patterns,
\@lcovutil::include_file_patterns,
\@lcovutil::file_subst_patterns,
\@lcovutil::omit_line_patterns,
\@lcovutil::exclude_function_patterns
) {
my @count;
foreach my $p (@$patType) {
push(@count, $p->[-1]);
}
push(@rtn, \@count);
}
return \@rtn;
}
sub update_state
{
my $updateCount = shift;
my $id = 0;
foreach my $count (@$updateCount) {
$message_count[$id++] += $count;
}
my $updateVersionCache = shift;
while (my ($f, $v) = each(%$updateVersionCache)) {
lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
"unexpected version entry")
if exists($versionCache{$f}) && $versionCache{$f} ne $v;
$versionCache{$f} = $v;
}
my $updateResolveCache = shift;
while (my ($f, $v) = each(%$updateResolveCache)) {
lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
"unexpected resolve entry")
if exists($resolveCache{$f}) && $resolveCache{$f} ne $v;
$resolveCache{$f} = $v;
}
my $msgTypes = shift;
while (my ($type, $h) = each(%$msgTypes)) {
while (my ($err, $count) = each(%$h)) {
if (exists($message_types{$type}) &&
exists($message_types{$type}{$err})) {
$message_types{$type}{$err} += $count;
} else {
$message_types{$type}{$err} = $count;
}
}
}
my $searchCount = shift;
$ReadCurrentSource::searchPath->update_count(@$searchCount);
my $profile = shift;
lcovutil::merge_child_profile($profile);
my $warnOnce = shift;
lcovutil::merge_deferred_warnings($warnOnce);
my $explainOnce = shift;
while (my ($key, $v) = each(%$explainOnce)) {
$lcovutil::explainOnce{$key} = $v;
}
foreach my $patType (\@lcovutil::exclude_file_patterns,
\@lcovutil::include_file_patterns,
\@lcovutil::file_subst_patterns,
\@lcovutil::omit_line_patterns,
\@lcovutil::exclude_function_patterns
) {
my $count = shift;
die("unexpected pattern count") unless $#$count == $#$patType;
foreach my $p (@$patType) {
$p->[-1] += shift @$count;
}
}
die("unexpected update data") unless -1 == $#_; # exhausted list
}
sub warnSuppress($$)
{
my ($code, $errName) = @_;
if ($ignore[$code] <= 1 && # don't warn if already suppressed
$message_count[$code] == ($suppressAfter + 1)
) {
# explain once per error type, if verbose - else only once
my $explain = explain_once(
'error_count' . ($lcovutil::verbose ? $errName : ''),
"\n\tTo increase or decrease this limit use '--rc max_message_count=value'."
);
ignorable_warning($ERROR_COUNT,
"max_message_count=$suppressAfter reached for '$errName' messages: no more will be reported.$explain"
);
}
}
sub _count_message($$)
{
my ($type, $name) = @_;
$message_types{$type}{$name} = 0
unless (exists($message_types{$type}) &&
exists($message_types{$type}{$name}));
++$message_types{$type}{$name};
}
sub saw_error
{
# true if we saw at least one error when 'stop_on_error' is false
# enables us to return non-zero exit status if any errors were detected
return exists($message_types{error});
}
sub ignorable_error($$;$)
{
my ($code, $msg, $quiet) = @_;
die("undefined error code for '$msg'") unless defined($code);
my $errName = "code_$code";
$errName = $ERROR_NAME{$code}
if exists($ERROR_NAME{$code});
if ($message_count[$code]++ >= $suppressAfter &&
0 < $suppressAfter) {
# safe to just continue without checking anything else - as either
# this message is not fatal and we emitted it some number of times,
# or the message is fatal - and this is the first time we see it
_count_message('ignore', $errName);
# warn that we are suppressing from here on - for the first skipped
# message of this type
warnSuppress($code, $errName);
return;
}
chomp($msg); # we insert the newline
if ($code >= scalar(@ignore) ||
!$ignore[$code]) {
my $ignoreOpt =
"\t(use \"$tool_name --ignore-errors $errName ...\" to bypass this error)\n";
$ignoreOpt = ''
if ($lcovutil::in_child_process ||
!($lcovutil::verbose || $message_count[$code] == 1));
if (defined($stop_on_error) && 0 == $stop_on_error) {
_count_message('error', $errName);
warn_handler("($errName) $msg\n$ignoreOpt", 1);
return;
}
_count_message('error', $errName);
die_handler("($errName) $msg\n$ignoreOpt");
}
# only tell the user how to suppress this on the first occurrence
my $ignoreOpt =
"\t(use \"$tool_name --ignore-errors $errName,$errName ...\" to suppress this warning)\n";
$ignoreOpt = ''
if ($lcovutil::in_child_process ||
!($lcovutil::verbose || $message_count[$code] == 1));
if ($ignore[$code] > 1 || (defined($quiet) && $quiet)) {
_count_message('ignore', $errName);
} else {
_count_message('warning', $errName);
warn_handler("($errName) $msg\n$ignoreOpt", 0);
}
}
sub ignorable_warning($$;$)
{
my ($code, $msg, $quiet) = @_;
if ($lcovutil::treat_warning_as_error) {
ignorable_error($code, $msg, $quiet);
return;
}
die("undefined error code for '$msg'") unless defined($code);
my $errName = "code_$code";
$errName = $ERROR_NAME{$code}
if exists($ERROR_NAME{$code});
if ($message_count[$code]++ >= $suppressAfter &&
0 < $suppressAfter) {
# warn that we are suppressing from here on - for the first skipped
# message of this type
warnSuppress($code, $errName);
_count_message('ignore', $errName);
return;
}
chomp($msg); # we insert the newline
if ($code >= scalar(@ignore) ||
!$ignore[$code]) {
# only tell the user how to suppress this on the first occurrence
my $ignoreOpt =
"\t(use \"$tool_name --ignore-errors $errName,$errName ...\" to suppress this warning)\n";
$ignoreOpt = ''
if ($lcovutil::in_child_process ||
!($lcovutil::verbose || $message_count[$code] == 1));
warn_handler("($errName) $msg\n$ignoreOpt", 0);
_count_message('warning', $errName);
} else {
_count_message('ignore', $errName);
}
}
sub report_unknown_child
{
my $child = shift;
# this can happen if the user loads a callback module which starts a chaild
# process when it is loaded or initialized and fails to wait for that child
# to finish. How it manifests is an orphan PID which is smaller (older)
# than any of the children that this parent actually scheduled
lcovutil::ignorable_error($lcovutil::ERROR_CHILD,
"found unknown process $child while waiting for parallel child:\n perhaps you forgot to close a process in your callback?"
);
}
sub report_fork_failure
{
my ($when, $errcode, $failedAttempts) = @_;
if ($failedAttempts > $lcovutil::max_fork_fails) {
lcovutil::ignorable_error($lcovutil::ERROR_PARALLEL,
"$failedAttempts consecutive fork() failures: consider reduced parallelism or increase the max_fork_fails limit. See man(5) lcovrc."
);
}
my $explain = explain_once('fork_fail',
["\n\tUse '$tool_name --ignore_errors " .
$ERROR_NAME{$ERROR_FORK} .
"' to bypass error and retry.",
$ignore[$lcovutil::ERROR_FORK] == 0
]);
my $retry =
lcovutil::is_ignored($lcovutil::ERROR_FORK) ? ' (retrying)' : '';
lcovutil::ignorable_error($lcovutil::ERROR_FORK,
"fork() syscall failed while trying to $when: " .
$errcode . $retry . $explain);
# if errors were ignored, then we wait for a while (in parent)
# before re-trying.
sleep($lcovutil::fork_fail_timeout);
}
sub report_exit_status
{
my ($errType, $message, $exitstatus, $prefix, $suffix) = @_;
my $status = $exitstatus >> 8;
my $signal = $exitstatus & 0xFF;
my $explain =
"$prefix " .
($exitstatus ? "returned non-zero exit status $status" : 'failed') .
MessageContext::context();
if ($signal) {
$explain =
"$prefix died died due to signal $signal (SIG" .
(split(' ', $Config{sig_name}))[$signal] .
')' . MessageContext::context() .
': possibly killed by OS due to out-of-memory';
$explain .=
lcovutil::explain_once('out_of_memory',
' - see --memory and --parallel options for throttling');
}
ignorable_error($errType, "$message: $explain$suffix");
}
sub report_parallel_error
{
my $operation = shift;
my $errno = shift;
my $pid = shift;
my $childstatus = shift;
my $msg = shift;
# kill all my remaining children so user doesn't see unexpected console
# messages from dangling children (who cannot open files because the
# temp directory has been deleted, and so forth)
kill(9, @_) if @_ && !is_ignored($errno);
report_exit_status($errno, "$operation: '$msg'",
$childstatus, "child $pid",
" (try removing the '--parallel' option)");
}
sub report_format_error($$$$)
{
my ($errType, $countType, $count, $obj) = @_;
my $context = MessageContext::context();
my $explain =
explain_once(
'err_negative',
["\n\tPerhaps you need to compile with '-fprofile-update=atomic'.",
($lcovutil::ERROR_NEGATIVE == $errType &&
'geninfo' eq $lcovutil::tool_name)
]);
my $errStr =
$lcovutil::ERROR_NEGATIVE == $errType ? 'negative' :
($lcovutil::ERROR_FORMAT == $errType ? 'non-integer' : 'excessive');
lcovutil::ignorable_error($errType,
"Unexpected $errStr $countType count '$count' for $obj$context.$explain"
);
}
sub check_parent_process
{
die("must call from child process") unless $lcovutil::in_child_process;
# if parent PID changed to 1 (init) - then my parent went away so
# I should exit now
# for reasons which are unclear to me: the PPID is sometimes unchanged
# after the parent process dies - to also check if we can send it a signal
my $ppid = getppid();
lcovutil::info(2, "check_parent_process($$) = $ppid\n");
if (1 == getppid() ||
1 != kill(0, $ppid)) {
lcovutil::ignorable_error($lcovutil::ERROR_PARENT,
"parent process died during '--parallel' execution - child $$ cannot continue."
);
exit(0);
}
}
sub is_filter_enabled
{
# return true of there is an opportunity for filtering
return (grep({ defined($_) } @lcovutil::cov_filter) ||
0 != scalar(@lcovutil::omit_line_patterns) ||
0 != scalar(@lcovutil::exclude_function_patterns));
}
sub init_filters
{
# initialize filter index numbers and mark that all filters are disabled.
my $idx = 0;
foreach my $item (sort keys(%COVERAGE_FILTERS)) {
my $ref = $COVERAGE_FILTERS{$item};
$COVERAGE_FILTERS{$item} = $idx;
$$ref = $idx;
$cov_filter[$idx++] = undef;
}
}
sub parse_cov_filters(@)
{
my @filters = split($split_char, join($split_char, @_));
goto final if (!@filters);
foreach my $item (@filters) {
die("unknown argument for --filter: '$item'\n")
unless exists($COVERAGE_FILTERS{lc($item)});
my $item_id = $COVERAGE_FILTERS{lc($item)};
$cov_filter[$item_id] = [$item, 0, 0];
}
if ($cov_filter[$FILTER_LINE]) {
# when line filtering is enabled, turn on brace and blank filtering as well
# (backward compatibility)
$cov_filter[$FILTER_LINE_CLOSE_BRACE] = ['brace', 0, 0];
$cov_filter[$FILTER_BLANK_LINE] = ['blank', 0, 0];
}
if ((defined($cov_filter[$FILTER_BRANCH_NO_COND]) ||
defined($cov_filter[$FILTER_EXCLUDE_BRANCH])) &&
!($br_coverage || $mcdc_coverage)
) {
lcovutil::ignorable_warning($ERROR_USAGE,
"branch filter enabled but neither branch or condition coverage is enabled"
);
}
lcovutil::ignorable_warning($ERROR_USAGE,
"'mcdc' filter enabled but MC/DC coverage is not enabled.")
if (defined($cov_filter[$FILTER_MCDC_SINGLE]) &&
!$mcdc_coverage);
if ($cov_filter[$FILTER_BRANCH_NO_COND]) {
# turn on exception and orphan filtering too
$cov_filter[$FILTER_EXCEPTION_BRANCH] = ['exception', 0, 0];
$cov_filter[$FILTER_ORPHAN_BRANCH] = ['orphan', 0, 0];
}
final:
if (@lcovutil::omit_line_patterns) {
$lcovutil::FILTER_OMIT_PATTERNS = scalar(@lcovutil::cov_filter);
push(@lcovutil::cov_filter, ['omit_lines', 0, 0]);
$lcovutil::COVERAGE_FILTERS{'omit_lines'} =
$lcovutil::FILTER_OMIT_PATTERNS;
}
}
sub summarize_cov_filters
{
# use verbosity level -1: so print unless user says "-q -q"...really quiet
my $leader = "Filter suppressions:\n";
for my $key (keys(%COVERAGE_FILTERS)) {
my $id = $COVERAGE_FILTERS{$key};
next unless defined($lcovutil::cov_filter[$id]);
my $histogram = $lcovutil::cov_filter[$id];
next if 0 == $histogram->[-2];
my $points = '';
if ($histogram->[-2] != $histogram->[-1]) {
$points = ' ' . $histogram->[-1] . ' coverpoint' .
($histogram->[-1] > 1 ? 's' : '') . "\n";
}
info(-1,
"$leader $key:\n " . $histogram->[-2] . " instance" .
($histogram->[-2] > 1 ? "s" : "") . "\n" . $points);
$leader = '';
}
foreach my $q (['omit-lines', 'line', \@omit_line_patterns],
['erase-functions', 'function', \@exclude_function_patterns]) {
my ($opt, $type, $patterns) = @$q;
my $patternCount = scalar(@$patterns);
if ($patternCount) {
my $omitCount = 0;
foreach my $p (@$patterns) {
$omitCount += $p->[-1];
}
info(-1,
"Omitted %d total $type%s matching %d '--$opt' pattern%s\n",
$omitCount,
$omitCount == 1 ? '' : 's',
$patternCount,
$patternCount == 1 ? '' : 's');
}
}
}
sub disable_cov_filters
{
# disable but return current status - so they can be re-enabled
my @filters = @lcovutil::cov_filter;
foreach my $f (@lcovutil::cov_filter) {
$f = undef;
}
my @omit = @lcovutil::omit_line_patterns;
@lcovutil::omit_line_patterns = ();
my @erase = @lcovutil::exclude_function_patterns;
@lcovutil::exclude_function_patterns = ();
return [\@filters, \@omit, \@erase];
}
sub reenable_cov_filters
{
my $data = shift;
my $filters = $data->[0];
# re-enable in the same order
for (my $i = 0; $i < scalar(@$filters); $i++) {
$cov_filter[$i] = $filters->[$i];
}
@lcovutil::omit_line_patterns = @{$data->[1]};
@lcovutil::exclude_function_patterns = @{$data->[2]};
}
sub filterStringsAndComments
{
my $src_line = shift;
# remove compiler directives
$src_line =~ s/^\s*#.*$//g;
# remove comments
$src_line =~ s#(/\*.*?\*/|//.*$)##g;
# remove strings
$src_line =~ s/\\"//g;
$src_line =~ s/"[^"]*"//g;
return $src_line;
}
sub simplifyCode
{
my $src_line = shift;
# remove comments
$src_line = filterStringsAndComments($src_line);
# remove some keywords..
$src_line =~ s/\b(const|volatile|typename)\b//g;
#collapse nested class names
# remove things that look like template names
my $id = '(::)?\w+\s*(::\s*\w+\s*)*';
while (1) {
my $current = $src_line;
$src_line =~ s/<\s*${id}(,\s*${id})*([*&]\s*)?>//g;
last if $src_line eq $current;
}
# remove ref and pointer decl
$src_line =~ s/^\s*$id[&*]\s*($id)/$3/g;
# cast which contains optional location spec
my $cast = "\\s*${id}(\\s+$id)?[*&]\\s*";
# C-style cast - with optional location spec
$src_line =~ s/\($cast\)//g;
$src_line =~ s/\b(reinterpret|dynamic|const)_cast<$cast>//g;
# remove addressOf that follows an open paren or a comma
#$src_line =~ s/([(,])\s*[&*]\s*($id)/$1 $2/g;
# remove some characters which might look like conditionals
$src_line =~ s/(->|>>|<<|::)//g;
return $src_line;
}
sub balancedParens
{
my $line = shift;
my $open = 0;
my $close = 0;
foreach my $char (split('', $line)) {
if ($char eq '(') {
++$open;
} elsif ($char eq ')') {
++$close;
}
}
return ($open == $close ||
# lambda code may have trailing parens after the function...
($close > $open && $line =~ /{lambda\(/)
); # this is a C++-specific check
}
#
# is_external(filename)
#
# Determine if a file is located outside of the specified data directories.
#
sub is_external($)
{
my $filename = shift;
# nothing is 'external' unless the user has requested "--no-external"
return 0 unless (defined($opt_no_external) && $opt_no_external);
foreach my $dir (@internal_dirs) {
return 0
if (($lcovutil::case_insensitive && $filename =~ /^\Q$dir\E/i) ||
(!$lcovutil::case_insensitive && $filename =~ /^\Q$dir\E/));
}
return 1;
}
#
# rate(hit, found[, suffix, precision, width])
#
# Return the coverage rate [0..100] for HIT and FOUND values. 0 is only
# returned when HIT is 0. 100 is only returned when HIT equals FOUND.
# PRECISION specifies the precision of the result. SUFFIX defines a
# string that is appended to the result if FOUND is non-zero. Spaces
# are added to the start of the resulting string until it is at least WIDTH
# characters wide.
#
sub rate($$;$$$)
{
my ($hit, $found, $suffix, $precision, $width) = @_;
# Assign defaults if necessary
$precision = $default_precision
if (!defined($precision));
$suffix = "" if (!defined($suffix));
$width = 0 if (!defined($width));
return sprintf("%*s", $width, "-") if (!defined($found) || $found == 0);
my $rate = sprintf("%.*f", $precision, $hit * 100 / $found);
# Adjust rates if necessary
if ($rate == 0 && $hit > 0) {
$rate = sprintf("%.*f", $precision, 1 / 10**$precision);
} elsif ($rate == 100 && $hit != $found) {
$rate = sprintf("%.*f", $precision, 100 - 1 / 10**$precision);
}
return sprintf("%*s", $width, $rate . $suffix);
}
#
# get_overall_line(found, hit, type)
#
# Return a string containing overall information for the specified
# found/hit data.
#
sub get_overall_line($$$)
{
my ($found, $hit, $name) = @_;
return "no data found" if (!defined($found) || $found == 0);
my $plural =
($found == 1) ? "" : (('ch' eq substr($name, -2, 2)) ? 'es' : 's');
return lcovutil::rate($hit, $found, "% ($hit of $found $name$plural)");
}
# Make sure precision is within valid range [1:4]
sub check_precision()
{
die("specified precision is out of range (1 to 4)\n")
if ($default_precision < 1 || $default_precision > 4);
}
# use vanilla color palette.
sub use_vanilla_color()
{
for my $tla (('CBC', 'GNC', 'GIC', 'GBC')) {
$lcovutil::tlaColor{$tla} = "#CAD7FE";
$lcovutil::tlaTextColor{$tla} = "#98A0AA";
}
for my $tla (('UBC', 'UNC', 'UIC', 'LBC')) {
$lcovutil::tlaColor{$tla} = "#FF6230";
$lcovutil::tlaTextColor{$tla} = "#AA4020";
}
for my $tla (('EUB', 'ECB')) {
$lcovutil::tlaColor{$tla} = "#FFFFFF";
$lcovutil::tlaTextColor{$tla} = "#AAAAAA";
}
}
my $didFirstExistenceCheck;
sub fileExistenceBeforeCallbackError
{
my $filename = shift;
if ($lcovutil::check_file_existence_before_callback &&
!-e $filename) {
my $explanation =
$didFirstExistenceCheck ? '' :
' Use \'check_existence_before_callback = 0\' config file option to remove this check.';
lcovutil::ignorable_error($lcovutil::ERROR_SOURCE,
"\"$filename\" does not exist." . $explanation);
$didFirstExistenceCheck = 1;
return 1;
}
return 0;
}
# figure out what file version we see
sub extractFileVersion
{
my $filename = shift;
return undef
unless $versionCallback;
return $versionCache{$filename} if exists($versionCache{$filename});
return undef if fileExistenceBeforeCallbackError($filename);
my $start = Time::HiRes::gettimeofday();
my $version;
eval { $version = $versionCallback->extract_version($filename); };
if ($@) {
my $context = MessageContext::context();
lcovutil::ignorable_error($lcovutil::ERROR_CALLBACK,
"extract_version($filename) failed$context: $@");
}
my $end = Time::HiRes::gettimeofday();
if (exists($lcovutil::profileData{version}) &&
exists($lcovutil::profileData{version}{$filename})) {
$lcovutil::profileData{version}{$filename} += $end - $start;
} else {
$lcovutil::profileData{version}{$filename} = $end - $start;
}
$versionCache{$filename} = $version;
return $version;
}
sub checkVersionMatch
{
my ($filename, $me, $you, $reason, $silent) = @_;
return 1
if defined($me) && defined($you) && $me eq $you; # simple string compare
if ($versionCallback) {
# work harder
my $status;
eval {
$status = $versionCallback->compare_version($you, $me, $filename);
};
if ($@) {
my $context = MessageContext::context();
lcovutil::ignorable_error($lcovutil::ERROR_CALLBACK,
"compare_version($you, $me, $filename) failed$context: $@");
$status = 1;
}
lcovutil::info(1, "compare_version: $status\n");
return 1 unless $status; # match if return code was zero
}
lcovutil::ignorable_error($ERROR_VERSION,
(defined($reason) ? ($reason . ' ') : '') .
"$filename: revision control version mismatch: " .
(defined($me) ? $me : 'undef') .
' <- ' . (defined($you) ? $you : 'undef'))
unless $silent;
# claim mismatch unless $me and $you are both undef
return !(defined($me) || defined($you));
}
#
# parse_w3cdtf(date_string)
#
# Parse date string in W3CDTF format into DateTime object.
#
my $have_w3cdtf;
sub parse_w3cdtf($)
{
if (!defined($have_w3cdtf)) {
# check to see if the package is here for us to use..
$have_w3cdtf = 1;
eval {
require DateTime::Format::W3CDTF;
DateTime::Format::W3CDTF->import();
};
if ($@) {
# package not there - fall back
lcovutil::ignorable_warning($lcovutil::ERROR_PACKAGE,
'package DateTime::Format::W3CDTF is not available - falling back to local implementation'
);
$have_w3cdtf = 0;
}
}
my $str = shift;
if ($have_w3cdtf) {
return DateTime::Format::W3CDTF->parse_datetime($str);
}
my ($year, $month, $day, $hour, $min, $sec, $ns, $tz) =
(0, 1, 1, 0, 0, 0, 0, "Z");
if ($str =~ /^(\d\d\d\d)$/) {
# YYYY
$year = $1;
} elsif ($str =~ /^(\d\d\d\d)-(\d\d)$/) {
# YYYY-MM
$year = $1;
$month = $2;
} elsif ($str =~ /^(\d\d\d\d)-(\d\d)-(\d\d)$/) {
# YYYY-MM-DD
$year = $1;
$month = $2;
$day = $3;
} elsif (
$str =~ /^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d)(Z|[+-]\d\d:\d\d)?$/) {
# YYYY-MM-DDThh:mmTZD
$year = $1;
$month = $2;
$day = $3;
$hour = $4;
$min = $5;
$tz = $6 if defined($6);
} elsif ($str =~
/^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(Z|[+-]\d\d:\d\d)?$/) {
# YYYY-MM-DDThh:mm:ssTZD
$year = $1;
$month = $2;
$day = $3;
$hour = $4;
$min = $5;
$sec = $6;
$tz = $7 if (defined($7));
} elsif ($str =~
/^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)\.(\d+)(Z|[+-]\d\d:\d\d)?$/
) {
# YYYY-MM-DDThh:mm:ss.sTZD
$year = $1;
$month = $2;
$day = $3;
$hour = $4;
$min = $5;
$sec = $6;
$ns = substr($7 . "00000000", 0, 9);
$tz = $8 if (defined($8));
} else {
die("Invalid W3CDTF date format: $str\n");
}
return
DateTime->new(year => $year,
month => $month,
day => $day,
hour => $hour,
minute => $min,
second => $sec,
nanosecond => $ns,
time_zone => $tz,);
}
package HTML_fileData;
use constant {
NAME => 0,
PARENT => 1,
HREFS => 2,
ANCHORS => 3,
};
sub new
{
my ($class, $parentDir, $filename) = @_;
my $self = [$parentDir, $filename, [], {}];
my $name = File::Spec->catfile($parentDir, $filename);
open(HTML, '<', $name) or die("unable to open $name: $!");
while (<HTML>) {
if (/<(a|span) .*id=\"([^\"]+)\"/) {
lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
"\"$name\":$.: duplicate anchor '$2' original at " .
$self->[ANCHORS]->{$2} . '.')
if exists($self->[ANCHORS]->{$2});
$self->[ANCHORS]->{$2} = $.;
} elsif (/<a .*href=\"([^#\"]+)(#([^\"]+))?\"/) {
next if 'http' eq substr($1, 0, 4);
push(@{$self->[HREFS]}, [$., $1, $3]); # lineNo, filename, anchor
} elsif (/<frame .*src=\"([^\"]+)\"/) {
push(@{$self->[HREFS]}, [$., $1, $3]); # lineNo, filename, anchor
}
}
close(HTML) or die("unable to close $name: $!");
return bless $self, $class;
}
sub verifyAnchor
{
my ($self, $anchor) = @_;
return exists($self->[ANCHORS]->{$anchor});
}
sub hrefs
{
my $self = shift;
return $self->[HREFS];
}
package ValidateHTML;
sub new
{
my ($class, $topDir, $htmlExt) = @_;
my $self = {};
$htmlExt = '.html' unless defined($htmlExt);
my @dirstack = ($topDir);
my %visited;
while (@dirstack) {
my $top = pop(@dirstack);
die("unexpected link $top") if -l $top;
opendir(my $dh, $top) or die("can't open directory $top: $!");
while (my $e = readdir($dh)) {
next if $e eq '.' || $e eq '..';
my $p = File::Spec->catfile($top, $e);
die("unexpected link $p") if -l $p;
if (-d $p) {
die("already visited $p") if exists($visited{$p});
$visited{$p} = [$top, $e];
push(@dirstack, $p);
} elsif (-f $p &&
$p =~ /.+$htmlExt$/) {
die("duplicate file $p??") if exists($self->{$p});
lcovutil::info(1, "schedule $p\n");
$self->{$p} = HTML_fileData->new($top, $e);
}
}
closedir($dh);
}
my %fileReferred;
while (my ($filename, $data) = each(%$self)) {
my $dir = File::Basename::dirname($filename);
lcovutil::info(1, "verify $filename:\n");
foreach my $href (@{$data->hrefs()}) {
my ($lineNo, $link, $anchor) = @$href;
my $path = File::Spec->catfile($dir, $link);
$path = File::Spec->abs2rel(Cwd::realpath($path), $main::cwd)
unless exists($self->{$path});
lcovutil::info(1,
" $lineNo: $link" . ($anchor ? "#$anchor" : '') . "\n");
unless (exists($self->{$path})) {
lcovutil::ignorable_error($lcovutil::ERROR_PATH,
"\"$filename\":$lineNo: non-existent file '$link'.");
next;
}
if (exists($fileReferred{$path})) {
# keep only one use
push(@{$fileReferred{$path}}, $filename)
if ($fileReferred{$path}->[-1] ne $filename);
} else {
$fileReferred{$path} = [$filename];
}
if (defined($anchor)) {
my $a = $self->{$path};
unless ($a->verifyAnchor($anchor)) {
lcovutil::ignorable_error($lcovutil::ERROR_PATH,
"\"$filename\":$lineNo: \"$link#$anchor\" doesn't point to valid anchor."
);
}
}
}
}
while (my ($filename, $data) = each(%$self)) {
lcovutil::ignorable_error($lcovutil::ERROR_UNUSED,
"HTML file \"$filename\" is not referenced.")
unless (exists($fileReferred{$filename}) ||
($topDir eq File::Basename::dirname($filename) &&
"index$htmlExt" eq File::Basename::basename($filename)));
}
return bless $self, $class;
}
package CoverageCriteria;
our @coverageCriteriaScript;
our $criteriaCallback;
our %coverageCriteria; # hash of name->(type, success 0/1, string)
our $coverageCriteriaStatus = 0; # set to non-zero if we see any errors
our @criteriaCallbackTypes; # include date, owner bin info
our @criteriaCallbackLevels; # call back at (top, directory, file) levels
sub executeCallback
{
my ($type, $name, $data) = @_;
my ($status, $msgs);
eval {
($status, $msgs) =
$criteriaCallback->check_criteria($name, $type, $data);
};
if ($@) {
my $context = MessageContext::context();
lcovutil::ignorable_error($lcovutil::ERROR_CALLBACK,
"check_criteria failed$context: $@");
$status = 2;
$msgs = [$@];
}
$coverageCriteria{$name} = [$type, $status, $msgs]
if (0 != $status ||
(defined $msgs &&
0 != scalar(@$msgs)));
$coverageCriteriaStatus = $status
if $status != 0;
}
sub check_failUnder
{
my $info = shift;
my $msg = $info->check_fail_under_criteria();
if ($msg) {
$coverageCriteriaStatus |= 1;
$coverageCriteria{'top'} = ['top', 1, [$msg]];
}
}
sub summarize
{
# print the criteria summary to stdout:
# all criteria fails + any non-empty messages
# In addition: print fails to stderr
# This way: Jenkins script can log failure if stderr is not empty
my $leader = '';
if ($coverageCriteriaStatus != 0) {
print("Failed coverage criteria:\n");
} else {
$leader = "Coverage criteria:\n";
}
# sort to print top-level report first, then directories, then files.
foreach my $name (sort({
my $da = $coverageCriteria{$a};
my $db = $coverageCriteria{$b};
my $ta = $da->[0];
my $tb = $db->[0];
return -1 if ($ta eq 'top');
return 1 if ($tb eq 'top');
if ($ta ne $tb) {
return $ta eq 'file' ? 1 : -1;
}
$a cmp $b
}
keys(%coverageCriteria))
) {
my $criteria = $coverageCriteria{$name};
my $v = $criteria->[1];
next if (!$v || $v == 0) && 0 == scalar(@{$criteria->[2]}); # passed
my $msg = $criteria->[0];
if ($criteria->[0] ne 'top') {
$msg .= " \"" . $name . "\"";
}
$msg .= ": \"" . join(' ', @{$criteria->[2]}) . "\"\n";
print($leader);
$leader = '';
print(" " . $msg);
if (0 != $criteria->[1]) {
print(STDERR $msg);
}
}
}
package MessageContext;
our @message_context;
sub new
{
my ($class, $str) = @_;
push(@message_context, $str);
my $self = [$str];
return bless $self, $class;
}
sub context
{
my $context = join(' while ', @message_context);
$context = ' while ' . $context if $context;
return $context;
}
sub DESTROY
{
my $self = shift;
die('unbalanced context "' . $self->[0] . '" not head of ("' .
join('" "', @message_context) . '")')
unless scalar(@message_context) && $self->[0] eq $message_context[-1];
pop(@message_context);
}
package PipeHelper;
sub new
{
my $class = shift;
my $reason = shift;
# backward compatibility: see if the arguments were passed in a
# one long string
my $args = \@_;
my $arglen = 'criteria' eq $reason ? 4 : 2;
if ($arglen == scalar(@_) && !-e $_[0]) {
# two arguments: a string (which seems not to be executable) and the
# file we are acting on
# After next release, issue 'deprecated' warning here.
my @args = split(' ', $_[0]);
push(@args, splice(@_, 1)); # append the rest of the args
$args = \@args;
}
my $self = [$reason, join(' ', @$args)];
bless $self, $class;
if (open(PIPE, "-|", @$args)) {
push(@$self, \*PIPE);
} else {
lcovutil::ignorable_error($lcovutil::ERROR_CALLBACK,
"$reason: 'open(-| " . $self->[1] . ")' failed: \"$!\"");
return undef;
}
return $self;
}
sub next
{
my $self = shift;
die("no handle") unless scalar(@$self) == 3;
my $hdl = $self->[2];
return scalar <$hdl>;
}
sub close
{
# close pipe and return exit status
my ($self, $checkError) = @_;
close($self->[2]);
if (0 != $? && $checkError) {
# $reason: $cmd returned non-zero exit...
lcovutil::ignorable_error($lcovutil::ERROR_CALLBACK,
$self->[0] . ' \'' . $self->[1] .
"\' returned non-zero exit code: '$!'");
}
pop(@$self);
return $?;
}
sub DESTROY
{
my $self = shift;
# FD can be undef if 'open' failed for any reason (e.g., filesystem issues)
# otherwise: don't close if FD was STDIN or STDOUT
CORE::close($self->[2])
if 3 == scalar(@$self);
}
package ScriptCaller;
sub new
{
my $class = shift;
my $self = [@_];
return bless $self, $class;
}
sub call
{
my ($self, $reason, @args) = @_;
my $cmd = join(' ', @$self) . ' ' . join(' ', @args);
lcovutil::info(1, "$reason: \"$cmd\"\n");
my $rtn = `$cmd`;
return $?;
}
sub pipe
{
my $self = shift;
my $reason = shift;
return PipeHelper->new($reason, @$self, @_);
}
sub context
{
my $self = shift;
lcovutil::info(1, 'context ' . join(' ', @$self) . "\n");
my $iter = $self->pipe('context');
return unless defined($iter);
my %context;
while (my $line = $iter->next()) {
chomp($line);
$line =~ s/\r//g; # remove CR from line-end
# first word on line is the key..
my ($key, $value) = split(/ +/, $line, 2);
if (exists($context{key})) {
$context{key} .= "\n" . $value;
} else {
$context{key} = $value;
}
}
my $status = $iter->close(1); # check error return
return \%context;
}
sub extract_version
{
my ($self, $filename) = @_;
my $version;
my $pipe = $self->pipe('extract_version', $filename);
if (defined $pipe &&
($version = $pipe->next())) {
chomp($version);
$version =~ s/\r//;
lcovutil::info(1, " version: $version\n");
}
return $version;
}
sub resolve
{
my ($self, $filename) = @_;
my $path;
my $pipe = $self->pipe('resolve_filename', $filename);
if ($pipe &&
($path = $pipe->next())) {
chomp($path);
$path =~ s/\r//;
lcovutil::info(1, " resolve: $path\n");
}
return $path;
}
sub compare_version
{
my ($self, $yours, $mine, $file) = @_;
return
$self->call('compare_version', '--compare',
"'$yours'", "'$mine'",
"'$file'");
}
# annotate callback is passed filename (as munged) -
# should return reference to array of line data,
# line data of the form list of:
# source_text: the content on that line
# abbreviated author name: (must be set to something - possibly NONE
# full author name: some string or undef
# date string: when this line was last changed
# commit ID: something meaningful to you
sub annotate
{
my ($self, $filename) = @_;
lcovutil::info(1, 'annotate ' . join(' ', @$self) . ' ' . $filename . "\n");
my $iter = $self->pipe('annotate', $filename);
return unless defined($iter);
my @lines;
while (my $line = $iter->next()) {
chomp $line;
$line =~ s/\r//g; # remove CR from line-end
my ($commit, $author, $when, $text) = split(/\|/, $line, 4);
# semicolon is not a legal character in email address -
# so we use that to delimit the 'abbreviated name' and
# the 'full name' - in case they are different.
# this is an attempt to be backward-compatible with
# existing annotation scripts which return only one name
my ($abbrev, $full) = split(/;/, $author, 2);
push(@lines, [$text, $abbrev, $full, $when, $commit]);
}
my $status = $iter->close();
return ($status, \@lines);
}
sub check_criteria
{
my ($self, $name, $type, $data) = @_;
my $iter =
$self->pipe('criteria', $name, $type, JsonSupport::encode($data));
return (0) unless $iter; # constructor will have given error message
my @messages;
while (my $line = $iter->next()) {
chomp $line;
$line =~ s/\r//g; # remove CR from line-end
next if '' eq $line;
push(@messages, $line);
}
return ($iter->close(), \@messages);
}
sub select
{
my ($self, $lineData, $annotateData, $filename, $lineNo) = @_;
my @params = ('select',
defined($lineData) ?
JsonSupport::encode($lineData->to_list()) : '',
defined($annotateData) ?
JsonSupport::encode($annotateData->to_list()) : '',
$filename,
$lineNo);
return $self->call(@params);
}
package JsonSupport;
our $rc_json_module = 'auto';
our $did_init;
#
# load_json_module(rc)
#
# If RC is "auto", load best available JSON module from a list of alternatives,
# otherwise load the module specified by RC.
#
sub load_json_module($)
{
my ($rc) = shift;
# List of alternative JSON modules to try
my @alternatives = ("JSON::XS", # Fast, but not always installed
"Cpanel::JSON::XS", # Fast, a more recent fork
"JSON::PP", # Slow, part of core-modules
"JSON", # Not available in all distributions
);
# Determine JSON module
if (lc($rc) eq "auto") {
for my $m (@alternatives) {
if (Module::Load::Conditional::check_install(module => $m)) {
$did_init = $m;
last;
}
}
if (!defined($did_init)) {
die("No Perl JSON module found on your system. Please install of of the following supported modules: "
. join(" ", @alternatives)
. " - for example (as root):\n \$ perl -MCPAN -e 'install "
. $alternatives[0]
. "'\n");
}
} else {
$did_init = $rc;
}
eval "use $did_init qw(encode_json decode_json);";
if ($@) {
die("Module is not installed: " . "'$did_init':$@\n");
}
lcovutil::info(1, "Using JSON module $did_init\n");
my ($index) =
grep { $alternatives[$_] eq $did_init } (0 .. @alternatives - 1);
warn(
"using JSON module \"$did_init\" - which is much slower than some alternatives. Consider installing one of "
. join(" or ", @alternatives[0 .. $index - 1]))
if (defined($index) && $index > 1);
}
sub encode($)
{
my $data = shift;
load_json_module($rc_json_module)
unless defined($did_init);
return encode_json($data);
}
sub decode($)
{
my $text = shift;
load_json_module($rc_json_module)
unless defined($did_init);
return decode_json($text);
}
sub load($)
{
my $filename = shift;
my $f = InOutFile->in($filename);
my $h = $f->hdl();
my @lines = <$h>;
return decode(join("\n", @lines));
}
package InOutFile;
our $checkedGzipAvail;
sub checkGzip
{
# Check for availability of GZIP tool
lcovutil::system_no_output(1, "gzip", "-h") and
die("gzip command not available!\n");
$checkedGzipAvail = 1;
}
sub out
{
my ($class, $f, $mode, $demangle) = @_;
$demangle = 0 unless defined($demangle);
my $self = [undef, $f];
bless $self, $class;
my $m = (defined($mode) && $mode eq 'append') ? ">>" : ">";
if (!defined($f) ||
'-' eq $f) {
if ($demangle) {
open(HANDLE, '|-', $lcovutil::demangle_cpp_cmd) or
die("unable to demangle: $!\n");
$self->[0] = \*HANDLE;
} else {
$self->[0] = \*STDOUT;
}
} else {
my $cmd = $demangle ? "$lcovutil::demangle_cpp_cmd " : '';
if ($f =~ /\.gz$/) {
checkGzip()
unless defined($checkedGzipAvail);
$cmd .= '| ' if $cmd;
# Open compressed file
$cmd .= "gzip -c $m'$f'";
open(HANDLE, "|-", $cmd) or
die("cannot start gzip to compress to file $f: $!\n");
} else {
if ($demangle) {
$cmd .= "$m '$f'";
} else {
$cmd .= $f;
}
open(HANDLE, $demangle ? '|-' : $m, $cmd) or
die("cannot write to $f: $!\n");
}
$self->[0] = \*HANDLE;
}
return $self;
}
sub in
{
my ($class, $f, $demangle) = @_;
$demangle = 0 unless defined($demangle);
my $self = [undef, $f];
bless $self, $class;
if (!defined($f) ||
'-' eq $f) {
$self->[0] = \*STDIN;
} else {
if ($f =~ /\.gz$/) {
checkGzip()
unless defined($checkedGzipAvail);
die("file '$f' does not exist\n")
unless -f $f;
die("'$f': unsupported empty gzipped file\n")
if (-z $f);
# Check integrity of compressed file - fails for zero size file
lcovutil::system_no_output(1, "gzip", "-dt", $f) and
die("integrity check failed for compressed file $f!\n");
# Open compressed file
my $cmd = "gzip -cd '$f'";
$cmd .= " | " . $lcovutil::demangle_cpp_cmd
if ($demangle);
open(HANDLE, "-|", $cmd) or
die("cannot start gunzip to decompress file $f: $!\n");
} elsif ($demangle &&
defined($lcovutil::demangle_cpp_cmd)) {
open(HANDLE, "-|", "cat '$f' | $lcovutil::demangle_cpp_cmd") or
die("cannot start demangler for file $f: $!\n");
} else {
# Open decompressed file
open(HANDLE, "<", $f) or
die("cannot read file $f: $!\n");
}
$self->[0] = \*HANDLE;
}
return $self;
}
sub DESTROY
{
my $self = shift;
# FD can be undef if 'open' failed for any reason (e.g., filesystem issues)
# otherwise: don't close if FD was STDIN or STDOUT
close($self->[0])
unless !defined($self->[1]) ||
'-' eq $self->[1] ||
!defined($self->[0]);
}
sub hdl
{
my $self = shift;
return $self->[0];
}
package SearchPath;
sub new
{
my $class = shift;
my $option = shift;
my $self = [];
bless $self, $class;
foreach my $p (@_) {
if (-d $p) {
push(@$self, [$p, 0]);
} else {
lcovutil::ignorable_error($lcovutil::ERROR_PATH,
"$option '$p' is not a directory");
}
}
return $self;
}
sub patterns
{
my $self = shift;
return $self;
}
sub resolve
{
my ($self, $filename, $applySubstitutions) = @_;
$filename = lcovutil::subst_file_name($filename) if $applySubstitutions;
return $filename if -e $filename;
if (!File::Spec->file_name_is_absolute($filename)) {
foreach my $d (@$self) {
my $path = File::Spec->catfile($d->[0], $filename);
if (-e $path) {
lcovutil::info(1, "found $filename at $path\n");
++$d->[1];
return $path;
}
}
}
return resolveCallback($filename, 0);
}
sub resolveCallback
{
my ($filename, $applySubstitutions, $returnCbValue) = @_;
$filename = lcovutil::subst_file_name($filename) if $applySubstitutions;
if ($lcovutil::resolveCallback) {
return $lcovutil::resolveCache{$filename}
if exists($lcovutil::resolveCache{$filename});
my $start = Time::HiRes::gettimeofday();
my $path;
eval { $path = $resolveCallback->resolve($filename); };
if ($@) {
my $context = MessageContext::context();
lcovutil::ignorable_error($lcovutil::ERROR_CALLBACK,
"resolve($filename) failed$context: $@");
}
# look up particular path at most once...
$lcovutil::resolveCache{$filename} = $path if $path;
my $cost = Time::HiRes::gettimeofday() - $start;
if (!$returnCbValue) {
$path = $filename unless $path;
}
my $p = $path ? $path : $filename;
if (exists($lcovutil::profileData{resolve}) &&
exists($lcovutil::profileData{resolve}{$p})) {
# might see multiple aliases for the same source file
$lcovutil::profileData{resolve}{$p} += $cost;
} else {
$lcovutil::profileData{resolve}{$p} = $cost;
}
return $path;
}
return $filename;
}
sub warn_unused
{
my ($self, $optName) = @_;
foreach my $d (@$self) {
my $name = $d->[0];
$name = "'$name'" if $name =~ /\s/;
if (0 == $d->[1]) {
lcovutil::ignorable_error($lcovutil::ERROR_UNUSED,
"\"$optName $name\" is unused.");
} else {
lcovutil::info(1,
"\"$optName $name\" used " . $d->[1] . " times\n");
}
}
}
sub reset
{
my $self = shift;
foreach my $d (@$self) {
$d->[1] = 0;
}
}
sub current_count
{
my $self = shift;
my @rtn;
foreach my $d (@$self) {
push(@rtn, $d->[1]);
}
return \@rtn;
}
sub update_count
{
my $self = shift;
die("invalid update count: " . scalar(@$self) . ' ' . scalar(@_))
unless ($#$self == $#_);
foreach my $d (@$self) {
$d->[1] += shift;
}
}
package MapData;
sub new
{
my $class = shift;
my $self = {};
bless $self, $class;
return $self;
}
sub is_empty
{
my $self = shift;
return 0 == scalar(keys %$self);
}
sub append_if_unset
{
my $self = shift;
my $key = shift;
my $data = shift;
if (!defined($self->{$key})) {
$self->{$key} = $data;
}
return $self;
}
sub replace
{
my $self = shift;
my $key = shift;
my $data = shift;
$self->{$key} = $data;
return $self;
}
sub value
{
my $self = shift;
my $key = shift;
if (!exists($self->{$key})) {
return undef;
}
return $self->{$key};
}
sub remove
{
my ($self, $key, $check_is_present) = @_;
if (!defined($check_is_present) || exists($self->{$key})) {
delete $self->{$key};
return 1;
}
return 0;
}
sub mapped
{
my $self = shift;
my $key = shift;
return defined($self->{$key}) ? 1 : 0;
}
sub keylist
{
my $self = shift;
return keys(%$self);
}
sub entries
{
my $self = shift;
return scalar(keys(%$self));
}
# Class definitions
package CountData;
our $UNSORTED = 0;
our $SORTED = 1;
use constant {
HASH => 0,
SORTABLE => 1,
FOUND => 2,
HIT => 3,
FILENAME => 4,
};
sub new
{
my $class = shift;
my $filename = shift;
my $sortable = defined($_[0]) ? shift : $UNSORTED;
my $self = [{},
$sortable,
0, # found
0, # hit
$filename, # for error messaging
];
bless $self, $class;
return $self;
}
sub filename
{
my $self = shift;
return $self->[FILENAME];
}
sub append
{
# return 1 if we hit something new, 0 if not (count was already non-zero)
# using $suppressErrMsg to avoid reporting same thing for bot the
# 'testcase' entry and the 'summary' entry
my ($self, $key, $count, $suppressErrMsg) = @_;
my $changed = 0; # hit something new or not
if (!Scalar::Util::looks_like_number($count)) {
lcovutil::report_format_error($lcovutil::ERROR_FORMAT, 'hit', $count,
'line "' . $self->filename() . ":$key\"")
unless $suppressErrMsg;
$count = 0;
} elsif ($count < 0) {
lcovutil::report_format_error($lcovutil::ERROR_NEGATIVE,
'hit',
$count,
'line ' . $self->filename() . ":$key\""
) unless $suppressErrMsg;
$count = 0;
} elsif (defined($lcovutil::excessive_count_threshold) &&
$count > $lcovutil::excessive_count_threshold) {
lcovutil::report_format_error($lcovutil::ERROR_EXCESSIVE_COUNT,
'hit',
$count,
'line ' . $self->filename() . ":$key\""
) unless $suppressErrMsg;
}
my $data = $self->[HASH];
if (!exists($data->{$key})) {
$changed = 1; # something new - whether we hit it or not
$data->{$key} = $count;
++$self->[FOUND]; # found
++$self->[HIT] if ($count > 0); # hit
} else {
my $current = $data->{$key};
if ($count > 0 &&
$current == 0) {
++$self->[HIT];
$changed = 1;
}
$data->{$key} = $count + $current;
}
return $changed;
}
sub value
{
my $self = shift;
my $key = shift;
my $data = $self->[HASH];
if (!exists($data->{$key})) {
return undef;
}
return $data->{$key};
}
sub remove
{
my ($self, $key, $check_if_present) = @_;
my $data = $self->[HASH];
if (!defined($check_if_present) ||
exists($data->{$key})) {
die("$key not found")
unless exists($data->{$key});
--$self->[FOUND]; # found;
--$self->[HIT] # hit
if ($data->{$key} > 0);
delete $data->{$key};
return 1;
}
return 0;
}
sub found
{
my $self = shift;
return $self->[FOUND];
}
sub hit
{
my $self = shift;
return $self->[HIT];
}
sub keylist
{
my $self = shift;
return keys(%{$self->[HASH]});
}
sub entries
{
my $self = shift;
return scalar(keys(%{$self->[HASH]}));
}
sub union
{
my $self = shift;
my $info = shift;
my $changed = 0;
foreach my $key ($info->keylist()) {
if ($self->append($key, $info->value($key))) {
$changed = 1;
}
}
return $changed;
}
sub intersect
{
my $self = shift;
my $you = shift;
my $changed = 0;
my $yourData = $you->[HASH];
foreach my $key ($self->keylist()) {
if (exists($yourData->{$key})) {
# append your count to mine
if ($self->append($key, $you->value($key))) {
# returns true if appended count was not zero
$changed = 1;
}
} else {
$self->remove($key);
$changed = 1;
}
}
return $changed;
}
sub difference
{
my $self = shift;
my $you = shift;
my $changed = 0;
my $yourData = $you->[HASH];
foreach my $key ($self->keylist()) {
if (exists($yourData->{$key})) {
$self->remove($key);
$changed = 1;
}
}
return $changed;
}
#
# get_found_and_hit(hash)
#
# Return the count for entries (found) and entries with an execution count
# greater than zero (hit) in a hash (linenumber -> execution count) as
# a list (found, hit)
#
sub get_found_and_hit
{
my $self = shift;
return ($self->[FOUND], $self->[HIT]);
}
package BranchBlock;
# branch element: index, taken/not-taken count, optional expression
# for baseline or current data, 'taken' is just a number (or '-')
# for differential data: 'taken' is an array [$taken, tla]
use constant {
ID => 0,
TAKEN => 1,
EXPR => 2,
EXCEPTION => 3,
};
sub new
{
my ($class, $id, $taken, $expr, $is_exception) = @_;
# if branchID is not an expression - go back to legacy behaviour
my $self = [$id, $taken,
(defined($expr) && $expr eq $id) ? undef : $expr,
defined($is_exception) && $is_exception ? 1 : 0
];
bless $self, $class;
my $c = $self->count();
if (!Scalar::Util::looks_like_number($c)) {
lcovutil::report_format_error($lcovutil::ERROR_FORMAT,
'taken', $c, 'branch ' . $self->id());
$self->[TAKEN] = 0;
} elsif ($c < 0) {
lcovutil::report_format_error($lcovutil::ERROR_NEGATIVE,
'taken', $c, 'branch ' . $self->id());
$self->[TAKEN] = 0;
} elsif (defined($lcovutil::excessive_count_threshold) &&
$c > $lcovutil::excessive_count_threshold) {
lcovutil::report_format_error($lcovutil::ERROR_EXCESSIVE_COUNT,
'taken', $c, 'branch ' . $self->id());
}
return $self;
}
sub isTaken
{
my $self = shift;
return $self->[TAKEN] ne '-';
}
sub id
{
my $self = shift;
return $self->[ID];
}
sub data
{
my $self = shift;
return $self->[TAKEN];
}
sub count
{
my $self = shift;
return $self->[TAKEN] eq '-' ? 0 : $self->[TAKEN];
}
sub expr
{
my $self = shift;
return $self->[EXPR];
}
sub exprString
{
my $self = shift;
my $e = $self->[EXPR];
return defined($e) ? $e : 'undef';
}
sub is_exception
{
my $self = shift;
return $self->[EXCEPTION];
}
sub merge
{
# return 1 if something changed, 0 if nothing new covered or discovered
my ($self, $that, $filename, $line) = @_;
# should have called 'iscompatible' first
die('attempt to merge incompatible expressions for id' .
$self->id() . ', ' . $that->id() .
": '" . $self->exprString() . "' -> '" . $that->exprString() . "'")
if ($self->exprString() ne $that->exprString());
if ($self->is_exception() != $that->is_exception()) {
my $loc = defined($filename) ? "\"$filename\":$line: " : '';
lcovutil::ignorable_error($lcovutil::ERROR_MISMATCH,
"${loc}mismatched exception tag for id " .
$self->id() . ", " . $that->id() .
": '" . $self->is_exception() .
"' -> '" . $that->is_exception() . "'");
# set 'self' to 'not related to exception' - to give a consistent
# answer for the merge operation. Otherwise, we pick whatever
# was seen first - which is unpredictable during threaded execution.
$self->[EXCEPTION] = 0;
}
my $t = $that->[TAKEN];
return 0 if $t eq '-'; # no new news
my $count = $self->[TAKEN];
my $changed;
if ($count ne '-') {
$count += $t;
$changed = $count == 0 && $t != 0;
} else {
$count = $t;
$changed = $t != 0;
}
$self->[TAKEN] = $count;
return $changed;
}
package BranchEntry;
# hash of blockID -> array of BranchBlock refs for each sequential branch ID
sub new
{
my ($class, $line) = @_;
my $self = [$line, {}];
bless $self, $class;
return $self;
}
sub line
{
my $self = shift;
return $self->[0];
}
sub hasBlock
{
my ($self, $id) = @_;
return exists($self->[1]->{$id});
}
sub removeBlock
{
my ($self, $id, $branchData) = @_;
$self->hasBlock($id) or die("unknown block $id");
# remove list of branches and adjust counts
$branchData->removeBranches($self->[1]->{$id});
delete($self->[1]->{$id});
}
sub getBlock
{
my ($self, $id) = @_;
$self->hasBlock($id) or die("unknown block $id");
return $self->[1]->{$id};
}
sub blocks
{
my $self = shift;
return keys %{$self->[1]};
}
sub addBlock
{
my ($self, $blockId) = @_;
!exists($self->[1]->{$blockId}) or die "duplicate block $blockId";
my $blockData = [];
$self->[1]->{$blockId} = $blockData;
return $blockData;
}
sub totals
{
my $self = shift;
# return (found, hit) counts of coverpoints in this entry
my $found = 0;
my $hit = 0;
foreach my $blockId ($self->blocks()) {
my $bdata = $self->getBlock($blockId);
foreach my $br (@$bdata) {
my $count = $br->count();
++$found;
++$hit if (0 != $count);
}
}
return ($found, $hit);
}
package MCDC_Block;
# there may be more than one MCDC groups on a particular line -
# we hold the groups in a hash, keyed by size (number of MCDC_expressions)
# The particular group is a sorted list
use constant {
LINE => 0,
GROUPS => 1,
};
sub new
{
my ($class, $line) = @_;
my $self = [$line, {}];
return bless $self, $class;
}
sub insertExpr
{
my ($self, $filename, $groupSize, $sense, $count, $idx, $expr) = @_;
my $groups = $self->[GROUPS];
my $group;
if (exists($groups->{$groupSize})) {
$group = $groups->{$groupSize};
} else {
$group = [];
$groups->{$groupSize} = $group;
}
my $cond;
if ($idx < scalar(@$group)) {
$cond = $group->[$idx];
if ($cond->expression() ne $expr) {
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
"\"$filename\":" . $self->line() .
": MC/DC group $groupSize expression $idx changed from '" .
$cond->expression() . "' to '$expr'");
}
} else {
if ($idx != scalar(@$group)) {
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$filename\":" . '":' . $self->line() .
": MC/DC group $groupSize: non-contiguous expression '$idx' found - should be '"
. scalar(@$group)
. "'.");
}
$cond = MCDC_Expression->new($self, $groupSize, $idx, $expr);
push(@$group, $cond);
}
$cond->set($sense, $count);
}
sub line
{
return $_[0]->[LINE];
}
sub totals
{
my $self = shift;
my $found = 0;
my $hit = 0;
while (my ($size, $group) = each(%{$self->groups()})) {
foreach my $expr (@$group) {
foreach my $sense (0, 1) {
my $count = $expr->count($sense);
if ('ARRAY' eq ref($count)) {
# differential number - report 'current'
next unless defined($count->[2]); # not in current
$count = $count->[2];
}
++$found;
++$hit if 0 != $count;
}
}
}
return ($found, $hit);
}
sub groups
{
return $_[0]->[GROUPS];
}
sub num_groups
{
return scalar(keys %{$_[0]->[GROUPS]});
}
sub expressions
{
my ($self, $size) = @_;
return exists($self->[GROUPS]->{$size}) ? $self->[GROUPS]->{$size} : undef;
}
sub expr
{
my ($self, $groupSize, $idx) = @_;
return $self->[GROUPS]->{$groupSize}->[$idx];
}
sub is_compatible
{
my ($self, $you) = @_;
my $yours = $you->groups();
my $groups = $self->groups();
foreach my $size (keys %$groups) {
next unless exists($yours->{$size});
my $idx = 0;
my $m = $groups->{$size};
my $y = $yours->{$size};
foreach my $e (@$m) {
my $ye = $y->[$idx++];
return 0 if $e->expression() ne $ye->expression();
}
}
return 1;
}
sub merge
{
# merge all groups from you into me
my ($self, $you) = @_;
my $mine = $self->groups();
my $yours = $you->groups();
my $changed = 0;
while (my ($size, $group) = each(%$yours)) {
if (exists($mine->{$size})) {
my $m = $mine->{$size};
my $idx = 0;
foreach my $e (@$m) {
my $y = $group->[$idx++];
$changed += $e->set(1, $y->count(1));
$changed += $e->set(0, $y->count(0));
}
} else {
$mine->{$size} = Storable::dclone($group);
$changed = 1;
}
}
return $changed;
}
package MCDC_Expression;
use constant {
PARENT => 0, # MCDC_BLOCK
GROUP_SIZE => 1, # which group in parent
INDEX => 2, # index of this expression
EXPRESSION => 3,
TRUE => 4, # hit count of sensitization of 'true' sense of expr
FALSE => 5, # hit count of sensitization of 'false' sense of expr
};
sub new
{
my ($class, $parent, $groupSize, $idx, $expr) = @_;
my $self = [$parent, $groupSize, $idx, $expr, 0, 0];
return bless $self, $class;
}
sub set
{
# 'sense' should be 0 or 1 - for 'false' and 'true' sense, respectively
my ($self, $sense, $count) = @_;
return 0 if 0 == $count;
if ('ARRAY' eq ref($count)) {
# recording a differential result
$self->[$sense ? TRUE : FALSE] = $count;
return 1; # assumed changed
}
my $changed = $count && $self->count($sense) == 0;
$self->[$sense ? TRUE : FALSE] += $count;
return $changed;
}
sub parent
{
return $_[0]->[PARENT];
}
sub groupSize
{
return $_[0]->[GROUP_SIZE];
}
sub index
{
return $_[0]->[INDEX];
}
sub expression
{
return $_[0]->[EXPRESSION];
}
sub count
{
my ($self, $sense) = @_;
return $_[0]->[$sense ? TRUE : FALSE];
}
package FunctionEntry;
# keep track of all the functions/all the function aliases
# at a particular line in the file. THey must all be the
# same function - perhaps just templatized differently.
use constant {
NAME => 0,
ALIASES => 1,
MAP => 2,
FIRST => 3, # start line
COUNT => 4,
LAST => 5,
};
sub new
{
my ($class, $name, $map, $startLine, $endLine) = @_;
die("unexpected type " . ref($map)) unless 'FunctionMap' eq ref($map);
my %aliases = ($name => 0); # not hit, yet
my $self = [$name, \%aliases, $map, $startLine, 0, $endLine];
bless $self, $class;
return $self;
}
sub cloneWithEndLine
{
my ($self, $withEnd, $cloneAliases) = @_;
my $fn = FunctionEntry->new($self->[NAME], $self->[MAP], $self->[FIRST],
$withEnd ? $self->[LAST] : undef);
if ($cloneAliases) {
my $count = 0;
while (my ($alias, $hit) = each(%{$self->aliases()})) {
$fn->[ALIASES]->{$alias} = $hit;
$count += $hit;
}
$fn->[COUNT] = $count;
}
return $fn;
}
sub name
{
my $self = shift;
return $self->[NAME];
}
sub filename
{
my $self = shift;
return $self->[MAP]->filename();
}
sub hit
{
# this is the hit count across all the aliases of the function
my $self = shift;
return $self->[COUNT];
}
sub isLambda
{
my $self = shift;
# jacoco may show both a lambda and a function on the same line - which
# lcov then associates as an alias
# alias name selection above ensures that the 'master' name is lambda
# only if every alias is a lambda.
# -> this is a lambda only if there is only one alias
return ((TraceFile::is_language('c', $self->filename()) &&
$self->name() =~ /{lambda\(/) ||
(TraceFile::is_language('java', $self->filename()) &&
$self->name() =~ /\.lambda\$/));
}
sub count
{
my ($self, $alias, $merged) = @_;
exists($self->aliases()->{$alias}) or
die("$alias is not an alias of " . $self->name());
return $self->[COUNT]
if (defined($merged) && $merged);
return $self->aliases()->{$alias};
}
sub aliases
{
my $self = shift;
return $self->[ALIASES];
}
sub numAliases
{
my $self = shift;
return scalar(keys %{$self->[ALIASES]});
}
sub file
{
my $self = shift;
return $self->[MAP]->filename();
}
sub line
{
my $self = shift;
return $self->[FIRST];
}
sub set_line
{
my ($self, $line) = @_;
return $self->[FIRST] = $line;
}
sub end_line
{
my $self = shift;
return $self->[LAST];
}
sub set_end_line
{
my ($self, $line) = @_;
if ($line < $self->line()) {
my $suffix =
lcovutil::explain_once('derive_end_line',
" See lcovrc man entry for 'derive_function_end_line'.");
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $self->file() . '":' . $self->line() .
': function ' . $self->name() .
" end line $line less than start line " .
$self->line() .
". Cannot derive function end line.$suffix"
);
return;
}
$self->[LAST] = $line;
}
sub _format_error
{
my ($self, $errno, $name, $count) = @_;
my $alias =
$name ne $self->name() ? " (alias of '" . $self->name() . "'" : "";
lcovutil::report_format_error($errno, 'hit', $count,
"function '$name'$alias in " . $self->file() . ':' . $self->line());
}
sub addAlias
{
my ($self, $name, $count) = @_;
if (!Scalar::Util::looks_like_number($count)) {
$self->_format_error($lcovutil::ERROR_FORMAT, $name, $count);
$count = 0;
} elsif ($count < 0) {
$self->_format_error($lcovutil::ERROR_NEGATIVE, $name, $count);
$count = 0;
} elsif (defined($lcovutil::excessive_count_threshold) &&
$count > $lcovutil::excessive_count_threshold) {
$self->_format_error($lcovutil::ERROR_EXCESSIVE_COUNT, $name, $count)
unless grep({ $name =~ $_ || $self->name() =~ $_ }
@lcovutil::suppress_function_patterns);
}
my $changed;
my $aliases = $self->[ALIASES];
if (exists($aliases->{$name})) {
$changed = 0 == $aliases->{$name} && 0 != $count;
$aliases->{$name} += $count;
} else {
$aliases->{$name} = $count;
$changed = 1;
# keep track of the shortest name as the function representative
my $curlen = length($self->[NAME]);
my $len = length($name);
# penalize lambda functions so that their name is not chosen
# (java workaround or ugly hack, depending on your perspective)
$curlen += 1000 if $self->[NAME] =~ /(\{lambda\(|\.lambda\$)/;
$len += 1000 if $name =~ /(\{lambda\(|\.lambda\$)/;
$self->[NAME] = $name
if ($len < $curlen || # alias is shorter
($len == $curlen && # alias is same length but lexically first
$name lt $self->[NAME]));
}
$self->[COUNT] += $count;
# perhaps should remove lambda aliases, if they exist -
# - Issue is that jacoco will show normal function and lambda on the
# same line - which lcov takes to mean that they are aliases
# could just delete the lambda in that case..pretend it doesn't exist.
return $changed;
}
sub merge
{
my ($self, $that) = @_;
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
$self->name() . " has different location than " .
$that->name() . " during merge")
if ($self->line() != $self->line());
while (my ($name, $count) = each(%{$that->[ALIASES]})) {
$self->addAlias($name, $count);
}
}
sub removeAliases
{
my $self = shift;
my $aliases = $self->[ALIASES];
my $rename = 0;
foreach my $name (@_) {
exists($aliases->{$name}) or die("removing non-existent alias $name");
my $count = $aliases->{$name};
delete($aliases->{$name});
$self->[COUNT] -= $count;
if ($self->[NAME] eq $name) {
$rename = 1;
}
}
if ($rename &&
%$aliases) {
my $name;
foreach my $alias (keys %$aliases) {
$name = $alias if !defined($name) || length($alias) < length($name);
}
$self->[NAME] = $name;
}
return %$aliases; # true if this function still exists
}
sub addAliasDifferential
{
my ($self, $name, $data) = @_;
die("alias $name exists")
if exists($self->[ALIASES]->{$name}) && $name ne $self->name();
die("expected array")
unless ref($data) eq "ARRAY" && 2 == scalar(@$data);
$self->[ALIASES]->{$name} = $data;
}
sub setCountDifferential
{
my ($self, $data) = @_;
die("expected array")
unless ref($data) eq "ARRAY" && 2 == scalar(@$data);
$self->[COUNT] = $data;
}
sub findMyLines
{
# use my start/end location to find my list of line coverpoints within
# this function.
# return sorted list of [ [lineNo, hitCount], ...]
my ($self, $lineData) = @_;
return undef unless $self->end_line();
my @lines;
for (my $lineNo = $self->line(); $lineNo <= $self->end_line(); ++$lineNo) {
my $hit = $lineData->value($lineNo);
push(@lines, [$lineNo, $hit])
if (defined($hit));
}
return \@lines;
}
sub _findConditionals
{
my ($self, $data) = @_;
return undef unless $self->end_line();
my @list;
for (my $lineNo = $self->line(); $lineNo <= $self->end_line(); ++$lineNo) {
my $entry = $data->value($lineNo);
push(@list, $entry)
if (defined($entry));
}
return \@list;
}
sub findMyBranches
{
# use my start/end location to list of branch entries within this function
# return sorted list [ branchEntry, ..] sorted by line
my ($self, $branchData) = @_;
die("expected BranchData") unless ref($branchData) eq "BranchData";
return $self->_findConditionals($branchData);
}
sub findMyMcdc
{
# use my start/end location to list of MC/DC entries within this function
# return list [ MCDC_Block, ..] sorted by line
my ($self, $mcdcData) = @_;
die("expected MCDC_Data") unless ref($mcdcData) eq "MCDC_Data";
return $self->_findConditionals($mcdcData);
}
package FunctionMap;
sub new($$)
{
my ($class, $filename) = @_;
my $self = [{}, {}, $filename]; # [locationMap, nameMap]
bless $self, $class;
}
sub filename
{
my $self = shift;
return $self->[2];
}
sub keylist
{
# return list of file:lineNo keys..
my $self = shift;
return keys(%{$self->[0]});
}
sub valuelist
{
# return list of FunctionEntry elements we know about
my $self = shift;
return values(%{$self->[0]});
}
sub list_functions
{
# return list of all the functions/function aliases that we know about
my $self = shift;
return keys(%{$self->[1]});
}
sub define_function
{
my ($self, $fnName, $start_line, $end_line, $location) = @_;
#lcovutil::info("define: $fnName " . $self->$filename() . ":$start_line->$end_line\n");
# could check that function ranges within file are non-overlapping
my ($locationMap, $nameMap) = @$self;
my $data = $self->findName($fnName);
if (defined($data) &&
#TraceFile::is_language('c', $self->filename()) &&
$data->line() != $start_line
) {
$location = '"' . $self->filename() . '":' . $start_line
unless defined($location);
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
"$location: duplicate function '$fnName' starts on line \"" .
$data->filename() .
"\":$start_line but previous definition started on " .
$data->line() . MessageContext::context() . '.')
unless
grep({ $fnName =~ $_ } @lcovutil::suppress_function_patterns);
# if ignored, just return the function we already have -
# record the function location as the smallest line number we saw
if ($start_line < $data->line()) {
delete $self->[0]->{$data->line()};
$data->set_line($start_line);
$self->[0]->{$start_line} = $data;
}
return $data;
}
if (exists($locationMap->{$start_line})) {
$data = $locationMap->{$start_line};
unless ((defined($end_line) &&
defined($data->end_line()) &&
$end_line == $data->end_line()) ||
(!defined($end_line) && !defined($data->end_line()))
) {
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
"mismatched end line for $fnName at " .
$self->filename() . ":$start_line: "
.
(defined($data->end_line()) ?
$data->end_line() : 'undef') .
" -> "
.
(defined($end_line) ? $end_line :
'undef') .
MessageContext::context())
unless
grep({ $fnName =~ $_ } @lcovutil::suppress_function_patterns);
# pick the highest end line if we didn't error out
$data->set_end_line($end_line)
if (defined($end_line) &&
(!defined($data->end_line()) ||
$end_line > $data->end_line()));
}
} else {
$data = FunctionEntry->new($fnName, $self, $start_line, $end_line);
$locationMap->{$start_line} = $data;
}
if (!exists($nameMap->{$fnName})) {
$nameMap->{$fnName} = $data;
$data->addAlias($fnName, 0);
}
return $data;
}
sub findName
{
my ($self, $name) = @_;
my $nameMap = $self->[1];
return exists($nameMap->{$name}) ? $nameMap->{$name} : undef;
}
sub findKey
{
my ($self, $key) = @_; # key is the start line of the function
my $locationMap = $self->[0];
return exists($locationMap->{$key}) ? $locationMap->{$key} : undef;
}
sub numFunc
{
my ($self, $merged) = @_;
if (defined($merged) && $merged) {
return scalar($self->keylist());
}
my $n = 0;
foreach my $key ($self->keylist()) {
my $data = $self->findKey($key);
$n += $data->numAliases();
}
return $n;
}
sub numHit
{
my ($self, $merged) = @_;
my $n = 0;
foreach my $key ($self->keylist()) {
my $data = $self->findKey($key);
if (defined($merged) && $merged) {
++$n
if $data->hit() > 0;
} else {
my $aliases = $data->aliases();
foreach my $alias (keys(%$aliases)) {
my $c = $aliases->{$alias};
++$n if $c > 0;
}
}
}
return $n;
}
sub get_found_and_hit
{
my $self = shift;
my $merged =
defined($lcovutil::cov_filter[$lcovutil::FILTER_FUNCTION_ALIAS]);
return ($self->numFunc($merged), $self->numHit($merged));
}
sub add_count
{
my ($self, $fnName, $count) = @_;
my $nameMap = $self->[1];
if (exists($nameMap->{$fnName})) {
my $data = $nameMap->{$fnName};
$data->addAlias($fnName, $count);
} else {
lcovutil::ignorable_error($lcovutil::ERROR_MISMATCH,
"unknown function '$fnName'");
}
}
sub union
{
my ($self, $that) = @_;
my $changed = 0;
my $myData = $self->[0];
my $yourData = $that->[0];
while (my ($key, $thatData) = each(%$yourData)) {
my $thisData;
if (!exists($myData->{$key})) {
$thisData =
$self->define_function($thatData->name(),
$thatData->line(), $thatData->end_line());
$changed = 1; # something new...
} else {
$thisData = $myData->{$key};
if (!($thisData->line() == $thatData->line()
&& ($thisData->file() eq $thatData->file() ||
($lcovutil::case_insensitive &&
lc($thisData->file()) eq lc($thatData->file())))
)) {
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
"function data mismatch at " .
$thatData->file() . ":" . $thatData->line());
next;
}
}
# merge in all the new aliases
while (my ($alias, $count) = each(%{$thatData->aliases()})) {
if ($thisData->addAlias($alias, $count)) {
$changed = 1;
}
}
}
return $changed;
}
sub intersect
{
my ($self, $that) = @_;
my $changed = 0;
my $myData = $self->[0];
my $myNames = $self->[1];
my $yourData = $that->[0];
my $yourNames = $that->[1];
foreach my $key (keys %$myData) {
my $me = $myData->{$key};
if (exists($yourData->{$key})) {
my $yourFn = $yourData->{$key};
# intersect operation: keep only the common aliases
my @remove;
my $yourAliases = $yourFn->aliases();
while (my ($alias, $count) = each(%{$me->aliases()})) {
if (exists($yourAliases->{$alias})) {
if ($me->addAlias($alias, $yourAliases->{$alias})) {
$changed = 1;
}
} else {
# remove this alias from me..
push(@remove, $alias);
delete($myNames->{$alias});
$changed = 1;
}
}
if (!$me->removeAliases(@remove)) {
# no aliases left (no common aliases) - so remove this function
delete($myData->{$key});
}
} else {
$self->remove($me);
$changed = 1;
}
}
return $changed;
}
sub difference
{
my ($self, $that) = @_;
my $changed = 0;
my $myData = $self->[0];
my $yourData = $that->[0];
foreach my $key (keys %$myData) {
if (exists($yourData->{$key})) {
# just remove the common aliases...
my $me = $myData->{$key};
my $you = $yourData->{$key};
my @remove;
while (my ($alias, $count) = each(%{$you->aliases()})) {
if (exists($me->aliases()->{$alias})) {
push(@remove, $alias);
$changed = 1;
}
}
if (!$me->removeAliases(@remove)) {
# no aliases left (no disjoint aliases) - so remove this function
delete($myData->{$key});
}
}
}
return $changed;
}
sub remove
{
my ($self, $entry) = @_;
die("expected FunctionEntry - " . ref($entry))
unless 'FunctionEntry' eq ref($entry);
my ($locationMap, $nameMap) = @$self;
my $key = $entry->line();
foreach my $alias (keys %{$entry->aliases()}) {
delete($nameMap->{$alias});
}
delete($locationMap->{$key});
}
package BranchMap;
use constant {
DATA => 0,
FOUND => 1,
HIT => 2,
};
sub new
{
my $class = shift;
my $self = [{}, # hash of lineNo -> BranchEntry/MCDC_Element
# BranchEntry:
# hash of blockID ->
# array of 'taken' entries for each sequential
# branch ID
# MCDC_Element:
0, # branches found
0, # branches executed
];
return bless $self, $class;
}
sub remove
{
my ($self, $line, $check_if_present) = @_;
my $data = $self->[DATA];
return 0 if ($check_if_present && !exists($data->{$line}));
my $branch = $data->{$line};
my ($f, $h) = $branch->totals();
$self->[FOUND] -= $f;
$self->[HIT] -= $h;
delete($data->{$line});
return 1;
}
sub found
{
my $self = shift;
return $self->[FOUND];
}
sub hit
{
my $self = shift;
return $self->[HIT];
}
# return BranchEntry struct (or undef)
sub value
{
my ($self, $lineNo) = @_;
my $map = $self->[DATA];
return exists($map->{$lineNo}) ? $map->{$lineNo} : undef;
}
# return list of lines which contain branch data
sub keylist
{
my $self = shift;
return keys(%{$self->[DATA]});
}
sub get_found_and_hit
{
my $self = shift;
return ($self->[FOUND], $self->[HIT]);
}
package BranchData;
use base 'BranchMap';
sub new
{
my $class = shift;
my $self = $class->SUPER::new();
return $self;
}
sub append
{
my ($self, $line, $block, $br, $filename) = @_;
# HGC: might be good idea to pass filename so we could give better
# error message if the data is inconsistent.
# OTOH: unclear what a normal user could do about it anyway.
# Maybe exclude that file?
my $data = $self->[BranchMap::DATA];
$filename = '<stdin>' if (defined($filename) && $filename eq '-');
if (!defined($br)) {
lcovutil::ignorable_error($lcovutil::ERROR_BRANCH,
(defined $filename ? "\"$filename\":$line: " : "")
. "expected 'BranchEntry' or 'integer, BranchBlock'"
) unless ('BranchEntry' eq ref($block));
die("line $line already contains element")
if exists($data->{$line});
# this gets called from 'apply_diff' method: the new line number
# which was assigned might be different than the original - so we
# have to fix up the branch entry.
$block->[0] = $line;
my ($f, $h) = $block->totals();
$self->[BranchMap::FOUND] += $f;
$self->[BranchMap::HIT] += $h;
$data->{$line} = $block;
return 1; # we added something
}
# this cannot happen unless inconsistent branch data was generated by gcov
die((defined $filename ? "\"$filename\":$line: " : "") .
"BranchData::append expected BranchBlock got '" .
ref($br) .
"'.\nThis may be due to mismatched 'gcc' and 'gcov' versions.\n")
unless ('BranchBlock' eq ref($br));
my $branch = $br->id();
my $branchElem;
my $changed = 0;
if (exists($data->{$line})) {
$branchElem = $data->{$line};
$line == $branchElem->line() or die("wrong line mapping");
} else {
$branchElem = BranchEntry->new($line);
$data->{$line} = $branchElem;
$changed = 1; # something new
}
if (!$branchElem->hasBlock($block)) {
$branch == 0
or
lcovutil::ignorable_error($lcovutil::ERROR_BRANCH,
"unexpected non-zero initial branch");
$branch = 0;
my $l = $branchElem->addBlock($block);
push(@$l,
BranchBlock->new($branch, $br->data(),
$br->expr(), $br->is_exception()));
++$self->[BranchMap::FOUND]; # found one
++$self->[BranchMap::HIT] if 0 != $br->count(); # hit one
$changed = 1; # something new..
} else {
$block = $branchElem->getBlock($block);
if ($branch > scalar(@$block)) {
lcovutil::ignorable_error($lcovutil::ERROR_BRANCH,
(defined $filename ? "\"$filename\":$line: " : "") .
"unexpected non-sequential branch ID $branch for block $block"
. (defined($filename) ? "" : " of line $line: ")
. ": found " .
scalar(@$block) . " blocks");
$branch = scalar(@$block);
}
if (!exists($block->[$branch])) {
$block->[$branch] =
BranchBlock->new($branch, $br->data(), $br->expr(),
$br->is_exception());
++$self->[BranchMap::FOUND]; # found one
++$self->[BranchMap::HIT] if 0 != $br->count(); # hit one
$changed = 1;
} else {
my $me = $block->[$branch];
if (0 == $me->count() && 0 != $br->count()) {
++$self->[BranchMap::HIT]; # hit one
$changed = 1;
}
if ($me->merge($br, $filename, $line)) {
$changed = 1;
}
}
}
return $changed;
}
sub removeBranches
{
my ($self, $branchList) = @_;
foreach my $b (@$branchList) {
--$self->[BranchMap::FOUND];
--$self->[BranchMap::HIT] if 0 != $b->count();
}
}
sub _checkCounts
{
# some consistency checking
my $self = shift;
my $data = $self->[BranchMap::DATA];
my $found = 0;
my $hit = 0;
while (my ($line, $branch) = each(%$data)) {
$line == $branch->line() or die("lost track of line");
my ($f, $h) = $branch->totals();
$found += $f;
$hit += $h;
}
die("invalid counts: found:" . $self->[BranchMap::FOUND] .
"->$found, hit:" . $self->[BranchMap::HIT] . "->$hit")
unless ($self->[BranchMap::FOUND] == $found &&
$self->[BranchMap::HIT] == $hit);
}
sub compatible($$)
{
my ($myBr, $yourBr) = @_;
# same number of branches
return 0 unless ($#$myBr == $#$yourBr);
for (my $i = 0; $i <= $#$myBr; ++$i) {
my $me = $myBr->[$i];
my $you = $yourBr->[$i];
if ($me->exprString() ne $you->exprString()) {
# this one doesn't match
return 0;
}
}
return 1;
}
sub union
{
my ($self, $info, $filename) = @_;
my $changed = 0;
my $mydata = $self->[BranchMap::DATA];
while (my ($line, $yourBranch) = each(%{$info->[BranchMap::DATA]})) {
# check if self has corresponding line:
# no: just copy all the data for this line, from 'info'
# yes: check for matching blocks
my $myBranch = $self->value($line);
if (!defined($myBranch)) {
$mydata->{$line} = Storable::dclone($yourBranch);
my ($f, $h) = $yourBranch->totals();
$self->[BranchMap::FOUND] += $f;
$self->[BranchMap::HIT] += $h;
$changed = 1;
next;
}
# keep track of which 'myBranch' blocks have already been merged in
# this pass. We don't want to merge multiple distinct blocks from $info
# into the same $self block (even if it appears compatible) - because
# those blocks were distinct in the input data
my %merged;
# we don't expect there to be a huge number of distinct blocks
# in each branch: most often, just one -
# Thus, we simply walk the list to find a matching block, if one exists
# The matching block will have the same number of branches, and the
# branch expressions will be the same.
# - expression only used in Verilog code at the moment -
# other languages will just have a (matching) integer
# branch index
# first: merge your blocks which seem to exist in me:
my @yourBlocks = sort($yourBranch->blocks());
foreach my $yourId (@yourBlocks) {
my $yourBr = $yourBranch->getBlock($yourId);
# Do I have a block with matching name, which is compatible?
my $myBr = $myBranch->getBlock($yourId)
if $myBranch->hasBlock($yourId);
if (defined($myBr) && # I have this one
compatible($myBr, $yourBr)
) {
foreach my $br (@$yourBr) {
if ($self->append($line, $yourId, $br, $filename)) {
$changed = 1;
}
}
$merged{$yourId} = 1;
$yourId = undef;
}
}
# now look for compatible blocks that aren't identical
BLOCK: foreach my $yourId (@yourBlocks) {
next unless defined($yourId);
my $yourBr = $yourBranch->getBlock($yourId);
# See if we can find a compatible block in $self
# if found: merge.
# no match: this is a different block - assign new ID
foreach my $myId ($myBranch->blocks()) {
next if exists($merged{$myId});
my $myBr = $myBranch->getBlock($myId);
if (compatible($myBr, $yourBr)) {
# we match - so merge our data
$merged{$myId} = 1; # used this one
foreach my $br (@$yourBr) {
if ($self->append($line, $myId, $br, $filename)) {
$changed = 1;
}
}
next BLOCK; # merged this one - go to next
}
} # end search for your block in my blocklist
# we didn't find a match - so this needs to be a new block
my $newID = scalar($myBranch->blocks());
$merged{$newID} = 1; # used this one
foreach my $br (@$yourBr) {
if ($self->append($line, $newID, $br, $filename)) {
$changed = 1;
}
}
}
}
if ($lcovutil::debug) {
$self->_checkCounts(); # some paranoia
}
return $changed;
}
sub intersect
{
my ($self, $info, $filename) = @_;
my $changed = 0;
my $mydata = $self->[BranchMap::DATA];
my $yourdata = $info->[BranchMap::DATA];
foreach my $line (keys %$mydata) {
if (exists($yourdata->{$line})) {
# look at all my blocks. If you have a compatible block, merge them
# - else delete mine
my $myBranch = $mydata->{$line};
my $yourBranch = $yourdata->{$line};
my @myBlocks = $myBranch->blocks();
foreach my $myId (@myBlocks) {
my $myBr = $myBranch->getBlock($myId);
# Do you have a block with matching name, which is compatible?
my $yourBlock = $yourBranch->getBlock($myId)
if $yourBranch->hasBlock($myId);
if (defined($yourBlock) && # you have this one
compatible($myBr, $yourBlock)
) {
foreach my $br (@$yourBlock) {
if ($self->append($line, $myId, $br, $filename)) {
$changed = 1;
}
}
} else {
# block not found...remove this one
$myBranch->removeBlock($myId, $self);
$changed = 1;
}
} # foreach block
} else {
# my line not found in your data - so remove this one
$changed = 1;
$self->remove($line);
}
}
return $changed;
}
sub difference
{
my ($self, $info, $filename) = @_;
my $changed = 0;
my $mydata = $self->[BranchMap::DATA];
my $yourdata = $info->[BranchMap::DATA];
foreach my $line (keys %$mydata) {
# keep everything here if you don't have this line
next unless exists($yourdata->{$line});
# look at all my blocks. If you have a compatible block, remove it:
my $myBranch = $mydata->{$line};
my $yourBranch = $yourdata->{$line};
my @myBlocks = $myBranch->blocks();
foreach my $myId (@myBlocks) {
my $myBr = $myBranch->getBlock($myId);
# Do you have a block with matching name, which is compatible?
my $yourBlock = $yourBranch->getBlock($myId)
if $yourBranch->hasBlock($myId);
if (defined($yourBlock) && # you have this one
compatible($myBr, $yourBlock)
) {
# remove common block
$myBranch->removeBlock($myId, $self);
$changed = 1;
}
} # foreach block
}
return $changed;
}
package MCDC_Data;
use base 'BranchMap';
sub new
{
my $class = shift;
my $self = $class->SUPER::new();
return $self;
}
sub append_mcdc
{
my ($self, $mcdc) = @_;
my $line = $mcdc->line();
die("MCDC already defined for $line")
if exists($self->[BranchMap::DATA]->{$line});
$self->[BranchMap::DATA]->{$line} = $mcdc;
}
sub new_mcdc
{
my ($self, $fileData, $line) = @_;
return $self->[BranchMap::DATA]->{$line}
if exists($self->[BranchMap::DATA]->{$line});
my $mcdc = MCDC_Block->new($line);
$self->[BranchMap::DATA]->{$line} = $mcdc;
return $mcdc;
}
sub close_mcdcBlock
{
my ($self, $mcdc) = @_;
my $found = 0;
my $hit = 0;
while (my ($groupSize, $exprs) = each(%{$mcdc->groups()})) {
foreach my $e (@$exprs) {
$found += 2;
++$hit if $e->count(0);
++$hit if $e->count(1);
}
}
$self->[BranchMap::FOUND] += $found;
$self->[BranchMap::HIT] += $hit;
}
sub _calculate_counts
{
my $self = shift;
my $found = 0;
my $hit = 0;
while (my ($line, $block) = each(%{$self->[BranchMap::DATA]})) {
my ($f, $h) = $block->totals();
$found += $f;
$hit += $h;
}
$self->[BranchMap::FOUND] = $found;
$self->[BranchMap::HIT] = $hit;
}
sub union
{
my ($self, $info) = @_;
my $changed = 0;
my $mydata = $self->[BranchMap::DATA];
while (my ($line, $yourBranch) = each(%{$info->[BranchMap::DATA]})) {
# check if self has corresponding line:
# no: just copy all the data for this line, from 'info'
# yes: check for matching blocks
my $myBranch = $self->value($line);
if (!defined($myBranch)) {
my $c = Storable::dclone($yourBranch);
$mydata->{$line} = $c;
$self->close_mcdcBlock($c);
$changed = 1;
next;
}
# check if we are compatible.
if ($myBranch->is_compatible($yourBranch)) {
$changed += $myBranch->merge($yourBranch);
} else {
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
"cannot merge iconsistent MC/DC record");
# possibly remove this record?
}
}
$self->_calculate_counts();
return $changed;
}
sub intersect
{
my ($self, $info, $filename) = @_;
my $changed = 0;
my $yourData = $info->[BranchMap::DATA];
my $mydata = $self->[BranchMap::DATA];
foreach my $line (keys %$mydata) {
if (exists($yourData->{$line})) {
# append your count to mine
my $yourBranch = $yourData->{$line};
my $myBranch = $mydata->{$line};
if ($myBranch->is_compatible($yourBranch)) {
$changed += $myBranch->merge($yourBranch);
} else {
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
"cannot merge iconsistent MC/DC record");
# possibly remove this record?
}
} else {
$self->remove($line);
$changed = 1;
}
}
$self->_calculate_counts();
return $changed;
}
sub difference
{
my ($self, $info, $filename) = @_;
my $changed = 0;
my $yourData = $info->[BranchMap::DATA];
my $mydata = $self->[BranchMap::DATA];
foreach my $line (keys %$mydata) {
if (exists($yourData->{$line})) {
$self->remove($line);
$changed = 1;
}
}
$self->_calculate_counts();
return $changed;
}
package FilterBranchExceptions;
sub new
{
my $class = shift;
my $self = [$lcovutil::cov_filter[$lcovutil::FILTER_EXCEPTION_BRANCH],
$lcovutil::cov_filter[$lcovutil::FILTER_ORPHAN_BRANCH],
$lcovutil::cov_filter[$lcovutil::FILTER_EXCLUDE_REGION],
$lcovutil::cov_filter[$lcovutil::FILTER_EXCLUDE_BRANCH]
];
bless $self, $class;
return grep({ defined($_) } @$self) ? $self : undef;
}
sub removeBranches
{
my ($self, $line, $branches, $filter, $isMasterData) = @_;
my $brdata = $branches->value($line);
return 0 unless defined($brdata);
my $modified = 0;
my $count = 0;
foreach my $block_id ($brdata->blocks()) {
my $blockData = $brdata->getBlock($block_id);
my @replace;
foreach my $br (@$blockData) {
if (defined($filter) && $br->is_exception()) {
--$branches->[BranchMap::FOUND];
--$branches->[BranchMap::HIT] if 0 != $br->count();
#lcovutil::info($srcReader->fileanme() . ": $line: remove exception branch\n");
$modified = 1;
++$count;
} else {
push(@replace, $br);
}
}
if ($count) {
@$blockData = @replace;
++$filter->[-2] if $isMasterData;
lcovutil::info(2,
"$line: remove $count exception branch" .
(1 == $count ? '' : 'es') . "\n")
if $isMasterData;
$filter->[-1] += $count;
}
# If there is only one branch left - then this is not a conditional
if (0 == scalar(@replace)) {
lcovutil::info(2, "$line: remove exception block $block_id\n");
lcovutil::info("$line: remove exception block $block_id\n");
$brdata->removeBlock($block_id, $branches);
} elsif (1 == scalar(@replace) &&
defined($self->[1])) { # filter orphan
lcovutil::info(2,
"$line: remove orphan exception block $block_id\n");
$brdata->removeBlock($block_id, $branches);
++$self->[1]->[-2]
if $isMasterData;
++$self->[1]->[-1];
}
}
if (0 == scalar($brdata->blocks())) {
lcovutil::info(2, "$line: no branches remain\n");
$branches->remove($line);
$modified = 1;
}
return $modified;
}
sub applyFilter
{
my ($self, $filter, $line, $branches, $perTestBranches) = @_;
my $modified = $self->removeBranches($line, $branches, $filter, 1);
foreach my $tn ($perTestBranches->keylist()) {
# want to remove matching branches everytwhere - so we don't want short-circuit evaluation
my $m = $self->removeBranches($line, $perTestBranches->value($tn),
$filter, 0);
$modified ||= $m;
}
return $modified;
}
sub filter
{
my ($self, $line, $srcReader, $branches, $perTestBranches) = @_;
if ($srcReader->isExcluded($line, 4)) {
# exception branch excluded..
if (defined($self->[2])) { # exclude region
return
$self->applyFilter($self->[2], $line, $branches,
$perTestBranches);
} elsif (defined($self->[3])) { # exclude branches
return
$self->applyFilter($self->[3], $line, $branches,
$perTestBranches);
}
}
# apply if filtering exceptions, orphans, or both
if (defined($self->[0]) || defined($self->[1])) {
return $self->applyFilter($self->[0], $line, $branches,
$perTestBranches);
}
return 0;
}
package TraceInfo;
# coveage data for a particular source file
use constant {
VERSION => 0,
LOCATION => 1,
FILENAME => 2,
CHECKSUM => 3,
LINE_DATA => 4, # per-testcase data
BRANCH_DATA => 5,
FUNCTION_DATA => 6,
MCDC_DATA => 7,
UNION => 0,
INTERSECT => 1,
DIFFERENCE => 2,
};
sub new
{
my ($class, $filename) = @_;
my $self = [];
bless $self, $class;
$self->[VERSION] = undef; # version ID from revision control (if any)
# keep track of location in .info file that this file data was found
# - useful in error messages
$self->[LOCATION] = []; # will fill with file/line
$self->[FILENAME] = $filename;
# _checkdata : line number -> source line checksum
$self->[CHECKSUM] = MapData->new();
# each line/branch/function element is a list of [summaryData, perTestcaseData]
# line: [ line number -> execution count - merged over all testcases,
# testcase_name -> CountData -> line_number -> execution_count ]
$self->[LINE_DATA] =
[CountData->new($filename, $CountData::SORTED), MapData->new()];
# branch: [ BranchData: line number -> branch coverage - for all tests
# testcase_name -> BranchData]
$self->[BRANCH_DATA] = [BranchData->new(), MapData->new()];
# function: [FunctionMap: function_name->FunctionEntry,
# tescase_name -> FucntionMap ]
$self->[FUNCTION_DATA] = [FunctionMap->new($filename), MapData->new()];
$self->[MCDC_DATA] = [MCDC_Data->new(), MapData->new()];
return $self;
}
sub filename
{
my $self = shift;
return $self->[FILENAME];
}
sub set_filename
{
my ($self, $name) = @_;
$self->[FILENAME] = $name;
}
# return true if no line, branch, or function coverage data
sub is_empty
{
my $self = shift;
return ($self->test()->is_empty() && # line cov
$self->testbr()->is_empty() && $self->testfnc()->is_empty());
}
sub location
{
my ($self, $filename, $lineNo) = @_;
my $l = $self->[LOCATION];
if (defined($filename)) {
$l->[0] = $filename;
$l->[1] = $lineNo;
}
return $l;
}
sub version
{
# return the version ID that we found
my ($self, $version) = @_;
(!defined($version) || !defined($self->[VERSION])) or
die("expected to set version ID at most once: " .
(defined($version) ? $version : "undef") . " " .
(defined($self->[VERSION]) ? $self->[VERSION] : "undef"));
$self->[VERSION] = $version
if defined($version);
return $self->[VERSION];
}
# line coverage data
sub test
{
my ($self, $testname) = @_;
my $data = $self->[LINE_DATA]->[1];
if (!defined($testname)) {
return $data;
}
if (!$data->mapped($testname)) {
$data->append_if_unset($testname, CountData->new($self->filename(), 1));
}
return $data->value($testname);
}
sub sum
{
# return MapData of line -> hit count
# data merged over all testcases
my $self = shift;
return $self->[LINE_DATA]->[0];
}
sub func
{
# return FunctionMap of function name or location -> FunctionEntry
# data is merged over all testcases
my $self = shift;
return $self->[FUNCTION_DATA]->[0];
}
sub found
{
my $self = shift;
return $self->sum()->found();
}
sub hit
{
my $self = shift;
return $self->sum()->hit();
}
sub function_found
{
my $self = shift;
return $self->func()
->numFunc(
defined($lcovutil::cov_filter[$lcovutil::FILTER_FUNCTION_ALIAS]));
}
sub function_hit
{
my $self = shift;
return $self->func()
->numHit(
defined($lcovutil::cov_filter[$lcovutil::FILTER_FUNCTION_ALIAS]));
}
sub branch_found
{
my $self = shift;
return $self->sumbr()->found();
}
sub branch_hit
{
my $self = shift;
return $self->sumbr()->hit();
}
sub mcdc_found
{
return $_[0]->mcdc()->found();
}
sub mcdc_hit
{
return $_[0]->mcdc()->hit();
}
sub check
{
my $self = shift;
return $self->[CHECKSUM];
}
# function coverage
sub testfnc
{
my ($self, $testname) = @_;
my $data = $self->[FUNCTION_DATA]->[1];
if (!defined($testname)) {
return $data;
}
if (!$data->mapped($testname)) {
$data->append_if_unset($testname, FunctionMap->new($self->filename()));
}
return $data->value($testname);
}
# branch coverage
sub testbr
{
my ($self, $testname) = @_;
my $data = $self->[BRANCH_DATA]->[1];
if (!defined($testname)) {
return $data;
}
if (!$data->mapped($testname)) {
$data->append_if_unset($testname, BranchData->new());
}
return $data->value($testname);
}
sub sumbr
{
# return BranchData map of line number -> BranchEntry
# data is merged over all testcases
my $self = shift;
return $self->[BRANCH_DATA]->[0];
}
# MCDC coverage
sub testcase_mcdc
{
my ($self, $testname) = @_;
my $data = $self->[MCDC_DATA]->[1];
if (!defined($testname)) {
return $data;
}
if (!$data->mapped($testname)) {
$data->append_if_unset($testname, MCDC_Data->new());
}
return $data->value($testname);
}
sub mcdc
{
# return MCDC_Data map of line number -> MCDC_Block
# data is merged over all testcases
my $self = shift;
return $self->[MCDC_DATA]->[0];
}
#
# check_data
# some paranoia checks
sub check_data($)
{
my $self = shift;
# some paranoia checking...
if (1 || $lcovutil::debug) {
my ($brSum, $brTest) = @{$self->[BRANCH_DATA]};
$brSum->_checkCounts();
foreach my $t ($brTest->keylist()) {
$brTest->value($t)->_checkCounts();
}
}
}
#
# get_info(hash_ref)
#
# Retrieve data from an entry of the structure generated by TraceFile::_read_info().
# Return a list of references to hashes:
# (test data hash ref, sum count hash ref, funcdata hash ref, checkdata hash
# ref, testfncdata hash ref, testbranchdata hash ref, branch summary hash ref)
#
sub get_info($)
{
my $self = shift;
my ($sumcount_ref, $testdata_ref) = @{$self->[LINE_DATA]};
my ($funcdata_ref, $testfncdata) = @{$self->[FUNCTION_DATA]};
my ($sumbrcount, $testbrdata) = @{$self->[BRANCH_DATA]};
my ($mcdccount, $testcasemcdc) = @{$self->[MCDC_DATA]};
my $checkdata_ref = $self->[CHECKSUM];
return ($testdata_ref, $sumcount_ref, $funcdata_ref,
$checkdata_ref, $testfncdata, $testbrdata,
$sumbrcount, $mcdccount, $testcasemcdc);
}
sub _merge_checksums
{
my $self = shift;
my $info = shift;
my $filename = shift;
my $mine = $self->check();
my $yours = $info->check();
foreach my $line ($yours->keylist()) {
if ($mine->mapped($line) &&
$mine->value($line) ne $yours->value($line)) {
lcovutil::ignorable_error($lcovutil::ERROR_MISMATCH,
"checksum mismatch at $filename:$line: " .
$mine->value($line),
' -> ' . $yours->value($line));
}
$mine->replace($line, $yours->value($line));
}
}
sub merge
{
my ($self, $info, $op, $filename) = @_;
my $me = defined($self->version()) ? $self->version() : "<no version>";
my $you = defined($info->version()) ? $info->version() : "<no version>";
my ($countOp, $funcOp, $brOp, $mcdcOp);
if ($op == UNION) {
$countOp = \&CountData::union;
$funcOp = \&FunctionMap::union;
$brOp = \&BranchData::union;
$mcdcOp = \&MCDC_Data::union;
} elsif ($op == INTERSECT) {
$countOp = \&CountData::intersect;
$funcOp = \&FunctionMap::intersect;
$brOp = \&BranchData::intersect;
$mcdcOp = \&MCDC_Data::intersect;
} else {
die("unexpected op $op") unless $op == DIFFERENCE;
$countOp = \&CountData::difference;
$funcOp = \&FunctionMap::difference;
$brOp = \&BranchData::difference;
$mcdcOp = \&MCDC_Data::difference;
}
lcovutil::checkVersionMatch($filename, $me, $you, 'merge');
my $changed = 0;
foreach my $name ($info->test()->keylist()) {
if (&$countOp($self->test($name), $info->test($name))) {
$changed = 1;
}
}
# if intersect and I contain some test that you don't, need to remove my data
if (&$countOp($self->sum(), $info->sum())) {
$changed = 1;
}
if (&$funcOp($self->func(), $info->func())) {
$changed = 1;
}
$self->_merge_checksums($info, $filename);
foreach my $name ($info->testfnc()->keylist()) {
if (&$funcOp($self->testfnc($name), $info->testfnc($name))) {
$changed = 1;
}
}
foreach my $name ($info->testbr()->keylist()) {
if (&$brOp($self->testbr($name), $info->testbr($name), $filename)) {
$changed = 1;
}
}
if (&$brOp($self->sumbr(), $info->sumbr(), $filename)) {
$changed = 1;
}
foreach my $name ($info->testcase_mcdc()->keylist()) {
if (
&$mcdcOp($self->testcase_mcdc($name), $info->testcase_mcdc($name),
$filename)
) {
$changed = 1;
}
}
if (&$mcdcOp($self->mcdc(), $info->mcdc(), $filename)) {
$changed = 1;
}
return $changed;
}
# this package merely reads sourcefiles as they are found on the current
# filesystem - ie., the baseline version might have been modified/might
# have diffs - but the current version does not.
package ReadCurrentSource;
our @source_directories;
our $searchPath;
our @dirs_used;
use constant {
FILENAME => 0,
PATH => 1,
SOURCE => 2,
EXCLUDE => 3,
# reasons: (bitfield)
EXCLUDE_REGION => 0x10,
EXCLUDE_BRANCH_REGION => 0x20,
EXCLUDE_DIRECTIVE => 0x40,
OMIT_LINE => 0x80,
};
sub new
{
my ($class, $filename) = @_;
# additional layer of indirection so derived class can hold its own data
my $self = [[]];
bless $self, $class;
$self->open($filename) if defined($filename);
return $self;
}
sub close
{
my $self = shift;
my $data = $self->[0];
while (scalar(@$data)) {
pop(@$data);
}
}
sub resolve_path
{
my ($filename, $applySubstitutions) = @_;
$filename = lcovutil::subst_file_name($filename) if $applySubstitutions;
return $filename
if (-e $filename ||
(!@lcovutil::resolveCallback &&
(File::Spec->file_name_is_absolute($filename) ||
0 == scalar(@source_directories))));
# don't pass 'applySubstitutions' flag as we already did that, above
return $searchPath->resolve($filename, 0);
}
sub warn_sourcedir_patterns
{
$searchPath->warn_unused(
@source_directories ? '--source-directory' : 'source_directory = ');
}
sub _load
{
my ($self, $filename, $version) = @_;
my $data = $self->[0];
$version = "" unless defined($version);
my $path = resolve_path($filename);
if (open(SRC, "<", $path)) {
lcovutil::info(1,
"read $version$filename" .
($path ne $filename ? " (at $path)" : '') . "\n");
$data->[PATH] = $path;
my @sourceLines = <SRC>;
CORE::close(SRC) or die("unable to close $filename: $!\n");
$data->[FILENAME] = $filename;
return \@sourceLines;
} else {
lcovutil::ignorable_error($lcovutil::ERROR_SOURCE,
"unable to open $filename: $!\n");
$self->close();
return undef;
}
}
sub open
{
my ($self, $filename, $version) = @_;
my $srcLines = $self->_load($filename, $version);
if (defined($srcLines)) {
return $self->parseLines($filename, $srcLines);
}
return undef;
}
sub path
{
my $self = shift;
return $self->[0]->[PATH];
}
sub parseLines
{
my ($self, $filename, $sourceLines) = @_;
my @excluded;
my $exclude_region;
my $exclude_br_region;
my $exclude_exception_region;
my $line = 0;
my $excl_start = qr($lcovutil::EXCL_START);
my $excl_stop = qr($lcovutil::EXCL_STOP);
my $excl_line = qr($lcovutil::EXCL_LINE);
my $excl_br_start = qr($lcovutil::EXCL_BR_START);
my $excl_br_stop = qr($lcovutil::EXCL_BR_STOP);
my $excl_br_line = qr($lcovutil::EXCL_BR_LINE);
my $excl_ex_start = qr($lcovutil::EXCL_EXCEPTION_BR_START);
my $excl_ex_stop = qr($lcovutil::EXCL_EXCEPTION_BR_STOP);
my $excl_ex_line = qr($lcovutil::EXCL_EXCEPTION_LINE);
# @todo: if we had annotated data here, then we could whine at the
# author of the unmatched start, extra end, etc.
my $exclude_directives =
qr/^\s*#\s*((else|endif)|((ifdef|ifndef|if|elif|include|define|undef)\s+))/
if (TraceFile::is_language('c', $filename) &&
defined($lcovutil::cov_filter[$lcovutil::FILTER_DIRECTIVE]));
my @excludes;
if (defined($lcovutil::cov_filter[$lcovutil::FILTER_EXCLUDE_REGION])) {
push(@excludes,
[$excl_start, $excl_stop,
\$exclude_region, 3 | EXCLUDE_REGION,
$lcovutil::EXCL_START, $lcovutil::EXCL_STOP
]);
} else {
$excl_line = undef;
}
if (defined($lcovutil::cov_filter[$lcovutil::FILTER_EXCLUDE_BRANCH])) {
push(@excludes,
[$excl_ex_start, $excl_ex_stop,
\$exclude_exception_region, 4 | EXCLUDE_BRANCH_REGION,
$lcovutil::EXCL_BR_START, $lcovutil::EXCL_BR_STOP,
],
[$excl_br_start,
$excl_br_stop,
\$exclude_br_region,
2 | EXCLUDE_BRANCH_REGION,
$lcovutil::EXCL_EXCEPTION_BR_START,
$lcovutil::EXCL_EXCEPTION_BR_STOP,
]);
} else {
$excl_br_line = undef;
$excl_ex_line = undef;
}
LINES: foreach (@$sourceLines) {
$line += 1;
my $exclude_branch_line = 0;
my $exclude_exception_branch_line = 0
; # per-line exception excludion not implemented at present. Probably unnecessary.
chomp($_);
s/\r//; # remove carriage return
if (defined($exclude_directives) &&
$_ =~ $exclude_directives) {
push(@excluded, 3 | EXCLUDE_DIRECTIVE); #everything excluded
lcovutil::info(2, "directive '#$1' on $filename:$line\n");
next;
}
foreach my $d (@excludes) {
# note: $d->[4] is the 'start' string (not converted to perl regexp)
# $d->[5] is the 'stop' string
my ($start, $stop, $ref, $reason) = @$d;
if ($_ =~ $start) {
lcovutil::ignorable_error($lcovutil::ERROR_MISMATCH,
"$filename: overlapping exclude directives. Found " .
$d->[4] .
" at line $line - but no matching " . $d->[5] .
' for ' . $d->[4] . ' at line ' . $$ref->[0])
if $$ref;
$$ref = [$line, $reason];
last;
} elsif ($_ =~ $stop) {
lcovutil::ignorable_error($lcovutil::ERROR_MISMATCH,
"$filename: found " . $d->[5] .
" directive at line $line without matching " .
$d->[4] . ' directive')
unless $$ref;
$$ref = undef;
last;
}
}
if (defined($excl_line) &&
$_ =~ $excl_line) {
push(@excluded, 3 | EXCLUDE_REGION); #everything excluded
next;
} elsif (defined($excl_br_line) &&
$_ =~ $excl_br_line) {
$exclude_branch_line = 2 | EXCLUDE_BRANCH_REGION;
} elsif (defined($excl_ex_line) &&
$_ =~ $excl_ex_line) {
$exclude_branch_line = 4 | EXCLUDE_BRANCH_REGION;
} elsif (0 != scalar(@lcovutil::omit_line_patterns)) {
foreach my $p (@lcovutil::omit_line_patterns) {
my $pat = $p->[0];
if ($_ =~ $pat) {
push(@excluded, 3 | OMIT_LINE); #everything excluded
#lcovutil::info("'" . $p->[-2] . "' matched \"$_\", line \"$filename\":"$line\n");
++$p->[-1];
next LINES;
}
}
}
push(@excluded,
($exclude_region ? $exclude_region->[1] : 0) |
($exclude_br_region ? $exclude_br_region->[1] : 0) | (
$exclude_exception_region ? $exclude_exception_region->[1] : 0
) | $exclude_branch_line | $exclude_exception_branch_line);
}
foreach my $t ([$exclude_region, $lcovutil::EXCL_START,
$lcovutil::EXCL_STOP
],
[$exclude_br_region, $lcovutil::EXCL_BR_START,
$lcovutil::EXCL_BR_STOP
],
[$exclude_exception_region,
$lcovutil::EXCL_EXCEPTION_BR_START,
$lcovutil::EXCL_EXCEPTION_BR_STOP
]
) {
my ($key, $start, $stop) = @$t;
lcovutil::ignorable_error($lcovutil::ERROR_MISMATCH,
"$filename: unmatched $start at line " .
$key->[0] .
" - saw EOF while looking for matching $stop"
) if ($key);
}
my $data = $self->[0];
$data->[FILENAME] = $filename;
$data->[SOURCE] = $sourceLines;
$data->[EXCLUDE] = \@excluded;
return $self;
}
sub notEmpty
{
my $self = shift;
return 0 != scalar(@{$self->[0]});
}
sub filename
{
return $_[0]->[0]->[FILENAME];
}
sub numLines
{
my $self = shift;
return scalar(@{$self->[0]->[SOURCE]});
}
sub getLine
{
my ($self, $line) = @_;
return $self->isOutOfRange($line) ?
undef :
$self->[0]->[SOURCE]->[$line - 1];
}
sub getExpr
{
my ($self, $startLine, $startCol, $endLine, $endCol) = @_;
die("bad range [$startLine:$endLine]") unless $endLine >= $startLine;
return 'NA' unless $endLine <= $self->numLines();
my $line = $self->getLine($startLine);
my $expr;
if ($startLine == $endLine) {
$expr = substr($line, $startCol - 1, $endCol - $startCol);
} else {
$expr = substr($line, $startCol - 1);
for (my $l = $startLine + 1; $l < $endLine; ++$l) {
$expr .= $self->getLine($l);
}
$line = $self->getLine($endLine);
$expr .= substr($line, 0, $endCol);
}
$expr =~ /^\s*(.+?)\s*$/;
return $1;
}
sub isOutOfRange
{
my ($self, $lineNo, $context) = @_;
my $data = $self->[0];
if (defined($data->[EXCLUDE]) &&
scalar(@{$data->[EXCLUDE]}) < $lineNo) {
# Can happen due to version mismatches: data extracted with
# version N of the file, then generating HTML with version M
# "--version-script callback" option can be used to detect this.
# Another case happens due to apparent bugs in some old 'gcov'
# versions - which sometimes inserts out-of-range line numbers
# when macro is used as last line in file.
my $filt = $lcovutil::cov_filter[$lcovutil::FILTER_LINE_RANGE];
if (defined($filt)) {
my $c = ($context eq 'line') ? 'line' : "$context at line";
lcovutil::info(2,
"filter out-of-range $c $lineNo in " .
$self->filename() . " (" .
scalar(@{$data->[EXCLUDE]}) .
" lines in file)\n");
++$filt->[-2]; # applied in 1 location
++$filt->[-1]; # one coverpoint suppressed
return 1;
}
my $key = $self->filename();
$key .= $lineNo unless $lcovutil::warn_once_per_file;
if (lcovutil::warn_once($lcovutil::ERROR_RANGE, $key)) {
my $c = ($context eq 'line') ? 'line' : "$context at line";
my $msg =
"unknown $c '$lineNo' in " .
$self->filename() . ": there are only " .
scalar(@{$data->[EXCLUDE]}) . " lines in the file.";
if ($lcovutil::verbose ||
0 == lcovutil::message_count($lcovutil::ERROR_RANGE)) {
# only print verbose addition on first message
$msg .= lcovutil::explain_once(
'version_script',
[ "\n Issue can be caused by code changes/version mismatch: see the \"--version-script script_file\" discussion in the genhtml man page.",
$lcovutil::tool_name ne 'geninfo'
],
"\n Use '$lcovutil::tool_name --filter range' to remove out-of-range lines."
);
}
# some versions of gcov seem to make up lines that do not exist -
# this appears to be related to macros on last line in file
lcovutil::store_deferred_message($lcovutil::ERROR_RANGE,
1, $key, $msg);
}
# Note: if user ignored the error, then we return 'not out of range'.
# The line is out of range/something is wrong - but the user did not
# ask us to filter it out.
}
return 0;
}
sub excludeReason
{
my ($self, $lineNo) = @_;
my $data = $self->[0];
die("missing data at $lineNo")
unless (defined($data->[EXCLUDE]) &&
scalar(@{$data->[EXCLUDE]}) >= $lineNo);
return $data->[EXCLUDE]->[$lineNo - 1] & 0xFF0;
}
sub isExcluded
{
my ($self, $lineNo, $branch) = @_;
my $data = $self->[0];
if (!defined($data->[EXCLUDE]) ||
scalar(@{$data->[EXCLUDE]}) < $lineNo) {
# this can happen due to version mismatches: data extracted with
# version N of the file, then generating HTML with version M
# "--version-script callback" option can be used to detect this
my $key = $self->filename();
$key .= $lineNo unless ($lcovutil::warn_once_per_file);
my $suffix = lcovutil::explain_once(
'version-script',
[ "\n Issue can be caused by code changes/version mismatch; see the \"--version-script script_file\" discussion in the genhtml man page.",
$lcovutil::verbose ||
lcovutil::message_count($lcovutil::ERROR_RANGE) == 0
]);
lcovutil::store_deferred_message(
$lcovutil::ERROR_RANGE,
1, $key,
"unknown line '$lineNo' in " . $self->filename()
.
(
defined($data->[EXCLUDE]) ?
(" there are only " .
scalar(@{$data->[EXCLUDE]}) . " lines in the file.") :
"") .
$suffix) if lcovutil::warn_once($lcovutil::ERROR_RANGE, $key);
return 0; # even though out of range - this is not excluded by filter
}
return 1
if ($branch &&
0 != ($data->[EXCLUDE]->[$lineNo - 1] & $branch));
return 0 != ($data->[EXCLUDE]->[$lineNo - 1] & 1);
}
sub removeComments
{
my $line = shift;
$line =~ s|//.*$||;
$line =~ s|/\*.*\*/||g;
return $line;
}
sub isCharacter
{
my ($self, $line, $char) = @_;
my $code = $self->getLine($line);
return 0
unless defined($code);
$code = removeComments($code);
return ($code =~ /^\s*${char}\s*$/);
}
# is line empty
sub isBlank
{
my ($self, $line) = @_;
my $code = $self->getLine($line);
return 0
unless defined($code);
$code = removeComments($code);
return ($code =~ /^\s*$/);
}
sub is_initializerList
{
my ($self, $line) = @_;
return 0 unless defined($self->[0]->[SOURCE]) && $line < $self->numLines();
my $code = '';
my $l = $line;
my $foundExpr = 0;
while ($l < $self->numLines()) {
my $src = $self->getLine($l);
# append to string until we find close brace...then look for next one...
$code = removeComments($code . $src);
# believe that initialization expressions are either numeric or C strings
while ($code =~
s/\s+("[^"]*"|0x[0-9a-fA-F]+|[-+]?[0-9]+((\.[0-9]+)([eE][-+][0-9]+)?)?)\s*,?//
) {
$foundExpr = 1;
}
# remove matching {} brace pairs - assume a sub-object initializer
$code =~ s/\s*{\s*,?\s*}\s*,?\s*//;
last if $code =~ /[};]/; # unmatched close or looks like statement
last unless $code =~ /^\s*([{}]\s*)*$/;
++$l;
}
return $foundExpr ? $l - $line : 0; # return number of consecutive lines
}
sub containsConditional
{
my ($self, $line) = @_;
# special case - maybe C++ exception handler on close brace at end of function?
return 0
if $self->isCharacter($line, '}');
my $src = $self->getLine($line);
return 1
unless defined($src);
my $code = "";
for (my $next = $line + 1;
defined($src) && ($next - $line) < $lcovutil::source_filter_lookahead;
++$next) {
$src = lcovutil::simplifyCode($src);
my $bitwiseOperators =
$lcovutil::source_filter_bitwise_are_conditional ? '&|~' : '';
return 1
if ($src =~
/([?!><$bitwiseOperators]|&&|\|\||==|!=|\b(if|switch|case|while|for)\b)/
);
$code = $code . $src;
if (lcovutil::balancedParens($code)) {
return 0; # got to the end and didn't see conditional
} elsif ($src =~ /[{;]\s*$/) {
# assume we got to the end of the statement if we see semicolon
# or brace.
# parens weren't balanced though - so assume this might be
# a conditional
return 1;
}
$src = $self->getLine($next);
$src = '' unless defined($src);
}
return 1; # not sure - so err on side of caution
}
sub containsTrivialFunction
{
my ($self, $start, $end) = @_;
return 0
if (1 + $end - $start >= $lcovutil::trivial_function_threshold);
my $text = '';
for (my $line = $start; $line <= $end; ++$line) {
my $src = $self->getLine($line);
$src = '' unless defined($src);
chomp($src);
$src =~ s/\s+$//; # whitespace
$src =~ s#//.*$##; # remove end-of-line comments
$text .= $src;
}
# remove any multiline comments that were present:
$text =~ s#/\*.*\*/##g;
# remove whitespace
$text =~ s/\s//g;
# remove :: C++ separator
$text =~ s/:://g;
if ($text =~ /:/) {
return 0;
}
# does code end with '{}', '{;}' or '{};'?
# Or: is this just a close brace?
if ($text =~ /(\{;?|^)\};?$/) {
return 1;
}
return 0;
}
# check if this line is a close brace with zero hit count that should be
# suppressed. We want to ignore spurious zero on close brace; depending
# on what gcov did the last time (zero count, no count, nonzero count) -
# it might be interpreted as UIC - which will violate our coverage criteria.
# We want to ignore this line if:
# - the line contain only a closing brace and
# - previous line is hit, OR
# - previous line is not an open-brace which has no associated
# count - i.e., this is not an empty block where the zero
# count is tagged to the closing brace, OR
# is line empty (no code) and
# - count is zero, and
# - either previous or next non-blank lines have an associated count
#
sub suppressCloseBrace
{
my ($self, $lineNo, $count, $lineCountData) = @_;
my $suppress = 0;
if ($self->isCharacter($lineNo, '}')) {
for (my $prevLine = $lineNo - 1; $prevLine >= 0; --$prevLine) {
my $prev = $lineCountData->value($prevLine);
if (defined($prev)) {
# previous line was executable
$suppress = 1
if ($prev == $count ||
($count == 0 &&
$prev > 0));
lcovutil::info(3,
"not skipping brace line $lineNo because previous line $prevLine hit count didn't match: $prev != $count"
) unless $suppress;
last;
} elsif ($count == 0 &&
# previous line not executable - was it an open brace?
$self->isCharacter($prevLine, '{')
) {
# look 'up' from the open brace to find the first
# line which has an associated count -
my $code = "";
for (my $l = $prevLine - 1; $l >= 0; --$l) {
$code = $self->getLine($l) . $code;
my $prevCount = $lineCountData->value($l);
if (defined($prevCount)) {
# don't suppress if previous line not hit either
last
if $prevCount == 0;
# if first non-whitespace character is a colon -
# then this looks like a C++ initialization list.
# suppress.
if ($code =~ /^\s*:(\s|[^:])/) {
$suppress = 1;
} else {
$code = lcovutil::filterStringsAndComments($code);
$code = lcovutil::simplifyCode($code);
# don't suppress if this looks like a conditional
$suppress = 1
unless (
$code =~ /\b(if|switch|case|while|for)\b/);
}
last;
}
} # for each prior line (looking for statement before block)
last;
} # if (line was an open brace)
} # foreach prior line
} # if line was close brace
return $suppress;
}
package TraceFile;
our $ignore_testcase_name; # use default name, if set
use constant {
FILES => 0,
COMMENTS => 1,
STATE => 2, # operations performed: don't do them again
DID_FILTER => 1,
DID_DERIVE => 2,
};
sub load
{
my ($class, $tracefile, $readSource, $verify_checksum,
$ignore_function_exclusions)
= @_;
my $self = $class->new();
my $context = MessageContext->new("loading $tracefile");
$self->_read_info($tracefile, $readSource, $verify_checksum);
$self->applyFilters($readSource);
return $self;
}
sub new
{
my $class = shift;
my $self = [{}, [], 0];
bless $self, $class;
return $self;
}
sub serialize
{
my ($self, $filename) = @_;
my $data = Storable::store($self, $filename);
die("serialize failed") unless defined($data);
}
sub deserialize
{
my ($class, $file) = @_;
my $self = Storable::retrieve($file) or
die("unable to deserialize $file\n");
ref($self) eq $class or die("did not deserialize a $class");
return $self;
}
sub empty
{
my $self = shift;
return !keys(%{$self->[FILES]});
}
sub files
{
my $self = shift;
# for case-insensitive support: need to store the file keys in
# lower case (so they can be found) - but return the actual
# names of the files (mixed case)
return keys %{$self->[FILES]};
}
sub directories
{
my $self = shift;
# return hash of directories which contain source files
my %dirs;
foreach my $f ($self->files()) {
my $d = File::Basename::dirname($f);
$dirs{$d} = [] unless exists($dirs{$d});
push(@{$dirs{$d}}, $f);
}
return \%dirs;
}
sub file_exists
{
my ($self, $name) = @_;
$name = lc($name) if $lcovutil::case_insensitive;
return exists($self->[FILES]->{$name});
}
sub count_totals
{
my $self = shift;
# return list of (number files, [#lines, #hit], [#branches, #hit], [#functions,#hit])
my @data = (0, [0, 0], [0, 0], [0, 0], [0, 0]);
foreach my $filename ($self->files()) {
my $entry = $self->data($filename);
++$data[0];
$data[1]->[0] += $entry->found(); # lines
$data[1]->[1] += $entry->hit();
$data[2]->[0] += $entry->branch_found(); # branch
$data[2]->[1] += $entry->branch_hit();
$data[3]->[0] += $entry->function_found(); # function
$data[3]->[1] += $entry->function_hit();
if ($lcovutil::mcdc_coverage) {
$data[4]->[0] += $entry->mcdc_found(); # mcdc
$data[4]->[1] += $entry->mcdc_hit();
}
}
return @data;
}
sub check_fail_under_criteria
{
my ($self, $type) = @_;
my @types;
if (!defined($type)) {
push(@types, 'line');
push(@types, 'branch', 'condition') if $lcovutil::br_coverage;
} else {
push(@types, $type);
}
foreach my $t (@types) {
my ($rate, $plural, $idx);
if ($t eq 'line') {
next unless defined($lcovutil::fail_under_lines);
$rate = $lcovutil::fail_under_lines;
$idx = 1; # lines
$plural = 'lines';
} else {
next unless defined($lcovutil::fail_under_branches);
$rate = $lcovutil::fail_under_branches;
$idx = 2;
$plural = 'branches';
}
next if $rate <= 0;
my @counts = $self->count_totals();
my ($found, $hit) = @{$counts[$idx]};
if ($found == 0) {
lcovutil::info(1, "No $plural found\n");
return "No $plural found";
}
my $actual_rate = ($hit / $found);
my $expected_rate = $rate / 100;
if ($actual_rate < $expected_rate) {
my $msg =
sprintf("Failed '$t' coverage criteria: %0.2f < %0.2f",
$actual_rate, $expected_rate);
lcovutil::info("$msg\n");
return $msg;
}
}
return 0;
}
sub checkCoverageCriteria
{
my $self = shift;
CoverageCriteria::check_failUnder($self);
return unless defined($CoverageCriteria::criteriaCallback);
my $perFile = 0 == scalar(@CoverageCriteria::criteriaCallbackLevels) ||
grep(/file/, @CoverageCriteria::criteriaCallbackLevels);
my %total = ('line' => {
'found' => 0,
'hit' => 0
},
'branch' => {
'found' => 0,
'hit' => 0
},
'condition' => {
'found' => 0,
'hit' => 0
},
'function' => {
'found' => 0,
'hit' => 0
});
my %data;
foreach my $filename ($self->files()) {
my $entry = $self->data($filename);
my @data = ($entry->found(), $entry->hit(),
$entry->branch_found(), $entry->branch_hit(),
$entry->function_found(), $entry->function_hit());
my $idx = 0;
foreach my $t ('line', 'branch', 'function') {
foreach my $x ('found', 'hit') {
$data{$t}->{$t} = $data[$idx] if $perFile;
$total{$t}->{$x} += $data[$idx++];
}
}
if ($perFile) {
CoverageCriteria::executeCallback('file', $filename, \%data);
}
}
CoverageCriteria::executeCallback('top', 'top', \%total);
}
#
# print_summary(fn_do, br_do)
#
# Print overall coverage rates for the specified coverage types.
# $countDat is the array returned by 'TraceFile->count_totals()'
sub print_summary
{
my ($self, $fn_do, $br_do, $mcdc_do) = @_;
$br_do = $lcovutil::br_coverage unless defined($br_do);
$mcdc_do = $lcovutil::mcdc_coverage unless defined($mcdc_do);
$fn_do = $lcovutil::func_coverage unless defined($fn_do);
my @counts = $self->count_totals();
lcovutil::info("Summary coverage rate:\n");
lcovutil::info(" source files: %d\n", $counts[0]);
lcovutil::info(" lines.......: %s\n",
lcovutil::get_overall_line(
$counts[1]->[0], $counts[1]->[1], "line"
));
lcovutil::info(" functions...: %s\n",
lcovutil::get_overall_line(
$counts[3]->[0], $counts[3]->[1], "function"
)) if ($fn_do);
lcovutil::info(" branches....: %s\n",
lcovutil::get_overall_line(
$counts[2]->[0], $counts[2]->[1], "branch"
)) if ($br_do);
lcovutil::info(" conditions..: %s\n",
lcovutil::get_overall_line(
$counts[4]->[0], $counts[4]->[1], "conditions"
)) if ($mcdc_do);
}
sub skipCurrentFile
{
my $filename = shift;
my $filt = $lcovutil::cov_filter[$lcovutil::FILTER_MISSING_FILE];
if ($filt) {
my $missing = !-r $filename;
if ($missing &&
$lcovutil::resolveCallback) {
my $path = SearchPath::resolveCallback($filename, 0, 1);
$missing = !defined($path) || '' eq $path;
}
if ($missing) {
lcovutil::info(
"Excluding \"$filename\": does not exist/is not readable\n");
++$filt->[-2];
++$filt->[-1];
return 1;
}
}
# check whether this file should be excluded or not...
foreach my $p (@lcovutil::exclude_file_patterns) {
my $pattern = $p->[0];
if ($filename =~ $pattern) {
lcovutil::info(1, "exclude $filename: matches '" . $p->[1] . "\n");
++$p->[-1];
return 1; # all done - explicitly excluded
}
}
if (@lcovutil::include_file_patterns) {
foreach my $p (@lcovutil::include_file_patterns) {
my $pattern = $p->[0];
if ($filename =~ $pattern) {
lcovutil::info(1,
"include: $filename: matches '" . $p->[1] . "\n");
++$p->[-1];
return 0; # explicitly included
}
}
lcovutil::info(1, "exclude $filename: no include matches\n");
return 1; # not explicitly included - so exclude
}
return 0;
}
sub comments
{
my $self = shift;
return @{$self->[COMMENTS]};
}
sub add_comments
{
my $self = shift;
foreach (@_) {
push(@{$self->[COMMENTS]}, $_);
}
}
sub data
{
my $self = shift;
my $file = shift;
my $checkMatchingBasename = shift;
my $key = $lcovutil::case_insensitive ? lc($file) : $file;
my $files = $self->[FILES];
if (!exists($files->{$key})) {
if (defined $checkMatchingBasename) {
# check if there is a file in the map that has the same basename
# as the lone we are looking for.
# this can happen if the 'udiff' file refers to paths in the repo
# whereas the .info files refer to paths in the build area.
my $base = File::Basename::basename($file);
$base = lc($base) if $lcovutil::case_insensitive;
my $count = 0;
my $found;
foreach my $f (keys %$files) {
my $b = File::Basename::basename($f);
$b = lc($b) if $lcovutil::case_insensitive;
if ($b eq $base) {
$count++;
$found = $files->{$f};
}
}
return $found
if $count == 1;
}
$files->{$key} = TraceInfo->new($file);
}
return $files->{$key};
}
sub contains
{
my ($self, $file) = @_;
my $key = $lcovutil::case_insensitive ? lc($file) : $file;
my $files = $self->[FILES];
return exists($files->{$key});
}
sub remove
{
my ($self, $filename) = @_;
$filename = lc($filename) if $lcovutil::case_insensitive;
$self->file_exists($filename) or
die("remove nonexistent file $filename");
delete($self->[FILES]->{$filename});
}
sub insert
{
my ($self, $filename, $data) = @_;
$filename = lc($filename) if $lcovutil::case_insensitive;
die("insert existing file $filename")
if $self->file_exists($filename);
die("expected TraceInfo got '" . ref($data) . "'")
unless (ref($data) eq 'TraceInfo');
$self->[FILES]->{$filename} = $data;
}
sub merge_tracefile
{
my ($self, $trace, $op) = @_;
die("expected TraceFile")
unless (defined($trace) && 'TraceFile' eq ref($trace));
my $changed = 0;
my $mine = $self->[FILES];
my $yours = $trace->[FILES];
foreach my $filename (keys %$mine) {
if (exists($yours->{$filename})) {
# this file in both me and you...merge as appropriate
#lcovutil::info(1, "merge common $filename\n");
if ($self->data($filename)
->merge($yours->{$filename}, $op, $filename)) {
$changed = 1;
}
} else {
# file in me and not you - remove mine if intersect operation
if ($op == TraceInfo::INTERSECT) {
#lcovutil::info(1, "removing my $filename: intersect\n");
delete $mine->{$filename};
$changed = 1;
}
}
}
if ($op == TraceInfo::UNION) {
# now add in any files from you that are not present in me...
while (my ($filename, $data) = each(%$yours)) {
if (!exists($mine->{$filename})) {
$mine->{$filename} = $data;
$changed = 1;
}
}
}
$self->add_comments($trace->comments());
return $changed;
}
sub _eraseFunction
{
my ($fcn, $name, $end_line, $source_file, $functionMap,
$lineData, $branchData, $mcdcData, $checksum) = @_;
if (defined($end_line)) {
for (my $line = $fcn->line(); $line <= $end_line; ++$line) {
if (defined($checksum)) {
$checksum->remove($line, 1); # remove if present
}
if ($lineData->remove($line, 1)) {
lcovutil::info(2,
"exclude DA in FN '$name' on $source_file:$line\n");
}
if (defined($branchData) && $branchData->remove($line, 1)) {
lcovutil::info(2,
"exclude BRDA in FN '$name' on $source_file:$line\n");
}
if (defined($mcdcData) && $mcdcData->remove($line, 1)) {
lcovutil::info(2,
"exclude MCDC in FN '$name' on $source_file:$line\n");
}
} # foreach line
}
# remove this function and all its aliases...
$functionMap->remove($fcn);
}
sub _eraseFunctions
{
my ($source_file, $srcReader, $functionMap, $lineData, $branchData,
$mcdcData, $checksum, $state, $isMasterList) = @_;
my $modified = 0;
my $removeTrivial = $cov_filter[$FILTER_TRIVIAL_FUNCTION];
FUNC: foreach my $key ($functionMap->keylist()) {
my $fcn = $functionMap->findKey($key);
my $end_line = $fcn->end_line();
my $name = $fcn->name();
if (!defined($end_line)) {
++$state->[0]->[1]; # mark that we don't have an end line
# we can skip out of processing if we don't know the end line
# - there is no way for us to remove line and branch points in
# the function region
# Or we can keep going and at least remove the matched function
# coverpoint.
#last; # at least for now: keep going
lcovutil::info(1, "no end line for '$name' at $key\n");
} elsif (
defined($removeTrivial) &&
is_language('c', $source_file) &&
(defined($srcReader) &&
$srcReader->containsTrivialFunction($fcn->line(), $end_line))
) {
# remove single-line functions which has no body
# Only count what we removed from the top level/master list -
# - otherwise, we double count for every testcase.
++$removeTrivial->[-2] if $isMasterList;
foreach my $alias (keys %{$fcn->aliases()}) {
lcovutil::info(1,
"\"$source_file\":$end_line: filter trivial FN $alias\n");
_eraseFunction($fcn, $alias, $end_line,
$source_file, $functionMap, $lineData,
$branchData, $mcdcData, $checksum);
++$removeTrivial->[-1] if $isMasterList;
}
$modified = 1;
next FUNC;
}
foreach my $p (@lcovutil::exclude_function_patterns) {
my $pat = $p->[0];
my $a = $fcn->aliases();
foreach my $alias (keys %$a) {
if ($alias =~ $pat) {
++$p->[-1] if $isMasterList;
if (defined($end_line)) {
# if user ignored the unsupported message, then the
# best we can do is to remove the matched function -
# and leave the lines and branches in place
lcovutil::info(
1 + (0 == $isMasterList),
"exclude FN $name line range $source_file:[" .
$fcn->line() .
":$end_line] due to '" . $p->[-2] . "'\n"
);
}
_eraseFunction($fcn, $alias, $end_line,
$source_file, $functionMap, $lineData,
$branchData, $mcdcData, $checksum);
$modified = 1;
next FUNC;
} # if match
} # foreach alias
} # foreach pattern
} # foreach function
return $modified;
}
sub _deriveFunctionEndLines
{
my $traceInfo = shift;
my $modified = 0;
my $start = Time::HiRes::gettimeofday();
my $lineData = $traceInfo->sum();
my @lines = sort { $a <=> $b } $lineData->keylist();
# sort functions by start line number
# ignore lambdas - which we don't process correctly at the moment
# (would need to do syntactic search for the end line)
my @functions = sort { $a->line() <=> $b->line() }
grep({ !$_->isLambda() } $traceInfo->func()->valuelist());
my $currentLine = @lines ? shift(@lines) : 0;
my $funcData = $traceInfo->testfnc();
FUNC: while (@functions) {
my $func = shift(@functions);
my $first = $func->line();
my $end = $func->end_line();
#unless (defined($lineData->value($first))) {
# lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
# '"' . $func->filename() .
# "\":$first: first line of function has no linecov.");
# $lineData->append($first, $func->hit());
#}
while ($first > $currentLine) {
if (@lines) {
last if $lines[0] > $first;
$currentLine = shift @lines;
} else {
if (!defined($end)) {
my $suffix =
lcovutil::explain_once('derive_end_line',
" See lcovrc man entry for 'derive_function_end_line'."
);
lcovutil::ignorable_error(
$lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $traceInfo->filename() .
"\":$first: function " . $func->name() .
" found on line but no corresponding 'line' coverage data point. Cannot derive function end line."
. $suffix);
}
next FUNC;
}
}
if (!defined($end)) {
# where is the next function? Find the last 'line' coverpoint
# less than the start line of that function..
if (@lines) {
# if there are no more lines in this file - then everything
# must be ending on the last line we saw
if (@functions) {
my $next_func = $functions[0];
my $start = $next_func->line();
while (@lines &&
$lines[0] < $start) {
$currentLine = shift @lines;
}
} else {
# last line in the file must be the last line
# of this function
if (@lines) {
$currentLine = $lines[-1];
} else {
my $suffix = lcovutil::explain_once('derive_end_line',
" See lcovrc man entry for 'derive_function_end_line'."
);
lcovutil::ignorable_error(
$lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $traceInfo->filename() .
"\":$first: function " . $func->name() .
": last line in file is not last line of function.$suffix"
);
next FUNC;
}
}
} elsif ($currentLine < $first) {
# we ran out of lines in the data...check for inconsistency
my $suffix =
lcovutil::explain_once('derive_end_line',
" See lcovrc man entry for 'derive_function_end_line'.");
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $traceInfo->filename() .
"\":$first: function " . $func->name() .
" found on line but no corresponding 'line' coverage data point. Cannot derive function end line."
. $suffix);
# last FUNC; # quit looking here - all the other functions after this one will have same issue
next FUNC; # warn about them all
}
lcovutil::info(1,
'"' . $traceInfo->filename() .
"\":$currentLine: assign end_line " .
$func->name() . "\n");
# warn that we are deriving end lines
_generate_end_line_message();
$func->set_end_line($currentLine);
$modified = 1;
}
# we may not have set the end line above due to inconsistency
# but we also might not have line data
# - see .../tests/lcov/extract with gcc/4.8
if (!defined($func->end_line())) {
my $suffix =
lcovutil::explain_once('derive_end_line',
" See lcovrc man entry for 'derive_function_end_line'.");
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $func->filename() . '":' . $func->line() .
': failed to set end line for function ' .
$func->name() . '.' . $suffix);
next FUNC;
}
# now look for this function in each testcase -
# set the same endline (if not already set)
my $key = $first;
foreach my $tn ($funcData->keylist()) {
my $d = $funcData->value($tn);
my $f = $d->findKey($key);
if (defined($f)) {
if (!defined($f->end_line())) {
$f->set_end_line($func->end_line());
$modified = 1;
} else {
if ($f->end_line() != $func->end_line()) {
lcovutil::ignorable_error(
$lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $func->file() .
'":' . $first . ': function \'' .
$func->name() . ' last line is ' .
$func->end_line() . ' but is ' .
$f->end_line() . " in testcase '$tn'"
);
}
}
}
} #foreach testcase
} # for each function
my $end = Time::HiRes::gettimeofday();
$lcovutil::profileData{derive_end}{$traceInfo->filename()} = $end - $start;
return $modified;
}
sub _consistencySuffix
{
return lcovutil::explain_once('consistency_check',
"\n\tTo skip consistency checks, see the 'check_data_consistency' section in man lcovrc(5)."
);
}
sub _fixFunction
{
my ($traceInfo, $func, $count) = @_;
my @fix = ($func);
my $line = $func->line();
my $per_testcase = $traceInfo->testfnc();
foreach my $testname ($per_testcase->keylist()) {
my $data = $traceInfo->testfnc($testname);
my $f = $data->findKey($line);
push(@fix, $f) if defined($f);
}
foreach my $f (@fix) {
$f->[FunctionEntry::COUNT] = $count;
# and mark that each alias was hit...
my $aliases = $f->aliases();
foreach my $alias (keys %$aliases) {
$aliases->{$alias} += $count;
}
}
}
sub _checkConsistency
{
return unless $lcovutil::check_data_consistency;
my $traceInfo = shift;
my $modified = 0;
my $start = Time::HiRes::gettimeofday();
my @functions = sort { $a->line() <=> $b->line() }
grep({ defined($_->end_line()) } $traceInfo->func()->valuelist());
my $lineData = $traceInfo->sum();
my @lines = sort { $a <=> $b } $lineData->keylist()
if @functions;
my $currentLine = @lines ? shift(@lines) : 0;
FUNC: while (@functions) {
my $func = shift(@functions);
my $first = $func->line();
my $end = $func->end_line();
my $imHit = $func->hit() != 0; # I'm hit if any aliases is hit
my $lineHit = 0;
while ($first > $currentLine) {
# skip until we find the first line of the current function
if (@lines) {
$currentLine = shift(@lines);
} else {
# can only get here with really inconsistent data...would have
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $func->filename() .
"\":$first: file linecov does not match function cov data - skipping checks."
);
last FUNC;
}
}
while ($end >= $currentLine) {
# look for first covered line in this function -
# sufficient to just look at the such line
die("bug: " . $func->filename() . " [$first:$end]: $currentLine")
unless $first <= $currentLine && $currentLine <= $end;
my $hit = $lineData->value($currentLine);
$lineHit = 1 if $hit;
if ($hit && !$imHit) {
# don't warn about the first line of a lambda:
# - the decl may executed even if the lambda function itself is
# not called
# - if no other lines are hit, then then the function is not
# covered, but the coverage DB is consistent
# - if some other line _is_ hit, then, the data is inconsistent
if ($func->isLambda() && $currentLine == $first) {
$lineHit = 0;
last unless @lines;
$currentLine = shift(@lines);
next;
}
my $suffix =
($lcovutil::fix_inconsistency && lcovutil::is_ignored(
$lcovutil::ERROR_INCONSISTENT_DATA)
) ? ": function marked 'hit'" :
'';
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $func->filename() .
"\":$first: function '" . $func->name() .
"' is not hit but line $currentLine is$suffix." .
_consistencySuffix());
if ($lcovutil::fix_inconsistency) {
# if message was ignored, then mark the function and all
# its aliases hit
$imHit = 1;
$modified = 1;
_fixFunction($traceInfo, $func, $hit);
}
last; # only warn on the first hit line in the function
}
last if $lineHit && $hit; # can stop looking at this function now
last unless (@lines);
$currentLine = shift @lines;
}
if ($imHit && !$lineHit) {
my $suffix =
($lcovutil::fix_inconsistency &&
lcovutil::is_ignored($lcovutil::ERROR_INCONSISTENT_DATA)) ?
": function marked 'not hit'" :
'';
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $traceInfo->filename() .
"\":$first: function '" . $func->name() .
"' is hit but no contained lines are hit$suffix." .
_consistencySuffix());
if ($lcovutil::fix_inconsistency) {
# if message was ignored, then mark the function and its aliases
# not hit
$modified = 1;
_fixFunction($traceInfo, $func, 0);
}
}
}
# check MC/DC consistency -
# Note that we might have an MC/DC block on a line which has no
# linecov data
# This can happen for template functions (and similar) where the
# expression is statically determned to be true or false - and elided
# by the compiler. In that case, generate a new line coverpoint
if ($lcovutil::mcdc_coverage) {
my $mcdc = $traceInfo->mcdc();
my $testcase_mcdc = $traceInfo->testcase_mcdc();
foreach my $line ($mcdc->keylist()) {
my $lineHit = $lineData->value($line);
next if defined($lineHit);
lcovutil::info(1,
'"' . $traceInfo->filename() .
"\":$line: generating DA entry for orphan MC/DC\n"
);
my $block = $mcdc->value($line);
my ($found, $hit) = $block->totals();
$lineData->append($line, $hit);
# create the entry in the per-testcase data
foreach my $testcase ($testcase_mcdc->keylist()) {
my $m = $testcase_mcdc->value($testcase);
if ($m->value($line)) {
$traceInfo->test($testcase)->append($line, $hit);
}
}
}
}
# also check branch data consistency...should not have non-zero branch hit
# count if line is not hit - and vice versa
my $checkBranchConsistency =
!TraceFile::is_language('perl', $traceInfo->filename());
if ($lcovutil::br_coverage) {
my $brData = $traceInfo->sumbr();
foreach my $line ($brData->keylist()) {
# we expect to find a line everywhere there is a branch
my $lineHit = $lineData->value($line);
unless (defined($lineHit)) {
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $traceInfo->filename() .
"\":$line: location has branchcov but no linecov data"
. _consistencySuffix());
}
my $brHit = 0;
my $brd = $brData->value($line);
BLOCK: foreach my $id ($brd->blocks()) {
my $block = $brd->getBlock($id);
foreach my $br (@$block) {
if (0 != $br->count()) {
$brHit = 1;
last BLOCK;
}
}
}
if (!defined($lineHit)) {
# must have ignored the above error - so build fake line data here
# (maybe should delete the branch instead?)
$lineData->append($line, $brHit);
next;
}
if ($lineHit && !$brHit) {
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $traceInfo->filename() .
"\":$line: line is hit but no branches on line have been evaluated."
. _consistencySuffix())
if $checkBranchConsistency;
} elsif (!$lineHit && $brHit) {
lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
'"' . $traceInfo->filename() .
"\":$line: line is not hit but at least one branch on line has been evaluated."
. _consistencySuffix());
}
}
}
# @todo expect to have a branch everywhere we have an MCDC -
# further, expect the number of branches and conditions to match
my $end = Time::HiRes::gettimeofday();
$lcovutil::profileData{check_consistency}{$traceInfo->filename()} =
$end - $start;
return $modified;
}
sub _filterFile
{
my ($traceInfo, $source_file, $actions, $srcReader, $state) = @_;
my $modified = 0;
if (0 != ($actions & DID_DERIVE)) {
$modified = _deriveFunctionEndLines($traceInfo);
$modified ||= _checkConsistency($traceInfo);
if (0 == ($actions & DID_FILTER)) {
return [$traceInfo, $modified];
}
}
# @todo: if MCDC has just one expression, then drop it -
# it is equivalent to branch coverage.
my $region = $cov_filter[$FILTER_EXCLUDE_REGION];
my $branch_region = $cov_filter[$FILTER_EXCLUDE_BRANCH];
my $range = $cov_filter[$lcovutil::FILTER_LINE_RANGE];
my $branch_histogram = $cov_filter[$FILTER_BRANCH_NO_COND]
if (is_language('c', $source_file));
my $brace_histogram = $cov_filter[$FILTER_LINE_CLOSE_BRACE]
if (is_language('c', $source_file));
my $blank_histogram = $cov_filter[$FILTER_BLANK_LINE];
my $function_alias_histogram = $cov_filter[$FILTER_FUNCTION_ALIAS];
my $trivial_histogram = $cov_filter[$FILTER_TRIVIAL_FUNCTION];
my $filter_initializer_list = $cov_filter[$FILTER_INITIALIZER_LIST]
if (is_language('c', $source_file));
my $directive = $cov_filter[$FILTER_DIRECTIVE];
my $omit = $cov_filter[$FILTER_OMIT_PATTERNS]
if defined($FILTER_OMIT_PATTERNS);
my $mcdc_single = $cov_filter[$FILTER_MCDC_SINGLE]
if defined($FILTER_MCDC_SINGLE && $lcovutil::mcdc_coverage);
my $context = MessageContext->new("filtering $source_file");
if (lcovutil::is_filter_enabled()) {
lcovutil::info(1, "reading $source_file for lcov filtering\n");
$srcReader->open($source_file);
} else {
$srcReader->close();
}
my $path = ReadCurrentSource::resolve_path($source_file);
lcovutil::info(1, "extractVersion($path) for $source_file\n")
if $path ne $source_file;
# Note: this is checking the version of the 'current' file - even if
# we are actually reading the baseline version.
# - This is what we want, as the 'baseline read' is actually recovering/
# recreating the baseline source from the current source and the diff.
# - We already checked that the diff and the coverage DB baseline/current
# version data is consistent - so filtering will be accurate as long as
# we see the right 'current' source version.
my $fileVersion = lcovutil::extractFileVersion($path)
if $srcReader->notEmpty();
if (defined($fileVersion) &&
defined($traceInfo->version())
&&
!lcovutil::checkVersionMatch($source_file, $traceInfo->version(),
$fileVersion, 'filter')
) {
lcovutil::info(1,
'$source_file: skip filtering due to version mismatch\n');
return ($traceInfo, 0);
}
if (defined($lcovutil::func_coverage) &&
(0 != scalar(@lcovutil::exclude_function_patterns) ||
defined($trivial_histogram))
) {
# filter excluded function line ranges
my $funcData = $traceInfo->testfnc();
my $lineData = $traceInfo->test();
my $branchData = $traceInfo->testbr();
my $mcdcData = $traceInfo->testcase_mcdc();
my $checkData = $traceInfo->check();
my $reader = defined($trivial_histogram) &&
$srcReader->notEmpty() ? $srcReader : undef;
foreach my $tn ($lineData->keylist()) {
my $m =
_eraseFunctions($source_file, $reader,
$funcData->value($tn), $lineData->value($tn),
$branchData->value($tn), $mcdcData->value($tn),
$checkData->value($tn), $state,
0);
$modified ||= $m;
}
my $m =
_eraseFunctions($source_file, $reader,
$traceInfo->func(), $traceInfo->sum(),
$traceInfo->sumbr(), $traceInfo->mcdc(),
$traceInfo->check(), $state,
1);
$modified ||= $m;
}
return
unless ($srcReader->notEmpty() &&
lcovutil::is_filter_enabled());
my $filterExceptionBranches = FilterBranchExceptions->new();
my ($testdata, $sumcount, $funcdata, $checkdata, $testfncdata,
$testbrdata, $sumbrcount, $mcdc, $testmcdc) = $traceInfo->get_info();
foreach my $testname (sort($testdata->keylist())) {
my $testcount = $testdata->value($testname);
my $testfnccount = $testfncdata->value($testname);
my $testbrcount = $testbrdata->value($testname);
my $mcdc_count = $testmcdc->value($testname);
my $functionMap = $testfncdata->{$testname};
if ($lcovutil::func_coverage &&
$functionMap &&
($region || $range)) {
# Write function related data - sort by line number
foreach my $key ($functionMap->keylist()) {
my $data = $functionMap->findKey($key);
my $line = $data->line();
my $remove;
if ($srcReader->isOutOfRange($line, 'line')) {
$remove = 1;
lcovutil::info(1,
"filter FN " . $data->name() .
' ' . $data->file() . ":$line\n");
++$range->[-2]; # one location where this applied
} elsif ($srcReader->isExcluded($line)) {
$remove = 1;
my $reason = $srcReader->excludeReason($line);
foreach my $f ([ReadCurrentSource::EXCLUDE_REGION, $region],
[ReadCurrentSource::OMIT_LINE, $omit]) {
if ($reason & $f->[0]) {
$f->[1]->[-2] += scalar(keys %{$data->aliases()});
last;
}
}
}
if ($remove) {
#remove this function from everywhere
foreach my $tn ($testfncdata->keylist()) {
my $d = $testfncdata->value($tn);
my $f = $d->findKey($key);
next unless $f;
$d->remove($f);
}
# and remove from the master table
$funcdata->remove($funcdata->findKey($key));
$modified = 1;
next;
} # if excluded
} # foreach function
} # if func_coverage
# $testbrcount is undef if there are no branches in the scope
if (($lcovutil::br_coverage || $lcovutil::mcdc_coverage) &&
(defined($testbrcount) ||
defined($mcdc_count)) &&
($branch_histogram ||
$region ||
$branch_region ||
$range ||
$filterExceptionBranches ||
$omit)
) {
my %uniq;
# check MC/DC lines which are not also branch lines
foreach
my $line (defined($mcdc_count) ? $mcdc_count->keylist() : (),
defined($testbrcount) ? $testbrcount->keylist() : ()) {
next if exists($uniq{$line});
$uniq{$line} = 1;
# for counting: keep track filter which triggered exclusion -
my $remove;
# omit if line excluded or branches excluded on this line
if ($srcReader->isOutOfRange($line, 'branch')) {
# only counting line coverpoints that got excluded
die("inconsistent state") unless $range;
$remove = $range;
} elsif ($srcReader->isExcluded($line, 2)) {
# all branches here
my $reason = $srcReader->excludeReason($line);
foreach my $f ([ReadCurrentSource::EXCLUDE_REGION, $region],
[ReadCurrentSource::OMIT_LINE, $omit],
[ReadCurrentSource::EXCLUDE_DIRECTIVE,
$directive
],
[ReadCurrentSource::EXCLUDE_BRANCH_REGION,
$branch_region
]
) {
if ($reason & $f->[0]) {
$remove = $f->[1];
last;
}
}
die("inconsistent reason $reason") unless $remove;
} elsif ($branch_histogram &&
!$srcReader->containsConditional($line)) {
$remove = $branch_histogram;
}
if ($remove) {
foreach my $t ([$testbrdata, $sumbrcount, 'BRDA'],
[$testmcdc, $mcdc, 'MCDC']) {
my ($testCount, $sumCount, $str) = @$t;
next unless $sumCount;
my $brdata = $sumCount->value($line);
# might not be MCDC here, even if there is a branch
next unless $brdata;
++$remove->[-2]; # one line where we skip
$remove->[-1] += ($brdata->totals())[0];
lcovutil::info(2,
"filter $str '"
.
($line < $srcReader->numLines() ?
$srcReader->getLine($line) :
'<-->') .
"' $source_file:$line\n");
# now remove this branch everywhere...
foreach my $tn ($testCount->keylist()) {
my $d = $testCount->value($tn);
$d->remove($line, 1); # remove if present
}
# remove at top
$sumCount->remove($line);
$modified = 1;
}
} elsif (defined($filterExceptionBranches) &&
defined($sumbrcount) &&
defined($sumbrcount->value($line))) {
# exclude exception branches here
my $m =
$filterExceptionBranches->filter($line, $srcReader,
$sumbrcount, $testbrdata, $mcdc, $mcdc_count);
$modified ||= $m;
}
} # foreach line
} # if branch_coverage
if ($mcdc_single) {
# find single-expression MC/DC's - if there is a matching branch
# expression on the same line, then remove the MC/DC
foreach my $line ($mcdc_count->keylist()) {
my $block = $mcdc_count->value($line);
my $groups = $block->groups();
if (exists($groups->{1}) &&
scalar(keys %$groups) == 1) {
my $branch = $testbrcount->value($line);
next unless $branch && ($branch->totals())[0] == 2;
$mcdc_count->remove($line);
++$mcdc_single->[-2]; # one MC/DC skipped
$mcdc->remove($line); # remove at top
}
}
}
next
unless $region ||
$range ||
$brace_histogram ||
$branch_histogram ||
$directive ||
$omit ||
$filter_initializer_list;
# Line related data
my %initializerListRange;
foreach my $line ($testcount->keylist()) {
# don't suppresss if this line has associated branch or MC/DC data
next
if (
(defined($sumbrcount) && defined($sumbrcount->value($line))) ||
(defined($mcdc_count) &&
defined($mcdc_count->value($line))));
my $is_initializer;
my $is_filtered = undef;
if (exists($initializerListRange{$line})) {
$is_initializer = 1;
$is_filtered = $filter_initializer_list;
delete $initializerListRange{$line};
} elsif ($filter_initializer_list) {
# check if this line looks like a complete statement (balanced
# parens, ending with semicolon, etc -
# or whether subsequent lines are required for completion.
# If those subsequent lines have associated coverpoints,
# then those points should be filtered out (see issue #1222)
my $count = $srcReader->is_initializerList($line);
if (0 != $count) {
$is_initializer = 1;
$is_filtered = $filter_initializer_list;
for (my $l = $line + $count - 1; $l > $line; --$l) {
# record start of range
$initializerListRange{$l} = $line;
}
}
}
my $outOfRange = $srcReader->isOutOfRange($line, 'line')
unless $is_filtered;
$is_filtered = $lcovutil::cov_filter[$lcovutil::FILTER_LINE_RANGE]
if !defined($is_filtered) &&
defined($outOfRange) &&
$outOfRange;
my $excluded = $srcReader->isExcluded($line)
unless $is_filtered;
if (defined($excluded) && $excluded) {
my $reason = $srcReader->excludeReason($line);
foreach my $f ([ReadCurrentSource::EXCLUDE_REGION, $region],
[ReadCurrentSource::OMIT_LINE, $omit],
[ReadCurrentSource::EXCLUDE_DIRECTIVE,
$directive
]
) {
if ($reason & $f->[0]) {
$is_filtered = $f->[1];
last;
}
}
}
my $l_hit = $testcount->value($line);
my $isCloseBrace =
($brace_histogram &&
$srcReader->suppressCloseBrace($line, $l_hit, $testcount))
unless $is_filtered;
$is_filtered = $brace_histogram
if !defined($is_filtered) &&
defined($isCloseBrace) &&
$isCloseBrace;
my $isBlank =
($blank_histogram &&
($lcovutil::filter_blank_aggressive || $l_hit == 0) &&
$srcReader->isBlank($line))
unless $is_filtered;
$is_filtered = $blank_histogram
if !defined($is_filtered) && defined($isBlank) && $isBlank;
next unless $is_filtered;
$modified = 1;
lcovutil::info(2,
'filter DA (' . $is_filtered->[0] . ') '
.
($line < $srcReader->numLines() ?
("'" . $srcReader->getLine($line) . "'") :
"") .
" $source_file:$line\n");
unless (defined($outOfRange) && $outOfRange) {
# some filters already counted...
++$is_filtered->[-2]; # one location where this applied
++$is_filtered->[-1]; # one coverpoint suppressed
}
# now remove everywhere
foreach my $tn ($testdata->keylist()) {
my $d = $testdata->value($tn);
$d->remove($line, 1); # remove if present
}
$sumcount->remove($line);
if (exists($checkdata->{$line})) {
delete($checkdata->{$line});
}
} # foreach line
} #foreach test
# count the number of function aliases..
if ($function_alias_histogram) {
$function_alias_histogram->[-2] += $funcdata->numFunc(1);
$function_alias_histogram->[-1] += $funcdata->numFunc(0);
}
return ($traceInfo, $modified);
}
sub _mergeParallelChunk
{
# called from parent
my ($self, $tmp, $child, $children, $childstatus, $store, $worklist,
$childRetryCounts)
= @_;
my ($chunk, $forkAt, $chunkId) = @{$children->{$child}};
my $dumped = File::Spec->catfile($tmp, "dumper_$child");
my $childLog = File::Spec->catfile($tmp, "filter_$child.log");
my $childErr = File::Spec->catfile($tmp, "filter_$child.err");
lcovutil::debug(1, "merge:$child ID $chunkId\n");
my $start = Time::HiRes::gettimeofday();
foreach my $f ($childLog, $childErr) {
if (!-f $f) {
$f = ''; # there was no output
next;
}
if (open(RESTORE, "<", $f)) {
# slurp into a string and eval..
my $str = do { local $/; <RESTORE> }; # slurp whole thing
close(RESTORE) or die("unable to close $f: $!\n");
unlink $f;
$f = $str;
} else {
$f = "unable to open $f: $!";
if (0 == $childstatus) {
lcovutil::report_parallel_error('filter',
$ERROR_PARALLEL, $child, 0, $f, keys(%$children));
}
}
}
my $signal = $childstatus & 0xFF;
print(STDOUT $childLog)
if ((0 != $childstatus &&
$signal != POSIX::SIGKILL &&
$lcovutil::max_fork_fails != 0) ||
$lcovutil::verbose);
print(STDERR $childErr);
my $data = Storable::retrieve($dumped)
if (-f $dumped && $childstatus == 0);
if (defined($data)) {
my ($updates, $save, $state, $childFinish, $update) = @$data;
lcovutil::update_state(@$update);
#my $childCpuTime = $lcovutil::profileData{filt_child}{$chunkId};
#$totalFilterCpuTime += $childCpuTime;
#$intervalFilterCpuTime += $childCpuTime;
my $now = Time::HiRes::gettimeofday();
$lcovutil::profileData{filt_undump}{$chunkId} = $now - $start;
foreach my $patType (@{$store->[0]}) {
my $svType = shift(@{$save->[0]});
foreach my $p (@$patType) {
$p->[-1] += shift(@$svType);
}
}
for (my $i = scalar(@{$store->[1]}) - 1; $i >= 0; --$i) {
$store->[1]->[$i]->[-2] += $save->[1]->[$i]->[0];
$store->[1]->[$i]->[-1] += $save->[1]->[$i]->[1];
}
foreach my $d (@$updates) {
$self->_updateModifiedFile(@$d, $state);
}
my $final = Time::HiRes::gettimeofday();
$lcovutil::profileData{filt_merge}{$chunkId} = $final - $now;
$lcovutil::profileData{filt_queue}{$chunkId} = $start - $childFinish;
#$intervalMonitor->checkUpdate($processedFiles);
} else {
if (!-f $dumped ||
POSIX::SIGKILL == $signal) {
if (exists($childRetryCounts->{$chunkId})) {
$childRetryCounts->{$chunkId} += 1;
} else {
$childRetryCounts->{$chunkId} = 1;
}
lcovutil::report_fork_failure(
"filter segment $chunkId",
(POSIX::SIGKILL == $signal ?
"killed by OS - possibly due to out-of-memory" :
"serialized data $dumped not found"),
$childRetryCounts->{$chunkId});
push(@$worklist, $chunk);
} else {
lcovutil::report_parallel_error('filter',
$ERROR_PARALLEL, $child, $childstatus,
"unable to filter segment $chunkId: $@",
keys(%$children));
}
}
foreach my $f ($dumped) {
unlink $f
if -f $f;
}
my $to = Time::HiRes::gettimeofday();
$lcovutil::profileData{filt_chunk}{$chunkId} = $to - $forkAt;
}
sub _generate_end_line_message
{
# don't generate gcov warnings for tools that don't use gcov
return if grep({ /(llvm|perl|py|xml)2lcov/ } $lcovutil::tool_name);
if (lcovutil::warn_once('compiler_version', 1)) {
my $msg =
'Function begin/end line exclusions not supported with this version of GCC/gcov; require gcc/9 or newer';
if ((defined($lcovutil::derive_function_end_line) &&
$lcovutil::derive_function_end_line != 0) ||
(defined($lcovutil::derive_function_end_line_all_files) &&
$lcovutil::derive_function_end_line_all_files != 0)
) {
lcovutil::ignorable_warning($lcovutil::ERROR_UNSUPPORTED,
$msg .
": attempting to derive function end lines - see lcovrc man entry for 'derive_function_end_line'."
);
} else {
lcovutil::ignorable_error($lcovutil::ERROR_UNSUPPORTED,
$msg .
". See lcovrc man entry for 'derive_function_end_line'."
);
}
}
}
sub _updateModifiedFile
{
my ($self, $name, $traceFile, $state) = @_;
$self->[FILES]->{$name} = $traceFile;
_generate_end_line_message()
if $state->[0]->[1] != 0;
}
sub _processParallelChunk
{
# called from child
my $childStart = Time::HiRes::gettimeofday();
my ($tmp, $chunk, $srcReader, $save, $state, $forkAt, $chunkId) = @_;
# clear profile - want only my contribution
my $currentState = lcovutil::initial_state();
my $stdout_file = File::Spec->catfile($tmp, "filter_$$.log");
my $stderr_file = File::Spec->catfile($tmp, "filter_$$.err");
my $childInfo;
# set count to zero so we know how many got created in
# the child process
my $now = Time::HiRes::gettimeofday();
my $status = 0;
# clear current status so we see updates from this child
# pattern counts
foreach my $l (@{$save->[0]}) {
foreach my $p (@$l) {
$p->[-1] = 0;
}
}
# filter counts
foreach my $f (@{$save->[1]}) {
$f->[-1] = 0;
$f->[-2] = 0;
}
# using 'capture' here so that we can both capture/redirect geninfo
# messages from a child process during parallel execution AND
# redirect stdout/stderr from gcov calls.
# It does not work to directly open/reopen the STDOUT and STDERR
# descriptors due to interactions between the child and parent
# processes (see the Capture::Tiny doc for some details)
my $start = Time::HiRes::gettimeofday();
my @updates;
my ($stdout, $stderr, $code) = Capture::Tiny::capture {
eval {
foreach my $d (@$chunk) {
# could keep track of individual file time if we wanted to
my ($data, $modified) = _filterFile(@$d, $srcReader, $state);
lcovutil::info(1,
$d->[1] . ' is ' .
($modified ? '' : 'NOT ') . "modified\n");
if ($modified) {
push(@updates, [$d->[1], $data]);
}
}
};
if ($@) {
print(STDERR $@);
$status = 1;
}
};
my $end = Time::HiRes::gettimeofday();
# collect pattern counts
my @pcounts;
foreach my $l (@{$save->[0]}) {
my @c = map({ $_->[-1] } @$l); # grab the counts
push(@pcounts, \@c);
}
$save->[0] = \@pcounts;
# filter counts
foreach my $f (@{$save->[1]}) {
$f = [$f->[-2], $f->[-1]];
}
# parent might have already caught an error, cleaned up and
# removed the tempdir and exited.
lcovutil::check_parent_process();
# print stdout and stderr ...
foreach my $d ([$stdout_file, $stdout], [$stderr_file, $stderr]) {
next unless ($d->[1]); # only print if there is something to print
my $f = InOutFile->out($d->[0]);
my $h = $f->hdl();
print($h $d->[1]);
}
my $dumpf = File::Spec->catfile($tmp, "dumper_$$");
my $then = Time::HiRes::gettimeofday();
$lcovutil::profileData{filt_proc}{$chunkId} = $then - $forkAt;
$lcovutil::profileData{filt_child}{$chunkId} = $end - $start;
my $data;
eval {
$data = Storable::store([\@updates, $save, $state, $then,
lcovutil::compute_update($currentState)
],
$dumpf);
};
if ($@ || !defined($data)) {
lcovutil::ignorable_error($lcovutil::ERROR_PARALLEL,
"Child $$ serialize failed" . ($@ ? ": $@" : ''));
}
return $status;
}
# chunkID is only used for uniquification and as a key in profile data.
# We want this umber to be unique - even if we process more than one TraceFile
our $masterChunkID = 0;
sub _processFilterWorklist
{
my ($self, $srcReader, $fileList) = @_;
my $chunkSize;
my $parallel = $lcovutil::lcov_filter_parallel;
# not much point in parallel calculation if the number of files is small
my $workList = $fileList;
if (exists($ENV{LCOV_FORCE_PARALLEL}) ||
(scalar(@$fileList) > 50 &&
$parallel &&
1 < $lcovutil::maxParallelism)
) {
$parallel = $lcovutil::maxParallelism;
if (defined($lcovutil::lcov_filter_chunk_size)) {
if ($lcovutil::lcov_filter_chunk_size =~ /^(\d+)\s*(%?)$/) {
if (defined($2) && $2) {
# a percentage
$chunkSize = int(scalar(@$fileList) * $1 / 100);
} else {
# an absolute value
$chunkSize = $1;
}
} else {
lcovutil::ignorable_warning($lcovutil::ERROR_FORMAT,
"lcov_filter_chunk_size '$lcovutil::lcov_filter_chunk_size not recognized - ignoring\n"
);
}
}
if (!defined($chunkSize)) {
$chunkSize =
$maxParallelism ?
(int(0.8 * scalar(@$fileList) / $lcovutil::maxParallelism)) :
1;
if ($chunkSize > 100) {
$chunkSize = 100;
} elsif ($chunkSize < 2) {
$chunkSize = 1;
}
}
if ($chunkSize != 1 ||
exists($ENV{LCOV_FORCE_PARALLEL})) {
$workList = [];
my $idx = 0;
my $current = [];
# maybe sort files by number of lines, then distribute larger ones
# across chunks? Or sort so total number of lines is balanced
foreach my $f (@$fileList) {
push(@$current, $f);
if (++$idx == $chunkSize) {
$idx = 0;
push(@$workList, $current);
$current = [];
}
}
push(@$workList, $current) if (@$current);
lcovutil::info("Filter: chunkSize $chunkSize nChunks " .
scalar(@$workList) . "\n");
}
}
my @state = (['saw_unsupported_end_line', 0],);
# keep track of patterns application counts before we fork children
my @pats = grep { @$_ }
(\@lcovutil::exclude_function_patterns, \@lcovutil::omit_line_patterns);
# and also filter application counts
my @filters = grep { defined($_) } @lcovutil::cov_filter;
my @save = (\@pats, \@filters);
my $processedChunks = 0;
my $currentParallel = 0;
my %children;
my $tmp = File::Temp->newdir(
"filter_datXXXX",
DIR => $lcovutil::tmp_dir,
CLEANUP => !defined($lcovutil::preserve_intermediates)
)
if (exists($ENV{LCOV_FORCE_PARALLEL}) ||
$parallel > 1);
my $failedAttempts = 0;
my %childRetryCounts;
do {
CHUNK: while (@$workList) {
my $d = pop(@$workList);
++$processedChunks;
# save current counts...
$state[0]->[1] = 0;
if (ref($d->[0]) eq 'TraceInfo') {
# serial processing...
my ($data, $modified) = _filterFile(@$d, $srcReader, \@state);
$self->_updateModifiedFile($d->[1], $data, \@state)
if $modified;
} else {
my $currentSize = 0;
if (0 != $lcovutil::maxMemory) {
$currentSize = lcovutil::current_process_size();
}
while ($currentParallel >= $lcovutil::maxParallelism ||
($currentParallel > 1 &&
(($currentParallel + 1) * $currentSize) >
$lcovutil::maxMemory)
) {
lcovutil::info(1,
"memory constraint ($currentParallel + 1) * $currentSize > $lcovutil::maxMemory violated: waiting. "
. (scalar(@$workList) - $processedChunks + 1)
. " remaining\n")
if ((($currentParallel + 1) * $currentSize) >
$lcovutil::maxMemory);
my $child = wait();
my $childstatus = $?;
unless (exists($children{$child})) {
lcovutil::report_unknown_child($child);
next;
}
eval {
$self->_mergeParallelChunk($tmp, $child, \%children,
$childstatus, \@save, $workList,
\%childRetryCounts);
};
if ($@) {
$childstatus = 1 << 8 unless $childstatus;
lcovutil::report_parallel_error('filter',
$lcovutil::ERROR_CHILD, $child, $childstatus, $@);
}
--$currentParallel;
}
# parallel processing...
$lcovutil::deferWarnings = 1;
my $now = Time::HiRes::gettimeofday();
my $pid = fork();
if (!defined($pid)) {
# fork failed
++$failedAttempts;
lcovutil::report_fork_failure('process filter chunk',
$!, $failedAttempts);
--$processedChunks;
push(@$workList, $d);
next CHUNK;
}
$failedAttempts = 0;
if (0 == $pid) {
# I'm the child
my $status =
_processParallelChunk($tmp, $d, $srcReader, \@save,
\@state, $now, $masterChunkID);
exit($status); # normal return
} else {
# parent
$children{$pid} = [$d, $now, $masterChunkID];
lcovutil::debug(1, "fork:$pid ID $masterChunkID\n");
++$currentParallel;
}
++$masterChunkID;
}
} # while (each segment in worklist)
while ($currentParallel != 0) {
my $child = wait();
my $childstatus = $?;
unless (exists($children{$child})) {
lcovutil::report_unknown_child($child);
next;
}
--$currentParallel;
eval {
$self->_mergeParallelChunk($tmp, $child, \%children,
$childstatus, \@save, $workList, \%childRetryCounts);
};
if ($@) {
$childstatus = 1 << 8 unless $childstatus;
lcovutil::report_parallel_error('filter',
$lcovutil::ERROR_CHILD, $child, $childstatus, $@);
}
}
} while (@$workList); # outer do/while - to catch spaceouts
lcovutil::info("Finished filter file processing\n");
}
sub applyFilters
{
my $self = shift;
my $srcReader = shift;
$srcReader = ReadCurrentSource->new()
unless defined($srcReader);
my $mask = DID_FILTER;
$mask |= DID_DERIVE
if (defined($lcovutil::derive_function_end_line) &&
$lcovutil::derive_function_end_line != 0);
return
if ($mask == ($self->[STATE] & $mask));
# have to look through each file in each testcase; they may be different
# due to differences in #ifdefs when the corresponding tests were compiled.
my @filter_workList;
my $computeEndLine =
(0 == ($self->[STATE] & DID_DERIVE) &&
defined($lcovutil::derive_function_end_line) &&
$lcovutil::derive_function_end_line != 0 &&
defined($lcovutil::func_coverage));
foreach my $name ($self->files()) {
my $traceInfo = $self->data($name);
die("expected TraceInfo, got '" . ref($traceInfo) . "'")
unless ('TraceInfo' eq ref($traceInfo));
my $source_file = $traceInfo->filename();
if (TraceFile::skipCurrentFile($source_file)) {
$self->remove($source_file);
next;
}
if (lcovutil::is_external($source_file)) {
lcovutil::info("excluding 'external' file '$source_file'\n");
$self->remove($source_file);
next;
}
# derive function end line for C/C++ and java code if requested
# (not trying to handle python nested functions, etc.)
# However, see indent handling in the py2lcov script. Arguably, that
# could/should be done here/in Perl rather than in Python.)
# Jacoco pretends to report function end line - but it appears
# to be the last line executed - not the actual last line of
# the function - so broken/completely useless.
my $actions = 0;
if ($computeEndLine &&
($lcovutil::derive_function_end_line_all_files ||
is_language('c|java|perl', $source_file))
) {
# try to derive end lines if at least one is unknown.
# can't compute for lambdas because we can't distinguish
# the last line reliably.
$actions = DID_DERIVE
if grep({ !($_->isLambda() || defined($_->end_line())) }
$traceInfo->func()->valuelist());
}
if ((defined($lcovutil::func_coverage) &&
(0 != scalar(@lcovutil::exclude_function_patterns) ||
defined($lcovutil::cov_filter[$FILTER_TRIVIAL_FUNCTION]))) ||
(is_language('c|perl|python|java', $source_file) &&
lcovutil::is_filter_enabled())
) {
# we are forking anyway - so also compute end lines there
$actions |= DID_FILTER;
push(@filter_workList, [$traceInfo, $name, $actions]);
} else {
if (0 != $actions) {
# all we are doing is deriving function end lines - which doesn't
# take long enough to be worth forking
TraceFile::_deriveFunctionEndLines($traceInfo);
}
TraceFile::_checkConsistency($traceInfo);
}
} # foreach file
$self->[STATE] |= DID_DERIVE;
if (@filter_workList) {
lcovutil::info("Apply filtering..\n");
$self->_processFilterWorklist($srcReader, \@filter_workList);
# keep track - so we don't do this again
$self->[STATE] |= DID_FILTER;
}
}
sub is_language
{
my ($lang, $filename) = @_;
my $idx = index($filename, '.');
my $ext = $idx == -1 ? '' : substr($filename, $idx);
foreach my $l (split('\|', $lang)) {
die("unknown language '$l'")
unless exists($lcovutil::languageExtensions{$l});
my $extensions = $lcovutil::languageExtensions{$l};
return 1 if ($ext =~ /\.($extensions)$/);
}
return 0;
}
# Read in the contents of the .info file specified by INFO_FILENAME. Data will
# be returned as a reference to a hash containing the following mappings:
#
# %result: for each filename found in file -> \%data
#
# %data: "test" -> \%testdata
# "sum" -> \%sumcount
# "func" -> \%funcdata
# "found" -> $lines_found (number of instrumented lines found in file)
# "hit" -> $lines_hit (number of executed lines in file)
# "function_found" -> $fn_found (number of instrumented functions found in file)
# "function_hit" -> $fn_hit (number of executed functions in file)
# "branch_found" -> $br_found (number of instrumented branches found in file)
# "branch_hit" -> $br_hit (number of executed branches in file)
# "check" -> \%checkdata
# "testfnc" -> \%testfncdata
# "testbr" -> \%testbrdata
# "sumbr" -> \%sumbrcount
#
# %testdata : name of test affecting this file -> \%testcount
# %testfncdata: name of test affecting this file -> \%testfnccount
# %testbrdata: name of test affecting this file -> \%testbrcount
#
# %testcount : line number -> execution count for a single test
# %testfnccount: function name -> execution count for a single test
# %testbrcount : line number -> branch coverage data for a single test
# %sumcount : line number -> execution count for all tests
# %sumbrcount : line number -> branch coverage data for all tests
# %funcdata : FunctionMap: function name -> FunctionEntry
# %checkdata : line number -> checksum of source code line
# $brdata : BranchData vector of items: block, branch, taken
#
# Note that .info file sections referring to the same file and test name
# will automatically be combined by adding all execution counts.
#
# Note that if INFO_FILENAME ends with ".gz", it is assumed that the file
# is compressed using GZIP. If available, GUNZIP will be used to decompress
# this file.
#
# Die on error.
#
sub _read_info
{
my ($self, $tracefile, $readSourceCallback, $verify_checksum) = @_;
$verify_checksum = 0 unless defined($verify_checksum);
if (!defined($readSourceCallback)) {
$readSourceCallback = ReadCurrentSource->new();
}
# per file data
my %perfile;
my $sumcount; # line total counts in this file
my $funcdata; # function total counts in this file
my $sumbrcount; # branch total counts
my $mcdcCount; # MD/DC total counts
my $checkdata; # line checksums
my %perTestData;
my %summaryData;
# hash of per-testcase coverage data per testcase, in this file
my $testdata; # hash of testname -> line coverage
my $testfncdata; # hash of testname -> function coverage
my $testbrdata; # hash of testname -> branch data
my $testMcdc; # -> MC/DC data
my $testcount; # line coverage for particular testcase
my $testfnccount; # func coverage " "
my $testbrcount; # branch coverage " "
my $testcase_mcdc; # MC/DC coverage " "
my $testname; # Current test name
my $filename; # Current filename
my $current_mcdc;
my $changed_testname; # If set, warn about changed testname
lcovutil::info(1, "Reading data file $tracefile\n");
# Check if file exists and is readable
stat($tracefile);
if (!(-r _)) {
die("cannot read file $tracefile!\n");
}
# Check if this is really a plain file
if (!(-f _)) {
die("not a plain file: $tracefile!\n");
}
# Check for .gz extension
my $inFile = InOutFile->in($tracefile, $lcovutil::demangle_cpp_cmd);
my $infoHdl = $inFile->hdl();
$testname = "";
my $fileData;
# HGC: somewhat of a hack.
# There are duplicate lines in the geninfo output result - for example,
# line '2095' may have multiple DA (line) entries, and may have multiple
# 'BRDA' entries - each with a different number of branches and different
# count
# The hack is to put branches into a hash keyed by branch ID - and
# merge elements with the same key if we run into them in the multiple
# times in the same 'file' data (within an SF entry).
my %nextBranchId; # line -> integer ID
my ($currentBranchLine, $skipBranch);
my $functionMap;
my %excludedFunction;
my $skipCurrentFile = 0;
my %fnIdxMap;
while (<$infoHdl>) {
chomp($_);
my $line = $_;
$line =~ s/\s+$//; # whitespace
next if $line =~ /^#/; # skip comment
if ($line =~ /^[SK]F:(.*)/) {
# Filename information found
if ($1 =~ /^\s*$/) {
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$tracefile\":$.: unexpected empty file name in record '$line'"
);
$skipCurrentFile = 1;
next;
}
#if ($self->contains($filename)) {
# # we expect there to be only one entry for each source file in each section
# lcovutil::ignorable_warning($lcovutil::ERROR_FORMAT,
# "Duplicate entries for \"$filename\""
# . ($testname ? " in testcase '$testname'" : '') . '.');
#}
$filename = ReadCurrentSource::resolve_path($1, 1);
# should this one be skipped?
$skipCurrentFile = skipCurrentFile($filename);
if ($skipCurrentFile) {
if (!exists($lcovutil::excluded_files{$filename})) {
$lcovutil::excluded_files{$filename} = 1;
lcovutil::info("Excluding $filename\n");
}
next;
}
# Retrieve data for new entry
%nextBranchId = ();
%excludedFunction = ();
%fnIdxMap = ();
if ($verify_checksum) {
# unconditionally 'close' the current file - in case we don't
# open a new one. If that happened, then we would be looking
# at the source for some previous file.
$readSourceCallback->close();
undef $currentBranchLine;
if (is_language('c', $filename)) {
$readSourceCallback->open($filename);
}
}
$fileData = $self->data($filename);
# record line number where file entry found - can use it in error messages
$fileData->location($tracefile, $.);
($testdata, $sumcount, $funcdata,
$checkdata, $testfncdata, $testbrdata,
$sumbrcount, $mcdcCount, $testMcdc) = $fileData->get_info();
if (defined($testname)) {
$testcount = $fileData->test($testname);
$functionMap = $fileData->testfnc($testname);
$testbrcount = $fileData->testbr($testname);
$testcase_mcdc = $fileData->testcase_mcdc($testname);
} else {
$testcount = CountData->new($filename, 1);
$testfnccount = CountData->new($filename, 0);
$testbrcount = BranchData->new();
$testcase_mcdc = MCDC_Data->new();
$functionMap = FunctionMap->new($filename);
}
next;
}
next if $skipCurrentFile;
# Switch statement
# Please note: if you add or change something here (lcov info file format) -
# then please make corresponding changes to the 'write_info' method, below
# and update the format description found in .../man/geninfo.1.
foreach ($line) {
next if $line =~ /^#/; # skip comment
/^VER:(.+)$/ && do {
# revision control version string found
# we might try to set the version multiple times if the
# file appears multiple times in the .info file
if (defined($fileData->version()) &&
$fileData->version() eq $1) {
# this is OK -
# we might try to set the version multiple times if the
# file appears multiple times in the .info file.
# This can happen, with some translators
last;
}
$fileData->version($1);
last;
};
/^TN:([^,]*)(,diff)?/ && do {
# Test name information found
$testname = defined($1) ? $1 : "";
my $orig = $testname;
if ($testname =~ s/\W/_/g) {
$changed_testname = $orig;
}
$testname .= $2 if (defined($2));
if (defined($ignore_testcase_name) &&
$ignore_testcase_name) {
lcovutil::debug(1,
"using default testcase rather than $testname at $tracefile:$.\n"
);
$testname = '';
}
last;
};
/^DA:(\d+),([^,]+)(,([^,\s]+))?/ && do {
my ($line, $count, $checksum) = ($1, $2, $4);
if ($line <= 0) {
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$tracefile\":$.: unexpected line number '$line' in .info file record '$_'"
);
# just keep invalid number - if error ignored
# last;
}
if ($readSourceCallback->notEmpty()) {
# does the source checksum match the recorded checksum?
if ($verify_checksum) {
if (defined($checksum)) {
my $content = $readSourceCallback->getLine($line);
my $chk =
defined($content) ?
Digest::MD5::md5_base64($content) :
0;
if ($chk ne $checksum) {
lcovutil::ignorable_error(
$lcovutil::ERROR_VERSION,
"checksum mismatch at between source $filename:$line and $tracefile: $checksum -> $chk"
);
}
} else {
# no checksum there
lcovutil::ignorable_error($lcovutil::ERROR_VERSION,
"no checksum for $filename:$line in $tracefile"
);
}
}
}
# hold line, count and testname for postprocessing?
my $linesum = $fileData->sum();
# Execution count found, add to structure
# Add summary counts
$linesum->append($line, $count);
# Add test-specific counts
if (defined($testname)) {
$fileData->test($testname)->append($line, $count, 1);
}
# Store line checksum if available
if (defined($checksum) &&
$lcovutil::verify_checksum) {
# Does it match a previous definition
if ($fileData->check()->mapped($line) &&
($fileData->check()->value($line) ne $checksum)) {
lcovutil::ignorable_error($lcovutil::ERROR_VERSION,
"checksum mismatch at $filename:$line in $tracefile"
);
}
$fileData->check()->replace($line, $checksum);
}
last;
};
/^FN:(\d+),((\d+),)?(.+)$/ && do {
last if (!$lcovutil::func_coverage);
# Function data found, add to structure
my $lineNo = $1;
my $fnName = $4;
my $end_line = $3;
if (!grep({ $fnName =~ $_ }
@lcovutil::suppress_function_patterns) &&
($lineNo <= 0 ||
(defined($end_line) && $end_line <= 0))
) {
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$tracefile\":$.: unexpected function line '$lineNo' in .info file record '$_'"
) if $lineNo <= 0;
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$tracefile\":$.: unexpected function end line '$end_line' in .info file record '$_'"
) if defined($end_line) && $end_line <= 0;
}
# the function may already be defined by another testcase
# (for the same file)
$functionMap->define_function($fnName, $lineNo,
$end_line ? $end_line : undef,
, "\"$tracefile\":$.");
last;
};
# Hit count may be float if Perl decided to convert it
/^FNDA:([^,]+),(.+)$/ && do {
last if (!$lcovutil::func_coverage);
my $fnName = $2;
my $hit = $1;
# error checking is in the addAlias method
$functionMap->add_count($fnName, $hit);
last;
};
# new format...
/^FNL:(\d+),(\d+)(,(\d+))?$/ && do {
last if (!$lcovutil::func_coverage);
my $fnIndex = $1;
my $lineNo = $2;
my $end_line = $4;
die("unexpected duplicate index $fnIndex")
if exists($fnIdxMap{$fnIndex});
$fnIdxMap{$fnIndex} = [$lineNo, $end_line];
last;
};
/^FNA:(\d+),([^,]+),(.+)$/ && do {
last if (!$lcovutil::func_coverage);
my $fnIndex = $1;
my $hit = $2;
my $alias = $3;
die("unknown index $fnIndex")
unless exists($fnIdxMap{$fnIndex});
my ($lineNo, $end_line) = @{$fnIdxMap{$fnIndex}};
my $fn =
$functionMap->define_function($alias, $lineNo, $end_line,
"\"$tracefile\":$.");
$fn->addAlias($alias, $hit);
last;
};
/^BRDA:(\d+),(e?)(\d+),(.+)$/ && do {
last if (!$lcovutil::br_coverage);
# Branch coverage data found
# line data is "lineNo,blockId,(branchIdx|branchExpr),taken
# - so grab the last two elements, split on the last comma,
# and check whether we found an integer or an expression
my ($line, $is_exception, $block, $d) =
($1, defined($2) && 'e' eq $2, $3, $4);
if ($line <= 0) {
# Python coverage.py emits line number 0 (zero) for branches
# - which is bogus, as there is no line number zero,
# and the corresponding branch expression is not there in
# any case.
# Meantime: this confuses the lcov DB - so we simply skip
# such data.
# Note that we only need to check while reading .info files.
# - if we wrote one from geninfo, then we will not have
# produced bogus data - so no need to check.
# - only some (broken) external tool could have the issue
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$tracefile\":$.: unexpected line number '$line' in .info file record '$_'"
);
# just keep invalid line number if error ignored
# last;
}
last if $is_exception && $lcovutil::exclude_exception_branch;
my $comma = rindex($d, ',');
my $taken = substr($d, $comma + 1);
my $expr = substr($d, 0, $comma);
# Notes:
# - there may be other branches on the same line (..the next
# contiguous BRDA entry).
# There should always be at least 2.
# - $block is generally '0' - but is used to distinguish cases
# where different branch constructs appear on the same line -
# e.g., due to template instantiation or funky macro usage -
# see .../tests/lcov/branch
# - $taken can be a number or '-'
# '-' means that the first clause of the branch short-circuited -
# so this branch was not evaluated at all.
# In any branch pair, either all should have a 'taken' of '-'
# or at least one should have a non-zero taken count and
# the others should be zero.
# - in order to support Verilog expressions, we treat the
# 'branchId' as an arbitrary string (e.g., ModelSim will
# generate an CNF or truth-table like entry corresponding
# to the branch.
my $key = "$line,$block";
my $branch =
exists($nextBranchId{$key}) ? $nextBranchId{$key} :
0;
$nextBranchId{$key} = $branch + 1;
my $br =
BranchBlock->new($branch, $taken, $expr, $is_exception);
$fileData->sumbr()->append($line, $block, $br, $filename);
# Add test-specific counts
if (defined($testname)) {
$fileData->testbr($testname)
->append($line, $block, $br, $filename);
}
last;
};
/^MCDC:(\d+),(\d+),([tf]),(\d+),(\d+),(.+)$/ && do {
# line number, groupSize, sense, count, index, expression
# 'sense' is t/f: was this expression sensitized
last unless $lcovutil::mcdc_coverage;
my ($line, $groupSize, $sense, $count, $idx, $expr) =
($1, $2, $3, $4, $5, $6);
if ($line <= 0) {
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$tracefile\":$.: unexpected line number '$line' in condition data record '$_'."
);
# keep invalid line number
#last;
}
if (!defined($current_mcdc) ||
$current_mcdc->line() != $line) {
if ($current_mcdc) {
$fileData->mcdc()->close_mcdcBlock($current_mcdc);
$fileData->testcase_mcdc($testname)
->append_mcdc(Storable::dclone($current_mcdc))
if (defined($testname));
}
$current_mcdc =
$fileData->mcdc()->new_mcdc($fileData, $line);
}
$current_mcdc->insertExpr($filename, $groupSize, $sense eq 't',
$count, $idx, $expr);
last;
};
/^end_of_record/ && do {
# Found end of section marker
if ($filename) {
if (!defined($fileData->version()) &&
$lcovutil::compute_file_version &&
@lcovutil::extractVersionScript) {
my $version = lcovutil::extractFileVersion($filename);
$fileData->version($version)
if (defined($version) && $version ne "");
}
if ($lcovutil::func_coverage) {
if ($funcdata != $functionMap) {
$funcdata->union($functionMap);
}
}
if ($current_mcdc) {
# close the current expression in case the next file
# has an expression on the same line
$fileData->mcdc()->close_mcdcBlock($current_mcdc);
$fileData->testcase_mcdc($testname)
->append_mcdc(Storable::dclone($current_mcdc))
if (defined($testname));
$current_mcdc = undef;
}
# some paranoic checks
$self->data($filename)->check_data();
last;
}
};
/^(FN|BR|L|MC)[HF]/ && do {
last; # ignore count records
};
/^\s*$/ && do {
last; # ignore empty line
};
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$tracefile\":$.: unexpected .info file record '$_'");
# default
last;
}
}
# Calculate lines_found and lines_hit for each file
foreach $filename ($self->files()) {
#$data = $result{$filename};
($testdata, $sumcount, undef, undef, $testfncdata, $testbrdata,
$sumbrcount) = $self->data($filename)->get_info();
# Filter out empty files
if ($self->data($filename)->sum()->entries() == 0) {
delete($self->[FILES]->{$filename});
next;
}
my $filedata = $self->data($filename);
# Filter out empty test cases
foreach $testname ($filedata->test()->keylist()) {
if (!$filedata->test()->mapped($testname) ||
scalar($filedata->test($testname)->keylist()) == 0) {
$filedata->test()->remove($testname);
$filedata->testfnc()->remove($testname);
$filedata->testbr()->remove($testname);
$filedata->testcase_mcdc()->remove($testname);
}
}
}
if (scalar($self->files()) == 0) {
lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
"no valid records found in tracefile $tracefile");
}
if (defined($changed_testname)) {
lcovutil::ignorable_warning($lcovutil::ERROR_FORMAT,
"invalid characters removed from testname in " .
"tracefile $tracefile: '$changed_testname'->'$testname'\n"
);
}
}
# write data to filename (stdout if '-')
# returns nothing
sub write_info_file($$$)
{
my ($self, $filename, $do_checksum) = @_;
if ($self->empty()) {
lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
"coverage DB is empty");
}
my $file = InOutFile->out($filename);
my $hdl = $file->hdl();
$self->write_info($hdl, $do_checksum);
}
#
# write data in .info format
# returns array of (lines found, lines hit, functions found, functions hit,
# branches found, branches_hit)
sub write_info($$$)
{
my $self = $_[0];
local *INFO_HANDLE = $_[1];
my $verify_checksum = defined($_[2]) ? $_[2] : 0;
my $br_found;
my $br_hit;
my $srcReader = ReadCurrentSource->new()
if ($verify_checksum);
foreach my $comment ($self->comments()) {
print(INFO_HANDLE '#', $comment, "\n");
}
foreach my $filename (sort($self->files())) {
my $entry = $self->data($filename);
my $source_file = $entry->filename();
die("expected to have have filtered $source_file out")
if lcovutil::is_external($source_file);
die("expected TraceInfo, got '" . ref($entry) . "'")
unless ('TraceInfo' eq ref($entry));
my ($testdata, $sumcount, $funcdata,
$checkdata, $testfncdata, $testbrdata,
$sumbrcount, $sum_mcdc, $testmcdc) = $entry->get_info();
# munge the source file name, if requested
$source_file = ReadCurrentSource::resolve_path($source_file, 1);
# Please note: if you add or change something here (lcov info file format) -
# then please make corresponding changes to the '_read_info' method, above
# and update the format description found in .../man/geninfo.1.
foreach my $testname (sort($testdata->keylist())) {
my $testcount = $testdata->value($testname);
my $testfnccount = $testfncdata->value($testname);
my $testbrcount = $testbrdata->value($testname);
my $mcdc = $testmcdc->value($testname);
print(INFO_HANDLE "TN:$testname\n");
print(INFO_HANDLE "SF:$source_file\n");
print(INFO_HANDLE "VER:" . $entry->version() . "\n")
if defined($entry->version());
if (defined($srcReader)) {
lcovutil::info(1, "reading $source_file for lcov checksum\n");
$srcReader->open($source_file);
}
my $functionMap = $testfncdata->{$testname};
if ($lcovutil::func_coverage &&
$functionMap) {
# Write function related data - sort by line number then
# by name (compiler-generated functions may have same line)
# sort enables diff of output data files, for testing
my @functionOrder =
sort({ $functionMap->findKey($a)->line()
cmp $functionMap->findKey($b)->line() or
$a cmp $b } $functionMap->keylist());
my $fnIndex = -1;
my $f_found = 0;
my $f_hit = 0;
foreach my $key (@functionOrder) {
my $data = $functionMap->findKey($key);
my $aliases = $data->aliases();
my $line = $data->line();
if ($line <= 0) {
my $alias = (sort keys %$aliases)[0];
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$source_file\": unexpected line number '$line' for function $alias"
);
# if message is ignored, leave bogus entry in the data
}
++$fnIndex;
my $endLine =
defined($data->end_line()) ?
',' . $data->end_line() :
'';
# print function leader
print(INFO_HANDLE "FNL:$fnIndex,$line$endLine\n");
++$f_found;
my $counted = 0;
foreach my $alias (sort keys %$aliases) {
my $hit = $aliases->{$alias};
++$f_hit if $hit > 0 && !$counted;
$counted ||= $hit > 0;
# print the alias
print(INFO_HANDLE "FNA:$fnIndex,$hit,$alias\n");
}
}
print(INFO_HANDLE "FNF:$f_found\n");
print(INFO_HANDLE "FNH:$f_hit\n");
}
# $testbrcount is undef if there are no branches in the scope
if ($lcovutil::br_coverage &&
defined($testbrcount)) {
# Write branch related data
my $br_found = 0;
my $br_hit = 0;
foreach my $line (sort({ $a <=> $b } $testbrcount->keylist())) {
if ($line <= 0) {
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$source_file\": unexpected line number '$line' in branch data record."
);
# keep bogus data if error ignored
# last;
}
my $brdata = $testbrcount->value($line);
# want the block_id to be treated as 32-bit unsigned integer
# (need masking to match regression tests)
my $mask = (1 << 32) - 1;
foreach my $block_id (sort(($brdata->blocks()))) {
my $blockData = $brdata->getBlock($block_id);
$block_id &= $mask;
foreach my $br (@$blockData) {
my $taken = $br->data();
my $branch_id = $br->id();
my $branch_expr = $br->expr();
# mostly for Verilog: if there is a branch expression: use it.
printf(INFO_HANDLE "BRDA:%u,%s%u,%s,%s\n",
$line,
$br->is_exception() ? 'e' : '',
$block_id,
defined($branch_expr) ? $branch_expr :
$branch_id,
$taken);
$br_found++;
$br_hit++
if ($taken ne '-' && $taken > 0);
}
}
}
if ($br_found > 0) {
print(INFO_HANDLE "BRF:$br_found\n");
print(INFO_HANDLE "BRH:$br_hit\n");
}
}
if ($mcdc &&
$lcovutil::mcdc_coverage) {
my $mcdc_found = 0;
my $mcdc_hit = 0;
foreach my $line (sort({ $a <=> $b } $mcdc->keylist())) {
if ($line <= 0) {
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$source_file\": unexpected line number '$line' in MC/DC data record."
);
}
my $m = $mcdc->value($line);
my $groups = $m->groups();
foreach my $groupSize (sort keys %$groups) {
my $exprs = $groups->{$groupSize};
my $index = -1;
foreach my $e (@$exprs) {
$mcdc_found += 2;
++$index;
foreach my $sense ('t', 'f') {
my $count = $e->count($sense eq 't');
++$mcdc_hit if 0 != $count;
print(INFO_HANDLE
"MCDC:$line,$groupSize,$sense,$count,$index,"
. $e->expression(),
"\n");
}
}
}
}
if ($mcdc_found != 0) {
print(INFO_HANDLE "MCF:$mcdc_found\n");
print(INFO_HANDLE "MCH:$mcdc_hit\n");
}
}
# Write line related data
my $found = 0;
my $hit = 0;
foreach my $line (sort({ $a <=> $b } $testcount->keylist())) {
if ($line <= 0) {
lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
"\"$source_file\": unexpected line number '$line' in 'line' data record."
);
}
my $l_hit = $testcount->value($line);
my $chk = '';
if ($verify_checksum) {
if (exists($checkdata->{$line})) {
$chk = $checkdata->{$line};
} elsif (defined($srcReader) &&
$srcReader->notEmpty()) {
my $content = $srcReader->getLine($line);
$chk =
defined($content) ?
Digest::MD5::md5_base64($content) :
0;
}
$chk = ',' . $chk if ($chk);
}
print(INFO_HANDLE "DA:$line,$l_hit$chk\n");
$found++;
$hit++
if ($l_hit > 0);
}
print(INFO_HANDLE "LF:$found\n");
print(INFO_HANDLE "LH:$hit\n");
print(INFO_HANDLE "end_of_record\n");
}
}
}
package AggregateTraces;
# parse sna merge TraceFiles - possibly in parallel
# - common utility, used by lcov 'add_trace' and genhtml multi-file read
# If set, create map of unique function to list of testcase/info
# files which hit that function at least once
our $function_mapping;
# need a static external segment index lest the exe aggregate multiple groups of data
our $segmentIdx = 0;
sub find_from_glob
{
my @merge;
die("no files specified") unless (@_);
foreach my $pattern (@_) {
if (-f $pattern) {
# this is a glob match...
push(@merge, $pattern);
next;
}
$pattern =~ s/([^\\]) /$1\\ /g # explicitly escape spaces
unless $^O =~ /Win/;
my @files = glob($pattern); # perl returns files in ASCII sorted order
lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
"no files matching pattern $pattern")
unless scalar(@files);
for (my $i = 0; $i <= $#files; ++$i) {
my $f = $files[$i];
if (-d $f) {
my $cmd =
"find '$f' -name '$lcovutil::info_file_pattern' -type f";
my ($stdout, $stderr, $code) = Capture::Tiny::capture {
system($cmd);
};
# can fail due to unreadable entry - but might still
# have returned data to process
lcovutil::ignorable_error($lcovutil::ERROR_UTILITY,
"error in \"$cmd\": $stderr")
if $code;
my @found = split(' ', $stdout);
lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
"no files matching '$lcovutil::info_file_pattern' found in $f"
) unless (@found);
push(@files, @found);
next;
}
unless (-r $f || -f $f) {
lcovutil::ignorable_error($lcovutil::ERROR_MISSING,
"'$f' found from pattern '$pattern' is not a readable file"
);
next;
}
push(@merge, $f);
}
}
lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
"no matching file found in '['" . join(', ', @_) . "]'")
unless (@merge);
return @merge;
}
sub _process_segment($$$)
{
my ($total_trace, $readSourceFile, $segment) = @_;
my @interesting;
my $total = scalar(@$segment);
foreach my $tracefile (@$segment) {
my $now = Time::HiRes::gettimeofday();
--$total;
lcovutil::info("Merging $tracefile..$total remaining"
.
($lcovutil::debug ?
(' mem:' . lcovutil::current_process_size()) :
'') .
"\n"
) if (1 != scalar(@$segment)); # ...in segment $segId
my $context = MessageContext->new("merging $tracefile");
if (!-f $tracefile ||
-z $tracefile) {
lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
"trace file '$tracefile' "
.
(-z $tracefile ? 'is empty' :
'does not exist'));
next;
}
my $current;
eval {
$current = TraceFile->load($tracefile, $readSourceFile,
$lcovutil::verify_checksum, 1);
lcovutil::debug("after load $tracefile: memory: " .
lcovutil::current_process_size() . "\n")
if $lcovutil::debug; # predicate to avoid function call...
};
my $then = Time::HiRes::gettimeofday();
$lcovutil::profileData{parse}{$tracefile} = $then - $now;
if ($@) {
lcovutil::ignorable_error($lcovutil::ERROR_CORRUPT,
"unable to read trace file '$tracefile': $@");
next;
}
if ($function_mapping) {
foreach my $srcFileName ($current->files()) {
my $traceInfo = $current->data($srcFileName);
my $funcData = $traceInfo->func();
foreach my $funcKey ($funcData->keylist()) {
my $funcEntry = $funcData->findKey($funcKey);
if (0 != $funcEntry->hit()) {
# function is hit in this file
my $key = $funcEntry->file() . ":$funcKey";
$function_mapping->{$key} = [$funcEntry->name(), []]
unless exists($function_mapping->{$key});
die("mismatched function name for " .
$funcEntry->name() .
" at $funcKey in $tracefile")
unless $funcEntry->name() eq
$function_mapping->{$key}->[0];
push(@{$function_mapping->{$key}->[1]}, $tracefile);
}
}
}
} else {
if ($total_trace->merge_tracefile($current, TraceInfo::UNION)) {
push(@interesting, $tracefile);
}
}
my $end = Time::HiRes::gettimeofday();
$lcovutil::profileData{append}{$tracefile} = $end - $then;
}
return @interesting;
}
sub merge
{
my $readSourceFile;
my $t = ref($_[0]);
if (!defined($_[0]) || '' eq $t) {
# backward compatibility - arg is undefined or is a filename
$readSourceFile = ReadCurrentSource->new();
shift unless defined($_[0]);
} else {
$readSourceFile = shift;
die("unexpected arg $t")
unless grep(/^$t$/, ('ReadCurrentSource', 'ReadBaselineSource'));
}
my $nTests = scalar(@_);
if (1 < $nTests) {
lcovutil::info("Combining tracefiles.\n");
} else {
lcovutil::info("Reading tracefile $_[0].\n");
}
$lcovutil::profileData{parse} = {}
unless exists($lcovutil::profileData{parse});
$lcovutil::profileData{append} = {}
unless exists($lcovutil::profileData{append});
my @effective;
# source-based filters are somewhat expensive - so we turn them
# off for file read and only re-enable when we write the data back out
my $save_filters = lcovutil::disable_cov_filters();
my $total_trace = TraceFile->new();
if (!(defined($lcovutil::maxParallelism) && defined($lcovutil::maxMemory)
)) {
lcovutil::init_parallel_params();
}
if (0 != $lcovutil::maxMemory &&
1 != $lcovutil::maxParallelism) {
# estimate the number of processes we think we can run..
my $currentSize = lcovutil::current_process_size();
# guess that the data size is no smaller than one of the files we will be reading
# which one is largest?
my $fileSize = 0;
foreach my $n (@_) {
my $s = (stat($n))[7];
$fileSize = $s if $s > $fileSize;
}
my $size = $currentSize + $fileSize;
my $num = int($lcovutil::maxMemory / $size);
lcovutil::debug(
"Sizes: self:$currentSize file:$fileSize total:$size num:$num paralled:$lcovutil::maxParallelism\n"
);
if ($num < $lcovutil::maxParallelism) {
$num = $num > 1 ? $num : 1;
lcovutil::info(
"Throttling to '--parallel $num' due to memory constraint\n");
$lcovutil::maxParallelism = $num;
}
}
# use a particular file sort order - to somewhat minimize order effects
my $filelist = \@_;
my @sorted_filelist;
if ($lcovutil::sort_inputs) {
@sorted_filelist = sort({ $a cmp $b } @_);
$filelist = \@sorted_filelist;
}
if (1 != $lcovutil::maxParallelism &&
(exists($ENV{LCOV_FORCE_PARALLEL}) ||
1 < $nTests)
) {
# parallel implementation is to segment the file list into N
# segments, then parse-and-merge scalar(@merge)/N files in each slave,
# then merge the slave result.
# The reasoning is that one of our examples appears to take 1.3s to
# load the trace file, and 0.8s to merge it into the master list.
# We thus want to parallelize both the load and the merge, as much as
# possible.
# Note that we try to keep the files in the order they were specified
# in the segments (i.e., so adjacent files go in order, into the same
# segment). This plays more nicely with the "--prune-tests" option
# because we expect that files with similar names (e.g., as returned
# by 'glob' have similar coverage profiles and are thus not likely to
# all be 'effective'. If we had put them into different segments,
# then each segment might think that their variant is 'effective' -
# whereas we will notice that only one is effective if they are all
# in the same segment.
my @segments;
my $testsPerSegment =
($nTests > $lcovutil::maxParallelism) ?
int(($nTests + $lcovutil::maxParallelism - 1) /
$lcovutil::maxParallelism) :
1;
my $idx = 0;
foreach my $tracefile (@$filelist) {
my $seg = $idx / $testsPerSegment;
$seg -= 1 if $seg == $lcovutil::maxParallelism;
push(@segments, [])
if ($seg >= scalar(@segments));
push(@{$segments[$seg]}, $tracefile);
++$idx;
}
lcovutil::info("Using " .
scalar(@segments) .
' segment' . (scalar(@segments) > 1 ? 's' : '') .
" of $testsPerSegment test" .
($testsPerSegment > 1 ? 's' : '') . "\n");
$lcovutil::profileData{config} = {}
unless exists($lcovutil::profileData{config});
$lcovutil::profileData{config}{segments} = scalar(@segments);
# kind of a hack...write to the named directory that the user gave
# us rather than to a funny generated name
my $tempDir = defined($lcovutil::tempdirname) ? $lcovutil::tempdirname :
lcovutil::create_temp_dir();
my %children;
my @pending;
my $patterns;
my $failedAttempts = 0;
my %childRetryCounts;
do {
while (my $segment = pop(@segments)) {
$lcovutil::deferWarnings = 1;
my $now = Time::HiRes::gettimeofday();
my $pid = fork();
if (!defined($pid)) {
++$failedAttempts;
lcovutil::report_fork_failure('process segment',
$!, $failedAttempts);
push(@segments, $segment);
next;
}
$failedAttempts = 0;
if (0 == $pid) {
# I'm the child
my $stdout_file =
File::Spec->catfile($tempDir, "lcov_$$.log");
my $stderr_file =
File::Spec->catfile($tempDir, "lcov_$$.err");
my $currentState = lcovutil::initial_state();
my $status = 0;
my @interesting;
my ($stdout, $stderr, $code) = Capture::Tiny::capture {
eval {
@interesting =
_process_segment($total_trace,
$readSourceFile, $segment);
};
if ($@) {
print(STDERR $@);
$status = 1;
}
my $then = Time::HiRes::gettimeofday();
$lcovutil::profileData{$segmentIdx}{total} =
$then - $now;
};
# print stdout and stderr ...
foreach
my $d ([$stdout_file, $stdout], [$stderr_file, $stderr])
{
next
unless ($d->[1])
; # only print if there is something to print
my $f = InOutFile->out($d->[0]);
my $h = $f->hdl();
print($h $d->[1]);
}
my $file = File::Spec->catfile($tempDir, "dumper_$$");
my $data;
eval {
$data =
Storable::store(
[$total_trace,
\@interesting,
$function_mapping,
lcovutil::compute_update($currentState)
],
$file);
};
if ($@ || !defined($data)) {
lcovutil::ignorable_error($lcovutil::ERROR_PARALLEL,
"Child $$ serialize failed" . ($@ ? ": $@" : ''));
}
exit($status);
} else {
$children{$pid} = [$now, $segmentIdx, $segment];
push(@pending, $segment);
}
$segmentIdx++;
}
# now wait for all the children to finish...
foreach (@pending) {
my $child = wait();
my $now = Time::HiRes::gettimeofday();
my $childstatus = $? >> 8;
unless (exists($children{$child})) {
lcovutil::report_unknown_child($child);
next;
}
my ($start, $idx, $segment) = @{$children{$child}};
lcovutil::info(
1,
"Merging segment $idx, status $childstatus"
.
(
$lcovutil::debug ?
(' mem:' . lcovutil::current_process_size()) :
'') .
"\n");
my $dumpfile = File::Spec->catfile($tempDir, "dumper_$child");
my $childLog = File::Spec->catfile($tempDir, "lcov_$child.log");
my $childErr = File::Spec->catfile($tempDir, "lcov_$child.err");
foreach my $f ($childLog, $childErr) {
if (!-f $f) {
$f = ''; # there was no output
next;
}
if (open(RESTORE, "<", $f)) {
# slurp into a string and eval..
my $str =
do { local $/; <RESTORE> }; # slurp whole thing
close(RESTORE) or die("unable to close $f: $!\n");
unlink $f
unless ($str && $lcovutil::preserve_intermediates);
$f = $str;
} else {
$f = "unable to open $f: $!";
if (0 == $childstatus) {
lcovutil::report_parallel_error('aggregate',
$ERROR_PARALLEL, $child, 0, $f,
keys(%children));
}
}
}
my $signal = $childstatus & 0xFF;
print(STDOUT $childLog)
if ((0 != $childstatus &&
$signal != POSIX::SIGKILL &&
$lcovutil::max_fork_fails != 0) ||
$lcovutil::verbose);
print(STDERR $childErr);
# undump the data
my $data = Storable::retrieve($dumpfile)
if (-f $dumpfile && 0 == $childstatus);
if (defined($data)) {
eval {
my ($current, $changed, $func_map, $update) = @$data;
my $then = Time::HiRes::gettimeofday();
$lcovutil::profileData{$idx}{undump} = $then - $now;
lcovutil::update_state(@$update);
if ($function_mapping) {
if (!defined($func_map)) {
lcovutil::report_parallel_error(
'aggregate',
$ERROR_PARALLEL,
$child,
0,
"segment $idx returned empty function data",
keys(%children));
next;
}
while (my ($key, $data) = each(%$func_map)) {
$function_mapping->{$key} = [$data->[0], []]
unless exists($function_mapping->{$key});
die("mismatched function name '" .
$data->[0] . "' at $key")
unless ($data->[0] eq
$function_mapping->{$key}->[0]);
push(@{$function_mapping->{$key}->[1]},
@{$data->[1]});
}
} else {
if (!defined($current)) {
lcovutil::report_parallel_error(
'aggregate',
$ERROR_PARALLEL,
$child,
0,
"segment $idx returned empty trace data",
keys(%children));
next;
}
if ($total_trace->merge_tracefile(
$current, TraceInfo::UNION
)) {
# something in this segment improved coverage...so save
# the effective input files from this one
push(@effective, @$changed);
}
}
}; # end eval
if ($@) {
$childstatus = 1 << 8 unless $childstatus;
lcovutil::report_parallel_error(
'aggregate',
$ERROR_PARALLEL,
$child,
$childstatus,
"unable to deserialize segment $idx $dumpfile:$@",
keys(%children));
}
}
if (!defined($data) || 0 != $childstatus) {
if (!-f $dumpfile ||
POSIX::SIGKILL == $signal) {
if (exists($childRetryCounts{$idx})) {
$childRetryCounts{$idx} += 1;
} else {
$childRetryCounts{$idx} = 1;
}
lcovutil::report_fork_failure(
"aggregate segment $idx",
(POSIX::SIGKILL == $signal ?
"killed by OS - possibly due to out-of-memory"
:
"serialized data $dumpfile not found"),
$childRetryCounts{$idx});
push(@segments, $segment);
} else {
lcovutil::report_parallel_error('aggregate',
$ERROR_CHILD, $child, $childstatus,
"while processing segment $idx",
keys(%children));
}
}
my $end = Time::HiRes::gettimeofday();
$lcovutil::profileData{$idx}{merge} = $end - $start;
unlink $dumpfile
if -f $dumpfile;
}
} while (@segments);
} else {
# sequential
@effective = _process_segment($total_trace, $readSourceFile, $filelist);
}
if (defined($lcovutil::tempdirname) &&
!$lcovutil::preserve_intermediates) {
# won't remove if directory not empty...probably what I want, for debugging
rmdir($lcovutil::tempdirname);
}
#...and turn any enabled filters back on...
lcovutil::reenable_cov_filters($save_filters);
# filters had been disabled - need to explicitly exclude function bodies
$total_trace->applyFilters($readSourceFile);
return ($total_trace, \@effective);
}
# call the common initialization functions
lcovutil::define_errors();
lcovutil::init_filters();
1;
|