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