【问题标题】:Can unexecuted code cause a segfault?未执行的代码会导致段错误吗?
【发布时间】:2016-03-31 20:36:23
【问题描述】:

是的,我知道这听起来很疯狂,但这是我目前可以描述它的唯一方式。我正在为一个模拟终端的类编写一个程序,因为它将命令作为输入并执行它们。 (我将在下面放一些代码)如您所见,该程序保存命令历史记录 historyArgs 以便用户可以执行最近的命令。

用户执行 Ctrl-C 时会列出命令历史记录。最近的命令通过命令 'r' (表示最近的)和 r 'x' (其中 x 匹配最近历史中命令的第一个字母)来访问。当我开始实施 'r' 命令时,我开始得到这个段错误。然后我恢复了所有更改并一次添加一行。我发现即使添加原始变量声明也会导致段错误(int temp = 10;)但这是它变得陌生的地方。我相信导致段错误(int temp = 10;)的行永远不会被访问。我在 if 块的开头放置 printf 语句并刷新输出,以查看是否已进入该块,但它们不执行。

为我们提供了设置。它接受用户输入并将其放入 char *args[] 中,即 input = ls -a -C, args = {"ls", "-a", "-C", NULL, ... NULL}。我在 main 中标记了导致段错误的行。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#define BUFFER_SIZE 50
static char buffer[BUFFER_SIZE];

#define MAX_LINE 80 /* 80 chars per line, per command, should be enough. */

char *historyArgs[10][MAX_LINE/2 + 1];
int historyCount = 0;
int indexOfLatestCommand = 0;

/* the signal handler function */
void handle_SIGINT() {
    //write(STDOUT_FILENO,buffer,strlen(buffer));
    if(historyCount > 0){
        printf("\n%i command(s), printing most recent:\n", historyCount);
        int i;
        for(i = 0; i < historyCount && i < 10; i++){
            printf("%i.] %s ", i+1, historyArgs[i][0]);
            //print args
            int j = 1;
            while(historyArgs[i][j] != NULL){
                printf("%s ", historyArgs[i][j]);
                j++;
            }
            printf("\n");
        }
    }
    else{
        printf("\nNo recent commands.\n");
    }
    fflush(stdout);
}

/**
 * setup() reads in the next command line, separating it into distinct tokens
 * using whitespace as delimiters. setup() sets the args parameter as a 
 * null-terminated string.
 */

void setup(char inputBuffer[], char *args[],int *background)
{
    int length, /* # of characters in the command line */
        i,      /* loop index for accessing inputBuffer array */
        start,  /* index where beginning of next command parameter is */
        ct;     /* index of where to place the next parameter into args[] */

    ct = 0;

    /* read what the user enters on the command line */
    length = read(STDIN_FILENO, inputBuffer, MAX_LINE);  

    start = -1;
    if (length == 0)
        //exit(0);            /* ^d was entered, end of user command stream */
    if (length < 0){
        perror("error reading the command");
    exit(-1);           /* terminate with error code of -1 */
    }

    /* examine every character in the inputBuffer */
    for (i = 0; i < length; i++) { 
        switch (inputBuffer[i]){
        case ' ':
        case '\t' :               /* argument separators */
            if(start != -1){
                args[ct] = &inputBuffer[start];    /* set up pointer */
                ct++;
            }
            inputBuffer[i] = '\0'; /* add a null char; make a C string */
            start = -1;
            break;

        case '\n':                 /* should be the final char examined */
            if (start != -1){
                args[ct] = &inputBuffer[start];
                ct++;
            }
            inputBuffer[i] = '\0';
            args[ct] = NULL; /* no more arguments to this command */
            break;

        case '&':
            *background = 1;
            inputBuffer[i] = '\0';
            break;

        default :             /* some other character */
            if (start == -1)
                start = i;
    }

    }    
    args[ct] = NULL; /* just in case the input line was > 80 */
} 


