about summary refs log tree commit diff stats
diff options
context:
space:
mode:
-rw-r--r--example/unpack_upx.py15
-rw-r--r--miasm/arch/ia32_arch.py33
-rw-r--r--miasm/arch/ia32_reg.py4
-rw-r--r--miasm/arch/ia32_sem.py145
-rw-r--r--miasm/expression/expression.py6
-rw-r--r--miasm/tools/emul_lib/libcodenat.c48
-rw-r--r--miasm/tools/emul_lib/libcodenat.h26
-rw-r--r--miasm/tools/seh_helper.py11
-rw-r--r--miasm/tools/to_c_helper.py31
-rw-r--r--miasm/tools/win_api.py3
10 files changed, 277 insertions, 45 deletions
diff --git a/example/unpack_upx.py b/example/unpack_upx.py
index 17960ea6..34da5ce8 100644
--- a/example/unpack_upx.py
+++ b/example/unpack_upx.py
@@ -27,6 +27,8 @@ init_code_bloc_pool_py()
 

 codenat_tcc_init()

 

+print "start emul..."

+machine = x86_machine()

 

 

 job_done = set()

@@ -34,17 +36,17 @@ symbol_pool = asmbloc.asm_symbol_pool()
 if e.Coffhdr.characteristics & (1<<13):

     # dll

     all_bloc = asmbloc.dis_bloc_all(x86_mn, in_str, decomp_func, job_done, symbol_pool, bloc_wd=2)

+    f_eip = emul_bloc(machine, all_bloc[0])

+    f_eip = emul_bloc(machine, all_bloc[1])

+

     b = all_bloc[1]

 else:

     # binary

     all_bloc = asmbloc.dis_bloc_all(x86_mn, in_str, decomp_func, job_done, symbol_pool, bloc_wd=1)

-    b = all_bloc[0]

-print b

+    f_eip = emul_bloc(machine, all_bloc[0])

 

 

-print "start emul..."

-machine = x86_machine()

-f_eip = emul_bloc(machine, b)

+#f_eip = emul_bloc(machine, b)

 

 decomp_buf_ad_in =  int(machine.pool[esi].arg)

 decomp_buf_ad_out = int( machine.pool[edi].arg)

@@ -273,4 +275,5 @@ print repr(e.SHList)
 e.DirImport.set_rva(s_myimp.addr)

 

 e.Opthdr.AddressOfEntryPoint = e.virt2rva(end_label)

-open('out.bin','w').write(str(e))

+fname = fname.replace('.', '_')

+open(fname+'_unupx.bin','w').write(str(e))

diff --git a/miasm/arch/ia32_arch.py b/miasm/arch/ia32_arch.py
index 2493948e..2fa17942 100644
--- a/miasm/arch/ia32_arch.py
+++ b/miasm/arch/ia32_arch.py
@@ -151,6 +151,7 @@ ft = "ft" # float
 w64= "w64"
 sd = "sd" # single/double
 wd = "wd" # word/dword
+mm = "mm" # word/dword
 
 
 bkf = "breakflow"
@@ -256,7 +257,7 @@ def dict_to_ad(d, modifs = {}, opmode = u32, admode = u32):
     tab32 = {x86_afs.u08:x86_afs.reg_list8, x86_afs.u16:x86_afs.reg_list16, x86_afs.u32:x86_afs.reg_list32,x86_afs.f32:x86_afs.reg_flt, x86_afs.f64:x86_afs.reg_flt}
     tab16 = {x86_afs.u08:x86_afs.reg_list8, x86_afs.u16:x86_afs.reg_list32, x86_afs.u32:x86_afs.reg_list16}
     ad_size = {x86_afs.u08:"byte ptr", x86_afs.u16:"word ptr", x86_afs.u32:"dword ptr", x86_afs.f32:"single ptr", x86_afs.f64:"double ptr"}
-
+    
     if is_reg(d):
         n = [x for x in d if type(x) in [int, long]]
         if len(n)!=1:
@@ -286,6 +287,9 @@ def dict_to_ad(d, modifs = {}, opmode = u32, admode = u32):
         if modifs[sd] is not None:
             t = tab32[size]
             n&=7
+        if modifs[mm] and n>0x7:
+            t = x86_afs.reg_mmx
+            n&=7
 
         try:
             out = t[n]
