File: api.c

package info (click to toggle)
f2j 0.8.1%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,604 kB
  • sloc: ansic: 18,992; java: 3,987; yacc: 3,804; sh: 153; makefile: 149
file content (4353 lines) | stat: -rw-r--r-- 97,881 bytes parent folder | download | duplicates (6)
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
/** @file api.c
 * Contains an API for generating Java bytecode.
 */

#include "api.h"

/**
 * This code creates the JVM_FIELD structure, assigns the
 * appropriate values into it, and inserts it into the field list.
 *
 * @param cclass -- The class to which the field should be added.
 * @param name -- The name of the field.
 * @param desc -- The field descriptor.
 * @param acc_flag -- The access flags for this field (for example
 *     JVM_ACC_PUBLIC, JVM_ACC_STATIC, etc)
 *
 * @returns The new JVM_FIELD structure.
 */

JVM_FIELD *
bc_add_field(JVM_CLASS *cclass, char *name, char *desc, u2 acc_flag)
{
  JVM_FIELD * tmpfield;
  int c;

  if(!cclass || !name || !desc) {
    BAD_ARG();
    return NULL;
  }

  debug_msg("bc_add_field() creating new field for %s - %s\n",name,desc);

  tmpfield = (JVM_FIELD *) malloc(sizeof(JVM_FIELD));
  
  if(!tmpfield)
    return NULL;

  tmpfield->access_flags = acc_flag;
  tmpfield->class = cclass;

  c = cp_find_or_insert(cclass, CONSTANT_Utf8, name);
  if(c < 0) {
    free(tmpfield);
    return NULL;
  }

  tmpfield->name_index = c;

  c = cp_find_or_insert(cclass, CONSTANT_Utf8, desc);
  if(c < 0) {
    free(tmpfield);
    return NULL;
  }

  tmpfield->descriptor_index = c;

  tmpfield->attributes_count = 0;
  tmpfield->attributes = make_dl();

  if(!tmpfield->attributes) {
    free(tmpfield);
    return NULL;
  }

  dl_insert_b(cclass->fields, tmpfield);

  cclass->fields_count++;

  return tmpfield;
}

/**
 * Returns the fully-qualified class name for the given class.
 * Generally this is the package name followed by the class name,
 * however the class name could already be a qualified name.
 *
 * @param thisclass -- The name of the class.
 * @param package_name -- The name of the package.  If NULL, the
 *   fully-qualified name is just the class name.
 *
 * @returns The fully-qualified class name.  Returns NULL on error.
 */

char *
bc_get_full_classname(char *thisclass, char *package_name)
{
  char *pname, *t;

  if(!thisclass) {
    BAD_ARG();
    return NULL;
  }
    
  /* maybe this is already qualified.  if so, just return a dup of the
   * class name.
   */
  for(t = thisclass; *t != '\0'; t++)
    if( (*t == '/') || (*t == '.') )
      return char_substitute(thisclass, '.', '/');

  if(package_name != NULL) {
    pname = (char *)malloc(strlen(thisclass) + strlen(package_name) + 2);

    if(!pname)
      return NULL;

    /* issue a warning if the package name has some trailing junk. */
    if(!isalnum((int)*(package_name + (strlen(package_name)-1))))
      debug_err("WARNING: last char of package name not alphanumeric.\n");

    t = char_substitute(package_name, '.', '/');

    if(!t) {
      free(pname);
      return NULL;
    }

    strcpy(pname, t);
    strcat(pname, "/");
    strcat(pname, thisclass);

    free(t);
    return pname;
  }
  else
    return strdup(thisclass);
}

/**
 * Creates a new class file structure.
 *
 * @param name -- The name of the class.
 * @param srcFile -- The name of the source code file from which this
 *   class was compiled.  If NULL, no SourceFile attribute will be created
 *   for this class.
 * @param super_class -- The name of the superclass for this class.  If NULL,
 *   the superclass is set to java.lang.Object.
 * @param package_name -- The name of the package this class file belongs to.
 *   If NULL, no package will be specified.
 * @param acc_flag -- The access flags for this class (for example
 *     JVM_ACC_PUBLIC, etc)
 *
 * @returns The new class file structure.
 */

JVM_CLASS *
bc_new_class(char *name, char *srcFile, char *super_class, 
   char *package_name, u2 acc_flag)
{
  CP_INFO *utf8node = NULL, *classnode = NULL;
  JVM_CLASS * tmp = NULL;
  char * fullclassname = NULL;
  int c;

#define err_new_class() \
      if(tmp->constant_pool) dl_delete_list(tmp->constant_pool); \
      tmp->constant_pool = NULL; \
      if(tmp->fields) dl_delete_list(tmp->fields); \
      tmp->fields = NULL; \
      if(tmp->interfaces) dl_delete_list(tmp->interfaces); \
      tmp->interfaces = NULL; \
      if(tmp->attributes) dl_delete_list(tmp->attributes); \
      tmp->attributes = NULL; \
      if(tmp->methods) dl_delete_list(tmp->methods); \
      tmp->methods = NULL; \
      if(fullclassname) free(fullclassname); \
      if(tmp) free(tmp); \
      if(utf8node && utf8node->cpnode.Utf8.bytes) \
         free(utf8node->cpnode.Utf8.bytes); \
      if(classnode && classnode->cpnode.Utf8.bytes) \
         free(classnode->cpnode.Utf8.bytes);
  
  if(!name) {
    BAD_ARG();
    return NULL;
  }

  tmp = (JVM_CLASS *)malloc(sizeof(JVM_CLASS));

  if(!tmp)
    return NULL;

  tmp->magic = JVM_MAGIC;

  bc_set_class_version(tmp, JVM_MAJOR_VER, JVM_MINOR_VER);

  /* we'll fill out the constant pool and fields later. */
  tmp->constant_pool_count = 0;
  tmp->constant_pool = make_dl();

  tmp->fields_count = 0;
  tmp->fields = make_dl();

  tmp->interfaces_count = 0;
  tmp->interfaces = make_dl();

  tmp->attributes_count = 0;
  tmp->attributes = make_dl();

  tmp->methods_count = 0;
  tmp->methods = make_dl();

  tmp->access_flags = acc_flag;

  if(!tmp->constant_pool || !tmp->fields || !tmp->interfaces || 
     !tmp->attributes || !tmp->methods) 
  {
    err_new_class();
    return NULL;
  }

  /* first create an entry for 'this'.  the class file variable this_class
   * points to a CONSTANT_Class_info entry in the constant pool, which in
   * turn points to a CONSTANT_Utf8_info entry representing the name of
   * this class.  so, first we create the Utf8 entry, then the Class entry.
   */

  fullclassname = bc_get_full_classname(name, package_name);

  if(!fullclassname) {
    err_new_class();
    return NULL;
  }

  debug_msg("##creating new entry, this -> %s\n",fullclassname);

  c = cp_find_or_insert(tmp, CONSTANT_Class, fullclassname);
  if(c < 0) {
    err_new_class();
    return NULL;
  }

  tmp->this_class = c;

  /* if a superclass was specified, then insert an entry for it into
   * the constant pool and set the superclass field in the class struct.
   * otherwise, set the superclass to java.lang.Object.
   */

  if(super_class) {
    char *sc;

    sc = char_substitute(super_class, '.', '/');

    if(!sc) {
      err_new_class();
      return NULL;
    }

    c = cp_find_or_insert(tmp, CONSTANT_Class, sc);

    free(sc);

    if(c < 0) {
      err_new_class();
      if(sc) free(sc);
      return NULL;
    }

    tmp->super_class = c;
  }
  else {
    c = cp_find_or_insert(tmp, CONSTANT_Class, "java/lang/Object");

    if(c < 0) {
      err_new_class();
      return NULL;
    }

    tmp->super_class = c;
  }

  /* the only attributes allowed for a class file are SourceFile and
   * Deprecated.  if srcFile was supplied by the user, then add a
   * SourceFile attribute to this class.
   */

  if(srcFile) {
    if(bc_add_source_file_attr(tmp, srcFile)) {
      err_new_class();
      return NULL;
    }
  }

  free(fullclassname);

  return tmp;
}

/**
 * Sets the version for this class file.  From the JVM Spec:
 *
 * The Java virtual machine implementation of Sun's JDK release 1.0.2
 * supports class file format versions 45.0 through 45.3 inclusive.
 * Sun's JDK releases 1.1.X can support class file formats of versions
 * in the range 45.0 through 45.65535 inclusive. Implementations of
 * version 1.2 of the Java 2 platform can support class file formats
 * of versions in the range 45.0 through 46.0 inclusive.
 *
 * @param class -- The class file whose version is to be set.
 * @param major -- The major version.
 * @param minor -- The minor version.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_class_version(JVM_CLASS *class, int major, int minor)
{
  if(!class) {
    BAD_ARG();
    return -1;
  }

  class->major_version = (u2)major;
  class->minor_version = (u2)minor;

  if((unsigned int)class->major_version != major)
    debug_err("Warning: possible truncation in bc_set_class_version.\n");

  if((unsigned int)class->minor_version != minor)
    debug_err("Warning: possible truncation in bc_set_class_version.\n");

  return 0;
}

/**
 * Creates a SourceFile attribute containing the specified name and adds it
 * to the given class file.
 *
 * @param class -- The class to which the SourceFile attribute should be
 *    added.
 * @param filename -- The name of the source code file from which this
 *   class was compiled.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_add_source_file_attr(JVM_CLASS *class, char *filename)
{
  JVM_ATTRIBUTE *attr_temp;
  int c;

  if(!class || !filename) {
    BAD_ARG();
    return -1;
  }

  class->attributes_count++;

  attr_temp = (JVM_ATTRIBUTE *)malloc(sizeof(JVM_ATTRIBUTE));

  if(!attr_temp)
    return -1;

  c = cp_find_or_insert(class, CONSTANT_Utf8, "SourceFile");

  if(c < 0) {
    free(attr_temp);
    return -1;
  }

  attr_temp->attribute_name_index = c;
  attr_temp->attribute_length = 2;  /* SourceFile attr length always 2 */
  attr_temp->attr.SourceFile = (struct SourceFile_attribute *)
       malloc(sizeof(struct SourceFile_attribute));

  if(!attr_temp->attr.SourceFile) {
    free(attr_temp);
    return -1;
  }

  c = cp_find_or_insert(class, CONSTANT_Utf8, filename);

  if(c < 0) {
    free(attr_temp);
    free(attr_temp->attr.SourceFile);
    return -1;
  }

  attr_temp->attr.SourceFile->sourcefile_index = c;

  dl_insert_b(class->attributes,attr_temp);

  return 0;
}

/**
 * Lets the user define their own attribute and add it to the class file.
 *
 * @param class -- The class to which this attribute should be added.
 * @param attribute_name -- The name of the attribute.
 * @param attribute_length -- The length of the attribute pointed to by the
 *    'attribute_data' parameter.
 * @param attribute_data -- Pointer to the attribute contents.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_add_user_defined_class_attr(JVM_CLASS *class, char *attribute_name,
  int attribute_length, void *attribute_data)
{
  JVM_ATTRIBUTE *attr_temp;
  int c;

  if(!class || !attribute_name || !attribute_data) {
    BAD_ARG();
    return -1;
  }

  attr_temp = (JVM_ATTRIBUTE *)malloc(sizeof(JVM_ATTRIBUTE));

  if(!attr_temp)
    return -1;

  c = cp_find_or_insert(class, CONSTANT_Utf8, attribute_name);

  if(c < 0) {
    free(attr_temp);
    return -1;
  }

  attr_temp->attribute_name_index = c;
  attr_temp->attribute_length = attribute_length;
  attr_temp->attr.UserDefined = (struct UserDefined_attribute *)
       malloc(sizeof(struct UserDefined_attribute));

  if(!attr_temp->attr.UserDefined) {
    free(attr_temp);
    return -1;
  }

  attr_temp->attr.UserDefined->data = (void *)malloc(attribute_length);

  if(!attr_temp->attr.UserDefined->data) {
    free(attr_temp->attr.UserDefined);
    free(attr_temp);
    return -1;
  }

  memcpy(attr_temp->attr.UserDefined->data, attribute_data, attribute_length);

  class->attributes_count++;

  dl_insert_b(class->attributes,attr_temp);

  return 0;
}

/**
 * Adds the "Deprecated" attribute to the specified class.
 *
 * @param class -- The class to be set as deprecated.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_class_deprecated(JVM_CLASS *class)
{
  JVM_ATTRIBUTE *attr_temp;

  if(!class) {
    BAD_ARG();
    return -1;
  }

  attr_temp = bc_new_deprecated_attr(class);

  if(!attr_temp)
    return -1;

  class->attributes_count++;

  dl_insert_b(class->attributes,attr_temp);

  return 0;
}

/**
 * Adds the specified interface to the list of interfaces that
 * this class implements.
 *
 * @param class -- The class to which the interface should be added.
 * @param interface -- The name of the interface that this class implements.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_add_class_interface(JVM_CLASS *class, char *interface)
{
  int *copy;
  int c;
  char *t;

  if(!class || !interface) {
    BAD_ARG();
    return -1;
  }

  t = char_substitute(interface, '.', '/');

  if(!t)
    return -1;

  c = cp_find_or_insert(class, CONSTANT_Class, t);

  free(t);

  if(c < 0) {
    free(t);
    return -1;
  }

  copy = (int *)malloc(sizeof(int));

  if(!copy) {
    free(t);
    return -1;
  }

  *copy = c;

  class->interfaces_count++;

  dl_insert_b(class->interfaces, copy);

  return 0;
}

/**
 * Adds the "ConstantValue" attribute to the specified field.  This allows
 * specifying the value that the field should have when the class containing
 * it is initialized.  Since a field with a ConstantValue attribue must be
 * static, this function will set the JVM_ACC_STATIC flag in the field's
 * access flags.
 *
 * @param field -- The field to which the ConstantValue attribute should be
 *   added.
 * @param tag -- The type of this constant (e.g. CONSTANT_Integer, 
 *   CONSTANT_Utf8, etc).  See the JVM_CONSTANT enum for the possible
 *   data types.
 * @param value -- Pointer to the constant value.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_constant_value_attr(JVM_FIELD *field, 
  JVM_CONSTANT tag, const void *value)
{
  JVM_ATTRIBUTE *attr_temp;
  int c;
  int val_idx;

  if(!field || !value) {
    BAD_ARG();
    return -1;
  }

  c = cp_manual_insert(field->class, tag, value);

  if(c < 0)
    return -1;

  val_idx = c;  

  /* JVM spec says that the ACC_STATIC flag must be set for a field
   * which has a ConstantValue attribute.
   */
  field->access_flags |= JVM_ACC_STATIC;

  attr_temp = (JVM_ATTRIBUTE *)malloc(sizeof(JVM_ATTRIBUTE));

  if(!attr_temp)
    return -1;

  c = cp_find_or_insert(field->class, CONSTANT_Utf8, "ConstantValue");
  if(c < 0) {
    free(attr_temp);
    return -1;
  }

  attr_temp->attribute_name_index = c;
  attr_temp->attribute_length = 2;  /* ConstantValue attr length always 2 */
  attr_temp->attr.ConstantValue = (struct ConstantValue_attribute *)
       malloc(sizeof(struct ConstantValue_attribute));

  if(!attr_temp->attr.ConstantValue) {
    free(attr_temp);
    return -1;
  }

  attr_temp->attr.ConstantValue->constantvalue_index = val_idx;

  field->attributes_count++;

  dl_insert_b(field->attributes,attr_temp);

  return 0;
}

/**
 * Adds the "Synthetic" attribute to the specified field.  The Synthetic
 * attribute is used for class members that do not appear in the source code.
 *
 * @param field -- The field to which the Synthetic attribute should be
 *   added.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_field_synthetic(JVM_FIELD *field)
{
  JVM_ATTRIBUTE *attr_temp;

  if(!field) {
    BAD_ARG();
    return -1;
  }

  attr_temp = bc_new_synthetic_attr(field->class);

  if(!attr_temp)
    return -1;

  field->attributes_count++;

  dl_insert_b(field->attributes,attr_temp);

  return 0;
}

/**
 * Adds the "Deprecated" attribute to the specified field.
 *
 * @param field -- The field to which the Deprecated attribute should be
 *   added.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_field_deprecated(JVM_FIELD *field)
{
  JVM_ATTRIBUTE *attr_temp;

  if(!field) {
    BAD_ARG();
    return -1;
  }

  attr_temp = bc_new_deprecated_attr(field->class);

  if(!attr_temp)
    return -1;

  field->attributes_count++;

  dl_insert_b(field->attributes,attr_temp);

  return 0;
}

/**
 * Adds the "Deprecated" attribute to the specified method.
 *
 * @param meth -- The method to which the Deprecated attribute should be
 *   added.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_method_deprecated(JVM_METHOD *meth)
{
  JVM_ATTRIBUTE *attr_temp;

  if(!meth) {
    BAD_ARG();
    return -1;
  }

  attr_temp = bc_new_deprecated_attr(meth->class);

  if(!attr_temp)
    return -1;

  meth->attributes_count++;

  dl_insert_b(meth->attributes,attr_temp);

  return 0;
}

/**
 * Creates a new "Deprecated" attribute.  This attribute can be
 * added to a class, field, or method.
 *
 * @param class -- Class containing the constant pool where this
 *   attribute will be stored.
 *
 * @returns Pointer to the new JVM_ATTRIBUTE.
 *    Returns NULL on error.
 */

JVM_ATTRIBUTE *
bc_new_deprecated_attr(JVM_CLASS *class) 
{
  JVM_ATTRIBUTE *attr_temp;
  int c;

  if(!class) {
    BAD_ARG();
    return NULL;
  }

  attr_temp = (JVM_ATTRIBUTE *)malloc(sizeof(JVM_ATTRIBUTE));

  if(!attr_temp)
    return NULL;

  c = cp_find_or_insert(class, CONSTANT_Utf8, "Deprecated");

  if(c < 0) {
    free(attr_temp);
    return NULL;
  }

  attr_temp->attribute_name_index = c;
  attr_temp->attribute_length = 0;  /* Deprecated attr length always 0 */

  return attr_temp;
}

/**
 * Creates a new "Synthetic" attribute.  This attribute can be
 * added to a field or method.
 *
 * @param class -- Class containing the constant pool where this
 *   attribute will be stored.
 *
 * @returns Pointer to the new JVM_ATTRIBUTE.
 *    Returns NULL on error.
 */

JVM_ATTRIBUTE *
bc_new_synthetic_attr(JVM_CLASS *class) 
{
  JVM_ATTRIBUTE *attr_temp;
  int c;

  if(!class) {
    BAD_ARG();
    return NULL;
  }

  attr_temp = (JVM_ATTRIBUTE *)malloc(sizeof(JVM_ATTRIBUTE));

  if(!attr_temp)
    return NULL;

  c = cp_find_or_insert(class, CONSTANT_Utf8, "Synthetic");

  if(c < 0) {
    free(attr_temp);
    return NULL;
  }

  attr_temp->attribute_name_index = c;
  attr_temp->attribute_length = 0;  /* Synthetic attr length always 0 */

  return attr_temp;
}

/**
 * Adds the "Synthetic" attribute to the specified method of the specified
 * class.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_method_synthetic(JVM_METHOD *meth)
{
  JVM_ATTRIBUTE *attr_temp;

  if(!meth) {
    BAD_ARG();
    return -1;
  }

  attr_temp = bc_new_synthetic_attr(meth->class);

  if(!attr_temp)
    return -1;

  meth->attributes_count++;

  dl_insert_b(meth->attributes,attr_temp);

  return 0;
}

/**
 * Adds an exception that this method could throw.
 *
 * @param meth -- The method to which the exception should be added.
 * @param exception -- The name of the exception that this method
 *   may throw.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_add_method_exception(JVM_METHOD *meth, char *exception)
{
  JVM_ATTRIBUTE *attr;
  int *copy;
  int c;
  char *t;

  if(!meth || !exception) {
    BAD_ARG();
    return -1;
  }

  t = char_substitute(exception, '.', '/');

  if(!t) return -1;

  c = cp_find_or_insert(meth->class, CONSTANT_Class, t);

  free(t);

  if(c < 0) return -1;

  copy = (int *)malloc(sizeof(int));

  if(!copy) return -1;

  *copy = c;

  attr = find_attribute(meth->class, meth->attributes, "Exceptions");

  if(!attr) {
    attr = bc_new_exceptions_attr(meth->class);

    if(!attr) {
      free(copy);
      return -1;
    }

    meth->attributes_count++;
    dl_insert_b(meth->attributes, attr);
  }

  attr->attribute_length+=2;
  attr->attr.Exceptions->number_of_exceptions++;

  dl_insert_b(attr->attr.Exceptions->exception_index_table, copy);

  return 0;
}

/**
 * Adds the "InnerClasses" attribute to the specified class.
 *
 * @param class -- The class to which the attribute should be added.
 * @param inner_class -- The name of the inner class.
 * @param outer_class -- The name of the class containing the inner class.
 * @param inner_name -- Specify NULL for an anonymous inner class.  Otherwise
 *   this is the simple name of the inner class.
 * @param acc_flags -- The access flags for the inner class (for example
 *     JVM_ACC_PUBLIC, JVM_ACC_STATIC, etc)
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_add_inner_classes_attr(JVM_CLASS *class, char *inner_class,
  char *outer_class, char *inner_name, int acc_flags)
{
  struct InnerClassEntry *entry;
  JVM_ATTRIBUTE *attr;
  int c;
  char *t;

  if(!class) {
    BAD_ARG();
    return -1;
  }

  attr = find_attribute(class, class->attributes, "InnerClasses");

  if(!attr) {
    attr = bc_new_inner_classes_attr(class);
    if(!attr) return -1;
    class->attributes_count++;
    dl_insert_b(class->attributes, attr);
  }

  /* increment the length by the size of one entry in the inner class list */

  entry = (struct InnerClassEntry *)malloc(sizeof(struct InnerClassEntry));

  if(!entry) return -1;

  entry->inner_class_info_index = 0;
  entry->outer_class_info_index = 0;
  entry->inner_name_index = 0;

  entry->inner_class_access_flags = acc_flags;

  if(inner_class) {
    t = char_substitute(inner_class, '.', '/');
    if(!t) {
      free(entry);
      return -1;
    }

    c = cp_find_or_insert(class, CONSTANT_Class, t);

    free(t);

    if(c < 0) {
      free(entry);
      return -1;
    }

    entry->inner_class_info_index = c;
  }

  if(outer_class) {
    t = char_substitute(outer_class, '.', '/');
    if(!t) {
      free(entry);
      return -1;
    }

    c = cp_find_or_insert(class, CONSTANT_Class, t);

    free(t);

    if(c < 0) {
      free(entry);
      return -1;
    }

    entry->outer_class_info_index = c;
  }

  if(inner_name) {
    t = char_substitute(inner_name, '.', '/');
    if(!t) {
      free(entry);
      return -1;
    }

    c = cp_find_or_insert(class, CONSTANT_Utf8, t);

    free(t);

    if(c < 0) {
      free(entry);
      return -1;
    }

    entry->inner_name_index = c;
  }

  attr->attribute_length+=8;
  attr->attr.InnerClasses->number_of_classes++;

  dl_insert_b(attr->attr.InnerClasses->classes, entry);

  return 0;
}

/**
 * Sets the name of a local variable in the specified method.
 *
 * @param meth -- The method containing the local variable.
 * @param num -- The local variable number whose name should be set.
 * @param name -- The name of the variable.
 * @param desc -- The descriptor of the variable.
 *
 * @returns Pointer to the local variable table entry created for
 *   this variable.  Returns NULL on error.
 */

JVM_LOCAL_VARIABLE_TABLE_ENTRY *
bc_set_local_var_name(JVM_METHOD *meth, int num, char *name, char *desc)
{
  JVM_LOCAL_VARIABLE_TABLE_ENTRY *loc;

  if(!meth || !name || !desc) {
    BAD_ARG();
    return NULL;
  }

  loc = (JVM_LOCAL_VARIABLE_TABLE_ENTRY *) 
    malloc(sizeof(JVM_LOCAL_VARIABLE_TABLE_ENTRY));

  if(!loc) return NULL;

  loc->index = num;
  loc->name = strdup(name);
  loc->name_index = 0;
  loc->descriptor = char_substitute(desc, '.', '/');
  loc->descriptor_index = 0;
  loc->start = NULL;
  loc->end = NULL;

  if(!loc->descriptor || !loc->name) {
    if(loc->name) free(loc->name);
    if(loc->descriptor) free(loc->descriptor);
    free(loc); 
    return NULL;
  }

  dl_insert_b(meth->locals_table, loc);

  return loc;
}

