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