Release 980329
[wine] / debugger / break.c
1 /*
2  * Debugger break-points handling
3  *
4  * Copyright 1994 Martin von Loewis
5  * Copyright 1995 Alexandre Julliard
6  */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <sys/types.h>
11 #include <sys/mman.h>
12 #include "module.h"
13 #include "process.h"
14 #include "toolhelp.h"
15 #include "windows.h"
16 #include "debugger.h"
17
18 #define INT3          0xcc   /* int 3 opcode */
19
20 #define MAX_BREAKPOINTS 100
21
22 typedef struct
23 {
24     DBG_ADDR      addr;
25     BYTE          addrlen;
26     BYTE          opcode;
27     BOOL16        enabled;
28     WORD          skipcount;
29     BOOL16        in_use;
30     struct expr * condition;
31 } BREAKPOINT;
32
33 static BREAKPOINT breakpoints[MAX_BREAKPOINTS];
34
35 static int next_bp = 1;  /* breakpoint 0 is reserved for step-over */
36
37
38 /***********************************************************************
39  *           DEBUG_ChangeOpcode
40  *
41  * Change the opcode at segment:addr.
42  */
43 static void DEBUG_SetOpcode( const DBG_ADDR *addr, BYTE op )
44 {
45     BYTE *ptr;
46
47     if (addr->seg) ptr = (BYTE *)PTR_SEG_OFF_TO_LIN( addr->seg, addr->off );
48     else ptr = (BYTE *)addr->off;
49
50     /* There are a couple of problems with this. On Linux prior to
51        1.1.62, this call fails (ENOACCESS) due to a bug in fs/exec.c.
52        This code is currently not tested at all on BSD.
53        How do I get the old protection in order to restore it later on?
54        */
55     if (mprotect((caddr_t)((int)ptr & (~4095)), 4096,
56                  PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
57     {
58         perror( "Can't set break point" );
59         return;
60     }
61     *ptr = op;
62     /* mprotect((caddr_t)(addr->off & ~4095), 4096,
63        PROT_READ | PROT_EXEC ); */
64 }
65
66
67 /***********************************************************************
68  *           DEBUG_IsStepOverInstr
69  *
70  * Determine if the instruction at CS:EIP is an instruction that
71  * we need to step over (like a call or a repetitive string move).
72  */
73 static BOOL32 DEBUG_IsStepOverInstr()
74 {
75     BYTE *instr = (BYTE *)PTR_SEG_OFF_TO_LIN( CS_reg(&DEBUG_context),
76                                               EIP_reg(&DEBUG_context) );
77
78     for (;;)
79     {
80         switch(*instr)
81         {
82           /* Skip all prefixes */
83
84         case 0x2e:  /* cs: */
85         case 0x36:  /* ss: */
86         case 0x3e:  /* ds: */
87         case 0x26:  /* es: */
88         case 0x64:  /* fs: */
89         case 0x65:  /* gs: */
90         case 0x66:  /* opcode size prefix */
91         case 0x67:  /* addr size prefix */
92         case 0xf0:  /* lock */
93         case 0xf2:  /* repne */
94         case 0xf3:  /* repe */
95             instr++;
96             continue;
97
98           /* Handle call instructions */
99
100         case 0xe8:  /* call <offset> */
101         case 0x9a:  /* lcall <seg>:<off> */
102             return TRUE;
103
104         case 0xff:  /* call <regmodrm> */
105             return (((instr[1] & 0x38) == 0x10) ||
106                     ((instr[1] & 0x38) == 0x18));
107
108           /* Handle string instructions */
109
110         case 0x6c:  /* insb */
111         case 0x6d:  /* insw */
112         case 0x6e:  /* outsb */
113         case 0x6f:  /* outsw */
114         case 0xa4:  /* movsb */
115         case 0xa5:  /* movsw */
116         case 0xa6:  /* cmpsb */
117         case 0xa7:  /* cmpsw */
118         case 0xaa:  /* stosb */
119         case 0xab:  /* stosw */
120         case 0xac:  /* lodsb */
121         case 0xad:  /* lodsw */
122         case 0xae:  /* scasb */
123         case 0xaf:  /* scasw */
124             return TRUE;
125
126         default:
127             return FALSE;
128         }
129     }
130 }
131
132
133 /***********************************************************************
134  *           DEBUG_IsFctReturn
135  *
136  * Determine if the instruction at CS:EIP is an instruction that
137  * is a function return.
138  */
139 BOOL32 DEBUG_IsFctReturn(void)
140 {
141     BYTE *instr = (BYTE *)PTR_SEG_OFF_TO_LIN( CS_reg(&DEBUG_context),
142                                               EIP_reg(&DEBUG_context) );
143
144     for (;;)
145     {
146         switch(*instr)
147         {
148         case 0xc2:
149         case 0xc3:
150           return TRUE;
151         default:
152             return FALSE;
153         }
154     }
155 }
156
157
158 /***********************************************************************
159  *           DEBUG_SetBreakpoints
160  *
161  * Set or remove all the breakpoints.
162  */
163 void DEBUG_SetBreakpoints( BOOL32 set )
164 {
165     int i;
166
167     for (i = 0; i < MAX_BREAKPOINTS; i++)
168     {
169         if (breakpoints[i].in_use && breakpoints[i].enabled)
170         {
171             /* Note: we check for read here, because if reading is allowed */
172             /*       writing permission will be forced in DEBUG_SetOpcode. */
173             if (DEBUG_IsBadReadPtr( &breakpoints[i].addr, 1 ))
174             {
175                 fprintf( stderr, "Invalid address for breakpoint %d, disabling it\n", i );
176                 breakpoints[i].enabled = FALSE;
177             }
178             else DEBUG_SetOpcode( &breakpoints[i].addr,
179                                   set ? INT3 : breakpoints[i].opcode );
180         }
181     }
182 }
183
184
185 /***********************************************************************
186  *           DEBUG_FindBreakpoint
187  *
188  * Find the breakpoint for a given address. Return the breakpoint
189  * number or -1 if none.
190  */
191 int DEBUG_FindBreakpoint( const DBG_ADDR *addr )
192 {
193     int i;
194
195     for (i = 0; i < MAX_BREAKPOINTS; i++)
196     {
197         if (breakpoints[i].in_use && breakpoints[i].enabled &&
198             breakpoints[i].addr.seg == addr->seg &&
199             breakpoints[i].addr.off == addr->off) return i;
200     }
201     return -1;
202 }
203
204
205 /***********************************************************************
206  *           DEBUG_AddBreakpoint
207  *
208  * Add a breakpoint.
209  */
210 void DEBUG_AddBreakpoint( const DBG_ADDR *address )
211 {
212     DBG_ADDR addr = *address;
213     int num;
214     unsigned int seg2;
215     BYTE *p;
216
217     DBG_FIX_ADDR_SEG( &addr, CS_reg(&DEBUG_context) );
218
219     if( addr.type != NULL && addr.type == DEBUG_TypeIntConst )
220       {
221         /*
222          * We know that we have the actual offset stored somewhere
223          * else in 32-bit space.  Grab it, and we
224          * should be all set.
225          */
226         seg2 = addr.seg;
227         addr.seg = 0;
228         addr.off = DEBUG_GetExprValue(&addr, NULL);
229         addr.seg = seg2;
230       }
231     if (!DBG_CHECK_READ_PTR( &addr, 1 )) return;
232
233     if (next_bp < MAX_BREAKPOINTS)
234         num = next_bp++;
235     else  /* try to find an empty slot */  
236     {
237         for (num = 1; num < MAX_BREAKPOINTS; num++)
238             if (!breakpoints[num].in_use) break;
239         if (num >= MAX_BREAKPOINTS)
240         {
241             fprintf( stderr, "Too many breakpoints. Please delete some.\n" );
242             return;
243         }
244     }
245     p = DBG_ADDR_TO_LIN( &addr );
246     breakpoints[num].addr    = addr;
247     breakpoints[num].addrlen = !addr.seg ? 32 :
248                          (GET_SEL_FLAGS(addr.seg) & LDT_FLAGS_32BIT) ? 32 : 16;
249     breakpoints[num].opcode  = *p;
250     breakpoints[num].enabled = TRUE;
251     breakpoints[num].in_use  = TRUE;
252     breakpoints[num].skipcount = 0;
253     fprintf( stderr, "Breakpoint %d at ", num );
254     DEBUG_PrintAddress( &breakpoints[num].addr, breakpoints[num].addrlen,
255                         TRUE );
256     fprintf( stderr, "\n" );
257 }
258
259
260 /***********************************************************************
261  *           DEBUG_DelBreakpoint
262  *
263  * Delete a breakpoint.
264  */
265 void DEBUG_DelBreakpoint( int num )
266 {
267     if ((num <= 0) || (num >= next_bp) || !breakpoints[num].in_use)
268     {
269         fprintf( stderr, "Invalid breakpoint number %d\n", num );
270         return;
271     }
272
273     if( breakpoints[num].condition != NULL )
274       {
275         DEBUG_FreeExpr(breakpoints[num].condition);
276         breakpoints[num].condition = NULL;
277       }
278
279     breakpoints[num].enabled = FALSE;
280     breakpoints[num].in_use  = FALSE;
281     breakpoints[num].skipcount = 0;
282 }
283
284
285 /***********************************************************************
286  *           DEBUG_EnableBreakpoint
287  *
288  * Enable or disable a break point.
289  */
290 void DEBUG_EnableBreakpoint( int num, BOOL32 enable )
291 {
292     if ((num <= 0) || (num >= next_bp) || !breakpoints[num].in_use)
293     {
294         fprintf( stderr, "Invalid breakpoint number %d\n", num );
295         return;
296     }
297     breakpoints[num].enabled = enable;
298     breakpoints[num].skipcount = 0;
299 }
300
301
302 /***********************************************************************
303  *           DEBUG_InfoBreakpoints
304  *
305  * Display break points information.
306  */
307 void DEBUG_InfoBreakpoints(void)
308 {
309     int i;
310
311     fprintf( stderr, "Breakpoints:\n" );
312     for (i = 1; i < next_bp; i++)
313     {
314         if (breakpoints[i].in_use)
315         {
316             fprintf( stderr, "%d: %c ", i, breakpoints[i].enabled ? 'y' : 'n');
317             DEBUG_PrintAddress( &breakpoints[i].addr, breakpoints[i].addrlen,
318                                 TRUE);
319             fprintf( stderr, "\n" );
320             if( breakpoints[i].condition != NULL )
321               {
322                 fprintf(stderr, "\t\tstop when  ");
323                 DEBUG_DisplayExpr(breakpoints[i].condition);
324                 fprintf(stderr, "\n");
325               }
326         }
327     }
328 }
329
330
331 /***********************************************************************
332  *           DEBUG_AddModuleBreakpoints
333  *
334  * Add a breakpoint at the start of every loaded module.
335  */
336 void DEBUG_AddModuleBreakpoints(void)
337 {
338     MODULEENTRY entry;
339     NE_MODULE *pModule;
340     BOOL32 ok;
341     DBG_ADDR addr = { NULL, 0, 0 };
342
343     for (ok = ModuleFirst(&entry); ok; ok = ModuleNext(&entry))
344     {
345         if (!(pModule = MODULE_GetPtr( entry.hModule ))) continue;
346         if (pModule->flags & NE_FFLAGS_LIBMODULE) continue;  /* Library */
347
348         if (pModule->flags & NE_FFLAGS_WIN32)  /* PE module */
349         {
350             PE_MODREF *pem = PROCESS_Current()->modref_list;
351             if (!pem)
352             {
353                 addr.seg = 0;
354                 addr.off = (DWORD)RVA_PTR( pModule->module32,
355                                            OptionalHeader.AddressOfEntryPoint);
356             }
357             else
358             {
359                 while (pem)
360                 {
361                    if (pem->module == pModule->module32) break;
362                    pem = pem->next;
363                 }
364                 if (!pem) continue;
365                 addr.seg = 0;
366                 addr.off = (DWORD)RVA_PTR( pem->module,
367                                            OptionalHeader.AddressOfEntryPoint);
368             }
369             fprintf( stderr, "Win32 task '%s': ", entry.szModule );
370             DEBUG_AddBreakpoint( &addr );
371         }
372         else  /* NE module */
373         {
374             addr.seg = NE_SEG_TABLE(pModule)[pModule->cs-1].selector;
375             addr.off = pModule->ip;
376             fprintf( stderr, "Win16 task '%s': ", entry.szModule );
377             DEBUG_AddBreakpoint( &addr );
378         }
379     }
380
381     DEBUG_SetBreakpoints( TRUE );  /* Setup breakpoints */
382 }
383
384
385 /***********************************************************************
386  *           DEBUG_ShouldContinue
387  *
388  * Determine if we should continue execution after a SIGTRAP signal when
389  * executing in the given mode.
390  */
391 BOOL32 DEBUG_ShouldContinue( enum exec_mode mode, int * count )
392 {
393     DBG_ADDR addr;
394     DBG_ADDR cond_addr;
395     int bpnum;
396     struct list_id list;
397     WORD cs;
398
399       /* If not single-stepping, back up over the int3 instruction */
400     if (!(EFL_reg(&DEBUG_context) & STEP_FLAG)) EIP_reg(&DEBUG_context)--;
401
402     GET_CS(cs);
403     addr.seg = (CS_reg(&DEBUG_context) == cs) ? 0 : CS_reg(&DEBUG_context);
404     addr.off = EIP_reg(&DEBUG_context);
405         
406     bpnum = DEBUG_FindBreakpoint( &addr );
407     breakpoints[0].enabled = 0;  /* disable the step-over breakpoint */
408
409     if ((bpnum != 0) && (bpnum != -1))
410     {
411         if( breakpoints[bpnum].condition != NULL )
412           {
413             cond_addr = DEBUG_EvalExpr(breakpoints[bpnum].condition);
414             if( cond_addr.type == NULL )
415               {
416                 /*
417                  * Something wrong - unable to evaluate this expression.
418                  */
419                 fprintf(stderr, "Unable to evaluate expression ");
420                 DEBUG_DisplayExpr(breakpoints[bpnum].condition);
421                 fprintf(stderr, "\nTurning off condition\n");
422                 DEBUG_AddBPCondition(bpnum, NULL);
423               }
424             else if( ! DEBUG_GetExprValue( &cond_addr, NULL) )
425               {
426                 return TRUE;
427               }
428           }
429
430         if( breakpoints[bpnum].skipcount > 0 )
431           {
432             breakpoints[bpnum].skipcount--;
433             if( breakpoints[bpnum].skipcount > 0 )
434               {
435                 return TRUE;
436               }
437           }
438         fprintf( stderr, "Stopped on breakpoint %d at ", bpnum );
439         DEBUG_PrintAddress( &breakpoints[bpnum].addr,
440                             breakpoints[bpnum].addrlen, TRUE );
441         fprintf( stderr, "\n" );
442         
443         /*
444          * See if there is a source file for this bp.  If so,
445          * then dig it out and display one line.
446          */
447         DEBUG_FindNearestSymbol( &addr, TRUE, NULL, 0, &list);
448         if( list.sourcefile != NULL )
449           {
450             DEBUG_List(&list, NULL, 0);
451           }
452         return FALSE;
453     }
454
455     /*
456      * If our mode indicates that we are stepping line numbers,
457      * get the current function, and figure out if we are exactly
458      * on a line number or not.
459      */
460     if( mode == EXEC_STEP_OVER 
461         || mode == EXEC_STEP_INSTR )
462       {
463         if( DEBUG_CheckLinenoStatus(&addr) == AT_LINENUMBER )
464           {
465             (*count)--;
466           }
467       }
468     else if( mode == EXEC_STEPI_OVER 
469         || mode == EXEC_STEPI_INSTR )
470
471       {
472         (*count)--;
473       }
474
475     if( *count > 0 || mode == EXEC_FINISH )
476       {
477         /*
478          * We still need to execute more instructions.
479          */
480         return TRUE;
481       }
482     
483     /*
484      * If we are about to stop, then print out the source line if we
485      * have it.
486      */
487     if( (mode != EXEC_CONT && mode != EXEC_FINISH) )
488       {
489         DEBUG_FindNearestSymbol( &addr, TRUE, NULL, 0, &list);
490         if( list.sourcefile != NULL )
491           {
492             DEBUG_List(&list, NULL, 0);
493           }
494       }
495
496     /* If there's no breakpoint and we are not single-stepping, then we     */
497     /* must have encountered an int3 in the Windows program; let's skip it. */
498     if ((bpnum == -1) && !(EFL_reg(&DEBUG_context) & STEP_FLAG))
499         EIP_reg(&DEBUG_context)++;
500
501       /* no breakpoint, continue if in continuous mode */
502     return (mode == EXEC_CONT || mode == EXEC_FINISH);
503 }
504
505
506 /***********************************************************************
507  *           DEBUG_RestartExecution
508  *
509  * Set the breakpoints to the correct state to restart execution
510  * in the given mode.
511  */
512 enum exec_mode DEBUG_RestartExecution( enum exec_mode mode, int count )
513 {
514     DBG_ADDR addr;
515     DBG_ADDR addr2;
516     int bp;
517     int delta;
518     int status;
519     unsigned int * value;
520     enum exec_mode ret_mode;
521     BYTE *instr;
522     WORD cs;
523
524     GET_CS(cs);
525     addr.seg = (CS_reg(&DEBUG_context) == cs) ? 0 : CS_reg(&DEBUG_context);
526     addr.off = EIP_reg(&DEBUG_context);
527
528     /*
529      * This is the mode we will be running in after we finish.  We would like
530      * to be able to modify this in certain cases.
531      */
532     ret_mode = mode;
533
534     bp = DEBUG_FindBreakpoint( &addr ); 
535     if ( bp != -1 && bp != 0)
536       {
537         /*
538          * If we have set a new value, then save it in the BP number.
539          */
540         if( count != 0 && mode == EXEC_CONT )
541           {
542             breakpoints[bp].skipcount = count;
543           }
544         mode = EXEC_STEPI_INSTR;  /* If there's a breakpoint, skip it */
545       }
546     else
547       {
548         if( mode == EXEC_CONT && count > 1 )
549           {
550             fprintf(stderr,"Not stopped at any breakpoint; argument ignored.\n");
551           }
552       }
553     
554     if( mode == EXEC_FINISH && DEBUG_IsFctReturn() )
555       {
556         mode = ret_mode = EXEC_STEPI_INSTR;
557       }
558
559     instr = (BYTE *)PTR_SEG_OFF_TO_LIN( CS_reg(&DEBUG_context),
560                                         EIP_reg(&DEBUG_context) );
561     /*
562      * See if the function we are stepping into has debug info
563      * and line numbers.  If not, then we step over it instead.
564      * FIXME - we need to check for things like thunks or trampolines,
565      * as the actual function may in fact have debug info.
566      */
567     if( *instr == 0xe8 )
568       {
569         delta = *(unsigned int*) (instr + 1);
570         addr2 = addr;
571         DEBUG_Disasm(&addr2, FALSE);
572         addr2.off += delta;
573         
574         status = DEBUG_CheckLinenoStatus(&addr2);
575         /*
576          * Anytime we have a trampoline, step over it.
577          */
578         if( ((mode == EXEC_STEP_OVER) || (mode == EXEC_STEPI_OVER))
579             && status == FUNC_IS_TRAMPOLINE )
580           {
581 #if 0
582             fprintf(stderr, "Not stepping into trampoline at %x (no lines)\n",
583                     addr2.off);
584 #endif
585             mode = EXEC_STEP_OVER_TRAMPOLINE;
586           }
587         
588         if( mode == EXEC_STEP_INSTR && status == FUNC_HAS_NO_LINES )
589           {
590 #if 0
591             fprintf(stderr, "Not stepping into function at %x (no lines)\n",
592                     addr2.off);
593 #endif
594             mode = EXEC_STEP_OVER;
595           }
596       }
597
598
599     if( mode == EXEC_STEP_INSTR )
600       {
601         if( DEBUG_CheckLinenoStatus(&addr) == FUNC_HAS_NO_LINES )
602           {
603             fprintf(stderr, "Single stepping until exit from function, \n");
604             fprintf(stderr, "which has no line number information.\n");
605             
606             ret_mode = mode = EXEC_FINISH;
607           }
608       }
609
610     switch(mode)
611     {
612     case EXEC_CONT: /* Continuous execution */
613         EFL_reg(&DEBUG_context) &= ~STEP_FLAG;
614         DEBUG_SetBreakpoints( TRUE );
615         break;
616
617     case EXEC_STEP_OVER_TRAMPOLINE:
618       /*
619        * This is the means by which we step over our conversion stubs
620        * in callfrom*.s and callto*.s.  We dig the appropriate address
621        * off the stack, and we set the breakpoint there instead of the
622        * address just after the call.
623        */
624       value = (unsigned int *) ESP_reg(&DEBUG_context) + 2;
625       addr.off = *value;
626       EFL_reg(&DEBUG_context) &= ~STEP_FLAG;
627       breakpoints[0].addr    = addr;
628       breakpoints[0].enabled = TRUE;
629       breakpoints[0].in_use  = TRUE;
630       breakpoints[0].skipcount = 0;
631       breakpoints[0].opcode  = *(BYTE *)DBG_ADDR_TO_LIN( &addr );
632       DEBUG_SetBreakpoints( TRUE );
633       break;
634
635     case EXEC_FINISH:
636     case EXEC_STEPI_OVER:  /* Stepping over a call */
637     case EXEC_STEP_OVER:  /* Stepping over a call */
638         if (DEBUG_IsStepOverInstr())
639         {
640             EFL_reg(&DEBUG_context) &= ~STEP_FLAG;
641             DEBUG_Disasm(&addr, FALSE);
642             breakpoints[0].addr    = addr;
643             breakpoints[0].enabled = TRUE;
644             breakpoints[0].in_use  = TRUE;
645             breakpoints[0].skipcount = 0;
646             breakpoints[0].opcode  = *(BYTE *)DBG_ADDR_TO_LIN( &addr );
647             DEBUG_SetBreakpoints( TRUE );
648             break;
649         }
650         /* else fall through to single-stepping */
651
652     case EXEC_STEP_INSTR: /* Single-stepping an instruction */
653     case EXEC_STEPI_INSTR: /* Single-stepping an instruction */
654         EFL_reg(&DEBUG_context) |= STEP_FLAG;
655         break;
656     }
657     return ret_mode;
658 }
659
660 int
661 DEBUG_AddBPCondition(int num, struct expr * exp)
662 {
663     if ((num <= 0) || (num >= next_bp) || !breakpoints[num].in_use)
664     {
665         fprintf( stderr, "Invalid breakpoint number %d\n", num );
666         return FALSE;
667     }
668
669     if( breakpoints[num].condition != NULL )
670       {
671         DEBUG_FreeExpr(breakpoints[num].condition);
672         breakpoints[num].condition = NULL;
673       }
674
675     if( exp != NULL )
676       {
677         breakpoints[num].condition = DEBUG_CloneExpr(exp);
678       }
679
680    return TRUE;
681 }