@@ -550,7 +554,7 @@ class x86allmncs:
     def addop(self, name, opc, afs, rm, modif_desc, prop_dict, sem):
         prop_dict.update(sem)
         modifs = dict([[x, True] for x in modif_desc])
-        base_modif = dict([[x, None] for x in [w8, se, sw, ww, sg, dr, cr, ft, w64, sd, wd, bkf, spf, dtf]])
+        base_modif = dict([[x, None] for x in [w8, se, sw, ww, sg, dr, cr, ft, w64, sd, wd, bkf, spf, dtf, mm]])
         base_modif.update(modifs)
 
         #update with forced properties
@@ -860,7 +864,7 @@ class x86allmncs:
         addop("jmpf",  [0xFF],             d5   , no_rm         , {}                 ,{}                , {bkf:True,dtf:True}         )
 
         addop("lahf",  [0x9F],             noafs, no_rm         , {}                 ,{}                , {},                         )
-        addop("lar",   [0x0F, 0x02],       noafs, no_rm         , {}                 ,{}                , {},                         )
+        addop("lar",   [0x0F, 0x02],       noafs, [rmr]         , {}                 ,{}                , {},                         )
         addop("ldmxcsr",[0x0F, 0xAE],      d2   , no_rm         , {}                 ,{}                , {},                         )
         addop("lds",   [0xC5],             noafs, [rmr]         , {}                 ,{}                , {},                         )
         addop("lss",   [0x0F, 0xB2],       noafs, [rmr]         , {}                 ,{}                , {},                         )
@@ -1262,6 +1266,9 @@ class x86allmncs:
         addop("fxtract",[0xD9, 0xF4],      noafs, no_rm         , {}                 ,{sd:False}        , {},                         )
         addop("fyl2x",  [0xD9, 0xF1],      noafs, no_rm         , {}                 ,{sd:False}        , {},                         )
         addop("fyl2xp1",[0xD9, 0xF9],      noafs, no_rm         , {}                 ,{sd:False}        , {},                         )
+
+        addop("movd",   [0x0F, 0x6e],      noafs, [rmr]         , {sw:(1,4)}         ,{mm:True}         , {sw:False},                         )
+
         pm = self.db_mnemo[0x9c]
         self.pushfw_m = mnemonic(pm.name, pm.opc, pm.afs, pm.rm, pm.modifs, pm.modifs_orig, None)#, pm.sem)
         self.pushfw_m.name = "pushfw"
@@ -1567,6 +1574,8 @@ class x86_mn:
                         reg_cat+=0x10
                     if m.modifs[sg]:
                         reg_cat+=0x20
+                    if m.modifs[mm]:
+                        reg_cat+=0x40
                     mafs = dict(x86mndb.get_afs_re(re+reg_cat))
                     if m.modifs[w8]:
                         mafs[x86_afs.size] = x86_afs.u08
@@ -2331,6 +2340,24 @@ if __name__ == '__main__':
     test_out = []
     log.setLevel(logging.DEBUG)
 
+
+
+    instr = x86mnemo.dis('0f6ec5'.replace(' ', '').decode('hex'))
+    print instr
+    print instr.arg
+    print instr.l
+    print instr.opmode, instr.admode
+
+
+    instr = x86mnemo.dis('0f7ec5'.replace(' ', '').decode('hex'))
+    print instr
+    print instr.arg
+    print instr.l
+    print instr.opmode, instr.admode
+
+
+    fds
+
     instr = x86mnemo.dis('67e1fa'.replace(' ', '').decode('hex'))
     print instr
     print instr.arg
diff --git a/miasm/arch/ia32_reg.py b/miasm/arch/ia32_reg.py
index 2910c328..3129a31e 100644
--- a/miasm/arch/ia32_reg.py
+++ b/miasm/arch/ia32_reg.py
@@ -133,7 +133,9 @@ class afs_desc:
                          self.r_fs,  self.r_gs,   None,       None]
 
         self.reg_flt =  ["st%d"%i for i in range(8)]
-        
+
+        self.reg_mmx =  ["mm%d"%i for i in range(8)]
+
         self.reg_dict = {}
         for i in range(8):
             self.reg_dict[self.reg_list8[i]] = i
diff --git a/miasm/arch/ia32_sem.py b/miasm/arch/ia32_sem.py
index 059661e4..304d4701 100644
--- a/miasm/arch/ia32_sem.py
+++ b/miasm/arch/ia32_sem.py
@@ -93,6 +93,15 @@ reg_cr5 = 'cr5'
 reg_cr6 = 'cr6'
 reg_cr7 = 'cr7'
 
