Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Code.cs « PEAPI « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: af8ae771cfa48247779c2f81463aa9719be4c282 (plain)
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
using System.IO;
using System.Collections;

namespace PEAPI {

	/**************************************************************************/  
	/// <summary>
	/// Descriptor for an IL instruction
	/// </summary>
	internal abstract class CILInstruction {
		protected static readonly sbyte maxByteVal = 127;
		protected static readonly sbyte minByteVal = -128;
		protected static readonly byte leadByte = 0xFE;
		protected static readonly uint USHeapIndex = 0x70000000;
		protected static readonly int longInstrStart = (int)Op.arglist;
		public bool twoByteInstr = false;
		public uint size = 0;
		public uint offset;

		internal virtual bool Check(MetaData md) 
		{
			return false;
		}

		internal virtual void Write(FileImage output) { }

	}

	internal class CILByte : CILInstruction {
		byte byteVal;

		internal CILByte(byte bVal) 
		{
			byteVal = bVal;
			size = 1;
		}

		internal override void Write(FileImage output) 
		{
			output.Write(byteVal);
		}

	}

	internal class Instr : CILInstruction {
		protected int instr;

		internal Instr(int inst) 
		{
			if (inst >= longInstrStart) {
				instr = inst - longInstrStart;
				twoByteInstr = true;
				size = 2;
			} else {
				instr = inst;
				size = 1;
			}
		}

		internal override void Write(FileImage output) 
		{
			//Console.WriteLine("Writing instruction " + instr + " with size " + size);
			if (twoByteInstr) output.Write(leadByte);
			output.Write((byte)instr);
		}

	}

	internal class IntInstr : Instr {
		int val;
		bool byteNum;

		internal IntInstr(int inst, int num, bool byteSize) : base(inst) 
		{
			val = num;
			byteNum = byteSize;
			if (byteNum) size++;
			else size += 4;
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			if (byteNum) 
				output.Write((sbyte)val);
			else 
				output.Write(val); 
		}

	}

	internal class UIntInstr : Instr {
		int val;
		bool byteNum;

		internal UIntInstr(int inst, int num, bool byteSize) : base(inst) 
		{
			val = num;
			byteNum = byteSize;
			if (byteNum) size++;
			else size += 2;
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			if (byteNum)
				output.Write((byte)val);
			else
				output.Write((ushort)val); 
		}

	}

	internal class LongInstr : Instr {
		long val;

		internal LongInstr(int inst, long l) : base(inst) 
		{
			val = l;
			size += 8;
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			output.Write(val);
		}

	}

	internal class FloatInstr : Instr {
		float fVal;

		internal FloatInstr(int inst, float f) : base(inst) 
		{
			fVal = f;
			size += 4;
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			output.Write(fVal);
		}

	}

	internal class DoubleInstr : Instr {
		double val;

		internal DoubleInstr(int inst, double d) : base(inst) 
		{
			val = d;
			size += 8;
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			output.Write(val);
		}

	}

	internal class StringInstr : Instr {
		string val;
		byte[] bval;                                                  
		uint strIndex;

		internal StringInstr(int inst, string str) : base(inst) 
		{
			val = str;  
			size += 4;
		}

		internal StringInstr (int inst, byte[] str) : base (inst) 
		{
			bval = str;
			size += 4;
		}

		internal sealed override bool Check(MetaData md) 
		{
			if (val != null)
				strIndex = md.AddToUSHeap(val);
			else
				strIndex = md.AddToUSHeap (bval);
			return false;
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			output.Write(USHeapIndex  | strIndex);
		}

	}

	internal class LabelInstr : CILInstruction {
		CILLabel label;

		internal LabelInstr(CILLabel lab) 
		{
			label = lab;
			label.AddLabelInstr(this);
		}
	}

	internal class FieldInstr : Instr {
		Field field;

		internal FieldInstr(int inst, Field f) : base(inst) 
		{
			field = f;
			size += 4;
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			output.Write(field.Token());
		}

	}

	internal class MethInstr : Instr {
		Method meth;

		internal MethInstr(int inst, Method m) : base(inst) 
		{
			meth = m;
			size += 4;
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			output.Write(meth.Token());
		}

	}

	internal class SigInstr : Instr {
		CalliSig signature;

		internal SigInstr(int inst, CalliSig sig) : base(inst) 
		{
			signature = sig;
			size += 4;
		}

		internal sealed override bool Check(MetaData md) 
		{
			md.AddToTable(MDTable.StandAloneSig,signature);
			signature.BuildTables(md);
			return false;
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			output.Write(signature.Token());
		}
	}

	internal class TypeInstr : Instr {
		MetaDataElement theType;

		internal TypeInstr(int inst, Type aType, MetaData md) : base(inst) 
		{
			theType = aType.GetTypeSpec(md);
			size += 4;
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			output.Write(theType.Token());
		}

	}

	internal class BranchInstr : Instr {
		CILLabel dest;
		private bool shortVer = true;
		private static readonly byte longInstrOffset = 13;
		private int target = 0;

		internal BranchInstr(int inst, CILLabel dst) : base(inst) 
		{
			dest = dst;
			dest.AddBranch(this);
			size++;

			if (inst >= (int) BranchOp.br && inst != (int) BranchOp.leave_s) {
				shortVer = false;
				size += 3;
			}
		}

		internal sealed override bool Check(MetaData md) 
		{
			target = (int)dest.GetLabelOffset() - (int)(offset + size);
			return false;
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			if (shortVer)
				output.Write((sbyte)target);
			else
				output.Write(target);
		}

	}

	internal class SwitchInstr : Instr {
		CILLabel[] cases;
		uint numCases = 0;

		internal SwitchInstr(int inst, CILLabel[] dsts) : base(inst) 
		{
			cases = dsts;
			if (cases != null) numCases = (uint)cases.Length;
			size += 4 + (numCases * 4);
			for (int i=0; i < numCases; i++) {
				cases[i].AddBranch(this);
			}
		}

		internal sealed override void Write(FileImage output) 
		{
			base.Write(output);
			output.Write(numCases);
			for (int i=0; i < numCases; i++) {
				int target = (int)cases[i].GetLabelOffset() - (int)(offset + size);
				output.Write(target);
			}
		}

	}

	/**************************************************************************/  
	/// <summary>
	/// The IL instructions for a method
	/// </summary>
	public class CILInstructions  {
		private static readonly uint ExHeaderSize = 4;
		private static readonly uint FatExClauseSize = 24;
		private static readonly uint SmlExClauseSize = 12;
		private static readonly sbyte maxByteVal = 127;
		private static readonly sbyte minByteVal = -128;
		private static readonly byte maxUByteVal = 255;
		private static readonly int smallSize = 64;
		private static readonly ushort TinyFormat = 0x2;
		private static readonly ushort FatFormat = 0x3003;
		private static readonly ushort MoreSects = 0x8;
		private static readonly ushort InitLocals = 0x10;
		private static readonly uint FatSize = 12;
		private static readonly uint FatWords = FatSize/4;
		private static readonly byte FatExceptTable = 0x41;
		private static readonly byte SmlExceptTable = 0x01; 

		private MetaData metaData;
		private ArrayList exceptions, blockStack;
		//private bool codeChecked = false;
		private static readonly int INITSIZE = 5;
		private CILInstruction[] buffer = new CILInstruction[INITSIZE];
		private int tide = 0;
		private uint offset = 0;
		private ushort headerFlags = 0;
		private short maxStack;
		private uint paddingNeeded = 0;
		private byte exceptHeader = 0;
		uint localSigIx = 0;
		uint codeSize = 0, exceptSize = 0;
		bool tinyFormat, fatExceptionFormat = false;

		public uint Offset {
			get { return offset; }
		}	

		internal CILInstructions(MetaData md) 
		{
			metaData = md;
		}

		private void AddToBuffer(CILInstruction inst) 
		{
			if (tide >= buffer.Length) {
				CILInstruction[] tmp = buffer;
				buffer = new CILInstruction[tmp.Length * 2];
				for (int i=0; i < tide; i++) {
					buffer[i] = tmp[i];
				}
			}
			//Console.WriteLine("Adding instruction at offset " + offset + " with size " + inst.size);
			inst.offset = offset;
			offset += inst.size;
			buffer[tide++] = inst;
		}

		/// <summary>
		/// Add a simple IL instruction
		/// </summary>
		/// <param name="inst">the IL instruction</param>
		public void Inst(Op inst) 
		{
			AddToBuffer(new Instr((int)inst));
		}

		/// <summary>
		/// Add an IL instruction with an integer parameter
		/// </summary>
		/// <param name="inst">the IL instruction</param>
		/// <param name="val">the integer parameter value</param>
		public void IntInst(IntOp inst, int val) 
		{
			int instr = (int)inst;
			if ((inst == IntOp.ldc_i4_s) || (inst == IntOp.ldc_i4)) 
				AddToBuffer(new IntInstr(instr,val,(inst == IntOp.ldc_i4_s)));
			else
				AddToBuffer(new UIntInstr(instr,val,((inst < IntOp.ldc_i4_s) ||
								(inst == IntOp.unaligned))));
		}

