Files
2025-03-02 14:58:20 +00:00

55 lines
1.8 KiB
TeX

\documentclass{article}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{document}
\begin{algorithm}
\caption{Memory Management with CHERI}
\begin{algorithmic}[1]
\State \textbf{Define} FILENAME $\gets "/dev/contigmem"$
\State \textbf{Define} $ptr$ \Comment{Pointer to allocated memory}
\State \textbf{Define} $MallocCounter$ \Comment{Remaining memory size}
\State \textbf{Define} $sizeUsed$ \Comment{Size of used memory}
\Function{INITAlloc}{}
\State $sz \gets 100000000$ \Comment{Set allocation size}
\State $fd \gets \text{open}(FILENAME, O\_RDWR, 0600)$
\If{$fd < 0$}
\State \textbf{Handle Error:} \text{exit}(EXIT\_FAILURE)
\EndIf
\State $offset \gets 0$ \Comment{Offset for seeking}
\If{$\text{ftruncate}(fd, sz) < 0$}
\State \textbf{Handle Error:} \text{close}(fd), \text{exit}(EXIT\_FAILURE)
\EndIf
\State $ptr \gets \text{mmap}(NULL, sz, PROT\_READ | PROT\_WRITE, MAP\_SHARED, fd, 0)$
\If{$ptr = \text{MAP\_FAILED}$}
\State \textbf{Handle Error:} \text{exit}(EXIT\_FAILURE)
\EndIf
\State $MallocCounter \gets sz$
\EndFunction
\Function{malloc}{sz}
\State $sz \gets \text{align\_up}(sz, \text{\_Alignof}(max\_align\_t))$ \Comment{Align the size}
\State $MallocCounter \gets MallocCounter - sz$
\State $ptrLink \gets ptr[MallocCounter]$ \Comment{Allocate memory at the current position}
\State $ptrLink \gets \text{cheri\_setbounds}(ptrLink, sz)$ \Comment{Set bounds for CHERI}
\State \Return $ptrLink$ \Comment{Return the allocated pointer}
\EndFunction
\Function{FREECHERI}{ptr}
\State $len \gets \text{cheri\_getlen}(ptr)$ \Comment{Get the length from pointer bounds}
\State \text{munmap}(ptr, len) \Comment{Unmap the memory}
\EndFunction
\end{algorithmic}
\end{algorithm}
\end{document}