1/*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22/*
23 * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24 * Use is subject to license terms.
25 */
26
27/*
28 * Implements the routines that are needed only for internal process
29 * control.
30 */
31
32#ifndef DEBUG
33#define	NDEBUG	1
34#endif
35
36#include "tnfctl_int.h"
37#include "kernel_int.h"
38#include "dbg.h"
39
40#include <stdio.h>
41#include <sys/types.h>
42#include <stdlib.h>
43#include <unistd.h>
44#include <string.h>
45#include <link.h>
46#include <sys/stat.h>
47#include <fcntl.h>
48#include <sys/param.h>
49#include <sys/procfs.h>
50#include <assert.h>
51#include <dlfcn.h>
52
53static int inprocess_read(void *ignore,
54    uintptr_t addr, void *buf, size_t size);
55static int inprocess_write(void *ignore,
56    uintptr_t addr, void *buf, size_t size);
57static pid_t inprocess_getpid(void *ignore);
58static tnfctl_errcode_t inprocess_get_dtdebug(void *hndl, uintptr_t *ret_val);
59static int inprocess_loadobj_iter(void *opq, tnfctl_ind_obj_f *obj_func,
60					void *cd);
61
62/*
63 * Cause interposition on dlclose() and dlopen()
64 */
65#pragma weak dlclose = _tnfctl_dlclose
66
67#pragma weak dlopen = _tnfctl_dlopen
68
69/*
70 * The lock used to protect the _tnfctl_internal_tracing_flag variable.
71 *
72 */
73mutex_t		_tnfctl_internalguard_lock = DEFAULTMUTEX;
74boolean_t	_tnfctl_internal_tracing_flag = 0;
75pid_t		_tnfctl_externally_traced_pid = NOPID;
76
77/*
78 * Returns a pointer to a tnfctl handle that can do in process probe control.
79 */
80tnfctl_errcode_t
81tnfctl_internal_open(tnfctl_handle_t **ret_val)
82{
83	tnfctl_handle_t	*hdl;
84	tnfctl_errcode_t	prexstat;
85	uintptr_t		dbgaddr;
86
87	/* allocate hdl and zero fill */
88	hdl = calloc(1, sizeof (*hdl));
89	if (hdl == NULL) {
90		return (TNFCTL_ERR_ALLOCFAIL);
91	}
92
93	hdl->mode = INTERNAL_MODE;
94	hdl->called_exit = B_FALSE;
95
96	/* plug in inprocess call back functions */
97	hdl->p_read = inprocess_read;
98	hdl->p_write = inprocess_write;
99	hdl->p_obj_iter = inprocess_loadobj_iter;
100	hdl->p_getpid = inprocess_getpid;
101
102	/*
103	 * get the address of DT_DEBUG and store it in proc_p
104	 * (the handle on the same process is the dbg address)
105	 */
106	prexstat = inprocess_get_dtdebug(hdl, &dbgaddr);
107	if (prexstat) {
108		free(hdl);
109		return (prexstat);
110	}
111	hdl->proc_p = (void *) dbgaddr;
112
113	/* initialize state in handle */
114	prexstat = _tnfctl_set_state(hdl);
115	if (prexstat) {
116		free(hdl);
117		return (prexstat);
118	}
119	/* see if process is already being traced */
120	prexstat = _tnfctl_internal_getlock();
121	if (prexstat) {
122		free(hdl);
123		return (prexstat);
124	}
125	*ret_val = hdl;
126	return (TNFCTL_ERR_NONE);
127}
128
129/*
130 * reads a block of memory from the same address space.
131 */
132static int
133inprocess_read(void *ignore, uintptr_t addr, void *buf, size_t size)
134{
135
136	DBG_TNF_PROBE_2(inprocess_read_1, "libtnfctl", "sunw%verbosity 3;",
137		tnf_long, num_bytes, size,
138		tnf_opaque, from_address, addr);
139
140	(void) memcpy(buf, (void *) addr, size);
141	return (0);
142}
143
144/*
145 * writes a block of memory to the same address space.
146 */
147static int
148inprocess_write(void *ignore, uintptr_t addr, void *buf, size_t size)
149{
150
151	DBG_TNF_PROBE_2(inprocess_write_1, "libtnfctl", "sunw%verbosity 3;",
152		tnf_long, num_bytes, size,
153		tnf_opaque, to_address, addr);
154
155	(void) memcpy((void *)addr, buf, size);
156	return (0);
157}
158
159/*
160 * returns the pid of the process.
161 */
162static pid_t
163inprocess_getpid(void *ignore)
164{
165	return (getpid());
166}
167extern Elf3264_Dyn _DYNAMIC;
168
169/*
170 * returns the address of the DT_DEBUG field in the _DYNAMIC array
171 * of the same address space.
172 */
173static tnfctl_errcode_t
174inprocess_get_dtdebug(void *hndl, uintptr_t *ret_val)
175{
176	Elf3264_Dyn 	*dyn = &_DYNAMIC;
177	Elf3264_Dyn	*dp;
178
179	for (dp = dyn; dp->d_tag != DT_NULL; dp++) {
180		if (dp->d_tag == DT_DEBUG) {
181			*ret_val = (uintptr_t) dp;
182			return (TNFCTL_ERR_NONE);
183		}
184	}
185	return (TNFCTL_ERR_INTERNAL);
186}
187
188#define	PROCFORMAT	"/proc/%d"
189
190/*
191 * iterate over all loadobjects in the same address space calling the
192 * callback function "obj_func".
193 */
194static int
195inprocess_loadobj_iter(void *opq, tnfctl_ind_obj_f *obj_func, void *cd)
196{
197	Elf3264_Dyn	*dtdebug = opq;
198	struct r_debug	*r_dbg;
199	struct link_map *lmap;
200	char		path[MAXPATHLEN];
201	int		procfd;
202	tnfctl_ind_obj_info_t	loadobj;
203	int		retval = 0;	/* sucessful return */
204
205	DBG_TNF_PROBE_0(inprocess_loadobj_iter_start, "libtnfctl",
206			"start inprocess_loadobj_iter; sunw%verbosity 1");
207
208	r_dbg = (struct r_debug *)dtdebug->d_un.d_ptr;
209
210	DBG_TNF_PROBE_1(inprocess_loadobj_iter_1, "libtnfctl",
211		"sunw%verbosity 1",
212		tnf_string, link_map_state,
213		(r_dbg->r_state == RT_CONSISTENT) ? "RT_CONSISTENT" :
214			(r_dbg->r_state == RT_ADD) ? "RT_ADD" : "RT_DELETE");
215
216	/* bail if link map is not consistent */
217	if (r_dbg->r_state != RT_CONSISTENT)
218		return (1);
219
220	(void) sprintf(path, PROCFORMAT, (int) getpid());
221
222	/*
223	 * opening /proc readonly, so debuggers can still run
224	 * We use /proc in order to get fd on the object.
225	 */
226	procfd = open(path, O_RDONLY);
227	if (procfd == -1)
228		return (1);
229
230	for (lmap = r_dbg->r_map; lmap; lmap = lmap->l_next) {
231		loadobj.text_base = lmap->l_addr;
232		loadobj.data_base = lmap->l_addr;
233		loadobj.objname = lmap->l_name;
234		/*
235		 * client of this interface should deal with -1 for objfd,
236		 * so no error checking is needed on this ioctl
237		 */
238		loadobj.objfd = ioctl(procfd, PIOCOPENM, &(lmap->l_addr));
239
240		retval = obj_func(opq, &loadobj, cd);
241
242		/* close the fd */
243		if (loadobj.objfd != -1)
244			close(loadobj.objfd);
245
246		/* check for error */
247		if (retval == 1)
248			goto end_of_func;
249	}
250
251end_of_func:
252	close(procfd);
253
254	DBG_TNF_PROBE_0(inprocess_loadobj_iter_end, "libtnfctl",
255			"end inprocess_loadobj_iter; sunw%verbosity 1");
256	return (retval);
257}
258
259/*
260 * The lock that prevents a thread from accessing our cached library list
261 * and a dlopen or dlclose happening at the same time in another thread.
262 */
263mutex_t		_tnfctl_lmap_lock = DEFAULTMUTEX;
264
265/*
266 * The flag that indicates that the library list has changed via a
267 * dlopen or dlclose.
268 */
269boolean_t	_tnfctl_libs_changed = B_FALSE;
270
271/*
272 * Thread id of the owner of the lock in order to implement a
273 * recursive lock i.e. no deadlock if the same thread tries to lock
274 * a lock it already holds.
275 */
276static thread_t	lock_holder = 0;	/* XXX - no tid with 0 */
277
278#define	LMAP_LOCK	(&_tnfctl_lmap_lock)
279
280/*
281 * dlclose interposition with a recursive lock so that a .fini section
282 * can recursively call dlopen or dlclose while holding _tnfctl_lmap_lock
283 * This interposition serializes access to rtld's loadobject list and
284 * also updates the flag _tnfctl_libs_changed to indicate a change in
285 * the library list.  This flag is checked by operations that update
286 * probes so that it can sync up with the new library list and potential
287 * new/deleted probes.
288 */
289int
290_tnfctl_dlclose(void *handle)
291{
292	static int (*real_dlclose)(void *handle) = NULL;
293	int retval;
294	thread_t tid;
295
296	if (real_dlclose == NULL) {
297		real_dlclose = (int (*)(void *)) dlsym(RTLD_NEXT, "dlclose");
298	}
299	assert(real_dlclose);
300
301	if (mutex_trylock(LMAP_LOCK) != 0) {
302		/* don't have lock */
303		tid = thr_self();
304		if (tid == lock_holder) {
305			/* recursive dlopen/dlclose by same thread */
306			return ((*real_dlclose)(handle));
307		}
308		/* not a recursive dlopen/dlclose - wait on lock */
309		mutex_lock(LMAP_LOCK);
310	}
311
312	/* lock is held now */
313	lock_holder = thr_self();
314	retval = (*real_dlclose)(handle);
315
316	/*
317	 * reset lock_holder so that if _tnfctl_lmap_lock is held by some
318	 * other part of the code, we don't assume it is a recursive
319	 * dlopen/dlclose
320	 */
321	lock_holder = 0;
322	_tnfctl_libs_changed = B_TRUE;
323	mutex_unlock(LMAP_LOCK);
324
325	return (retval);
326}
327
328/*
329 * dlopen interposition with a recursive lock so that a .init section
330 * can recursively call dlopen or dlclose while holding _tnfctl_lmap_lock
331 * This interposition serializes access to rtld's loadobject list and
332 * also updates the flag _tnfctl_libs_changed to indicate a change in
333 * the library list.  This flag is checked by operations that update
334 * probes so that it can sync up with the new library list and potential
335 * new/deleted probes.
336 */
337void *
338_tnfctl_dlopen(const char *pathname, int mode)
339{
340	static void * (*real_dlopen)(const char *, int) = NULL;
341	void *retval;
342	thread_t tid;
343
344	if (real_dlopen == NULL) {
345		real_dlopen = (void * (*)(const char *, int))
346					dlsym(RTLD_NEXT, "dlopen");
347	}
348	assert(real_dlopen);
349
350	if (mutex_trylock(LMAP_LOCK) != 0) {
351		/* don't have lock */
352		tid = thr_self();
353		if (tid == lock_holder) {
354			/* recursive dlopen/dlclose by same thread */
355			return ((*real_dlopen)(pathname, mode));
356		}
357		/* not a recursive dlopen/dlclose - wait on lock */
358		mutex_lock(LMAP_LOCK);
359	}
360
361	/* lock is held now */
362	lock_holder = thr_self();
363	retval = (*real_dlopen)(pathname, mode);
364
365	/*
366	 * reset lock_holder so that if _tnfctl_lmap_lock is held by some
367	 * other part of the code, we don't assume it is a recursive
368	 * dlopen/dlclose
369	 */
370	lock_holder = 0;
371	_tnfctl_libs_changed = B_TRUE;
372	mutex_unlock(LMAP_LOCK);
373
374	return (retval);
375}
376
377tnfctl_errcode_t
378_tnfctl_internal_getlock()
379{
380	mutex_lock(&_tnfctl_internalguard_lock);
381	if (_tnfctl_internal_tracing_flag == 1) {
382	/* internal trace control active */
383	mutex_unlock(&_tnfctl_internalguard_lock);
384	return (TNFCTL_ERR_BUSY);
385	}
386	_tnfctl_internal_tracing_flag = 1;
387	if (_tnfctl_externally_traced_pid == getpid()) {
388	/* external trace control is active */
389	_tnfctl_internal_tracing_flag = 0;
390	mutex_unlock(&_tnfctl_internalguard_lock);
391	return (TNFCTL_ERR_BUSY);
392	}
393	DBG((void) fprintf(stderr, "_tnfctl_internal_getlock: ok to trace %d\n",
394	getpid()));
395	mutex_unlock(&_tnfctl_internalguard_lock);
396	return (TNFCTL_ERR_NONE);
397}
398