		/// <summary>
		/// Add the load long instruction
		/// </summary>
		/// <param name="cVal">the long value</param>
		public void ldc_i8(long cVal) 
		{
			AddToBuffer(new LongInstr(0x21,cVal));
		}

		/// <summary>
		/// Add the load float32 instruction
		/// </summary>
		/// <param name="cVal">the float value</param>
		public void ldc_r4(float cVal) 
		{
			AddToBuffer(new FloatInstr(0x22,cVal));
		}

		/// <summary>
		/// Add the load float64 instruction
		/// </summary>
		/// <param name="cVal">the float value</param>
		public void ldc_r8(double cVal) 
		{
			AddToBuffer(new DoubleInstr(0x23,cVal));
		}

		/// <summary>
		/// Add the load string instruction
		/// </summary>
		/// <param name="str">the string value</param>
		public void ldstr(string str) 
		{
			AddToBuffer(new StringInstr(0x72,str));
		}

		/// <summary>
		/// Add the load string instruction
		/// </summary>
		public void ldstr (byte[] str) 
		{
			AddToBuffer (new StringInstr (0x72, str));
		}

		/// <summary>
		/// Add the calli instruction
		/// </summary>
		/// <param name="sig">the signature for the calli</param>
		public void calli(CalliSig sig) 
		{
			AddToBuffer(new SigInstr(0x29,sig));
		}

		/// <summary>
		/// Add a label to the CIL instructions
		/// </summary>
		/// <param name="lab">the label to be added</param>
		public void CodeLabel(CILLabel lab) 
		{
			AddToBuffer(new LabelInstr(lab));
		}

		/// <summary>
		/// Add an instruction with a field parameter
		/// </summary>
		/// <param name="inst">the CIL instruction</param>
		/// <param name="f">the field parameter</param>
		public void FieldInst(FieldOp inst, Field f) 
		{
			AddToBuffer(new FieldInstr((int)inst,f));
		}

		/// <summary>
		/// Add an instruction with a method parameter
		/// </summary>
		/// <param name="inst">the CIL instruction</param>
		/// <param name="m">the method parameter</param>
		public void MethInst(MethodOp inst, Method m) 
		{
			AddToBuffer(new MethInstr((int)inst,m));
		}

		/// <summary>
		/// Add an instruction with a type parameter
		/// </summary>
		/// <param name="inst">the CIL instruction</param>
		/// <param name="t">the type argument for the CIL instruction</param>
		public void TypeInst(TypeOp inst, Type aType) 
		{
			AddToBuffer(new TypeInstr((int)inst,aType,metaData));
		}

		/// <summary>
		/// Add a branch instruction
		/// </summary>
		/// <param name="inst">the branch instruction</param>
		/// <param name="lab">the label that is the target of the branch</param>
		public void Branch(BranchOp inst,  CILLabel lab) 
		{
			AddToBuffer(new BranchInstr((int)inst,lab));
		}

		/// <summary>
		/// Add a switch instruction
		/// </summary>
		/// <param name="labs">the target labels for the switch</param>
		public void Switch(CILLabel[] labs) 
		{
			AddToBuffer(new SwitchInstr(0x45,labs));
		}

		/// <summary>
		/// Add a byte to the CIL instructions (.emitbyte)
		/// </summary>
		/// <param name="bVal"></param>
		public void emitbyte(byte bVal) 
		{
			AddToBuffer(new CILByte(bVal));
		}

		/// <summary>
		/// Add an instruction which puts an integer on TOS.  This method
		/// selects the correct instruction based on the value of the integer.
		/// </summary>
		/// <param name="i">the integer value</param>
		public void PushInt(int i) 
		{
			if (i == -1) {
				AddToBuffer(new Instr((int)Op.ldc_i4_m1));
			} else if ((i >= 0) && (i <= 8)) {
				Op op = (Op)(Op.ldc_i4_0 + i);
				AddToBuffer(new Instr((int)op));
			} else if ((i >= minByteVal) && (i <= maxByteVal)) {
				AddToBuffer(new IntInstr((int)IntOp.ldc_i4_s,i,true));
			} else {
				AddToBuffer(new IntInstr((int)IntOp.ldc_i4,i,false)); 
			}
		}

		/// <summary>
		/// Add the instruction to load a long on TOS
		/// </summary>
		/// <param name="l">the long value</param>
		public void PushLong(long l) 
		{
			AddToBuffer(new LongInstr(0x21,l));
		}