+reg_mm0 = 'mm0'
+reg_mm1 = 'mm1'
+reg_mm2 = 'mm2'
+reg_mm3 = 'mm3'
+reg_mm4 = 'mm4'
+reg_mm5 = 'mm5'
+reg_mm6 = 'mm6'
+reg_mm7 = 'mm7'
+
 
 reg_tsc1 = "tsc1"
 reg_tsc2 = "tsc2"
@@ -209,6 +218,15 @@ cr5 = ExprId(reg_cr5)
 cr6 = ExprId(reg_cr6)
 cr7 = ExprId(reg_cr7)
 
+mm0 = ExprId(reg_mm0, 64)
+mm1 = ExprId(reg_mm1, 64)
+mm2 = ExprId(reg_mm2, 64)
+mm3 = ExprId(reg_mm3, 64)
+mm4 = ExprId(reg_mm4, 64)
+mm5 = ExprId(reg_mm5, 64)
+mm6 = ExprId(reg_mm6, 64)
+mm7 = ExprId(reg_mm7, 64)
+
 
 eflag= ExprId(reg_eflag)
 tmp1= ExprId(reg_tmp1)
@@ -2108,7 +2126,7 @@ def sidt(info, a):
     b = a.arg
     print "DEFAULT SIDT ADDRESS %s!!"%str(a)
     e.append(ExprAff(ExprMem(b, 32), ExprInt32(0xe40007ff)))
-    e.append(ExprAff(ExprMem(ExprOp("+", b, ExprInt32(4)), 32), ExprInt32(0x8245)))
+    e.append(ExprAff(ExprMem(ExprOp("+", b, ExprInt32(4)), 16), ExprInt32(0x8245)))
     return e
 
 
@@ -2132,6 +2150,18 @@ def cmovle(info, a, b):
     e= []
     e.append(ExprAff(a, ExprCond( ExprOp('|', ExprOp('^', nf, of), zf) , b, a)))
     return e
+def cmova(info, a, b):
+    e= []
+    e.append(ExprAff(a, ExprCond( ExprOp('|', cf, zf) , a, b)))
+    return e
+def cmovae(info, a, b):
+    e= []
+    e.append(ExprAff(a, ExprCond( cf , a, b)))
+    return e
+def cmovbe(info, a, b):
+    e= []
+    e.append(ExprAff(a, ExprCond( ExprOp('|', cf, zf) , b, a)))
+    return e
 def cmovo(info, a, b):
     e= []
     e.append(ExprAff(a, ExprCond(of , b, a)))
@@ -2201,38 +2231,60 @@ def cpuid(info):
     e.append(ExprAff(edx, ExprOp('cpuid', eax, ExprInt32(3))))
     return e
 
+def bittest_get(a, b):
+    if isinstance(a, ExprId):
+        off_bit = ExprOp('&', b, ExprInt_from(a, a.get_size() - 1))
+        d = a
+        #d = ExprOp('>>', a, off_bit)
+    else:
+        off_bit = ExprOp('&', b, ExprInt_from(a, a.get_size() - 1))
+        off_byte = ExprOp("&",
+                          ExprOp('>>', b, ExprInt_from(a, 3)),
+                          ExprOp('!', ExprInt_from(a, a.get_size()/8 -1)))
+
+        d = ExprMem(a.arg+off_byte, a.size)
+        #d = ExprOp('>>', mem, off_bit)
+    return d, off_bit
+
 def bt(info, a, b):
     e= []
-    c= ExprOp('&', b, ExprInt_from(a, b.get_size() - 1))
-    d= ExprOp('>>', a, c)
+    d, off_bit = bittest_get(a, b)
+    d = ExprOp(">>", d, off_bit)
     e.append(ExprAff(cf, ExprOp('&', d, ExprInt_from(a, 1))))
     return e
 
 def btc(info, a, b):
     e= []
-    c= ExprOp('&', b, ExprInt_from(a, b.get_size() - 1))
-    d= ExprOp('>>', a, c)
-    m= ExprOp('<<', ExprInt_from(a, 1), b)
-    e.append(ExprAff(cf, ExprOp('&', d, ExprInt_from(a, 1))))
-    e.append(ExprAff(a, ExprOp('^', a, m)))
+    d, off_bit = bittest_get(a, b)
+    e.append(ExprAff(cf, ExprOp('&',
+                                ExprOp(">>", d, off_bit),
+                                ExprInt_from(a, 1))))
+
+    m = ExprOp('<<', ExprInt_from(a, 1), off_bit)
+    e.append(ExprAff(d, ExprOp('^', d, m)))
+
     return e
 
 def bts(info, a, b):
     e= []
-    c= ExprOp('&', b, ExprInt_from(a, b.get_size() - 1))
-    d= ExprOp('>>', a, c)
-    m= ExprOp('<<', ExprInt_from(a, 1), b)
-    e.append(ExprAff(cf, ExprOp('&', d, ExprInt_from(a, 1))))
-    e.append(ExprAff(a, ExprOp('|', a, m)))
+    d, off_bit = bittest_get(a, b)
+    e.append(ExprAff(cf, ExprOp('&',
+                                ExprOp(">>", d, off_bit),
+                                ExprInt_from(a, 1))))
+    m = ExprOp('<<', ExprInt_from(a, 1), off_bit)
+    e.append(ExprAff(d, ExprOp('|', d, m)))
+
     return e
 
 def btr(info, a, b):
     e= []
-    c= ExprOp('&', b, ExprInt_from(a, b.get_size() - 1))
-    d= ExprOp('>>', a, c)
-    m= ~ExprOp('<<', ExprInt_from(a, 1), b)
-    e.append(ExprAff(cf, ExprOp('&', d, ExprInt_from(a, 1))))
-    e.append(ExprAff(a, ExprOp('&', a, m)))
+    d, off_bit = bittest_get(a, b)
+    e.append(ExprAff(cf, ExprOp('&',
+                                ExprOp(">>", d, off_bit),
+                                ExprInt_from(a, 1))))
+    m = ~ExprOp('<<', ExprInt_from(a, 1), off_bit)
+    e.append(ExprAff(d, ExprOp('&', d, m)))
+
     return e
 
 
@@ -2299,6 +2351,40 @@ def sahf(info):
     e.append(ExprAff(zf, ExprSlice(tmp, 6, 7)))
     e.append(ExprAff(nf, ExprSlice(tmp, 7, 8)))
     return e
+
+def lar(info, a, b):
+    e = []
+    e.append(ExprAff(a, ExprOp('access_segment', b)))
+    e.append(ExprAff(zf, ExprOp('access_segment_ok', b)))
+    return e
+
+def lsl(info, a, b):
+    e = []
+    e.append(ExprAff(a, ExprOp('load_segment_limit', b)))
+    e.append(ExprAff(zf, ExprOp('load_segment_limit_ok', b)))
+    return e
+
+def fclex(info):
+    # XXX TODO
+    return []
+
+def fnclex(info):
+    # XXX TODO
+    return []
+
+def l_str(info, a):
+    e = []
+    e.append(ExprAff(a, ExprOp('load_tr_segment_selector', ExprInt32(0))))
+    return e
+
+def movd(info, a, b):
+    e = []
+    if a.get_size() == 64:
+        e.append(ExprAff(a, ExprCompose([(ExprInt32(0), 32, 64), (b, 0, 32)])))
+    else:
+        e.append(ExprAff(a, b[0:32]))
+    return e
+
 mnemo_func = {'mov': mov,
               'xchg': xchg,
               'movzx': movzx,
@@ -2478,6 +2564,9 @@ mnemo_func = {'mov': mov,
               'cmovge':cmovge,
               'cmovnl':cmovge,
               'cmovl':cmovl,
+              'cmova':cmova,
+              'cmovae':cmovae,
+              'cmovbe':cmovbe,
               'cmovnge':cmovl,
               'cmovle':cmovle,
               'cmovng':cmovle,
@@ -2511,6 +2600,12 @@ mnemo_func = {'mov': mov,
               "lss": lss,
               "lahf": lahf,
               "sahf": sahf,
+              "lar":lar,
+              "lsl":lsl,
+              "fclex":fclex,
+              "fnclex":fnclex,
+              "str":l_str,
+              "movd":movd,
               }
 
 
@@ -2584,6 +2679,15 @@ class ia32_rexpr:
     r_cr6 = cr6
     r_cr7 = cr7
 
+    r_mm0 = mm0
+    r_mm1 = mm1
+    r_mm2 = mm2
+    r_mm3 = mm3
+    r_mm4 = mm4
+    r_mm5 = mm5
+    r_mm6 = mm6
+    r_mm7 = mm7
+
     r_ax = r_eax[:16]
     r_cx = r_ecx[:16]
     r_dx = r_edx[:16]
@@ -2622,6 +2726,8 @@ class ia32_rexpr:
     reg_listdr=[r_dr0, r_dr1, r_dr2, r_dr3, r_dr4, r_dr5, r_dr6, r_dr7]
     reg_listcr=[r_cr0, r_cr1, r_cr2, r_cr3, r_cr4, r_cr5, r_cr6, r_cr7]
 
+    reg_mmx=   [r_mm0, r_mm1, r_mm2, r_mm3, r_mm4, r_mm5, r_mm6, r_mm7]
+
     reg_flt = [float_st0, float_st1, float_st2, float_st3, float_st4, float_st5, float_st6, float_st7]
 
     reg_dict = {}
@@ -2677,6 +2783,9 @@ def dict_to_Expr(d, modifs = {}, opmode = u32, admode = u32, segm_to_do = set())
         if modifs[sd] is not None:
             t = tab32[size]
             n&=7
+        if modifs[mm] and n>0x7:
+            t = ia32_rexpr.reg_mmx
+            n&=7
 
         out = t[n]
     elif is_imm(d):
diff --git a/miasm/expression/expression.py b/miasm/expression/expression.py
index 5ec5f4f0..8763ab24 100644
--- a/miasm/expression/expression.py
+++ b/miasm/expression/expression.py
@@ -456,6 +456,12 @@ class ExprOp(Expr):
                 return "%s(%s)"%(self.op, self.args[0].toC())
             elif self.op in ["-"]:
                 return "%s(%s)"%(self.op, self.args[0].toC())
+            elif self.op in ["access_segment", "access_segment_ok"]:
+                return "%s(%s)"%(self.op, self.args[0].toC())
+            elif self.op in ["load_segment_limit", "load_segment_limit_ok"]:
+                return "%s(%s)"%(self.op, self.args[0].toC())
+            elif self.op in ["load_tr_segment_selector"]:
+                return "%s(%s)"%(self.op, self.args[0].toC())
             else:
                 print self.op
                 raise ValueError('unknown op!!', str(self.op))
diff --git a/miasm/tools/emul_lib/libcodenat.c b/miasm/tools/emul_lib/libcodenat.c
index ba491e16..2030c66a 100644
--- a/miasm/tools/emul_lib/libcodenat.c
+++ b/miasm/tools/emul_lib/libcodenat.c
@@ -781,11 +781,26 @@ int rcl_rez_op(unsigned int size, unsigned int a, unsigned int b, unsigned int c
 {
     uint64_t tmp;
 
-    tmp = (cf << size) | a;
 
     size++;
     b %= size;
 
+    if (b == 0) {
+	    switch(size){
+		    case 8+1:
+			    return a&0xff;
+		    case 16+1:
+			    return a&0xffff;
+		    case 32+1:
+			    return a&0xffffffff;
+		    default:
+			    fprintf(stderr, "inv size in rclleft %d\n", size);
+			    exit(0);
+	    }
+    }
+
+    tmp = (a<<1) | cf;
+    b -=1;
     switch(size){
 	    case 8+1:
 		    tmp = (tmp << b) | ((tmp&0x1FF) >> (size-b));
@@ -1567,7 +1582,6 @@ void _vm_init_regs()
 }
 
 
-
 unsigned int _get_memory_page_max_address_py(void)
 {
     unsigned int ret;
@@ -1589,7 +1603,37 @@ unsigned int _get_memory_page_from_min_ad_py(unsigned int size)
     return ret;
 }
 
+unsigned int access_segment(unsigned int d)
+{
+	// XXX TODO
+	printf("access segment %X\n", d);
+	return 0;
+}
+unsigned int access_segment_ok(unsigned int d)
+{
+	// XXX TODO
+	printf("access segment ok %X\n", d);
+	return 0;
+}
 
+unsigned int load_segment_limit(unsigned int d)
+{
+	// XXX TODO
+	printf("load segment limit %X\n", d);
+	return 0;
+}
+unsigned int load_segment_limit_ok(unsigned int d)
+{
+	// XXX TODO
+	printf("load segment limit ok %X\n", d);
+	return 0;
+}
+
+unsigned int load_tr_segment_selector(unsigned int d)
+{
+	// XXX TODO
+	return 0;
+}
 
 
 //#include "libcodenat_interface.c"
diff --git a/miasm/tools/emul_lib/libcodenat.h b/miasm/tools/emul_lib/libcodenat.h
index d0f4930a..b7c0360b 100644
--- a/miasm/tools/emul_lib/libcodenat.h
+++ b/miasm/tools/emul_lib/libcodenat.h
@@ -236,6 +236,25 @@ typedef struct {
 	uint64_t pfmem64_6;
 	uint64_t pfmem64_7;
 
+
+	uint64_t mm0;
+	uint64_t mm1;
+	uint64_t mm2;
+	uint64_t mm3;
+	uint64_t mm4;
+	uint64_t mm5;
+	uint64_t mm6;
+	uint64_t mm7;
+
+	uint64_t mm0_new;
+	uint64_t mm1_new;
+	uint64_t mm2_new;
+	uint64_t mm3_new;
+	uint64_t mm4_new;
+	uint64_t mm5_new;
+	uint64_t mm6_new;
+	uint64_t mm7_new;
+
 	uint32_t segm_base[0x10000];
 
 }vm_cpu_t;
@@ -514,6 +533,13 @@ double fadd(double a, double b);
 unsigned int double_to_mem_32(double d);
 uint64_t double_to_mem_64(double d);
 
+unsigned int access_segment(unsigned int d);
+unsigned int access_segment_ok(unsigned int d);
+
+unsigned int load_segment_limit(unsigned int d);
+unsigned int load_segment_limit_ok(unsigned int d);
+
+unsigned int load_tr_segment_selector(unsigned int d);
 
 #define shift_right_arith_08(a, b)\
 	((((char)(a)) >> ((int)(b)&0x1f))&0xff)
diff --git a/miasm/tools/seh_helper.py b/miasm/tools/seh_helper.py
index efdd7191..2ca499f2 100644
--- a/miasm/tools/seh_helper.py
+++ b/miasm/tools/seh_helper.py
@@ -297,10 +297,12 @@ def create_modules_chain(modules_name):
         bpath = fname.replace('/', '\\')
         bname = os.path.split(fname)[1].lower()
         bname = "\x00".join(bname)+"\x00"
-        print "add module", repr(bname), repr(bpath)
+        #print "add module", repr(bname), repr(bpath)
         #print hex(InInitializationOrderModuleList_address+i*0x1000)
         if e == None:
             e = pe_init.PE(open(fname, 'rb').read())
+        print "add module", hex(e.NThdr.ImageBase), repr(bname)
+
         modules_info[bname] = addr, e
 
         m_o = ""
@@ -361,7 +363,7 @@ def fix_InLoadOrderModuleList(module_info):
         e, bname, addr = olist[i]
         p_e, p_bname, p_addr = olist[(i-1)%len(olist)]
         n_e, n_bname, n_addr = olist[(i+1)%len(olist)]
-        vm_set_mem(addr+0, pdw(p_addr)+pdw(n_addr))
+        vm_set_mem(addr+0, pdw(n_addr)+pdw(p_addr))
 
 
 
@@ -397,7 +399,7 @@ def fix_InInitializationOrderModuleList(module_info):
         e, bname, addr = olist[i]
         p_e, p_bname, p_addr = olist[(i-1)%len(olist)]
         n_e, n_bname, n_addr = olist[(i+1)%len(olist)]
-        vm_set_mem(addr+0x10, pdw(p_addr)+pdw(n_addr))
+        vm_set_mem(addr+0x10, pdw(n_addr+0x10)+pdw(p_addr+0x10))
 
 
 def add_process_env():
@@ -478,11 +480,12 @@ def build_fake_InLoadOrderModuleList(modules_name):
             fname, e = m, None
         bname = os.path.split(fname)[1].lower()
         bname = "\x00".join(bname)+"\x00"
-        print "add module", repr(bname)
         print hex(InLoadOrderModuleList_address+i*0x1000)
         if e == None:
             e = pe_init.PE(open(fname, 'rb').read())
 
+        print "add module", hex(e.NThdr.ImageBase), repr(bname)
+
         next_ad = InLoadOrderModuleList_address + (i+1)*0x1000
         if i == len(modules_name) -1:
             next_ad = InLoadOrderModuleList_address
diff --git a/miasm/tools/to_c_helper.py b/miasm/tools/to_c_helper.py
index d8d77db1..bbfe9bde 100644
--- a/miasm/tools/to_c_helper.py
+++ b/miasm/tools/to_c_helper.py
@@ -210,6 +210,15 @@ my_C_id = [
     pfmem64_6,
     pfmem64_7,
 
+    mm0,
+    mm1,
+    mm2,
+    mm3,
+    mm4,
+    mm5,
+    mm6,
+    mm7,
+
     ]
 
 float_id_e = [
@@ -1163,11 +1172,8 @@ def load_pe_in_vm(fname_in, options, all_imp_dll = None, **kargs):
     from miasm.tools import pe_helper
     from miasm.tools import codenat
 
-    parse_resources = True
-    if 'parse_resources' in kargs:
-        parse_resources = kargs['parse_resources']
     e = pe_init.PE(open(fname_in, 'rb').read(),
-                   parse_resources = parse_resources)
+                   parse_resources = options.parse_resources)
 
     vm_init_regs()
     init_memory_page_pool_py()
@@ -1250,19 +1256,25 @@ def load_pe_in_vm(fname_in, options, all_imp_dll = None, **kargs):
     return e, in_str, runtime_dll, segm_to_do, symbol_pool
 
 
-def vm2pe(fname, runtime_dll = None, e_orig = None, max_addr = 1<<64):
+def vm2pe(fname, runtime_dll = None, e_orig = None, max_addr = 1<<64, min_addr = 0x401000, min_section_offset = 0x1000):
     from elfesteem import pe
 
     mye = pe_init.PE()
+    mye.NThdr.ImageBase = e_orig.NThdr.ImageBase
     all_mem = vm_get_all_memory()
-    min_addr = 0x401000
     addrs = all_mem.keys()
     addrs.sort()
     mye.Opthdr.AddressOfEntryPoint  = mye.virt2rva(vm_get_gpreg()['eip'])
+    first = True
     for ad in addrs:
         if not min_addr <= ad < max_addr:
             continue
-        mye.SHList.add_section("%.8X"%ad, addr = ad - mye.NThdr.ImageBase, data = all_mem[ad]['data'])
+        if first:
+            mye.SHList.add_section("%.8X"%ad, addr = ad - mye.NThdr.ImageBase, data = all_mem[ad]['data'],
+                                   offset = min_section_offset)
+        else:
+            mye.SHList.add_section("%.8X"%ad, addr = ad - mye.NThdr.ImageBase, data = all_mem[ad]['data'])
+        first = False
 
     if runtime_dll:
         new_dll = runtime_dll.gen_new_lib(mye)
@@ -1271,15 +1283,14 @@ def vm2pe(fname, runtime_dll = None, e_orig = None, max_addr = 1<<64):
 
     s_imp = mye.SHList.add_section("import", rawsize = len(mye.DirImport))
     mye.DirImport.set_rva(s_imp.addr)
-
+    print repr(mye.SHList)
     if e_orig:
         # resource
         xx = str(mye)
         mye.content = xx
-        ad = e_orig.rva2virt(e_orig.NThdr.optentries[pe.DIRECTORY_ENTRY_RESOURCE].rva)
+        ad = e_orig.NThdr.optentries[pe.DIRECTORY_ENTRY_RESOURCE].rva
         print 'dirres', hex(ad)
         if ad != 0:
-            ad = mye.virt2rva(ad)
             mye.NThdr.optentries[pe.DIRECTORY_ENTRY_RESOURCE].rva = ad
             mye.DirRes = pe.DirRes.unpack(xx,ad,mye)
             #print repr(mye.DirRes)
diff --git a/miasm/tools/win_api.py b/miasm/tools/win_api.py
index 741f1c7f..8eb62e95 100644
--- a/miasm/tools/win_api.py
+++ b/miasm/tools/win_api.py
@@ -1171,7 +1171,7 @@ def kernel32_GetCommandLineA():
     print whoami(), hex(ret_ad)
 
     s = winobjs.module_path
-
+    s = '"%s"'%s
     alloc_addr = get_next_alloc_addr(0x1000)
     vm_add_memory_page(alloc_addr, PAGE_READ|PAGE_WRITE, s)
 
@@ -1963,6 +1963,7 @@ def my_GetEnvironmentVariable(funcname, get_str, set_str, mylen):
     s = get_str(lpname)
     if get_str == get_str_unic:
         s = s[::2]
+    print 'variable', repr(s)
     if s in winobjs.env_variables:
         v = set_str(winobjs.env_variables[s])
     else: