summaryrefslogtreecommitdiff
path: root/src/msil/ch/epfl/lamp/compiler/msil/PEType.java
blob: 418c6603b330b3e1a9fdd2a06d1cbe3908ede342 (plain) (blame)
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
/*
 * System.Reflection-like API for access to .NET assemblies (DLL & EXE)
 */


package ch.epfl.lamp.compiler.msil;

import ch.epfl.lamp.compiler.msil.PEFile.Sig;

import ch.epfl.lamp.compiler.msil.util.Table;
import ch.epfl.lamp.compiler.msil.util.Table.*;
import ch.epfl.lamp.compiler.msil.util.Signature;
import ch.epfl.lamp.compiler.msil.util.PECustomMod;

import java.util.ArrayList;

/**
 * Represents a type from a .NET assembly
 *
 * @author Nikolay Mihaylov
 * @version 1.0
 */
final class PEType extends Type implements Signature {

    //##########################################################################

    /** The PEFile that holds the description of the type. */
    final PEFile file;

    /** The number of the row in the TypeDef table defining the type. */
    final int definingRow;

    /** The row of the first method in the MethodDef table. */
    final int methodListBeg;

    /** The row of the last method in the MethodDef table + 1. */
    final int methodListEnd;

    /** @param definingRow - the index in the TypeDef table where
     *  the type description is.
     */
    PEType(PEModule module,
	   int attributes,
	   String fullName,
	   Type declType,
	   int auxAttr,
	   PEFile file,
	   int definingRow)
    {
	super(module, attributes, fullName, null, null, declType, auxAttr);
	this.file = file;
	this.definingRow = definingRow;
	methodListBeg = file.TypeDef(definingRow).MethodList;
	methodListEnd = definingRow < file.TypeDef.rows
	    ? file.TypeDef(definingRow + 1).MethodList
	    : file.MethodDef.rows + 1;
    }

    //##########################################################################
    // lazy type construction methods

    protected void loadBaseType() {
	TypeDef type = file.TypeDef(definingRow);
	baseType = type.Extends == 0 ? null
	    : ((PEModule)Module).getTypeDefOrRef(type.Extends);
    }

    protected void loadFields() {
	// the list of the declared fields starts from the
	// FieldList index in the TypeDef table up to the smaller of the:
	//  - the last row of the FieldDef table
	//  - the start of the next list of fields determined by the
	// FieldList index of the next row in the TypeDef table
	final ArrayList fields = new ArrayList();
	int fieldListBeg = file.TypeDef(definingRow).FieldList;
	int fieldListEnd = file.FieldDef.rows + 1;
	if (definingRow < file.TypeDef.rows)
	    fieldListEnd = file.TypeDef(definingRow + 1).FieldList;

	for (int row = fieldListBeg; row < fieldListEnd; row++) {
	    int frow = file.FieldTrans.rows == 0
		? row : file.FieldTrans(row).Field;
	    int attrs = file.FieldDef(frow).Flags;
	    String name = file.FieldDef.getName();
	    //System.out.println("\t-->Loading field: " + name);
	    Sig sig = file.FieldDef.getSignature();
	    PECustomMod pecmod = sig.decodeFieldType();
	    Object val = null;
	    Table.Constant consts = file.Constant;
	    for (int i = 1; i <= consts.rows; i++) {
		consts.readRow(i);
		int tableId = Table.getTableId(Table._HasConstant,consts.Parent);
		int refRow = consts.Parent >> Table.NoBits[Table._HasConstant];
		if (tableId == Table.FieldDef.ID && refRow == frow)
		    val = consts.getValue();
	    }
	    FieldInfo field = new PEFieldInfo(row, name, attrs, pecmod, val);
	    if (field.Name.equals("value__") && field.IsSpecialName()) {
		    assert underlyingType == null : underlyingType.toString();
		    underlyingType = field.FieldType;
		}
	    fields.add(field);
	}
	this.fields = (FieldInfo[])
	    fields.toArray(FieldInfo.EMPTY_ARRAY);
	fields.clear();
    }