/**
 * Sets the start of this named local variable.  That is, the instruction from
 * which the given local variable table entry is valid.
 *
 * @param loc -- The local variable table entry for the variable.
 * @param instr -- The first instruction for which this variable is defined.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_local_var_start(JVM_LOCAL_VARIABLE_TABLE_ENTRY *loc, JVM_CODE_GRAPH_NODE *instr)
{
  if(!loc || !instr) {
    BAD_ARG();
    return -1;
  }

  loc->start = instr;

  return 0;
}

/**
 * Sets the end of this named local variable.  That is, the instruction after
 * which the given local variable table entry would not be valid.
 *
 * @param loc -- The local variable table entry for the variable.
 * @param instr -- The last instruction for which this variable is defined.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_local_var_end(JVM_LOCAL_VARIABLE_TABLE_ENTRY *loc, JVM_CODE_GRAPH_NODE *instr)
{
  if(!loc || !instr) {
    BAD_ARG();
    return -1;
  }

  loc->end = instr;

  return 0;
}

/**
 * Sets the line number (from the original source file) for the given
 * JVM instruction.
 *
 * @param meth -- The method containing the line number table to be updated.
 * @param instr -- The instruction corresponding to the given line number.
 * @param lnum -- The line number from the original source code.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_line_number(JVM_METHOD *meth, JVM_CODE_GRAPH_NODE *instr, int lnum)
{
  JVM_LINE_NUMBER_TABLE_ENTRY *tmp;

  if(!meth || !instr) {
    BAD_ARG();
    return -1;
  }

  tmp = (JVM_LINE_NUMBER_TABLE_ENTRY *) malloc(sizeof(JVM_LINE_NUMBER_TABLE_ENTRY));

  if(!tmp) return -1;
  
  tmp->op = instr;
  tmp->line_number = lnum;

  dl_insert_b(meth->line_table, tmp);

  return 0;
}

/**
 * Creates a new exception table entry.  The exception table entry
 * represents the range of instructions for which the given exception
 * should be trapped.
 *
 * @param meth -- The method containing the following instructions.
 * @param from -- The first instruction from which the exception should be
 *   caught.
 * @param to -- The last instruction to which the exception applies.
 * @param target -- The first instruction of the catch block.  This is where
 *   the JVM branches when the exception is caught.
 * @param exc_class -- The name of the exception class which should be caught.
 *
 * @returns The exception table entry.
 */

JVM_EXCEPTION_TABLE_ENTRY *
bc_new_exception_table_entry(JVM_METHOD *meth, JVM_CODE_GRAPH_NODE *from, 
  JVM_CODE_GRAPH_NODE * to, JVM_CODE_GRAPH_NODE * target, char *exc_class)
{
  JVM_EXCEPTION_TABLE_ENTRY *new_et;

  if(!meth || !from || !to || !target) {
    BAD_ARG();
    return NULL;
  }

  new_et = (JVM_EXCEPTION_TABLE_ENTRY *)malloc(sizeof(JVM_EXCEPTION_TABLE_ENTRY));

  if(!new_et) return NULL;

  new_et->from = from;
  new_et->to = to;
  new_et->target = target;

  /* check if the exception type was specified, then insert an entry
   * in the constant pool if necessary and set the catch_type field.
   * otherwise it should be set to 0.
   */

  if(exc_class) {
    char *etmp;
    int c;

    etmp = char_substitute(exc_class, '.', '/');
    if(!etmp) { 
      free(new_et);
      return NULL;
    }

    c = cp_find_or_insert(meth->class, CONSTANT_Class, etmp);

    free(etmp);

    if(c < 0) { 
      free(new_et);
      return NULL;
    }

    new_et->catch_type = c;
  }
  else
    new_et->catch_type = 0;

  return new_et;
}

/**
 * Adds the specified exception table entry to the specified method.
 *
 * @param meth -- The method to which the exception table entry should be
 *   added.
 * @param et_entry -- The exception table entry to add to this method.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_add_exception_handler(JVM_METHOD *meth,
   JVM_EXCEPTION_TABLE_ENTRY *et_entry)
{
  if(!meth || !et_entry) {
    BAD_ARG();
    return -1;
  }

  dl_insert_b(meth->exc_table, et_entry);

  return 0;
}

/**
 * Returns a new code graph node initialized with the given opcode, operand,
 * and pc.
 *
 * @param meth -- The method containing the instruction.
 * @param op -- The opcode of the instruction.
 * @param operand -- The instruction's operand.
 *
 * @returns The new code graph node with this opcode.
 */

JVM_CODE_GRAPH_NODE *
bc_new_graph_node(JVM_METHOD *meth, JVM_OPCODE op, u4 operand)
{
  JVM_CODE_GRAPH_NODE *tmp;
  
  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  tmp = (JVM_CODE_GRAPH_NODE *)malloc(sizeof(JVM_CODE_GRAPH_NODE));

  if(!tmp) return NULL;
 
  tmp->op = op;
  tmp->operand = operand;
  tmp->width = bc_op_width(op);

  /* set pc and branch targets later */
  tmp->pc = meth->pc;
  tmp->branch_target = NULL;
  tmp->next = NULL;
  tmp->branch_label = NULL;
  tmp->stack_depth = -1;
  tmp->visited = FALSE;

  return tmp;
}

/**
 * Creates a new method structure with the given access flags.
 *
 * @param cclass -- The class to which the new method should be added.
 * @param name -- The name of the method.
 * @param desc -- The method descriptor.  This can be NULL initially but
 *   the method descriptor must be set before calling bc_write_class().
 * @param flags -- The access flags for the method.
 *
 * @returns Pointer to the new method structure.
 *    Returns NULL on error.
 */

JVM_METHOD *
bc_new_method(JVM_CLASS *cclass, char *name, char *desc, unsigned int flags)
{
  JVM_METHOD *meth;
  int lv_start;
  int c;
  u2 acc;

  if(!cclass || !name) {
    BAD_ARG();
    return NULL;
  }

#define err_new_meth() \
     if(meth && meth->name) free(meth->name); \
     free(meth);

  acc = (u2) flags;

  if((unsigned int)acc != flags)
    debug_err("Warning: possible truncation in bc_new_method.\n");

  meth = (JVM_METHOD *)malloc(sizeof(JVM_METHOD));

  if(!meth) return NULL;

  meth->access_flags = acc;

  meth->class = cclass;

  meth->gen_bytecode = TRUE;

  /* if this is a static method, then local variables are numbered 
   * starting at 0, otherwise they start at 1.
   */

  if(acc & JVM_ACC_STATIC)
    lv_start = 0;
  else
    lv_start = 1;

  debug_msg("access flags = %d\n", flags);

  meth->name = strdup(name);

  if(!meth->name) {
    err_new_meth();
    return NULL;
  }

  c = cp_find_or_insert(cclass, CONSTANT_Utf8, name);

  if(c < 0) {
    err_new_meth();
    return NULL;
  }

  meth->name_index = c;

  if(desc) {
    c = cp_find_or_insert(cclass, CONSTANT_Utf8, desc);

    if(c < 0) {
      err_new_meth();
      return NULL;
    }

    meth->descriptor_index = c;

    /* if there was a descriptor specified, then go ahead and
     * set the current local and maximum variable numbers.
     */

    meth->cur_local_number = lv_start + num_locals_in_descriptor(desc);
    meth->max_locals = meth->cur_local_number;
  }
  else {
    /* no descriptor specified yet.  we will rely on the user to set
     * it later.  for now set the index to 0 which should cause a
     * verification error in case the user forgets to set a proper
     * descriptor index.
     */

    meth->descriptor_index = 0;
    meth->cur_local_number = 1; 
    meth->max_locals = 1;
  }

  meth->attributes = make_dl();
  meth->attributes_count = 0;

  meth->cur_code = new_code_attr(cclass);

  meth->line_table = make_dl();
  meth->locals_table = make_dl();
  meth->label_list = make_dl();
  meth->exc_table = make_dl();

  if(!meth->attributes || !meth->line_table || !meth->locals_table || 
     !meth->label_list || !meth->exc_table) 
  {
    if(meth->attributes) dl_delete_list(meth->attributes);
    if(meth->line_table) dl_delete_list(meth->line_table);
    if(meth->locals_table) dl_delete_list(meth->locals_table);
    if(meth->label_list) dl_delete_list(meth->label_list);
    if(meth->exc_table) dl_delete_list(meth->exc_table);

    if(meth->cur_code)
      bc_free_code_attribute(cclass, meth->cur_code);

    meth->attributes = NULL;
    meth->line_table = NULL;
    meth->locals_table = NULL;
    meth->label_list = NULL;
    meth->exc_table = NULL;
    meth->cur_code = NULL;

    err_new_meth();
    return NULL;
  }

  meth->lastOp = jvm_nop;

  meth->stacksize = meth->pc = meth->num_handlers = 0;

  cclass->methods_count++;
  dl_insert_b(cclass->methods, meth);

  return meth;
}

/**
 * Removes the specified method from its containing class.
 *
 * @param meth -- The method to be removed.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_remove_method(JVM_METHOD *meth)
{
  JVM_METHOD *tmpmeth;
  Dlist tmpPtr;

  if(!meth) {
    BAD_ARG();
    return -1;
  }

  dl_traverse(tmpPtr,meth->class->methods) {
    tmpmeth = (JVM_METHOD *) tmpPtr->val;

    if(tmpmeth == meth) {
      meth->class->methods_count--;
      dl_delete_node(tmpPtr);
      return 0;
    }
  }

  return -1;
}

/**
 * Gets the number of bytes of code in this method.
 *
 * @param meth -- The method whose length should be returned.
 *
 * @returns The code length (in bytes).  Returns -1 on failure.
 */

int
bc_get_code_length(JVM_METHOD *meth)
{
  if(!meth) {
    BAD_ARG();
    return -1;
  }

  return meth->pc;
}

/**
 * Gets the instruction following this instruction.
 *
 * @param node -- Pointer to an instruction node.
 *
 * @returns The next instruction.
 */

JVM_CODE_GRAPH_NODE *
bc_get_next_instr(JVM_CODE_GRAPH_NODE *node)
{
  if(!node) {
    BAD_ARG();
    return NULL;
  }

  return node->next;
}

/**
 * Sets the stack depth at the given instruction.  Most of the
 * time it won't be necessary to use this call, however there
 * may be some exceptional circumstances that require manually
 * setting the stack depth.
 *
 * @param node -- The instruction node for which the stack depth
 *   should be set.
 * @param depth -- The depth in number of stack entries.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_stack_depth(JVM_CODE_GRAPH_NODE *node, int depth)
{
  if(!node) {
    BAD_ARG();
    return -1;
  }

  node->stack_depth = depth;
  return 0;
}

/**
 * Gets the last opcode in the given method.
 *
 * @param meth -- Pointer to a method structure.
 *
 * @returns The last opcode (see the JVM_OPCODE enum).  Returns -1 on failure.
 */

JVM_OPCODE 
bc_get_last_opcode(JVM_METHOD *meth)
{
  if(!meth) {
    BAD_ARG();
    return -1;
  }

  return meth->lastOp;
}

/**
 * Sets the method descriptor index in the specified method.  This would be
 * useful in situations where you don't know the descriptor when the method
 * is first created.
 *
 * @param meth -- The method whose descriptor should be set.
 * @param desc -- The method descriptor.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_method_descriptor(JVM_METHOD *meth, char *desc)
{
  int c;

  if(!meth) {
    BAD_ARG();
    return -1;
  }

  if(desc) {
    c = cp_find_or_insert(meth->class, CONSTANT_Utf8, desc);

    if(c < 0)
      return -1;

    meth->descriptor_index = c;
  }
   
  return 0;
}

/**
 * Creates a new local variable table attribute.
 *
 * @param meth -- The method which will contain the local variable table.
 *
 * @returns Pointer to the new local variable table attribute.
 *    Returns NULL on error.
 */

JVM_ATTRIBUTE *
bc_new_local_variable_table_attr(JVM_METHOD *meth)
{
  JVM_ATTRIBUTE * tmp;
  int c;
  Dlist list_tmp, entries, const_table;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  const_table = meth->class->constant_pool;
  entries = meth->locals_table;

  tmp = (JVM_ATTRIBUTE *)malloc(sizeof(JVM_ATTRIBUTE));

  if(!tmp) return NULL;

  c = cp_find_or_insert(meth->class, CONSTANT_Utf8, "LocalVariableTable");

  if(c < 0) {
    free(tmp);
    return NULL;
  }

  tmp->attribute_name_index = c;

  tmp->attribute_length = 0;
  tmp->attr.LocalVariableTable = (struct LocalVariableTable_attribute *)
         malloc(sizeof(struct LocalVariableTable_attribute));

  if(!tmp->attr.LocalVariableTable) {
    free(tmp);
    return NULL;
  }

  tmp->attr.LocalVariableTable->local_variable_table_length = 0;

  dl_traverse(list_tmp, entries) {
    JVM_LOCAL_VARIABLE_TABLE_ENTRY *entry;

    entry = (JVM_LOCAL_VARIABLE_TABLE_ENTRY *)list_tmp->val;

    c = cp_find_or_insert(meth->class, CONSTANT_Utf8, entry->name);

    if(c < 0) {
      free(tmp);
      return NULL;
    }

    entry->name_index = c;

    c = cp_find_or_insert(meth->class, CONSTANT_Utf8, entry->descriptor);

    if(c < 0) {
      free(tmp);
      return NULL;
    }

    entry->descriptor_index = c;

    if(!entry->end)
      entry->end = dl_last(meth->cur_code->attr.Code->code)->val;

    tmp->attr.LocalVariableTable->local_variable_table_length++;
  }
 
  /* each local var table entry is 10 bytes, plus 2 bytes for the length */
  tmp->attribute_length = 
    (tmp->attr.LocalVariableTable->local_variable_table_length * 10) + 2;

  tmp->attr.LocalVariableTable->local_variable_table = entries;

  return tmp;
}

