Index: head/sys/ddb/db_capture.c =================================================================== --- head/sys/ddb/db_capture.c (revision 326266) +++ head/sys/ddb/db_capture.c (revision 326267) @@ -1,360 +1,362 @@ /*- + * SPDX-License-Identifier: BSD-2-Clause-FreeBSD + * * Copyright (c) 2007 Robert N. M. Watson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * DDB capture support: capture kernel debugger output into a fixed-size * buffer for later dumping to disk or extraction from user space. */ #include __FBSDID("$FreeBSD$"); #include "opt_ddb.h" #include #include #include #include #include #include #include #include #include #include #include #include /* * While it would be desirable to use a small block-sized buffer and dump * incrementally to disk in fixed-size blocks, it's not possible to enter * kernel dumper routines without restarting the kernel, which is undesirable * in the midst of debugging. Instead, we maintain a large static global * buffer that we fill from DDB's output routines. * * We enforce an invariant at runtime that buffer sizes are even multiples of * the textdump block size, which is a design choice that we might want to * reconsider. */ static MALLOC_DEFINE(M_DDB_CAPTURE, "ddb_capture", "DDB capture buffer"); #ifndef DDB_CAPTURE_DEFAULTBUFSIZE #define DDB_CAPTURE_DEFAULTBUFSIZE 48*1024 #endif #ifndef DDB_CAPTURE_MAXBUFSIZE #define DDB_CAPTURE_MAXBUFSIZE 5*1024*1024 #endif #define DDB_CAPTURE_FILENAME "ddb.txt" /* Captured DDB output. */ static char *db_capture_buf; static u_int db_capture_bufsize = DDB_CAPTURE_DEFAULTBUFSIZE; static u_int db_capture_maxbufsize = DDB_CAPTURE_MAXBUFSIZE; /* Read-only. */ static u_int db_capture_bufoff; /* Next location to write in buffer. */ static u_int db_capture_bufpadding; /* Amount of zero padding. */ static int db_capture_inpager; /* Suspend capture in pager. */ static int db_capture_inprogress; /* DDB capture currently in progress. */ struct sx db_capture_sx; /* Lock against user thread races. */ SX_SYSINIT(db_capture_sx, &db_capture_sx, "db_capture_sx"); static SYSCTL_NODE(_debug_ddb, OID_AUTO, capture, CTLFLAG_RW, 0, "DDB capture options"); SYSCTL_UINT(_debug_ddb_capture, OID_AUTO, bufoff, CTLFLAG_RD, &db_capture_bufoff, 0, "Bytes of data in DDB capture buffer"); SYSCTL_UINT(_debug_ddb_capture, OID_AUTO, maxbufsize, CTLFLAG_RD, &db_capture_maxbufsize, 0, "Maximum value for debug.ddb.capture.bufsize"); SYSCTL_INT(_debug_ddb_capture, OID_AUTO, inprogress, CTLFLAG_RD, &db_capture_inprogress, 0, "DDB output capture in progress"); /* * Boot-time allocation of the DDB capture buffer, if any. Force all buffer * sizes, including the maximum size, to be rounded to block sizes. */ static void db_capture_sysinit(__unused void *dummy) { TUNABLE_INT_FETCH("debug.ddb.capture.bufsize", &db_capture_bufsize); db_capture_maxbufsize = roundup(db_capture_maxbufsize, TEXTDUMP_BLOCKSIZE); db_capture_bufsize = roundup(db_capture_bufsize, TEXTDUMP_BLOCKSIZE); if (db_capture_bufsize > db_capture_maxbufsize) db_capture_bufsize = db_capture_maxbufsize; if (db_capture_bufsize != 0) db_capture_buf = malloc(db_capture_bufsize, M_DDB_CAPTURE, M_WAITOK); } SYSINIT(db_capture, SI_SUB_DDB_SERVICES, SI_ORDER_ANY, db_capture_sysinit, NULL); /* * Run-time adjustment of the capture buffer. */ static int sysctl_debug_ddb_capture_bufsize(SYSCTL_HANDLER_ARGS) { u_int len, size; char *buf; int error; size = db_capture_bufsize; error = sysctl_handle_int(oidp, &size, 0, req); if (error || req->newptr == NULL) return (error); size = roundup(size, TEXTDUMP_BLOCKSIZE); if (size > db_capture_maxbufsize) return (EINVAL); sx_xlock(&db_capture_sx); if (size != 0) { /* * Potentially the buffer is quite large, so if we can't * allocate it, fail rather than waiting. */ buf = malloc(size, M_DDB_CAPTURE, M_NOWAIT); if (buf == NULL) { sx_xunlock(&db_capture_sx); return (ENOMEM); } len = min(db_capture_bufoff, size); } else { buf = NULL; len = 0; } if (db_capture_buf != NULL && buf != NULL) bcopy(db_capture_buf, buf, len); if (db_capture_buf != NULL) free(db_capture_buf, M_DDB_CAPTURE); db_capture_bufoff = len; db_capture_buf = buf; db_capture_bufsize = size; sx_xunlock(&db_capture_sx); KASSERT(db_capture_bufoff <= db_capture_bufsize, ("sysctl_debug_ddb_capture_bufsize: bufoff > bufsize")); KASSERT(db_capture_bufsize <= db_capture_maxbufsize, ("sysctl_debug_ddb_capture_maxbufsize: bufsize > maxbufsize")); return (0); } SYSCTL_PROC(_debug_ddb_capture, OID_AUTO, bufsize, CTLTYPE_UINT|CTLFLAG_RW, 0, 0, sysctl_debug_ddb_capture_bufsize, "IU", "Size of DDB capture buffer"); /* * Sysctl to read out the capture buffer from userspace. We require * privilege as sensitive process/memory information may be accessed. */ static int sysctl_debug_ddb_capture_data(SYSCTL_HANDLER_ARGS) { int error; char ch; error = priv_check(req->td, PRIV_DDB_CAPTURE); if (error) return (error); sx_slock(&db_capture_sx); error = SYSCTL_OUT(req, db_capture_buf, db_capture_bufoff); sx_sunlock(&db_capture_sx); if (error) return (error); ch = '\0'; return (SYSCTL_OUT(req, &ch, sizeof(ch))); } SYSCTL_PROC(_debug_ddb_capture, OID_AUTO, data, CTLTYPE_STRING | CTLFLAG_RD, NULL, 0, sysctl_debug_ddb_capture_data, "A", "DDB capture data"); /* * Routines for capturing DDB output into a fixed-size buffer. These are * invoked from DDB's input and output routines. If we hit the limit on the * buffer, we simply drop further data. */ void db_capture_write(char *buffer, u_int buflen) { u_int len; if (db_capture_inprogress == 0 || db_capture_inpager) return; len = min(buflen, db_capture_bufsize - db_capture_bufoff); bcopy(buffer, db_capture_buf + db_capture_bufoff, len); db_capture_bufoff += len; KASSERT(db_capture_bufoff <= db_capture_bufsize, ("db_capture_write: bufoff > bufsize")); } void db_capture_writech(char ch) { return (db_capture_write(&ch, sizeof(ch))); } void db_capture_enterpager(void) { db_capture_inpager = 1; } void db_capture_exitpager(void) { db_capture_inpager = 0; } /* * Zero out any bytes left in the last block of the DDB capture buffer. This * is run shortly before writing the blocks to disk, rather than when output * capture is stopped, in order to avoid injecting nul's into the middle of * output. */ static void db_capture_zeropad(void) { u_int len; len = min(TEXTDUMP_BLOCKSIZE, (db_capture_bufsize - db_capture_bufoff) % TEXTDUMP_BLOCKSIZE); bzero(db_capture_buf + db_capture_bufoff, len); db_capture_bufpadding = len; } /* * Reset capture state, which flushes buffers. */ static void db_capture_reset(void) { db_capture_inprogress = 0; db_capture_bufoff = 0; db_capture_bufpadding = 0; } /* * Start capture. Only one session is allowed at any time, but we may * continue a previous session, so the buffer isn't reset. */ static void db_capture_start(void) { if (db_capture_inprogress) { db_printf("Capture already started\n"); return; } db_capture_inprogress = 1; } /* * Terminate DDB output capture--real work is deferred to db_capture_dump, * which executes outside of the DDB context. We don't zero pad here because * capture may be started again before the dump takes place. */ static void db_capture_stop(void) { if (db_capture_inprogress == 0) { db_printf("Capture not started\n"); return; } db_capture_inprogress = 0; } /* * Dump DDB(4) captured output (and resets capture buffers). */ void db_capture_dump(struct dumperinfo *di) { u_int offset; if (db_capture_bufoff == 0) return; db_capture_zeropad(); textdump_mkustar(textdump_block_buffer, DDB_CAPTURE_FILENAME, db_capture_bufoff); (void)textdump_writenextblock(di, textdump_block_buffer); for (offset = 0; offset < db_capture_bufoff + db_capture_bufpadding; offset += TEXTDUMP_BLOCKSIZE) (void)textdump_writenextblock(di, db_capture_buf + offset); db_capture_bufoff = 0; db_capture_bufpadding = 0; } /*- * DDB(4) command to manage capture: * * capture on - start DDB output capture * capture off - stop DDB output capture * capture reset - reset DDB capture buffer (also stops capture) * capture status - print DDB output capture status */ static void db_capture_usage(void) { db_error("capture [on|off|reset|status]\n"); } void db_capture_cmd(db_expr_t addr, bool have_addr, db_expr_t count, char *modif) { int t; t = db_read_token(); if (t != tIDENT) { db_capture_usage(); return; } if (db_read_token() != tEOL) db_error("?\n"); if (strcmp(db_tok_string, "on") == 0) db_capture_start(); else if (strcmp(db_tok_string, "off") == 0) db_capture_stop(); else if (strcmp(db_tok_string, "reset") == 0) db_capture_reset(); else if (strcmp(db_tok_string, "status") == 0) { db_printf("%u/%u bytes used\n", db_capture_bufoff, db_capture_bufsize); if (db_capture_inprogress) db_printf("capture is on\n"); else db_printf("capture is off\n"); } else db_capture_usage(); } Index: head/sys/ddb/db_script.c =================================================================== --- head/sys/ddb/db_script.c (revision 326266) +++ head/sys/ddb/db_script.c (revision 326267) @@ -1,562 +1,564 @@ /*- + * SPDX-License-Identifier: BSD-2-Clause-FreeBSD + * * Copyright (c) 2007 Robert N. M. Watson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /*- * Simple DDB scripting mechanism. Each script consists of a named list of * DDB commands to execute sequentially. A more sophisticated scripting * language might be desirable, but would be significantly more complex to * implement. A more interesting syntax might allow general use of variables * and extracting of useful values, such as a thread's process identifier, * for passing into further DDB commands. Certain scripts are run * automatically at kdb_enter(), if defined, based on how the debugger is * entered, allowing scripted responses to panics, break signals, etc. * * Scripts may be managed from within DDB using the script, scripts, and * unscript commands. They may also be managed from userspace using ddb(8), * which operates using a set of sysctls. * * TODO: * - Allow scripts to be defined using tunables so that they can be defined * before boot and be present in single-user mode without boot scripts * running. * - Memory allocation is not possible from within DDB, so we use a set of * statically allocated buffers to hold defined scripts. However, when * scripts are being defined from userspace via sysctl, we could in fact be * using malloc(9) and therefore not impose a static limit, giving greater * flexibility and avoiding hard-defined buffer limits. * - When scripts run automatically on entrance to DDB, placing "continue" at * the end still results in being in the debugger, as we unconditionally * run db_command_loop() after the script. There should be a way to avoid * this. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* * struct ddb_script describes an individual script. */ struct ddb_script { char ds_scriptname[DB_MAXSCRIPTNAME]; char ds_script[DB_MAXSCRIPTLEN]; }; /* * Global list of scripts -- defined scripts have non-empty name fields. */ static struct ddb_script db_script_table[DB_MAXSCRIPTS]; /* * While executing a script, we parse it using strsep(), so require a * temporary buffer that may be used destructively. Since we support weak * recursion of scripts (one may reference another), we need one buffer for * each concurrently executing script. */ static struct db_recursion_data { char drd_buffer[DB_MAXSCRIPTLEN]; } db_recursion_data[DB_MAXSCRIPTRECURSION]; static int db_recursion = -1; /* * We use a separate static buffer for script validation so that it is safe * to validate scripts from within a script. This is used only in * db_script_valid(), which should never be called reentrantly. */ static char db_static_buffer[DB_MAXSCRIPTLEN]; /* * Synchronization is not required from within the debugger, as it is * singe-threaded (although reentrance must be carefully considered). * However, it is required when interacting with scripts from user space * processes. Sysctl procedures acquire db_script_mtx before accessing the * global script data structures. */ static struct mtx db_script_mtx; MTX_SYSINIT(db_script_mtx, &db_script_mtx, "db_script_mtx", MTX_DEF); /* * Some script names have special meaning, such as those executed * automatically when KDB is entered. */ #define DB_SCRIPT_KDBENTER_PREFIX "kdb.enter" /* KDB has entered. */ #define DB_SCRIPT_KDBENTER_DEFAULT "kdb.enter.default" /* * Find the existing script slot for a named script, if any. */ static struct ddb_script * db_script_lookup(const char *scriptname) { int i; for (i = 0; i < DB_MAXSCRIPTS; i++) { if (strcmp(db_script_table[i].ds_scriptname, scriptname) == 0) return (&db_script_table[i]); } return (NULL); } /* * Find a new slot for a script, if available. Does not mark as allocated in * any way--this must be done by the caller. */ static struct ddb_script * db_script_new(void) { int i; for (i = 0; i < DB_MAXSCRIPTS; i++) { if (strlen(db_script_table[i].ds_scriptname) == 0) return (&db_script_table[i]); } return (NULL); } /* * Perform very rudimentary validation of a proposed script. It would be * easy to imagine something more comprehensive. The script string is * validated in a static buffer. */ static int db_script_valid(const char *scriptname, const char *script) { char *buffer, *command; if (strlen(scriptname) == 0) return (EINVAL); if (strlen(scriptname) >= DB_MAXSCRIPTNAME) return (EINVAL); if (strlen(script) >= DB_MAXSCRIPTLEN) return (EINVAL); buffer = db_static_buffer; strcpy(buffer, script); while ((command = strsep(&buffer, ";")) != NULL) { if (strlen(command) >= DB_MAXLINE) return (EINVAL); } return (0); } /* * Modify an existing script or add a new script with the specified script * name and contents. If there are no script slots available, an error will * be returned. */ static int db_script_set(const char *scriptname, const char *script) { struct ddb_script *dsp; int error; error = db_script_valid(scriptname, script); if (error) return (error); dsp = db_script_lookup(scriptname); if (dsp == NULL) { dsp = db_script_new(); if (dsp == NULL) return (ENOSPC); strlcpy(dsp->ds_scriptname, scriptname, sizeof(dsp->ds_scriptname)); } strlcpy(dsp->ds_script, script, sizeof(dsp->ds_script)); return (0); } /* * Delete an existing script by name, if found. */ static int db_script_unset(const char *scriptname) { struct ddb_script *dsp; dsp = db_script_lookup(scriptname); if (dsp == NULL) return (ENOENT); strcpy(dsp->ds_scriptname, ""); strcpy(dsp->ds_script, ""); return (0); } /* * Trim leading/trailing white space in a command so that we don't pass * carriage returns, etc, into DDB command parser. */ static int db_command_trimmable(char ch) { switch (ch) { case ' ': case '\t': case '\n': case '\r': return (1); default: return (0); } } static void db_command_trim(char **commandp) { char *command; command = *commandp; while (db_command_trimmable(*command)) command++; while ((strlen(command) > 0) && db_command_trimmable(command[strlen(command) - 1])) command[strlen(command) - 1] = 0; *commandp = command; } /* * Execute a script, breaking it up into individual commands and passing them * sequentially into DDB's input processing. Use the KDB jump buffer to * restore control to the main script loop if things get too wonky when * processing a command -- i.e., traps, etc. Also, make sure we don't exceed * practical limits on recursion. * * XXXRW: If any individual command is too long, it will be truncated when * injected into the input at a lower layer. We should validate the script * before configuring it to avoid this scenario. */ static int db_script_exec(const char *scriptname, int warnifnotfound) { struct db_recursion_data *drd; struct ddb_script *dsp; char *buffer, *command; void *prev_jb; jmp_buf jb; dsp = db_script_lookup(scriptname); if (dsp == NULL) { if (warnifnotfound) db_printf("script '%s' not found\n", scriptname); return (ENOENT); } if (db_recursion >= DB_MAXSCRIPTRECURSION) { db_printf("Script stack too deep\n"); return (E2BIG); } db_recursion++; drd = &db_recursion_data[db_recursion]; /* * Parse script in temporary buffer, since strsep() is destructive. */ buffer = drd->drd_buffer; strcpy(buffer, dsp->ds_script); while ((command = strsep(&buffer, ";")) != NULL) { db_printf("db:%d:%s> %s\n", db_recursion, scriptname, command); db_command_trim(&command); prev_jb = kdb_jmpbuf(jb); if (setjmp(jb) == 0) db_command_script(command); else db_printf("Script command '%s' returned error\n", command); kdb_jmpbuf(prev_jb); } db_recursion--; return (0); } /* * Wrapper for exec path that is called on KDB enter. Map reason for KDB * enter to a script name, and don't whine if the script doesn't exist. If * there is no matching script, try the catch-all script. */ void db_script_kdbenter(const char *eventname) { char scriptname[DB_MAXSCRIPTNAME]; snprintf(scriptname, sizeof(scriptname), "%s.%s", DB_SCRIPT_KDBENTER_PREFIX, eventname); if (db_script_exec(scriptname, 0) == ENOENT) (void)db_script_exec(DB_SCRIPT_KDBENTER_DEFAULT, 0); } /*- * DDB commands for scripting, as reached via the DDB user interface: * * scripts - lists scripts * run - run a script * script - prints script * script