26ba2f9f0f2a5223e57704dae3306a76f9e11c15
[ia32rtools.git] / plugin / 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 idaapi run(int /*arg*/)
197 {
198   // isEnabled(ea) // address belongs to disassembly
199   // ea_t ea = get_screen_ea();
200   // foo = DecodeInstruction(ScreenEA());
201   FILE *fout = NULL;
202   int fout_line = 0;
203   char buf[MAXSTR];
204   char buf2[MAXSTR];
205   const char *name;
206   struc_t *frame;
207   func_t *func;
208   ea_t ui_ea_block = 0, ea_size;
209   ea_t tmp_ea, target_ea;
210   ea_t ea;
211   flags_t ea_flags;
212   uval_t idx;
213   int i, o, m, n;
214   int ret;
215   char **pp;
216   char *p;
217
218   nonlocal_bt_cnt = 0;
219
220   // get rid of structs, masm doesn't understand them
221   idx = get_first_struc_idx();
222   while (idx != BADNODE) {
223     tid_t tid = get_struc_by_idx(idx);
224     struc_t *struc = get_struc(tid);
225     get_struc_name(tid, buf, sizeof(buf));
226     msg("removing struct '%s'\n", buf);
227     //del_struc_members(struc, 0, get_max_offset(struc));
228     del_struc(struc);
229
230     idx = get_first_struc_idx();
231   }
232
233   rebuild_name_cache();
234
235   // 1st pass: walk through all funcs
236   ea = inf.minEA;
237   func = get_func(ea);
238   while (func != NULL)
239   {
240     func_tail_iterator_t fti(func);
241     if (!fti.main()) {
242       msg("%x: func_tail_iterator_t main failed\n", ea);
243       return;
244     }
245     const area_t &f_area = fti.chunk();
246     ea = f_area.startEA;
247
248     // rename global syms which conflict with frame member names
249     frame = get_frame(func);
250     if (frame != NULL)
251     {
252       for (m = 0; m < (int)frame->memqty; m++)
253       {
254         ret = get_member_name(frame->members[m].id, buf, sizeof(buf));
255         if (ret <= 0) {
256           msg("%x: member has no name?\n", ea);
257           return;
258         }
259         if (buf[0] == ' ') // what's this?
260           continue;
261         if (IS_START(buf, "arg_") || IS_START(buf, "var_"))
262           continue;
263
264         // check for dupe names
265         int m1, dupe = 0;
266         for (m1 = 0; m1 < m; m1++) {
267           get_member_name(frame->members[m1].id, buf2, sizeof(buf2));
268           if (stricmp(buf, buf2) == 0)
269             dupe = 1;
270         }
271
272         if (is_name_reserved(buf) || dupe) {
273           msg("%x: renaming '%s'\n", ea, buf);
274           qstrncat(buf, "_", sizeof(buf));
275           ret = set_member_name(frame, frame->members[m].soff, buf);
276           if (!ret) {
277             msg("%x: renaming failed\n", ea);
278             return;
279           }
280         }
281
282         p = buf;
283         pp = (char **)bsearch(&p, name_cache, name_cache_size,
284               sizeof(name_cache[0]), name_cache_cmp);
285         if (pp == NULL)
286           continue;
287
288         tmp_ea = get_name_ea(BADADDR, *pp);
289         msg("%x: renaming '%s' because of '%s' at %x\n",
290           tmp_ea, *pp, buf, ea);
291         my_rename(tmp_ea, *pp);
292       }
293     }
294
295     func = get_next_func(ea);
296   }
297
298   // 2nd pass over whole .text and .(ro)data segments
299   for (ea = inf.minEA; ea != BADADDR; ea = next_head(ea, inf.maxEA))
300   {
301     segment_t *seg = getseg(ea);
302     if (!seg)
303       break;
304     if (seg->type == SEG_XTRN)
305       continue;
306     if (seg->type != SEG_CODE && seg->type != SEG_DATA)
307       break;
308
309     ea_flags = get_flags_novalue(ea);
310     func = get_func(ea);
311     if (isCode(ea_flags))
312     {
313       if (!decode_insn(ea)) {
314         msg("%x: decode_insn() failed\n", ea);
315         continue;
316       }
317
318       // masm doesn't understand IDA's float/xmm types
319       if (cmd.itype == NN_fld || cmd.itype == NN_fst
320         || cmd.itype == NN_movapd || cmd.itype == NN_movlpd)
321       {
322         for (o = 0; o < UA_MAXOP; o++) {
323           if (cmd.Operands[o].type == o_void)
324             break;
325
326           if (cmd.Operands[o].type == o_mem) {
327             tmp_ea = cmd.Operands[o].addr;
328             flags_t tmp_ea_flags = get_flags_novalue(tmp_ea);
329             // ..but base float is ok..
330             int is_flt = isDwrd(tmp_ea_flags) || isFloat(tmp_ea_flags);
331             if (!is_flt && !isUnknown(tmp_ea_flags))
332             {
333               buf[0] = 0;
334               get_name(ea, tmp_ea, buf, sizeof(buf));
335               msg("%x: undefining %x '%s'\n", ea, tmp_ea, buf);
336               do_unknown(tmp_ea, DOUNK_EXPAND);
337             }
338           }
339         }
340       }
341       else if (cmd.itype == NN_lea) {
342         // detect code alignment
343         if (cmd.Operands[0].reg == cmd.Operands[1].reg
344           && cmd.Operands[1].type == o_displ
345           && cmd.Operands[1].addr == 0)
346         {
347           tmp_ea = next_head(ea, inf.maxEA);
348           if ((tmp_ea & 0x03) == 0) {
349             n = calc_max_align(tmp_ea);
350             if (n > 4) // masm doesn't like more..
351               n = 4;
352             msg("%x: align %d\n", ea, 1 << n);
353             do_unknown(ea, DOUNK_SIMPLE);
354             doAlign(ea, tmp_ea - ea, n);
355           }
356         }
357         else if (!isDefArg1(ea_flags)
358           && cmd.Operands[1].type == o_mem // why o_mem?
359           && cmd.Operands[1].dtyp == dt_dword)
360         {
361           if (inf.minEA <= cmd.Operands[1].addr
362             && cmd.Operands[1].addr < inf.maxEA)
363           {
364             // lea to segments, like ds:58D6A8h[edx*8]
365             msg("%x: lea offset to %x\n", ea, cmd.Operands[1].addr);
366             op_offset(ea, 1, REF_OFF32);
367           }
368           else
369           {
370             // ds:0[eax*8] -> [eax*8+0]
371             msg("%x: dropping ds: for %x\n", ea, cmd.Operands[1].addr);
372             op_hex(ea, 1);
373           }
374         }
375       }
376
377       // find non-local branches
378       if (is_insn_jmp(cmd.itype) && cmd.Operands[0].type == o_near)
379       {
380         target_ea = cmd.Operands[0].addr;
381         if (func == NULL)
382           nonlocal_add(target_ea);
383         else {
384           ret = get_func_chunknum(func, target_ea);
385           if (ret != 0) {
386             // a jump to another func or chunk
387             // check if it lands on func start
388             if (!isFunc(get_flags_novalue(target_ea)))
389               nonlocal_add(target_ea);
390           }
391         }
392       }
393     }
394     else { // not code
395       int do_undef = 0;
396       ea_size = get_item_size(ea);
397
398       if (func == NULL && isOff0(ea_flags)) {
399         for (tmp_ea = 0; tmp_ea < ea_size; tmp_ea += 4)
400           nonlocal_add(get_long(ea + tmp_ea));
401       }
402
403       // IDA vs masm float/mmx/xmm type incompatibility
404       if (isDouble(ea_flags) || isTbyt(ea_flags)
405        || isPackReal(ea_flags))
406       {
407         do_undef = 1;
408       }
409       else if (isOwrd(ea_flags)) {
410         buf[0] = 0;
411         get_name(BADADDR, ea, buf, sizeof(buf));
412         if (IS_START(buf, "xmm"))
413           do_undef = 1;
414       }
415       // masm doesn't understand IDA's unicode
416       else if (isASCII(ea_flags) && ea_size >= 4
417         && (get_long(ea) & 0xff00ff00) == 0) // lame..
418       {
419         do_undef = 1;
420       }
421       // masm doesn't understand large aligns
422       else if (isAlign(ea_flags) && ea_size > 0x10) {
423         msg("%x: undefining align %d\n", ea, ea_size);
424         do_unknown(ea, DOUNK_EXPAND);
425       }
426
427       if (do_undef) {
428         buf[0] = 0;
429         get_name(BADADDR, ea, buf, sizeof(buf));
430         msg("%x: undefining '%s'\n", ea, buf);
431         do_unknown(ea, DOUNK_EXPAND);
432       }
433     }
434   }
435
436   // check namelist for reserved names
437   n = get_nlist_size();
438   for (i = 0; i < n; i++) {
439     ea = get_nlist_ea(i);
440     name = get_nlist_name(i);
441     if (name == NULL) {
442       msg("%x: null name?\n", ea);
443       continue;
444     }
445
446     // rename vars with '?@' (funcs are ok)
447     int change_qat = 0;
448     ea_flags = get_flags_novalue(ea);
449     if (!isCode(ea_flags) && strpbrk(name, "?@"))
450       change_qat = 1;
451
452     if (change_qat || is_name_reserved(name)) {
453       msg("%x: renaming name '%s'\n", ea, name);
454       qsnprintf(buf, sizeof(buf), "%s", name);
455
456       if (change_qat) {
457         for (p = buf; *p != 0; p++) {
458           if (*p == '?' || *p == '@') {
459             qsnprintf(buf2, sizeof(buf2), "%02x", (unsigned char)*p);
460             memmove(p + 1, p, strlen(p) + 1);
461             memcpy(p, buf2, 2);
462           }
463         }
464       }
465
466       my_rename(ea, buf);
467     }
468   }
469
470   if (nonlocal_bt_cnt > 1) {
471     qsort(nonlocal_bt, nonlocal_bt_cnt,
472       sizeof(nonlocal_bt[0]), nonlocal_bt_cmp);
473   }
474
475   char *fname = askfile_c(1, NULL, "Save asm file");
476   if (fname == NULL)
477     return;
478   fout = qfopen(fname, "w");
479   if (fout == NULL) {
480     msg("couldn't open '%s'\n", fname);
481     return;
482   }
483
484   show_wait_box("Saving..");
485
486   // deal with the beginning
487   ea = inf.minEA;
488   int flags = 0; // calc_default_idaplace_flags();
489   linearray_t ln(&flags);
490   idaplace_t pl;
491   pl.ea = ea;
492   pl.lnnum = 0;
493   ln.set_place(&pl);
494   n = ln.get_linecnt();
495   for (i = 0; i < n - 1; i++) {
496     do_def_line(buf, sizeof(buf), ln.down(), ea);
497     if (strstr(buf, "include"))
498       continue;
499
500     fout_line++;
501     qfprintf(fout, "%s\n", buf);
502     p = strstr(buf, ".mmx");
503     if (p != NULL) {
504       memcpy(p, ".xmm", 4);
505       fout_line++;
506       qfprintf(fout, "%s\n", buf);
507       continue;
508     }
509     p = strstr(buf, ".model");
510     if (p != NULL) {
511       qstrncpy(p, "include imports.inc", sizeof(buf) - (p - buf));
512       fout_line++;
513       qfprintf(fout, "\n%s\n", buf);
514       i++;
515       break;
516     }
517   }
518   pl.lnnum = i;
519
520   for (;;)
521   {
522     int drop_large = 0, do_rva = 0, set_scale = 0, jmp_near = 0;
523     int word_imm = 0, dword_imm = 0, do_pushf = 0, do_nops = 0;
524
525     if ((ea >> 14) != ui_ea_block) {
526       ui_ea_block = ea >> 14;
527       showAddr(ea);
528       if (wasBreak())
529         break;
530     }
531
532     segment_t *seg = getseg(ea);
533     if (!seg || (seg->type != SEG_CODE && seg->type != SEG_DATA))
534       goto pass;
535
536     ea_flags = get_flags_novalue(ea);
537     if (isCode(ea_flags))
538     {
539       if (!decode_insn(ea))
540         goto pass;
541
542       if (is_insn_jmp(cmd.itype) && cmd.Operands[0].type == o_near
543         && cmd.Operands[0].dtyp == dt_dword)
544       {
545         jmp_near = 1;
546       }
547       else if ((cmd.itype == NN_pushf || cmd.itype == NN_popf)
548         && natop())
549       {
550         do_pushf = 1;
551       }
552
553       for (o = 0; o < UA_MAXOP; o++) {
554         const op_t &opr = cmd.Operands[o];
555         if (opr.type == o_void)
556           break;
557
558         // correct?
559         if (opr.type == o_mem && opr.specval_shorts.high == 0x21)
560           drop_large = 1;
561         if (opr.hasSIB && x86_scale(opr) == 0
562           && x86_index(opr) != INDEX_NONE)
563         {
564           set_scale = 1;
565         }
566         // annoying alignment variant..
567         if (opr.type == o_imm && opr.dtyp == dt_dword
568           && (opr.value < 0x80 || opr.value > 0xffffff80)
569           && cmd.size >= opr.offb + 4)
570         {
571           if (get_long(ea + opr.offb) == opr.value)
572             dword_imm = 1;
573         }
574         else if (opr.type == o_imm && opr.dtyp == dt_word
575           && (opr.value < 0x80 || opr.value > 0xff80)
576           && cmd.size >= opr.offb + 2)
577         {
578           if (get_word(ea + opr.offb) == (ushort)opr.value)
579             word_imm = 1;
580         }
581         else if (opr.type == o_displ && opr.addr == 0
582           && opr.offb != 0 && opr.hasSIB && opr.sib == 0x24)
583         {
584           // uses [esp+0] with 0 encoded into op
585           do_nops++;
586         }
587       }
588     }
589     else { // not code
590       if (isOff0(ea_flags))
591         do_rva = 1;
592     }
593
594 pass:
595     n = ln.get_linecnt();
596     for (i = pl.lnnum; i < n; i++) {
597       do_def_line(buf, sizeof(buf), ln.down(), ea);
598
599       char *fw;
600       for (fw = buf; *fw != 0 && *fw == ' '; )
601         fw++;
602
603       // patches..
604       if (drop_large) {
605         p = strstr(fw, "large ");
606         if (p != NULL)
607           memmove(p, p + 6, strlen(p + 6) + 1);
608       }
609       while (do_rva) {
610         p = strstr(fw, " rva ");
611         if (p == NULL)
612           break;
613         memmove(p + 4 + 3, p + 4, strlen(p + 4) + 1);
614         memcpy(p + 1, "offset", 6);
615       }
616       if (set_scale) {
617         p = strchr(fw, '[');
618         if (p != NULL)
619           p = strchr(p, '+');
620         if (p != NULL && p[1] == 'e') {
621           p += 4;
622           // scale is 1, must specify it explicitly so that
623           // masm chooses the right scaled reg
624           memmove(p + 2, p, strlen(p) + 1);
625           memcpy(p, "*1", 2);
626         }
627       }
628       else if (jmp_near) {
629         p = NULL;
630         if (fw != buf && fw[0] == 'j')
631           p = fw;
632         while (p && *p != ' ')
633           p++;
634         while (p && *p == ' ')
635           p++;
636         if (p != NULL) {
637           memmove(p + 9, p, strlen(p) + 1);
638           memcpy(p, "near ptr ", 9);
639           jmp_near = 0;
640         }
641       }
642       if (word_imm) {
643         p = strstr(fw, ", ");
644         if (p != NULL && '0' <= p[2] && p[2] <= '9') {
645           p += 2;
646           memmove(p + 9, p, strlen(p) + 1);
647           memcpy(p, "word ptr ", 9);
648         }
649       }
650       else if (dword_imm) {
651         p = strstr(fw, ", ");
652         if (p != NULL && '0' <= p[2] && p[2] <= '9') {
653           p += 2;
654           memmove(p + 10, p, strlen(p) + 1);
655           memcpy(p, "dword ptr ", 10);
656         }
657       }
658       else if (do_pushf) {
659         p = strstr(fw, "pushf");
660         if (p == NULL)
661           p = strstr(fw, "popf");
662         if (p != NULL) {
663           p = strchr(p, 'f') + 1;
664           memmove(p + 1, p, strlen(p) + 1);
665           *p = 'd';
666         }
667       }
668
669       if (fw[0] == 'a' && IS_START(fw, "assume cs")) {
670         // "assume cs" causes problems with ext syms
671         memmove(fw + 1, fw, strlen(fw) + 1);
672         *fw = ';';
673       }
674       else if (fw[0] == 'e' && IS_START(fw, "end") && fw[3] == ' ') {
675         fout_line++;
676         qfprintf(fout, "include public.inc\n\n");
677
678         // kill entry point
679         fw[3] = 0;
680       }
681
682       fout_line++;
683       qfprintf(fout, "%s\n", buf);
684     }
685
686     while (do_nops-- > 0)
687       qfprintf(fout, "                nop ; adj\n");
688
689     // note: next_head skips some undefined stuff
690     ea = next_not_tail(ea); // correct?
691     if (ea == BADADDR)
692       break;
693
694     pl.ea = ea;
695     pl.lnnum = 0;
696     ln.set_place(&pl);
697   }
698
699   if (fout != NULL)
700     qfclose(fout);
701   if (fname != NULL)
702     qfree(fname);
703
704   hide_wait_box();
705   msg("%d lines saved.\n", fout_line);
706 }
707
708 //--------------------------------------------------------------------------
709
710 static const char comment[] = "Generate disassembly lines for one address";
711 static const char help[] = "Generate asm file\n";
712 static const char wanted_name[] = "Save asm";
713 static const char wanted_hotkey[] = "Ctrl-F6";
714
715 //--------------------------------------------------------------------------
716 //
717 //      PLUGIN DESCRIPTION BLOCK
718 //
719 //--------------------------------------------------------------------------
720 plugin_t PLUGIN =
721 {
722   IDP_INTERFACE_VERSION,
723   0,                    // plugin flags
724   init,                 // initialize
725   term,                 // terminate. this pointer may be NULL.
726   run,                  // invoke plugin
727   comment,              // long comment about the plugin
728                         // it could appear in the status line
729                         // or as a hint
730   help,                 // multiline help about the plugin
731   wanted_name,          // the preferred short name of the plugin
732   wanted_hotkey         // the preferred hotkey to run the plugin
733 };
734
735 // vim:ts=2:shiftwidth=2:expandtab