5be0ddab321ace37a785f0be2ea4d7bb799b11ec
[ia32rtools.git] / ida / saveasm / saveasm.cpp
1 /*
2  * ia32rtools
3  * (C) notaz, 2013,2014
4  *
5  * This work is licensed under the terms of 3-clause BSD license.
6  * See COPYING file in the top-level directory.
7  */
8
9 #define NO_OBSOLETE_FUNCS
10 #include <ida.hpp>
11 #include <idp.hpp>
12 #include <bytes.hpp>
13 #include <loader.hpp>
14 #include <kernwin.hpp>
15
16 #include <name.hpp>
17 #include <frame.hpp>
18 #include <struct.hpp>
19 #include <offset.hpp>
20 #include <auto.hpp>
21 #include <intel.hpp>
22
23 #define IS_START(w, y) !strncmp(w, y, strlen(y))
24 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
25
26 static char **name_cache;
27 static size_t name_cache_size;
28
29 // non-local branch targets
30 static ea_t *nonlocal_bt;
31 static int nonlocal_bt_alloc;
32 static int nonlocal_bt_cnt;
33
34 //--------------------------------------------------------------------------
35 static int idaapi init(void)
36 {
37   return PLUGIN_OK;
38 }
39
40 //--------------------------------------------------------------------------
41 static void idaapi term(void)
42 {
43   size_t i;
44
45   if (nonlocal_bt != NULL) {
46     free(nonlocal_bt);
47     nonlocal_bt = NULL;
48   }
49   nonlocal_bt_alloc = 0;
50
51   if (name_cache != NULL) {
52     for (i = 0; i < name_cache_size; i++)
53       free(name_cache[i]);
54     free(name_cache);
55     name_cache = NULL;
56   }
57   name_cache_size = 0;
58 }
59
60 //--------------------------------------------------------------------------
61
62 static const char *reserved_names[] = {
63   "name",
64   "type",
65   "offset",
66   "aam",
67   "text",
68   "size",
69   "c",
70   "align",
71 };
72
73 static int is_name_reserved(const char *name)
74 {
75   int i;
76   for (i = 0; i < ARRAY_SIZE(reserved_names); i++)
77     if (strcasecmp(name, reserved_names[i]) == 0)
78       return 1;
79
80   return 0;
81 }
82
83 static int nonlocal_bt_cmp(const void *p1, const void *p2)
84 {
85   const ea_t *e1 = (const ea_t *)p1, *e2 = (const ea_t *)p2;
86   return *e1 - *e2;
87 }
88
89 static void nonlocal_add(ea_t ea)
90 {
91   if (nonlocal_bt_cnt >= nonlocal_bt_alloc) {
92     nonlocal_bt_alloc += nonlocal_bt_alloc * 2 + 64;
93     nonlocal_bt = (ea_t *)realloc(nonlocal_bt,
94       nonlocal_bt_alloc * sizeof(nonlocal_bt[0]));
95     if (nonlocal_bt == NULL) {
96       msg("OOM\n");
97       return;
98     }
99   }
100   nonlocal_bt[nonlocal_bt_cnt++] = ea;
101 }
102
103 // is instruction a (un)conditional jump (not call)?
104 static int is_insn_jmp(uint16 itype)
105 {
106   return itype == NN_jmp || (NN_ja <= itype && itype <= NN_jz);
107 }
108
109 static void do_def_line(char *buf, size_t buf_size, const char *line,
110   ea_t ea)
111 {
112   ea_t *ea_ret;
113   char *p;
114   int len;
115
116   tag_remove(line, buf, buf_size); // remove color codes
117   len = strlen(buf);
118   if (len < 9) {
119     buf[0] = 0;
120     return;
121   }
122   memmove(buf, buf + 9, len - 9 + 1); // rm address
123
124   p = buf;
125   while (*p && *p != ' ' && *p != ':')
126     p++;
127   if (*p == ':') {
128     ea_ret = (ea_t *)bsearch(&ea, nonlocal_bt, nonlocal_bt_cnt,
129       sizeof(nonlocal_bt[0]), nonlocal_bt_cmp);
130     if (ea_ret != 0) {
131       if (p[1] != ' ')
132         msg("no trailing blank in '%s'\n", buf);
133       else
134         p[1] = ':';
135     }
136   }
137 }
138
139 static int name_cache_cmp(const void *p1, const void *p2)
140 {
141   // masm ignores case, so do we
142   return stricmp(*(char * const *)p1, *(char * const *)p2);
143 }
144
145 static void rebuild_name_cache(void)
146 {
147   size_t i, newsize;
148   void *tmp;
149
150   // build a sorted name cache
151   newsize = get_nlist_size();
152   if (newsize > name_cache_size) {
153     tmp = realloc(name_cache, newsize * sizeof(name_cache[0]));
154     if (tmp == NULL) {
155       msg("OOM for name cache\n");
156       return;
157     }
158     name_cache = (char **)tmp;
159   }
160   for (i = 0; i < name_cache_size; i++)
161     free(name_cache[i]);
162   for (i = 0; i < newsize; i++)
163     name_cache[i] = strdup(get_nlist_name(i));
164
165   name_cache_size = newsize;
166   qsort(name_cache, name_cache_size, sizeof(name_cache[0]),
167     name_cache_cmp);
168 }
169
170 static void my_rename(ea_t ea, char *name)
171 {
172   char buf[256];
173   char *p, **pp;
174   int n = 0;
175
176   qsnprintf(buf, sizeof(buf), "%s", name);
177   do {
178     p = buf;
179     pp = (char **)bsearch(&p, name_cache, name_cache_size,
180         sizeof(name_cache[0]), name_cache_cmp);
181     if (pp == NULL)
182       break;
183
184     qsnprintf(buf, sizeof(buf), "%s_g%d", name, n);
185     n++;
186   }
187   while (n < 100);
188
189   if (n == 100)
190     msg("rename failure? '%s'\n", name);
191
192   do_name_anyway(ea, buf);
193   rebuild_name_cache();
194 }
195
196 static void make_align(ea_t ea)
197 {
198   ea_t tmp_ea;
199   int n;
200
201   tmp_ea = next_head(ea, inf.maxEA);
202   if ((tmp_ea & 0x03) == 0) {
203     n = calc_max_align(tmp_ea);
204     if (n > 4) // masm doesn't like more..
205       n = 4;
206     msg("%x: align %d\n", ea, 1 << n);
207     do_unknown(ea, DOUNK_SIMPLE);
208     doAlign(ea, tmp_ea - ea, n);
209   }
210 }
211
212 static void idaapi run(int /*arg*/)
213 {
214   // isEnabled(ea) // address belongs to disassembly
215   // ea_t ea = get_screen_ea();
216   // extern foo;
217   // foo = DecodeInstruction(ScreenEA());
218   FILE *fout = NULL;
219   int fout_line = 0;
220   char buf[MAXSTR];
221   char buf2[MAXSTR];
222   const char *name;
223   struc_t *frame;
224   func_t *func;
225   ea_t ui_ea_block = 0, ea_size;
226   ea_t tmp_ea, target_ea;
227   ea_t ea;
228   flags_t ea_flags;
229   uval_t idx;
230   int i, o, m, n;
231   int ret;
232   char **pp;
233   char *p;
234
235   nonlocal_bt_cnt = 0;
236
237   // get rid of structs, masm doesn't understand them
238   idx = get_first_struc_idx();
239   while (idx != BADNODE) {
240     tid_t tid = get_struc_by_idx(idx);
241     struc_t *struc = get_struc(tid);
242     get_struc_name(tid, buf, sizeof(buf));
243     msg("removing struct '%s'\n", buf);
244     //del_struc_members(struc, 0, get_max_offset(struc));
245     del_struc(struc);
246
247     idx = get_first_struc_idx();
248   }
249
250   rebuild_name_cache();
251
252   // 1st pass: walk through all funcs
253   ea = inf.minEA;
254   func = get_func(ea);
255   while (func != NULL)
256   {
257     func_tail_iterator_t fti(func);
258     if (!fti.main()) {
259       msg("%x: func_tail_iterator_t main failed\n", ea);
260       return;
261     }
262     const area_t &f_area = fti.chunk();
263     ea = f_area.startEA;
264
265     // rename global syms which conflict with frame member names
266     frame = get_frame(func);
267     if (frame != NULL)
268     {
269       for (m = 0; m < (int)frame->memqty; m++)
270       {
271         ret = get_member_name(frame->members[m].id, buf, sizeof(buf));
272         if (ret <= 0) {
273           msg("%x: member has no name?\n", ea);
274           return;
275         }
276         if (buf[0] == ' ') // what's this?
277           continue;
278         if (IS_START(buf, "arg_") || IS_START(buf, "var_"))
279           continue;
280
281         // check for dupe names
282         int m1, dupe = 0;
283         for (m1 = 0; m1 < m; m1++) {
284           get_member_name(frame->members[m1].id, buf2, sizeof(buf2));
285           if (stricmp(buf, buf2) == 0)
286             dupe = 1;
287         }
288
289         if (is_name_reserved(buf) || dupe) {
290           msg("%x: renaming '%s'\n", ea, buf);
291           qstrncat(buf, "_", sizeof(buf));
292           ret = set_member_name(frame, frame->members[m].soff, buf);
293           if (!ret) {
294             msg("%x: renaming failed\n", ea);
295             return;
296           }
297         }
298
299         p = buf;
300         pp = (char **)bsearch(&p, name_cache, name_cache_size,
301               sizeof(name_cache[0]), name_cache_cmp);
302         if (pp == NULL)
303           continue;
304
305         tmp_ea = get_name_ea(BADADDR, *pp);
306         msg("%x: renaming '%s' because of '%s' at %x\n",
307           tmp_ea, *pp, buf, ea);
308         my_rename(tmp_ea, *pp);
309       }
310     }
311
312     func = get_next_func(ea);
313   }
314
315   // 2nd pass over whole .text and .(ro)data segments
316   for (ea = inf.minEA; ea != BADADDR; ea = next_head(ea, inf.maxEA))
317   {
318     segment_t *seg = getseg(ea);
319     if (!seg)
320       break;
321     if (seg->type == SEG_XTRN)
322       continue;
323     if (seg->type != SEG_CODE && seg->type != SEG_DATA)
324       break;
325
326     ea_flags = get_flags_novalue(ea);
327     func = get_func(ea);
328     if (isCode(ea_flags))
329     {
330       if (!decode_insn(ea)) {
331         msg("%x: decode_insn() failed\n", ea);
332         continue;
333       }
334
335       // masm doesn't understand IDA's float/xmm types
336       if (cmd.itype == NN_fld || cmd.itype == NN_fst
337         || cmd.itype == NN_movapd || cmd.itype == NN_movlpd)
338       {
339         for (o = 0; o < UA_MAXOP; o++) {
340           if (cmd.Operands[o].type == o_void)
341             break;
342
343           if (cmd.Operands[o].type == o_mem) {
344             tmp_ea = cmd.Operands[o].addr;
345             flags_t tmp_ea_flags = get_flags_novalue(tmp_ea);
346             // ..but base float is ok..
347             int is_flt = isDwrd(tmp_ea_flags) || isFloat(tmp_ea_flags);
348             if (!is_flt && !isUnknown(tmp_ea_flags))
349             {
350               buf[0] = 0;
351               get_name(ea, tmp_ea, buf, sizeof(buf));
352               msg("%x: undefining %x '%s'\n", ea, tmp_ea, buf);
353               do_unknown(tmp_ea, DOUNK_EXPAND);
354             }
355           }
356         }
357       }
358       else if (cmd.itype == NN_lea) {
359         // detect code alignment
360         if (cmd.Operands[0].reg == cmd.Operands[1].reg
361           && cmd.Operands[1].type == o_displ
362           && cmd.Operands[1].addr == 0)
363         {
364           // lea eax, [eax+0]
365           make_align(ea);
366         }
367         else if (!isDefArg1(ea_flags)
368           && cmd.Operands[1].type == o_mem // why o_mem?
369           && cmd.Operands[1].dtyp == dt_dword)
370         {
371           if (inf.minEA <= cmd.Operands[1].addr
372             && cmd.Operands[1].addr < inf.maxEA)
373           {
374             // lea to segments, like ds:58D6A8h[edx*8]
375             msg("%x: lea offset to %x\n", ea, cmd.Operands[1].addr);
376             op_offset(ea, 1, REF_OFF32);
377           }
378           else
379           {
380             // ds:0[eax*8] -> [eax*8+0]
381             msg("%x: dropping ds: for %x\n", ea, cmd.Operands[1].addr);
382             op_hex(ea, 1);
383           }
384         }
385       }
386       else if (cmd.itype == NN_mov && cmd.segpref == 0x1e // 2e?
387         && cmd.Operands[0].type == o_reg
388         && cmd.Operands[1].type == o_reg
389         && cmd.Operands[0].dtyp == cmd.Operands[1].dtyp
390         && cmd.Operands[0].reg == cmd.Operands[1].reg)
391       {
392         // db 2Eh; mov eax, eax
393         make_align(ea);
394       }
395
396       // find non-local branches
397       if (is_insn_jmp(cmd.itype) && cmd.Operands[0].type == o_near)
398       {
399         target_ea = cmd.Operands[0].addr;
400         if (func == NULL)
401           nonlocal_add(target_ea);
402         else {
403           ret = get_func_chunknum(func, target_ea);
404           if (ret != 0) {
405             // a jump to another func or chunk
406             // check if it lands on func start
407             if (!isFunc(get_flags_novalue(target_ea)))
408               nonlocal_add(target_ea);
409           }
410         }
411       }
412     }
413     else { // not code
414       int do_undef = 0;
415       ea_size = get_item_size(ea);
416
417       if (func == NULL && isOff0(ea_flags)) {
418         for (tmp_ea = 0; tmp_ea < ea_size; tmp_ea += 4)
419           nonlocal_add(get_long(ea + tmp_ea));
420       }
421
422       // IDA vs masm float/mmx/xmm type incompatibility
423       if (isDouble(ea_flags) || isTbyt(ea_flags)
424        || isPackReal(ea_flags))
425       {
426         do_undef = 1;
427       }
428       else if (isOwrd(ea_flags)) {
429         buf[0] = 0;
430         get_name(BADADDR, ea, buf, sizeof(buf));
431         if (IS_START(buf, "xmm"))
432           do_undef = 1;
433       }
434       // masm doesn't understand IDA's unicode
435       else if (isASCII(ea_flags) && ea_size >= 4
436         && (get_long(ea) & 0xff00ff00) == 0) // lame..
437       {
438         do_undef = 1;
439       }
440       // masm doesn't understand large aligns
441       else if (isAlign(ea_flags) && ea_size > 0x10) {
442         msg("%x: undefining align %d\n", ea, ea_size);
443         do_unknown(ea, DOUNK_EXPAND);
444       }
445
446       if (do_undef) {
447         buf[0] = 0;
448         get_name(BADADDR, ea, buf, sizeof(buf));
449         msg("%x: undefining '%s'\n", ea, buf);
450         do_unknown(ea, DOUNK_EXPAND);
451       }
452     }
453   }
454
455   // check namelist for reserved names
456   n = get_nlist_size();
457   for (i = 0; i < n; i++) {
458     ea = get_nlist_ea(i);
459     name = get_nlist_name(i);
460     if (name == NULL) {
461       msg("%x: null name?\n", ea);
462       continue;
463     }
464
465     // rename vars with '?@' (funcs are ok)
466     int change_qat = 0;
467     ea_flags = get_flags_novalue(ea);
468     if (!isCode(ea_flags) && strpbrk(name, "?@"))
469       change_qat = 1;
470
471     if (change_qat || is_name_reserved(name)) {
472       msg("%x: renaming name '%s'\n", ea, name);
473       qsnprintf(buf, sizeof(buf), "%s", name);
474
475       if (change_qat) {
476         for (p = buf; *p != 0; p++) {
477           if (*p == '?' || *p == '@') {
478             qsnprintf(buf2, sizeof(buf2), "%02x", (unsigned char)*p);
479             memmove(p + 1, p, strlen(p) + 1);
480             memcpy(p, buf2, 2);
481           }
482         }
483       }
484
485       my_rename(ea, buf);
486     }
487   }
488
489   if (nonlocal_bt_cnt > 1) {
490     qsort(nonlocal_bt, nonlocal_bt_cnt,
491       sizeof(nonlocal_bt[0]), nonlocal_bt_cmp);
492   }
493
494   char *fname = askfile_c(1, NULL, "Save asm file");
495   if (fname == NULL)
496     return;
497   fout = qfopen(fname, "w");
498   if (fout == NULL) {
499     msg("couldn't open '%s'\n", fname);
500     return;
501   }
502
503   show_wait_box("Saving..");
504
505   // deal with the beginning
506   ea = inf.minEA;
507   int flags = 0; // calc_default_idaplace_flags();
508   linearray_t ln(&flags);
509   idaplace_t pl;
510   pl.ea = ea;
511   pl.lnnum = 0;
512   ln.set_place(&pl);
513   n = ln.get_linecnt();
514   for (i = 0; i < n - 1; i++) {
515     do_def_line(buf, sizeof(buf), ln.down(), ea);
516     if (strstr(buf, "include"))
517       continue;
518
519     fout_line++;
520     qfprintf(fout, "%s\n", buf);
521     p = strstr(buf, ".mmx");
522     if (p != NULL) {
523       memcpy(p, ".xmm", 4);
524       fout_line++;
525       qfprintf(fout, "%s\n", buf);
526       continue;
527     }
528     p = strstr(buf, ".model");
529     if (p != NULL) {
530       qstrncpy(p, "include imports.inc", sizeof(buf) - (p - buf));
531       fout_line++;
532       qfprintf(fout, "\n%s\n", buf);
533       i++;
534       break;
535     }
536   }
537   pl.lnnum = i;
538
539   for (;;)
540   {
541     int drop_large = 0, do_rva = 0, set_scale = 0, jmp_near = 0;
542     int word_imm = 0, dword_imm = 0, do_pushf = 0, do_nops = 0;
543
544     if ((ea >> 14) != ui_ea_block) {
545       ui_ea_block = ea >> 14;
546       showAddr(ea);
547       if (wasBreak())
548         break;
549     }
550
551     segment_t *seg = getseg(ea);
552     if (!seg || (seg->type != SEG_CODE && seg->type != SEG_DATA))
553       goto pass;
554
555     ea_flags = get_flags_novalue(ea);
556     if (isCode(ea_flags))
557     {
558       if (!decode_insn(ea))
559         goto pass;
560
561       if (is_insn_jmp(cmd.itype) && cmd.Operands[0].type == o_near
562         && cmd.Operands[0].dtyp == dt_dword)
563       {
564         jmp_near = 1;
565       }
566       else if ((cmd.itype == NN_pushf || cmd.itype == NN_popf)
567         && natop())
568       {
569         do_pushf = 1;
570       }
571
572       for (o = 0; o < UA_MAXOP; o++) {
573         const op_t &opr = cmd.Operands[o];
574         if (opr.type == o_void)
575           break;
576
577         // correct?
578         if (opr.type == o_mem && opr.specval_shorts.high == 0x21)
579           drop_large = 1;
580         if (opr.hasSIB && x86_scale(opr) == 0
581           && x86_index(opr) != INDEX_NONE)
582         {
583           set_scale = 1;
584         }
585         // annoying alignment variant..
586         if (opr.type == o_imm && opr.dtyp == dt_dword
587           && (opr.value < 0x80 || opr.value > 0xffffff80)
588           && cmd.size >= opr.offb + 4)
589         {
590           if (get_long(ea + opr.offb) == opr.value)
591             dword_imm = 1;
592         }
593         else if (opr.type == o_imm && opr.dtyp == dt_word
594           && (opr.value < 0x80 || opr.value > 0xff80)
595           && cmd.size >= opr.offb + 2)
596         {
597           if (get_word(ea + opr.offb) == (ushort)opr.value)
598             word_imm = 1;
599         }
600         else if (opr.type == o_displ && opr.addr == 0
601           && opr.offb != 0 && opr.hasSIB && opr.sib == 0x24)
602         {
603           // uses [esp+0] with 0 encoded into op
604           do_nops++;
605         }
606       }
607     }
608     else { // not code
609       if (isOff0(ea_flags))
610         do_rva = 1;
611     }
612
613 pass:
614     n = ln.get_linecnt();
615     for (i = pl.lnnum; i < n; i++) {
616       do_def_line(buf, sizeof(buf), ln.down(), ea);
617
618       char *fw;
619       for (fw = buf; *fw != 0 && *fw == ' '; )
620         fw++;
621
622       // patches..
623       if (drop_large) {
624         p = strstr(fw, "large ");
625         if (p != NULL)
626           memmove(p, p + 6, strlen(p + 6) + 1);
627       }
628       while (do_rva) {
629         p = strstr(fw, " rva ");
630         if (p == NULL)
631           break;
632         memmove(p + 4 + 3, p + 4, strlen(p + 4) + 1);
633         memcpy(p + 1, "offset", 6);
634       }
635       if (set_scale) {
636         p = strchr(fw, '[');
637         if (p != NULL)
638           p = strchr(p, '+');
639         if (p != NULL && p[1] == 'e') {
640           p += 4;
641           // scale is 1, must specify it explicitly so that
642           // masm chooses the right scaled reg
643           memmove(p + 2, p, strlen(p) + 1);
644           memcpy(p, "*1", 2);
645         }
646       }
647       else if (jmp_near) {
648         p = NULL;
649         if (fw != buf && fw[0] == 'j')
650           p = fw;
651         while (p && *p != ' ')
652           p++;
653         while (p && *p == ' ')
654           p++;
655         if (p != NULL) {
656           memmove(p + 9, p, strlen(p) + 1);
657           memcpy(p, "near ptr ", 9);
658           jmp_near = 0;
659         }
660       }
661       if (word_imm) {
662         p = strstr(fw, ", ");
663         if (p != NULL && '0' <= p[2] && p[2] <= '9') {
664           p += 2;
665           memmove(p + 9, p, strlen(p) + 1);
666           memcpy(p, "word ptr ", 9);
667         }
668       }
669       else if (dword_imm) {
670         p = strstr(fw, ", ");
671         if (p != NULL && '0' <= p[2] && p[2] <= '9') {
672           p += 2;
673           memmove(p + 10, p, strlen(p) + 1);
674           memcpy(p, "dword ptr ", 10);
675         }
676       }
677       else if (do_pushf) {
678         p = strstr(fw, "pushf");
679         if (p == NULL)
680           p = strstr(fw, "popf");
681         if (p != NULL) {
682           p = strchr(p, 'f') + 1;
683           memmove(p + 1, p, strlen(p) + 1);
684           *p = 'd';
685         }
686       }
687
688       if (fw[0] == 'a' && IS_START(fw, "assume cs")) {
689         // "assume cs" causes problems with ext syms
690         memmove(fw + 1, fw, strlen(fw) + 1);
691         *fw = ';';
692       }
693       else if (fw[0] == 'e' && IS_START(fw, "end") && fw[3] == ' ') {
694         fout_line++;
695         qfprintf(fout, "include public.inc\n\n");
696
697         // kill entry point
698         fw[3] = 0;
699       }
700
701       fout_line++;
702       qfprintf(fout, "%s\n", buf);
703     }
704
705     while (do_nops-- > 0)
706       qfprintf(fout, "                nop ; adj\n");
707
708     // note: next_head skips some undefined stuff
709     ea = next_not_tail(ea); // correct?
710     if (ea == BADADDR)
711       break;
712
713     pl.ea = ea;
714     pl.lnnum = 0;
715     ln.set_place(&pl);
716   }
717
718   if (fout != NULL)
719     qfclose(fout);
720   if (fname != NULL)
721     qfree(fname);
722
723   hide_wait_box();
724   msg("%d lines saved.\n", fout_line);
725 }
726
727 //--------------------------------------------------------------------------
728
729 static const char comment[] = "Generate disassembly for nasm";
730 static const char help[] = "Generate asm file\n";
731 static const char wanted_name[] = "Save asm";
732 static const char wanted_hotkey[] = "Shift-S";
733
734 //--------------------------------------------------------------------------
735 //
736 //      PLUGIN DESCRIPTION BLOCK
737 //
738 //--------------------------------------------------------------------------
739 plugin_t PLUGIN =
740 {
741   IDP_INTERFACE_VERSION,
742   0,                    // plugin flags
743   init,                 // initialize
744   term,                 // terminate. this pointer may be NULL.
745   run,                  // invoke plugin
746   comment,              // long comment about the plugin
747                         // it could appear in the status line
748                         // or as a hint
749   help,                 // multiline help about the plugin
750   wanted_name,          // the preferred short name of the plugin
751   wanted_hotkey         // the preferred hotkey to run the plugin
752 };
753
754 // vim:ts=2:shiftwidth=2:expandtab