/**
 * Creates a new line number table attribute.
 *
 * @param meth -- The method which will contain the line number table.
 *
 * @returns Pointer to the new line number table attribute.
 *    Returns NULL on error.
 */

JVM_ATTRIBUTE *
bc_new_line_number_table_attr(JVM_METHOD *meth)
{
  JVM_ATTRIBUTE * tmp;
  int c;
  Dlist list_tmp, entries;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  entries = meth->line_table;

  tmp = (JVM_ATTRIBUTE *)malloc(sizeof(JVM_ATTRIBUTE));

  if(!tmp) return NULL;

  c = cp_find_or_insert(meth->class, CONSTANT_Utf8, "LineNumberTable");

  if(c < 0) {
    free(tmp);
    return NULL;
  }

  tmp->attribute_name_index = c;

  tmp->attribute_length = 0;
  tmp->attr.LineNumberTable = (struct LineNumberTable_attribute *)
         malloc(sizeof(struct LineNumberTable_attribute));

  if(!tmp->attr.LineNumberTable) {
    free(tmp);
    return NULL;
  }

  tmp->attr.LineNumberTable->line_number_table_length = 0;

  dl_traverse(list_tmp, entries) {
    tmp->attr.LineNumberTable->line_number_table_length++;
  }
 
  /* each line number table entry is 4 bytes, plus 2 bytes for the length */
  tmp->attribute_length = 
    (tmp->attr.LineNumberTable->line_number_table_length * 4) + 2;

  tmp->attr.LineNumberTable->line_number_table = entries;

  return tmp;
}

/**
 * Creates a new attribute structure and initializes the
 * Exception_attribute section with some initial values.
 *
 * @param cclass -- The class which will contain the attribute.
 *
 * @returns Pointer to the new exceptions attribute.
 *    Returns NULL on error.
 */

JVM_ATTRIBUTE *
bc_new_exceptions_attr(JVM_CLASS *cclass)
{
  JVM_ATTRIBUTE * tmp;
  int c;

  if(!cclass) {
    BAD_ARG();
    return NULL;
  }

  tmp = (JVM_ATTRIBUTE *)malloc(sizeof(JVM_ATTRIBUTE));

  if(!tmp) return NULL;

  c = cp_find_or_insert(cclass, CONSTANT_Utf8, "Exceptions");

  if(c < 0) {
    free(tmp);
    return NULL;
  }

  tmp->attribute_name_index = c;

  tmp->attr.Exceptions = (struct Exceptions_attribute *)
                 malloc(sizeof(struct Exceptions_attribute));

  if(!tmp->attr.Exceptions) {
    free(tmp);
    return NULL;
  }

  /* initially the attribute length is 2 which covers the size of the
   * 2-byte length field.
   */

  tmp->attribute_length = 2;
  tmp->attr.Exceptions->number_of_exceptions = (u2) 0;
  tmp->attr.Exceptions->exception_index_table = make_dl();

  if(!tmp->attr.Exceptions->exception_index_table) {
    free(tmp->attr.Exceptions);
    free(tmp);
    return NULL;
  }

  return tmp;
}

/**
 * Creates a new InnerClasses attribute structure.
 *
 * @param cclass -- The class which will contain the attribute.
 *
 * @returns Pointer to the new InnerClasses attribute.
 *    Returns NULL on error.
 */

JVM_ATTRIBUTE *
bc_new_inner_classes_attr(JVM_CLASS *cclass)
{
  JVM_ATTRIBUTE * tmp;
  int c;

  if(!cclass) {
    BAD_ARG();
    return NULL;
  }

  tmp = (JVM_ATTRIBUTE *)malloc(sizeof(JVM_ATTRIBUTE));

  if(!tmp) return NULL;

  c = cp_find_or_insert(cclass, CONSTANT_Utf8, "InnerClasses");

  if(c < 0) {
    free(tmp);
    return NULL;
  }

  tmp->attribute_name_index = c;

  tmp->attr.InnerClasses = (struct InnerClasses_attribute *)
                 malloc(sizeof(struct InnerClasses_attribute));

  if(!tmp->attr.InnerClasses) {
    free(tmp);
    return NULL;
  }

  /* initially the attribute length is 2 which covers the size of the
   * 2-byte length field.
   */

  tmp->attribute_length = 2;
  tmp->attr.InnerClasses->number_of_classes = (u2) 0;
  tmp->attr.InnerClasses->classes = make_dl();

  if(!tmp->attr.InnerClasses->classes) {
    free(tmp->attr.InnerClasses);
    free(tmp);
    return NULL;
  }

  return tmp;
}

/**
 * This function 'releases' a local variable.  That is, calling this
 * function signifies that we no longer need this local variable.
 *
 * @param meth -- The method containing the local variable.
 * @param vtype -- The JVM data type of the variable (see the JVM_DATA_TYPE
 *   enum).
 *
 * @returns The current local variable number.  Returns -1 on error.
 */

int
bc_release_local(JVM_METHOD *meth, JVM_DATA_TYPE vtype)
{
  if(!meth) {
    BAD_ARG();
    return -1;
  }

  if((vtype == jvm_Double) || (vtype == jvm_Long))
    meth->cur_local_number-=2;
  else
    meth->cur_local_number--;

  return meth->cur_local_number;
}

/**
 * This function returns the next available local variable number and
 * updates the max if necessary.
 *
 * @param meth -- The method containing the local variable.
 * @param vtype -- The JVM data type of the variable (see the JVM_DATA_TYPE
 *   enum).
 *
 * @returns The next local variable number.  Returns -1 on error.
 */

int
bc_get_next_local(JVM_METHOD *meth, JVM_DATA_TYPE vtype)
{
  if(!meth) {
    BAD_ARG();
    return -1;
  }

  if((vtype == jvm_Double) || (vtype == jvm_Long))
    meth->cur_local_number+=2;
  else
    meth->cur_local_number++;

  if(meth->cur_local_number > meth->max_locals)
    meth->max_locals = meth->cur_local_number;

  return meth->cur_local_number - 
      (((vtype == jvm_Double) || (vtype == jvm_Long)) ? 2 : 1);
}

/**
 * Sets the current local variable number for this method.  If the new value
 * is greater than the current maximum number of locals, then the max_locals
 * field is set also.
 *
 * @param meth -- The method whose local variable number should be set.
 * @param curlocal -- The current local variable number.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_cur_local_num(JVM_METHOD *meth, unsigned int curlocal) {
  if(!meth) {
    BAD_ARG();
    return -1;
  }

  meth->cur_local_number = curlocal;

  if(curlocal > meth->max_locals)
    meth->max_locals = curlocal;

  return 0;
}

/**
 * Allow suspending the generation of bytecode for situations in which the
 * code generation ordering is very different between java source and JVM
 * bytecode.
 * 
 * @param meth -- The method to suspend/enable bytecode generation.
 * @param value -- If TRUE, calls which generate code (e.g. bc_append())
 *   will actually add the instructions to the code graph.  If FALSE, you
 *   can still call these routines, but they will have no effect.
 *
 * @returns 0 on success, -1 on failure.
 */

int 
bc_set_gen_status(JVM_METHOD *meth, BOOL value) {
  if(!meth) {
    BAD_ARG();
    return -1;
  }

  meth->gen_bytecode = value;
  return 0;
}

/**
 * Creates the bytecode for a new default constructor and adds it to the
 * given class.
 *
 * @param cur_class -- The class for which the default constructor should
 *    be created.
 * @param acc_flag -- The access flags for the constructor (for example
 *     JVM_ACC_PUBLIC, JVM_ACC_STATIC, etc)
 *
 * @returns Pointer to the new constructor (a JVM_METHOD structure).
 *    Returns NULL on error.
 */

JVM_METHOD *
bc_add_default_constructor(JVM_CLASS *cur_class, u2 acc_flag)
{
  JVM_METHOD *meth_tmp;
  char *cur_sc;
  CP_NODE *c;
  int idx;

  if(!cur_class) {
    BAD_ARG();
    return NULL;
  }

  c = cp_entry_by_index(cur_class, cur_class->super_class);

  if(!c) return NULL;

  c = cp_entry_by_index(cur_class, c->val->cpnode.Class.name_index);

  if(!c) return NULL;

  cur_sc = cp_null_term_utf8(c->val);

  if(!cur_sc) return NULL;

  meth_tmp = bc_new_method(cur_class, "<init>", "()V", acc_flag);
 
  if(!meth_tmp) {
    free(cur_sc);
    return NULL;
  }

  idx = bc_new_methodref(cur_class, cur_sc, "<init>", "()V");

  if(idx < 0) {
    free(cur_sc);
    return NULL;
  }

  bytecode0(meth_tmp, jvm_aload_0);
  bytecode1(meth_tmp, jvm_invokespecial, idx);
  bytecode0(meth_tmp, jvm_return);

  bc_set_cur_local_num(meth_tmp, 1);

  free(cur_sc);

  return meth_tmp;
}

/**
 * Creates bytecode for a new multi dimensional array.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param dimensions -- The number of dimensions to be created.
 * @param desc -- The descriptor of the array.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_new_multi_array(JVM_METHOD *meth, u4 dimensions, char *desc)
{
  u4 operand;
  int c;

  if(!meth || !desc) {
    BAD_ARG();
    return NULL;
  }

  c = cp_find_or_insert(meth->class, CONSTANT_Class, desc);

  if(c < 0) return NULL;

  operand = (c<<8) | dimensions;
  return bytecode1(meth, jvm_multianewarray, operand);
}

/**
 * Generates an instruction to load the specified field onto the
 * stack (jvm_getfield).
 *
 * @param meth -- The method to which this instruction should be added.
 * @param class -- The name of the class containing the field.
 * @param field -- The field name.
 * @param desc -- The field descriptor.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_get_field(JVM_METHOD *meth, char *class, char *field, char *desc)
{
  int field_idx;

  if(!meth || !class || !field || !desc) {
    BAD_ARG();
    return NULL;
  }

  field_idx = bc_new_fieldref(meth->class, class, field, desc);

  if(field_idx < 0) return NULL;

  return bytecode1(meth, jvm_getfield, field_idx);
}

/**
 * Generates an instruction to store the top stack value to the
 * specified field (jvm_putfield).
 *
 * @param meth -- The method to which this instruction should be added.
 * @param class -- The name of the class containing the field.
 * @param field -- The field name.
 * @param desc -- The field descriptor.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_put_field(JVM_METHOD *meth, char *class, char *field, char *desc)
{
  int field_idx;

  if(!meth || !class || !field || !desc) {
    BAD_ARG();
    return NULL;
  }

  field_idx = bc_new_fieldref(meth->class, class, field, desc);

  if(field_idx < 0) return NULL;

  return bytecode1(meth, jvm_putfield, field_idx);
}

/**
 * Generates an instruction to load the specified static field onto the
 * stack (jvm_getstatic).
 *
 * @param meth -- The method to which this instruction should be added.
 * @param class -- The name of the class containing the field.
 * @param field -- The field name.
 * @param desc -- The field descriptor.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_get_static(JVM_METHOD *meth, char *class, char *field, char *desc)
{
  int field_idx;

  if(!meth || !class || !field || !desc) {
    BAD_ARG();
    return NULL;
  }

  field_idx = bc_new_fieldref(meth->class, class, field, desc);

  if(field_idx < 0) return NULL;

  return bytecode1(meth, jvm_getstatic, field_idx);
}

/**
 * Generates an instruction to store the top stack value to the
 * specified static field (jvm_putstatic).
 *
 * @param meth -- The method to which this instruction should be added.
 * @param class -- The name of the class containing the field.
 * @param field -- The field name.
 * @param desc -- The field descriptor. 
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_put_static(JVM_METHOD *meth, char *class, char *field, char *desc)
{
  int field_idx;

  if(!meth || !class || !field || !desc) {
    BAD_ARG();
    return NULL;
  }

  field_idx = bc_new_fieldref(meth->class, class, field, desc);

  if(field_idx < 0) return NULL;

  return bytecode1(meth, jvm_putstatic, field_idx);
}

/**
 * Generates an "instanceof" instruction which determines whether the
 * operand on top of the stack is an instance of the specified class.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param class -- The name of the class which the object might be an
 *    instance of.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_instanceof(JVM_METHOD *meth, char *class)
{
  int c;

  if(!meth || !class) {
    BAD_ARG();
    return NULL;
  }

  c = cp_find_or_insert(meth->class, CONSTANT_Class, class);

  if(c < 0) return NULL;

  return bytecode1(meth, jvm_instanceof, c);
}

/**
 * Generates a "checkcast" instruction which determines whether the
 * operand on top of the stack is of the specified type.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param class -- The name of the class which might be the object's type.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_checkcast(JVM_METHOD *meth, char *class)
{
  int c;

  if(!meth || !class) {
    BAD_ARG();
    return NULL;
  }

  c = cp_find_or_insert(meth->class, CONSTANT_Class, class);

  if(c < 0) return NULL;

  return bytecode1(meth, jvm_checkcast, c);
}

/**
 * Generates a switch instruction.  This will either be a "tableswitch" or
 * a "lookupswitch" depending on how many empty cases there are after all
 * cases have been specified.  When most of the cases are specified, then
 * the "tableswitch" instruction is used, but if the switch is more sparsely
 * filled with cases, the "lookupswitch" would use less space.  The value 
 * defined for JVM_SWITCH_FILL_THRESH in bytecode.h determines how many empty
 * cases there must be before the "lookupswitch" is used.
 *
 * @param meth -- The method to which this instruction should be added.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_switch(JVM_METHOD *meth) {
  JVM_CODE_GRAPH_NODE *instr;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  instr = bytecode0(meth, jvm_tableswitch);

  instr->switch_info = 
     (JVM_SWITCH_INFO *)malloc(sizeof(JVM_SWITCH_INFO));

  if(!instr->switch_info) return NULL;

  /* we will calculate the cell padding, and low/high case numbers later */

  instr->switch_info->cell_padding = 0;
  instr->switch_info->low = 0;
  instr->switch_info->high = 0;

  instr->switch_info->offsets = make_dl();
  instr->switch_info->num_entries = 0;

  if(!instr->switch_info->offsets) {
    free(instr->switch_info);
    return NULL;
  }
 
  /* the width is unknown at this time, but it doesn't matter because 
   * the real width will be calculated later.
   */
  instr->width = bc_op_width(jvm_tableswitch);

  return instr;
}

