← العودة إلى الدورة: C programming from scratch

Debugging with gdb and writing safe C

الفيديو قريبًا

Sanitizers tell you something is wrong; the debugger lets you step inside the program while it runs and see why. gdb is the standard debugger on Linux, macOS (with lldb as an alternative) and MSYS2. With it you can stop the program at a line, advance step by step, look at the value of any variable and see the chain of calls that led to a failure. It is far more effective than filling the code with printf. In the second half of the lesson you will see which mistakes turn a C program into a security problem, and how to avoid them with a few habits.

First gdb session

Compile with -g and without optimisations (-O0) so the debugger relates machine code to your lines. Then run gdb ./program. The essential commands are: break (b) to set a breakpoint on a function or line, run (r) to start, next (n) to advance one line without entering functions, step (s) to enter them, print (p) to see an expression, backtrace (bt) to see the call stack, continue (c) to go on until the next breakpoint and quit (q) to exit. If the program dies with a segmentation fault, gdb stops right at the guilty line.

c
#include <stdio.h>

void fill(int *dst, int n) {
    for (int i = 0; i < n; i++) {
        dst[i] = i;
    }
}

int main(void) {
    int *p = NULL;
    fill(p, 3);
    printf("done\n");
    return 0;
}
bash
gcc -std=c17 -g -O0 crash.c -o crash
gdb ./crash
(gdb) run
# Program received signal SIGSEGV, Segmentation fault.
# fill (dst=0x0, n=3) at crash.c:5
# 5	        dst[i] = i;
(gdb) bt
# #0  fill (dst=0x0, n=3) at crash.c:5
# #1  main () at crash.c:11
(gdb) print dst
# $1 = (int *) 0x0
(gdb) frame 1
(gdb) print p
# $2 = (int *) 0x0
(gdb) quit

Read the session like a detective. The failure happened in fill, line 5, and dst is 0x0: a null pointer. The backtrace shows that main called fill from line 11, and with frame 1 you look at main's variable p: it was never given a valid address. The cause is not where the program crashed, but two steps earlier. That is the great use of bt. Other useful commands: watch total stops the program each time that variable changes, info locals shows all local variables, and finish runs until the current function ends and shows its return value.

Writing safe C

Most famous security failures in C software are the same mistake: writing or reading beyond the end of a buffer. An attacker who controls the input can overwrite neighbouring data and even change the program flow. The defences are habits, not magic. First, do not use unbounded functions: gets (removed from the standard), sprintf and strcpy copy without knowing the size of the destination; use fgets, snprintf and memcpy with checked lengths. Second, never pass user text as a format: printf(text) lets the input contain %n or %s and read or write memory; always write printf("%s", text).

Third, check every allocation and every size calculation: malloc can return NULL, and a multiplication such as count * sizeof(int) can overflow and allocate far too little; calloc(count, size) does that check for you. Fourth, after free set the pointer to NULL to avoid use-after-free and double free, and release everything you allocated. Fifth, validate index bounds before using them, especially if they come from a file or the user. A program that is correct on your computer with your data can be vulnerable with someone else's data.

c
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Returns a heap copy of src, or NULL on failure. Caller must free it. */
char *copy_text(const char *src) {
    size_t len = strlen(src);
    char *dst = malloc(len + 1);
    if (dst == NULL) {
        return NULL;
    }
    memcpy(dst, src, len + 1); /* copies the final '\0' too */
    return dst;
}

/* Allocates count zeroed ints; refuses sizes that would overflow. */
int *make_array(size_t count) {
    if (count == 0 || count > SIZE_MAX / sizeof(int)) {
        return NULL;
    }
    return calloc(count, sizeof(int));
}

int main(void) {
    char name[16];
    int n = snprintf(name, sizeof name, "user-%d", 12345);
    if (n < 0 || (size_t)n >= sizeof name) {
        fputs("name was truncated\n", stderr);
        return 1;
    }

    char *copy = copy_text(name);
    if (copy == NULL) {
        return 1;
    }
    printf("%s\n", copy); /* user-12345 */
    free(copy);
    copy = NULL;

    int *numbers = make_array(5);
    if (numbers == NULL) {
        return 1;
    }
    printf("%d\n", numbers[0]); /* 0 */
    free(numbers);
    return 0;
}
  • Debug with gcc -g -O0 and gdb: break, run, next, step, print, bt, watch.
  • Read the backtrace from the bottom up: the cause is usually before the failure.
  • Replace gets, strcpy and sprintf with fgets, memcpy and snprintf with limits.
  • Never use user text as a format string.
  • Check malloc and size calculations; set the pointer to NULL after free.

اختبر ما تعلمته

السؤال 1 من 5

What does the bt command do in gdb?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →