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