about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorserpilliere <devnull@localhost>2012-02-02 09:29:50 +0100
committerserpilliere <devnull@localhost>2012-02-02 09:29:50 +0100
commit7cd05b55b9171a8e54859cb88a51ab9d24aa4cca (patch)
tree324ce363e8f07a40ecabd3e0404faec21d239719
parent0ec9723acb6cc6cf2401c61110e154fb42c93bea (diff)
downloadmiasm-7cd05b55b9171a8e54859cb88a51ab9d24aa4cca.tar.gz
miasm-7cd05b55b9171a8e54859cb88a51ab9d24aa4cca.zip
fix log; fix winapi
Diffstat (limited to '')
-rw-r--r--miasm/arch/ia32_sem.py34
-rw-r--r--miasm/expression/expression.py7
-rwxr-xr-xmiasm/tools/emul_helper.py3
-rw-r--r--miasm/tools/emul_lib/libcodenat.c7
-rw-r--r--miasm/tools/to_c_helper.py12
-rw-r--r--miasm/tools/win_api.py27
6 files changed, 76 insertions, 14 deletions
diff --git a/miasm/arch/ia32_sem.py b/miasm/arch/ia32_sem.py
index 1808f53d..74237139 100644
--- a/miasm/arch/ia32_sem.py
+++ b/miasm/arch/ia32_sem.py
@@ -846,6 +846,39 @@ def shld_cl(info, a, b):
     e.append(ExprAff(a, c))
     return e
 
+def shld(info, a, b, c):
+    e= []
+    cast_int = tab_uintsize[a.get_size()]
+    cast_intb = tab_uintsize[b.get_size()]
+    shifter = ExprOp('&',c, ExprInt(cast_int(0x1f)))
+    c = ExprOp('|',
+            ExprOp('<<', a, shifter),
+            ExprOp('>>', b, ExprOp('-',
+                                    ExprInt(cast_int(a.get_size())),
+                                    shifter)
+                                    )
+          )
+
+    new_cf = ExprOp('&',
+                    ExprInt(cast_int(1)),
+                    ExprOp('>>',
+                           a,
+                           ExprOp('-',
+                                  ExprInt(cast_intb(a.get_size())),
+                                  shifter
+                                  )
+                           )
+                    )
+    e.append(ExprAff(cf, ExprCond(shifter,
+                                  new_cf,
+                                  cf)
+                     )
+             )
+    e+=update_flag_znp(c)
+    e.append(ExprAff(of, ExprOp('^', get_op_msb(c), new_cf)))
+    e.append(ExprAff(a, c))
+    return e
+
 
 #XXX todo ###
 def cmc(info):
@@ -2003,6 +2036,7 @@ mnemo_func = {'mov': mov,
               'sal':sal,
               'shl':shl,
               'shld_cl':shld_cl,
+              'shld':shld,
               'cmc':cmc,
               'clc':clc,
               'stc':stc,
diff --git a/miasm/expression/expression.py b/miasm/expression/expression.py
index 07cb0e1f..fd560c54 100644
--- a/miasm/expression/expression.py
+++ b/miasm/expression/expression.py
@@ -280,7 +280,7 @@ class ExprAff(Expr):
             raise ValueError("get mod slice not on expraff slice", str(self))
         modified_s = []
         for x in self.src.args:
-            if x.arg.arg != dst or x.start != x.arg.start or x.stop != x.arg.stop:
+            if not isinstance(x.arg, ExprSlice) or x.arg.arg != dst or x.start != x.arg.start or x.stop != x.arg.stop:
                 modified_s.append(x)
 
         return modified_s
@@ -507,12 +507,13 @@ class ExprOp(Expr):
                             self.args[0].toC(),
                             self.args[1].toC())
 
-            elif self.op == 'imul32_lo':
+            elif self.op in ['imul16_lo', 'imul32_lo']:
                 return 'imul_lo_op_%s(%s, %s)' %(
                             self.args[0].get_size(),
                             self.args[0].toC(),
                             self.args[1].toC())
