Skip to content
Snippets Groups Projects
Commit 6ece86f4 authored by Adorn Binoy's avatar Adorn Binoy
Browse files

Assignment 3 submission

parent 5418cf4c
No related branches found
No related tags found
No related merge requests found
{
"configurations": [
{
"name": "(gdb) 3-ShellP1",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/3-ShellP1/starter/dsh",
"args": [""],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/3-ShellP1/starter",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Set Disassembly Flavor to Intel",
"text": "-gdb-set disassembly-flavor intel",
"ignoreFailures": true
}
],
"preLaunchTask": "Build 3-ShellP1"
}
]
}
\ No newline at end of file
{
"version": "2.0.0",
"tasks": [
{
"label": "Build 3-ShellP1",
"type": "shell",
"command": "make",
"group": {
"kind": "build",
"isDefault": true
},
"options": {
"cwd": "${workspaceFolder}/3-ShellP1/starter"
},
"problemMatcher": ["$gcc"],
"detail": "Runs the 'make' command to build the project."
}
]
}
\ No newline at end of file
File added
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dshlib.h"
/*
* Implement your main function by building a loop that prompts the
* user for input. Use the SH_PROMPT constant from dshlib.h and then
* use fgets to accept user input. Since we want fgets to also handle
* end of file so we can run this headless for testing we need to check
* the return code of fgets. I have provided an example below of how
* to do this assuming you are storing user input inside of the cmd_buff
* variable.
*
* while(1){
* printf("%s", SH_PROMPT);
* if (fgets(cmd_buff, ARG_MAX, stdin) == NULL){
* printf("\n");
* break;
* }
* //remove the trailing \n from cmd_buff
* cmd_buff[strcspn(cmd_buff,"\n")] = '\0';
*
* //IMPLEMENT THE REST OF THE REQUIREMENTS
* }
*
* Also, use the constants in the dshlib.h in this code.
* SH_CMD_MAX maximum buffer size for user input
* EXIT_CMD constant that terminates the dsh program
* SH_PROMPT the shell prompt
* OK the command was parsed properly
* WARN_NO_CMDS the user command was empty
* ERR_TOO_MANY_COMMANDS too many pipes used
*
* Expected output:
*
* CMD_OK_HEADER if the command parses properly. You will
* follow this by the command details
*
* CMD_WARN_NO_CMD if the user entered a blank command
* CMD_ERR_PIPE_LIMIT if the user entered too many commands using
* the pipe feature, e.g., cmd1 | cmd2 | ... |
*
* See the provided test cases for output expectations.
*/
int main()
{
char *cmd_buff = (char *)malloc(SH_CMD_MAX * sizeof(char));
if (cmd_buff == NULL) {
fprintf(stderr, "Failed to allocate memory\n");
return 1;
}
int rc = 0;
command_list_t clist;
while(1) {
printf("%s", SH_PROMPT);
if (fgets(cmd_buff, ARG_MAX, stdin) == NULL) {
printf("\n");
break;
}
//remove the trailing \n from cmd_buff
cmd_buff[strcspn(cmd_buff,"\n")] = '\0';
//IMPLEMENT THE REST OF THE REQUIREMENTS
if (strcmp(cmd_buff, EXIT_CMD) == 0) {
exit(0);
}
int result = build_cmd_list(cmd_buff, &clist);
if (result == OK) {
printf(CMD_OK_HEADER, clist.num);
for (int i = 0; i < clist.num; i++) {
if (strlen(clist.commands[i].args) > 0)
printf("<%d> %s [%s]\n", i + 1, clist.commands[i].exe, clist.commands[i].args);
else
printf("<%d> %s\n", i + 1, clist.commands[i].exe);
}
} else if (result == WARN_NO_CMDS) {
printf(CMD_WARN_NO_CMD "\n");
} else if (result == ERR_TOO_MANY_COMMANDS) {
printf(CMD_ERR_PIPE_LIMIT "\n", CMD_MAX);
} else if (result == ERR_CMD_OR_ARGS_TOO_BIG) {
printf("Error: command or arguments too big\n");
}
}
return 0;
}
\ No newline at end of file
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "dshlib.h"
/*
* build_cmd_list
* cmd_line: the command line from the user
* clist *: pointer to clist structure to be populated
*
* This function builds the command_list_t structure passed by the caller
* It does this by first splitting the cmd_line into commands by spltting
* the string based on any pipe characters '|'. It then traverses each
* command. For each command (a substring of cmd_line), it then parses
* that command by taking the first token as the executable name, and
* then the remaining tokens as the arguments.
*
* NOTE your implementation should be able to handle properly removing
* leading and trailing spaces!
*
* errors returned:
*
* OK: No Error
* ERR_TOO_MANY_COMMANDS: There is a limit of CMD_MAX (see dshlib.h)
* commands.
* ERR_CMD_OR_ARGS_TOO_BIG: One of the commands provided by the user
* was larger than allowed, either the
* executable name, or the arg string.
*
* Standard Library Functions You Might Want To Consider Using
* memset(), strcmp(), strcpy(), strtok(), strlen(), strchr()
*/
int build_cmd_list(char *cmd_line, command_list_t *clist) {
if (!cmd_line || strlen(cmd_line) == 0) {
return WARN_NO_CMDS;
}
clist->num = 0;
char cmd_copy[SH_CMD_MAX];
strncpy(cmd_copy, cmd_line, SH_CMD_MAX - 1);
cmd_copy[SH_CMD_MAX - 1] = '\0';
char* saveptr1;
char* cmd = strtok_r(cmd_copy, PIPE_STRING, &saveptr1);
while (cmd != NULL) {
if (clist->num >= CMD_MAX) {
return ERR_TOO_MANY_COMMANDS;
}
while(isspace((unsigned char)*cmd)) cmd++;
if(*cmd != 0) {
char* end = cmd + strlen(cmd) - 1;
while(end > cmd && isspace((unsigned char)*end)) end--;
end[1] = '\0';
}
if (strlen(cmd) == 0) {
return WARN_NO_CMDS;
}
char* saveptr2;
char* exe = strtok_r(cmd, " ", &saveptr2);
if (!exe) {
return WARN_NO_CMDS;
}
if (strlen(exe) >= EXE_MAX) {
return ERR_CMD_OR_ARGS_TOO_BIG;
}
strncpy(clist->commands[clist->num].exe, exe, EXE_MAX - 1);
clist->commands[clist->num].exe[EXE_MAX - 1] = '\0';
char* args = strtok_r(NULL, "", &saveptr2);
if (args) {
while(isspace((unsigned char)*args)) args++;
if(*args != 0) {
char* end = args + strlen(args) - 1;
while(end > args && isspace((unsigned char)*end)) end--;
end[1] = '\0';
}
if (strlen(args) >= ARG_MAX) {
return ERR_CMD_OR_ARGS_TOO_BIG;
}
strncpy(clist->commands[clist->num].args, args, ARG_MAX - 1);
clist->commands[clist->num].args[ARG_MAX - 1] = '\0';
} else {
clist->commands[clist->num].args[0] = '\0';
}
clist->num++;
cmd = strtok_r(NULL, PIPE_STRING, &saveptr1);
}
return 0;
}
\ No newline at end of file
#ifndef __DSHLIB_H__
#define __DSHLIB_H__
// Constants for command structure sizes
#define EXE_MAX 64
#define ARG_MAX 256
#define CMD_MAX 8
// Longest command that can be read from the shell
#define SH_CMD_MAX EXE_MAX + ARG_MAX
typedef struct command
{
char exe[EXE_MAX];
char args[ARG_MAX];
} command_t;
typedef struct command_list
{
int num;
command_t commands[CMD_MAX];
} command_list_t;
// Special character #defines
#define SPACE_CHAR ' '
#define PIPE_CHAR '|'
#define PIPE_STRING "|"
#define SH_PROMPT "dsh> "
#define EXIT_CMD "exit"
// Standard Return Codes
#define OK 0
#define WARN_NO_CMDS -1
#define ERR_TOO_MANY_COMMANDS -2
#define ERR_CMD_OR_ARGS_TOO_BIG -3
// starter code
#define M_NOT_IMPL "The requested operation is not implemented yet!\n"
#define EXIT_NOT_IMPL 3
#define NOT_IMPLEMENTED_YET 0
// prototypes
int build_cmd_list(char *cmd_line, command_list_t *clist);
// output constants
#define CMD_OK_HEADER "PARSED COMMAND LINE - TOTAL COMMANDS %d\n"
#define CMD_WARN_NO_CMD "warning: no commands provided\n"
#define CMD_ERR_PIPE_LIMIT "error: piping limited to %d commands\n"
#endif
\ No newline at end of file
# Compiler settings
CC = gcc
CFLAGS = -Wall -Wextra -g
# Target executable name
TARGET = dsh
# Find all source and header files
SRCS = $(wildcard *.c)
HDRS = $(wildcard *.h)
# Default target
all: $(TARGET)
# Compile source to executable
$(TARGET): $(SRCS) $(HDRS)
$(CC) $(CFLAGS) -o $(TARGET) $(SRCS)
# Clean up build files
clean:
rm -f $(TARGET)
test:
./test.sh
# Phony targets
.PHONY: all clean
\ No newline at end of file
1. In this assignment I suggested you use `fgets()` to get user input in the main while loop. Why is `fgets()` a good choice for this application?
> **Answer**: 'fgets()' is a good choice for this application because it is able to handle the new line character, is able to detect the EOF, and most importantly, prevents buffer overflows.
2. You needed to use `malloc()` to allocte memory for `cmd_buff` in `dsh_cli.c`. Can you explain why you needed to do that, instead of allocating a fixed-size array?
> **Answer**: We had to make use of malloc() because it allows for future proofing in a sense. When larger commands get created in later assignments, having a dynamic memory allocation system will prove to be beneifical.
3. In `dshlib.c`, the function `build_cmd_list(`)` must trim leading and trailing spaces from each command before storing it. Why is this necessary? If we didn't trim spaces, what kind of issues might arise when executing commands in our shell?
> **Answer**: This is necessary because it can potentially change the way that user input is treated. This is especially true when piping is involved. Finally, certain system calls may fail to execeute if trailing spaces are included.
4. For this question you need to do some research on STDIN, STDOUT, and STDERR in Linux. We've learned this week that shells are "robust brokers of input and output". Google _"linux shell stdin stdout stderr explained"_ to get started.
- One topic you should have found information on is "redirection". Please provide at least 3 redirection examples that we should implement in our custom shell, and explain what challenges we might have implementing them.
> **Answer**: command > file: ensuring permissions are properly set. command < file: the file must be verified to exist before the command is attempted to run. command 2> error.log: Filer descriptor handling and separation of the streams.
- You should have also learned about "pipes". Redirection and piping both involve controlling input and output in the shell, but they serve different purposes. Explain the key differences between redirection and piping.
> **Answer**: The main differences between redirection and piping are that redirection involves a command with files while pipes work with 2 separate commands. Pipes are also bidirectional (work both ways) while redirection is unidirectional. Finally, pipes are temporary and only exists when the command is run while redirection has the power to modify files permanently.
- STDERR is often used for error messages, while STDOUT is for regular output. Why is it important to keep these separate in a shell?
> **Answer**: It is important to have sepation here as error messages should be visible even if there was output being redirected. Error logging is also made easier when they are separate from the program's typical output.
- How should our custom shell handle errors from commands that fail? Consider cases where a command outputs both STDOUT and STDERR. Should we provide a way to merge them, and if so, how?
> **Answer**: Our shell should handle errors from failed commands by treating them separatley from the normal output by returning error codes. This can be done using SRDERR and the shell should have the ability to continue running even if errors occur (unless specified otherwise).
\ No newline at end of file
#!/usr/bin/env bats
@test "Simple Command" {
run ./dsh <<EOF
test_command
exit
EOF
# Strip all whitespace (spaces, tabs, newlines) from the output
stripped_output=$(echo "$output" | tr -d '[:space:]')
# Expected output with all whitespace removed for easier matching
expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>test_commanddsh>"
# These echo commands will help with debugging and will only print
#if the test fails
echo "Captured stdout:"
echo "Output: $output"
echo "Exit Status: $status"
# Check exact match
[ "$stripped_output" = "$expected_output" ]
# Assertions
[ "$status" -eq 0 ]
}
@test "Simple Command with Args" {
run ./dsh <<EOF
cmd -a1 -a2
exit
EOF
# Strip all whitespace (spaces, tabs, newlines) from the output
stripped_output=$(echo "$output" | tr -d '[:space:]')
# Expected output
expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>cmd[-a1-a2]dsh>"
# These echo commands will help with debugging and will only print
#if the test fails
echo "Captured stdout:"
echo "Output: $output"
echo "Exit Status: $status"
# Check exact match
[ "$stripped_output" = "$expected_output" ]
# Assertions
[ "$status" -eq 0 ]
}
@test "No command provided" {
run ./dsh <<EOF
exit
EOF
# Strip all whitespace (spaces, tabs, newlines) from the output
stripped_output=$(echo "$output" | tr -d '[:space:]')
# Expected output with all whitespace removed for easier matching
expected_output="dsh>warning:nocommandsprovideddsh>"
# These echo commands will help with debugging and will only print
#if the test fails
echo "Captured stdout:"
echo "Output: $output"
echo "Exit Status: $status"
# Check exact match
[ "$stripped_output" = "$expected_output" ]
# Assertions
[ "$status" -eq 0 ]
}
@test "Two commands" {
run ./dsh <<EOF
command_one | command_two
exit
EOF
# Strip all whitespace (spaces, tabs, newlines) from the output
stripped_output=$(echo "$output" | tr -d '[:space:]')
# Expected output with all whitespace removed for easier matching
expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS2<1>command_one<2>command_twodsh>"
# These echo commands will help with debugging and will only print
#if the test fails
echo "Captured stdout:"
echo "Output: $output"
echo "Exit Status: $status"
# Check exact match
[ "$stripped_output" = "$expected_output" ]
# Assertions
[ "$status" -eq 0 ]
}
@test "three commands with args" {
run ./dsh <<EOF
cmd1 a1 a2 a3 | cmd2 a4 a5 a6 | cmd3 a7 a8 a9
exit
EOF
# Strip all whitespace (spaces, tabs, newlines) from the output
stripped_output=$(echo "$output" | tr -d '[:space:]')
# Expected output with all whitespace removed for easier matching
expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS3<1>cmd1[a1a2a3]<2>cmd2[a4a5a6]<3>cmd3[a7a8a9]dsh>"
# These echo commands will help with debugging and will only print
#if the test fails
echo "Captured stdout:"
echo "Output: $output"
echo "Exit Status: $status"
# Check exact match
[ "$stripped_output" = "$expected_output" ]
# Assertions
[ "$status" -eq 0 ]
}
@test "try max (8) commands" {
run ./dsh <<EOF
cmd1 | cmd2 | cmd3 | cmd4 | cmd5 | cmd6 | cmd7 | cmd8
exit
EOF
# Strip all whitespace (spaces, tabs, newlines) from the output
stripped_output=$(echo "$output" | tr -d '[:space:]')
# Expected output with all whitespace removed for easier matching
expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS8<1>cmd1<2>cmd2<3>cmd3<4>cmd4<5>cmd5<6>cmd6<7>cmd7<8>cmd8dsh>"
# These echo commands will help with debugging and will only print
#if the test fails
echo "Captured stdout:"
echo "Output: $output"
echo "Exit Status: $status"
# Check exact match
[ "$stripped_output" = "$expected_output" ]
# Assertions
[ "$status" -eq 0 ]
}
@test "try too many commands" {
run ./dsh <<EOF
cmd1 | cmd2 | cmd3 | cmd4 | cmd5 | cmd6 | cmd7 | cmd8 | cmd9
exit
EOF
# Strip all whitespace (spaces, tabs, newlines) from the output
stripped_output=$(echo "$output" | tr -d '[:space:]')
# Expected output with all whitespace removed for easier matching
expected_output="dsh>error:pipinglimitedto8commandsdsh>"
# These echo commands will help with debugging and will only print
#if the test fails
echo "Captured stdout:"
echo "Output: $output"
echo "Exit Status: $status"
# Check exact match
[ "$stripped_output" = "$expected_output" ]
# Assertions
[ "$status" -eq 0 ]
}
@test "kitchen sink - multiple commands" {
run ./dsh <<EOF
cmd1
cmd2 arg arg2
p1 | p2
p3 p3a1 p3a2 | p4 p4a1 p4a2
EOF
# Strip all whitespace (spaces, tabs, newlines) from the output
stripped_output=$(echo "$output" | tr -d '[:space:]')
# Expected output with all whitespace removed for easier matching
expected_output="dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>cmd1dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS1<1>cmd2[argarg2]dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS2<1>p1<2>p2dsh>PARSEDCOMMANDLINE-TOTALCOMMANDS2<1>p3[p3a1p3a2]<2>p4[p4a1p4a2]dsh>"
# These echo commands will help with debugging and will only print
#if the test fails
echo "Captured stdout:"
echo "Output: $output"
echo "Exit Status: $status"
# Check exact match
[ "$stripped_output" = "$expected_output" ]
# Assertions
[ "$status" -eq 0 ]
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment