1 /* radare - LGPL - Copyright 2009-2018 - pancake, jduck, TheLemonMan, saucec0de */
2 
3 #include <r_debug.h>
4 #include <r_drx.h>
5 #include <r_core.h>
6 #include <signal.h>
7 
8 R_LIB_VERSION(r_debug);
9 
10 // Size of the lookahead buffers used in r_debug functions
11 #define DBG_BUF_SIZE 512
12 
r_debug_info(RDebug * dbg,const char * arg)13 R_API RDebugInfo *r_debug_info(RDebug *dbg, const char *arg) {
14 	if (!dbg || !dbg->h || !dbg->h->info) {
15 		return NULL;
16 	}
17 	if (dbg->pid < 0) {
18 		return NULL;
19 	}
20 	return dbg->h->info (dbg, arg);
21 }
22 
r_debug_info_free(RDebugInfo * rdi)23 R_API void r_debug_info_free(RDebugInfo *rdi) {
24 	if (rdi) {
25 		free (rdi->cwd);
26 		free (rdi->exe);
27 		free (rdi->cmdline);
28 		free (rdi->libname);
29 		free (rdi->usr);
30 		free (rdi);
31 	}
32 }
33 
r_debug_bp_update(RDebug * dbg)34 R_API void r_debug_bp_update(RDebug *dbg) {
35 	/* update all bp->addr if they are named bps */
36 	RBreakpointItem *bp;
37 	RListIter *iter;
38 	r_list_foreach (dbg->bp->bps, iter, bp) {
39 		if (bp->expr) {
40 			bp->addr = dbg->corebind.numGet (dbg->corebind.core, bp->expr);
41 		}
42 	}
43 }
44 
r_debug_drx_at(RDebug * dbg,ut64 addr)45 static int r_debug_drx_at(RDebug *dbg, ut64 addr) {
46 	if (dbg && dbg->h && dbg->h->drx) {
47 		return dbg->h->drx (dbg, 0, addr, 0, 0, 0, DRX_API_GET_BP);
48 	}
49 	return -1;
50 }
51 
52 /*
53  * Recoiling after a breakpoint has two stages:
54  * 1. remove the breakpoint and fix the program counter.
55  * 2. on resume, single step once and then replace the breakpoint.
56  *
57  * Thus, we have two functions to handle these situations.
58  * r_debug_bp_hit handles stage 1.
59  * r_debug_recoil handles stage 2.
60  */
r_debug_bp_hit(RDebug * dbg,RRegItem * pc_ri,ut64 pc,RBreakpointItem ** pb)61 static int r_debug_bp_hit(RDebug *dbg, RRegItem *pc_ri, ut64 pc, RBreakpointItem **pb) {
62 	RBreakpointItem *b;
63 
64 	if (!pb) {
65 		eprintf ("BreakpointItem is NULL!\n");
66 		return false;
67 	}
68 	/* initialize the output parameter */
69 	*pb = NULL;
70 
71 	/* if we are tracing, update the tracing data */
72 	if (dbg->trace->enabled) {
73 		r_debug_trace_pc (dbg, pc);
74 	}
75 
76 	/* remove all sw breakpoints for now. we'll set them back in stage 2
77 	 *
78 	 * this is necessary because while stopped we don't want any breakpoints in
79 	 * the code messing up our analysis.
80 	 */
81 	r_debug_bp_update (dbg);
82 	if (!r_bp_restore (dbg->bp, false)) { // unset sw breakpoints
83 		return false;
84 	}
85 
86 	/* if we are recoiling, tell r_debug_step that we ignored a breakpoint
87 	 * event */
88 	if (!dbg->swstep && dbg->recoil_mode != R_DBG_RECOIL_NONE) {
89 		dbg->reason.bp_addr = 0;
90 		return true;
91 	}
92 
93 	/* The MIPS ptrace has a different behaviour */
94 # if __mips__
95 	/* see if we really have a breakpoint here... */
96 	b = r_bp_get_at (dbg->bp, pc);
97 	if (!b) { /* we don't. nothing left to do */
98 		return true;
99 	}
100 # else
101 	int pc_off = dbg->bpsize;
102 	/* see if we really have a breakpoint here... */
103 	if (!dbg->pc_at_bp_set) {
104 		b = r_bp_get_at (dbg->bp, pc - dbg->bpsize);
105 		if (!b) { /* we don't. nothing left to do */
106 			/* Some targets set pc to breakpoint */
107 			b = r_bp_get_at (dbg->bp, pc);
108 			if (!b) {
109 				/* handle the case of hw breakpoints - notify the user */
110 				int drx_reg_idx = r_debug_drx_at (dbg, pc);
111 				if (drx_reg_idx != -1) {
112 					eprintf ("hit hardware breakpoint %d at: %" PFMT64x "\n",
113 						drx_reg_idx, pc);
114 				}
115 				/* Couldn't find the break point. Nothing more to do... */
116 				return true;
117 			}
118 			else {
119 				dbg->pc_at_bp_set = true;
120 				dbg->pc_at_bp = true;
121 			}
122 		} else {
123 			dbg->pc_at_bp_set = true;
124 			dbg->pc_at_bp = false;
125 		}
126 	}
127 
128 	if (!dbg->pc_at_bp_set) {
129 		eprintf ("failed to determine position of pc after breakpoint");
130 	}
131 
132 	if (dbg->pc_at_bp) {
133 		pc_off = 0;
134 		b = r_bp_get_at (dbg->bp, pc);
135 	} else {
136 		b = r_bp_get_at (dbg->bp, pc - dbg->bpsize);
137 	}
138 
139 	if (!b) {
140 		return true;
141 	}
142 
143 	b = r_bp_get_at (dbg->bp, pc - dbg->bpsize);
144 	if (!b) { /* we don't. nothing left to do */
145 		/* Some targets set pc to breakpoint */
146 		b = r_bp_get_at (dbg->bp, pc);
147 		if (!b) {
148 			return true;
149 		}
150 		pc_off = 0;
151 	}
152 
153 	/* set the pc value back */
154 	if (pc_off) {
155 		pc -= pc_off;
156 		if (!r_reg_set_value (dbg->reg, pc_ri, pc)) {
157 			eprintf ("failed to set PC!\n");
158 			return false;
159 		}
160 		if (!r_debug_reg_sync (dbg, R_REG_TYPE_GPR, true)) {
161 			eprintf ("cannot set registers!\n");
162 			return false;
163 		}
164 	}
165 # endif
166 
167 	*pb = b;
168 
169 	/* if we are on a software stepping breakpoint, we hide what is going on... */
170 	if (b->swstep) {
171 		dbg->reason.bp_addr = 0;
172 		return true;
173 	}
174 
175 	/* setup our stage 2 */
176 	dbg->reason.bp_addr = b->addr;
177 
178 	/* inform the user of what happened */
179 	if (dbg->hitinfo) {
180 		eprintf ("hit %spoint at: 0x%" PFMT64x "\n",
181 			b->trace ? "trace" : "break", pc);
182 	}
183 
184 	/* now that we've cleaned up after the breakpoint, call the other
185 	 * potential breakpoint handlers
186 	 */
187 	if (dbg->corebind.core && dbg->corebind.bphit) {
188 		dbg->corebind.bphit (dbg->corebind.core, b);
189 	}
190 	return true;
191 }
192 
193 /* enable all software breakpoints */
r_debug_bps_enable(RDebug * dbg)194 static int r_debug_bps_enable(RDebug *dbg) {
195 	/* restore all sw breakpoints. we are about to step/continue so these need
196 	 * to be in place. */
197 	if (!r_bp_restore (dbg->bp, true)) {
198 		return false;
199 	}
200 	/* done recoiling... */
201 	dbg->recoil_mode = R_DBG_RECOIL_NONE;
202 	return true;
203 }
204 
205 /*
206  * replace breakpoints before we continue execution
207  *
208  * this is called from r_debug_step_hard or r_debug_continue_kill
209  *
210  * this is a trick process because of breakpoints/tracepoints.
211  *
212  * if a breakpoint was just hit, we need step over that instruction before
213  * allowing the caller to proceed as desired.
214  *
215  * if the user wants to step, the single step here does the job.
216  */
r_debug_recoil(RDebug * dbg,RDebugRecoilMode rc_mode)217 static int r_debug_recoil(RDebug *dbg, RDebugRecoilMode rc_mode) {
218 	/* if bp_addr is not set, we must not have actually hit a breakpoint */
219 	if (!dbg->reason.bp_addr) {
220 		return r_debug_bps_enable (dbg);
221 	}
222 
223 	/* don't do anything if we already are recoiling */
224 	if (dbg->recoil_mode != R_DBG_RECOIL_NONE) {
225 		/* the first time recoil is called with swstep, we just need to
226 		 * look up the bp and step past it.
227 		 * the second time it's called, the new sw breakpoint should exist
228 		 * so we just restore all except what we originally hit and reset.
229 		 */
230 		if (dbg->swstep) {
231 			if (!r_bp_restore_except (dbg->bp, true, dbg->reason.bp_addr)) {
232 				return false;
233 			}
234 			return true;
235 		}
236 
237 		/* otherwise, avoid recursion */
238 		return true;
239 	}
240 
241 	/* we have entered recoil! */
242 	dbg->recoil_mode = rc_mode;
243 
244 	/* step over the place with the breakpoint and let the caller resume */
245 	if (r_debug_step (dbg, 1) != 1) {
246 		return false;
247 	}
248 
249 	/* when stepping away from a breakpoint during recoil in stepping mode,
250 	 * the r_debug_bp_hit function tells us that it was called
251 	 * innapropriately by setting bp_addr back to zero. however, recoil_mode
252 	 * is still set. we use this condition to know not to proceed but
253 	 * pretend as if we had.
254 	 */
255 	if (!dbg->reason.bp_addr && dbg->recoil_mode == R_DBG_RECOIL_STEP) {
256 		return true;
257 	}
258 	dbg->reason.bp_addr = 0;
259 
260 	return r_debug_bps_enable (dbg);
261 }
262 
263 /* add a breakpoint with some typical values */
r_debug_bp_add(RDebug * dbg,ut64 addr,int hw,bool watch,int rw,char * module,st64 m_delta)264 R_API RBreakpointItem *r_debug_bp_add(RDebug *dbg, ut64 addr, int hw, bool watch, int rw, char *module, st64 m_delta) {
265 	int bpsz = r_bp_size(dbg->bp);
266 	RBreakpointItem *bpi;
267 	const char *module_name = module;
268 	RListIter *iter;
269 	RDebugMap *map;
270 	if (!addr && module) {
271 		bool detect_module, valid = false;
272 		int perm;
273 
274 		if (m_delta) {
275 			detect_module = false;
276 			RList *list = r_debug_modules_list (dbg);
277 			r_list_foreach (list, iter, map) {
278 				if (strstr (map->file, module)) {
279 					addr = map->addr + m_delta;
280 					module_name = map->file;
281 					break;
282 				}
283 			}
284 			r_list_free (list);
285 		} else {
286 			//module holds the address
287 			addr = (ut64)r_num_math (dbg->num, module);
288 			if (!addr) {
289 				return NULL;
290 			}
291 			detect_module = true;
292 		}
293 		r_debug_map_sync (dbg);
294 		r_list_foreach (dbg->maps, iter, map) {
295 			if (addr >= map->addr && addr < map->addr_end) {
296 				valid = true;
297 				if (detect_module) {
298 					module_name = map->file;
299 					m_delta = addr - map->addr;
300 				}
301 				perm = ((map->perm & 1) << 2) | (map->perm & 2) | ((map->perm & 4) >> 2);
302 				if (!(perm & R_BP_PROT_EXEC)) {
303 					eprintf ("WARNING: setting bp within mapped memory without exec perm\n");
304 				}
305 				break;
306 			}
307 		}
308 		if (!valid) {
309 			eprintf ("WARNING: module's base addr + delta is not a valid address\n");
310 			return NULL;
311 		}
312 	}
313 	if (!module) {
314 		//express db breakpoints as dbm due to ASLR when saving into project
315 		r_debug_map_sync (dbg);
316 		r_list_foreach (dbg->maps, iter, map) {
317 			if (addr >= map->addr && addr < map->addr_end) {
318 				module_name = map->file;
319 				m_delta = addr - map->addr;
320 				break;
321 			}
322 		}
323 	}
324 	if (watch) {
325 		hw = 1; //XXX
326 		bpi = r_bp_watch_add (dbg->bp, addr, bpsz, hw, rw);
327 	} else {
328 		bpi = hw
329 			? r_bp_add_hw (dbg->bp, addr, bpsz, R_BP_PROT_EXEC)
330 			: r_bp_add_sw (dbg->bp, addr, bpsz, R_BP_PROT_EXEC);
331 	}
332 	if (bpi) {
333 		if (module_name) {
334 			bpi->module_name = strdup (module_name);
335 			bpi->name = r_str_newf ("%s+0x%" PFMT64x, module_name, m_delta);
336 		}
337 		bpi->module_delta = m_delta;
338 	}
339 	return bpi;
340 }
341 
r_debug_str_callback(RNum * userptr,ut64 off,int * ok)342 static const char *r_debug_str_callback(RNum *userptr, ut64 off, int *ok) {
343 	// RDebug *dbg = (RDebug *)userptr;
344 	eprintf ("STR CALLBACK WTF WTF WTF\n");
345 	return NULL;
346 }
347 
r_debug_new(int hard)348 R_API RDebug *r_debug_new(int hard) {
349 	RDebug *dbg = R_NEW0 (RDebug);
350 	if (!dbg) {
351 		return NULL;
352 	}
353 	// R_SYS_ARCH
354 	dbg->arch = strdup (R_SYS_ARCH);
355 	dbg->bits = R_SYS_BITS;
356 	dbg->trace_forks = 1;
357 	dbg->forked_pid = -1;
358 	dbg->main_pid = -1;
359 	dbg->n_threads = 0;
360 	dbg->trace_clone = 0;
361 	dbg->egg = r_egg_new ();
362 	r_egg_setup (dbg->egg, R_SYS_ARCH, R_SYS_BITS, R_SYS_ENDIAN, R_SYS_OS);
363 	dbg->trace_aftersyscall = true;
364 	dbg->follow_child = false;
365 	R_FREE (dbg->btalgo);
366 	dbg->trace_execs = 0;
367 	dbg->anal = NULL;
368 	dbg->pid = -1;
369 	dbg->bpsize = 1;
370 	dbg->tid = -1;
371 	dbg->tree = r_tree_new ();
372 	dbg->tracenodes = sdb_new0 ();
373 	dbg->swstep = 0;
374 	dbg->stop_all_threads = false;
375 	dbg->trace = r_debug_trace_new ();
376 	dbg->cb_printf = (void *)printf;
377 	dbg->reg = r_reg_new ();
378 	dbg->num = r_num_new (r_debug_num_callback, r_debug_str_callback, dbg);
379 	dbg->h = NULL;
380 	dbg->threads = NULL;
381 	dbg->hitinfo = 1;
382 	/* TODO: needs a redesign? */
383 	dbg->maps = r_debug_map_list_new ();
384 	dbg->maps_user = r_debug_map_list_new ();
385 	dbg->q_regs = NULL;
386 	dbg->call_frames = NULL;
387 	dbg->main_arena_resolved = false;
388 	dbg->glibc_version = 231; /* default version ubuntu 20 */
389 	r_debug_signal_init (dbg);
390 	if (hard) {
391 		dbg->bp = r_bp_new ();
392 		r_debug_plugin_init (dbg);
393 		dbg->bp->iob.init = false;
394 		dbg->bp->baddr = 0;
395 	}
396 	return dbg;
397 }
398 
free_tracenodes_entry(RDebug * dbg,const char * k,const char * v)399 static int free_tracenodes_entry(RDebug *dbg, const char *k, const char *v) {
400 	ut64 v_num = r_num_get (NULL, v);
401 	free((void *)(size_t)v_num);
402 	return true;
403 }
404 
r_debug_tracenodes_reset(RDebug * dbg)405 R_API void r_debug_tracenodes_reset(RDebug *dbg) {
406 	sdb_foreach (dbg->tracenodes, (SdbForeachCallback)free_tracenodes_entry, dbg);
407 	sdb_reset (dbg->tracenodes);
408 }
409 
r_debug_free(RDebug * dbg)410 R_API RDebug *r_debug_free(RDebug *dbg) {
411 	if (dbg) {
412 		// TODO: free it correctly.. we must ensure this is an instance and not a reference..
413 		r_bp_free (dbg->bp);
414 		//r_reg_free(&dbg->reg);
415 		free (dbg->snap_path);
416 		r_list_free (dbg->maps);
417 		r_list_free (dbg->maps_user);
418 		r_list_free (dbg->threads);
419 		r_num_free (dbg->num);
420 		sdb_free (dbg->sgnls);
421 		r_tree_free (dbg->tree);
422 		sdb_foreach (dbg->tracenodes, (SdbForeachCallback)free_tracenodes_entry, dbg);
423 		sdb_free (dbg->tracenodes);
424 		r_list_free (dbg->plugins);
425 		r_list_free (dbg->call_frames);
426 		free (dbg->btalgo);
427 		r_debug_trace_free (dbg->trace);
428 		r_debug_session_free (dbg->session);
429 		r_anal_op_free (dbg->cur_op);
430 		dbg->trace = NULL;
431 		r_egg_free (dbg->egg);
432 		free (dbg->arch);
433 		free (dbg->glob_libs);
434 		free (dbg->glob_unlibs);
435 		free (dbg);
436 	}
437 	return NULL;
438 }
439 
r_debug_attach(RDebug * dbg,int pid)440 R_API int r_debug_attach(RDebug *dbg, int pid) {
441 	int ret = false;
442 	if (dbg && dbg->h && dbg->h->attach) {
443 		ret = dbg->h->attach (dbg, pid);
444 		if (ret != -1) {
445 			r_debug_select (dbg, pid, ret); //dbg->pid, dbg->tid);
446 		}
447 	}
448 	return ret;
449 }
450 
451 /* stop execution of child process */
r_debug_stop(RDebug * dbg)452 R_API int r_debug_stop(RDebug *dbg) {
453 	if (dbg && dbg->h && dbg->h->stop) {
454 		return dbg->h->stop (dbg);
455 	}
456 	return false;
457 }
458 
r_debug_set_arch(RDebug * dbg,const char * arch,int bits)459 R_API bool r_debug_set_arch(RDebug *dbg, const char *arch, int bits) {
460 	if (arch && dbg && dbg->h) {
461 		switch (bits) {
462 		case 27:
463 			if (dbg->h->bits == 27) {
464 				dbg->bits = 27;
465 			}
466 			break;
467 		case 32:
468 			if (dbg->h->bits & R_SYS_BITS_32) {
469 				dbg->bits = R_SYS_BITS_32;
470 			}
471 			break;
472 		case 64:
473 			dbg->bits = R_SYS_BITS_64;
474 			break;
475 		}
476 		if (!dbg->h->bits) {
477 			dbg->bits = dbg->h->bits;
478 		} else if (!(dbg->h->bits & dbg->bits)) {
479 			dbg->bits = dbg->h->bits & R_SYS_BITS_64;
480 			if (!dbg->bits) {
481 				dbg->bits = dbg->h->bits & R_SYS_BITS_32;
482 			}
483 			if (!dbg->bits) {
484 				dbg->bits = R_SYS_BITS_32;
485 			}
486 		}
487 		free (dbg->arch);
488 		dbg->arch = strdup (arch);
489 		return true;
490 	}
491 	return false;
492 }
493 
494 /*
495  * Save 4096 bytes from %esp
496  * TODO: Add support for reverse stack architectures
497  * Also known as r_debug_inject()
498  */
r_debug_execute(RDebug * dbg,const ut8 * buf,int len,int restore)499 R_API ut64 r_debug_execute(RDebug *dbg, const ut8 *buf, int len, int restore) {
500 	int orig_sz;
501 	ut8 stackbackup[4096];
502 	ut8 *backup, *orig = NULL;
503 	RRegItem *ri, *risp, *ripc;
504 	ut64 rsp, rpc, ra0 = 0LL;
505 	if (r_debug_is_dead (dbg)) {
506 		return false;
507 	}
508 	ripc = r_reg_get (dbg->reg, dbg->reg->name[R_REG_NAME_PC], R_REG_TYPE_GPR);
509 	risp = r_reg_get (dbg->reg, dbg->reg->name[R_REG_NAME_SP], R_REG_TYPE_GPR);
510 	if (ripc) {
511 		r_debug_reg_sync (dbg, R_REG_TYPE_GPR, false);
512 		orig = r_reg_get_bytes (dbg->reg, R_REG_TYPE_ALL, &orig_sz);
513 		if (!orig) {
514 			eprintf ("Cannot get register arena bytes\n");
515 			return 0LL;
516 		}
517 		rpc = r_reg_get_value (dbg->reg, ripc);
518 		rsp = r_reg_get_value (dbg->reg, risp);
519 
520 		backup = malloc (len);
521 		if (!backup) {
522 			free (orig);
523 			return 0LL;
524 		}
525 		dbg->iob.read_at (dbg->iob.io, rpc, backup, len);
526 		dbg->iob.read_at (dbg->iob.io, rsp, stackbackup, len);
527 
528 		r_bp_add_sw (dbg->bp, rpc+len, dbg->bpsize, R_BP_PROT_EXEC);
529 
530 		/* execute code here */
531 		dbg->iob.write_at (dbg->iob.io, rpc, buf, len);
532 		//r_bp_add_sw (dbg->bp, rpc+len, 4, R_BP_PROT_EXEC);
533 		r_debug_continue (dbg);
534 		//r_bp_del (dbg->bp, rpc+len);
535 		/* TODO: check if stopped in breakpoint or not */
536 
537 		r_bp_del (dbg->bp, rpc+len);
538 		dbg->iob.write_at (dbg->iob.io, rpc, backup, len);
539 		if (restore) {
540 			dbg->iob.write_at (dbg->iob.io, rsp, stackbackup, len);
541 		}
542 
543 		r_debug_reg_sync (dbg, R_REG_TYPE_GPR, false);
544 		ri = r_reg_get (dbg->reg, dbg->reg->name[R_REG_NAME_A0], R_REG_TYPE_GPR);
545 		ra0 = r_reg_get_value (dbg->reg, ri);
546 		if (restore) {
547 			r_reg_read_regs (dbg->reg, orig, orig_sz);
548 		} else {
549 			r_reg_set_value (dbg->reg, ripc, rpc);
550 		}
551 		r_debug_reg_sync (dbg, R_REG_TYPE_GPR, true);
552 		free (backup);
553 		free (orig);
554 		eprintf ("ra0=0x%08"PFMT64x"\n", ra0);
555 	} else {
556 		eprintf ("r_debug_execute: Cannot get program counter\n");
557 	}
558 	return (ra0);
559 }
560 
r_debug_startv(struct r_debug_t * dbg,int argc,char ** argv)561 R_API int r_debug_startv(struct r_debug_t *dbg, int argc, char **argv) {
562 	/* TODO : r_debug_startv unimplemented */
563 	return false;
564 }
565 
r_debug_start(RDebug * dbg,const char * cmd)566 R_API int r_debug_start(RDebug *dbg, const char *cmd) {
567 	/* TODO: this argc/argv parser is done in r_io */
568 	// TODO: parse cmd and generate argc and argv
569 	return false;
570 }
571 
r_debug_detach(RDebug * dbg,int pid)572 R_API int r_debug_detach(RDebug *dbg, int pid) {
573 	int ret = 0;
574 	if (dbg->h && dbg->h->detach) {
575 		ret = dbg->h->detach (dbg, pid);
576 		if (dbg->pid == pid) {
577 			dbg->pid = -1;
578 			dbg->tid = -1;
579 		}
580 	}
581 	return ret;
582 }
583 
r_debug_select(RDebug * dbg,int pid,int tid)584 R_API bool r_debug_select(RDebug *dbg, int pid, int tid) {
585 	ut64 pc = 0;
586 	int prev_pid = dbg->pid;
587 	int prev_tid = dbg->tid;
588 
589 	if (pid < 0) {
590 		return false;
591 	}
592 	if (tid < 0) {
593 		tid = pid;
594 	}
595 	if (pid != -1 && tid != -1) {
596 		if ((pid != dbg->pid || tid != dbg->tid) && dbg->verbose) {
597 			eprintf ("= attach %d %d\n", pid, tid);
598 		}
599 	} else {
600 		if (dbg->pid != -1) {
601 			eprintf ("Child %d is dead\n", dbg->pid);
602 		}
603 	}
604 	if (pid < 0 || tid < 0) {
605 		return false;
606 	}
607 
608 	if (dbg->h && dbg->h->select && !dbg->h->select (dbg, pid, tid)) {
609 		return false;
610 	}
611 
612 	// Don't change the pid/tid if the plugin already modified it due to internal constraints
613 	if (dbg->pid == prev_pid) {
614 		dbg->pid = pid;
615 	}
616 	if (dbg->tid == prev_tid) {
617 		dbg->tid = tid;
618 	}
619 
620 	free (r_io_system (dbg->iob.io, sdb_fmt ("pid %d", dbg->tid)));
621 
622 	// Synchronize with the current thread's data
623 	if (dbg->corebind.core) {
624 		RCore *core = (RCore *)dbg->corebind.core;
625 
626 		r_reg_arena_swap (core->dbg->reg, true);
627 		r_debug_reg_sync (dbg, R_REG_TYPE_ALL, false);
628 
629 		pc = r_debug_reg_get (dbg, "PC");
630 		core->offset = pc;
631 	}
632 
633 	return true;
634 }
635 
r_debug_reason_to_string(int type)636 R_API const char *r_debug_reason_to_string(int type) {
637 	switch (type) {
638 	case R_DEBUG_REASON_DEAD: return "dead";
639 	case R_DEBUG_REASON_ABORT: return "abort";
640 	case R_DEBUG_REASON_SEGFAULT: return "segfault";
641 	case R_DEBUG_REASON_NONE: return "none";
642 	case R_DEBUG_REASON_SIGNAL: return "signal";
643 	case R_DEBUG_REASON_BREAKPOINT: return "breakpoint";
644 	case R_DEBUG_REASON_TRACEPOINT: return "tracepoint";
645 	case R_DEBUG_REASON_READERR: return "read-error";
646 	case R_DEBUG_REASON_WRITERR: return "write-error";
647 	case R_DEBUG_REASON_DIVBYZERO: return "div-by-zero";
648 	case R_DEBUG_REASON_ILLEGAL: return "illegal";
649 	case R_DEBUG_REASON_UNKNOWN: return "unknown";
650 	case R_DEBUG_REASON_ERROR: return "error";
651 	case R_DEBUG_REASON_NEW_PID: return "new-pid";
652 	case R_DEBUG_REASON_NEW_TID: return "new-tid";
653 	case R_DEBUG_REASON_NEW_LIB: return "new-lib";
654 	case R_DEBUG_REASON_EXIT_PID: return "exit-pid";
655 	case R_DEBUG_REASON_EXIT_TID: return "exit-tid";
656 	case R_DEBUG_REASON_EXIT_LIB: return "exit-lib";
657 	case R_DEBUG_REASON_TRAP: return "trap";
658 	case R_DEBUG_REASON_SWI: return "software-interrupt";
659 	case R_DEBUG_REASON_INT: return "interrupt";
660 	case R_DEBUG_REASON_FPU: return "fpu";
661 	case R_DEBUG_REASON_STEP: return "step";
662 	case R_DEBUG_REASON_USERSUSP: return "suspended-by-user";
663 	}
664 	return "unhandled";
665 }
666 
r_debug_stop_reason(RDebug * dbg)667 R_API RDebugReasonType r_debug_stop_reason(RDebug *dbg) {
668 	// TODO: return reason to stop debugging
669 	// - new process
670 	// - trap instruction
671 	// - illegal instruction
672 	// - fpu exception
673 	// return dbg->reason
674 	return dbg->reason.type;
675 }
676 
677 /*
678  * wait for an event to happen on the selected pid/tid
679  *
680  * Returns  R_DEBUG_REASON_*
681  */
r_debug_wait(RDebug * dbg,RBreakpointItem ** bp)682 R_API RDebugReasonType r_debug_wait(RDebug *dbg, RBreakpointItem **bp) {
683 	RDebugReasonType reason = R_DEBUG_REASON_ERROR;
684 	if (!dbg) {
685 		return reason;
686 	}
687 
688 	if (bp) {
689 		*bp = NULL;
690 	}
691 	/* default to unknown */
692 	dbg->reason.type = R_DEBUG_REASON_UNKNOWN;
693 	if (r_debug_is_dead (dbg)) {
694 		return R_DEBUG_REASON_DEAD;
695 	}
696 
697 	/* if our debugger plugin has wait */
698 	if (dbg->h && dbg->h->wait) {
699 		reason = dbg->h->wait (dbg, dbg->pid);
700 		if (reason == R_DEBUG_REASON_DEAD) {
701 			eprintf ("\n==> Process finished\n\n");
702 			REventDebugProcessFinished event = {
703 				.pid = dbg->pid
704 			};
705 			r_event_send (dbg->ev, R_EVENT_DEBUG_PROCESS_FINISHED, &event);
706 			// XXX(jjd): TODO: handle fallback or something else
707 			//r_debug_select (dbg, -1, -1);
708 			return R_DEBUG_REASON_DEAD;
709 		}
710 
711 #if __linux__
712 		// Letting other threads running will cause ptrace commands to fail
713 		// when writing to the same process memory to set/unset breakpoints
714 		// and is problematic in Linux.
715 		if (dbg->continue_all_threads) {
716 			r_debug_stop (dbg);
717 		}
718 #endif
719 
720 		/* propagate errors from the plugin */
721 		if (reason == R_DEBUG_REASON_ERROR) {
722 			return R_DEBUG_REASON_ERROR;
723 		}
724 
725 		/* read general purpose registers */
726 		if (!r_debug_reg_sync (dbg, R_REG_TYPE_GPR, false)) {
727 			return R_DEBUG_REASON_ERROR;
728 		}
729 
730 		bool libs_bp = (dbg->glob_libs || dbg->glob_unlibs) ? true : false;
731 		/* if the underlying stop reason is a breakpoint, call the handlers */
732 		if (reason == R_DEBUG_REASON_BREAKPOINT ||
733 			reason == R_DEBUG_REASON_STEP ||
734 			(libs_bp && ((reason == R_DEBUG_REASON_NEW_LIB) || (reason == R_DEBUG_REASON_EXIT_LIB)))) {
735 			RRegItem *pc_ri;
736 			RBreakpointItem *b = NULL;
737 			ut64 pc;
738 
739 			/* get the program coounter */
740 			pc_ri = r_reg_get (dbg->reg, dbg->reg->name[R_REG_NAME_PC], -1);
741 			if (!pc_ri) { /* couldn't find PC?! */
742 				eprintf ("Couldn't find PC!\n");
743 				return R_DEBUG_REASON_ERROR;
744 			}
745 
746 			/* get the value */
747 			pc = r_reg_get_value (dbg->reg, pc_ri);
748 
749 			if (!r_debug_bp_hit (dbg, pc_ri, pc, &b)) {
750 				return R_DEBUG_REASON_ERROR;
751 			}
752 
753 			if (bp) {
754 				*bp = b;
755 			}
756 
757 			if (b && reason == R_DEBUG_REASON_STEP) {
758 				reason = R_DEBUG_REASON_BREAKPOINT;
759 			}
760 			/* if we hit a tracing breakpoint, we need to continue in
761 			 * whatever mode the user desired. */
762 			if (dbg->corebind.core && b && b->cond) {
763 				reason = R_DEBUG_REASON_COND;
764 			}
765 			if (b && b->trace) {
766 				reason = R_DEBUG_REASON_TRACEPOINT;
767 			}
768 		}
769 
770 		dbg->reason.type = reason;
771 		if (reason == R_DEBUG_REASON_SIGNAL && dbg->reason.signum != -1) {
772 			/* handle signal on continuations here */
773 			int what = r_debug_signal_what (dbg, dbg->reason.signum);
774 			const char *name = r_signal_to_string (dbg->reason.signum);
775 			if (name && strcmp ("SIGTRAP", name)) {
776 				r_cons_printf ("[+] signal %d aka %s received %d\n",
777 						dbg->reason.signum, name, what);
778 			}
779 		}
780 	}
781 	return reason;
782 }
783 
r_debug_step_soft(RDebug * dbg)784 R_API int r_debug_step_soft(RDebug *dbg) {
785 	ut8 buf[32];
786 	ut64 pc, sp, r;
787 	ut64 next[2];
788 	RAnalOp op;
789 	int br, i, ret;
790 	union {
791 		ut64 r64;
792 		ut32 r32[2];
793 	} sp_top;
794 	union {
795 		ut64 r64;
796 		ut32 r32[2];
797 	} memval;
798 
799 	if (dbg->recoil_mode == R_DBG_RECOIL_NONE) {
800 		dbg->recoil_mode = R_DBG_RECOIL_STEP;
801 	}
802 
803 	if (r_debug_is_dead (dbg)) {
804 		return false;
805 	}
806 
807 	pc = r_debug_reg_get (dbg, dbg->reg->name[R_REG_NAME_PC]);
808 	sp = r_debug_reg_get (dbg, dbg->reg->name[R_REG_NAME_SP]);
809 
810 	if (!dbg->iob.read_at) {
811 		return false;
812 	}
813 	if (!dbg->iob.read_at (dbg->iob.io, pc, buf, sizeof (buf))) {
814 		return false;
815 	}
816 	if (!r_anal_op (dbg->anal, &op, pc, buf, sizeof (buf), R_ANAL_OP_MASK_BASIC)) {
817 		return false;
818 	}
819 	if (op.type == R_ANAL_OP_TYPE_ILL) {
820 		return false;
821 	}
822 	switch (op.type) {
823 	case R_ANAL_OP_TYPE_RET:
824 		dbg->iob.read_at (dbg->iob.io, sp, (ut8 *)&sp_top, 8);
825 		next[0] = (dbg->bits == R_SYS_BITS_32) ? sp_top.r32[0] : sp_top.r64;
826 		br = 1;
827 		break;
828 	case R_ANAL_OP_TYPE_CJMP:
829 	case R_ANAL_OP_TYPE_CCALL:
830 		next[0] = op.jump;
831 		next[1] = op.fail;
832 		br = 2;
833 		break;
834 	case R_ANAL_OP_TYPE_CALL:
835 	case R_ANAL_OP_TYPE_JMP:
836 		next[0] = op.jump;
837 		br = 1;
838 		break;
839 	case R_ANAL_OP_TYPE_RJMP:
840 	case R_ANAL_OP_TYPE_RCALL:
841 		r = r_debug_reg_get (dbg,op.reg);
842 		next[0] = r;
843 		br = 1;
844 		break;
845 	case R_ANAL_OP_TYPE_IRCALL:
846 	case R_ANAL_OP_TYPE_IRJMP:
847 		r = r_debug_reg_get (dbg,op.reg);
848 		if (!dbg->iob.read_at (dbg->iob.io, r, (ut8*)&memval, 8)) {
849 			next[0] = op.addr + op.size;
850 		} else {
851 			next[0] = (dbg->bits == R_SYS_BITS_32) ? memval.r32[0] : memval.r64;
852 		}
853 		br = 1;
854 		break;
855 	case R_ANAL_OP_TYPE_UCALL:
856 	case R_ANAL_OP_TYPE_MJMP:
857 		if (op.ireg) {
858 			r = r_debug_reg_get (dbg,op.ireg);
859 		} else {
860 			r = 0;
861 		}
862 		if (!dbg->iob.read_at (dbg->iob.io, r*op.scale + op.disp, (ut8*)&memval, 8)) {
863 			next[0] = op.addr + op.size;
864 		} else {
865 			next[0] = (dbg->bits == R_SYS_BITS_32) ? memval.r32[0] : memval.r64;
866 		}
867 		br = 1;
868 		break;
869 	case R_ANAL_OP_TYPE_UJMP:
870 	default:
871 		next[0] = op.addr + op.size;
872 		br = 1;
873 		break;
874 	}
875 
876 	for (i = 0; i < br; i++) {
877 		RBreakpointItem *bpi = r_bp_add_sw (dbg->bp, next[i], dbg->bpsize, R_BP_PROT_EXEC);
878 		if (bpi) {
879 			bpi->swstep = true;
880 		}
881 	}
882 
883 	ret = r_debug_continue (dbg);
884 
885 	for (i = 0; i < br; i++) {
886 		r_bp_del (dbg->bp, next[i]);
887 	}
888 
889 	return ret;
890 }
891 
r_debug_step_hard(RDebug * dbg,RBreakpointItem ** pb)892 R_API int r_debug_step_hard(RDebug *dbg, RBreakpointItem **pb) {
893 	RDebugReasonType reason;
894 
895 	dbg->reason.type = R_DEBUG_REASON_STEP;
896 	if (r_debug_is_dead (dbg)) {
897 		return false;
898 	}
899 
900 	/* only handle recoils when not already in recoil mode. */
901 	if (dbg->recoil_mode == R_DBG_RECOIL_NONE) {
902 		/* handle the stage-2 of breakpoints */
903 		if (!r_debug_recoil (dbg, R_DBG_RECOIL_STEP)) {
904 			return false;
905 		}
906 
907 		/* recoil already stepped once, so we don't step again. */
908 		if (dbg->recoil_mode == R_DBG_RECOIL_STEP) {
909 			dbg->recoil_mode = R_DBG_RECOIL_NONE;
910 			return true;
911 		}
912 	}
913 
914 	if (!dbg->h->step (dbg)) {
915 		return false;
916 	}
917 
918 #if __linux__
919 	// Turn off continue_all_threads to make sure linux_dbg_wait
920 	// only waits for one target for a single-step or breakpoint trap
921 	bool prev_continue = dbg->continue_all_threads;
922 	dbg->continue_all_threads = false;
923 #endif
924 	reason = r_debug_wait (dbg, pb);
925 #if __linux__
926 	dbg->continue_all_threads = prev_continue;
927 #endif
928 
929 	if (reason == R_DEBUG_REASON_DEAD || r_debug_is_dead (dbg)) {
930 		return false;
931 	}
932 	// Unset breakpoints before leaving
933 	if (reason != R_DEBUG_REASON_BREAKPOINT &&
934 		reason != R_DEBUG_REASON_COND &&
935 		reason != R_DEBUG_REASON_TRACEPOINT) {
936 		r_bp_restore (dbg->bp, false);
937 	}
938 	/* TODO: handle better */
939 	if (reason == R_DEBUG_REASON_ERROR) {
940 		return false;
941 	}
942 	return true;
943 }
944 
r_debug_step(RDebug * dbg,int steps)945 R_API int r_debug_step(RDebug *dbg, int steps) {
946 	RBreakpointItem *bp = NULL;
947 	int ret, steps_taken = 0;
948 
949 	/* who calls this without giving a positive number? */
950 	if (steps < 1) {
951 		steps = 1;
952 	}
953 
954 	if (!dbg || !dbg->h) {
955 		return steps_taken;
956 	}
957 
958 	if (r_debug_is_dead (dbg)) {
959 		return steps_taken;
960 	}
961 
962 	dbg->reason.type = R_DEBUG_REASON_STEP;
963 
964 	if (dbg->session) {
965 		if (dbg->session->cnum != dbg->session->maxcnum) {
966 			steps_taken = r_debug_step_cnum (dbg, steps);
967 		}
968 	}
969 
970 	for (; steps_taken < steps; steps_taken++) {
971 		if (dbg->session && dbg->recoil_mode == R_DBG_RECOIL_NONE) {
972 			dbg->session->cnum++;
973 			dbg->session->maxcnum++;
974 			dbg->session->bp = 0;
975 			if (!r_debug_trace_ins_before (dbg)) {
976 				eprintf ("trace_ins_before: failed");
977 			}
978 		}
979 
980 		if (dbg->swstep) {
981 			ret = r_debug_step_soft (dbg);
982 		} else {
983 			ret = r_debug_step_hard (dbg, &bp);
984 		}
985 		if (!ret) {
986 			eprintf ("Stepping failed!\n");
987 			return steps_taken;
988 		}
989 
990 		if (dbg->session && dbg->recoil_mode == R_DBG_RECOIL_NONE) {
991 			if (!r_debug_trace_ins_after (dbg)) {
992 				eprintf ("trace_ins_after: failed");
993 			}
994 			dbg->session->reasontype = dbg->reason.type;
995 			dbg->session->bp = bp;
996 		}
997 
998 		dbg->steps++;
999 		dbg->reason.type = R_DEBUG_REASON_STEP;
1000 	}
1001 
1002 	return steps_taken;
1003 }
1004 
isStepOverable(ut64 opType)1005 static bool isStepOverable(ut64 opType) {
1006 	switch (opType & R_ANAL_OP_TYPE_MASK) {
1007 	case R_ANAL_OP_TYPE_SWI:
1008 	case R_ANAL_OP_TYPE_CALL:
1009 	case R_ANAL_OP_TYPE_UCALL:
1010 	case R_ANAL_OP_TYPE_RCALL:
1011 		return true;
1012 	}
1013 	return false;
1014 }
1015 
r_debug_step_over(RDebug * dbg,int steps)1016 R_API int r_debug_step_over(RDebug *dbg, int steps) {
1017 	RAnalOp op;
1018 	ut64 buf_pc, pc, ins_size;
1019 	ut8 buf[DBG_BUF_SIZE];
1020 	int steps_taken = 0;
1021 
1022 	if (r_debug_is_dead (dbg)) {
1023 		return steps_taken;
1024 	}
1025 
1026 	if (steps < 1) {
1027 		steps = 1;
1028 	}
1029 
1030 	if (dbg->h && dbg->h->step_over) {
1031 		for (; steps_taken < steps; steps_taken++) {
1032 			if (dbg->session && dbg->recoil_mode == R_DBG_RECOIL_NONE) {
1033 				dbg->session->cnum++;
1034 				dbg->session->maxcnum++;
1035 				r_debug_trace_ins_before (dbg);
1036 			}
1037 			if (!dbg->h->step_over (dbg)) {
1038 				return steps_taken;
1039 			}
1040 			if (dbg->session && dbg->recoil_mode == R_DBG_RECOIL_NONE) {
1041 				r_debug_trace_ins_after (dbg);
1042 			}
1043 		}
1044 		return steps_taken;
1045 	}
1046 
1047 	if (!dbg->anal || !dbg->reg) {
1048 		return steps_taken;
1049 	}
1050 
1051 	// Initial refill
1052 	buf_pc = r_debug_reg_get (dbg, dbg->reg->name[R_REG_NAME_PC]);
1053 	dbg->iob.read_at (dbg->iob.io, buf_pc, buf, sizeof (buf));
1054 
1055 	for (; steps_taken < steps; steps_taken++) {
1056 		pc = r_debug_reg_get (dbg, dbg->reg->name[R_REG_NAME_PC]);
1057 		// Try to keep the buffer full
1058 		if (pc - buf_pc > sizeof (buf)) {
1059 			buf_pc = pc;
1060 			dbg->iob.read_at (dbg->iob.io, buf_pc, buf, sizeof (buf));
1061 		}
1062 		// Analyze the opcode
1063 		if (!r_anal_op (dbg->anal, &op, pc, buf + (pc - buf_pc), sizeof (buf) - (pc - buf_pc), R_ANAL_OP_MASK_BASIC)) {
1064 			eprintf ("debug-step-over: Decode error at %"PFMT64x"\n", pc);
1065 			return steps_taken;
1066 		}
1067 		if (op.fail == -1) {
1068 			ins_size = pc + op.size;
1069 		} else {
1070 			// Use op.fail here instead of pc+op.size to enforce anal backends to fill in this field
1071 			ins_size = op.fail;
1072 		}
1073 		// Skip over all the subroutine calls
1074 		if (isStepOverable (op.type)) {
1075 			if (!r_debug_continue_until (dbg, ins_size)) {
1076 				eprintf ("Could not step over call @ 0x%"PFMT64x"\n", pc);
1077 				return steps_taken;
1078 			}
1079 		} else if ((op.prefix & (R_ANAL_OP_PREFIX_REP | R_ANAL_OP_PREFIX_REPNE | R_ANAL_OP_PREFIX_LOCK))) {
1080 			//eprintf ("REP: skip to next instruction...\n");
1081 			if (!r_debug_continue_until (dbg, ins_size)) {
1082 				eprintf ("step over failed over rep\n");
1083 				return steps_taken;
1084 			}
1085 		} else {
1086 			r_debug_step (dbg, 1);
1087 		}
1088 	}
1089 
1090 	return steps_taken;
1091 }
1092 
r_debug_goto_cnum(RDebug * dbg,ut32 cnum)1093 R_API bool r_debug_goto_cnum(RDebug *dbg, ut32 cnum) {
1094 	if (cnum > dbg->session->maxcnum) {
1095 		eprintf ("Error: out of cnum range\n");
1096 		return false;
1097 	}
1098 	dbg->session->cnum = cnum;
1099 	r_debug_session_restore_reg_mem (dbg, cnum);
1100 
1101 	return true;
1102 }
1103 
r_debug_step_back(RDebug * dbg,int steps)1104 R_API int r_debug_step_back(RDebug *dbg, int steps) {
1105 	if (steps > dbg->session->cnum) {
1106 		steps = dbg->session->cnum;
1107 	}
1108 	if (!r_debug_goto_cnum (dbg, dbg->session->cnum - steps)) {
1109 		return -1;
1110 	}
1111 	return steps;
1112 }
1113 
r_debug_step_cnum(RDebug * dbg,int steps)1114 R_API int r_debug_step_cnum(RDebug *dbg, int steps) {
1115 	if (steps > dbg->session->maxcnum - dbg->session->cnum) {
1116 		steps = dbg->session->maxcnum - dbg->session->cnum;
1117 	}
1118 
1119 	r_debug_goto_cnum (dbg, dbg->session->cnum + steps);
1120 
1121 	return steps;
1122 }
1123 
r_debug_continue_kill(RDebug * dbg,int sig)1124 R_API int r_debug_continue_kill(RDebug *dbg, int sig) {
1125 	RDebugReasonType reason = R_DEBUG_REASON_NONE;
1126 	int ret = 0;
1127 	RBreakpointItem *bp = NULL;
1128 
1129 	if (!dbg) {
1130 		return 0;
1131 	}
1132 
1133 	// If the debugger is not at the end of the changes
1134 	// Go to the end or the next breakpoint in the changes
1135 	if (dbg->session && dbg->session->cnum != dbg->session->maxcnum) {
1136 		bool has_bp = false;
1137 		RRegItem *ripc = r_reg_get (dbg->reg, dbg->reg->name[R_REG_NAME_PC], R_REG_TYPE_GPR);
1138 		RVector *vreg = ht_up_find (dbg->session->registers, ripc->offset | (ripc->arena << 16), NULL);
1139 		RDebugChangeReg *reg;
1140 		r_vector_foreach_prev (vreg, reg) {
1141 			if (reg->cnum <= dbg->session->cnum) {
1142 				continue;
1143 			}
1144 			has_bp = r_bp_get_in (dbg->bp, reg->data, R_BP_PROT_EXEC) != NULL;
1145 			if (has_bp) {
1146 				eprintf ("hit breakpoint at: 0x%" PFMT64x " cnum: %d\n", reg->data, reg->cnum);
1147 				r_debug_goto_cnum (dbg, reg->cnum);
1148 				return dbg->tid;
1149 			}
1150 		}
1151 
1152 		r_debug_goto_cnum (dbg, dbg->session->maxcnum);
1153 		return dbg->tid;
1154 	}
1155 
1156 repeat:
1157 	if (r_debug_is_dead (dbg)) {
1158 		return 0;
1159 	}
1160 	if (dbg->session && dbg->trace_continue) {
1161 		while (!r_cons_is_breaked ()) {
1162 			if (r_debug_step (dbg, 1) != 1) {
1163 				break;
1164 			}
1165 			if (dbg->session->reasontype != R_DEBUG_REASON_STEP) {
1166 				break;
1167 			}
1168 		}
1169 		reason = dbg->session->reasontype;
1170 		bp = dbg->session->bp;
1171 	} else if (dbg->h && dbg->h->cont) {
1172 		/* handle the stage-2 of breakpoints */
1173 		if (!r_debug_recoil (dbg, R_DBG_RECOIL_CONTINUE)) {
1174 			return 0;
1175 		}
1176 		/* tell the inferior to go! */
1177 		ret = dbg->h->cont (dbg, dbg->pid, dbg->tid, sig);
1178 		//XXX(jjd): why? //dbg->reason.signum = 0;
1179 		reason = r_debug_wait (dbg, &bp);
1180 	} else {
1181 		return 0;
1182 	}
1183 
1184 	if (dbg->corebind.core) {
1185 		RCore *core = (RCore *)dbg->corebind.core;
1186 		RNum *num = core->num;
1187 		if (reason == R_DEBUG_REASON_COND) {
1188 			if (bp && bp->cond && dbg->corebind.cmd) {
1189 				dbg->corebind.cmd (dbg->corebind.core, bp->cond);
1190 			}
1191 			if (num->value) {
1192 				goto repeat;
1193 			}
1194 		}
1195 	}
1196 	if (reason == R_DEBUG_REASON_BREAKPOINT &&
1197 	   ((bp && !bp->enabled) || (!bp && !r_cons_is_breaked () && dbg->corebind.core &&
1198 					dbg->corebind.cfggeti (dbg->corebind.core, "dbg.bpsysign")))) {
1199 		goto repeat;
1200 	}
1201 
1202 #if __linux__
1203 	if (reason == R_DEBUG_REASON_NEW_PID && dbg->follow_child) {
1204 #if DEBUGGER
1205 		/// if the plugin is not compiled link fails, so better do runtime linking
1206 		/// until this code gets fixed
1207 		static bool (*linux_attach_new_process) (RDebug *dbg, int pid) = NULL;
1208 		if (!linux_attach_new_process) {
1209 			linux_attach_new_process = r_lib_dl_sym (NULL, "linux_attach_new_process");
1210 		}
1211 		if (linux_attach_new_process) {
1212 			linux_attach_new_process (dbg, dbg->forked_pid);
1213 		}
1214 #endif
1215 		goto repeat;
1216 	}
1217 
1218 	if (reason == R_DEBUG_REASON_NEW_TID) {
1219 		ret = dbg->tid;
1220 		if (!dbg->trace_clone) {
1221 			goto repeat;
1222 		}
1223 	}
1224 
1225 	if (reason == R_DEBUG_REASON_EXIT_TID) {
1226 		goto repeat;
1227 	}
1228 #endif
1229 	if (reason != R_DEBUG_REASON_DEAD) {
1230 		ret = dbg->tid;
1231 	}
1232 #if __WINDOWS__
1233 	if (reason == R_DEBUG_REASON_NEW_LIB ||
1234 		reason == R_DEBUG_REASON_EXIT_LIB ||
1235 		reason == R_DEBUG_REASON_NEW_TID ||
1236 		reason == R_DEBUG_REASON_NONE ||
1237 		reason == R_DEBUG_REASON_EXIT_TID ) {
1238 		goto repeat;
1239 	}
1240 #endif
1241 	if (reason == R_DEBUG_REASON_EXIT_PID) {
1242 #if __WINDOWS__
1243 		dbg->pid = -1;
1244 #elif __linux__
1245 		r_debug_bp_update (dbg);
1246 		r_bp_restore (dbg->bp, false); // (vdf) there has got to be a better way
1247 #endif
1248 	}
1249 
1250 	/* if continuing killed the inferior, we won't be able to get
1251 	 * the registers.. */
1252 	if (reason == R_DEBUG_REASON_DEAD || r_debug_is_dead (dbg)) {
1253 		return 0;
1254 	}
1255 
1256 	/* if we hit a tracing breakpoint, we need to continue in
1257 	 * whatever mode the user desired. */
1258 	if (reason == R_DEBUG_REASON_TRACEPOINT) {
1259 		r_debug_step (dbg, 1);
1260 		goto repeat;
1261 	}
1262 
1263 	/* choose the thread that was returned from the continue function */
1264 	// XXX(jjd): there must be a cleaner way to do this...
1265 	if (ret != dbg->tid) {
1266 		r_debug_select (dbg, dbg->pid, ret);
1267 	}
1268 	sig = 0; // clear continuation after signal if needed
1269 
1270 	/* handle general signals here based on the return from the wait
1271 	 * function */
1272 	if (dbg->reason.signum != -1) {
1273 		int what = r_debug_signal_what (dbg, dbg->reason.signum);
1274 		if (what & R_DBG_SIGNAL_CONT) {
1275 			sig = dbg->reason.signum;
1276 			eprintf ("Continue into the signal %d handler\n", sig);
1277 			goto repeat;
1278 		} else if (what & R_DBG_SIGNAL_SKIP) {
1279 			// skip signal. requires skipping one instruction
1280 			ut8 buf[64];
1281 			RAnalOp op = {0};
1282 			ut64 pc = r_debug_reg_get (dbg, "PC");
1283 			dbg->iob.read_at (dbg->iob.io, pc, buf, sizeof (buf));
1284 			r_anal_op (dbg->anal, &op, pc, buf, sizeof (buf), R_ANAL_OP_MASK_BASIC);
1285 			if (op.size > 0) {
1286 				const char *signame = r_signal_to_string (dbg->reason.signum);
1287 				r_debug_reg_set (dbg, "PC", pc+op.size);
1288 				eprintf ("Skip signal %d handler %s\n",
1289 					dbg->reason.signum, signame);
1290 				goto repeat;
1291 			} else {
1292 				ut64 pc = r_debug_reg_get (dbg, "PC");
1293 				eprintf ("Stalled with an exception at 0x%08"PFMT64x"\n", pc);
1294 			}
1295 		}
1296 	}
1297 #if __WINDOWS__
1298 	r_cons_break_pop ();
1299 #endif
1300 
1301 	// Unset breakpoints before leaving
1302 	if (reason != R_DEBUG_REASON_BREAKPOINT) {
1303 		r_bp_restore (dbg->bp, false);
1304 	}
1305 
1306 	// Add a checkpoint at stops
1307 	if (dbg->session && !dbg->trace_continue) {
1308 		dbg->session->cnum++;
1309 		dbg->session->maxcnum++;
1310 		r_debug_add_checkpoint (dbg);
1311 	}
1312 
1313 	return ret;
1314 }
1315 
r_debug_continue(RDebug * dbg)1316 R_API int r_debug_continue(RDebug *dbg) {
1317 	return r_debug_continue_kill (dbg, 0); //dbg->reason.signum);
1318 }
1319 
1320 #if __WINDOWS__
r_debug_continue_pass_exception(RDebug * dbg)1321 R_API int r_debug_continue_pass_exception(RDebug *dbg) {
1322 	return r_debug_continue_kill (dbg, DBG_EXCEPTION_NOT_HANDLED);
1323 }
1324 #endif
1325 
r_debug_continue_until_nontraced(RDebug * dbg)1326 R_API int r_debug_continue_until_nontraced(RDebug *dbg) {
1327 	eprintf ("TODO\n");
1328 	return false;
1329 }
1330 
r_debug_continue_until_optype(RDebug * dbg,int type,int over)1331 R_API int r_debug_continue_until_optype(RDebug *dbg, int type, int over) {
1332 	int ret, n = 0;
1333 	ut64 pc, buf_pc = 0;
1334 	RAnalOp op;
1335 	ut8 buf[DBG_BUF_SIZE];
1336 
1337 	if (r_debug_is_dead (dbg)) {
1338 		return false;
1339 	}
1340 
1341 	if (!dbg->anal || !dbg->reg) {
1342 		eprintf ("Undefined pointer at dbg->anal\n");
1343 		return false;
1344 	}
1345 
1346 	r_debug_step (dbg, 1);
1347 	r_debug_reg_sync (dbg, R_REG_TYPE_GPR, false);
1348 
1349 	// Initial refill
1350 	buf_pc = r_debug_reg_get (dbg, dbg->reg->name[R_REG_NAME_PC]);
1351 	dbg->iob.read_at (dbg->iob.io, buf_pc, buf, sizeof (buf));
1352 
1353 	// step first, we don't want to check current optype
1354 	for (;;) {
1355 		if (!r_debug_reg_sync (dbg, R_REG_TYPE_GPR, false)) {
1356 			break;
1357 		}
1358 
1359 		pc = r_debug_reg_get (dbg, dbg->reg->name[R_REG_NAME_PC]);
1360 		// Try to keep the buffer full
1361 		if (pc - buf_pc > sizeof (buf)) {
1362 			buf_pc = pc;
1363 			dbg->iob.read_at (dbg->iob.io, buf_pc, buf, sizeof (buf));
1364 		}
1365 		// Analyze the opcode
1366 		if (!r_anal_op (dbg->anal, &op, pc, buf + (pc - buf_pc), sizeof (buf) - (pc - buf_pc), R_ANAL_OP_MASK_BASIC)) {
1367 			eprintf ("Decode error at %"PFMT64x"\n", pc);
1368 			return false;
1369 		}
1370 		if (op.type == type) {
1371 			break;
1372 		}
1373 		// Step over and repeat
1374 		ret = over
1375 			? r_debug_step_over (dbg, 1)
1376 			: r_debug_step (dbg, 1);
1377 
1378 		if (!ret) {
1379 			eprintf ("r_debug_step: failed\n");
1380 			break;
1381 		}
1382 		n++;
1383 	}
1384 
1385 	return n;
1386 }
1387 
r_debug_continue_until_internal(RDebug * dbg,ut64 addr,bool block)1388 static int r_debug_continue_until_internal(RDebug *dbg, ut64 addr, bool block) {
1389 	if (r_debug_is_dead (dbg)) {
1390 		return false;
1391 	}
1392 	// Check if there was another breakpoint set at addr
1393 	bool has_bp = r_bp_get_in (dbg->bp, addr, R_BP_PROT_EXEC) != NULL;
1394 	if (!has_bp) {
1395 		r_bp_add_sw (dbg->bp, addr, dbg->bpsize, R_BP_PROT_EXEC);
1396 	}
1397 
1398 	// Continue until the bp is reached
1399 	dbg->reason.type = 0;
1400 	for (;;) {
1401 		if (r_debug_is_dead (dbg) || dbg->reason.type) {
1402 			break;
1403 		}
1404 		ut64 pc = r_debug_reg_get (dbg, dbg->reg->name[R_REG_NAME_PC]);
1405 		if (pc == addr) {
1406 			break;
1407 		}
1408 		if (block && r_bp_get_at (dbg->bp, pc)) {
1409 			break;
1410 		}
1411 		r_debug_continue (dbg);
1412 	}
1413 	// Clean up if needed
1414 	if (!has_bp) {
1415 		r_bp_del (dbg->bp, addr);
1416 	}
1417 	return true;
1418 }
1419 
r_debug_continue_until(RDebug * dbg,ut64 addr)1420 R_API int r_debug_continue_until(RDebug *dbg, ut64 addr) {
1421 	return r_debug_continue_until_internal (dbg, addr, true);
1422 }
1423 
r_debug_continue_until_nonblock(RDebug * dbg,ut64 addr)1424 R_API int r_debug_continue_until_nonblock(RDebug *dbg, ut64 addr) {
1425 	return r_debug_continue_until_internal (dbg, addr, false);
1426 }
1427 
r_debug_continue_back(RDebug * dbg)1428 R_API bool r_debug_continue_back(RDebug *dbg) {
1429 	int cnum;
1430 	bool has_bp = false;
1431 
1432 	RRegItem *ripc = r_reg_get (dbg->reg, dbg->reg->name[R_REG_NAME_PC], R_REG_TYPE_GPR);
1433 	RVector *vreg = ht_up_find (dbg->session->registers, ripc->offset | (ripc->arena << 16), NULL);
1434 	if (!vreg) {
1435 		eprintf ("Error: cannot find PC change vector");
1436 		return false;
1437 	}
1438 	RDebugChangeReg *reg;
1439 	r_vector_foreach_prev (vreg, reg) {
1440 		if (reg->cnum >= dbg->session->cnum) {
1441 			continue;
1442 		}
1443 		has_bp = r_bp_get_in (dbg->bp, reg->data, R_BP_PROT_EXEC) != NULL;
1444 		if (has_bp) {
1445 			cnum = reg->cnum;
1446 			eprintf ("hit breakpoint at: 0x%" PFMT64x " cnum: %d\n", reg->data, reg->cnum);
1447 			break;
1448 		}
1449 	}
1450 
1451 	if (has_bp) {
1452 		r_debug_goto_cnum (dbg, cnum);
1453 	} else {
1454 		if (dbg->session->maxcnum > 0) {
1455 			r_debug_goto_cnum (dbg, 0);
1456 		}
1457 	}
1458 
1459 	return true;
1460 }
1461 
show_syscall(RDebug * dbg,const char * sysreg)1462 static int show_syscall(RDebug *dbg, const char *sysreg) {
1463 	const char *sysname;
1464 	char regname[32];
1465 	int reg, i, args;
1466 	RSyscallItem *si;
1467 	reg = (int)r_debug_reg_get (dbg, sysreg);
1468 	si = r_syscall_get (dbg->anal->syscall, reg, -1);
1469 	if (si) {
1470 		sysname = r_str_get_fail (si->name, "unknown");
1471 		args = si->args;
1472 	} else {
1473 		sysname = "unknown";
1474 		args = 3;
1475 	}
1476 	eprintf ("--> %s 0x%08"PFMT64x" syscall %d %s (", sysreg,
1477 			r_debug_reg_get (dbg, "PC"), reg, sysname);
1478 	for (i=0; i<args; i++) {
1479 		ut64 val;
1480 		snprintf (regname, sizeof (regname)-1, "A%d", i);
1481 		val = r_debug_reg_get (dbg, regname);
1482 		if (((st64)val<0) && ((st64)val>-0xffff)) {
1483 			eprintf ("%"PFMT64d"%s", val, (i+1==args)?"":" ");
1484 		} else {
1485 			eprintf ("0x%"PFMT64x"%s", val, (i+1==args)?"":" ");
1486 		}
1487 	}
1488 	eprintf (")\n");
1489 	r_syscall_item_free (si);
1490 	return reg;
1491 }
1492 
r_debug_continue_syscalls(RDebug * dbg,int * sc,int n_sc)1493 R_API int r_debug_continue_syscalls(RDebug *dbg, int *sc, int n_sc) {
1494 	int i, err, reg, ret = false;
1495 	if (!dbg || !dbg->h || r_debug_is_dead (dbg)) {
1496 		return false;
1497 	}
1498 	if (!dbg->h->contsc) {
1499 		/* user-level syscall tracing */
1500 		r_debug_continue_until_optype (dbg, R_ANAL_OP_TYPE_SWI, 0);
1501 		return show_syscall (dbg, "A0");
1502 	}
1503 
1504 	if (!r_debug_reg_sync (dbg, R_REG_TYPE_GPR, false)) {
1505 		eprintf ("--> cannot read registers\n");
1506 		return -1;
1507 	}
1508 	reg = (int)r_debug_reg_get_err (dbg, "SN", &err, NULL);
1509 	if (err) {
1510 		eprintf ("Cannot find 'sn' register for current arch-os.\n");
1511 		return -1;
1512 	}
1513 	for (;;) {
1514 		RDebugReasonType reason;
1515 
1516 		if (r_cons_singleton ()->context->breaked) {
1517 			break;
1518 		}
1519 #if __linux__
1520 		// step is needed to avoid dupped contsc results
1521 		/* XXX(jjd): actually one stop is before the syscall, the other is
1522 		 * after.  this allows you to inspect the arguments before and the
1523 		 * return value after... */
1524 		r_debug_step (dbg, 1);
1525 #endif
1526 		dbg->h->contsc (dbg, dbg->pid, 0); // TODO handle return value
1527 		// wait until continuation
1528 		reason = r_debug_wait (dbg, NULL);
1529 		if (reason == R_DEBUG_REASON_DEAD || r_debug_is_dead (dbg)) {
1530 			break;
1531 		}
1532 #if 0
1533 		if (reason != R_DEBUG_REASON_STEP) {
1534 			eprintf ("astep\n");
1535 			break;
1536 		}
1537 #endif
1538 		if (!r_debug_reg_sync (dbg, R_REG_TYPE_GPR, false)) {
1539 			eprintf ("--> cannot sync regs, process is probably dead\n");
1540 			return -1;
1541 		}
1542 		reg = show_syscall (dbg, "SN");
1543 
1544 		if (dbg->corebind.core && dbg->corebind.syshit) {
1545 			dbg->corebind.syshit (dbg->corebind.core);
1546 		}
1547 
1548 		if (n_sc == -1) {
1549 			continue;
1550 		}
1551 		if (n_sc == 0) {
1552 			break;
1553 		}
1554 		for (i = 0; i < n_sc; i++) {
1555 			if (sc[i] == reg) {
1556 				return reg;
1557 			}
1558 		}
1559 		// TODO: must use r_core_cmd(as)..import code from rcore
1560 	}
1561 	return ret;
1562 }
1563 
r_debug_continue_syscall(RDebug * dbg,int sc)1564 R_API int r_debug_continue_syscall(RDebug *dbg, int sc) {
1565 	return r_debug_continue_syscalls (dbg, &sc, 1);
1566 }
1567 
1568 // TODO: remove from here? this is code injection!
r_debug_syscall(RDebug * dbg,int num)1569 R_API int r_debug_syscall(RDebug *dbg, int num) {
1570 	bool ret = true;
1571 	if (dbg->h->contsc) {
1572 		ret = dbg->h->contsc (dbg, dbg->pid, num);
1573 	}
1574 	eprintf ("TODO: show syscall information\n");
1575 	/* r2rc task? ala inject? */
1576 	return (int)ret;
1577 }
1578 
r_debug_kill(RDebug * dbg,int pid,int tid,int sig)1579 R_API int r_debug_kill(RDebug *dbg, int pid, int tid, int sig) {
1580 	if (r_debug_is_dead (dbg)) {
1581 		return false;
1582 	}
1583 	if (dbg->h && dbg->h->kill) {
1584 		if (pid > 0) {
1585 			return dbg->h->kill (dbg, pid, tid, sig);
1586 		}
1587 		return -1;
1588 	}
1589 	eprintf ("Backend does not implement kill()\n");
1590 	return false;
1591 }
1592 
r_debug_frames(RDebug * dbg,ut64 at)1593 R_API RList *r_debug_frames(RDebug *dbg, ut64 at) {
1594 	if (dbg && dbg->h && dbg->h->frames) {
1595 		return dbg->h->frames (dbg, at);
1596 	}
1597 	return NULL;
1598 }
1599 
1600 /* TODO: Implement fork and clone */
r_debug_child_fork(RDebug * dbg)1601 R_API int r_debug_child_fork(RDebug *dbg) {
1602 	//if (dbg && dbg->h && dbg->h->frames)
1603 		//return dbg->h->frames (dbg);
1604 	return 0;
1605 }
1606 
r_debug_child_clone(RDebug * dbg)1607 R_API int r_debug_child_clone(RDebug *dbg) {
1608 	//if (dbg && dbg->h && dbg->h->frames)
1609 		//return dbg->h->frames (dbg);
1610 	return 0;
1611 }
1612 
r_debug_is_dead(RDebug * dbg)1613 R_API bool r_debug_is_dead(RDebug *dbg) {
1614 	if (!dbg->h) {
1615 		return false;
1616 	}
1617 	// workaround for debug.io.. should be generic
1618 	if (!strcmp (dbg->h->name, "io")) {
1619 		return false;
1620 	}
1621 	bool is_dead = (dbg->pid == -1 && strncmp (dbg->h->name, "gdb", 3)) || (dbg->reason.type == R_DEBUG_REASON_DEAD);
1622 	if (dbg->pid > 0 && dbg->h && dbg->h->kill) {
1623 		is_dead = !dbg->h->kill (dbg, dbg->pid, false, 0);
1624 	}
1625 #if 0
1626 	if (!is_dead && dbg->h && dbg->h->kill) {
1627 		is_dead = !dbg->h->kill (dbg, dbg->pid, false, 0);
1628 	}
1629 #endif
1630 	if (is_dead) {
1631 		dbg->reason.type = R_DEBUG_REASON_DEAD;
1632 	}
1633 	return is_dead;
1634 }
1635 
r_debug_map_protect(RDebug * dbg,ut64 addr,int size,int perms)1636 R_API int r_debug_map_protect(RDebug *dbg, ut64 addr, int size, int perms) {
1637 	if (dbg && dbg->h && dbg->h->map_protect) {
1638 		return dbg->h->map_protect (dbg, addr, size, perms);
1639 	}
1640 	return false;
1641 }
1642 
r_debug_drx_list(RDebug * dbg)1643 R_API void r_debug_drx_list(RDebug *dbg) {
1644 	if (dbg && dbg->h && dbg->h->drx) {
1645 		dbg->h->drx (dbg, 0, 0, 0, 0, 0, DRX_API_LIST);
1646 	}
1647 }
1648 
r_debug_drx_set(RDebug * dbg,int idx,ut64 addr,int len,int rwx,int g)1649 R_API int r_debug_drx_set(RDebug *dbg, int idx, ut64 addr, int len, int rwx, int g) {
1650 	if (dbg && dbg->h && dbg->h->drx) {
1651 		return dbg->h->drx (dbg, idx, addr, len, rwx, g, DRX_API_SET_BP);
1652 	}
1653 	return false;
1654 }
1655 
r_debug_drx_unset(RDebug * dbg,int idx)1656 R_API int r_debug_drx_unset(RDebug *dbg, int idx) {
1657 	if (dbg && dbg->h && dbg->h->drx) {
1658 		return dbg->h->drx (dbg, idx, 0, -1, 0, 0, DRX_API_REMOVE_BP);
1659 	}
1660 	return false;
1661 }
1662 
r_debug_get_baddr(RDebug * dbg,const char * file)1663 R_API ut64 r_debug_get_baddr(RDebug *dbg, const char *file) {
1664 	if (!dbg || !dbg->iob.io || !dbg->iob.io->desc) {
1665 		return 0LL;
1666 	}
1667 	if (!strcmp (dbg->iob.io->desc->plugin->name, "gdb")) {		//this is very bad
1668 		// Tell gdb that we want baddr, not full mem map
1669 		dbg->iob.system (dbg->iob.io, "baddr");
1670 	}
1671 	int pid = r_io_desc_get_pid (dbg->iob.io->desc);
1672 	int tid = r_io_desc_get_tid (dbg->iob.io->desc);
1673 	if (pid < 0 || tid < 0) {
1674 		return 0LL;
1675 	}
1676 	if (r_debug_attach (dbg, pid) == -1) {
1677 		return 0LL;
1678 	}
1679 #if __WINDOWS__
1680 	ut64 base;
1681 	bool ret = r_io_desc_get_base (dbg->iob.io->desc, &base);
1682 	if (ret) {
1683 		return base;
1684 	}
1685 #endif
1686 	RListIter *iter;
1687 	RDebugMap *map;
1688 	r_debug_select (dbg, pid, tid);
1689 	r_debug_map_sync (dbg);
1690 	char *abspath = r_sys_pid_to_path (pid);
1691 #if !__WINDOWS__
1692 	if (!abspath) {
1693 		abspath = r_file_abspath (file);
1694 	}
1695 #endif
1696 	if (!abspath) {
1697 		abspath = strdup (file);
1698 	}
1699 	if (abspath) {
1700 		r_list_foreach (dbg->maps, iter, map) {
1701 			if (!strcmp (abspath, map->name)) {
1702 				free (abspath);
1703 				return map->addr;
1704 			}
1705 		}
1706 		free (abspath);
1707 	}
1708 	// fallback resolution (osx/w32?)
1709 	// we assume maps to be loaded in order, so lower addresses come first
1710 	r_list_foreach (dbg->maps, iter, map) {
1711 		if (map->perm == 5) { // r-x
1712 			return map->addr;
1713 		}
1714 	}
1715 	return 0LL;
1716 }
1717 
r_debug_bp_rebase(RDebug * dbg,ut64 old_base,ut64 new_base)1718 R_API void r_debug_bp_rebase(RDebug *dbg, ut64 old_base, ut64 new_base) {
1719 	RBreakpointItem *bp;
1720 	RListIter *iter;
1721 	ut64 diff = new_base - old_base;
1722 	// update bp->baddr
1723 	dbg->bp->baddr = new_base;
1724 
1725 	// update bp's address
1726 	r_list_foreach (dbg->bp->bps, iter, bp) {
1727 		bp->addr += diff;
1728 		bp->delta = bp->addr - dbg->bp->baddr;
1729 	}
1730 }
1731