xref: /illumos-gate/usr/src/cmd/mdb/common/kmdb/kmdb_context.c (revision 7a6d80f1660abd4755c68cbd094d4a914681d26e)
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, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * Debugger co-routine context support.  kmdb co-routines are essentially the
29  * same as the ones used by mdb, with the exception that we allocate the stack
30  * for the co-routine from our heap.
31  */
32 
33 #include <kmdb/kmdb_context_impl.h>
34 #include <mdb/mdb_modapi.h>
35 #include <mdb/mdb_debug.h>
36 #include <mdb/mdb_err.h>
37 #include <mdb/mdb_umem.h>
38 #include <mdb/mdb.h>
39 
40 #include <sys/types.h>
41 
42 #include <ucontext.h>
43 #include <setjmp.h>
44 
45 static void
46 context_init(mdb_context_t *volatile c)
47 {
48 	c->ctx_status = c->ctx_func();
49 	ASSERT(c->ctx_resumes > 0);
50 	longjmp(c->ctx_pcb, 1);
51 }
52 
53 mdb_context_t *
54 mdb_context_create(int (*func)(void))
55 {
56 	mdb_context_t *c = mdb_zalloc(sizeof (mdb_context_t), UM_NOSLEEP);
57 	size_t pagesize = mdb.m_pagesize;
58 
59 	if (c == NULL)
60 		return (NULL);
61 
62 	c->ctx_func = func;
63 	c->ctx_stacksize = pagesize * 4;
64 	c->ctx_stack = mdb_alloc_align(c->ctx_stacksize, pagesize, UM_NOSLEEP);
65 
66 	if (c->ctx_stack == NULL) {
67 		mdb_free(c, sizeof (mdb_context_t));
68 		return (NULL);
69 	}
70 
71 	kmdb_makecontext(&c->ctx_uc, (void (*)(void *))context_init, c,
72 	    c->ctx_stack, c->ctx_stacksize);
73 
74 	return (c);
75 }
76 
77 void
78 mdb_context_destroy(mdb_context_t *c)
79 {
80 	mdb_free_align(c->ctx_stack, c->ctx_stacksize);
81 	mdb_free(c, sizeof (mdb_context_t));
82 }
83 
84 void
85 mdb_context_switch(mdb_context_t *c)
86 {
87 	if (setjmp(c->ctx_pcb) == 0 && kmdb_setcontext(&c->ctx_uc) == -1)
88 		fail("failed to change context to %p", (void *)c);
89 	else
90 		fail("unexpectedly returned from context %p", (void *)c);
91 }
92 
93 jmp_buf *
94 mdb_context_getpcb(mdb_context_t *c)
95 {
96 	c->ctx_resumes++;
97 	return (&c->ctx_pcb);
98 }
99