Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /*
0003  * Copyright (C) 2008 Steven Rostedt <srostedt@redhat.com>
0004  *
0005  */
0006 #include <linux/sched/task_stack.h>
0007 #include <linux/stacktrace.h>
0008 #include <linux/security.h>
0009 #include <linux/kallsyms.h>
0010 #include <linux/seq_file.h>
0011 #include <linux/spinlock.h>
0012 #include <linux/uaccess.h>
0013 #include <linux/ftrace.h>
0014 #include <linux/module.h>
0015 #include <linux/sysctl.h>
0016 #include <linux/init.h>
0017 
0018 #include <asm/setup.h>
0019 
0020 #include "trace.h"
0021 
0022 #define STACK_TRACE_ENTRIES 500
0023 
0024 static unsigned long stack_dump_trace[STACK_TRACE_ENTRIES];
0025 static unsigned stack_trace_index[STACK_TRACE_ENTRIES];
0026 
0027 static unsigned int stack_trace_nr_entries;
0028 static unsigned long stack_trace_max_size;
0029 static arch_spinlock_t stack_trace_max_lock =
0030     (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
0031 
0032 DEFINE_PER_CPU(int, disable_stack_tracer);
0033 static DEFINE_MUTEX(stack_sysctl_mutex);
0034 
0035 int stack_tracer_enabled;
0036 
0037 static void print_max_stack(void)
0038 {
0039     long i;
0040     int size;
0041 
0042     pr_emerg("        Depth    Size   Location    (%d entries)\n"
0043                "        -----    ----   --------\n",
0044                stack_trace_nr_entries);
0045 
0046     for (i = 0; i < stack_trace_nr_entries; i++) {
0047         if (i + 1 == stack_trace_nr_entries)
0048             size = stack_trace_index[i];
0049         else
0050             size = stack_trace_index[i] - stack_trace_index[i+1];
0051 
0052         pr_emerg("%3ld) %8d   %5d   %pS\n", i, stack_trace_index[i],
0053                 size, (void *)stack_dump_trace[i]);
0054     }
0055 }
0056 
0057 /*
0058  * The stack tracer looks for a maximum stack at each call from a function. It
0059  * registers a callback from ftrace, and in that callback it examines the stack
0060  * size. It determines the stack size from the variable passed in, which is the
0061  * address of a local variable in the stack_trace_call() callback function.
0062  * The stack size is calculated by the address of the local variable to the top
0063  * of the current stack. If that size is smaller than the currently saved max
0064  * stack size, nothing more is done.
0065  *
0066  * If the size of the stack is greater than the maximum recorded size, then the
0067  * following algorithm takes place.
0068  *
0069  * For architectures (like x86) that store the function's return address before
0070  * saving the function's local variables, the stack will look something like
0071  * this:
0072  *
0073  *   [ top of stack ]
0074  *    0: sys call entry frame
0075  *   10: return addr to entry code
0076  *   11: start of sys_foo frame
0077  *   20: return addr to sys_foo
0078  *   21: start of kernel_func_bar frame
0079  *   30: return addr to kernel_func_bar
0080  *   31: [ do trace stack here ]
0081  *
0082  * The save_stack_trace() is called returning all the functions it finds in the
0083  * current stack. Which would be (from the bottom of the stack to the top):
0084  *
0085  *   return addr to kernel_func_bar
0086  *   return addr to sys_foo
0087  *   return addr to entry code
0088  *
0089  * Now to figure out how much each of these functions' local variable size is,
0090  * a search of the stack is made to find these values. When a match is made, it
0091  * is added to the stack_dump_trace[] array. The offset into the stack is saved
0092  * in the stack_trace_index[] array. The above example would show:
0093  *
0094  *        stack_dump_trace[]        |   stack_trace_index[]
0095  *        ------------------        +   -------------------
0096  *  return addr to kernel_func_bar  |          30
0097  *  return addr to sys_foo          |          20
0098  *  return addr to entry            |          10
0099  *
0100  * The print_max_stack() function above, uses these values to print the size of
0101  * each function's portion of the stack.
0102  *
0103  *  for (i = 0; i < nr_entries; i++) {
0104  *     size = i == nr_entries - 1 ? stack_trace_index[i] :
0105  *                    stack_trace_index[i] - stack_trace_index[i+1]
0106  *     print "%d %d %d %s\n", i, stack_trace_index[i], size, stack_dump_trace[i]);
0107  *  }
0108  *
0109  * The above shows
0110  *
0111  *     depth size  location
0112  *     ----- ----  --------
0113  *  0    30   10   kernel_func_bar
0114  *  1    20   10   sys_foo
0115  *  2    10   10   entry code
0116  *
0117  * Now for architectures that might save the return address after the functions
0118  * local variables (saving the link register before calling nested functions),
0119  * this will cause the stack to look a little different:
0120  *
0121  * [ top of stack ]
0122  *  0: sys call entry frame
0123  * 10: start of sys_foo_frame
0124  * 19: return addr to entry code << lr saved before calling kernel_func_bar
0125  * 20: start of kernel_func_bar frame
0126  * 29: return addr to sys_foo_frame << lr saved before calling next function
0127  * 30: [ do trace stack here ]
0128  *
0129  * Although the functions returned by save_stack_trace() may be the same, the
0130  * placement in the stack will be different. Using the same algorithm as above
0131  * would yield:
0132  *
0133  *        stack_dump_trace[]        |   stack_trace_index[]
0134  *        ------------------        +   -------------------
0135  *  return addr to kernel_func_bar  |          30
0136  *  return addr to sys_foo          |          29
0137  *  return addr to entry            |          19
0138  *
0139  * Where the mapping is off by one:
0140  *
0141  *   kernel_func_bar stack frame size is 29 - 19 not 30 - 29!
0142  *
0143  * To fix this, if the architecture sets ARCH_RET_ADDR_AFTER_LOCAL_VARS the
0144  * values in stack_trace_index[] are shifted by one to and the number of
0145  * stack trace entries is decremented by one.
0146  *
0147  *        stack_dump_trace[]        |   stack_trace_index[]
0148  *        ------------------        +   -------------------
0149  *  return addr to kernel_func_bar  |          29
0150  *  return addr to sys_foo          |          19
0151  *
0152  * Although the entry function is not displayed, the first function (sys_foo)
0153  * will still include the stack size of it.
0154  */
0155 static void check_stack(unsigned long ip, unsigned long *stack)
0156 {
0157     unsigned long this_size, flags; unsigned long *p, *top, *start;
0158     static int tracer_frame;
0159     int frame_size = READ_ONCE(tracer_frame);
0160     int i, x;
0161 
0162     this_size = ((unsigned long)stack) & (THREAD_SIZE-1);
0163     this_size = THREAD_SIZE - this_size;
0164     /* Remove the frame of the tracer */
0165     this_size -= frame_size;
0166 
0167     if (this_size <= stack_trace_max_size)
0168         return;
0169 
0170     /* we do not handle interrupt stacks yet */
0171     if (!object_is_on_stack(stack))
0172         return;
0173 
0174     /* Can't do this from NMI context (can cause deadlocks) */
0175     if (in_nmi())
0176         return;
0177 
0178     local_irq_save(flags);
0179     arch_spin_lock(&stack_trace_max_lock);
0180 
0181     /* In case another CPU set the tracer_frame on us */
0182     if (unlikely(!frame_size))
0183         this_size -= tracer_frame;
0184 
0185     /* a race could have already updated it */
0186     if (this_size <= stack_trace_max_size)
0187         goto out;
0188 
0189     stack_trace_max_size = this_size;
0190 
0191     stack_trace_nr_entries = stack_trace_save(stack_dump_trace,
0192                            ARRAY_SIZE(stack_dump_trace) - 1,
0193                            0);
0194 
0195     /* Skip over the overhead of the stack tracer itself */
0196     for (i = 0; i < stack_trace_nr_entries; i++) {
0197         if (stack_dump_trace[i] == ip)
0198             break;
0199     }
0200 
0201     /*
0202      * Some archs may not have the passed in ip in the dump.
0203      * If that happens, we need to show everything.
0204      */
0205     if (i == stack_trace_nr_entries)
0206         i = 0;
0207 
0208     /*
0209      * Now find where in the stack these are.
0210      */
0211     x = 0;
0212     start = stack;
0213     top = (unsigned long *)
0214         (((unsigned long)start & ~(THREAD_SIZE-1)) + THREAD_SIZE);
0215 
0216     /*
0217      * Loop through all the entries. One of the entries may
0218      * for some reason be missed on the stack, so we may
0219      * have to account for them. If they are all there, this
0220      * loop will only happen once. This code only takes place
0221      * on a new max, so it is far from a fast path.
0222      */
0223     while (i < stack_trace_nr_entries) {
0224         int found = 0;
0225 
0226         stack_trace_index[x] = this_size;
0227         p = start;
0228 
0229         for (; p < top && i < stack_trace_nr_entries; p++) {
0230             /*
0231              * The READ_ONCE_NOCHECK is used to let KASAN know that
0232              * this is not a stack-out-of-bounds error.
0233              */
0234             if ((READ_ONCE_NOCHECK(*p)) == stack_dump_trace[i]) {
0235                 stack_dump_trace[x] = stack_dump_trace[i++];
0236                 this_size = stack_trace_index[x++] =
0237                     (top - p) * sizeof(unsigned long);
0238                 found = 1;
0239                 /* Start the search from here */
0240                 start = p + 1;
0241                 /*
0242                  * We do not want to show the overhead
0243                  * of the stack tracer stack in the
0244                  * max stack. If we haven't figured
0245                  * out what that is, then figure it out
0246                  * now.
0247                  */
0248                 if (unlikely(!tracer_frame)) {
0249                     tracer_frame = (p - stack) *
0250                         sizeof(unsigned long);
0251                     stack_trace_max_size -= tracer_frame;
0252                 }
0253             }
0254         }
0255 
0256         if (!found)
0257             i++;
0258     }
0259 
0260 #ifdef ARCH_FTRACE_SHIFT_STACK_TRACER
0261     /*
0262      * Some archs will store the link register before calling
0263      * nested functions. This means the saved return address
0264      * comes after the local storage, and we need to shift
0265      * for that.
0266      */
0267     if (x > 1) {
0268         memmove(&stack_trace_index[0], &stack_trace_index[1],
0269             sizeof(stack_trace_index[0]) * (x - 1));
0270         x--;
0271     }
0272 #endif
0273 
0274     stack_trace_nr_entries = x;
0275 
0276     if (task_stack_end_corrupted(current)) {
0277         print_max_stack();
0278         BUG();
0279     }
0280 
0281  out:
0282     arch_spin_unlock(&stack_trace_max_lock);
0283     local_irq_restore(flags);
0284 }
0285 
0286 /* Some archs may not define MCOUNT_INSN_SIZE */
0287 #ifndef MCOUNT_INSN_SIZE
0288 # define MCOUNT_INSN_SIZE 0
0289 #endif
0290 
0291 static void
0292 stack_trace_call(unsigned long ip, unsigned long parent_ip,
0293          struct ftrace_ops *op, struct ftrace_regs *fregs)
0294 {
0295     unsigned long stack;
0296 
0297     preempt_disable_notrace();
0298 
0299     /* no atomic needed, we only modify this variable by this cpu */
0300     __this_cpu_inc(disable_stack_tracer);
0301     if (__this_cpu_read(disable_stack_tracer) != 1)
0302         goto out;
0303 
0304     /* If rcu is not watching, then save stack trace can fail */
0305     if (!rcu_is_watching())
0306         goto out;
0307 
0308     ip += MCOUNT_INSN_SIZE;
0309 
0310     check_stack(ip, &stack);
0311 
0312  out:
0313     __this_cpu_dec(disable_stack_tracer);
0314     /* prevent recursion in schedule */
0315     preempt_enable_notrace();
0316 }
0317 
0318 static struct ftrace_ops trace_ops __read_mostly =
0319 {
0320     .func = stack_trace_call,
0321 };
0322 
0323 static ssize_t
0324 stack_max_size_read(struct file *filp, char __user *ubuf,
0325             size_t count, loff_t *ppos)
0326 {
0327     unsigned long *ptr = filp->private_data;
0328     char buf[64];
0329     int r;
0330 
0331     r = snprintf(buf, sizeof(buf), "%ld\n", *ptr);
0332     if (r > sizeof(buf))
0333         r = sizeof(buf);
0334     return simple_read_from_buffer(ubuf, count, ppos, buf, r);
0335 }
0336 
0337 static ssize_t
0338 stack_max_size_write(struct file *filp, const char __user *ubuf,
0339              size_t count, loff_t *ppos)
0340 {
0341     long *ptr = filp->private_data;
0342     unsigned long val, flags;
0343     int ret;
0344 
0345     ret = kstrtoul_from_user(ubuf, count, 10, &val);
0346     if (ret)
0347         return ret;
0348 
0349     local_irq_save(flags);
0350 
0351     /*
0352      * In case we trace inside arch_spin_lock() or after (NMI),
0353      * we will cause circular lock, so we also need to increase
0354      * the percpu disable_stack_tracer here.
0355      */
0356     __this_cpu_inc(disable_stack_tracer);
0357 
0358     arch_spin_lock(&stack_trace_max_lock);
0359     *ptr = val;
0360     arch_spin_unlock(&stack_trace_max_lock);
0361 
0362     __this_cpu_dec(disable_stack_tracer);
0363     local_irq_restore(flags);
0364 
0365     return count;
0366 }
0367 
0368 static const struct file_operations stack_max_size_fops = {
0369     .open       = tracing_open_generic,
0370     .read       = stack_max_size_read,
0371     .write      = stack_max_size_write,
0372     .llseek     = default_llseek,
0373 };
0374 
0375 static void *
0376 __next(struct seq_file *m, loff_t *pos)
0377 {
0378     long n = *pos - 1;
0379 
0380     if (n >= stack_trace_nr_entries)
0381         return NULL;
0382 
0383     m->private = (void *)n;
0384     return &m->private;
0385 }
0386 
0387 static void *
0388 t_next(struct seq_file *m, void *v, loff_t *pos)
0389 {
0390     (*pos)++;
0391     return __next(m, pos);
0392 }
0393 
0394 static void *t_start(struct seq_file *m, loff_t *pos)
0395 {
0396     local_irq_disable();
0397 
0398     __this_cpu_inc(disable_stack_tracer);
0399 
0400     arch_spin_lock(&stack_trace_max_lock);
0401 
0402     if (*pos == 0)
0403         return SEQ_START_TOKEN;
0404 
0405     return __next(m, pos);
0406 }
0407 
0408 static void t_stop(struct seq_file *m, void *p)
0409 {
0410     arch_spin_unlock(&stack_trace_max_lock);
0411 
0412     __this_cpu_dec(disable_stack_tracer);
0413 
0414     local_irq_enable();
0415 }
0416 
0417 static void trace_lookup_stack(struct seq_file *m, long i)
0418 {
0419     unsigned long addr = stack_dump_trace[i];
0420 
0421     seq_printf(m, "%pS\n", (void *)addr);
0422 }
0423 
0424 static void print_disabled(struct seq_file *m)
0425 {
0426     seq_puts(m, "#\n"
0427          "#  Stack tracer disabled\n"
0428          "#\n"
0429          "# To enable the stack tracer, either add 'stacktrace' to the\n"
0430          "# kernel command line\n"
0431          "# or 'echo 1 > /proc/sys/kernel/stack_tracer_enabled'\n"
0432          "#\n");
0433 }
0434 
0435 static int t_show(struct seq_file *m, void *v)
0436 {
0437     long i;
0438     int size;
0439 
0440     if (v == SEQ_START_TOKEN) {
0441         seq_printf(m, "        Depth    Size   Location"
0442                "    (%d entries)\n"
0443                "        -----    ----   --------\n",
0444                stack_trace_nr_entries);
0445 
0446         if (!stack_tracer_enabled && !stack_trace_max_size)
0447             print_disabled(m);
0448 
0449         return 0;
0450     }
0451 
0452     i = *(long *)v;
0453 
0454     if (i >= stack_trace_nr_entries)
0455         return 0;
0456 
0457     if (i + 1 == stack_trace_nr_entries)
0458         size = stack_trace_index[i];
0459     else
0460         size = stack_trace_index[i] - stack_trace_index[i+1];
0461 
0462     seq_printf(m, "%3ld) %8d   %5d   ", i, stack_trace_index[i], size);
0463 
0464     trace_lookup_stack(m, i);
0465 
0466     return 0;
0467 }
0468 
0469 static const struct seq_operations stack_trace_seq_ops = {
0470     .start      = t_start,
0471     .next       = t_next,
0472     .stop       = t_stop,
0473     .show       = t_show,
0474 };
0475 
0476 static int stack_trace_open(struct inode *inode, struct file *file)
0477 {
0478     int ret;
0479 
0480     ret = security_locked_down(LOCKDOWN_TRACEFS);
0481     if (ret)
0482         return ret;
0483 
0484     return seq_open(file, &stack_trace_seq_ops);
0485 }
0486 
0487 static const struct file_operations stack_trace_fops = {
0488     .open       = stack_trace_open,
0489     .read       = seq_read,
0490     .llseek     = seq_lseek,
0491     .release    = seq_release,
0492 };
0493 
0494 #ifdef CONFIG_DYNAMIC_FTRACE
0495 
0496 static int
0497 stack_trace_filter_open(struct inode *inode, struct file *file)
0498 {
0499     struct ftrace_ops *ops = inode->i_private;
0500 
0501     /* Checks for tracefs lockdown */
0502     return ftrace_regex_open(ops, FTRACE_ITER_FILTER,
0503                  inode, file);
0504 }
0505 
0506 static const struct file_operations stack_trace_filter_fops = {
0507     .open = stack_trace_filter_open,
0508     .read = seq_read,
0509     .write = ftrace_filter_write,
0510     .llseek = tracing_lseek,
0511     .release = ftrace_regex_release,
0512 };
0513 
0514 #endif /* CONFIG_DYNAMIC_FTRACE */
0515 
0516 int
0517 stack_trace_sysctl(struct ctl_table *table, int write, void *buffer,
0518            size_t *lenp, loff_t *ppos)
0519 {
0520     int was_enabled;
0521     int ret;
0522 
0523     mutex_lock(&stack_sysctl_mutex);
0524     was_enabled = !!stack_tracer_enabled;
0525 
0526     ret = proc_dointvec(table, write, buffer, lenp, ppos);
0527 
0528     if (ret || !write || (was_enabled == !!stack_tracer_enabled))
0529         goto out;
0530 
0531     if (stack_tracer_enabled)
0532         register_ftrace_function(&trace_ops);
0533     else
0534         unregister_ftrace_function(&trace_ops);
0535  out:
0536     mutex_unlock(&stack_sysctl_mutex);
0537     return ret;
0538 }
0539 
0540 static char stack_trace_filter_buf[COMMAND_LINE_SIZE+1] __initdata;
0541 
0542 static __init int enable_stacktrace(char *str)
0543 {
0544     int len;
0545 
0546     if ((len = str_has_prefix(str, "_filter=")))
0547         strncpy(stack_trace_filter_buf, str + len, COMMAND_LINE_SIZE);
0548 
0549     stack_tracer_enabled = 1;
0550     return 1;
0551 }
0552 __setup("stacktrace", enable_stacktrace);
0553 
0554 static __init int stack_trace_init(void)
0555 {
0556     int ret;
0557 
0558     ret = tracing_init_dentry();
0559     if (ret)
0560         return 0;
0561 
0562     trace_create_file("stack_max_size", TRACE_MODE_WRITE, NULL,
0563             &stack_trace_max_size, &stack_max_size_fops);
0564 
0565     trace_create_file("stack_trace", TRACE_MODE_READ, NULL,
0566             NULL, &stack_trace_fops);
0567 
0568 #ifdef CONFIG_DYNAMIC_FTRACE
0569     trace_create_file("stack_trace_filter", TRACE_MODE_WRITE, NULL,
0570               &trace_ops, &stack_trace_filter_fops);
0571 #endif
0572 
0573     if (stack_trace_filter_buf[0])
0574         ftrace_set_early_filter(&trace_ops, stack_trace_filter_buf, 1);
0575 
0576     if (stack_tracer_enabled)
0577         register_ftrace_function(&trace_ops);
0578 
0579     return 0;
0580 }
0581 
0582 device_initcall(stack_trace_init);