From 715c2aced8f98dd81ade94ef9b896a764e5ffe14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kha=C3=AFs=20COLIN?= Date: Wed, 2 Apr 2025 19:14:00 +0200 Subject: [PATCH] exit: handle invalid and large arguments --- src/executing/simple_cmd/builtin_exit.c | 58 +++++++++++++++++++++++-- test.sh | 49 +++++++++++++++++++++ 2 files changed, 104 insertions(+), 3 deletions(-) diff --git a/src/executing/simple_cmd/builtin_exit.c b/src/executing/simple_cmd/builtin_exit.c index e164a38..2c9eb18 100644 --- a/src/executing/simple_cmd/builtin_exit.c +++ b/src/executing/simple_cmd/builtin_exit.c @@ -6,21 +6,73 @@ /* By: khais +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2025/04/01 18:17:56 by khais #+# #+# */ -/* Updated: 2025/04/02 15:06:22 by khais ### ########.fr */ +/* Updated: 2025/04/15 11:48:05 by khais ### ########.fr */ /* */ /* ************************************************************************** */ #include "builtins.h" #include #include "libft.h" +#include "simple_cmd_execute.h" +#include "unistd.h" + +static int ft_isspace(char c) +{ + return ((c == ' ' || c == '\f' || c == '\n' + || c == '\r' || c == '\t' || c == '\v')); +} + +static int ft_atoi_strict(const char *nptr, bool *ok) +{ + int sign; + int calc; + + sign = 1; + calc = 0; + *ok = true; + while (*nptr && ft_isspace(*nptr)) + nptr++; + if (*nptr == '+' || *nptr == '-') + { + if (nptr[0] == '-') + sign = -1; + nptr++; + } + while (*nptr && ft_isdigit(*nptr)) + { + calc = calc * 10 + (*nptr - '0'); + nptr++; + } + if (*nptr != '\0') + *ok = false; + return (sign * calc); +} + +static int numeric_arg_required(char *arg) +{ + ft_dprintf(STDERR_FILENO, + "minishell: exit: %s: numeric argument required\n", arg); + return (2); +} t_builtin_type builtin_exit(t_simple_cmd *cmd, t_minishell *app) { - int status; + int status; + bool ok; status = 0; if (cmd->words->next != NULL) - status = ft_atoi(cmd->words->next->word->word); + { + status = ft_atoi_strict(cmd->words->next->word->word, &ok); + if (!ok) + status = numeric_arg_required(cmd->words->next->word->word); + else if (cmd->words->next->next != NULL) + { + ft_dprintf(STDERR_FILENO, "minishell: exit: too many arguments\n"); + app->last_return_value = 1; + return (BUILTIN_EXIT); + } + } simple_cmd_destroy(cmd); env_destroy(app->env); exit(status); diff --git a/test.sh b/test.sh index 8061ec0..c5b6717 100755 --- a/test.sh +++ b/test.sh @@ -375,6 +375,55 @@ expecting <