IKVM11  11
Java SE 11 Virtual Machine for .NET
Loading...
Searching...
No Matches
LocalVarInfo.cs
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2010 Jeroen Frijters
3
4 This software is provided 'as-is', without any express or implied
5 warranty. In no event will the authors be held liable for any damages
6 arising from the use of this software.
7
8 Permission is granted to anyone to use this software for any purpose,
9 including commercial applications, and to alter it and redistribute it
10 freely, subject to the following restrictions:
11
12 1. The origin of this software must not be misrepresented; you must not
13 claim that you wrote the original software. If you use this software
14 in a product, an acknowledgment in the product documentation would be
15 appreciated but is not required.
16 2. Altered source versions must be plainly marked as such, and must not be
17 misrepresented as being the original software.
18 3. This notice may not be removed or altered from any source distribution.
19
20 Jeroen Frijters
21 jeroen@frijters.net
22
23*/
24using System;
25using System.Collections.Generic;
26using System.Diagnostics;
27using System.Text;
28
29using InstructionFlags = IKVM.Runtime.ClassFile.Method.InstructionFlags;
30
31namespace IKVM.Runtime
32{
33
35 {
36
37 readonly LocalVar[/*instructionIndex*/] localVars;
38 readonly LocalVar[/*instructionIndex*/][/*localIndex*/] invokespecialLocalVars;
39 readonly LocalVar[/*index*/] allLocalVars;
40
50 internal LocalVarInfo(CodeInfo ma, ClassFile classFile, ClassFile.Method method, UntangledExceptionTable exceptions, RuntimeJavaMethod mw, RuntimeClassLoader classLoader)
51 {
52 var localStoreReaders = FindLocalVariables(ma, mw, classFile, method);
53
54 // now that we've done the code flow analysis, we can do a liveness analysis on the local variables
55 var instructions = method.Instructions;
56 var localByStoreSite = new Dictionary<long, LocalVar>();
57 var locals = new List<LocalVar>();
58
59 for (int i = 0; i < localStoreReaders.Length; i++)
60 if (localStoreReaders[i] != null)
61 VisitLocalLoads(classLoader.Context, ma, method, locals, localByStoreSite, localStoreReaders[i], i, classLoader.EmitSymbols);
62
63 var forwarders = new Dictionary<LocalVar, LocalVar>();
64 if (classLoader.EmitSymbols)
65 {
66 var flags = MethodAnalyzer.ComputePartialReachability(ma, method.Instructions, exceptions, 0, false);
67
68 // if we're emitting debug info, we need to keep dead stores as well...
69 for (int i = 0; i < instructions.Length; i++)
70 {
71 if ((flags[i] & InstructionFlags.Reachable) != 0 && IsStoreLocal(instructions[i].NormalizedOpCode))
72 {
73 if (localByStoreSite.ContainsKey(MakeKey(i, instructions[i].NormalizedArg1)) == false)
74 {
75 var v = new LocalVar();
76 v.local = instructions[i].NormalizedArg1;
77 v.type = ma.GetStackTypeWrapper(i, 0);
78 FindLvtEntry(v, method, i);
79 locals.Add(v);
80 localByStoreSite.Add(MakeKey(i, v.local), v);
81 }
82 }
83 }
84
85 // to make the debugging experience better, we have to trust the
86 // LocalVariableTable (unless it's clearly bogus) and merge locals
87 // together that are the same according to the LVT
88 for (int i = 0; i < locals.Count - 1; i++)
89 {
90 for (int j = i + 1; j < locals.Count; j++)
91 {
92 var v1 = locals[i];
93 var v2 = locals[j];
94
95 if (v1.name != null && v1.name == v2.name && v1.start_pc == v2.start_pc && v1.end_pc == v2.end_pc)
96 {
97 // we can only merge if the resulting type is valid (this protects against incorrect
98 // LVT data, but is also needed for constructors, where the uninitialized this is a different
99 // type from the initialized this)
100 var tw = InstructionState.FindCommonBaseType(classLoader.Context, v1.type, v2.type);
101 if (tw != classLoader.Context.VerifierJavaTypeFactory.Invalid)
102 {
103 v1.isArg |= v2.isArg;
104 v1.type = tw;
105 forwarders.Add(v2, v1);
106 locals.RemoveAt(j);
107 j--;
108 }
109 }
110 }
111 }
112 }
113 else
114 {
115 for (int i = 0; i < locals.Count - 1; i++)
116 {
117 for (int j = i + 1; j < locals.Count; j++)
118 {
119 var v1 = locals[i];
120 var v2 = locals[j];
121
122 // if the two locals are the same, we merge them, this is a small
123 // optimization, it should *not* be required for correctness.
124 if (v1.local == v2.local && v1.type == v2.type)
125 {
126 v1.isArg |= v2.isArg;
127 forwarders.Add(v2, v1);
128 locals.RemoveAt(j);
129 j--;
130 }
131 }
132 }
133 }
134
135 invokespecialLocalVars = new LocalVar[instructions.Length][];
136 localVars = new LocalVar[instructions.Length];
137 for (int i = 0; i < localVars.Length; i++)
138 {
139 LocalVar v = null;
140 if (localStoreReaders[i] != null)
141 {
142 Debug.Assert(IsLoadLocal(instructions[i].NormalizedOpCode));
143
144 // lame way to look up the local variable for a load
145 // (by indirecting through a corresponding store)
146 foreach (int store in localStoreReaders[i].Keys)
147 {
148 v = localByStoreSite[MakeKey(store, instructions[i].NormalizedArg1)];
149 break;
150 }
151 }
152 else
153 {
154 if (instructions[i].NormalizedOpCode == NormalizedByteCode.__invokespecial || instructions[i].NormalizedOpCode == NormalizedByteCode.__dynamic_invokespecial)
155 {
156 invokespecialLocalVars[i] = new LocalVar[method.MaxLocals];
157 for (int j = 0; j < invokespecialLocalVars[i].Length; j++)
158 localByStoreSite.TryGetValue(MakeKey(i, j), out invokespecialLocalVars[i][j]);
159 }
160 else
161 {
162 localByStoreSite.TryGetValue(MakeKey(i, instructions[i].NormalizedArg1), out v);
163 }
164 }
165
166 if (v != null)
167 {
168 if (forwarders.TryGetValue(v, out var fwd))
169 v = fwd;
170
171 localVars[i] = v;
172 }
173 }
174
175 allLocalVars = locals.ToArray();
176 }
177
178 static void FindLvtEntry(LocalVar lv, ClassFile.Method method, int instructionIndex)
179 {
180 var lvt = method.LocalVariableTableAttribute;
181 if (lvt != null)
182 {
183 var pc = method.Instructions[instructionIndex].PC;
184 var nextPC = method.Instructions[instructionIndex + 1].PC;
185 var isStore = IsStoreLocal(method.Instructions[instructionIndex].NormalizedOpCode);
186
187 foreach (var e in lvt)
188 {
189 // TODO validate the contents of the LVT entry
190 if (e.index == lv.local && (e.start_pc <= pc || (e.start_pc == nextPC && isStore)) && e.start_pc + e.length > pc)
191 {
192 lv.name = e.name;
193 lv.start_pc = e.start_pc;
194 lv.end_pc = e.start_pc + e.length;
195 break;
196 }
197 }
198 }
199 }
200
201 // NOTE for dead stores, this returns null
202 internal LocalVar GetLocalVar(int instructionIndex)
203 {
204 return localVars[instructionIndex];
205 }
206
207 internal LocalVar[] GetLocalVarsForInvokeSpecial(int instructionIndex)
208 {
209 return invokespecialLocalVars[instructionIndex];
210 }
211
212 internal LocalVar[] GetAllLocalVars()
213 {
214 return allLocalVars;
215 }
216
218 {
219 return bc is
220 NormalizedByteCode.__aload or
221 NormalizedByteCode.__iload or
222 NormalizedByteCode.__lload or
223 NormalizedByteCode.__fload or
224 NormalizedByteCode.__dload or
225 NormalizedByteCode.__iinc or
226 NormalizedByteCode.__ret;
227 }
228
230 {
231 return bc is
232 NormalizedByteCode.__astore or
233 NormalizedByteCode.__istore or
234 NormalizedByteCode.__lstore or
235 NormalizedByteCode.__fstore or
236 NormalizedByteCode.__dstore;
237 }
238
240 {
241
242 internal bool changed;
243 internal FindLocalVarStoreSite[] sites;
244
245 internal void Store(int instructionIndex, int localIndex)
246 {
247 if (sites[localIndex].Count == 1 && sites[localIndex][0] == instructionIndex)
248 return;
249
250 sites = (FindLocalVarStoreSite[])sites.Clone();
251 sites[localIndex] = new FindLocalVarStoreSite();
252 sites[localIndex].Add(instructionIndex);
253 }
254
255 internal void Merge(FindLocalVarState state)
256 {
257 if (sites == null)
258 {
259 sites = state.sites;
260 changed = true;
261 }
262 else
263 {
264 var dirty = true;
265 for (int i = 0; i < sites.Length; i++)
266 {
267 for (int j = 0; j < state.sites[i].Count; j++)
268 {
269 if (!sites[i].Contains(state.sites[i][j]))
270 {
271 if (dirty)
272 {
273 dirty = false;
274 sites = (FindLocalVarStoreSite[])sites.Clone();
275 }
276
277 sites[i].Add(state.sites[i][j]);
278 changed = true;
279 }
280 }
281 }
282 }
283 }
284
285 internal FindLocalVarState Copy()
286 {
287 var copy = new FindLocalVarState();
288 copy.sites = sites;
289 return copy;
290 }
291
292 public override string ToString()
293 {
294 var sb = new ValueStringBuilder();
295
296 if (sites != null)
297 {
298 foreach (var site in sites)
299 {
300 sb.Append('[');
301
302 for (int i = 0; i < site.Count; i++)
303 {
304 sb.Append(site[i].ToString());
305 sb.Append(", ");
306 }
307
308 sb.Append(']');
309 }
310 }
311
312 return sb.ToString();
313 }
314 }
315
317 {
318
319 int[] data;
320
321 internal bool Contains(int instructionIndex)
322 {
323 if (data != null)
324 for (int i = 0; i < data.Length; i++)
325 if (data[i] == instructionIndex)
326 return true;
327
328 return false;
329 }
330
331 internal void Add(int instructionIndex)
332 {
333 data = data == null ? [instructionIndex] : [.. data, instructionIndex];
334 }
335
336 internal readonly int this[int index] => data[index];
337
338 internal readonly int Count => data == null ? 0 : data.Length;
339
340 }
341
342 static Dictionary<int, string>[] FindLocalVariables(CodeInfo codeInfo, RuntimeJavaMethod mw, ClassFile classFile, ClassFile.Method method)
343 {
344 var state = new FindLocalVarState[method.Instructions.Length];
345 state[0].changed = true;
346 state[0].sites = new FindLocalVarStoreSite[method.MaxLocals];
347
348 var parameters = mw.GetParameters();
349 int argpos = 0;
350 if (!mw.IsStatic)
351 state[0].sites[argpos++].Add(-1);
352
353 for (int i = 0; i < parameters.Length; i++)
354 {
355 state[0].sites[argpos++].Add(-1);
356 if (parameters[i].IsWidePrimitive)
357 argpos++;
358 }
359
360 return FindLocalVariablesImpl(mw.DeclaringType.Context, codeInfo, classFile, method, state);
361 }
362
363 static Dictionary<int, string>[] FindLocalVariablesImpl(RuntimeContext context, CodeInfo codeInfo, ClassFile classFile, ClassFile.Method method, FindLocalVarState[] state)
364 {
365 var instructions = method.Instructions;
366 var exceptions = method.ExceptionTable;
367 var maxLocals = method.MaxLocals;
368 var localStoreReaders = new Dictionary<int, string>[instructions.Length];
369
370 var done = false;
371 while (!done)
372 {
373 done = true;
374 for (int i = 0; i < instructions.Length; i++)
375 {
376 if (state[i].changed)
377 {
378 done = false;
379 state[i].changed = false;
380
381 var curr = state[i].Copy();
382
383 for (int j = 0; j < exceptions.Length; j++)
384 if (exceptions[j].startIndex <= i && i < exceptions[j].endIndex)
385 state[exceptions[j].handlerIndex].Merge(curr);
386
387 if (IsLoadLocal(instructions[i].NormalizedOpCode) && (instructions[i].NormalizedOpCode != NormalizedByteCode.__aload || !RuntimeVerifierJavaType.IsFaultBlockException(codeInfo.GetRawStackTypeWrapper(i + 1, 0))))
388 {
389 localStoreReaders[i] ??= new Dictionary<int, string>();
390
391 for (int j = 0; j < curr.sites[instructions[i].NormalizedArg1].Count; j++)
392 localStoreReaders[i][curr.sites[instructions[i].NormalizedArg1][j]] = "";
393 }
394
395 if (IsStoreLocal(instructions[i].NormalizedOpCode) && (instructions[i].NormalizedOpCode != NormalizedByteCode.__astore || !RuntimeVerifierJavaType.IsFaultBlockException(codeInfo.GetRawStackTypeWrapper(i, 0))))
396 {
397 curr.Store(i, instructions[i].NormalizedArg1);
398
399 // if this is a store at the end of an exception block,
400 // we need to propagate the new state to the exception handler
401 for (int j = 0; j < exceptions.Length; j++)
402 if (exceptions[j].endIndex == i + 1)
403 state[exceptions[j].handlerIndex].Merge(curr);
404 }
405
406 if (instructions[i].NormalizedOpCode == NormalizedByteCode.__invokespecial)
407 {
408 var cpi = classFile.GetMethodref(instructions[i].Arg1);
409 if (ReferenceEquals(cpi.Name, StringConstants.INIT))
410 {
411 var type = codeInfo.GetRawStackTypeWrapper(i, cpi.GetArgTypes().Length);
412 // after we've invoked the constructor, the uninitialized references are now initialized
413 if (type == context.VerifierJavaTypeFactory.UninitializedThis || RuntimeVerifierJavaType.IsNew(type))
414 for (int j = 0; j < maxLocals; j++)
415 if (codeInfo.GetLocalTypeWrapper(i, j) == type)
416 curr.Store(i, j);
417 }
418 }
419 else if (instructions[i].NormalizedOpCode == NormalizedByteCode.__goto_finally)
420 {
421 int handler = instructions[i].HandlerIndex;
422
423 // Normally a store at the end of a try block doesn't affect the handler block,
424 // but in the case of a finally handler it does, so we need to make sure that
425 // we merge here in case the try block ended with a store.
426 state[handler].Merge(curr);
427
428 // Now we recursively analyse the handler and afterwards merge the endfault locations back to us
429 FindLocalVarState[] handlerState = new FindLocalVarState[instructions.Length];
430 handlerState[handler].Merge(curr);
431 curr = new FindLocalVarState();
432 FindLocalVariablesImpl(context, codeInfo, classFile, method, handlerState);
433
434 // Merge back to the target of our __goto_finally
435 for (int j = 0; j < handlerState.Length; j++)
436 {
437 if (instructions[j].NormalizedOpCode == NormalizedByteCode.__athrow
438 && codeInfo.HasState(j)
439 && RuntimeVerifierJavaType.IsFaultBlockException(codeInfo.GetRawStackTypeWrapper(j, 0))
440 && ((RuntimeVerifierJavaType)codeInfo.GetRawStackTypeWrapper(j, 0)).Index == handler)
441 {
442 curr.Merge(handlerState[j]);
443 }
444 }
445 }
446
447 switch (ByteCodeMetaData.GetFlowControl(instructions[i].NormalizedOpCode))
448 {
449 case ByteCodeFlowControl.Switch:
450 {
451 for (int j = 0; j < instructions[i].SwitchEntryCount; j++)
452 state[instructions[i].GetSwitchTargetIndex(j)].Merge(curr);
453
454 state[instructions[i].DefaultTarget].Merge(curr);
455 break;
456 }
457 case ByteCodeFlowControl.Branch:
458 state[instructions[i].TargetIndex].Merge(curr);
459 break;
460 case ByteCodeFlowControl.CondBranch:
461 state[instructions[i].TargetIndex].Merge(curr);
462 state[i + 1].Merge(curr);
463 break;
464 case ByteCodeFlowControl.Return:
465 case ByteCodeFlowControl.Throw:
466 break;
467 case ByteCodeFlowControl.Next:
468 state[i + 1].Merge(curr);
469 break;
470 default:
471 throw new InvalidOperationException();
472 }
473 }
474 }
475 }
476
477 return localStoreReaders;
478 }
479
480 static void VisitLocalLoads(RuntimeContext context, CodeInfo codeInfo, ClassFile.Method method, List<LocalVar> locals, Dictionary<long, LocalVar> localByStoreSite, Dictionary<int, string> storeSites, int instructionIndex, bool debug)
481 {
482 Debug.Assert(IsLoadLocal(method.Instructions[instructionIndex].NormalizedOpCode));
483
484 LocalVar local = null;
485 var type = context.VerifierJavaTypeFactory.Null;
486 var localIndex = method.Instructions[instructionIndex].NormalizedArg1;
487 var isArg = false;
488 foreach (int store in storeSites.Keys)
489 {
490 if (store == -1)
491 {
492 // it's a method argument, it has no initial store, but the type is simply the parameter type
493 type = InstructionState.FindCommonBaseType(context, type, codeInfo.GetLocalTypeWrapper(0, localIndex));
494 isArg = true;
495 }
496 else
497 {
498 if (method.Instructions[store].NormalizedOpCode == NormalizedByteCode.__invokespecial)
499 {
500 type = InstructionState.FindCommonBaseType(context, type, codeInfo.GetLocalTypeWrapper(store + 1, localIndex));
501 }
502 else if (method.Instructions[store].NormalizedOpCode == NormalizedByteCode.__static_error)
503 {
504 // it's an __invokespecial that turned into a __static_error
505 // (since a __static_error doesn't continue, we don't need to set type)
506 }
507 else
508 {
509 Debug.Assert(IsStoreLocal(method.Instructions[store].NormalizedOpCode));
510 type = InstructionState.FindCommonBaseType(context, type, codeInfo.GetStackTypeWrapper(store, 0));
511 }
512 }
513 // we can't have an invalid type, because that would have failed verification earlier
514 Debug.Assert(type != context.VerifierJavaTypeFactory.Invalid);
515
516 if (localByStoreSite.TryGetValue(MakeKey(store, localIndex), out var l))
517 {
518 if (local == null)
519 {
520 local = l;
521 }
522 else if (local != l)
523 {
524 // If we've already defined a LocalVar and we find another one, then we merge them
525 // together.
526 // This happens for the following code fragment:
527 //
528 // int i = -1;
529 // try { i = 0; for(; ; ) System.out.println(i); } catch(Exception x) {}
530 // try { i = 0; for(; ; ) System.out.println(i); } catch(Exception x) {}
531 // System.out.println(i);
532 //
533 local = MergeLocals(context, locals, localByStoreSite, local, l);
534 }
535 }
536 }
537
538 if (local == null)
539 {
540 local = new LocalVar();
541 local.local = localIndex;
542 local.type = RuntimeVerifierJavaType.IsThis(type) ? ((RuntimeVerifierJavaType)type).UnderlyingType : type;
543 local.isArg = isArg;
544
545 if (debug)
546 FindLvtEntry(local, method, instructionIndex);
547
548 locals.Add(local);
549 }
550 else
551 {
552 local.isArg |= isArg;
553 local.type = InstructionState.FindCommonBaseType(context, local.type, type);
554 Debug.Assert(local.type != context.VerifierJavaTypeFactory.Invalid);
555 }
556
557 foreach (int store in storeSites.Keys)
558 {
559 if (!localByStoreSite.TryGetValue(MakeKey(store, localIndex), out var v))
560 {
561 localByStoreSite[MakeKey(store, localIndex)] = local;
562 }
563 else if (v != local)
564 {
565 local = MergeLocals(context, locals, localByStoreSite, local, v);
566 }
567 }
568 }
569
570 static long MakeKey(int i, int j)
571 {
572 return (((long)(uint)i) << 32) + (uint)j;
573 }
574
575 static LocalVar MergeLocals(RuntimeContext context, List<LocalVar> locals, Dictionary<long, LocalVar> localByStoreSite, LocalVar l1, LocalVar l2)
576 {
577 Debug.Assert(l1 != l2);
578 Debug.Assert(l1.local == l2.local);
579
580 for (int i = 0; i < locals.Count; i++)
581 {
582 if (locals[i] == l2)
583 {
584 locals.RemoveAt(i);
585 i--;
586 }
587 }
588
589 var temp = new Dictionary<long, LocalVar>(localByStoreSite);
590 localByStoreSite.Clear();
591 foreach (var kv in temp)
592 localByStoreSite[kv.Key] = kv.Value == l2 ? l1 : kv.Value;
593
594 l1.isArg |= l2.isArg;
595 l1.type = InstructionState.FindCommonBaseType(context, l1.type, l2.type);
596 Debug.Assert(l1.type != context.VerifierJavaTypeFactory.Invalid);
597
598 return l1;
599 }
600 }
601
602}
IKVM.Runtime.ClassFile.Method.InstructionFlags InstructionFlags
Definition atomic.cs:37
Runtime support for a class loader.
RuntimeContext Context
Gets a reference to the RuntimeContext that this RuntimeClassLoader is hosted within.
Maintains services relevant to an instane of the IKVM runtime.
RuntimeVerifierJavaTypeFactory VerifierJavaTypeFactory
Gets the RuntimeVerifierJavaTypeFactory associated with this instance of the runtime.
static bool IsStoreLocal(NormalizedByteCode bc)
static Dictionary< int, string >[] FindLocalVariables(CodeInfo codeInfo, RuntimeJavaMethod mw, ClassFile classFile, ClassFile.Method method)
static bool IsLoadLocal(NormalizedByteCode bc)
static void VisitLocalLoads(RuntimeContext context, CodeInfo codeInfo, ClassFile.Method method, List< LocalVar > locals, Dictionary< long, LocalVar > localByStoreSite, Dictionary< int, string > storeSites, int instructionIndex, bool debug)
readonly LocalVar[] allLocalVars
static void FindLvtEntry(LocalVar lv, ClassFile.Method method, int instructionIndex)
static long MakeKey(int i, int j)
static Dictionary< int, string >[] FindLocalVariablesImpl(RuntimeContext context, CodeInfo codeInfo, ClassFile classFile, ClassFile.Method method, FindLocalVarState[] state)
static LocalVar MergeLocals(RuntimeContext context, List< LocalVar > locals, Dictionary< long, LocalVar > localByStoreSite, LocalVar l1, LocalVar l2)
readonly LocalVar[] localVars
readonly LocalVar[][] invokespecialLocalVars