Advertisement
Guest User

Untitled

a guest
Jan 22nd, 2016
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. So - After looking at the byte code emitted, it *does* work when compiling with optimizations (more importantly, removing useless code which is used by the debugger). After comparing the bytes emitted against [the CIL instruction list](https://en.wikipedia.org/wiki/List_of_CIL_instructions)
  2.  
  3. **In debug mode**
  4.  
  5.     0x00    0x00    NOP
  6.     0x01    0x20    ldc.i4 <int32>  Push num of type int32 onto the stack as int32
  7.     0x02    0xAD    argument for ldc.i4
  8.     0x03    0xDE    argument for ldc.i4
  9.     0x04    0x00    argument for ldc.i4
  10.     0x05    0x00    argument for ldc.i4
  11.     0x06    0x0A    stloc.0 Pop a value from stack into local variable 0
  12.     0x07    0x2B    br.s <int8> Branch to target, short form.
  13.     0x08    0x00    argument for br.s  
  14.     0x09    0x06    ldloc.0 Load local variable 0 onto stack
  15.     0x0A    0x2A    ret
  16.  
  17. Note instruction `0x2B` - which is jumping back to `0x00`. Decompilation of the same method via LINQPad
  18.  
  19.     IL_0000:  nop        
  20.     IL_0001:  ldc.i4      AD DE 00 00
  21.     IL_0006:  stloc.0     // CS$1$0000
  22.     IL_0007:  br.s        IL_0009
  23.     IL_0009:  ldloc.0     // CS$1$0000
  24.     IL_000A:  ret        
  25.  
  26. Here it's branching to `0009`, which is fine (the branch does nothing, essentially).
  27.  
  28. **In release mode**
  29.  
  30.     0x20    ldc.i4
  31.     0xAD    argument for ldc.i4
  32.     0xDE    argument for ldc.i4
  33.     0x00    argument for ldc.i4
  34.     0x00    argument for ldc.i4
  35.     0x2A    ret
  36.  
  37. vs LINQPad decompilation:
  38.  
  39.    IL_0000:  ldc.i4      AD DE 00 00
  40.    IL_0005:  ret        
  41.  
  42. The code *does* work in this case, with a slight change to the end of your method:
  43.  
  44.    var obj = Activator.CreateInstance(type);
  45.    return (R)type.GetMethod(info.Name).Invoke(obj, new object[] { t });
  46.  
  47. instead of
  48.  
  49.    Func<T, R> method = type.GetMethod(info.Name).CreateDelegate(typeof(Func<T, R>)) as Func<T, R>;
  50.    return method(t);
  51.  
  52. Whether this invalid branch target is because it's a debugger helper, or whether branch targets are never returned in `GetILAsByteArray`, I'm not sure. At the very least, trying to re-compile a method compiled in `DEBUG` is probably always going to result in weirdness.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement