\documentclass[a4paper, 11pt,oneside]{article}
\usepackage[
  top=1.5cm,
  bottom=1cm,
  left=2cm,
  right=1.5cm,
  headheight=25.22153pt, % as per the warning by fancyhdr
  includehead,includefoot,
  heightrounded, % to avoid spurious underfull messages
]{geometry} 

\usepackage[T1]{fontenc}
\usepackage{microtype}
\usepackage{fancyhdr}
\usepackage{fancyvrb}
\usepackage{lipsum}
\usepackage{url}
\usepackage{listings}
\usepackage{lastpage}
\usepackage{enumitem}
\usepackage{datetime}
\usepackage{minted}

\settimeformat{hhmmsstime}
\yyyymmdddate

\pagestyle{fancy}
\fancyhf{} % clear all fields

\pagestyle{fancy}
\lhead{CMSC 125: Operating Systems \\ First Semester 2023-2024}
\rhead{Institute of Computer Science \\ University of the Philippines Los Banos}
\rfoot{JACHermocilla | CC BY-NC-SA 4.0}
%\cfoot{Enjoy!:)}
\cfoot{\thepage\ of \pageref{LastPage}}
\lfoot{Revision: \today\ \currenttime}
%\rfoot{https://jachermocilla.org/teaching/125}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}

\begin{document}

\begin{center}
   {\LARGE \textbf{ICS-OS Lab 02: Command Line Interface, System Calls, and System
Utilities }}
\end{center}

\section*{Objectives}
   At the end of this activity, you should be able to:
   \begin{enumerate}[itemsep=0pt,parsep=0pt]
       \item add a new console command;
       \item add a new system call service/function; and
       \item invoke a system call from a system utility.
   \end{enumerate}   

\section{Introduction}
The command line interface (CLI) is one way an operating system allows users to 
access its services such as program execution, file reading, displaying a 
string, and others. The CLI can be implemented as part of the kernel itself, as 
in the case of ICS-OS, or as a separate program, called a \textit{shell}, which 
is outside of the kernel. 

The user enters a command line on the CLI prompt and the shell executes the 
command. The command can be an \textit{internal shell command, a script, or an 
executable binary}. 

Running programs usually involve a \textit{system call} to be able to use the  
services provided by the kernel. These services are functions that execute in 
\textit{privileged or kernel mode} thus they cannot be invoked in the same 
manner as ordinary function calls in C (which execute in \textit{user mode}). 
The mechanism to perform system calls is in the form of software interrupts in 
x86 (32-bit Linux uses \texttt{int 80h}, MSDOS uses \texttt{int 21h}, and 
ICS-OS uses \texttt{int 30h}). 

Application Programming Interfaces(APIs), Software Development Kit(SDKs), and 
Runtime Environments (REs) make it easy to write programs for operating systems 
by hiding the details of the systems calls from the application programmers.


\section{Prerequisites}
To proceed with this lab, you should have completed \texttt{Lab 01}. Most of 
the commands that we will use in this lab will be run relative to the 
\texttt{\$ICSOS\_HOME/ics-os} directory. Update your local copy of the source 
code and create a new branch for this lab with the commands below.

\begin{minted}[frame=single,framesep=10pt]{bash}
$cd $ICSOS_HOME/ics-os
$git checkout master
$git pull
$git checkout -b lab02
$git branch    #to check the currrent branch
\end{minted}

You will need at least two terminals, one for the build container and another 
for code editing. See Task 3 in Lab 01 to start the build container.

\section{Deliverables and Credit}
Perform the tasks below and capture screenshots while you do them. Answer
all questions. Submit a PDF file containing the screen shots with captions
and answers to questions. Do not forget to put your name and laboratory
section.  Credit is ten (10) points.

\section{Tasks}

\subsection*{Task 1: Add a new console command (3 points)} 
The CLI in ICS-OS is part of the kernel. Its implementation is located in
\texttt{kernel/console/console.c}. The function \texttt{int 
console\_execute(const char *str)} is where the command string (what you type
in the \texttt{\%} prompt) is processed. Study this function. The 
\texttt{strtok()} function is used to tokenize the command string to extract
the command name and its arguments. The code fragment below is for the new
\texttt{add} internal command, with two integer arguments, that we wish to 
include. Insert the code fragment in an appropriate location in the 
\texttt{console\_execute()} function. Build and boot ICS-OS (as discussed in 
Tasks 3-5 in Lab 01) to test if the command works. Capture screenshots. Also 
show where you placed the code fragment. 

\begin{minted}[frame=single,framesep=10pt]{C}
if (strcmp(u,"add") == 0){   //-- Adds two integers. Args: <num1> <num2> 
   int a, b; 
   u = strtok(0," "); 
   a = atoi(u);
   u = strtok(0," "); 
   b = atoi(u); 
   printf("%d + %d = %d\n",a,b,a+b); 
}else
\end{minted}

\textbf{QUESTION}: What are the advantages and disadvantages of having the CLI as part of the kernel itself instead of a user application like Bash?

\subsection*{Task 2: Add a new system call service/function (3 points)}
The list of functions/services accessible through system calls are placed in a
\textit{system call table}. In ICS-OS, it is the array of structures 
defined in \texttt{kernel/dexapi/dex32API.h}: 

\begin{minted}[frame=single,framesep=10pt]{C}
api_systemcall api_syscalltable[API_MAXSYSCALLS];
\end{minted}

The function \texttt{api\_init()} in \texttt{kernel/dexapi/dex32API.c}
populates this table. 

ICS-OS hooks to \texttt{int 30h} to handle system calls. This is set in
\texttt{kernel/hardware/chips/irqhandlers.c}. Recall the interrupt system 
and the interrupt vector table (IVT) of x86 discussed in the lecture.

\begin{minted}[frame=single,framesep=10pt]{C}
setinterruptvector(0x30, dex_idtbase, 0xEE, syscallwrapper, SYS_CODE_SEL); 
\end{minted}

You do not have to understand all the parameters of the above function for now. 
The parameter \texttt{syscallwrapper} is a function defined in 
\texttt{kernel/irqwrap.asm}. It calls the function \texttt{api\_syscall(...)} 
from \texttt{kernel/dexapi/dex32API.c} which processes the system call and 
invokes the appropriate service from the system call table. 
\texttt{api\_syscall(...)} is called everytime \texttt{int 30h} is invoked or  
generated.

\begin{minted}[frame=single,framesep=10pt]{C}
DWORD api_syscall(DWORD fxn,DWORD val,DWORD val2,
                  DWORD val3,DWORD val4,DWORD val5);
\end{minted}


To add a system call, the \texttt{api\_addsystemcall()} function in 
\texttt{kernel/dexapi/dex32API.c} is used. Its prototype is shown below.
\begin{minted}[frame=single,framesep=10pt]{C}
int api_addsystemcall(DWORD function_number, void *function_ptr,
                        DWORD access_check, DWORD flags);
\end{minted}

The important parameters are \texttt{function\_number} and 
\texttt{function\_ptr}. Say you want to implement the 
\texttt{kchown()}\footnote{Usually functions in the kernel are written with the 
letter \texttt{k} at the start} system call function/service below that changes 
the owner of a file (does nothing for now). Edit  
\texttt{kernel/dexapi/dex32API.c} and add the function.

\begin{minted}[frame=single,framesep=10pt]{C}
int kchown(int fd, int uid, int gid){
   printf("Changing owner of fd=%d to user id=%d and group id=%d\n", fd, uid, gid);
   //Actual code to change file ownership is placed here.
   //For now this is just empty   
   return 0; //0-success
}
\end{minted}

To add it to the system call table, add the following line at the end of the 
\texttt{api\_init()} function in \newline 
\texttt{kernel/dexapi/dex32API.c}. The function/service number we will use is 
\texttt{0xC2}. Take note of this number.

\begin{minted}[frame=single,framesep=10pt]{C}
api_addsystemcall(0xC2, kchown, 0, 0);
\end{minted}

Capture screenshots where you placed the codes. 
Build ICS-OS (Task 3 of Lab 01). At this point, the new system call is added to 
the kernel but it 
is not being used/invoked yet. We will do that in the next task. 

\subsection*{Task 3: Invoke a system call in a system utility (4 points)}
In this task you are to make a system utility that invokes the system call 
service you created in \texttt{Task 2}. In ICS-OS, system utilities  and user 
applications source codes are placed in the \texttt{contrib} folder. There is 
an example application, \texttt{hello}, which we will use as template. Study 
the \texttt{Makefile}. 

\subsubsection*{Task3a: Create the source}
Run the commands below on the code editing terminal to create the  
\texttt{chown.exe} system utility source code. We are basically copying 
\texttt{hello} and replacing some information.

\begin{minted}[frame=single,framesep=10pt]{bash}
$cd contrib	   #go to the contrib folder
$cp -r hello/ chown/   #copy hello to chown
$cd chown/             #go inside chown
$mv hello.c chown.c    #rename hello.c to chown .c
$sed -i 's/hello/chown/g' Makefile   #replace hello with chown in the Makefile
\end{minted}

\subsubsection*{Task3b: Build the executable and install}
Start the build container to create and install the \texttt{chown.exe} 
executable. Use the following commands.
\begin{minted}[frame=single,framesep=10pt]{bash}
#cd /home/ics-os/contrib/chown
#make
#make install
\end{minted}

\subsubsection*{Task3c: Run the executable inside ICS-OS}
Build and boot ICS-OS (Task 3 and Task 4 of Lab 01). Inside ICS-OS, run the 
following commands and capture screenshots.

\begin{minted}[frame=single,framesep=10pt]{bash}
%cd apps
%ls -l -oname
%chown.exe
\end{minted}

\textbf{QUESTION}: What is the output after executing \texttt{chown.exe} inside 
ICS-OS? \newline

\subsubsection*{Task3d: Modify chown.c to invoke the new service via syscall}
Go back to the \texttt{contrib/chown} folder in the code editing terminal. Edit 
\texttt{chown.c} and replace the contents with the code below. Perform Task 3b 
and Task 3c above again after the edit.

\begin{minted}[frame=single,framesep=10pt]{C}
#include "../../sdk/dexsdk.h"
#define KCHOWN_SERVICE_NO 0xC2
int main(int argc, char *argv[]) {
   if (argc < 4){ 
      printf("Usage: chown.exe <fd> <uid> <gid>\n");
      return -1; 
   }   
   dexsdk_systemcall(KCHOWN_SERVICE_NO, atoi(argv[1]), atoi(argv[2]), 
                     atoi(argv[3]), 0, 0); 
   return 0;
}
\end{minted}

\textbf{QUESTION}: Study the function \texttt{dexsdk\_systemcall()} defined in 
\texttt{sdk/tccsdk.c}. What does this function do? Discuss two other functions 
that call \texttt{dexsdk\_systemcall()}. \newline 

\textbf{QUESTION}: What is the output of executing \texttt{chown.exe}, complete with command line arguments, this time? Describe what you think happened.


\subsection*{Task 4: Cleanup}
To exit the build container. 
\begin{minted}[frame=single,framesep=10pt]{bash}
:/#exit
\end{minted}

Go back to the master branch of the source code.
\begin{minted}[frame=single,framesep=10pt]{bash}
$git checkout master
\end{minted}



%\begin{thebibliography}{9} \end{thebibliography}
\section{Tips}
You can use the \texttt{grep} utility to quickly search for strings in files from \texttt{\$ICSOS\_HOME} .
\begin{minted}[frame=single,framesep=10pt]{bash}
$ grep -rn api_init
\end{minted}
 
\section{Reflection}
Write some realizations and questions that crossed your mind while doing this 
lab. 


\end{document}