-            elif self.op == 'imul32_hi':
+
+            elif self.op in ['imul16_hi', 'imul32_hi']:
                 return 'imul_hi_op_%s(%s, %s)' %(
                             self.args[0].get_size(),
                             self.args[0].toC(),
diff --git a/miasm/tools/emul_helper.py b/miasm/tools/emul_helper.py
index 1944e873..a36cba85 100755
--- a/miasm/tools/emul_helper.py
+++ b/miasm/tools/emul_helper.py
@@ -564,7 +564,8 @@ def emul_full_expr(e, l, my_eip, env, machine):
             my_edi = machine.eval_expr(machine.pool[edi], {})
             tmp,mem_dst =  emul_expr(machine, e, my_eip)
             
-            machine.eval_instr(mov(ecx, ExprOp('-', my_ecx, ExprInt(uint32(1)))))
+            info = l.opmode, l.admode
+            machine.eval_instr(mov(info, ecx, ExprOp('-', my_ecx, ExprInt(uint32(1)))))
             machine.eval_expr(machine.pool[ecx], {})
 
             if zf_w :
diff --git a/miasm/tools/emul_lib/libcodenat.c b/miasm/tools/emul_lib/libcodenat.c
index 469928d4..7e201b63 100644
--- a/miasm/tools/emul_lib/libcodenat.c
+++ b/miasm/tools/emul_lib/libcodenat.c
@@ -58,6 +58,9 @@ struct memory_page_node *memory_page_pool_tab[MAX_MEMORY_PAGE_POOL_TAB];
 #define MAX(a,b)  (((a)>(b))?(a):(b))
 
 
+//#define DEBUG_MIASM_AUTOMOD_CODE
+
+
 
 
 
@@ -281,9 +284,11 @@ inline void check_write_code_bloc(unsigned int my_size, uint64_t addr)
 		LIST_FOREACH(cbp, &code_bloc_pool, next){
 			if ((cbp->ad_start <= addr + my_size/8) &&
 			    (addr < cbp->ad_stop)){
+#ifdef DEBUG_MIASM_AUTOMOD_CODE
 				fprintf(stderr, "self modifying code %"PRIX64" %.8X",
 				       addr, my_size);
 				fprintf(stderr, " from approx %X\n", vmcpu.eip);
+#endif
 				vmcpu.vm_exception_flags |= EXCEPT_CODE_AUTOMOD;
 				break;
 			}
@@ -305,9 +310,11 @@ void MEM_WRITE(unsigned int my_size, uint64_t addr, unsigned int src)
 		LIST_FOREACH(cbp, &code_bloc_pool, next){
 			if ((cbp->ad_start <= addr + my_size/8) &&
 			    (addr < cbp->ad_stop)){
+#ifdef DEBUG_MIASM_AUTOMOD_CODE
 				fprintf(stderr, "self modifying code %"PRIX64" %.8X",
 				       addr, my_size);
 				fprintf(stderr, " from approx %X\n", vmcpu.eip);
+#endif
 				vmcpu.vm_exception_flags |= EXCEPT_CODE_AUTOMOD;
 				break;
 			}
diff --git a/miasm/tools/to_c_helper.py b/miasm/tools/to_c_helper.py
index f82b83ca..d3394117 100644
--- a/miasm/tools/to_c_helper.py
+++ b/miasm/tools/to_c_helper.py
@@ -21,6 +21,12 @@ from miasm.arch.ia32_arch import *
 from miasm.arch.ia32_sem import *
 import struct
 
+log_to_c_h = logging.getLogger("emu.to_c_helper")
+console_handler = logging.StreamHandler()
+console_handler.setFormatter(logging.Formatter("%(levelname)-5s: %(message)s"))
+log_to_c_h.addHandler(console_handler)
+log_to_c_h.setLevel(logging.WARN)
+
 from elfesteem import *
 
 
@@ -290,8 +296,8 @@ def Exp2C(exprs, l = None, addr2label = None, gen_exception_code = False):
         if len(exs) ==1:
             new_expr += exs
             continue
-        print 'warning: detected multi dst to same id'
-        print l
+        log_to_c_h.debug('warning: detected multi dst to same id')
+        log_to_c_h.debug(str(l))
         new_expr+=exs
         #test if multi slice (for example xchg al, ah)
         if not False in [isinstance(e.src, ExprCompose) for e in exs]:
@@ -1049,7 +1055,7 @@ def updt_pe_from_emul(e):
 
 def updt_automod_code(known_blocs):
     w_ad, w_size = vm_get_last_write_ad(), vm_get_last_write_size()
-    print hex(w_ad), hex(w_size)
+    log_to_c_h.debug("%X %X"%(w_ad, w_size))
     known_blocs = del_bloc_in_range(known_blocs, w_ad, w_ad+w_size/8)
     code_addr = blocs_to_memory_ranges([bn.b for bn in known_blocs.values()])
     merge_memory_ranges(code_addr)
diff --git a/miasm/tools/win_api.py b/miasm/tools/win_api.py
index dfcf2346..f38522fd 100644
--- a/miasm/tools/win_api.py
+++ b/miasm/tools/win_api.py
@@ -149,6 +149,7 @@ class c_winobjs:
 
         self.lastwin32error = 0
         self.mutex = {}
+        self.env_variables = {}
 winobjs = c_winobjs()
 
 
@@ -261,7 +262,7 @@ def kernel32_CreateToolhelp32Snapshot():
     print whoami(), hex(ret_ad), '(', hex(dwflags), hex(th32processid), ')'
     regs = vm_get_gpreg()
     regs['eip'] = ret_ad
-    regs['eax'] = win_api.handle_toolhelpsnapshot
+    regs['eax'] = winobjs.handle_toolhelpsnapshot
     vm_set_gpreg(regs)
 
 def kernel32_GetCurrentProcess():
@@ -345,7 +346,7 @@ def kernel32_Process32First():
 
     print whoami(), hex(ret_ad), '(', hex(s_handle), hex(ad_pentry), ')'
 
-    pentry = struct.pack('LLLLLLLLL', *process_list[0][:-1])+process_list[0][-1]
+    pentry = struct.pack('IIIIIIIII', *process_list[0][:-1])+process_list[0][-1]
     vm_set_mem(ad_pentry, pentry)
     winobjs.toolhelpsnapshot_info[s_handle] = 0
 
@@ -367,7 +368,7 @@ def kernel32_Process32Next():
         eax = 1
         n = winobjs.toolhelpsnapshot_info[s_handle]
         print whoami(), hex(ret_ad), '(', hex(s_handle), hex(ad_pentry), ')'
-        pentry = struct.pack('LLLLLLLLL', *process_list[n][:-1])+process_list[n][-1]
+        pentry = struct.pack('IIIIIIIII', *process_list[n][:-1])+process_list[n][-1]
         vm_set_mem(ad_pentry, pentry)
     regs = vm_get_gpreg()
     regs['eip'] = ret_ad
@@ -645,6 +646,8 @@ def kernel32_CreateFile(funcname, get_str):
     elif fname.upper() in ['NUL']:
         eax = winobjs.module_cur_hwnd
     else:
+        # nuxify path
+        fname = fname.replace('\\', "/").lower()
         # go in sandbox files
         f = os.path.join('file_sb', fname)
         if access & 0x80000000:
@@ -677,21 +680,26 @@ def kernel32_ReadFile():
 
     if hwnd == winobjs.module_cur_hwnd:
         pass
+    elif hwnd in winobjs.handle_pool:
+        pass
     else:
         raise ValueError('unknown hwnd!')
 
     eax = 0xffffffff
-
+    data = None
     if hwnd in winobjs.files_hwnd:
         data = winobjs.files_hwnd[winobjs.module_cur_hwnd].read(nnumberofbytestoread)
+    elif hwnd in winobjs.handle_pool:
+        wh = winobjs.handle_pool[hwnd]
+        data = wh.info.read(nnumberofbytestoread)
+    else:
+        raise ValueError('unknown filename')
 
+    if data != None:
         if (lpnumberofbytesread):
             vm_set_mem(lpnumberofbytesread, pdw(len(data)))
         vm_set_mem(lpbuffer, data)
 
-    else:
-        raise ValueError('unknown filename')
-
 
     regs = vm_get_gpreg()
     regs['eip'] = ret_ad
@@ -707,6 +715,10 @@ def kernel32_GetFileSize():
 
     if hwnd == winobjs.module_cur_hwnd:
         eax = len(open(winobjs.module_fname_nux).read())
+    elif hwnd in winobjs.handle_pool:
+        wh = winobjs.handle_pool[hwnd]
+        print wh
+        eax = len(open(wh.name).read())
     else:
         raise ValueError('unknown hwnd!')
 
@@ -1984,6 +1996,7 @@ def kernel32_WaitForSingleObject():
     handle = vm_pop_uint32_t()
     dwms = vm_pop_uint32_t()
 
+    print whoami(), hex(ret_ad), hex(handle), hex(dwms)
 
     t_start = time.time()*1000
     while True: