Added Finnish resources.
[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 static 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     BOOL ret = FALSE;
96
97     if (lvalue->cookie == DLV_TARGET)
98     {
99         void*   linear = memory_to_linear_addr(&lvalue->addr);
100         if (!(ret = dbg_read_memory(linear, result, size)))
101             memory_report_invalid_addr(linear);
102     }
103     else
104     {
105         if (lvalue->addr.Offset)
106         {
107             memcpy(result, (void*)lvalue->addr.Offset, size);
108             ret = TRUE;
109         }
110     }
111     return TRUE;
112 }
113
114 /***********************************************************************
115  *           memory_write_value
116  *
117  * Store a value in memory.
118  */
119 BOOL memory_write_value(const struct dbg_lvalue* lvalue, DWORD size, void* value)
120 {
121     BOOL        ret = TRUE;
122     DWORD       os;
123
124     os = ~size;
125     types_get_info(&lvalue->type, TI_GET_LENGTH, &os);
126     assert(size == os);
127
128     /* FIXME: only works on little endian systems */
129     if (lvalue->cookie == DLV_TARGET)
130     {
131         void*       linear = memory_to_linear_addr(&lvalue->addr);
132         if (!(ret = dbg_write_memory(linear, value, size)))
133             memory_report_invalid_addr(linear);
134     }
135     else 
136     {
137         memcpy((void*)lvalue->addr.Offset, value, size);
138     }
139     return ret;
140 }
141
142 /***********************************************************************
143  *           memory_examine
144  *
145  * Implementation of the 'x' command.
146  */
147 void memory_examine(const struct dbg_lvalue *lvalue, int count, char format)
148 {
149     int                 i;
150     char                buffer[256];
151     ADDRESS             addr;
152     void               *linear;
153
154     if (lvalue->type.id == dbg_itype_none) addr = lvalue->addr;
155     else
156     {
157         addr.Mode = AddrModeFlat;
158         addr.Offset = types_extract_as_integer( lvalue );
159     }
160     linear = memory_to_linear_addr( &addr );
161
162     if (format != 'i' && count > 1)
163     {
164         print_address(&addr, FALSE);
165         dbg_printf(": ");
166     }
167
168     switch (format)
169     {
170     case 'u':
171         if (count == 1) count = 256;
172         memory_get_string(dbg_curr_process, linear, 
173                           TRUE, TRUE, buffer, min(count, sizeof(buffer)));
174         dbg_printf("%s\n", buffer);
175         return;
176     case 's':
177         if (count == 1) count = 256;
178         memory_get_string(dbg_curr_process, linear,
179                           TRUE, FALSE, buffer, min(count, sizeof(buffer)));
180         dbg_printf("%s\n", buffer);
181         return;
182     case 'i':
183         while (count-- && memory_disasm_one_insn(&addr));
184         return;
185     case 'g':
186         while (count--)
187         {
188             GUID guid;
189             if (!dbg_read_memory(linear, &guid, sizeof(guid)))
190             {
191                 memory_report_invalid_addr(linear);
192                 break;
193             }
194             dbg_printf("{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}\n",
195                        guid.Data1, guid.Data2, guid.Data3,
196                        guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
197                        guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
198             linear = (char*)linear + sizeof(guid);
199             addr.Offset += sizeof(guid);
200             if (count)
201             {
202                 print_address(&addr, FALSE);
203                 dbg_printf(": ");
204             }
205         }
206         return;
207
208 #define DO_DUMP2(_t,_l,_f,_vv) {                                        \
209             _t _v;                                                      \
210             for (i = 0; i < count; i++) {                               \
211                 if (!dbg_read_memory(linear, &_v, sizeof(_t)))          \
212                 { memory_report_invalid_addr(linear); break; }          \
213                 dbg_printf(_f, (_vv));                                  \
214                 addr.Offset += sizeof(_t);                              \
215                 linear = (char*)linear + sizeof(_t);                    \
216                 if ((i % (_l)) == (_l) - 1 && i != count - 1)           \
217                 {                                                       \
218                     dbg_printf("\n");                                   \
219                     print_address(&addr, FALSE);                        \
220                     dbg_printf(": ");                                   \
221                 }                                                       \
222             }                                                           \
223             dbg_printf("\n");                                           \
224         }                                                               \
225         return
226 #define DO_DUMP(_t,_l,_f) DO_DUMP2(_t,_l,_f,_v)
227
228     case 'x': DO_DUMP(int, 4, " %8.8x");
229     case 'd': DO_DUMP(unsigned int, 4, " %10d");
230     case 'w': DO_DUMP(unsigned short, 8, " %04x");
231     case 'c': DO_DUMP2(char, 32, " %c", (_v < 0x20) ? ' ' : _v);
232     case 'b': DO_DUMP2(char, 16, " %02x", (_v) & 0xff);
233     }
234 }
235
236 BOOL memory_get_string(struct dbg_process* pcs, void* addr, BOOL in_debuggee,
237                        BOOL unicode, char* buffer, int size)
238 {
239     DWORD       sz;
240     WCHAR*      buffW;
241
242     buffer[0] = 0;
243     if (!addr) return FALSE;
244     if (in_debuggee)
245     {
246         BOOL ret;
247
248         if (!unicode) ret = pcs->process_io->read(pcs->handle, addr, buffer, size, &sz);
249         else
250         {
251             buffW = HeapAlloc(GetProcessHeap(), 0, size * sizeof(WCHAR));
252             ret = pcs->process_io->read(pcs->handle, addr, buffW, size * sizeof(WCHAR), &sz);
253             WideCharToMultiByte(CP_ACP, 0, buffW, sz / sizeof(WCHAR), buffer, size,
254                                 NULL, NULL);
255             HeapFree(GetProcessHeap(), 0, buffW);
256         }
257         if (size) buffer[size-1] = 0;
258         return ret;
259     }
260     else
261     {
262         lstrcpynA(buffer, addr, size);
263     }
264     return TRUE;
265 }
266
267 BOOL memory_get_string_indirect(struct dbg_process* pcs, void* addr, BOOL unicode, char* buffer, int size)
268 {
269     void*       ad;
270     DWORD       sz;
271
272     buffer[0] = 0;
273     if (addr && 
274         pcs->process_io->read(pcs->handle, addr, &ad, sizeof(ad), &sz) && sz == sizeof(ad) && ad)
275     {
276         return memory_get_string(pcs, ad, TRUE, unicode, buffer, size);
277     }
278     return FALSE;
279 }
280
281 static void print_typed_basic(const struct dbg_lvalue* lvalue)
282 {
283     long long int       val_int;
284     void*               val_ptr;
285     long double         val_real;
286     DWORD               tag, size, count, bt;
287     struct dbg_type     rtype;
288
289     if (lvalue->type.id == dbg_itype_none ||
290         !types_get_info(&lvalue->type, TI_GET_SYMTAG, &tag))
291         return;
292
293     switch (tag)
294     {
295     case SymTagBaseType:
296         if (!types_get_info(&lvalue->type, TI_GET_LENGTH, &size) ||
297             !types_get_info(&lvalue->type, TI_GET_BASETYPE, &bt))
298         {
299             WINE_ERR("Couldn't get information\n");
300             RaiseException(DEBUG_STATUS_INTERNAL_ERROR, 0, 0, NULL);
301         }
302
303         switch (bt)
304         {
305         case btInt:
306             if (!be_cpu->fetch_integer(lvalue, size, TRUE, &val_int)) return;
307             dbg_printf("%lld", val_int);
308             break;
309         case btUInt:
310             if (!be_cpu->fetch_integer(lvalue, size, FALSE, &val_int)) return;
311             dbg_printf("%llu", val_int);
312             break;
313         case btFloat:
314             if (!be_cpu->fetch_float(lvalue, size, &val_real)) return;
315             dbg_printf("%Lf", val_real);
316             break;
317         case btChar:
318             if (!be_cpu->fetch_integer(lvalue, size, TRUE, &val_int)) return;
319             /* FIXME: should do the same for a Unicode character (size == 2) */
320             if (size == 1 && (val_int < 0x20 || val_int > 0x80))
321                 dbg_printf("%d", (int)val_int);
322             else
323                 dbg_printf("'%c'", (char)val_int);
324             break;
325         default:
326             WINE_FIXME("Unsupported basetype %lu\n", bt);
327             break;
328         }
329         break;
330     case SymTagPointerType:
331         if (!memory_read_value(lvalue, sizeof(void*), &val_ptr)) return;
332
333         if (!types_get_info(&lvalue->type, TI_GET_TYPE, &rtype.id) ||
334             rtype.id == dbg_itype_none)
335         {
336             dbg_printf("Internal symbol error: unable to access memory location %p", val_ptr);
337             break;
338         }
339         rtype.module = lvalue->type.module;
340         if (types_get_info(&rtype, TI_GET_SYMTAG, &tag) && tag == SymTagBaseType &&
341             types_get_info(&rtype, TI_GET_BASETYPE, &bt) && bt == btChar &&
342             types_get_info(&rtype, TI_GET_LENGTH, &size))
343         {
344             char    buffer[1024];
345
346             memory_get_string(dbg_curr_process, val_ptr, 
347                               lvalue->cookie == DLV_TARGET,
348                               size == 2, buffer, sizeof(buffer));
349             dbg_printf("\"%s\"", buffer);
350         }
351         else dbg_printf("%p", val_ptr);
352         break;
353     case SymTagArrayType:
354     case SymTagUDT:
355         assert(lvalue->cookie == DLV_TARGET);
356         if (!memory_read_value(lvalue, sizeof(val_ptr), &val_ptr)) return;
357         dbg_printf("%p", val_ptr);
358         break;
359     case SymTagEnum:
360         {
361             BOOL        ok = FALSE;
362
363             assert(lvalue->cookie == DLV_TARGET);
364             /* FIXME: it depends on underlying type for enums 
365              * (not supported yet in dbghelp)
366              * Assuming 4 as for an int
367              */
368             if (!be_cpu->fetch_integer(lvalue, 4, TRUE, &val_int)) return;
369
370             if (types_get_info(&lvalue->type, TI_GET_CHILDRENCOUNT, &count))
371             {
372                 char                    buffer[sizeof(TI_FINDCHILDREN_PARAMS) + 256 * sizeof(DWORD)];
373                 TI_FINDCHILDREN_PARAMS* fcp = (TI_FINDCHILDREN_PARAMS*)buffer;
374                 WCHAR*                  ptr;
375                 char                    tmp[256];
376                 VARIANT                 variant;
377                 int                     i;
378                 struct dbg_type         type;
379
380                 fcp->Start = 0;
381                 while (count)
382                 {
383                     fcp->Count = min(count, 256);
384                     if (types_get_info(&lvalue->type, TI_FINDCHILDREN, fcp))
385                     {
386                         type.module = lvalue->type.module;
387                         for (i = 0; i < min(fcp->Count, count); i++)
388                         {
389                             type.id = fcp->ChildId[i];
390                             if (!types_get_info(&type, TI_GET_VALUE, &variant)) 
391                                 continue;
392                             switch (variant.n1.n2.vt)
393                             {
394                             case VT_I4: ok = (val_int == variant.n1.n2.n3.lVal); break;
395                             default: WINE_FIXME("Unsupported variant type (%u)\n", variant.n1.n2.vt);
396                             }
397                             if (ok)
398                             {
399                                 ptr = NULL;
400                                 types_get_info(&type, TI_GET_SYMNAME, &ptr);
401                                 if (!ptr) continue;
402                                 WideCharToMultiByte(CP_ACP, 0, ptr, -1, tmp, sizeof(tmp), NULL, NULL);
403                                 HeapFree(GetProcessHeap(), 0, ptr);
404                                 dbg_printf("%s", tmp);
405                                 count = 0; /* so that we'll get away from outter loop */
406                                 break;
407                             }
408                         }
409                     }
410                 }
411                 count -= min(count, 256);
412                 fcp->Start += 256;
413             }
414             if (!ok) dbg_printf("%lld", val_int);
415         }
416         break;
417     default:
418         WINE_FIXME("Unsupported tag %lu\n", tag);
419         break;
420     }
421 }
422
423 /***********************************************************************
424  *           print_basic
425  *
426  * Implementation of the 'print' command.
427  */
428 void print_basic(const struct dbg_lvalue* lvalue, int count, char format)
429 {
430     long int    res;
431
432     if (lvalue->type.id == dbg_itype_none)
433     {
434         dbg_printf("Unable to evaluate expression\n");
435         return;
436     }
437
438     res = types_extract_as_integer(lvalue);
439
440     /* FIXME: this implies i386 byte ordering */
441     switch (format)
442     {
443     case 'x':
444         if (lvalue->addr.Mode != AddrModeFlat)
445             dbg_printf("0x%04lx", res);
446         else
447             dbg_printf("0x%08lx", res);
448         break;
449
450     case 'd':
451         dbg_printf("%ld\n", res);
452         break;
453
454     case 'c':
455         dbg_printf("%d = '%c'", (char)(res & 0xff), (char)(res & 0xff));
456         break;
457
458     case 'u':
459         {
460             WCHAR wch = (WCHAR)(res & 0xFFFF);
461             dbg_printf("%d = '", wch);
462             dbg_outputW(&wch, 1);
463             dbg_printf("'");
464         }
465         break;
466
467     case 'i':
468     case 's':
469     case 'w':
470     case 'b':
471         dbg_printf("Format specifier '%c' is meaningless in 'print' command\n", format);
472     case 0:
473         print_typed_basic(lvalue);
474         break;
475     }
476 }
477
478 void print_bare_address(const ADDRESS* addr)
479 {
480     switch (addr->Mode)
481     {
482     case AddrModeFlat: 
483         dbg_printf("0x%08lx", addr->Offset); 
484         break;
485     case AddrModeReal:
486     case AddrMode1616:
487         dbg_printf("0x%04x:0x%04lx", addr->Segment, addr->Offset);
488         break;
489     case AddrMode1632:
490         dbg_printf("0x%04x:0x%08lx", addr->Segment, addr->Offset);
491         break;
492     default:
493         dbg_printf("Unknown mode %x\n", addr->Mode);
494         break;
495     }
496 }
497
498 /***********************************************************************
499  *           print_address
500  *
501  * Print an 16- or 32-bit address, with the nearest symbol if any.
502  */
503 void print_address(const ADDRESS* addr, BOOLEAN with_line)
504 {
505     char                buffer[sizeof(SYMBOL_INFO) + 256];
506     SYMBOL_INFO*        si = (SYMBOL_INFO*)buffer;
507     void*               lin = memory_to_linear_addr(addr);
508     DWORD64             disp64;
509     DWORD               disp;
510
511     print_bare_address(addr);
512
513     si->SizeOfStruct = sizeof(*si);
514     si->MaxNameLen   = 256;
515     if (!SymFromAddr(dbg_curr_process->handle, (DWORD_PTR)lin, &disp64, si)) return;
516     dbg_printf(" %s", si->Name);
517     if (disp64) dbg_printf("+0x%lx", (DWORD_PTR)disp64);
518     if (with_line)
519     {
520         IMAGEHLP_LINE               il;
521         IMAGEHLP_MODULE             im;
522
523         il.SizeOfStruct = sizeof(il);
524         if (SymGetLineFromAddr(dbg_curr_process->handle, (DWORD_PTR)lin, &disp, &il))
525             dbg_printf(" [%s:%lu]", il.FileName, il.LineNumber);
526         im.SizeOfStruct = sizeof(im);
527         if (SymGetModuleInfo(dbg_curr_process->handle, (DWORD_PTR)lin, &im))
528             dbg_printf(" in %s", im.ModuleName);
529     }
530 }
531
532 struct sym_enum
533 {
534     char*       tmp;
535     DWORD       frame;
536 };
537
538 static BOOL WINAPI sym_enum_cb(SYMBOL_INFO* sym_info, ULONG size, void* user)
539 {
540     struct sym_enum*    se = (struct sym_enum*)user;
541     DWORD               addr;
542     unsigned            val;
543     long                offset;
544
545     if ((sym_info->Flags & (SYMFLAG_PARAMETER|SYMFLAG_FRAMEREL)) == (SYMFLAG_PARAMETER|SYMFLAG_FRAMEREL))
546     {
547         struct dbg_type     type;
548
549         if (se->tmp[0]) strcat(se->tmp, ", ");
550         addr = se->frame;
551         type.module = sym_info->ModBase;
552         type.id = sym_info->TypeIndex;
553         types_get_info(&type, TI_GET_OFFSET, &offset);
554         addr += offset;
555         if (dbg_read_memory((char*)addr, &val, sizeof(val)))
556             sprintf(se->tmp + strlen(se->tmp), "%s=0x%x", sym_info->Name, val);
557         else
558             sprintf(se->tmp + strlen(se->tmp), "%s=<\?\?\?>", sym_info->Name);
559     }
560     return TRUE;
561 }
562
563 void print_addr_and_args(const ADDRESS* pc, const ADDRESS* frame)
564 {
565     char                        buffer[sizeof(SYMBOL_INFO) + 256];
566     SYMBOL_INFO*                si = (SYMBOL_INFO*)buffer;
567     IMAGEHLP_STACK_FRAME        isf;
568     IMAGEHLP_LINE               il;
569     IMAGEHLP_MODULE             im;
570     DWORD64                     disp64;
571
572     print_bare_address(pc);
573
574     isf.InstructionOffset = (DWORD_PTR)memory_to_linear_addr(pc);
575     isf.FrameOffset       = (DWORD_PTR)memory_to_linear_addr(frame);
576
577     /* grab module where symbol is. If we don't have a module, we cannot print more */
578     im.SizeOfStruct = sizeof(im);
579     if (!SymGetModuleInfo(dbg_curr_process->handle, isf.InstructionOffset, &im))
580         return;
581
582     si->SizeOfStruct = sizeof(*si);
583     si->MaxNameLen   = 256;
584     if (SymFromAddr(dbg_curr_process->handle, isf.InstructionOffset, &disp64, si))
585     {
586         struct sym_enum se;
587         char            tmp[1024];
588         DWORD           disp;
589
590         dbg_printf(" %s", si->Name);
591         if (disp) dbg_printf("+0x%lx", (DWORD_PTR)disp64);
592
593         SymSetContext(dbg_curr_process->handle, &isf, NULL);
594         se.tmp = tmp;
595         se.frame = isf.FrameOffset;
596         tmp[0] = '\0';
597         SymEnumSymbols(dbg_curr_process->handle, 0, NULL, sym_enum_cb, &se);
598         if (tmp[0]) dbg_printf("(%s)", tmp);
599
600         il.SizeOfStruct = sizeof(il);
601         if (SymGetLineFromAddr(dbg_curr_process->handle, isf.InstructionOffset,
602                                &disp, &il))
603             dbg_printf(" [%s:%lu]", il.FileName, il.LineNumber);
604         dbg_printf(" in %s", im.ModuleName);
605     }
606     else dbg_printf(" in %s (+0x%lx)", 
607                     im.ModuleName, (DWORD_PTR)(isf.InstructionOffset - im.BaseOfImage));
608 }
609
610 BOOL memory_disasm_one_insn(ADDRESS* addr)
611 {
612     char        ch;
613
614     print_address(addr, TRUE);
615     dbg_printf(": ");
616     if (!dbg_read_memory(memory_to_linear_addr(addr), &ch, sizeof(ch)))
617     {
618         dbg_printf("-- no code accessible --\n");
619         return FALSE;
620     }
621     be_cpu->disasm_one_insn(addr, TRUE);
622     dbg_printf("\n");
623     return TRUE;
624 }
625
626 void memory_disassemble(const struct dbg_lvalue* xstart, 
627                         const struct dbg_lvalue* xend, int instruction_count)
628 {
629     static ADDRESS last = {0,0,0};
630     int stop = 0;
631     int i;
632
633     if (!xstart && !xend) 
634     {
635         if (!last.Segment && !last.Offset) memory_get_current_pc(&last);
636     }
637     else
638     {
639         if (xstart)
640         {
641             last.Mode = AddrModeFlat;
642             last.Offset = types_extract_as_integer(xstart);
643         }
644         if (xend) 
645             stop = types_extract_as_integer(xend);
646     }
647     for (i = 0; (instruction_count == 0 || i < instruction_count)  &&
648                 (stop == 0 || last.Offset <= stop); i++)
649         memory_disasm_one_insn(&last);
650 }