		/// <summary>
		/// Add an instruction to push the boolean value true on TOS
		/// </summary>
		public void PushTrue() 
		{
			AddToBuffer(new Instr((int)Op.ldc_i4_1));
		}

		/// <summary>
		///  Add an instruction to push the boolean value false on TOS
		/// </summary>
		public void PushFalse() 
		{
			AddToBuffer(new Instr((int)Op.ldc_i4_0));
		}

		/// <summary>
		/// Add the instruction to load an argument on TOS.  This method
		/// selects the correct instruction based on the value of argNo
		/// </summary>
		/// <param name="argNo">the number of the argument</param>
		public void LoadArg(int argNo) 
		{
			if (argNo < 4) {
				int op = (int)Op.ldarg_0 + argNo;
				AddToBuffer(new Instr(op));
			} else if (argNo <= maxUByteVal) {
				AddToBuffer(new UIntInstr((int)IntOp.ldarg,argNo,true));
			} else {
				AddToBuffer(new UIntInstr(0x09,argNo,false)); 
			}
		}

		/// <summary>
		/// Add the instruction to load the address of an argument on TOS.
		/// This method selects the correct instruction based on the value
		/// of argNo.
		/// </summary>
		/// <param name="argNo">the number of the argument</param>
		public void LoadArgAdr(int argNo) 
		{
			if (argNo <= maxUByteVal) {
				AddToBuffer(new UIntInstr((int)IntOp.ldarga,argNo,true));
			} else {
				AddToBuffer(new UIntInstr(0x0A,argNo,false)); 
			}
		}

		/// <summary>
		/// Add the instruction to load a local on TOS.  This method selects
		/// the correct instruction based on the value of locNo.
		/// </summary>
		/// <param name="locNo">the number of the local to load</param>
		public void LoadLocal(int locNo) 
		{
			if (locNo < 4) {
				int op = (int)Op.ldloc_0 + locNo;
				AddToBuffer(new Instr(op));
			} else if (locNo <= maxUByteVal) {
				AddToBuffer(new UIntInstr((int)IntOp.ldloc,locNo,true));
			} else {
				AddToBuffer(new UIntInstr(0x0C,locNo,false)); 
			}
		}

		/// <summary>
		/// Add the instruction to load the address of a local on TOS.
		/// This method selects the correct instruction based on the 
		/// value of locNo.
		/// </summary>
		/// <param name="locNo">the number of the local</param>
		public void LoadLocalAdr(int locNo) 
		{
			if (locNo <= maxUByteVal) {
				AddToBuffer(new UIntInstr((int)IntOp.ldloca,locNo,true));
			} else {
				AddToBuffer(new UIntInstr(0x0D,locNo,false)); 
			}
		}

		/// <summary>
		/// Add the instruction to store to an argument.  This method
		/// selects the correct instruction based on the value of argNo.
		/// </summary>
		/// <param name="argNo">the argument to be stored to</param>
		public void StoreArg(int argNo) 
		{
			if (argNo <= maxUByteVal) {
				AddToBuffer(new UIntInstr((int)IntOp.starg,argNo,true));
			} else {
				AddToBuffer(new UIntInstr(0x0B,argNo,false)); 
			}
		}

		/// <summary>
		/// Add the instruction to store to a local.  This method selects
		/// the correct instruction based on the value of locNo.
		/// </summary>
		/// <param name="locNo">the local to be stored to</param>
		public void StoreLocal(int locNo) 
		{
			if (locNo < 4) {
				int op = (int)Op.stloc_0 + locNo;
				AddToBuffer(new Instr(op));
			} else if (locNo <= maxUByteVal) {
				AddToBuffer(new UIntInstr((int)IntOp.stloc,locNo,true));
			} else {
				AddToBuffer(new UIntInstr(0x0E,locNo,false)); 
			}
		}

		/// <summary>
		/// Create a new CIL label.  To place the label in the CIL instruction
		/// stream use CodeLabel.
		/// </summary>
		/// <returns>a new CIL label</returns>
		public CILLabel NewLabel() 
		{
			return new CILLabel();
		}

		public void AddTryBlock(TryBlock tryBlock) 
		{
			if (exceptions == null) 
				exceptions = new ArrayList();
			else if (exceptions.Contains(tryBlock)) return;
			exceptions.Add(tryBlock);
		}

		/// <summary>
		/// Create a new label at this position in the code buffer
		/// </summary>
		/// <returns>the label at the current position</returns>
		public CILLabel NewCodedLabel() 
		{
			CILLabel lab = new CILLabel();
			AddToBuffer(new LabelInstr(lab));
			return lab;
		}

		/// <summary>
		/// Mark this position as the start of a new block
		/// (try, catch, filter, finally or fault)
		/// </summary>
		public void StartBlock() 
		{
			if (blockStack == null) blockStack = new ArrayList();
			blockStack.Insert(0,NewCodedLabel());
		}

		/// <summary>
		/// Mark this position as the end of the last started block and
		/// make it a try block.  This try block is added to the current 
		/// instructions (ie do not need to call AddTryBlock)
		/// </summary>
		/// <returns>The try block just ended</returns>
		public TryBlock EndTryBlock() 
		{
			TryBlock tBlock = new TryBlock((CILLabel)blockStack[0],NewCodedLabel());
			blockStack.RemoveAt(0);
			AddTryBlock(tBlock);
			return tBlock;
		}

		/// <summary>
		/// Mark this position as the end of the last started block and
		/// make it a catch block.  This catch block is associated with the
		/// specified try block.
		/// </summary>
		/// <param name="exceptType">the exception type to be caught</param>
		/// <param name="tryBlock">the try block associated with this catch block</param>
		public void EndCatchBlock(Class exceptType, TryBlock tryBlock) 
		{
			Catch catchBlock = new Catch(exceptType,(CILLabel)blockStack[0],
					NewCodedLabel());
			tryBlock.AddHandler(catchBlock);
		}

		/// <summary>
		/// Mark this position as the end of the last started block and
		/// make it a filter block.  This filter block is associated with the
		/// specified try block.
		/// </summary>
		/// <param name="filterLab">the label where the filter code is</param>
		/// <param name="tryBlock">the try block associated with this filter block</param>
		public void EndFilterBlock(CILLabel filterLab, TryBlock tryBlock) 
		{
			Filter filBlock = new Filter(filterLab,(CILLabel)blockStack[0],NewCodedLabel());
			tryBlock.AddHandler(filBlock);
		}

		/// <summary>
		/// Mark this position as the end of the last started block and
		/// make it a finally block.  This finally block is associated with the
		/// specified try block.
		/// </summary>
		/// <param name="tryBlock">the try block associated with this finally block</param>
		public void EndFinallyBlock(TryBlock tryBlock) 
		{
			Finally finBlock= new Finally((CILLabel)blockStack[0],NewCodedLabel());
			tryBlock.AddHandler(finBlock);
		}

		/// <summary>
		/// Mark this position as the end of the last started block and
		/// make it a fault block.  This fault block is associated with the
		/// specified try block.
		/// </summary>
		/// <param name="tryBlock">the try block associated with this fault block</param>
		public void EndFaultBlock(TryBlock tryBlock) 
		{
			Fault fBlock= new Fault((CILLabel)blockStack[0],NewCodedLabel());
			tryBlock.AddHandler(fBlock);
		}

		internal uint GetCodeSize() 
		{
			return codeSize + paddingNeeded + exceptSize;
		}

		internal void CheckCode(uint locSigIx, bool initLocals, int maxStack) 
		{
			if (tide == 0) return;
			bool changed = true;
			while (changed) {
				changed = false;
				for (int i=0; i < tide; i++) {
					changed = buffer[i].Check(metaData) || changed;
				}
				if (changed) {
					for (int i=1; i < tide; i++) {
						buffer[i].offset = buffer[i-1].offset + buffer[i-1].size;
					}
					offset = buffer[tide-1].offset + buffer[tide-1].size;
				}
			}
			codeSize = offset;
			// Console.WriteLine("codeSize before header added = " + codeSize);
			if ((offset < smallSize) && (maxStack <= 8) && (locSigIx == 0) && (exceptions == null)) {
				// can use tiny header
				//Console.WriteLine("Tiny Header");
				tinyFormat = true;
				headerFlags = (ushort)(TinyFormat | ((ushort)codeSize << 2));
				codeSize++;
				if ((codeSize % 4) != 0) { paddingNeeded = 4 - (codeSize % 4); }
			} else {
				//Console.WriteLine("Fat Header");
				tinyFormat = false;
				localSigIx = locSigIx;
				this.maxStack = (short)maxStack;
				headerFlags = FatFormat;
				if (exceptions != null) {
					// Console.WriteLine("Got exceptions");
					headerFlags |= MoreSects;
					uint numExceptClauses = 0;
					for (int i=0; i < exceptions.Count; i++) {
						TryBlock tryBlock = (TryBlock)exceptions[i];
						tryBlock.SetSize();
						numExceptClauses += (uint)tryBlock.NumHandlers();
						if (tryBlock.isFat()) fatExceptionFormat = true;
					}

					uint data_size = ExHeaderSize + numExceptClauses *
						(fatExceptionFormat ? FatExClauseSize : SmlExClauseSize);

					if (data_size > 255)
						fatExceptionFormat = true;

					// Console.WriteLine("numexceptclauses = " + numExceptClauses);
					if (fatExceptionFormat) {
						// Console.WriteLine("Fat exception format");
						exceptHeader = FatExceptTable;
						exceptSize = ExHeaderSize + numExceptClauses * FatExClauseSize;
					} else {
						// Console.WriteLine("Tiny exception format");
						exceptHeader = SmlExceptTable;
						exceptSize = ExHeaderSize + numExceptClauses * SmlExClauseSize;
					}
					// Console.WriteLine("exceptSize = " + exceptSize);
				}
				if (initLocals) headerFlags |= InitLocals;
				if ((offset % 4) != 0) { paddingNeeded = 4 - (offset % 4); }
				codeSize += FatSize;
			}
			// Console.WriteLine("codeSize = " + codeSize + "  headerFlags = " + 
			//                   Hex.Short(headerFlags));
		}

		internal void Write(FileImage output) 
		{
			// Console.WriteLine("Writing header flags = " + Hex.Short(headerFlags));
			if (tinyFormat) {
				// Console.WriteLine("Writing tiny code");
				output.Write((byte)headerFlags);
			} else {
				// Console.WriteLine("Writing fat code");
				output.Write(headerFlags);
				output.Write((ushort)maxStack);
				output.Write(offset);
				output.Write(localSigIx);
			}
			// Console.WriteLine(Hex.Int(tide) + " CIL instructions");
			// Console.WriteLine("starting instructions at " + output.Seek(0,SeekOrigin.Current));
			for (int i=0; i < tide; i++) {
				buffer[i].Write(output);
			}
			// Console.WriteLine("ending instructions at " + output.Seek(0,SeekOrigin.Current));
			for (int i=0; i < paddingNeeded; i++) { output.Write((byte)0); }
			if (exceptions != null) {
				// Console.WriteLine("Writing exceptions");
				// Console.WriteLine("header = " + Hex.Short(exceptHeader) + " exceptSize = " + Hex.Int(exceptSize));
				output.Write(exceptHeader);
				output.Write3Bytes((uint)exceptSize);
				for (int i=0; i < exceptions.Count; i++) {
					TryBlock tryBlock = (TryBlock)exceptions[i];
					tryBlock.Write(output,fatExceptionFormat);
				}
			}
		}

	}

	/**************************************************************************/  
	public abstract class CodeBlock {

		private static readonly int maxCodeSize = 255;
		protected CILLabel start, end;
		protected bool small = true;

		public CodeBlock(CILLabel start, CILLabel end) 
		{
			this.start = start;
			this.end = end;
		}

		internal virtual bool isFat() 
		{
			// Console.WriteLine("block start = " + start.GetLabelOffset() +
			//                  "  block end = " + end.GetLabelOffset());
			return (end.GetLabelOffset() - start.GetLabelOffset()) > maxCodeSize;
		}

		internal virtual void Write(FileImage output, bool fatFormat) 
		{
			if (fatFormat) output.Write(start.GetLabelOffset());
			else output.Write((short)start.GetLabelOffset());
			uint len = end.GetLabelOffset() - start.GetLabelOffset();
			if (fatFormat) output.Write(len);
			else output.Write((byte)len);
		}

	}

	/// <summary>
	/// The descriptor for a guarded block (.try)
	/// </summary>
	public class TryBlock : CodeBlock {
		protected bool fatFormat = false;
		protected int flags = 0;
		ArrayList handlers = new ArrayList();

		/// <summary>
		/// Create a new try block
		/// </summary>
		/// <param name="start">start label for the try block</param>
		/// <param name="end">end label for the try block</param>
		public TryBlock(CILLabel start, CILLabel end) : base(start,end) { }

		/// <summary>
		/// Add a handler to this try block
		/// </summary>
		/// <param name="handler">a handler to be added to the try block</param>
		public void AddHandler(HandlerBlock handler) 
		{
			flags = handler.GetFlag();
			handlers.Add(handler);
		}

		internal void SetSize() 
		{
			fatFormat = base.isFat();
			if (fatFormat) return;
			for (int i=0; i < handlers.Count; i++) {
				HandlerBlock handler = (HandlerBlock)handlers[i];
				if (handler.isFat()) {
					fatFormat = true;
					return;
				}
			}
		}

		internal int NumHandlers() 
		{
			return handlers.Count;
		}

		internal override bool isFat() 
		{
			return fatFormat;
		}