/**
 * Adds another case to the given switch instruction.
 * 
 * @param instr -- The node of the switch instruction.
 * @param target -- The node of the first instruction in the case to be added.
 * @param case_num -- The integer corresponding to this case.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_add_switch_case(JVM_CODE_GRAPH_NODE *instr, JVM_CODE_GRAPH_NODE *target,
  int case_num)
{
  JVM_SWITCH_ENTRY *newcase;

  if(!instr || !target) {
    BAD_ARG();
    return -1;
  }

  if(dl_empty(instr->switch_info->offsets)) {
    instr->switch_info->low = case_num;
    instr->switch_info->high = case_num;
  }
  else {
    if(case_num < instr->switch_info->low)
      instr->switch_info->low = case_num;

    if(case_num > instr->switch_info->high)
      instr->switch_info->high = case_num;
  }

  newcase = (JVM_SWITCH_ENTRY *)malloc(sizeof(JVM_SWITCH_ENTRY));

  if(!newcase) return -1;

  newcase->instr = target;
  newcase->case_num = case_num;

  dl_insert_b(instr->switch_info->offsets, newcase);

  instr->switch_info->num_entries++;

  return 0;
}

/**
 * Specifies the default case for the given switch instruction.
 *
 * @param instr -- The node of the switch instruction.
 * @param target -- The node of the first instruction in the default 
 *    case to be added.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_add_switch_default(JVM_CODE_GRAPH_NODE *instr, JVM_CODE_GRAPH_NODE *target)
{
  if(!instr || !target) {
    BAD_ARG();
    return -1;
  }

  instr->switch_info->default_case = target;

  return 0;
}

/**
 * Sets the branch target of a JVM_CODE_GRAPH_NODE (that is, which instruction
 * this instruction branches to, either conditionally or unconditionally).
 *
 * @param node -- The node of the conditional or unconditional branching
 *    instruction.
 * @param target -- The target of the branch instruction.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_branch_target(JVM_CODE_GRAPH_NODE *node, JVM_CODE_GRAPH_NODE *target)
{
  if(!node || !target) {
    BAD_ARG();
    return -1;
  }

  node->branch_target = target;

  return 0;
}

/**
 * Sets the label to which this instruction branches.  This is used
 * when implementing languages which can branch forward to labeled
 * statements.  Thus the forward instruction does not need to have been
 * emitted when the branch target is set.  Later the address will be
 * resolved.
 *
 * @param node -- The node of the branch instruction.
 * @param label -- The label to which the instruction branches.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_branch_label(JVM_CODE_GRAPH_NODE *node, const char *label)
{
  if(!node || !label) {
    BAD_ARG();
    return -1;
  }

  node->branch_label = strdup(label);

  if(!node->branch_label) return -1;

  return 0;
}

/**
 * Same as bc_set_branch_label() except that the label is specified
 * as an integer instead of a string.
 *
 * @param node -- The node of the branch instruction.
 * @param label -- The label to which the instruction branches.
 *
 * @returns 0 on success, -1 on failure.
 */

int
bc_set_integer_branch_label(JVM_CODE_GRAPH_NODE *node, int label_num)
{
  char label[20];

  if(!node) {
    BAD_ARG();
    return -1;
  }

  sprintf(label, "%d", label_num);

  return bc_set_branch_label(node, label);
}


/**
 * Generates an iinc instruction.  First check if the iinc needs to be
 * preceeded by a jvm_wide opcode and generate that if necessary.  The wide
 * instruction is required if the local variable index or the immediate
 * operand would exceed a one-byte value.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param idx -- The index of the local variable to be incremented.
 * @param inc_const -- The constant value to add to the specified local variable.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_iinc(JVM_METHOD *meth, unsigned int idx, int inc_const)
{
  unsigned int operand;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  if((idx > 255) || (inc_const < -128) || (inc_const > 127)) {
    bytecode0(meth, jvm_wide);
    operand = ((idx & 0xFFFF) << 16) | ((u2)inc_const & 0xFFFF);
  }
  else
    operand = ((idx & 0xFF) << 8) | (inc_const & 0xFF);

  return bytecode1(meth, jvm_iinc, operand);
}

/**
 * This function returns a pointer to the next field type in this descriptor.
 *
 * @param str -- The descriptor to be parsed.
 *
 * @returns Pointer to the beginning of the next field in the descriptor.
 *    If there are no more field types this function returns NULL.  On error, 
 *    this function also returns NULL.
 */

char *
bc_next_desc_token(char *str)
{
  char *p = str;

  if(!str) {
    BAD_ARG();
    return NULL;
  }

  switch(*p) {
    case 'B': case 'C': case 'D': case 'F':
    case 'I': case 'J': case 'S': case 'Z':
      return p+1;

    case 'L':
      while((*p != ';') && (*p != '\0'))
        p++;

      if(*p == '\0') {
        debug_err("bc_next_desc_token() incomplete classname in desc\n");
        return NULL;
      }

      return p+1;

    case '[':
      return bc_next_desc_token(p+1);

    case '(':
      /* we should hit this case at the beginning of the descriptor */
      return p+1;

    case ')':
      return NULL;

    default:
      debug_err("bc_next_desc_token() unrecognized char in desc:%s\n",str);
      return NULL;
  }

  /* should never reach here */
}

/**
 * Generates a return instruction.  This can be used in a generic way
 * and when the class is emitted, the proper type-specific return
 * instruction is generated based on the method descriptor.
 *
 * @param meth -- The method to which this instruction should be added.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_return(JVM_METHOD *meth)
{
  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  return bytecode0(meth, jvm_return);
}

/**
 * Pushes an integer constant onto the stack.  The exact instruction
 * generated depends on the value of the constant (sipush, bipush, etc).
 *
 * @param meth -- The method to which this instruction should be added.
 * @param ival -- The integer constant to be loaded.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_push_int_const(JVM_METHOD *meth, int ival)
{
  JVM_CODE_GRAPH_NODE *node = NULL;
  int ct;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  ct = cp_find_or_insert(meth->class, CONSTANT_Integer, (void*)&ival);

  if(ct >= 0) {
    if(ct > CP_IDX_MAX)
      node = bytecode1(meth, jvm_ldc_w,ct);
    else
      node = bytecode1(meth, jvm_ldc,ct);
  } else {   /* not found, use literal */
    if((ival < JVM_SHORT_MIN) || (ival > JVM_SHORT_MAX)) {
      debug_err("WARNING:expr_emit() bad int literal: %d\n", ival);
      return NULL;
    }
    else if((ival < JVM_BYTE_MIN) || (ival > JVM_BYTE_MAX))
      node = bytecode1(meth, jvm_sipush, ival);
    else if((ival < JVM_ICONST_MIN) || (ival > JVM_ICONST_MAX))
      node = bytecode1(meth, jvm_bipush, ival);
    else
      node = bytecode0(meth, jvm_iconst_op[ival+1]);
  }

  return node;
}

/**
 * Pushes a null object value onto the stack.
 *
 * @param meth -- The method to which this instruction should be added.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_push_null_const(JVM_METHOD *meth)
{
  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  return bytecode0(meth, jvm_aconst_null);
}

/**
 * Pushes a float constant onto the stack.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param fval -- The floating point value to be loaded.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_push_float_const(JVM_METHOD *meth, float fval)
{
  JVM_CODE_GRAPH_NODE *node = NULL;
  int ct;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  ct = cp_find_or_insert(meth->class, CONSTANT_Float, (void*)&fval);

  if(ct >= 0) {
    if(ct > CP_IDX_MAX)
      node = bytecode1(meth, jvm_ldc_w,ct);
    else
      node = bytecode1(meth, jvm_ldc,ct);
  }
  else if(fval == 0.0)
    node = bytecode0(meth, jvm_fconst_0);
  else if(fval == 1.0)
    node = bytecode0(meth, jvm_fconst_1);
  else if(fval == 2.0)
    node = bytecode0(meth, jvm_fconst_2);
  else
    debug_err("bc_push_float_const(): bad float precision literal\n");

  return node;
}

/**
 * Pushes a double constant onto the stack.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param dval -- The double precision floating point value to be loaded.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_push_double_const(JVM_METHOD *meth, double dval)
{
  JVM_CODE_GRAPH_NODE *node = NULL;
  int ct;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  ct = cp_find_or_insert(meth->class, CONSTANT_Double, (void*)&dval);

  if(ct >= 0)
    node = bytecode1(meth, jvm_ldc2_w, ct);
  else if(dval == 0.0)
    node = bytecode0(meth, jvm_dconst_0);
  else if(dval == 1.0)
    node = bytecode0(meth, jvm_dconst_1);
  else
    debug_err("bc_push_double_const(): bad double precision literal\n");

  return node;
}

/**
 * Pushes a long constant onto the stack.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param lval -- The long constant to be loaded.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_push_long_const(JVM_METHOD *meth, long long lval)
{
  JVM_CODE_GRAPH_NODE *node = NULL;
  int ct;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  ct = cp_find_or_insert(meth->class, CONSTANT_Long, (void*)&lval);

  if(ct >= 0)
    node = bytecode1(meth, jvm_ldc2_w, ct);
  else if(lval == 0)
    node = bytecode0(meth, jvm_lconst_0);
  else if(lval == 1)
    node = bytecode0(meth, jvm_lconst_1);
  else
    debug_err("bc_push_long_const(): bad literal\n");

  return node;
}

/**
 * Pushes a string constant onto the stack.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param str -- The string value to be loaded.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_push_string_const(JVM_METHOD *meth, char *str)
{
  JVM_CODE_GRAPH_NODE *node = NULL;
  int ct;

  if(!meth || !str) {
    BAD_ARG();
    return NULL;
  }

  ct = cp_find_or_insert(meth->class, CONSTANT_String, (void*)str);

  if(ct < 0) return NULL;

  if(ct > CP_IDX_MAX)
    node = bytecode1(meth, jvm_ldc_w, ct);
  else
    node = bytecode1(meth, jvm_ldc, ct);

  return node;
}

/**
 * This function searches the list of nodes for the given PC.  Returns the
 * node if found, otherwise NULL.  This is not very efficient - we should
 * probably modify it eventually if it becomes an issue.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param num -- The address of the node to find.
 *
 * @returns Pointer to the instruction node with the specified address.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_node_at_pc(JVM_METHOD *meth, int num)
{
  JVM_CODE_GRAPH_NODE *nodeptr;
  Dlist tmp;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  dl_traverse(tmp, meth->cur_code->attr.Code->code) {
    nodeptr = (JVM_CODE_GRAPH_NODE *)tmp->val;
    if(nodeptr->pc == (unsigned int)num)
      return nodeptr;
    if(nodeptr->pc > (unsigned int)num)
      return NULL;
  }

  return NULL;
}

/**
 * Get the width of the specified op.
 *
 * @param op -- The op to return the length of.
 *
 * @returns The width in bytes of this op, including operands.
 */

u1
bc_op_width(JVM_OPCODE op)
{
  return jvm_opcode[op].width;
}

