Avoid a compiler warning.
[wine] / programs / winedbg / memory.c
1 /*
2  * Debugger memory handling
3  *
4  * Copyright 1993 Eric Youngdale
5  * Copyright 1995 Alexandre Julliard
6  * Copyright 2000-2004 Eric Pouech
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <stdlib.h>
27 #include <string.h>
28 #include <stdio.h>
29
30 #include "debugger.h"
31 #include "wine/debug.h"
32
33 WINE_DEFAULT_DEBUG_CHANNEL(winedbg);
34
35 void* be_cpu_linearize(HANDLE hThread, const ADDRESS* addr)
36 {
37     assert(addr->Mode == AddrModeFlat);
38     return (void*)addr->Offset;
39 }
40
41 unsigned be_cpu_build_addr(HANDLE hThread, const CONTEXT* ctx, ADDRESS* addr, 
42                            unsigned seg, unsigned long offset)
43 {
44     addr->Mode    = AddrModeFlat;
45     addr->Segment = 0; /* don't need segment */
46     addr->Offset  = offset;
47     return TRUE;
48 }
49
50 void* memory_to_linear_addr(const ADDRESS* addr)
51 {
52     return be_cpu->linearize(dbg_curr_thread->handle, addr);
53 }
54
55 BOOL memory_get_current_pc(ADDRESS* addr)
56 {
57     assert(be_cpu->get_addr);
58     return be_cpu->get_addr(dbg_curr_thread->handle, &dbg_context, 
59                             be_cpu_addr_pc, addr);
60 }
61
62 BOOL memory_get_current_stack(ADDRESS* addr)
63 {
64     assert(be_cpu->get_addr);
65     return be_cpu->get_addr(dbg_curr_thread->handle, &dbg_context, 
66                             be_cpu_addr_stack, addr);
67 }
68
69 BOOL memory_get_current_frame(ADDRESS* addr)
70 {
71     assert(be_cpu->get_addr);
72     return be_cpu->get_addr(dbg_curr_thread->handle, &dbg_context, 
73                             be_cpu_addr_frame, addr);
74 }
75
76 void    memory_report_invalid_addr(const void* addr)
77 {
78     ADDRESS     address;
79
80     address.Mode    = AddrModeFlat;
81     address.Segment = 0;
82     address.Offset  = (unsigned long)addr;
83     dbg_printf("*** Invalid address ");
84     print_address(&address, FALSE);
85     dbg_printf("\n");
86 }
87
88 /***********************************************************************
89  *           memory_read_value
90  *
91  * Read a memory value.
92  */
93 BOOL memory_read_value(const struct dbg_lvalue* lvalue, DWORD size, void* result)
94 {
95     if (lvalue->cookie == DLV_TARGET)
96     {
97         if (!dbg_read_memory_verbose(memory_to_linear_addr(&lvalue->addr), result, size))
98             return FALSE;
99     }
100     else
101     {
102         if (!lvalue->addr.Offset) return FALSE;
103         memcpy(result, (void*)lvalue->addr.Offset, size);
104     }
105     return TRUE;
106 }
107
108 /***********************************************************************
109  *           memory_write_value
110  *
111  * Store a value in memory.
112  */
113 BOOL memory_write_value(const struct dbg_lvalue* lvalue, DWORD size, void* value)
114 {
115     BOOL        ret = TRUE;
116     DWORD       os;
117     DWORD       linear = (DWORD)memory_to_linear_addr(&lvalue->addr);
118
119     os = ~size;
120     types_get_info(&lvalue->type, TI_GET_LENGTH, &os);
121     assert(size == os);
122
123     /* FIXME: only works on little endian systems */
124     if (lvalue->cookie == DLV_TARGET)
125     {
126         ret = dbg_write_memory_verbose((void*)linear, value, size);
127     }
128     else 
129     {
130         memcpy((void*)lvalue->addr.Offset, value, size);
131     }
132     return ret;
133 }
134
135 /***********************************************************************
136  *           memory_examine
137  *
138  * Implementation of the 'x' command.
139  */
140 void memory_examine(const struct dbg_lvalue *lvalue, int count, char format)
141 {
142     int                 i;
143     char                buffer[256];
144     ADDRESS             addr;
145     void               *linear;
146
147     if (lvalue->type.id == dbg_itype_none) addr = lvalue->addr;
148     else
149     {
150         addr.Mode = AddrModeFlat;
151         addr.Offset = types_extract_as_integer( lvalue );
152     }
153     linear = memory_to_linear_addr( &addr );
154
155     if (format != 'i' && count > 1)
156     {
157         print_address(&addr, FALSE);
158         dbg_printf(": ");
159     }
160
161     switch (format)
162     {
163     case 'u':
164         if (count == 1) count = 256;
165         memory_get_string(dbg_curr_process->handle, linear, 
166                           TRUE, TRUE, buffer, min(count, sizeof(buffer)));
167         dbg_printf("%s\n", buffer);
168         return;
169     case 's':
170         if (count == 1) count = 256;
171         memory_get_string(dbg_curr_process->handle, linear,
172                           TRUE, FALSE, buffer, min(count, sizeof(buffer)));
173         dbg_printf("%s\n", buffer);
174         return;
175     case 'i':
176         while (count-- && memory_disasm_one_insn(&addr));
177         return;
178     case 'g':
179         while (count--)
180         {
181             GUID guid;
182             if (!dbg_read_memory_verbose(linear, &guid, sizeof(guid))) break;
183             dbg_printf("{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n",
184                        guid.Data1, guid.Data2, guid.Data3,
185                        guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
186                        guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
187             linear = (char*)linear + sizeof(guid);
188             addr.Offset += sizeof(guid);
189             if (count)
190             {
191                 print_address(&addr, FALSE);
192                 dbg_printf(": ");
193             }
194         }
195         return;
196
197 #define DO_DUMP2(_t,_l,_f,_vv) {                                        \
198             _t _v;                                                      \
199             for (i = 0; i < count; i++) {                               \
200                 if (!dbg_read_memory_verbose(linear, &_v,               \
201                                              sizeof(_t))) break;        \
202                 dbg_printf(_f, (_vv));                                  \
203                 addr.Offset += sizeof(_t);                              \
204                 linear = (char*)linear + sizeof(_t);                    \
205                 if ((i % (_l)) == (_l) - 1 && i != count - 1)           \
206                 {                                                       \
207                     dbg_printf("\n");                                   \
208                     print_address(&addr, FALSE);                        \
209                     dbg_printf(": ");                                   \
210                 }                                                       \
211             }                                                           \
212             dbg_printf("\n");                                           \
213         }                                                               \
214         return
215 #define DO_DUMP(_t,_l,_f) DO_DUMP2(_t,_l,_f,_v)
216
217     case 'x': DO_DUMP(int, 4, " %8.8x");
218     case 'd': DO_DUMP(unsigned int, 4, " %10d");
219     case 'w': DO_DUMP(unsigned short, 8, " %04x");
220     case 'c': DO_DUMP2(char, 32, " %c", (_v < 0x20) ? ' ' : _v);
221     case 'b': DO_DUMP2(char, 16, " %02x", (_v) & 0xff);
222     }
223 }
224
225 BOOL memory_get_string(HANDLE hp, void* addr, BOOL in_debuggee, BOOL unicode, 
226                        char* buffer, int size)
227 {
228     DWORD       sz;
229     WCHAR*      buffW;
230
231     buffer[0] = 0;
232     if (!addr) return FALSE;
233     if (in_debuggee)
234     {
235         if (!unicode) return ReadProcessMemory(hp, addr, buffer, size, &sz);
236
237         buffW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
238         ReadProcessMemory(hp, addr, buffW, size * sizeof(WCHAR), &sz);
239         WideCharToMultiByte(CP_ACP, 0, buffW, sz / sizeof(WCHAR), buffer, size, 
240                             NULL, NULL);
241         HeapFree(GetProcessHeap(), 0, buffW);
242     }
243     else
244     {
245         strncpy(buffer, addr, size);
246         buffer[size - 1] = 0;
247     }
248     return TRUE;
249 }
250
251 BOOL memory_get_string_indirect(HANDLE hp, void* addr, BOOL unicode, char* buffer, int size)
252 {
253     void*       ad;
254     DWORD       sz;
255
256     buffer[0] = 0;
257     if (addr && 
258         ReadProcessMemory(hp, addr, &ad, sizeof(ad), &sz) && sz == sizeof(ad) && ad)
259     {
260         return memory_get_string(hp, ad, TRUE, unicode, buffer, size);
261     }
262     return FALSE;
263 }
264
265 static void print_typed_basic(const struct dbg_lvalue* lvalue)
266 {
267     long long int       val_int;
268     void*               val_ptr;
269     long double         val_real;
270     DWORD               tag, size, count, bt;
271     struct dbg_type     rtype;
272
273     if (lvalue->type.id == dbg_itype_none ||
274         !types_get_info(&lvalue->type, TI_GET_SYMTAG, &tag))
275         return;
276
277     switch (tag)
278     {
279     case SymTagBaseType:
280         if (!types_get_info(&lvalue->type, TI_GET_LENGTH, &size) ||
281             !types_get_info(&lvalue->type, TI_GET_BASETYPE, &bt))
282         {
283             WINE_ERR("Couldn't get information\n");
284             RaiseException(DEBUG_STATUS_INTERNAL_ERROR, 0, 0, NULL);
285         }
286
287         switch (bt)
288         {
289         case btInt:
290             if (!be_cpu->fetch_integer(lvalue, size, TRUE, &val_int)) return;
291             dbg_printf("%lld", val_int);
292             break;
293         case btUInt:
294             if (!be_cpu->fetch_integer(lvalue, size, FALSE, &val_int)) return;
295             dbg_printf("%llu", val_int);
296             break;
297         case btFloat:
298             if (!be_cpu->fetch_float(lvalue, size, &val_real)) return;
299             dbg_printf("%Lf", val_real);
300             break;
301         case btChar:
302             if (!be_cpu->fetch_integer(lvalue, size, TRUE, &val_int)) return;
303             /* FIXME: should do the same for a Unicode character (size == 2) */
304             if (size == 1 && (val_int < 0x20 || val_int > 0x80))
305                 dbg_printf("%d", (int)val_int);
306             else
307                 dbg_printf("'%c'", (char)val_int);
308             break;
309         default:
310             WINE_FIXME("Unsupported basetype %lu\n", bt);
311             break;
312         }
313         break;
314     case SymTagPointerType:
315         if (!memory_read_value(lvalue, sizeof(void*), &val_ptr)) return;
316
317         if (!types_get_info(&lvalue->type, TI_GET_TYPE, &rtype.id) ||
318             rtype.id == dbg_itype_none)
319         {
320             dbg_printf("Internal symbol error: unable to access memory location %p", val_ptr);
321             break;
322         }
323         rtype.module = lvalue->type.module;
324         if (types_get_info(&rtype, TI_GET_SYMTAG, &tag) && tag == SymTagBaseType &&
325             types_get_info(&rtype, TI_GET_BASETYPE, &bt) && bt == btChar &&
326             types_get_info(&rtype, TI_GET_LENGTH, &size))
327         {
328             char    buffer[1024];
329
330             memory_get_string(dbg_curr_process->handle, val_ptr, 
331                               lvalue->cookie == DLV_TARGET,
332                               size == 2, buffer, sizeof(buffer));
333             dbg_printf("\"%s\"", buffer);
334         }
335         else dbg_printf("%p", val_ptr);
336         break;
337     case SymTagArrayType:
338     case SymTagUDT:
339         assert(lvalue->cookie == DLV_TARGET);
340         if (!memory_read_value(lvalue, sizeof(val_ptr), &val_ptr)) return;
341         dbg_printf("%p", val_ptr);
342         break;
343     case SymTagEnum:
344         {
345             BOOL        ok = FALSE;
346
347             assert(lvalue->cookie == DLV_TARGET);
348             /* FIXME: it depends on underlying type for enums 
349              * (not supported yet in dbghelp)
350              * Assuming 4 as for an int
351              */
352             if (!be_cpu->fetch_integer(lvalue, 4, TRUE, &val_int)) return;
353
354             if (types_get_info(&lvalue->type, TI_GET_CHILDRENCOUNT, &count))
355             {
356                 char                    buffer[sizeof(TI_FINDCHILDREN_PARAMS) + 256 * sizeof(DWORD)];
357                 TI_FINDCHILDREN_PARAMS* fcp = (TI_FINDCHILDREN_PARAMS*)buffer;
358                 WCHAR*                  ptr;
359                 char                    tmp[256];
360                 VARIANT                 variant;
361                 int                     i;
362                 struct dbg_type         type;
363
364                 fcp->Start = 0;
365                 while (count)
366                 {
367                     fcp->Count = min(count, 256);
368                     if (types_get_info(&lvalue->type, TI_FINDCHILDREN, fcp))
369                     {
370                         type.module = lvalue->type.module;
371                         for (i = 0; i < min(fcp->Count, count); i++)
372                         {
373                             type.id = fcp->ChildId[i];
374                             if (!types_get_info(&type, TI_GET_VALUE, &variant)) 
375                                 continue;
376                             switch (variant.n1.n2.vt)
377                             {
378                             case VT_I4: ok = (val_int == variant.n1.n2.n3.lVal); break;
379                             default: WINE_FIXME("Unsupported variant type (%u)\n", variant.n1.n2.vt);
380                             }
381                             if (ok)
382                             {
383                                 ptr = NULL;
384                                 types_get_info(&type, TI_GET_SYMNAME, &ptr);
385                                 if (!ptr) continue;
386                                 WideCharToMultiByte(CP_ACP, 0, ptr, -1, tmp, sizeof(tmp), NULL, NULL);
387                                 HeapFree(GetProcessHeap(), 0, ptr);
388                                 dbg_printf("%s", tmp);
389                                 count = 0; /* so that we'll get away from outter loop */
390                                 break;
391                             }
392                         }
393                     }
394                 }
395                 count -= min(count, 256);
396                 fcp->Start += 256;
397             }
398             if (!ok) dbg_printf("%lld", val_int);
399         }
400         break;
401     default:
402         WINE_FIXME("Unsupported tag %lu\n", tag);
403         break;
404     }
405 }
406
407 /***********************************************************************
408  *           print_basic
409  *
410  * Implementation of the 'print' command.
411  */
412 void print_basic(const struct dbg_lvalue* lvalue, int count, char format)
413 {
414     long int    res;
415
416     if (lvalue->type.id == dbg_itype_none)
417     {
418         dbg_printf("Unable to evaluate expression\n");
419         return;
420     }
421
422     res = types_extract_as_integer(lvalue);
423
424     /* FIXME: this implies i386 byte ordering */
425     switch (format)
426     {
427     case 'x':
428         if (lvalue->addr.Mode != AddrModeFlat)
429             dbg_printf("0x%04lx", res);
430         else
431             dbg_printf("0x%08lx", res);
432         break;
433
434     case 'd':
435         dbg_printf("%ld\n", res);
436         break;
437
438     case 'c':
439         dbg_printf("%d = '%c'", (char)(res & 0xff), (char)(res & 0xff));
440         break;
441
442     case 'u':
443         {
444             WCHAR wch = (WCHAR)(res & 0xFFFF);
445             dbg_printf("%d = '", wch);
446             dbg_outputW(&wch, 1);
447             dbg_printf("'");
448         }
449         break;
450
451     case 'i':
452     case 's':
453     case 'w':
454     case 'b':
455         dbg_printf("Format specifier '%c' is meaningless in 'print' command\n", format);
456     case 0:
457         print_typed_basic(lvalue);
458         break;
459     }
460 }
461
462 void print_bare_address(const ADDRESS* addr)
463 {
464     switch (addr->Mode)
465     {
466     case AddrModeFlat: 
467         dbg_printf("0x%08lx", addr->Offset); 
468         break;
469     case AddrModeReal:
470     case AddrMode1616:
471         dbg_printf("0x%04x:0x%04lx", addr->Segment, addr->Offset);
472         break;
473     case AddrMode1632:
474         dbg_printf("0x%04x:0x%08lx", addr->Segment, addr->Offset);
475         break;
476     default:
477         dbg_printf("Unknown mode %x\n", addr->Mode);
478         break;
479     }
480 }
481
482 /***********************************************************************
483  *           print_address
484  *
485  * Print an 16- or 32-bit address, with the nearest symbol if any.
486  */
487 void print_address(const ADDRESS* addr, BOOLEAN with_line)
488 {
489     char                buffer[sizeof(SYMBOL_INFO) + 256];
490     SYMBOL_INFO*        si = (SYMBOL_INFO*)buffer;
491     void*               lin = memory_to_linear_addr(addr);
492     DWORD64             disp64;
493     DWORD               disp;
494
495     print_bare_address(addr);
496
497     si->SizeOfStruct = sizeof(*si);
498     si->MaxNameLen   = 256;
499     if (!SymFromAddr(dbg_curr_process->handle, (DWORD_PTR)lin, &disp64, si)) return;
500     dbg_printf(" %s", si->Name);
501     if (disp64) dbg_printf("+0x%lx", (DWORD_PTR)disp64);
502     if (with_line)
503     {
504         IMAGEHLP_LINE               il;
505         IMAGEHLP_MODULE             im;
506
507         il.SizeOfStruct = sizeof(il);
508         if (SymGetLineFromAddr(dbg_curr_process->handle, (DWORD_PTR)lin, &disp, &il))
509             dbg_printf(" [%s:%lu]", il.FileName, il.LineNumber);
510         im.SizeOfStruct = sizeof(im);
511         if (SymGetModuleInfo(dbg_curr_process->handle, (DWORD_PTR)lin, &im))
512             dbg_printf(" in %s", im.ModuleName);
513     }
514 }
515
516 struct sym_enum
517 {
518     char*       tmp;
519     DWORD       frame;
520 };
521
522 static BOOL WINAPI sym_enum_cb(SYMBOL_INFO* sym_info, ULONG size, void* user)
523 {
524     struct sym_enum*    se = (struct sym_enum*)user;
525     DWORD               addr;
526     unsigned            val;
527     long                offset;
528
529     if ((sym_info->Flags & (SYMFLAG_PARAMETER|SYMFLAG_FRAMEREL)) == (SYMFLAG_PARAMETER|SYMFLAG_FRAMEREL))
530     {
531         struct dbg_type     type;
532
533         if (se->tmp[0]) strcat(se->tmp, ", ");
534         addr = se->frame;
535         type.module = sym_info->ModBase;
536         type.id = sym_info->TypeIndex;
537         types_get_info(&type, TI_GET_OFFSET, &offset);
538         addr += offset;
539         dbg_read_memory_verbose((char*)addr, &val, sizeof(val));
540         sprintf(se->tmp + strlen(se->tmp), "%s=0x%x", sym_info->Name, val);
541     }
542     return TRUE;
543 }
544
545 void print_addr_and_args(const ADDRESS* pc, const ADDRESS* frame)
546 {
547     char                        buffer[sizeof(SYMBOL_INFO) + 256];
548     SYMBOL_INFO*                si = (SYMBOL_INFO*)buffer;
549     IMAGEHLP_STACK_FRAME        isf;
550     IMAGEHLP_LINE               il;
551     IMAGEHLP_MODULE             im;
552     DWORD64                     disp64;
553
554     print_bare_address(pc);
555
556     isf.InstructionOffset = (DWORD_PTR)memory_to_linear_addr(pc);
557     isf.FrameOffset       = (DWORD_PTR)memory_to_linear_addr(frame);
558
559     /* grab module where symbol is. If we don't have a module, we cannot print more */
560     im.SizeOfStruct = sizeof(im);
561     if (!SymGetModuleInfo(dbg_curr_process->handle, isf.InstructionOffset, &im))
562         return;
563
564     si->SizeOfStruct = sizeof(*si);
565     si->MaxNameLen   = 256;
566     if (SymFromAddr(dbg_curr_process->handle, isf.InstructionOffset, &disp64, si))
567     {
568         struct sym_enum se;
569         char            tmp[1024];
570         DWORD           disp;
571
572         dbg_printf(" %s", si->Name);
573         if (disp) dbg_printf("+0x%lx", (DWORD_PTR)disp64);
574
575         SymSetContext(dbg_curr_process->handle, &isf, NULL);
576         se.tmp = tmp;
577         se.frame = isf.FrameOffset;
578         tmp[0] = '\0';
579         SymEnumSymbols(dbg_curr_process->handle, 0, NULL, sym_enum_cb, &se);
580         if (tmp[0]) dbg_printf("(%s)", tmp);
581
582         il.SizeOfStruct = sizeof(il);
583         if (SymGetLineFromAddr(dbg_curr_process->handle, isf.InstructionOffset,
584                                &disp, &il))
585             dbg_printf(" [%s:%lu]", il.FileName, il.LineNumber);
586         dbg_printf(" in %s", im.ModuleName);
587     }
588     else dbg_printf(" in %s (+0x%lx)", 
589                     im.ModuleName, (DWORD_PTR)(isf.InstructionOffset - im.BaseOfImage));
590 }
591
592 BOOL memory_disasm_one_insn(ADDRESS* addr)
593 {
594     char        ch;
595
596     print_address(addr, TRUE);
597     dbg_printf(": ");
598     if (!dbg_read_memory(memory_to_linear_addr(addr), &ch, sizeof(ch)))
599     {
600         dbg_printf("-- no code accessible --\n");
601         return FALSE;
602     }
603     be_cpu->disasm_one_insn(addr, TRUE);
604     dbg_printf("\n");
605     return TRUE;
606 }
607
608 void memory_disassemble(const struct dbg_lvalue* xstart, 
609                         const struct dbg_lvalue* xend, int instruction_count)
610 {
611     static ADDRESS last = {0,0,0};
612     int stop = 0;
613     int i;
614
615     if (!xstart && !xend) 
616     {
617         if (!last.Segment && !last.Offset) memory_get_current_pc(&last);
618     }
619     else
620     {
621         if (xstart)
622         {
623             last.Mode = AddrModeFlat;
624             last.Offset = types_extract_as_integer(xstart);
625         }
626         if (xend) 
627             stop = types_extract_as_integer(xend);
628     }
629     for (i = 0; (instruction_count == 0 || i < instruction_count)  &&
630                 (stop == 0 || last.Offset <= stop); i++)
631         memory_disasm_one_insn(&last);
632 }