    protected MethodBase[] methoddefs;

    protected MethodInfo getMethod(int n) {
        return (MethodInfo)methoddefs[n - methodListBeg];
    }

    protected void loadMethods() {
	methoddefs = new MethodBase[methodListEnd - methodListBeg];

	final ArrayList methods = new ArrayList();
	final ArrayList constrs = new ArrayList();
	PEModule pemodule = (PEModule) Module;
	for (int row = methodListBeg; row < methodListEnd; row++) {
	    int mrow = file.MethodTrans.rows == 0
		? row : file.MethodTrans(row).Method;
	    int attrs = file.MethodDef(mrow).Flags;
	    String name = file.MethodDef.getName();
	    Sig sig = file.MethodDef.getSignature();
            /* we're about to parse a MethodDefSig, defined in Sec. 23.2.1 of Partition II ()  */

	    int callConv = sig.readByte();
            // TODO decode HASTHIS from high byte of calling convention
            // TODO decode EXPLICITTHIS from high byte of calling convention
            // TODO handle VARARG calling convention (not CLS but may show up )
            if((callConv & 0x1F) == Signature.GENERIC) {
                int genParamCount = sig.decodeInt();
                /* genParamCount is ignored because the method's type params will be obtained below
                (see: file.GenericParam.getMVarIdxes(row) ) */
            }
	    int paramCount = sig.decodeInt();
	    Type retType = sig.decodeRetType();
	    Type[] paramType = new Type[paramCount];
	    for (int i = 0; i < paramCount; i++)
		paramType[i] = sig.decodeParamType();

	    ParameterInfo[] params = new ParameterInfo[paramCount];
	    int paramListBeg = file.MethodDef.ParamList;
            int paramListEnd = paramListBeg + paramCount;
            if (paramListEnd > file.ParamDef.rows) {
                /* don't try to read param names past ParamDef's row count
                   Some assembly-writers don't bother to give names for all params. */
                paramListEnd = file.ParamDef.rows + 1;
	    }
	    for (int i = paramListBeg; i < paramListEnd; i++) {
		int pattr = file.ParamDef(i).Flags;
		String paramName = file.ParamDef.getName();
		int seq = file.ParamDef.Sequence;
		if (seq == 0) {
		    //System.out.println("Retval attributes 0x" +
		    //		       PEFile.short2hex(pattr));
		} else {
		    params[seq - 1] = new ParameterInfo(paramName, paramType[seq - 1], pattr, seq - 1);
		}
	    }
	    for (int i = 0; i < params.length; i++) {
		if (params[i] == null)
		    params[i] = new ParameterInfo(null, paramType[i], 0, 0);
	    }
	    MethodBase method = null;
	    if ((attrs & MethodAttributes.SpecialName) != 0
		&& (attrs & MethodAttributes.RTSpecialName) != 0
		&& (name.equals(ConstructorInfo.CTOR)
		    || name.equals(ConstructorInfo.CCTOR)))
            {
		method = new PEConstructorInfo(row, attrs, params);
            }
            else {
		method = new PEMethodInfo(row, name, attrs, retType, params);
                int[] mvarIdxes = file.GenericParam.getMVarIdxes(row);
                // if(mvarIdxes.length > 0) { System.out.println("Method: " + method); }
                for(int i = 0; i < mvarIdxes.length; i++) {
                    GenericParamAndConstraints mvarAndConstraints = pemodule.getTypeConstraints(mvarIdxes[i]);
                    // add mvarAndConstraints as i-th MVar in method
                    ((PEMethodInfo)method).addMVar(mvarAndConstraints);
                }
            }
	    (method.IsConstructor() ? constrs : methods).add(method);
	    methoddefs[row - methodListBeg] = method;
	}

	this.constructors = (ConstructorInfo[])
	    constrs.toArray(ConstructorInfo.EMPTY_ARRAY);
	this.methods = (MethodInfo[])
	    methods.toArray(MethodInfo.EMPTY_ARRAY);
	constrs.clear(); methods.clear();
    }