		internal override void Write(FileImage output, bool fatFormat) 
		{
			// Console.WriteLine("writing exception details");
			for (int i=0; i < handlers.Count; i++) {
				// Console.WriteLine("Except block " + i);
				HandlerBlock handler = (HandlerBlock)handlers[i];
				if (fatFormat) output.Write(flags);
				else output.Write((short)flags);
				// Console.WriteLine("flags = " + Hex.Short(flags));
				base.Write(output,fatFormat);
				handler.Write(output,fatFormat);
			}
		}
	}

	public abstract class HandlerBlock : CodeBlock  {

		protected static readonly short ExceptionFlag = 0;
		protected static readonly short FilterFlag = 0x01;
		protected static readonly short FinallyFlag = 0x02;
		protected static readonly short FaultFlag = 0x04;

		public HandlerBlock(CILLabel start, CILLabel end) : base(start,end) { }

		internal virtual short GetFlag() { return ExceptionFlag; }

		internal override void Write(FileImage output, bool fatFormat) 
		{
			base.Write(output,fatFormat);
		}

	}

	/// <summary>
	/// The descriptor for a catch clause (.catch)
	/// </summary>
	public class Catch : HandlerBlock  {

		Class exceptType;

		/// <summary>
		/// Create a new catch clause
		/// </summary>
		/// <param name="except">the exception to be caught</param>
		/// <param name="handlerStart">start of the handler code</param>
		/// <param name="handlerEnd">end of the handler code</param>
		public Catch(Class except, CILLabel handlerStart, CILLabel handlerEnd) 
			: base(handlerStart,handlerEnd) 
		{
			exceptType = except;
		}

		internal override void Write(FileImage output, bool fatFormat) 
		{
			base.Write(output,fatFormat);
			output.Write(exceptType.Token());
		}
	}

	/// <summary>
	/// The descriptor for a filter clause (.filter)
	/// </summary>
	public class Filter : HandlerBlock  {

		CILLabel filterLabel;

		/// <summary>
		/// Create a new filter clause
		/// </summary>
		/// <param name="filterLabel">the label where the filter code starts</param>
		/// <param name="handlerStart">the start of the handler code</param>
		/// <param name="handlerEnd">the end of the handler code</param>
		public Filter(CILLabel filterLabel, CILLabel handlerStart, 
				CILLabel handlerEnd) : base(handlerStart,handlerEnd) 
				{
			this.filterLabel = filterLabel;
		}

		internal override short GetFlag() 
		{
			return FilterFlag; 
		}

		internal override void Write(FileImage output, bool fatFormat) 
		{
			base.Write(output,fatFormat);
			output.Write(filterLabel.GetLabelOffset());
		}

	}

	/// <summary>
	/// Descriptor for a finally block (.finally)
	/// </summary>
	public class Finally : HandlerBlock  {

		/// <summary>
		/// Create a new finally clause
		/// </summary>
		/// <param name="finallyStart">start of finally code</param>
		/// <param name="finallyEnd">end of finally code</param>
		public Finally(CILLabel finallyStart, CILLabel finallyEnd)
			: base(finallyStart,finallyEnd) { }

		internal override short GetFlag() 
		{
			return FinallyFlag; 
		}

		internal override void Write(FileImage output, bool fatFormat) 
		{
			base.Write(output,fatFormat);
			output.Write((int)0);
		}

	}

	/// <summary>
	/// Descriptor for a fault block (.fault)
	/// </summary>
	public class Fault : HandlerBlock  {

		/// <summary>
		/// Create a new fault clause
		/// </summary>
		/// <param name="faultStart">start of the fault code</param>
		/// <param name="faultEnd">end of the fault code</param>
		public Fault(CILLabel faultStart, CILLabel faultEnd)
			: base(faultStart,faultEnd) { }

		internal override short GetFlag() 
		{
			return FaultFlag; 
		}

		internal override void Write(FileImage output, bool fatFormat) 
		{
			base.Write(output,fatFormat);
			output.Write((int)0);

		}
	}

	/**************************************************************************/  
	/// <summary>
	/// Descriptor for the locals for a method
	/// </summary>
	public class LocalSig : Signature {

		private static readonly byte LocalSigByte = 0x7;
		Local[] locals;

		public LocalSig(Local[] locals)         
		{
			this.locals = locals;
			tabIx = MDTable.StandAloneSig;
		}

		internal sealed override void BuildTables(MetaData md) 
		{
			if (done) return;
			MemoryStream sig = new MemoryStream();
			sig.WriteByte(LocalSigByte);
			MetaData.CompressNum((uint)locals.Length,sig);
			for (int i=0; i < locals.Length; i++) {
				((Local)locals[i]).TypeSig(sig);
			}
			sigIx = md.AddToBlobHeap(sig.ToArray());
			done = true;
		}

	}