/**
 * Given the local variable number, this function generates a store opcode
 * to store a value to the local var.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param lvnum -- The local variable number to which the value should
 *   be stored.
 * @param rt -- The JVM data type of the local variable (see the enumeration
 *   JVM_DATA_TYPE).
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_store_op(JVM_METHOD *meth, unsigned int lvnum, 
  JVM_DATA_TYPE rt)
{
  JVM_CODE_GRAPH_NODE *node;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  if(lvnum > 255) {
    node = bytecode0(meth, jvm_wide);
    bytecode1(meth, jvm_store_op[rt], lvnum);
  }
  else if(lvnum <= 3)
    node = bytecode0(meth, jvm_short_store_op[rt][lvnum]);
  else
    node = bytecode1(meth, jvm_store_op[rt], lvnum);

  updateMaxLocals(meth, lvnum, rt);

  return node;
}

/**
 * Given the local variable number, this function generates a load opcode
 * to load a value from the local var.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param lvnum -- The local variable from which the value should be loaded.
 * @param rt -- The JVM data type of the local variable (see the enumeration
 *   JVM_DATA_TYPE).
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_load_op(JVM_METHOD *meth, unsigned int lvnum, 
  JVM_DATA_TYPE rt)
{
  JVM_CODE_GRAPH_NODE *node;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  if(lvnum > 255) {
    node = bytecode0(meth, jvm_wide);
    bytecode1(meth, jvm_load_op[rt], lvnum);
  }
  else if(lvnum <= 3)
    node = bytecode0(meth, jvm_short_load_op[rt][lvnum]);
  else
    node = bytecode1(meth, jvm_load_op[rt], lvnum);

  updateMaxLocals(meth, lvnum, rt);

  return node;
}

/**
 * This function generates a load opcode to load a value from an array.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param rt -- The JVM data type of the array (see the enumeration
 *   JVM_DATA_TYPE).
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_array_load_op(JVM_METHOD *meth, JVM_DATA_TYPE rt)
{
  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  return bytecode0(meth, jvm_array_load_op[rt]);
}

/**
 * This function generates a store opcode to store a value to an array.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param rt -- The JVM data type of the array (see the enumeration
 *   JVM_DATA_TYPE).
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_array_store_op(JVM_METHOD *meth, JVM_DATA_TYPE rt)
{
  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  return bytecode0(meth, jvm_array_store_op[rt]);
}

/**
 * Generates an instruction to create a new object of the specified class.
 * Note: this does not completely create a new instance.  For that, you will
 * still need to call the constructor.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param classname -- The name of the class to be created.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_new_obj(JVM_METHOD *meth, char *classname)
{
  int c;
  char *class;
  
  if(!meth || !classname) {
    BAD_ARG();
    return NULL;
  }

  class = char_substitute(classname, '.', '/');

  if(!class) return NULL;

  c = cp_find_or_insert(meth->class, CONSTANT_Class, class);

  free(class);

  if(c < 0) return NULL;

  return bc_append(meth, jvm_new, c);
}

/**
 * Generates two instructions.  The first creates a new object of the 
 * specified class.  The second instruction duplicates the new object.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param classname -- The name of the class to be created.
 *
 * @returns Pointer to the instruction node (the first instruction).
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_new_obj_dup(JVM_METHOD *meth, char *classname)
{
  JVM_CODE_GRAPH_NODE *newobj;

  if(!meth || !classname) {
    BAD_ARG();
    return NULL;
  }

  newobj = bc_gen_new_obj(meth, classname);

  if(!newobj) return NULL;

  bc_append(meth, jvm_dup);

  return newobj;
}

/**
 * Generates a sequence of instructions which completely creates a new
 * instance of the specified class which must have a constructor with no 
 * arguments.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param classname -- The name of the class to be created.
 *
 * @returns Pointer to the first instruction node in the sequence (it will
 *    be the jvm_new instruction).  Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_obj_instance_default(JVM_METHOD *meth, char *classname)
{
  JVM_CODE_GRAPH_NODE *newobj;
  int meth_idx;

  if(!meth || !classname) {
    BAD_ARG();
    return NULL;
  }

  newobj = bc_gen_new_obj_dup(meth, classname);

  if(!newobj) return NULL;

  meth_idx = bc_new_methodref(meth->class, classname, "<init>", "()V");

  if(meth_idx < 0) return NULL;

  bc_append(meth, jvm_invokespecial, meth_idx);

  return newobj;
}

/**
 * Generates the instructions to create a new array for any type except
 * objects (use bc_gen_new_object_array() for objects).
 *
 * This will generate an instruction to push the specified size onto the 
 * stack.  If you want to omit that instruction (if you're pushing the
 * size yourself before calling this function), then just specify -1 as
 * the size.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param size -- The size of the array to be created (-1 to omit the
 *   instruction to push this value).
 * @param rt -- The JVM data type of the array (see the enumeration
 *   JVM_DATA_TYPE).
 *
 * @returns Pointer to the first instruction node emitted.  This will
 *    either be an integer load (if the size was specified) or the
 *    jvm_newarray instruction.  Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_new_array(JVM_METHOD *meth, int size, JVM_DATA_TYPE rt)
{
  JVM_CODE_GRAPH_NODE *node, *first;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  first = NULL;

  if(size >= 0)
    first = bc_push_int_const(meth, size);

  if(rt == jvm_Object)
    debug_err(
       "Warning: bc_gen_new_array() shouldn't be used for objects\n");

  node = bytecode1(meth, jvm_newarray, jvm_newarray_type[rt]);  

  if(first)
    return first;
  else
    return node;
}

/**
 * Generates the instructions to create a new object array.
 *
 * This will push the specified size onto the stack.  If you want to omit
 * that instruction (if you're pushing the size yourself before calling this
 * function), then just specify -1 as the size.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param size -- The size of the array to be created (-1 to omit the
 *   instruction to push this value).
 * @param class -- The name of the class which represents the data type of
 *   the array elements.
 *
 * @returns Pointer to the first instruction node emitted.  This will
 *    either be an integer load (if the size was specified) or the
 *    jvm_newarray instruction.  Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_gen_new_object_array(JVM_METHOD *meth, int size, char *class)
{
  JVM_CODE_GRAPH_NODE *node, *first;
  int c;
  char *tmp;

  if(!meth || !class) {
    BAD_ARG();
    return NULL;
  }

  first = NULL;

  if(size >= 0)
    first = bc_push_int_const(meth, size);

  tmp = char_substitute(class, '.', '/');

  if(!tmp) return NULL;

  c = cp_find_or_insert(meth->class, CONSTANT_Class, tmp);

  free(tmp);

  if(c < 0) return NULL;

  node = bytecode1(meth, jvm_anewarray, c);  

  if(first)
    return first;
  else
    return node;
}

/**
 * This function creates a new method reference and inserts it into the
 * constant pool if necessary.  The return value is a pointer to the
 * constant pool node containing the method reference.
 *
 * @param class -- Class containing the constant pool where this
 *   method reference will be stored.
 * @param cname -- The name of the class.
 * @param mname -- The name of the method.
 * @param dnmae -- The method descriptor.
 *
 * @returns The constant pool index of the method reference.
 *    Returns -1 on failure.
 */

int
bc_new_methodref(JVM_CLASS *class, char *cname, char *mname, char *dname)
{
  JVM_METHODREF *methodref;
  int retval;

  if(!class || !cname || !mname || !dname) {
    BAD_ARG();
    return -1;
  }

  methodref = bc_new_method_node(cname,mname,dname);

  if(!methodref) return -1;

  retval = cp_find_or_insert(class, CONSTANT_Methodref, methodref);

  bc_free_fieldref(methodref);

  return retval;
}

/**
 * This function creates a new interface method reference and inserts it
 * into the constant pool if necessary.  The return value is a pointer to
 * the constant pool node containing the interface method reference.
 *
 * @param class -- Class containing the constant pool where this
 *   interface reference will be stored.
 * @param cname -- The name of the class.
 * @param mname -- The name of the method.
 * @param dnmae -- The method descriptor.
 *
 * @returns The constant pool index of the interface reference.
 *    Returns -1 on failure.
 */

int
bc_new_interface_methodref(JVM_CLASS *class, char *cname, char *mname, 
  char *dname)
{
  JVM_METHODREF *interfaceref;
  int retval;

  if(!class || !cname || !mname || !dname) {
    BAD_ARG();
    return -1;
  }

  interfaceref = bc_new_method_node(cname,mname,dname);

  if(!interfaceref) return -1;

  retval = cp_find_or_insert(class, CONSTANT_InterfaceMethodref, interfaceref);

  bc_free_interfaceref(interfaceref);

  return retval;
}

/**
 * This function creates a new method 'node' initialized with the given
 * values for class name, method name, and descriptor.
 *
 * @param cname -- The name of the class.
 * @param mname -- The name of the method.
 * @param dnmae -- The method descriptor.
 *
 * @returns Pointer to the created method reference node.
 */
 
JVM_METHODREF *
bc_new_method_node(char *cname, char *mname, char *dname)
{
  JVM_METHODREF *methodref;
  
  if(!cname || !mname || !dname) {
    BAD_ARG();
    return NULL;
  }

  debug_msg("%%%% new node '%s','%s','%s'\n", cname,mname,dname);

  methodref = (JVM_METHODREF *)malloc(sizeof(JVM_METHODREF));

  if(!methodref) return NULL;

  methodref->classname = char_substitute(cname, '.', '/');
  methodref->methodname = strdup(mname);
  methodref->descriptor = char_substitute(dname, '.', '/');

  if(!methodref->classname || !methodref->methodname || !methodref->descriptor)
  {
    if(methodref->classname) free(methodref->classname);
    if(methodref->methodname) free(methodref->methodname);
    if(methodref->descriptor) free(methodref->descriptor);

    free(methodref);
    return NULL;
  }

  return methodref;
}

/**
 * This function creates a new reference to a name and descriptor in the
 * constant pool.
 *
 * @param class -- Class containing the constant pool where this
 *   namd-and-type reference will be stored.
 * @param name -- The name of the item.
 * @param desc -- The descriptor of the item.
 *
 * @returns The constant pool index of the name-and-type reference.
 *    Returns -1 on failure.
 */

int
bc_new_name_and_type(JVM_CLASS *class, char *name, char *desc)
{
  JVM_METHODREF *nameref;
  int retval;

  if(!class || !name || !desc) {
    BAD_ARG();
    return -1;
  }

  nameref = (JVM_METHODREF *)malloc(sizeof(JVM_METHODREF));

  if(!nameref) return -1;

  nameref->classname = NULL;
  nameref->methodname = strdup(name);
  nameref->descriptor = char_substitute(desc, '.', '/');

  if(!nameref->methodname || !nameref->descriptor)
  {
    bc_free_nameandtype(nameref);
    return -1;
  }

  retval = cp_find_or_insert(class, CONSTANT_NameAndType, nameref);

  bc_free_nameandtype(nameref);

  return retval;
}

/**
 * This function creates a new field reference and inserts it into the
 * constant pool if necessary.  The return value is a pointer to the
 * constant pool node containing the field reference.
 *
 * @param class -- Class containing the constant pool where this
 *   field reference will be stored.
 * @param cname -- The name of the class.
 * @param mname -- The name of the field.
 * @param dnmae -- The field descriptor.
 *
 * @returns The constant pool index of the interface reference.
 *    Returns -1 on failure.
 */

int
bc_new_fieldref(JVM_CLASS *class, char *cname, char *mname, char *dname)
{ 
  JVM_METHODREF *fieldref;
  int retval;
  
  if(!class || !cname || !mname || !dname) {
    BAD_ARG();
    return -1;
  }

  fieldref = bc_new_method_node(cname, mname, dname);
  
  if(!fieldref) return -1;

  retval = cp_find_or_insert(class, CONSTANT_Fieldref, fieldref);
  
  bc_free_fieldref(fieldref);
  
  return retval;
}

/**
 * This function associates a label with a particular instruction.
 * This information is used later to calculate the branch target
 * offsets for branch instructions whose targets were labels.
 * See the bc_set_branch_label() function.
 *
 * Misc notes: this function creates a JVM_BRANCH_PC struct and fills 
 * it in with the pc and label number. This is then inserted into the 
 * method info struct.  Used later by calc_offsets for goto stmts.
 *
 * @param meth -- The method containing the branch and target instructions.
 * @param node -- The node of the target (that is, the instruction which
 *   corresponds to the label in the source code).
 * @param label -- The label specified for this instruction.
 * 
 * @returns 0 on success, -1 on failure.
 */

int
bc_associate_branch_label(JVM_METHOD *meth, JVM_CODE_GRAPH_NODE *node,
  const char *label) 
{
  JVM_BRANCH_PC *bp;

  if(!meth || !node) {
    BAD_ARG();
    return -1;
  }

  bp = (JVM_BRANCH_PC *)malloc(sizeof(JVM_BRANCH_PC));

  if(!bp) return -1;

  bp->instr = node;
  bp->label = strdup(label);

  dl_insert_b(meth->label_list, bp);

  return 0;
}