int main(void)
{
    int i;
    char inputBuffer[MAX_LINE]; /* buffer to hold the command entered */
    int background;             /* equals 1 if a command is followed by '&' */
    char* args[MAX_LINE/2+1];/* command line (of 80) has max of 40 arguments */
    int status;

    struct sigaction handler;
    handler.sa_handler = handle_SIGINT; 
    sigaction(SIGINT, &handler, NULL);
    strcpy(buffer,"Caught <ctrl><c>\n");

    while (1){            /* Program terminates normally inside setup */
        background = 0;
        printf("COMMAND->");
        fflush(0);
        setup(inputBuffer, args, &background);       /* get next command */

        //If command wasn't empty
        if(args[0] !=  NULL){
            if(strcmp(args[0], "r") != 0){
                //Copy into history if not a recent call
                for(i = 0; i < MAX_LINE/2+1 && args[i] != NULL; i++){
                    historyArgs[historyCount%10][i] = malloc(strlen(args[i]));
                    strcpy(historyArgs[historyCount%10][i], args[i]);
                }
                indexOfLatestCommand = historyCount%10;
                historyCount++;
            }


            //Create child process
            int pid = fork();

            //In child process
            if(pid == 0){
                if(strcmp(args[0], "r") == 0){
                    //If only "r" was entered, execute most recent command
                    if(args[1] == NULL){
                        printf("Entering recent?\n");
                        fflush(stdout);
                        int temp = 10; //SEGFAULTS HERE IF THIS IS INCLUDED
                        execvp(historyArgs[indexOfLatestCommand][0], &historyArgs[indexOfLatestCommand][0]);
                    }
                    else{
                        //Find in args[1][0] history, run if found
                        for(i = indexOfLatestCommand; i >= 0; i--){
                            if(historyArgs[i][0][0] == args[1][0]){
                                execvp(historyArgs[i][0], &historyArgs[i][0]);
                                break;
                            }
                        }
                        if(i == -1){
                            for(i = historyCount > HISTORY_SIZE ? HISTORY_SIZE : historyCount; i > indexOfLatestCommand; i--){
                                if(historyArgs[i][0][0] == args[1][0])
                                execvp(historyArgs[i][0], &historyArgs[i][0]);
                                break;
                            }
                        }
                    }
                }
                else execvp(args[0], &args[0]);
            }
            //In parent process
            else if (pid > 0){
                /*If child isn't a background process,
                 wait for child to terminate*/
                if(background == 0)
                    while(wait(&status) != pid);
            }

        }
    }
}

另一件值得一提的是,在该位置声明变量不会导致段错误。只有给新变量赋值。在该部分重新分配全局变量也不会导致段错误。

编辑:什么触发了崩溃。命令正确执行。当你运行它时,你可以输入任何命令,这应该可以工作。直到我执行 Ctrl-C 并打印出程序段错误的历史记录。

示例输入:


ls -a
grep
Ctrl-C

注意:如果你决定运行这个,知道要结束任务,你可能需要使用 kill 命令,因为我还没有实现“q”来退出。

【问题讨论】:

  • 哦,伙计,该信号处理程序中的未定义行为。你听说过异步安全吗?
  • 我的猜测是,您不会对传递给execvpargv 进行空终止,并且execvp 在访问未初始化的指针后会出现段错误。始终将 NULL 放在参数列表的末尾。
  • 但最重要的是:在信号处理程序中几乎没有什么是安全的。您可以在信号处理程序中调用的系统调用和库函数列表非常简短。 printf 和一般 C 库 IO 函数是绝对禁止的。理想情况下,信号处理程序应该设置一些标志并返回,让“常规”程序流稍后处理问题。
  • @MatteoItalia:“只是设置一些标志”有点不具体:标志必须是无锁原子或volatile sig_atomic_t类型。
  • 我不确定尝试调试这个程序是否有任何意义,使用这样的信号处理程序在设计上是无可救药的。您必须学习如何编写信号处理程序或尽可能避免使用它们。在这种特殊情况下,我会忘记信号,而是直接从主代码路径处理组合键。处理 tty I'm raw 模式需要做一些工作,但它更灵活(你可以使用任何你想要的组合键),而且它比异步安全更简单。

标签: c linux segmentation-fault


【解决方案1】:

您看到的症状(不相关的代码更改似乎会影响崩溃的性质)通常意味着您的程序更早导致了未定义的行为。行为的性质发生了变化,因为您的程序依赖于它在某个阶段读取或写入的垃圾值。

要调试它,请尝试删除程序中所有未定义行为的来源。最明显的一个是您的 void handle_SIGINT() 函数的内容。 唯一你可以在信号器中便携地做的事情是:

  • 设置volatile sig_atomic_t或其他无锁类型的变量,并返回
  • 做其他事情并致电_Exitabort 或类似名称。

特别是,您不能调用任何库函数,因为它们可能不可重入。

有关完整规范,请参阅当前 C 标准的第 7.14.1 节。如果您还遵循其他一些标准,例如POSIX,它可能会指定信号处理程序中允许的其他一些东西。

如果您不打算退出,则必须设置一个标志,然后稍后从您的主“线程”测试该标志以查看是否出现信号。

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 2021-04-06
    • 1970-01-01
    • 2022-12-18
    • 2017-08-18
    • 2017-05-10
    • 2011-03-16
    • 1970-01-01
    • 2011-02-22
    相关资源
    最近更新 更多