    protected void loadProperties() {
	final PropertyMap pmap = file.PropertyMap;
	if (pmap == null) {
	    properties = PropertyInfo.EMPTY_ARRAY;
	    return;
	}

        final PropertyDef pdef = file.PropertyDef;
        int propListBeg =  -1;
        int propListEnd = pdef.rows + 1;
	for (int i = 1; i <= pmap.rows; i++) {
	    pmap.readRow(i);
	    if (pmap.Parent == this.definingRow) {
                propListBeg = pmap.PropertyList;
                if (i < pmap.rows) {
                    pmap.readRow(i + 1);
                    propListEnd = pmap.PropertyList;
                }
                break;
            }
        }
	if (propListBeg < 0) {
	    properties = PropertyInfo.EMPTY_ARRAY;
	    return;
	}

	final ArrayList properties = new ArrayList();
        for (int i = propListBeg; i < propListEnd; i++) {
            pdef.readRow(i);
            Sig sig = pdef.getSignature();
            int b = sig.readByte();
            b &= ~HASTHIS;
            int paramCount = sig.readByte();
            assert b == PROPERTY;
            Type propType = sig.decodeType();
            int index = Table.encodeIndex(i, Table._HasSemantics,
                                          Table.PropertyDef.ID);
            MethodSemantics msem = file.MethodSemantics;
            MethodInfo getter = null, setter = null;
            for (int j = 1; j <= msem.rows; j++) {
                msem.readRow(j);
                if (msem.Association != index)
                    continue;
                if (msem.isGetter())
                    getter = getMethod(msem.Method);
                else if (msem.isSetter())
                    setter = getMethod(msem.Method);
                else
                    System.err.println("PEType.loadProperties(): !?!");
            }
            properties.add
                (new PEPropertyInfo(i, pdef.getName(), (short)pdef.Flags,
                                    propType, getter, setter));
	}
	this.properties = (PropertyInfo[]) properties
	    .toArray(PropertyInfo.EMPTY_ARRAY);
    }

    protected void loadEvents() {
        EventMap emap = file.EventMap;
        if (emap == null) {
            this.events = EventInfo.EMPTY_ARRAY;
            return;
        }

        final EventDef edef = file.EventDef;
        int eventListBeg = -1;
        int eventListEnd = edef.rows + 1;
        for (int i = 1; i <= emap.rows; i++) {
            emap.readRow(i);
            if (emap.Parent == this.definingRow) {
                eventListBeg = emap.EventList;
                if (i < emap.rows) {
                    emap.readRow(i + 1);
                    eventListEnd = emap.EventList;
                }
                break;
            }
        }
        if (eventListBeg < 0) {
            this.events = EventInfo.EMPTY_ARRAY;
            return;
        }

        final ArrayList events = new ArrayList();
        final MethodSemantics msem = file.MethodSemantics;
        for (int i = eventListBeg; i < eventListEnd; i++) {
            edef.readRow(i);
            final Type handler =
                ((PEModule)Module).getTypeDefOrRef(edef.EventType);
            int index =
                Table.encodeIndex(i, Table._HasSemantics, Table.EventDef.ID);
            MethodInfo add = null, remove = null;
            for (int j = 1; j <= msem.rows; j++) {
                msem.readRow(j);
                if (msem.Association != index)
                    continue;
                if (msem.isAddOn())
                    add = getMethod(msem.Method);
                else if (msem.isRemoveOn())
                    remove = getMethod(msem.Method);
                else {
                }
            }
            events.add(new PEEventInfo(i, edef.getName(),
                                       (short)edef.EventFlags,
                                       handler, add, remove));
        }
        this.events = (EventInfo[]) events
            .toArray(EventInfo.EMPTY_ARRAY);
    }