/**
 * This function associates a label with a particular instruction.
 * Same as bc_associate_branch_label() except that the label is
 * specified as an integer rather than string.
 *
 * @param meth -- The method containing the branch and target instructions.
 * @param node -- The node of the target (that is, the instruction which
 *   corresponds to the label in the source code).
 * @param label_num -- The label number specified for this instruction.
 * 
 * @returns 0 on success, -1 on failure.
 */

int
bc_associate_integer_branch_label(JVM_METHOD *meth, JVM_CODE_GRAPH_NODE *node,
  int label_num)
{
  char label[20];

  if(!meth || !node) {
    BAD_ARG();
    return -1;
  }

  sprintf(label, "%d", label_num);

  return bc_associate_branch_label(meth, node, label);
}

/**
 * This function gets a variable length argument and calls the appropriate
 * routine.  All routines deal with appending an opcode instruction to a
 * methods code array.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param op -- The opcode to be generated.
 * @param ... -- The remaining arguments represent the operands of the
 *   instruction.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

JVM_CODE_GRAPH_NODE *
bc_append(JVM_METHOD *meth, JVM_OPCODE op, ...)
{
  JVM_CODE_GRAPH_NODE *cgNode;
  int inv_idx, inv_cnt;
  va_list pvar;
  u1 index, value;
  u2 dimensions, idx2;
  u4 operand; 

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  va_start(pvar, op);

  switch(op) {
    case jvm_multianewarray:
      idx2 = (u2)va_arg(pvar, int);
      dimensions = (u1)va_arg(pvar, int);
      operand =(idx2<<8) | dimensions;
      cgNode =  bytecode1(meth, jvm_multianewarray, operand);
      break;
    case jvm_tableswitch:
    case jvm_lookupswitch:
      cgNode = bc_gen_switch(meth);  
      break;
    case jvm_invokeinterface:
      inv_idx = va_arg(pvar, int);
      inv_cnt = va_arg(pvar, int);

      operand = (inv_idx << 16) | (inv_cnt << 8);
      cgNode = bytecode1(meth, op, operand);
      break;
    case jvm_xxxunusedxxx:
      cgNode = bytecode0(meth, op);
      break;
    case jvm_goto:
      cgNode = bytecode0(meth, op);
      break;
    case jvm_jsr:
      cgNode = bytecode0(meth, op);
      break;
    case jvm_iinc:
      index = (u1)va_arg(pvar, int);
      value = (u1)va_arg(pvar, int);
      cgNode = bc_gen_iinc(meth, index, value);
      break;
    default:
      if(jvm_opcode[op].width <= 1) {
        cgNode = bytecode0(meth, op);
      }
      else if(jvm_opcode[op].width > 1) {
        operand = (u4)va_arg(pvar, int);
        cgNode = bytecode1(meth, op, operand);
      }
  }

  va_end(pvar);

  return cgNode;
} 

/**
 * Given a file path, open and create directories along the way, if needed.
 *
 * @param file -- The name of the file to be opened.
 * @param mode -- The file creation mode (man fopen(3)).
 * @param output_dir -- The prefix for the full file name (if NULL, just
 *   open the file in the current directory).
 *
 * @returns A file pointer to the created file.
 */
  
