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