    protected void loadNestedTypes() {
	final ArrayList nested = new ArrayList();
	for (int i = 1; i <= file.NestedClass.rows; i++) {
	    file.NestedClass.readRow(i);
	    if (file.NestedClass.EnclosingClass == this.definingRow)
		nested.add(((PEModule)Module)
			   .getTypeDef(file.NestedClass.NestedClass));
	}
	this.nestedTypes = (Type[]) nested.toArray(Type.EmptyTypes);
    }

    protected void loadInterfaces() {
	// get the interfaces implemented by this class
	interfaces = Type.EmptyTypes;
	int index = file.InterfaceImpl.findType(definingRow);
	if (index > 0) {
	    ArrayList ifaces = new ArrayList();
	    for (int i = index; i <= file.InterfaceImpl.rows; i++) {
		file.InterfaceImpl.readRow(i);
		if (file.InterfaceImpl.Class != definingRow)
		    break;
		ifaces.add(((PEModule)Module)
			   .getTypeDefOrRef(file.InterfaceImpl.Interface));
	    }
	    interfaces = (Type[]) ifaces.toArray(new Type[ifaces.size()]);
	}
    }

    protected void loadCustomAttributes(Type attributeType) {
	initAttributes(this, definingRow, Table.TypeDef.ID, attributeType);
    }

    private void initAttributes(CustomAttributeProvider cap, int definingRow,
                                 int sourceTableId, Type attributeType)
    {
        ((PEModule)this.Module).initAttributes
            (cap, definingRow, sourceTableId, attributeType);
    }

    //##########################################################################

    private class PEFieldInfo extends FieldInfo {
	private final int definingRow;
	public PEFieldInfo(int definingRow, String name,
                       int attrs, PECustomMod pecmod, Object value)
	{
	    super(name, PEType.this, attrs, pecmod, value);
	    this.definingRow = definingRow;
	}
	protected void loadCustomAttributes(Type attributeType) {
	    PEType.this.initAttributes
                (this, definingRow, Table.FieldDef.ID, attributeType);
	}
    }

    private class PEMethodInfo extends MethodInfo {
	private final int definingRow;
	public PEMethodInfo(int row, String name,
                            int attrs, Type retType, ParameterInfo[] params)
	{
	    super(name, PEType.this, attrs, retType, params);
	    this.definingRow = row;
	}
	protected void loadCustomAttributes(Type attributeType) {
	    PEType.this.initAttributes
                (this, definingRow, Table.MethodDef.ID, attributeType);
	}
    }

    private class PEConstructorInfo extends ConstructorInfo {
	private final int definingRow;
	public PEConstructorInfo(int row, int attrs, ParameterInfo[] params) {
	    super(PEType.this, attrs, params);
	    this.definingRow = row;
	}
	protected void loadCustomAttributes(Type attributeType) {
	    PEType.this.initAttributes
                (this, definingRow, Table.MethodDef.ID, attributeType);
	}
    }

    private class PEPropertyInfo extends PropertyInfo {
	private final int definingRow;
	public PEPropertyInfo(int row, String name, short attrs, Type propType,
                              MethodInfo getter, MethodInfo setter)
	{
	    super(name, PEType.this, attrs, propType, getter, setter);
	    this.definingRow = row;
	}
	protected void loadCustomAttributes(Type attributeType) {
	    PEType.this.initAttributes
                (this, definingRow, Table.PropertyDef.ID, attributeType);
	}
    }

    private class PEEventInfo extends EventInfo {
        private final int definingRow;
        public PEEventInfo(int row, String name, short attrs, Type handler,
                           MethodInfo add, MethodInfo remove)
        {
            super(name, PEType.this, attrs, handler, add, remove);
            this.definingRow = row;
        }
        protected void loadCustomAttributes(Type attributeType) {
            PEType.this.initAttributes
                (this, definingRow, Table.EventDef.ID, attributeType);
        }
    }

    //##########################################################################

}  // class PEType