FILE *
bc_fopen_fullpath(char *file, char *mode, char *output_dir)
{
  char *pwd = NULL, *prev = NULL, *segment = NULL, *full_file = NULL;
  struct stat *buf = NULL;
  int cur_size;
  FILE *f;

#define err_fopen_full() \
    if(buf) free(buf); \
    if(pwd) free(pwd); \
    if(segment) free(segment); \
    if(full_file) free(full_file);

  if(!file) {
    BAD_ARG();
    return NULL;
  }

  if(!mode) mode = "wb";

  cur_size = 2;
  pwd = (char *)malloc(cur_size);
  if(!pwd) return NULL;

  buf = (struct stat *)malloc(sizeof(struct stat));
  if(!buf) {
    err_fopen_full();
    return NULL;
  }

  while(getcwd(pwd, cur_size) == NULL) {
    char *tmp;

    cur_size *= 2;
 
    tmp = pwd;
    pwd = (char *)realloc(pwd,cur_size);

    if(!pwd) {
      free(tmp);
      err_fopen_full();
      return NULL;
    }
  }

  if(output_dir != NULL) {
    full_file = (char *)malloc(strlen(output_dir) + strlen(file) + 3);

    strcpy(full_file, output_dir);
    if(output_dir[strlen(output_dir)-1] != BC_FILE_DELIM[0])
      strcat(full_file, BC_FILE_DELIM);
    strcat(full_file, file);
  }
  else
    full_file = strdup(file);

  if(!full_file) {
    err_fopen_full();
    return NULL;
  }

  debug_msg("full_file = '%s'\n", full_file);

  if( stat(full_file, buf) == 0)
    if(! S_ISREG(buf->st_mode) ) {
      err_fopen_full();
      return NULL;
    }

  if( (f = fopen(full_file, mode)) != NULL ) {
    err_fopen_full();
    return f;
  }

  if(full_file[0] == BC_FILE_DELIM[0])
    chdir(BC_FILE_DELIM);

  prev = strtok(full_file, BC_FILE_DELIM);

  while( (segment = strtok(NULL,BC_FILE_DELIM)) != NULL ) {

    if( stat(prev, buf) == -1) {
      if(errno == ENOENT) {
#ifdef _WIN32
        if(mkdir(prev) == -1) {
#else
        if(mkdir(prev, 0755) == -1) {
#endif
          chdir(pwd);
          err_fopen_full();
          return NULL;
        }
      }
      else {
        chdir(pwd);
        err_fopen_full();
        return NULL;
      }
    }
    else {
      if(! S_ISDIR(buf->st_mode)) {
        chdir(pwd);
        err_fopen_full();
        return NULL;
      }
    }

    if(chdir(prev) == -1) {
      chdir(pwd);
      err_fopen_full();
      return NULL;
    }

    prev = segment;
  } 
    
  if( (f = fopen(prev, mode)) != NULL ) {
    chdir(pwd);
    err_fopen_full();
    return f;
  }
  
  chdir(pwd);
  free(full_file);
  free(buf);
  free(pwd);
  return NULL; 
}

/**
 * Frees a method info structure.
 *
 * @param m -- The method to be freed.
 */

void
bc_free_method(JVM_METHOD *m)
{
  JVM_ATTRIBUTE *code_attr = NULL;

  if(!m) {
    BAD_ARG();
    return;
  }

  code_attr = find_attribute(m->class,m->attributes,"Code");

  bc_free_attributes(m->class, m->attributes);
  m->attributes = NULL;

  /* if this method was abstract or native, then the code graph would not
   * have been inserted as an attribute to this method (because such methods
   * do not have any code).  therefore the code graph (actually a Dlist) 
   * would not have been freed yet, so we free it here.
   */

  if(!code_attr)
  {
    bc_free_code_attribute(m->class, m->cur_code);
    m->cur_code = NULL;
  }

  if(m->exc_table) dl_delete_list(m->exc_table);

  bc_free_locals_table(m);
  bc_free_line_number_table(m);
  bc_free_label_list(m);

  m->attributes = NULL;
  m->exc_table = NULL;
  m->label_list = NULL;
  m->line_table = NULL;

  if(m->name) free(m->name);
  free(m);
}

/**
 * Frees a line number table.
 *
 * @param m -- The method containing the line number table.
 */

void
bc_free_line_number_table(JVM_METHOD *m)
{
  Dlist tmp;

  dl_traverse(tmp, m->line_table) {
    free(dl_val(tmp));
  }
  dl_delete_list(m->line_table);
  m->line_table = NULL;
}

/**
 * Frees a local variable table.
 *
 * @param m -- The method containing the local variable table.
 */

void
bc_free_locals_table(JVM_METHOD *m)
{
  Dlist tmp;

  dl_traverse(tmp, m->locals_table) {
    JVM_LOCAL_VARIABLE_TABLE_ENTRY * loc;

    loc = (JVM_LOCAL_VARIABLE_TABLE_ENTRY *) dl_val(tmp);

    if(loc->name) free(loc->name);
    if(loc->descriptor) free(loc->descriptor);
    free(loc);
  }

  dl_delete_list(m->locals_table);
  m->locals_table = NULL;
}

/**
 * Frees the list of branch labels in a method.
 *
 * @param m -- The method containing the local variable table.
 */

void
bc_free_label_list(JVM_METHOD *m)
{
  Dlist tmp;

  dl_traverse(tmp, m->label_list) {
    JVM_BRANCH_PC *bp = (JVM_BRANCH_PC *)dl_val(tmp);
    free(bp->label);
    free(bp);
  }
  dl_delete_list(m->label_list);
  m->label_list = NULL;
}

/**
 * Frees a class (and frees all fields of the class file structure).
 *
 * @param class -- The class to be freed.
 */

void
bc_free_class(JVM_CLASS *class)
{
  if(!class) {
    BAD_ARG();
    return;
  }

  bc_free_interfaces(class);
  bc_free_fields(class);
  bc_free_methods(class);
  bc_free_attributes(class, class->attributes);

  /* NOTE: free constant pool last. */
  bc_free_constant_pool(class);

  free(class);
}

/**
 * Frees the list of interfaces the class implements.
 *
 * @param class -- The class containing the list of interfaces.
 */

void
bc_free_interfaces(JVM_CLASS *class)
{
  int * tmpconst;
  Dlist tmpPtr;

  if(!class) {
    BAD_ARG();
    return;
  }

  dl_traverse(tmpPtr,class->interfaces) {
    tmpconst = (int *) tmpPtr->val;
    free(tmpconst);
  }

  dl_delete_list(class->interfaces);
  class->interfaces = NULL;
}

/**
 * Frees the constant pool.
 *
 * @param class -- The class containing the constant pool.
 */

void
bc_free_constant_pool(JVM_CLASS *class)
{
  CP_NODE * tmpconst;
  Dlist tmpPtr;

  if(!class) {
    BAD_ARG();
    return;
  }

  dl_traverse(tmpPtr,class->constant_pool) {
    tmpconst = (CP_NODE *) tmpPtr->val;

    if(tmpconst->val->tag == CONSTANT_Utf8)
      free(tmpconst->val->cpnode.Utf8.bytes);
    free(tmpconst->val);
    free(tmpconst);
  }

  dl_delete_list(class->constant_pool);
  class->constant_pool = NULL;
}

/**
 * Frees the list of fields of this class.
 *
 * @param class -- The class containing the list of fields.
 */

void
bc_free_fields(JVM_CLASS *class)
{
  JVM_FIELD *tmpfield;
  Dlist tmpPtr;

  if(!class) {
    BAD_ARG();
    return;
  }

  dl_traverse(tmpPtr,class->fields) {
    tmpfield = (JVM_FIELD *) tmpPtr->val;

    bc_free_attributes(class, tmpfield->attributes);
    free(tmpfield);
  }

  dl_delete_list(class->fields);
  class->fields = NULL;
}

/**
 * Frees the list of methods of this class.
 *
 * @param class -- The class containing the list of methods.
 */

void
bc_free_methods(JVM_CLASS *class)
{
  Dlist tmpPtr;

  if(!class) {
    BAD_ARG();
    return;
  }

  dl_traverse(tmpPtr,class->methods) {
    bc_free_method((JVM_METHOD *) tmpPtr->val);
  }

  dl_delete_list(class->methods);
  class->methods = NULL;
}

/**
 * Frees a list of attributes.  The attribute list may correspond to
 * a class, method, or field.
 *
 * @param class -- The class containing the constant pool relevant to
 *   the attributes.
 * @param attr_list -- The attribute list to be freed.
 */

void
bc_free_attributes(JVM_CLASS *class, Dlist attr_list)
{
  JVM_ATTRIBUTE *tmpattr;
  char *attr_name;
  Dlist tmpPtr, tmpPtr2;
  CP_NODE *c;

  if(!attr_list || !class) {
    BAD_ARG();
    return;
  }

  dl_traverse(tmpPtr,attr_list) {
    tmpattr = (JVM_ATTRIBUTE *) tmpPtr->val;

    c = cp_entry_by_index(class, tmpattr->attribute_name_index);
    if(c==NULL) {
      debug_err("WARNING: bc_free_attributes() can't find attr name\n");
      continue;
    }

    attr_name = cp_null_term_utf8(c->val);
    if(!attr_name)
      continue;

    if(!strcmp(attr_name,"SourceFile")) {
      free(tmpattr->attr.SourceFile);
      free(tmpattr);
    }
    else if(!strcmp(attr_name,"Deprecated") ||
            !strcmp(attr_name,"Synthetic")) {
      free(tmpattr);
    }
    else if(!strcmp(attr_name,"LocalVariableTable")) {
      free(tmpattr->attr.LocalVariableTable);
      free(tmpattr);
    }
    else if(!strcmp(attr_name,"LineNumberTable")) {
      free(tmpattr->attr.LineNumberTable);
      free(tmpattr);
    }
    else if(!strcmp(attr_name,"InnerClasses")) {
      dl_traverse(tmpPtr2, tmpattr->attr.InnerClasses->classes)
        free(tmpPtr2->val);

      dl_delete_list(tmpattr->attr.InnerClasses->classes);
      free(tmpattr->attr.InnerClasses);
      free(tmpattr);
    }
    else if(!strcmp(attr_name,"ConstantValue")) {
      free(tmpattr->attr.ConstantValue);
      free(tmpattr);
    }
    else if(!strcmp(attr_name,"Code")) {
      bc_free_code_attribute(class, tmpattr);
    }
    else if(!strcmp(attr_name,"Exceptions")) {
      dl_traverse(tmpPtr2, tmpattr->attr.Exceptions->exception_index_table)
        free(tmpPtr2->val);

      dl_delete_list(tmpattr->attr.Exceptions->exception_index_table);
      tmpattr->attr.Exceptions->exception_index_table = NULL;
      free(tmpattr->attr.Exceptions);
      free(tmpattr);
    }
    else {
      /* if the attribute name doesn't match any of the known attributes
       * then assume it's a user defined attribute.
       */
      free(tmpattr->attr.UserDefined->data);
      free(tmpattr->attr.UserDefined);
      free(tmpattr);
    }

    free(attr_name);
  }

  dl_delete_list(attr_list);
}

/**
 * Frees a code attribute.
 *
 * @param class -- The class containing the constant pool relevant to
 *   the code attribute.
 * @param attr -- The code attribute to be freed.
 */

void
bc_free_code_attribute(JVM_CLASS *class, JVM_ATTRIBUTE *attr)
{
  if(!attr) {
    BAD_ARG();
    return;
  }

  bc_free_code(attr->attr.Code->code);

  if(attr->attr.Code->exception_table_length > 0)
    free(attr->attr.Code->exception_table);

  if((attr->attr.Code->attributes_count > 0) && (class != NULL))
    bc_free_attributes(class, attr->attr.Code->attributes);
  else
    dl_delete_list(attr->attr.Code->attributes);

  attr->attr.Code->attributes = NULL;

  free(attr->attr.Code);
  free(attr);
}

/**
 * Frees the list of instruction nodes.
 *
 * @param g -- The list of instructions to be freed.
 */

void
bc_free_code(Dlist g)
{
  Dlist tmp;
  int i;

  if(!g) {
    BAD_ARG();
    return;
  }

  dl_traverse(tmp, g) {
    JVM_CODE_GRAPH_NODE *instr = (JVM_CODE_GRAPH_NODE *)dl_val(tmp);

    if((instr->op == jvm_tableswitch) ||
       (instr->op == jvm_lookupswitch))
    {
      dl_delete_list(instr->switch_info->offsets);

      for(i=0;i<instr->switch_info->num_entries;i++)
        free(instr->switch_info->sorted_entries[i]);
      free(instr->switch_info->sorted_entries);
      free(instr->switch_info);
    }

    if(instr->branch_label) free(instr->branch_label);

    free(tmp->val);
  }

  dl_delete_list(g);
}

/**
 * This function frees memory previously allocated for a fieldref.
 * 
 * @param fieldref -- The field reference to be freed.
 */

void
bc_free_fieldref(JVM_METHODREF *fieldref)
{
  if(!fieldref) {
    BAD_ARG();
    return;
  }

  free(fieldref->classname);
  free(fieldref->methodname);
  free(fieldref->descriptor);
  free(fieldref);
}

/**
 * This function frees memory previously allocated for a methodref.
 * 
 * @param methodref -- The method reference to be freed.
 */

void
bc_free_methodref(JVM_METHODREF *methodref)
{
  if(!methodref) {
    BAD_ARG();
    return;
  }

  bc_free_fieldref(methodref);
}

/**
 * This function frees memory previously allocated for an interface method
 * reference.
 * 
 * @param interfaceref -- The interface reference to be freed.
 */

void
bc_free_interfaceref(JVM_METHODREF *interfaceref)
{
  if(!interfaceref) {
    BAD_ARG();
    return;
  }

  bc_free_fieldref(interfaceref);
}

/**
 * This function frees memory previously allocated for a name and descriptor
 * reference.
 * 
 * @param nameref -- The name-and-type reference to be freed.
 */

void
bc_free_nameandtype(JVM_METHODREF *nameref)
{
  if(!nameref) {
    BAD_ARG();
    return;
  }

  bc_free_fieldref(nameref);
}

/*****************************************************************************
 *****************************************************************************
 **                                                                         **
 ** Functions after this point are not exposed as part of the API.          **
 **                                                                         **
 *****************************************************************************
 *****************************************************************************/


/**
 * Finds the given attribute in an attribute list.
 * Returns NULL if the attribute cannot be found.
 *
 * @param class -- The class containing the constant pool relevant to
 *   the attribute.
 * @param attr_list -- The list of attributes to be searched.
 * @param attr -- The name of the attribute to find.
 *
 * @returns Pointer to the attribute, if found.  If the attribute is not
 *   found, returns NULL.
 */
  
static JVM_ATTRIBUTE *
find_attribute(JVM_CLASS *class, Dlist attr_list, char *attr)
{
  JVM_ATTRIBUTE *tmpattr;
  char *attr_name;
  Dlist tmpPtr;
  CP_NODE *c;

  if(!attr_list || !class || !attr) {
    BAD_ARG();
    return NULL;
  }

  dl_traverse(tmpPtr,attr_list) {
    tmpattr = (JVM_ATTRIBUTE *) tmpPtr->val;

    c = cp_entry_by_index(class, tmpattr->attribute_name_index);

    if(c == NULL) {
      debug_err("WARNING: find_attribute() can't find attr name\n");
      continue;
    }

    attr_name = cp_null_term_utf8(c->val);
    if(!attr_name)
      continue;

    if(!strcmp(attr_name,attr)) {
      free(attr_name);
      return tmpattr;
    }

    free(attr_name);
  }

  return NULL;
}

/**
 * Creates a new attribute structure and initializes the Code_attribute
 * section with some initial values.
 *
 * @param cclass -- The class containing the constant pool relevant to
 *   the attribute.
 *
 * @returns Pointer to the new attribute.
 */

static JVM_ATTRIBUTE *
new_code_attr(JVM_CLASS *cclass)
{
  JVM_ATTRIBUTE * tmp;
  int c;

  if(!cclass) {
    BAD_ARG();
    return NULL;
  }

  tmp = (JVM_ATTRIBUTE *)malloc(sizeof(JVM_ATTRIBUTE));

  if(!tmp) return NULL;

  c = cp_find_or_insert(cclass, CONSTANT_Utf8, "Code");

  if(c < 0) {
    free(tmp);
    return NULL;
  }

  tmp->attribute_name_index = c;
  tmp->attribute_length = 0;
  tmp->attr.Code = (struct Code_attribute *)
        malloc(sizeof(struct Code_attribute));

  if(!tmp->attr.Code) {
    free(tmp);
    return NULL;
  }

  tmp->attr.Code->max_stack = 0;
  tmp->attr.Code->max_locals = 0;
  tmp->attr.Code->code_length = 0;
  tmp->attr.Code->code = make_dl();
  tmp->attr.Code->exception_table_length = 0;
  tmp->attr.Code->exception_table = NULL;
  tmp->attr.Code->attributes_count = 0;
  tmp->attr.Code->attributes = make_dl();
  
  if(!tmp->attr.Code->code || !tmp->attr.Code->attributes) {
    if(tmp->attr.Code->code) dl_delete_list(tmp->attr.Code->code);
    if(tmp->attr.Code->attributes) dl_delete_list(tmp->attr.Code->attributes);

    tmp->attr.Code->code = NULL;
    tmp->attr.Code->attributes = NULL;

    free(tmp->attr.Code);
    tmp->attr.Code = NULL;

    free(tmp);
    return NULL;
  }

  return tmp;
}

/**
 * Inserts the given instruction into the code graph.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param op -- The opcode to be generated.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

static JVM_CODE_GRAPH_NODE *
bytecode0(JVM_METHOD *meth, JVM_OPCODE op)
{
  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  return bytecode1(meth, op,0);
}

/**
 * Inserts the given instruction into the code graph.
 *
 * @param meth -- The method to which this instruction should be added.
 * @param op -- The opcode to be generated.
 * @param operand -- The operand to this instruction.
 *
 * @returns Pointer to the instruction node.
 *    Returns NULL on error.
 */

static JVM_CODE_GRAPH_NODE *
bytecode1(JVM_METHOD *meth, JVM_OPCODE op, u4 operand)
{
  JVM_CODE_GRAPH_NODE *tmp, *prev;

  if(!meth) {
    BAD_ARG();
    return NULL;
  }

  /* if we should not generate bytecode, then just return a dummy node */
  if(!meth->gen_bytecode) {
    JVM_CODE_GRAPH_NODE *g;

    /* keep track of the dummy node so that we may reclaim the memory later. */
    g = bc_new_graph_node(meth, op, operand);
    return g;
  }

  meth->lastOp = op;

  if(meth->cur_code->attr.Code->code == NULL)
    debug_err("ERROR: null code graph.\n");

  prev = (JVM_CODE_GRAPH_NODE *) dl_val(dl_last(meth->cur_code->attr.Code->code));

  if((prev != NULL) && (prev->op == jvm_xxxunusedxxx)) {
    prev->op = op;
    prev->operand = operand;
    prev->width = bc_op_width(op);
    meth->pc += bc_op_width(op) - bc_op_width(jvm_xxxunusedxxx);
    return prev;
  }

  tmp = bc_new_graph_node(meth, op, operand);

  if(!tmp) return NULL;

  if(prev != NULL)
    prev->next = tmp;

  dl_insert_b(meth->cur_code->attr.Code->code, tmp);

  /* if the previous instruction was 'wide', then we need to
   * increase the width of this instruction.
   */
  if((prev != NULL) && (prev->op == jvm_wide)) {
    if( (op == jvm_iload) || (op == jvm_fload) || (op == jvm_aload) ||
        (op == jvm_lload) || (op == jvm_dload) || (op == jvm_istore) ||
        (op == jvm_fstore) || (op == jvm_astore) || (op == jvm_lstore) ||
        (op == jvm_dstore) || (op == jvm_ret))
      tmp->width = bc_op_width(op) + 1;
    else if(op == jvm_iinc)
      tmp->width = bc_op_width(op) + 2;
    else
      debug_err("Error: bad op used after wide instruction (%s)\n",
          jvm_opcode[op].op);
  }

  meth->pc += tmp->width;

  return tmp;
}

/**
 * Given a local variable number (which presumably is the target of some
 * load/store or other instruction that uses a local), make sure that the
 * total number of local variables for this method is large enough to
 * accommodate the specified local variable.  If not, then update it based
 * on the given number.
 *
 * @param meth -- The current method.
 * @param lvnum -- The local variable number being used in some instruction.
 * @param rt -- The JVM data type of the local variable (see the enumeration
 *   JVM_DATA_TYPE).
 */

static void
updateMaxLocals(JVM_METHOD *meth, unsigned int lvnum,
  JVM_DATA_TYPE rt)
{
  int max = lvnum + jvm_localvar_width[rt];

  if(!meth) {
    BAD_ARG();
    return;
  }

  if(max > meth->max_locals)
    meth->max_locals = max;
}

/**
 * Given a method descriptor, this function returns the number of local
 * variables needed to hold the arguments.  doubles and longs use 2 local
 * vars, while every other data type only uses 1 local.
 * 
 * @param d -- The method descriptor.
 *
 * @returns The number of local variables in this descriptor.
 */

static int
num_locals_in_descriptor(char *d)
{
  int vlen = 0;

  if(!d) {
    BAD_ARG();
    return 0;
  }

  while( (d = bc_next_desc_token(d)) != NULL) {

    /* if the next token is NULL, then we have no more useful tokens in
     * this descriptor.
     */
    if(bc_next_desc_token(d) == NULL)
      break;

    if((d[0] == 'D') || (d[0] == 'J'))
      vlen += 2;
    else
      vlen++;
  }

  return vlen;
}

/**
 * This function substitutes every occurrence of 'from_char' with 'to_char'
 * typically this is used to convert package names:
 *
 *   e.g.     "java.lang.whatever" -> "java/lang/whatever"
 *
 * Space for the modified string is allocated by this function.
 *
 * @param str -- The string to be converted.
 * @param from_char -- The character to change from.
 * @param to_char -- The character to change to.
 *
 * @returns The modified string (in newly allocated memory).
 */

static char *
char_substitute(char *str, int from_char, int to_char)
{
  char *newstr, *idx;

  if(!str) {
    BAD_ARG();
    return NULL;
  }

  newstr = strdup(str);
  if(!newstr) return NULL;

  while( (idx = strchr(newstr, from_char)) != NULL )
    *idx = to_char;

  return newstr;
}