	/**************************************************************************/  
	/// <summary>
	/// Signature for calli instruction
	/// </summary>
	public class CalliSig : Signature {

		private static readonly byte Sentinel = 0x41;
		CallConv callConv;
		Type returnType;
		Type[] parameters, optParams;
		uint numPars = 0, numOptPars = 0;

		/// <summary>
		/// Create a signature for a calli instruction
		/// </summary>
		/// <param name="cconv">calling conventions</param>
		/// <param name="retType">return type</param>
		/// <param name="pars">parameter types</param>
		public CalliSig(CallConv cconv, Type retType, Type[] pars) 
		{
			tabIx = MDTable.StandAloneSig;
			callConv = cconv;
			returnType = retType;
			parameters = pars;
			if (pars != null) numPars = (uint)pars.Length;
		}

		/// <summary>
		/// Add the optional parameters to a vararg method
		/// This method sets the vararg calling convention
		/// </summary>
		/// <param name="optPars">the optional pars for the vararg call</param>
		public void AddVarArgs(Type[] optPars) 
		{
			optParams = optPars;
			if (optPars != null) numOptPars = (uint)optPars.Length;
			callConv |= CallConv.Vararg;
		}

		/// <summary>
		/// Add extra calling conventions to this callsite signature
		/// </summary>
		/// <param name="cconv"></param>
		public void AddCallingConv(CallConv cconv) 
		{
			callConv |= cconv;
		}

		internal sealed override void BuildTables(MetaData md) 
		{
			if (done) return;
			MemoryStream sig = new MemoryStream();
			sig.WriteByte((byte)callConv);
			MetaData.CompressNum(numPars+numOptPars,sig);
			returnType.TypeSig(sig);
			for (int i=0; i < numPars; i++) {
				parameters[i].TypeSig(sig);
			}
			sigIx = md.AddToBlobHeap(sig.ToArray());
			if (numOptPars > 0) {
				sig.WriteByte(Sentinel);
				for (int i=0; i < numOptPars; i++) {
					optParams[i].TypeSig(sig);
				}
			}
			done = true;
		}

	}

	/**************************************************************************/  
	/// <summary>
	/// Descriptor for a local of a method
	/// </summary>
	public class Local {

		private static readonly byte Pinned = 0x45;
		string name;
		Type type;
		bool pinned = false, byref = false;

		/// <summary>
		/// Create a new local variable 
		/// </summary>
		/// <param name="lName">name of the local variable</param>
		/// <param name="lType">type of the local variable</param>
		public Local(string lName, Type lType) 
		{
			name = lName;
			type = lType;
		}

		/// <summary>
		/// Create a new local variable that is byref and/or pinned
		/// </summary>
		/// <param name="lName">local name</param>
		/// <param name="lType">local type</param>
		/// <param name="byRef">is byref</param>
		/// <param name="isPinned">has pinned attribute</param>
		public Local(string lName, Type lType, bool byRef, bool isPinned)
		{
			name = lName;
			type = lType;
			byref = byRef;
			pinned = isPinned;
		}

		internal void TypeSig(MemoryStream str) 
		{
			if (pinned) str.WriteByte(Pinned);
			type.TypeSig(str);
		}

	}

	/**************************************************************************/  
	/// <summary>
	/// A label in the IL
	/// </summary>
	public class CILLabel {

		CILInstruction branch;
		CILInstruction[] multipleBranches;
		int tide = 0;
		CILInstruction labInstr;
		uint offset = 0;

		public CILLabel (uint offset) 
		{
			this.offset = offset;
		}


		internal CILLabel() 
		{
		}

		internal void AddBranch(CILInstruction instr) 
		{
			if (branch == null) {
				branch = instr;
				return;
			}
			if (multipleBranches == null) {
				multipleBranches = new CILInstruction[2];
			} else if (tide >= multipleBranches.Length) {
				CILInstruction[] tmp = multipleBranches;
				multipleBranches = new CILInstruction[tmp.Length*2];
				for (int i=0; i < tide; i++) {
					multipleBranches[i] = tmp[i];
				}
			}
			multipleBranches[tide++] = instr;
		}

		internal void AddLabelInstr(LabelInstr lInstr) 
		{
			labInstr = lInstr;
		}

		internal uint GetLabelOffset() 
		{
			if (labInstr == null) return 0;
			return labInstr.offset + offset;
		}

	}


}