From 5352fb5da75bcc6d1cfdcad2f92046212316b686 Mon Sep 17 00:00:00 2001 From: tink Date: Wed, 11 Oct 2023 23:40:45 +0800 Subject: [PATCH] first commit --- .gitmodules | 3 + Makefile | 7 + README.md | 13 + archetypes/default.md | 5 + assets/_fonts.scss | 33 ++ content/en/_index.md | 11 + content/en/chap1/Authors.md | 215 ++++++++++++ content/en/chap1/_index.md | 19 ++ content/en/chap2/Debugging_Environments.md | 181 ++++++++++ content/en/chap2/GDB.md | 323 ++++++++++++++++++ content/en/chap2/Homework0.md | 219 ++++++++++++ content/en/chap2/Systems_Architecture.md | 50 +++ content/en/chap2/Valgrind.md | 70 ++++ content/en/chap2/_index.md | 7 + content/en/chap3/_index.md | 15 + content/en/chap4/_index.md | 47 +++ content/en/chap5/_index.md | 6 + content/en/chap6/_index.md | 9 + content/en/menu/index.md | 23 ++ content/zh/_index.md | 17 + content/zh/menu/index.md | 0 hugo.toml | 118 +++++++ ...s_e129fe35b8d0a70789c8a08429469073.content | 1 + ...scss_e129fe35b8d0a70789c8a08429469073.json | 1 + themes/hugo-book | 1 + 25 files changed, 1394 insertions(+) create mode 100644 .gitmodules create mode 100644 Makefile create mode 100644 README.md create mode 100644 archetypes/default.md create mode 100644 assets/_fonts.scss create mode 100644 content/en/_index.md create mode 100644 content/en/chap1/Authors.md create mode 100644 content/en/chap1/_index.md create mode 100644 content/en/chap2/Debugging_Environments.md create mode 100644 content/en/chap2/GDB.md create mode 100644 content/en/chap2/Homework0.md create mode 100644 content/en/chap2/Systems_Architecture.md create mode 100644 content/en/chap2/Valgrind.md create mode 100644 content/en/chap2/_index.md create mode 100644 content/en/chap3/_index.md create mode 100644 content/en/chap4/_index.md create mode 100644 content/en/chap5/_index.md create mode 100644 content/en/chap6/_index.md create mode 100644 content/en/menu/index.md create mode 100644 content/zh/_index.md create mode 100644 content/zh/menu/index.md create mode 100644 hugo.toml create mode 100644 resources/_gen/assets/scss/book.scss_e129fe35b8d0a70789c8a08429469073.content create mode 100644 resources/_gen/assets/scss/book.scss_e129fe35b8d0a70789c8a08429469073.json create mode 160000 themes/hugo-book diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..12744dd --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "themes/hugo-book"] + path = themes/hugo-book + url = https://github.com/alex-shpak/hugo-book diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..797c050 --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +all: + +serve: + hugo serve + +html: + hugo \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..8edcebc --- /dev/null +++ b/README.md @@ -0,0 +1,13 @@ +# UIUC CS241 系统编程中文讲义 + +![](https://static.cyub.vip/images/202207/duck-alpha-cropped.png) + +伊利诺伊大学香槟分校 (UIUC) 的CS 341: System Programming课程(之前课程名是CS 241)的教学讲义的中文译本。 + +Happy Reading! + +## 资料 + +- [CS 341: System Programming课程官网](http://cs341.cs.illinois.edu/) +- [CS 341: System Programming讲义](http://cs341.cs.illinois.edu/coursebook/index.html) +- [CS 341: System Programming讲义的Github link](https://github.com/illinois-cs241/coursebook/wiki) \ No newline at end of file diff --git a/archetypes/default.md b/archetypes/default.md new file mode 100644 index 0000000..c6f3fce --- /dev/null +++ b/archetypes/default.md @@ -0,0 +1,5 @@ ++++ +title = '{{ replace .File.ContentBaseName "-" " " | title }}' +date = {{ .Date }} +draft = true ++++ diff --git a/assets/_fonts.scss b/assets/_fonts.scss new file mode 100644 index 0000000..ca5ef0d --- /dev/null +++ b/assets/_fonts.scss @@ -0,0 +1,33 @@ +body { + font-size: 16px; + font-weight: normal; + font-family: "Noto Sans CJK SC", "Source Han Sans SC", "Source Han Sans CN", "Noto Sans SC", "PingFang SC", "Microsoft YaHei", sans-serif; +} + +.formula-text-center { + margin-left: auto; + margin-right: auto; + display: block; + font-size: 18px; + text-align: center; +} + +.markdown { + summary { + font-size: 16px; + font-weight: bold; + } + + figure { + img { + text-align: right; + margin-left: auto; + margin-right: auto; + display: block; + } + + figcaption { + text-align: center; + } + } +} \ No newline at end of file diff --git a/content/en/_index.md b/content/en/_index.md new file mode 100644 index 0000000..bcd184b --- /dev/null +++ b/content/en/_index.md @@ -0,0 +1,11 @@ ++++ +title = "Preface" ++++ + +# systems programming coursebook + +{{< figure src="https://static.cyub.vip/images/202207/duck-alpha-cropped.png" width="500px" class="text-center" >}} + +This coursebook is being built by students and faculty from the University of Illinois. It is based on a crowd-source authoring wikibook experiment by Lawrence Angrave from CS @ Illinois, but is now its own .tex based project. Its source code is located at the Github link which you can find a pdf version of the book as well. + +This book is an introduction to programming in C, and system programming (processes, threads, synchronization, networking and more!). We assume you’ve already had some programming experience, in an earlier computer science course. If you have any typos to report or content to request, feel free to file an issue at the link above. Happy Reading! \ No newline at end of file diff --git a/content/en/chap1/Authors.md b/content/en/chap1/Authors.md new file mode 100644 index 0000000..fc16fbc --- /dev/null +++ b/content/en/chap1/Authors.md @@ -0,0 +1,215 @@ +# Authors + +``` +Bhuvan Venkatesh +Lawrence Angrave +joebenassi +jakebailey +Ebrahim Byagowi +Alex Kizer +dimyr7 +Ed K +ace-n +josephmilla +Thomas Liu +Johnny Chang +goldcase +vassimladenov +SurtaiHan +Brandon Chong +Ben Kurtovic +dprorok2 +anchal-agrawal +Lawrence Angrave +daeyun +bchong95 +rushingseas8 +lukspdev +hilalh +dimyr7 +Azrakal +G. Carl Evans +Cornel Punga +vikasagartha +dyarbrough93 +berwin7996 +Sudarshan Govindaprasad +NMyren +Ankit Gohel +vha-weh-shh +sasankc +rishabhjain2795 +nickgarfield +by700git +bw-vbnm +Navneeth Jayendran +Joe Benassi +Harpreet Singh +FenixFeather +EntangledLight +Bliss Chapman +zikaeroh +time bandit +paultgibbons +kevinwang +cPolaris +Zecheng (張澤成) +Wieschie +WeiL +Graham Dyer +Arun Prakash Jana +Ankit Goel +Allen Kleiner +Abhishek Deep Nigam +zmmille2 +sidewallme +raych05 +mmahes +mass +kovaka +gmag23 +ejian2 +cerutii +briantruong777 +adevar +Yuxuan Zou (Sean) +Xikun Zhang +Vishal Disawar +Taemin Shin +Sujay Patwardhan +SufeiZ +Sufei Zhang +Steven Shang +Steve Zhu +Sibo Wang +Shane Ryan +Scott Bigelow +Riyad Shauk +Nathan Somers +LieutenantChips +Jacob K LaGrou +George +David Levering +Bernard Lim +zwang180 +xuanwang91 +xin-0 +wchill +vishnui +tvarun2013 +sstevenshang +ssquirrel +smeenai +shrujancheruku +ruiqili2 +rchwlsk2 +ralphchung +nikioftime +mosaic0123 +majiasheng +m +li820970 +kuck1 +kkgomez2 +jjames34 +jargals2 +hzding621 +hzding621 +hsingh23 +denisdemaisbr +daishengliang +cucumbur +codechao999 +chrisshroba +cesarcastmore +briantruong777 +botengHY +blapalp +bchhetri1 +anadella96 +akleiner2 +aRatnam12 +Yash Sharma +Xiangbin Hu +WininWin +William Klock +WenhanZ +Vivek Pandya +Vineeth Puli +Vangelis Tsiatsianas +Vadiml1024 +Utsav2 +Thirumal Venkat +TheEntangledLight +SudarshanGp +Sudarshan Konge <6025419+sudk1896@users.noreply.github.com> +Slix +Sasank Chundi +SachinRaghunathan +Rémy Léone +RusselLuo +Roman Vaivod +Rohit Sarathy +Rick Sheahan +Rakhim Davletkaliyev +Punitvara +Phillip Quy Le +Pavle Simonovic +Paul Hindt +Nishant Maniam +Mustafa Altun +Mohammed Sadik P. K +Mingchao Zhang <43462732+mingchao-zhang@users.noreply.github.com> +Michael Vanderwater +Maxiwell Luo +LunaMystic +Liam Monahan +Joshua Wertheim +John Pham +Johannes Scheuermann +Joey Bloom <15joeybloom@users.noreply.github.com> +Jimmy Zhang +Jeffrey Foster +James Daniel +Jake Bailey +JACKHAHA363 +Hydrosis +Hong +Grant Wu +EvanFabry +EddieVilla +Deepak Nagaraj +Daniel Meir Doron +Daniel Le +Daniel Jamrozik +Daniel Carballal +Daniel +Daeyun Shin +Creyslz +Christian Cygnus +CharlieMartell +Caleb Bassi +Brian Kurek +Brendan Wilson +Bo Liu +Ayush Ranjan +Atul kumar Agrawal +Artur Sak +Ankush Agarwal +Angelino +Andrey Zaytsev +Alex Yang +Alex Cusack +Aidan Epstein +Ace Nassri +Abdullahi Abdalla +Aneesh Durg +Assassin Eclipse +Eric Cao +Raphael Long +WeiL +williamsentosa95 <38774380+williamsentosa95@users.noreply.github.com> +Pradyumna Shome +Benjamin West Pollak +姜芃越 Pengyue Jiang +``` \ No newline at end of file diff --git a/content/en/chap1/_index.md b/content/en/chap1/_index.md new file mode 100644 index 0000000..d5da2a7 --- /dev/null +++ b/content/en/chap1/_index.md @@ -0,0 +1,19 @@ ++++ +title = "Introduction" ++++ + +# Introduction + + To thy happy children of the future, those of the past send greetings. - Alma Mater + +At the University of Illinois at Urbana-Champaign, We fundamentally believe that we have a right to make the university better for all future students. It is a message etched into our Alma Mater and makes up the DNA of our course staff. As such, we created the coursebook. The coursebook is a free and open systems programming textbook that anyone can read, contribute to, and modify for now and forever. We don’t think information should be behind a walled garden, and we truly believe that complex concepts can be explained simply and fully, for anyone to understand. The goal of this book is to teach you the basics and give you some intuition into the complexities of systems programming. + +Like any good book, it isn’t complete. We still have plenty of examples, ideas, typos, and chapters to work on. If you find any issues, please file an https://github.com/illinois-cs241/coursebook/issues or email a list of typos to http://cs241.cs.illinois.edu/staff, and we’ll be happy to work on it. We are constantly trying to make the book better for students a year and ten years from now. + +This work is based on the original coursebook located at https://github.com/angrave/SystemProgramming/wiki. All these peoples’ hard work is included in the section below. + +Oh and the duck? Keep reading until synchronization :). + +Thanks again and happy reading! + +– Bhuvy diff --git a/content/en/chap2/Debugging_Environments.md b/content/en/chap2/Debugging_Environments.md new file mode 100644 index 0000000..90313ea --- /dev/null +++ b/content/en/chap2/Debugging_Environments.md @@ -0,0 +1,181 @@ ++++ +title = "Debugging and Environments" ++++ + +# Debugging and Environments + +I’m going to tell you a secret about this course: it is about working smarter not harder. The course can be time-consuming but the reason that so many people see it as such (and why so many students don’t see it as such) is the relative familiarity of people with their tools. Let’s go through some of the common tools that you’ll be working on and need to be familiar with. + +## ssh + +ssh is short for the Secure Shell (“Ssh(1),” #ref-openbsd_ssh). It is a network protocol that allows you to spawn a shell on a remote machine. Most of the times in this class you will need to ssh into your VM like this + +```shell +$ ssh netid@sem-cs241-VM.cs.illinois.edu +``` + +If you don’t want to type your password out every time, you can generate an ssh key that uniquely identifies your machine. If you already have a key pair, you can skip to the copy id stage. + +```shell +> ssh-keygen -t rsa -b 4096 +# Do whatever keygen tells you +# Don't feel like you need a passcode if your login password is secure +> ssh-copy-id netid@sem-cs241-VM.cs.illinois.edu +# Enter your password for maybe the final time +> ssh netid@sem-cs241-VM.cs.illinois.edu +``` + +If you still think that that is too much typing, you can always alias hosts. You may need to restart your VM or reload sshd for this to take effect. The config file is available on Linux and Mac distros. For Windows, you’ll have to use the Windows Linux Subsystem or configure any aliases in PuTTY + +```shell +> cat ~/.ssh/config +Host vm + User netid + HostName sem-cs241-VM.cs.illinois.edu +> ssh vm +``` + +## git + +What is ‘git‘? Git is a version control system. What that means is git stores the entire history of a directory. We refer to the directory as a repository. So what do you need to know is a few things. First, create your repository with the repo creator. If you haven’t already signed into enterprise GitHub, make sure to do so otherwise your repository won’t be created for you. After that, that means your repository is created on the server. Git is a decentralized version control system, meaning that you’ll need to get a repository onto your VM. We can do this with a clone. Whatever you do, do not go through the README.md tutorial. + +```shell +$ git clone https://github-dev.cs.illinois.edu/cs241-fa18/.git +``` + +This will create a local repository. The workflow is you make a change on your local repository, add the changes to a current commit, actually commit, and push the changes to the server. + +```shell +$ # edit the file, maybe using vim +$ git add +$ git commit -m "Committing my file" +$ git push origin master +``` + +Now to explain git well, you need to understand that git for our purposes will look like a linked list. You will always be at the head of master, and you will do the edit-add-commit-push loop. We have a separate branch on Github that we push feedback to under a specific branch which you can view on Github website. The markdown file will have information on the test cases and results (like standard out). + +Every so often git can break. Here is a list of commands you probably won’t need to fix your repo + +1. git-cherry-pick +2. git-pack +3. git-gc +4. git-clean +5. git-rebase +6. git-stash/git-apply/git-pop +7. git-branch + +If you are currently on a branch, and you don’t see either + +```shell +$ git status +On branch master +Your branch is up-to-date with 'origin/master'. +nothing to commit, working directory clean +``` + +or + +```shell +$ git status +On branch master +Your branch is up-to-date with 'origin/master'. +Changes not staged for commit: + (use "git add ..." to update what will be committed) + (use "git checkout -- ..." to discard changes in working directory) + + modified: + ... + +no changes added to commit (use "git add" and/or "git commit -a") +``` + +And something like + +```shell +$ git status +HEAD detached at 4bc4426 +nothing to commit, working directory clean +``` + +Don’t panic, but your repository may be in an unworkable state. If you aren’t nearing a deadline, come to office hours or ask your question on Piazza, and we’d be happy to help. In an emergency scenario, delete your repository and re-clone (you’ll have to add the release as above). **This will lose any local uncommitted changes. Make sure to copy any files you were working on outside the directory, remove and copy them back in** + +If you want to learn more about git, there are all but an endless number of tutorials and resources online that can help you. Here are some links that can help you out + +1. https://git-scm.com/docs/gittutorial + +2. https://www.atlassian.com/git/tutorials/what-is-version-control + +3. https://thenewstack.io/tutorial-git-for-absolutely-everyone/ + +## Editors + +Some people take this as an opportunity to learn a new editor, others not so much. The first part is those of you who want to learn a new editor. In the editor war that spans decades, we have come to the battle of vim vs emacs. + +Vim is a text editor and a Unix-like utility. You enter vim by typing vim [file], which takes you into the editor. There are three most commonly used modes: normal mode, insert mode, and command mode. You start off in normal mode. In this mode, you can move around with many keys with the most common ones being hjkl (corresponding to left, down, up, and right respectively). To run commands in vim, you can first type : and then a command after it. For instance, to quit vim, simply type :q (q stands for quit). If you have any unsaved edits, you must either save them :w, save and quit :wq, or quit and discard changes :q!. To make edits you can either type i to change you into insert mode or a to change to insert mode after the cursor. This is the basics when it comes to vim. In addition to the countless great resources out there on the internet, vim also has its own built-in tutorials set up for beginners. To access the interactive tutorial, enter vimtutor in the command line (not inside of vim), and you are all set! + +Emacs is more of a way of life, and I don’t mean that figuratively. A lot of people say that emacs is a powerful operating system lacking a decent text editor. This means emacs can house a terminal, gdb session, ssh session, code and a whole lot more. It would not be fitting any other way to introduce you to the gnu-emacs any other way than the gnu-docs https://www.gnu.org/software/emacs/tour/. Just note that emacs is insanely powerful. You can do almost anything with it. There are a fair number of students who like the IDE-aspect of other programming languages. Know that you can set up emacs to be an IDE, but you have to learn a bit of Lisp http://martinsosic.com/development/emacs/2017/12/09/emacs-cpp-ide.html. + +Then there are those of you who like to use your own editors. That is completely fine. For this, we require sshfs which has ports on many different machines. + +1. Windows https://github.com/billziss-gh/sshfs-win + +2. Mac https://github.com/osxfuse/osxfuse/wiki/SSHFS + +3. Linux https://help.ubuntu.com/community/SSHFS + +At that point, the files on your VM are synced with the files on your machine and edits can be made and will be synced. + +At the time of writing, an author likes to use spacemacs http://spacemacs.org/ which marries both vim and emacs and both of their difficulties. I’ll give my soapbox for why I like it, but be warned that if you are starting from absolutely no vim or emacs experience the learning curve along with this course may be too much. + +1. Extensible. Spacemacs has a clean design written in lisp. There are 100s of packages ready to be installed by editing your spacemacs config and reloading that do everything from syntax checking, automatic static analyzing, etc. + +2. Most of the good parts from vim and emacs. Emacs is good at doing everything by being a fast editor. Vim is good at making fast edits and moving around. Spacemacs is the best of both worlds allowing vim keybindings to all the emacs goodness underneath. + +3. Lots of preconfiguration done. As opposed with a fresh emacs install, a lot of the configurations with language and projects are done for you like neotree, helm, various language layers. All that you have to do is navigate neotree to the base of your project and emacs will turn into an IDE for that programming language. + +But obviously to each his or her own. Many people will argue that editor gurus spend more time editing their editors and actually editing. + +## Clean Code + +Make your code modular using helper functions. If there is a repeated task (getting the pointers to contiguous blocks in the malloc MP, for example), make them helper functions. And make sure each function does one thing well so that you don’t have to debug twice. Let’s say that we are doing selection sort by finding the minimum element each iteration like so, + +```c +void selection_sort(int *a, long len){ + for(long i = len-1; i > 0; --i){ + long max_index = i; + for(long j = len-1; j >= 0; --j){ + if(a[max_index] < a[j]){ + max_index = j; + } + } + int temp = a[i]; + a[i] = a[max_index]; + a[max_index] = temp; + } + +} +``` + +Many can see the bug in the code, but it can help to refactor the above method into + +```c +long max_index(int *a, long start, long end); +void swap(int *a, long idx1, long idx2); +void selection_sort(int *a, long len); +``` + +And the error is specifically in one function. In the end, this class is about writing system programs, not a class about refactoring/debugging your code. In fact, most kernel code is so atrocious that you don’t want to read it – the defense there is that it needs to be. But for the sake of debugging, it may benefit you in the long run to adopt some of these practices. + +## Asserts + +Use assertions to make sure your code works up to a certain point – and importantly, to make sure you don’t break it later. For example, if your data structure is a doubly-linked list, you can do something like assert(node == node->next->prev) to assert that the next node has a pointer to the current node. You can also check the pointer is pointing to an expected range of memory address, non-null, ->size is reasonable, etc. The DEBUG macro will disable all assertions, so don’t forget to set that once you finish debugging (“Assert,”[^2]). + +Here is a quick example with an assert. Let’s say that we are writing code using memcpy. We would want to put an assert before that checks whether my two memory regions overlap. If they do overlap, memcpy runs into undefined behavior, so we want to catch that problem than later. + +assert(!(src < dest+n && dest < src+n)); //Checks overlap +memcpy(dest, src, n); + +This check can be turned off at compile-time, but will save you tons of trouble debugging! + +[^2]: “Assert.” n.d. Cplusplus.com. cplusplus.com. http://www.cplusplus.com/reference/cassert/assert/. + diff --git a/content/en/chap2/GDB.md b/content/en/chap2/GDB.md new file mode 100644 index 0000000..7e214c6 --- /dev/null +++ b/content/en/chap2/GDB.md @@ -0,0 +1,323 @@ ++++ +title = "GDB" ++++ + +# GDB + +GDB is short for the GNU Debugger. GDB is a program that helps you track down errors by interactively debugging them (“GDB: The Gnu Project Debugger”[^1]). It can start and stop your program, look around, and put in ad hoc constraints and checks. Here are a few examples. + +## Setting breakpoints programmatically + +A breakpoint is a line of code where you want the execution to stop and give control back to the debugger. A useful trick when debugging complex C programs with GDB is setting breakpoints in the source code. + +```c +int main() { + int val = 1; + val = 42; + asm("int $3"); // set a breakpoint here + val = 7; +} +``` +```shell +$ gcc main.c -g -o main +$ gdb --args ./main +(gdb) r +[...] +Program received signal SIGTRAP, Trace/breakpoint trap. +main () at main.c:6 +6 val = 7; +(gdb) p val +$1 = 42 +``` + +You can also set breakpoints programmatically. Assume that we have no optimization and the line numbers are as follows + +```c +int main() { + int val = 1; + val = 42; + val = 7; +} +``` + +We can now set the breakpoint before the program starts. + +```shell +$ gcc main.c -g -o main +$ gdb --args ./main +(gdb) break main.c:4 +[...] +(gdb) p val +$1 = 42 +``` + +## Checking memory content + +We can also use gdb to check the content of different pieces of memory. For example, + +```c +int main() { + char bad_string[3] = {'C', 'a', 't'}; + printf("%s", bad_string); +} +``` + +Compiled we get + +``` +$ gcc main.c -g -o main && ./main +$ Cat ZVQ� $ +``` + +We can now use gdb to look at specific bytes of the string and reason about when the program should’ve stopped running + +```shell +(gdb) l +1 #include +2 int main() { +3 char bad_string[3] = {'C', 'a', 't'}; +4 printf("%s", bad_string); +5 } +(gdb) b 4 +Breakpoint 1 at 0x100000f57: file main.c, line 4. +(gdb) r +[...] +Breakpoint 1, main () at main.c:4 +4 printf("%s", bad_string); +(gdb) x/16xb bad_string +0x7fff5fbff9cd: 0x63 0x61 0x74 0xe0 0xf9 0xbf 0x5f 0xff +0x7fff5fbff9d5: 0x7f 0x00 0x00 0xfd 0xb5 0x23 0x89 0xff +(gdb) +``` + +Here, by using the x command with parameters `16xb`, we can see that starting at memory address `0x7fff5fbff9c`` (value of `bad_string`), `printf` would actually see the following sequence of bytes as a string because we provided a malformed string without a null terminator. + +## Involved gdb example + +Here is how one of your TAs would go through and debug a simple program that is going wrong. First, the source code of the program. If you can see the error immediately, please bear with us. + +```c +#include + +double convert_to_radians(int deg); + +int main(){ + for (int deg = 0; deg > 360; ++deg){ + double radians = convert_to_radians(deg); + printf("%d. %f\n", deg, radians); + } + return 0; +} + +double convert_to_radians(int deg){ + return ( 31415 / 1000 ) * deg / 180; +} +``` + +How can we use gdb to debug? First we ought to load GDB. + +```shell +$ gdb --args ./main +(gdb) layout src; # If you want a GUI type +(gdb) run +(gdb) +``` + +Want to take a look at the source? + +```shell +(gdb) l +1 #include +2 +3 double convert_to_radians(int deg); +4 +5 int main(){ +6 for (int deg = 0; deg > 360; ++deg){ +7 double radians = convert_to_radians(deg); +8 printf("%d. %f\n", deg, radians); +9 } +10 return 0; +(gdb) break 7 # break :line or break :function +(gdb) run +(gdb) +``` + +From running the code, the breakpoint didn’t even trigger, meaning the code never got to that point. That’s because of the comparison! Okay, flip the sign it should work now right? + +```shell +(gdb) run +350. 60.000000 +351. 60.000000 +352. 60.000000 +353. 60.000000 +354. 60.000000 +355. 61.000000 +356. 61.000000 +357. 61.000000 +358. 61.000000 +359. 61.000000 + +(gdb) break 14 if deg == 359 # Let's check the last iteration only +(gdb) run +... +(gdb) print/x deg # print the hex value of degree +$1 = 0x167 +(gdb) print (31415/1000) +$2 = 0x31 +(gdb) print (31415/1000.0) +$3 = 201.749 +(gdb) print (31415.0/10000.0) +$4 = 3.1414999999999999 +``` + +That was only the bare minimum, though most of you will get by with that. There are a whole load more resources on the web, here are a few specific ones that can help you get started. + +1. http://www.cs.cmu.edu/~gilpin/tutorial/ + +2. http://www.delorie.com/gnu/docs/gdb/gdb_56.html + +3. https://www.youtube.com/watch?v=PorfLSr3DDI + +## Shell + +What do you actually use to run your program? A shell! A shell is a programming language that is running inside your terminal. A terminal is merely a window to input commands. Now, on POSIX we usually have one shell called `sh` that is linked to a POSIX compliant shell called `dash`. Most of the time, you use a shell called `bash` that is somewhat POSIX compliant but has some nifty built-in features. If you want to be even more advanced, zsh has some more powerful features like tab complete on programs and fuzzy patterns. + +## Undefined Behavior Sanitizer + +The undefined behavior sanitizer is a wonderful tool provided by the llvm project. It allows you to compile code with a runtime checker to make sure that you don’t do undefined behavior for various categories. We will try to include it into our projects, but requires support form all the external libraries that we use so we may not get around to all of them. https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html + +**Undefined behavior - why we can’t solve it in general** + +Also please please read Chris Lattner’s 3 Part blog post on undefined behavior. It can shed light on debug builds and the mystery of compiler optimization. + +http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html + +## Clang Static Build Tools + +Clang provides a great drop-in replacement tools for compiling programs. If you want to see if there is an error that may cause a race condition, casting error, etc, all you need to do is the following. + +```shell +$ scan-build make +``` + +And in addition to the make output, you will get static build warnings. + +## strace and ltrace + +`strace` and `ltrace` are two programs that trace the system calls and library calls respectively of a running program or command. These may be missing on your system so to install feel free to run the following. + +```shell +$ sudo apt install strace ltrace +``` + +Debugging with `ltrace` can be as simple as figuring out what was the return call of the last library call that failed. + +```shell +int main() { + FILE *fp = fopen("I don't exist", "r"); + fprintf(fp, "a"); + fclose(fp); + return 0; +} +``` + +```shell +> ltrace ./a.out + __libc_start_main(0x8048454, 1, 0xbfc19db4, 0x80484c0, 0x8048530 + fopen("I don't exist", "r") = 0x0 + fwrite("Invalid Write\n", 1, 14, 0x0 + --- SIGSEGV (Segmentation fault) --- + +++ killed by SIGSEGV +++ +``` + +`ltrace` output can clue you in to weird things your program is doing live. Unfortunately, `ltrace` can’t be used to inject faults, meaning that ltrace can tell you what is happening, but it can’t tamper with what is already happening. + +`strace` on the other hand could modify your program. Debugging with `strace` is amazing. The basic usage is running `strace` with a program, and it’ll get you a complete list of system call parameters. + +```shell +$ strace head README.md +execve("/usr/bin/head", ["head", "README.md"], 0x7ffff28c8fa8 /* 60 vars */) = 0 +brk(NULL) = 0x7ffff5719000 +access("/etc/ld.so.nohwcap", F_OK) = -1 ENOENT (No such file or directory) +access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) +openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 +fstat(3, {st_mode=S_IFREG|0644, st_size=32804, ...}) = 0 +... +``` + +If the output is too verbose, you can use `trace=` with a command delimited list of syscalls to filter all but those calls. + +```shell +$ strace -e trace=read,write head README.md +read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\260\34\2\0\0\0\0\0"..., 832) = 832 +read(3, "# Locale name alias data base.\n#"..., 4096) = 2995 +read(3, "", 4096) = 0 +read(3, "# C Datastructures\n\n[![Build Sta"..., 8192) = 1250 +write(1, "# C Datastructures\n", 19# C Datastructures +``` + +You can also trace files or targets. + +```shell +$ strace -e trace=read,write -P README.md head README.md +strace: Requested path 'README.md' resolved into '/mnt/c/Users/user/personal/libds/README.md' +read(3, "# C Datastructures\n\n[![Build Sta"..., 8192) = 1250 +``` + +Newer versions of `strace` can actually inject faults into your program. This is useful when you want to occasionally make reads and writes fail for example in a networking application, which your program should handle. The problem is as of early 2019, that version is missing from Ubuntu repositories. Meaning that you’ll have to install it from the source. + +## printfs + +When all else fails, print! Each of your functions should have an idea of what it is going to do. You want to test that each of your functions is doing what it set out to do and see exactly where your code breaks. In the case with race conditions, tsan may be able to help, but having each thread print out data at certain times could help you identify the race condition. + +To make printfs useful, try to have a macro that fills in the context by which the printf was called – a log statement if you will. A simple useful but untested log statement could be as follows. Try to make a test and figure out something that is going wrong, then log the state of your variables. + +```c +#include +#include +#include +#include +#include + +// bt is print backtrace +const int num_stack = 10; +int __log(int line, const char *file, int bt, const char *fmt, ...) { + if (bt) { + void *raw_trace[num_stack]; + size_t size = backtrace(raw_trace, sizeof(raw_trace) / sizeof(raw_trace[0])); + char **syms = backtrace_symbols(raw_trace, size); + + for(ssize_t i = 0; i < size; i++) { + fprintf(stderr, "|%s:%d| %s\n", file, line, syms[i]); + } + free(syms); + } + int ret = fprintf(stderr, "|%s:%d| ", file, line); + va_list args; + va_start(args, fmt); + ret += vfprintf(stderr, fmt, args); + va_end(args); + ret += fprintf(stderr, "\n"); + return ret; +} + +#ifdef DEBUG +#define log(...) __log(__LINE__, __FILE__, 0, __VA_ARGS__) +#define bt(...) __log(__LINE__, __FILE__, 1, __VA_ARGS__) +#else +#define log(...) +#define bt(...) +#endif + +//Use as log(args like printf) or bt(args like printf) to either log or get backtrace + +int main() { + log("Hello Log"); + bt("Hello Backtrace"); +} +``` + +And then use as appropriately. Check out the compiling and linking section in the appendix if you have any questions on how a C program gets translated to machine code. + + +[^1]: “GDB: The Gnu Project Debugger.” 2019. *GDB: The GNU Project Debugger*. Free Software Foundation. https://www.gnu.org/software/gdb/. diff --git a/content/en/chap2/Homework0.md b/content/en/chap2/Homework0.md new file mode 100644 index 0000000..07ab9ea --- /dev/null +++ b/content/en/chap2/Homework0.md @@ -0,0 +1,219 @@ ++++ +title = "Homework 0" ++++ + +# Homework 0 + +```c +// First, can you guess which lyrics have been transformed into this C-like system code? +char q[] = "Do you wanna build a C99 program?"; +#define or "go debugging with gdb?" +static unsigned int i = sizeof(or) != strlen(or); +char* ptr = "lathe"; +size_t come = fprintf(stdout,"%s door", ptr+2); +int away = ! (int) * ""; + +int* shared = mmap(NULL, sizeof(int*), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0); +munmap(shared,sizeof(int*)); + +if(!fork()) { + execlp("man","man","-3","ftell", (char*)0); perror("failed"); +} + +if(!fork()) { + execlp("make","make", "snowman", (char*)0); execlp("make","make", (char*)0)); +} + +exit(0); +``` + +So you want to master System Programming? And get a better grade than B? + +```c +int main(int argc, char** argv) { + puts("Great! We have plenty of useful resources for you, but it's up to you to"); + puts(" be an active learner and learn how to solve problems and debug code."); + puts("Bring your near-completed answers the problems below"); + puts(" to the first lab to show that you've been working on this."); + printf("A few \"don't knows\" or \"unsure\" is fine for lab 1.\n"); + puts("Warning: you and your peers will work hard in this class."); + puts("This is not CS225; you will be pushed much harder to"); + puts(" work things out on your own."); + fprintf(stdout,"This homework is a stepping stone to all future assignments.\n"); + char p[] = "So, you will want to clear up any confusions or misconceptions.\n"; + write(1, p, strlen(p) ); + char buffer[1024]; + sprintf(buffer,"For grading purposes, this homework 0 will be graded as part of your lab %d work.\n", 1); + write(1, buffer, strlen(buffer)); + printf("Press Return to continue\n"); + read(0, buffer, sizeof(buffer)); + return 0; +} +``` + +Watch the videos and write up your answers to the following questions + +Important! + +The virtual machine-in-your-browser and the videos you need for HW0 are here: + +http://cs-education.github.io/sys/ + +Questions? Comments? Use the current semester’s CS241 Piazza: https://piazza.com/ + +The in-browser virtual machine runs entirely in JavaScript and is fastest in Chrome. Note the VM and any code you write is reset when you reload the page, so copy your code to a separate document. The post-video challenges are not part of homework 0, but you learn the most by doing rather than passively watching. You have some fun with each end-of-video challenge. + +HW0 questions are below. Copy your answers into a text document because you’ll need to submit them later in the course. + +## Chapter 1 + +In which our intrepid hero battles standard out, standard error, file descriptors and writing to files + +1. Hello, World! (system call style) Write a program that uses write() to print out “Hi! My name is ”. + +2. Hello, Standard Error Stream! Write a function to print out a triangle of height n to standard error. Your function should have the signature void write_triangle(int n) and should use write(). The triangle should look like this, for n = 3: + + * + ** + *** + +3. Writing to files Take your program from “Hello, World!” modify it write to a file called hello_world.txt. Make sure to use correct flags and a correct mode for open() (man 2 open is your friend). + +4. Not everything is a system call Take your program from “Writing to files” and replace write() with printf(). Make sure to print to the file instead of standard out! + +5. What are some differences between write() and printf()? + +## Chapter 2 + +Sizing up C types and their limits, int and char arrays, and incrementing pointers + +1. How many bits are there in a byte? + +2. How many bytes are there in a char? + +3. How many bytes the following are on your machine? int, double, float, long, and long long + +4. On a machine with 8 byte integers, the declaration for the variable data is int data[8]. If the address of data is 0x7fbd9d40, then what is the address of data+2? + +5. What is data[3] equivalent to in C? Hint: what does C convert data[3] to before dereferencing the address? Remember, the type of a string constant "abc" is an array. + +6. Why does this SEGFAULT? + ```c + char *ptr = "hello"; + *ptr = 'J'; + ``` + +7. What is the value of the variable str_size? + ```c + ssize_t str_size = sizeof("Hello\0World") + ``` + +8. What is the value of the variable str_len + ```c + ssize_t str_len = strlen("Hello\0World") + ``` + +9. Give an example of X such that sizeof(X) is 3. + +10. Give an example of Y such that sizeof(Y) might be 4 or 8 depending on the machine. + +## Chapter 3 + +Program arguments, environment variables, and working with character arrays (strings) + +1. What are at least two ways to find the length of argv? + +2. What does argv[0] represent? + +3. Where are the pointers to environment variables stored (on the stack, the heap, somewhere else)? + +4. On a machine where pointers are 8 bytes, and with the following code: + ```c + char *ptr = "Hello"; + char array[] = "Hello"; + ``` + + What are the values of sizeof(ptr) and sizeof(array)? Why? + +5. What data structure manages the lifetime of automatic variables? + +## Chapter 4 + +Heap and stack memory, and working with structs + +1. If I want to use data after the lifetime of the function it was created in ends, where should I put it? How do I put it there? + +2. What are the differences between heap and stack memory? + +3. Are there other kinds of memory in a process? + +4. Fill in the blank: “In a good C program, for every malloc, there is a ___”. + +5. What is one reason malloc can fail? + +6. What are some differences between time() and ctime()? + +7. What is wrong with this code snippet? + ```c + free(ptr); + free(ptr); + ``` +8. What is wrong with this code snippet? + ```c + free(ptr); + printf("%s\n", ptr); + ``` + +9. How can one avoid the previous two mistakes? + +10. Create a struct that represents a Person. Then make a typedef, so that struct Person can be replaced with a single word. A person should contain the following information: their name (a string), their age (an integer), and a list of their friends (stored as a pointer to an array of pointers to Persons). + +11. Now, make two persons on the heap, “Agent Smith” and “Sonny Moore”, who are 128 and 256 years old respectively and are friends with each other. Create functions to create and destroy a Person (Person’s and their names should live on the heap). + +12. create() should take a name and age. The name should be copied onto the heap. Use malloc to reserve sufficient memory for everyone having up to ten friends. Be sure initialize all fields (why?). + +13. destroy() should free up both the memory of the person struct and all of its attributes that are stored on the heap. Destroying one person keeps other people in tact any other. + +## Chapter 5 + +Text input and output and parsing using `getchar`, `gets`, and `getline`. + +1. What functions can be used for getting characters from stdin and writing them to stdout? + +3. Name one issue with gets(). + +4. Write code that parses the string “Hello 5 World” and initializes 3 variables to “Hello”, 5, and “World”. + +5. What does one need to define before including getline()? + +6. Write a C program to print out the content of a file line-by-line using getline(). + +## C Development + +These are general tips for compiling and developing using a compiler and git. Some web searches will be useful here + +1. What compiler flag is used to generate a debug build? + +2. You fix a problem in the Makefile and type make again. Explain why this may be insufficient to generate a new build. + +3. Are tabs or spaces used to indent the commands after the rule in a Makefile? + +4. What does git commit do? What’s a sha in the context of git? + +5. What does git log show you? + +6. What does git status tell you and how would the contents of .gitignore change its output? + +7. What does git push do? Why is it insufficient to commit with ` git commit -m ’fixed all bugs’ `? + +8. What does a non-fast-forward error git push reject mean? What is the most common way of dealing with this? + +## Optional: Just for fun + +- Convert a song lyrics into System Programming and C code covered in this wiki book and share on Piazza. + +- Find, in your opinion, the best and worst C code on the web and post the link to Piazza. + +- Write a short C program with a deliberate subtle C bug and post it on Piazza to see if others can spot your bug. + +- Do you have any cool/disastrous system programming bugs you’ve heard about? Feel free to share with your peers and the course staff on Piazza. diff --git a/content/en/chap2/Systems_Architecture.md b/content/en/chap2/Systems_Architecture.md new file mode 100644 index 0000000..01862bb --- /dev/null +++ b/content/en/chap2/Systems_Architecture.md @@ -0,0 +1,50 @@ ++++ +title = "Systems Architecture" ++++ + +# Systems Architecture + +This section is a short review of System Architecture topics that you’ll need for System Programming. + + +## Assembly + +What is assembly? Assembly is the lowest that you’ll get to machine language without writing 1’s and 0’s. Each computer has an architecture, and that architecture has an associated assembly language. Each assembly command has a 1:1 mapping to a set of 1’s and 0’s that tell the computer exactly what to do. For example, the following in the widely used x86 Assembly language add one to the memory address 20 (Wikibooks #ref-wiki:xxx) – you can also look in (Guide #ref-guide2011intel) Section 2A under the add instruction though it is more verbose. + +```shell +add BYTE PTR [0x20], 1 +``` + +Why do we mention this? Because it is important that although you are going to be doing most of this class in C, that this is what the code is translated into. Serious implications arise for race conditions and atomic operations. +Atomic Operations + +An operation is atomic if no other processor should interrupt it. Take for example the above assembly code to add one to a register. In the architecture, it may actually have a few different steps on the circuit. The operation may start by fetching the value of the memory from the stick of ram, then storing it in the cache or a register, and then finally writing back (Schweizer, Besta, and Hoefler #ref-schweizer2015evaluating) – under the description for fetch-and-add though your micro-architecture may vary. Or depending on performance operations, it may keep that value in cache or in a register which is local to that process – try dumping the -O2 optimized assembly of incrementing a variable. The problem comes in if two processors try to do it at the same time. The two processors could at the same time copy the value of the memory address, add one, and store the same result back, resulting in the value only being incremented once. That is why we have a special set of instructions on modern systems called atomic operations. If an instruction is atomic, it makes sure that only one processor or thread performs any intermediate step at a time. With x86 this is done by the lock prefix (Guide #ref-guide2011intel, 1120). + +```shell +lock add BYTE PTR [0x20], 1 +``` + +Why don’t we do this for everything? It makes commands slower! If every time a computer does something it has to make sure that the other cores or processors aren’t doing anything, it’ll be much slower. Most of the time we differentiate these with special consideration. Meaning, we will tell you when we use something like this. Most of the time you can assume the instructions are unlocked. +Caching + +Ah yes, Caching. One of computer science’s greatest problems. Caching that we are referring is processor caching. If a particular address is already in the cache when reading or writing, the processor will perform the operation on the cache such as adding and update the actual memory later because updating memory is slow (Intel #ref-intel2015improving Section 3.4). If it isn’t, the processor requests a chunk of memory from the memory chip and stores it in the cache, kicking out the least recently used page – this depends on caching policy, but Intel’s does use this. This is done because the l3 processor cache is roughly three times faster to reach than the memory in terms of time (Levinthal #ref-levinthal2009performance, 22) though exact speeds will vary based on the clock speed and architecture. Naturally, this leads to problems because there are two different copies of the same value, in the cited paper this refers to an unshared line. This isn’t a class about caching, know how this could impact your code. A short but non-complete list could be + +1. Race Conditions! If a value is stored in two different processor caches, then that value should be accessed by a single thread. + +2. Speed. With a cache, your program may look faster mysteriously. Just assume that reads and writes that either happened recently or are next to each other in memory are fast. + +3. Side effects. Every read or write effects the cache state. While most of the time this doesn’t help or hurt, it is important to know. Check the Intel programmer guide on the lock prefix for more information. + +## Interrupts + +Interrupts are a important part of system programming. An interrupt is internally an electrical signal that is delivered to the processor when something happens – this is a hardware interrupt (“Chapter 3. Hardware Interrupts,” #ref-redhat_hardware_int). Then the hardware decides if this is something that it should handle (i.e. handling keyboard or mouse input for older keyboard and mouses) or it should pass to the operating system. The operating system then decides if this is something that it should handle (i.e. paging a memory table from disk) or something the application should handle (i.e. a SEGFAULT). If the operating system decides that this is something that the process or program should take care of, it sends a software fault and that software fault is then propagated. The application then decides if it is an error (SEGFAULT) or not (SIGPIPE for example) and reports to the user. Applications can also send signals to the kernel and to the hardware as well. This is an oversimplification because there are certain hardware faults that can’t be ignored or masked away, but this class isn’t about teaching you to build an operating system. + +An important application of this is this is how system calls are served! There is a well-established set of registers that the arguments go in according to the kernel as well as a system call “number” again defined by the kernel. Then the operating system triggers an interrupt which the kernel catches and serves the system call (Garg #ref-garg_2006). + +Operating system developers and instruction set developers alike didn’t like the overhead of causing an interrupt on a system call. Now, systems use SYSENTER and SYSEXIT which has a cleaner way of transferring control safely to the kernel and safely back. What safely means is obvious out of the scope for this class, but it persists. + +## Optional: Hyperthreading + +Hyperthreading is a new technology and is in no way shape or form multithreading. Hyperthreading allows one physical core to appear as many virtual cores to the operating system (Guide #ref-guide2011intel, P.51). The operating system can then schedule processes on these virtual cores and one core will execute them. Each core interleaves processes or threads. While the core is waiting for one memory access to complete, it may perform a few instructions of another process thread. The overall result is more instructions executed in a shorter time. This potentially means that you can divide the number of cores you need to power smaller devices. + +There be dragons here though. With hyperthreading, you must be wary of optimizations. A famous hyperthreading bug that caused programs to crash if at least two processes were scheduled on a physical core, using specific registers, in a tight loop. The actual problem is better explained through an architecture lens. But, the actual application was found through systems programmers working on OCaml’s mainline (Leroy #ref-leroy_2017). \ No newline at end of file diff --git a/content/en/chap2/Valgrind.md b/content/en/chap2/Valgrind.md new file mode 100644 index 0000000..f69d533 --- /dev/null +++ b/content/en/chap2/Valgrind.md @@ -0,0 +1,70 @@ ++++ +title = "Valgrind" ++++ + +# Valgrind + +Valgrind is a suite of tools designed to provide debugging and profiling tools to make your programs more correct and detect some runtime issues (“4. Memcheck: A Memory Error Detector,” #ref-valgrind). The most used of these tools is Memcheck, which can detect many memory-related errors that are common in C and C++ programs and that can lead to crashes and unpredictable behavior (for example, unfreed memory buffers). To run Valgrind on your program: + +```shell +valgrind --leak-check=full --show-leak-kinds=all myprogram arg1 arg2 +``` + +Arguments are optional and the default tool that will run is Memcheck. The output will be presented in the form: the number of allocations, frees, and errors. Suppose we have a simple program like this: + +```c +#include + +void dummy_function() { + int* x = malloc(10 * sizeof(int)); + x[10] = 0; // error 1: Out of bounds write, as you can see here we write to an out of bound memory address. +} // error 2: Memory Leak, x is allocated at function exit. + +int main(void) { + dummy_function(); + return 0; +} +``` + +This program compiles and runs with no errors. Let’s see what Valgrind will output. + +```shell +==29515== Memcheck, a memory error detector +==29515== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al. +==29515== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info +==29515== Command: ./a +==29515== +==29515== Invalid write of size 4 +==29515== at 0x400544: dummy_function (in /home/rafi/projects/exocpp/a) +==29515== by 0x40055A: main (in /home/rafi/projects/exocpp/a) +==29515== Address 0x5203068 is 0 bytes after a block of size 40 alloc'd +==29515== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) +==29515== by 0x400537: dummy_function (in /home/rafi/projects/exocpp/a) +==29515== by 0x40055A: main (in /home/rafi/projects/exocpp/a) +==29515== +==29515== +==29515== HEAP SUMMARY: +==29515== in use at exit: 40 bytes in 1 blocks +==29515== total heap usage: 1 allocs, 0 frees, 40 bytes allocated +==29515== +==29515== LEAK SUMMARY: +==29515== definitely lost: 40 bytes in 1 blocks +==29515== indirectly lost: 0 bytes in 0 blocks +==29515== possibly lost: 0 bytes in 0 blocks +==29515== still reachable: 0 bytes in 0 blocks +==29515== suppressed: 0 bytes in 0 blocks +==29515== Rerun with --leak-check=full to see details of leaked memory +==29515== +==29515== For counts of detected and suppressed errors, rerun with: -v +==29515== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0) +``` + +**Invalid write:** It detected our heap block overrun, writing outside of an allocated block. + +**Definitely lost:** Memory leak — you probably forgot to free a memory block. + +Valgrind is a effective tool to check for errors at runtime. C is special when it comes to such behavior, so after compiling your program you can use Valgrind to fix errors that your compiler may miss and that usually happens when your program is running. + +For more information, you can refer to the manual[^1] + +[^1]:“4. Memcheck: A Memory Error Detector.” n.d. *Valgrind*. http://valgrind.org/docs/manual/mc-manual.html. \ No newline at end of file diff --git a/content/en/chap2/_index.md b/content/en/chap2/_index.md new file mode 100644 index 0000000..e6f7cd7 --- /dev/null +++ b/content/en/chap2/_index.md @@ -0,0 +1,7 @@ ++++ +title = "Background" ++++ + +# Background + + Sometimes the journey of a thousand steps begins by learning to walk \ No newline at end of file diff --git a/content/en/chap3/_index.md b/content/en/chap3/_index.md new file mode 100644 index 0000000..6aa1750 --- /dev/null +++ b/content/en/chap3/_index.md @@ -0,0 +1,15 @@ ++++ +title = "The C Programming Language" ++++ + +# The C Programming Language + + If you want to teach systems, don’t drum up the programmers, sort the issues, and make PRs. + Instead, teach them to yearn for the vast and endless C. - Antoine de Saint-Exupéry (With edits) + +Note: This chapter is long and goes into a lot of detail. Feel free to gloss over parts with which you have experience in. + +C is the de-facto programming language to do serious system serious programming. Why? Most kernels have their API accessible through C. The Linux kernel[^2] and the XNU kernel[^1] of which MacOS is based on are written in C and have C API - Application Programming Interface. The Windows Kernel uses C++, but doing system programming on that is much harder on windows that UNIX for novice system programmers. C doesn’t have abstractions like classes and Resource Acquisition Is Initialization (RAII) to clean up memory. C also gives you much more of an opportunity to shoot yourself in the foot, but it lets you do things at a much more fine-grained level. + +[^1]:Inc., Apple. 2017. “XNU Kernel.” *GitHub Repository*. https://github.com/apple/darwin-xnu; GitHub +[^2]:Love, Robert. 2010. Linux Kernel Development. 3rd ed. Addison-Wesley Professional. \ No newline at end of file diff --git a/content/en/chap4/_index.md b/content/en/chap4/_index.md new file mode 100644 index 0000000..414007b --- /dev/null +++ b/content/en/chap4/_index.md @@ -0,0 +1,47 @@ ++++ +title = "Processes" ++++ + +# Processes + + Who needs process isolation? - Intel Marketing on Meltdown and Spectre + +To understand what a process is, you need to understand what an operating system is. An operating system is a program that provides an interface between hardware and user software as well as providing a set of tools that the software can use. The operating system manages hardware and gives user programs a uniform way of interacting with hardware as long as the operating system can be installed on that hardware. Although this idea sounds like it is the end-all, we know that there are many different operating systems with their own quirks and standards. As a solution to that, there is another layer of abstraction: POSIX or portable operating systems interface. This is a standard (or many standards now) that an operating system must implement to be POSIX compatible – most systems that we’ll be studying are almost POSIX compatible due more to political reasons. + +Before we talk about POSIX systems, we should understand what the idea of a kernel is generally. In an operating system (OS), there are two spaces: kernel space and user space. Kernel space is a power operating mode that allows the system to interact with the hardware and has the potential to destroy your machine. User space is where most applications run because they don’t need this level of power for every operation. When a user space program needs additional power, it interacts with the hardware through a system call that is conducted by the kernel. This adds a layer of security so that normal user programs can’t destroy your entire operating system. For the purposes of our class, we’ll talk about single machine multiple user operating systems. This is where there is a central clock on a standard laptop or desktop. Other OSes relax the central clock requirement (distributed) or the “standardness” of the hardware (embedded systems). Other invariants make sure events happen at particular times too. + +The operating system is made up of many different pieces. There may be a program running to handle incoming USB connections, another one to stay connected to the network, etc. The most important one is the kernel – although it might be a set of processes – which is the heart of the operating system. The kernel has many important tasks. The first of which is booting. + +1. The computer hardware executes code from read-only memory, called firmware. + +2. The firmware executes a bootloader, which often conforms to the Extensible Firmware Interface (EFI), which is an interface between the system firmware and the operating system. + +3. The bootloader’s boot manager loads the operating system kernels, based on the boot settings. + +4. Your kernel executes `init` to https://en.wikipedia.org/wiki/Bootstrapping itself from nothing. + +5. The kernel executes startup scripts like starting networking and USB handling. + +6. The kernel executes userland scripts like starting a desktop, and you get to use your computer! + +When a program is executing in user space, the kernel provides some important services to programs in User space. + +- Scheduling processes and threads + +- Handling synchronization primitives (futexes, mutexes, semaphores, etc.) + +- Providing system calls such as `write` or `read` + +- Managing virtual memory and low-level binary devices such as USB drivers + +- Managing filesystems + +- Handling communication over networks + +- Handling communication between processes + +- Dynamically linking libraries + +- The list goes on and on. + +The kernel creates the first process `init.d` (an alternative is system.d). init.d boots up programs such as graphical user interfaces, terminals, etc – by default, this is the only process explicitly created by the system. All other processes are instantiated by using the system calls `fork` and `exec` from that single process. \ No newline at end of file diff --git a/content/en/chap5/_index.md b/content/en/chap5/_index.md new file mode 100644 index 0000000..0e46eb0 --- /dev/null +++ b/content/en/chap5/_index.md @@ -0,0 +1,6 @@ ++++ +title = "Memory Allocators" ++++ + +# Memory Allocators + Memory memory everywhere but not an allocation to be made - A fragmented heap \ No newline at end of file diff --git a/content/en/chap6/_index.md b/content/en/chap6/_index.md new file mode 100644 index 0000000..599401c --- /dev/null +++ b/content/en/chap6/_index.md @@ -0,0 +1,9 @@ ++++ +title = "Threads" ++++ + +# Threads + + If you think your programs crashing before, wait until they crash ten times as fast + +A thread is short for ‘thread-of-execution’. It represents the sequence of instructions that the CPU has and will execute. To remember how to return from function calls, and to store the values of automatic variables and parameters a thread uses a stack. Almost weirdly, a thread is a process, meaning that creating a thread is similar to `fork`, except there is no copying meaning no copy on write. What this allows is for a process to share the same address space, variables, heap, file descriptors and etc. The actual system call to create a thread is similar to `fork`. It’s `clone`. We won’t go into the specifics, but you can read the http://man7.org/linux/man-pages/man2/clone.2.html keeping in mind that it is outside the direct scope of this course. LWP or Lightweight Processes or threads are preferred to forking for a lot of scenarios because there is a lot less overhead creating them. But in some cases, notably python uses this, multiprocessing is the way to make your code faster. \ No newline at end of file diff --git a/content/en/menu/index.md b/content/en/menu/index.md new file mode 100644 index 0000000..f6c92c4 --- /dev/null +++ b/content/en/menu/index.md @@ -0,0 +1,23 @@ +--- +headless: true +--- + +- **[1. Introduction]({{< relref "/chap1" >}})** + - [Authors]({{< relref "/chap1/Authors" >}}) + +- **[2. Background]({{< relref "/chap2" >}})** + - [Systems Architecture]({{< relref "/chap2/Systems_Architecture" >}}) + - [Debugging and Environments]({{< relref "/chap2/Debugging_Environments" >}}) + - [Valgrind]({{< relref "/chap2/Valgrind" >}}) + - [GDB]({{< relref "/chap2/GDB" >}}) + - [Homework 0]({{< relref "/chap2/Homework0" >}}) + +- **[3. The C Programming Language]({{< relref "/chap3" >}})** + + +- **[4. Processes]({{< relref "/chap4" >}})** + +- **[5. Memory Allocators]({{< relref "/chap5" >}})** + +- **[6. Threads]({{< relref "/chap6" >}})** + diff --git a/content/zh/_index.md b/content/zh/_index.md new file mode 100644 index 0000000..03a3125 --- /dev/null +++ b/content/zh/_index.md @@ -0,0 +1,17 @@ ++++ +title = "简介" ++++ + +# 伊利诺伊大学系统编程讲义中文版 + +{{< figure src="https://static.cyub.vip/images/202207/duck-alpha-cropped.png" width="500px" class="text-center" >}} + +伊利诺伊大学香槟分校 (UIUC) 的CS 241: System Programming课程的教学讲义的中文译本。 + +Happy Reading! 享受您的阅读时光! + +## 资料 + +- [CS 241: System Programming课程官网](http://cs241.cs.illinois.edu/) +- [CS 241: System Programming讲义在线地址](http://cs241.cs.illinois.edu/coursebook/index.html) +- [CS 241: System Programming讲义的Github link](https://github.com/illinois-cs241/coursebook/wiki) \ No newline at end of file diff --git a/content/zh/menu/index.md b/content/zh/menu/index.md new file mode 100644 index 0000000..e69de29 diff --git a/hugo.toml b/hugo.toml new file mode 100644 index 0000000..9a37a7e --- /dev/null +++ b/hugo.toml @@ -0,0 +1,118 @@ +baseURL = 'https://doc.cyub.vip/cs341' +languageCode = 'zh-CN' +title = 'System Programming' +theme = "hugo-book" + +# Book configuration +disablePathToLower = true +# enableGitInfo = true +defaultContentLanguage = 'en' +defaultContentLanguageInSubdir = true + + +# Needed for mermaid/katex shortcodes +[markup] +[markup.goldmark.renderer] +unsafe = true + +# [markup.highlight] +# linenos = false + +# [markup.tableOfContents] +# startLevel = 1 + + +[languages] +[languages.cn] +contentDir = 'content/zh' +disabled = false +languageCode = 'zh-CN' +languageDirection = 'ltr' +languageName = 'chinese' +title = '伊利诺伊大学计算系统编程讲义中文版' +weight = 2 +[languages.cn.params] +subtitle = '计算机系统编程' +[languages.en] +contentDir = 'content/en' +disabled = false +languageCode = 'en-US' +languageDirection = 'ltr' +languageName = 'English' +title = 'System Programming' +weight = 1 +[languages.en.params] +subtitle = 'System Programming' + +[params] +# (Optional, default light) Sets color theme: light, dark or auto. +# Theme 'auto' switches between dark and light modes based on browser/os preferences +BookTheme = 'light' + +# (Optional, default true) Controls table of contents visibility on right side of pages. +# Start and end levels can be controlled with markup.tableOfContents setting. +# You can also specify this parameter per page in front matter. +BookToC = false + +# (Optional, default favicon.png) Set the path to a favicon file. +# If the favicon is /static/favicon.png then the path would be favicon.png +# BookFavicon = 'favicon.png' + +# (Optional, default none) Set the path to a logo for the book. +# If the logo is /static/logo.png then the path would be logo.png +# BookLogo = 'logo.png' + +# (Optional, default none) Set leaf bundle to render as side menu +# When not specified file structure and weights will be used +BookMenuBundle = '/menu' + +# (Optional, default docs) Specify root page to render child pages as menu. +# Page is resoled by .GetPage function: https://gohugo.io/functions/getpage/ +# For backward compatibility you can set '*' to render all sections to menu. Acts same as '/' +BookSection = '*' + +# Set source repository location. +# Used for 'Last Modified' and 'Edit this page' links. +# BookRepo = 'https://github.com/alex-shpak/hugo-book' + +# (Optional, default 'commit') Specifies commit portion of the link to the page's last modified +# commit hash for 'doc' page type. +# Requires 'BookRepo' param. +# Value used to construct a URL consisting of BookRepo/BookCommitPath/ +# Github uses 'commit', Bitbucket uses 'commits' +# BookCommitPath = 'commit' + +# Enable "Edit this page" links for 'doc' page type. +# Disabled by default. Uncomment to enable. Requires 'BookRepo' param. +# Edit path must point to root directory of repo. +# BookEditPath = 'edit/main/exampleSite' + +# Configure the date format used on the pages +# - In git information +# - In blog posts +# BookDateFormat = 'January 2, 2006' + +# (Optional, default true) Enables search function with flexsearch, +# Index is built on fly, therefore it might slowdown your website. +# Configuration for indexing can be adjusted in i18n folder per language. +BookSearch = true + +# (Optional, default true) Enables comments template on pages +# By default partals/docs/comments.html includes Disqus template +# See https://gohugo.io/content-management/comments/#configure-disqus +# Can be overwritten by same param in page frontmatter +BookComments = true + +# /!\ This is an experimental feature, might be removed or changed at any time +# (Optional, experimental, default false) Enables portable links and link checks in markdown pages. +# Portable links meant to work with text editors and let you write markdown without {{< relref >}} shortcode +# Theme will print warning if page referenced in markdown does not exists. +BookPortableLinks = true + +# /!\ This is an experimental feature, might be removed or changed at any time +# (Optional, experimental, default false) Enables service worker that caches visited pages and resources for offline use. +BookServiceWorker = true + +# /!\ This is an experimental feature, might be removed or changed at any time +# (Optional, experimental, default false) Enables a drop-down menu for translations only if a translation is present. +BookTranslatedOnly = false diff --git a/resources/_gen/assets/scss/book.scss_e129fe35b8d0a70789c8a08429469073.content b/resources/_gen/assets/scss/book.scss_e129fe35b8d0a70789c8a08429469073.content new file mode 100644 index 0000000..4cee5b1 --- /dev/null +++ b/resources/_gen/assets/scss/book.scss_e129fe35b8d0a70789c8a08429469073.content @@ -0,0 +1 @@ +@charset "UTF-8";:root{--gray-100:#f8f9fa;--gray-200:#e9ecef;--gray-500:#adb5bd;--color-link:#0055bb;--color-visited-link:#8440f1;--body-background:white;--body-font-color:black;--icon-filter:none;--hint-color-info:#6bf;--hint-color-warning:#fd6;--hint-color-danger:#f66}/*!normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css*/html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button}button::-moz-focus-inner,[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner{border-style:none;padding:0}button:-moz-focusring,[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}.flex{display:flex}.flex-auto{flex:auto}.flex-even{flex:1 1}.flex-wrap{flex-wrap:wrap}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.align-center{align-items:center}.mx-auto{margin:0 auto}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.hidden{display:none}input.toggle{height:0;width:0;overflow:hidden;opacity:0;position:absolute}.clearfix::after{content:"";display:table;clear:both}html{font-size:16px;scroll-behavior:smooth;touch-action:manipulation}body{min-width:20rem;color:var(--body-font-color);background:var(--body-background);letter-spacing:.33px;font-weight:400;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;box-sizing:border-box}body *{box-sizing:inherit}h1,h2,h3,h4,h5{font-weight:400}a{text-decoration:none;color:var(--color-link)}img{vertical-align:baseline}:focus{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}aside nav ul{padding:0;margin:0;list-style:none}aside nav ul li{margin:1em 0;position:relative}aside nav ul a{display:block}aside nav ul a:hover{opacity:.5}aside nav ul ul{padding-inline-start:1rem}ul.pagination{display:flex;justify-content:center;list-style-type:none;padding-inline-start:0}ul.pagination .page-item a{padding:1rem}.container{max-width:80rem;margin:0 auto}.book-icon{filter:var(--icon-filter)}.book-brand{margin-top:0;margin-bottom:1rem}.book-brand img{height:1.5em;width:1.5em;margin-inline-end:.5rem}.book-menu{flex:0 0 16rem;font-size:.875rem}.book-menu .book-menu-content{width:16rem;padding:1rem;background:var(--body-background);position:fixed;top:0;bottom:0;overflow-x:hidden;overflow-y:auto}.book-menu a,.book-menu label{color:inherit;cursor:pointer;word-wrap:break-word}.book-menu a.active{color:var(--color-link)}.book-menu input.toggle+label+ul{display:none}.book-menu input.toggle:checked+label+ul{display:block}.book-menu input.toggle+label::after{content:"▸"}.book-menu input.toggle:checked+label::after{content:"▾"}body[dir=rtl] .book-menu input.toggle+label::after{content:"◂"}body[dir=rtl] .book-menu input.toggle:checked+label::after{content:"▾"}.book-section-flat{margin:2rem 0}.book-section-flat>a,.book-section-flat>span,.book-section-flat>label{font-weight:bolder}.book-section-flat>ul{padding-inline-start:0}.book-page{min-width:20rem;flex-grow:1;padding:1rem}.book-post{margin-bottom:3rem}.book-header{display:none;margin-bottom:1rem}.book-header label{line-height:0}.book-header img.book-icon{height:1.5em;width:1.5em}.book-search{position:relative;margin:1rem 0;border-bottom:1px solid transparent}.book-search input{width:100%;padding:.5rem;border:0;border-radius:.25rem;background:var(--gray-100);color:var(--body-font-color)}.book-search input:required+.book-search-spinner{display:block}.book-search .book-search-spinner{position:absolute;top:0;margin:.5rem;margin-inline-start:calc(100% - 1.5rem);width:1rem;height:1rem;border:1px solid transparent;border-top-color:var(--body-font-color);border-radius:50%;animation:spin 1s ease infinite}@keyframes spin{100%{transform:rotate(360deg)}}.book-search small{opacity:.5}.book-toc{flex:0 0 16rem;font-size:.75rem}.book-toc .book-toc-content{width:16rem;padding:1rem;position:fixed;top:0;bottom:0;overflow-x:hidden;overflow-y:auto}.book-toc img{height:1em;width:1em}.book-toc nav>ul>li:first-child{margin-top:0}.book-footer{padding-top:1rem;font-size:.875rem}.book-footer img{height:1em;width:1em;margin-inline-end:.5rem}.book-comments{margin-top:1rem}.book-languages{margin-block-end:2rem}.book-languages .book-icon{height:1em;width:1em;margin-inline-end:.5em}.book-languages ul{padding-inline-start:1.5em}.book-menu-content,.book-toc-content,.book-page,.book-header aside,.markdown{transition:.2s ease-in-out;transition-property:transform,margin,opacity,visibility;will-change:transform,margin,opacity}@media screen and (max-width:56rem){#menu-control,#toc-control{display:inline}.book-menu{visibility:hidden;margin-inline-start:-16rem;font-size:16px;z-index:1}.book-toc{display:none}.book-header{display:block}#menu-control:focus~main label[for=menu-control]{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}#menu-control:checked~main .book-menu{visibility:initial}#menu-control:checked~main .book-menu .book-menu-content{transform:translateX(16rem);box-shadow:0 0 .5rem rgba(0,0,0,.1)}#menu-control:checked~main .book-page{opacity:.25}#menu-control:checked~main .book-menu-overlay{display:block;position:absolute;top:0;bottom:0;left:0;right:0}#toc-control:focus~main label[for=toc-control]{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}#toc-control:checked~main .book-header aside{display:block}body[dir=rtl] #menu-control:checked~main .book-menu .book-menu-content{transform:translateX(-16rem)}}@media screen and (min-width:80rem){.book-page,.book-menu .book-menu-content,.book-toc .book-toc-content{padding:2rem 1rem}}body{font-size:16px;font-weight:400;font-family:noto sans cjk sc,source han sans sc,source han sans cn,noto sans sc,pingfang sc,microsoft yahei,sans-serif}.formula-text-center{margin-left:auto;margin-right:auto;display:block;font-size:18px;text-align:center}.markdown summary{font-size:16px;font-weight:700}.markdown figure img{text-align:right;margin-left:auto;margin-right:auto;display:block}.markdown figure figcaption{text-align:center}@media print{.book-menu,.book-footer,.book-toc{display:none}.book-header,.book-header aside{display:block}main{display:block!important}}.markdown{line-height:1.6}.markdown>:first-child{margin-top:0}.markdown h1,.markdown h2,.markdown h3,.markdown h4,.markdown h5,.markdown h6{font-weight:400;line-height:1;margin-top:1.5em;margin-bottom:1rem}.markdown h1 a.anchor,.markdown h2 a.anchor,.markdown h3 a.anchor,.markdown h4 a.anchor,.markdown h5 a.anchor,.markdown h6 a.anchor{opacity:0;font-size:.75em;vertical-align:middle;text-decoration:none}.markdown h1:hover a.anchor,.markdown h1 a.anchor:focus,.markdown h2:hover a.anchor,.markdown h2 a.anchor:focus,.markdown h3:hover a.anchor,.markdown h3 a.anchor:focus,.markdown h4:hover a.anchor,.markdown h4 a.anchor:focus,.markdown h5:hover a.anchor,.markdown h5 a.anchor:focus,.markdown h6:hover a.anchor,.markdown h6 a.anchor:focus{opacity:initial}.markdown h4,.markdown h5,.markdown h6{font-weight:bolder}.markdown h5{font-size:.875em}.markdown h6{font-size:.75em}.markdown b,.markdown optgroup,.markdown strong{font-weight:bolder}.markdown a{text-decoration:none}.markdown a:hover{text-decoration:underline}.markdown a:visited{color:var(--color-visited-link)}.markdown img{max-width:100%;height:auto}.markdown code{padding:0 .25rem;background:var(--gray-200);border-radius:.25rem;font-size:.875em}.markdown pre{padding:1rem;background:var(--gray-100);border-radius:.25rem;overflow-x:auto}.markdown pre code{padding:0;background:0 0}.markdown p{word-wrap:break-word}.markdown blockquote{margin:1rem 0;padding:.5rem 1rem .5rem .75rem;border-inline-start:.25rem solid var(--gray-200);border-radius:.25rem}.markdown blockquote :first-child{margin-top:0}.markdown blockquote :last-child{margin-bottom:0}.markdown table{overflow:auto;display:block;border-spacing:0;border-collapse:collapse;margin-top:1rem;margin-bottom:1rem}.markdown table tr th,.markdown table tr td{padding:.5rem 1rem;border:1px solid var(--gray-200)}.markdown table tr:nth-child(2n){background:var(--gray-100)}.markdown hr{height:1px;border:none;background:var(--gray-200)}.markdown ul,.markdown ol{padding-inline-start:2rem;word-wrap:break-word}.markdown dl dt{font-weight:bolder;margin-top:1rem}.markdown dl dd{margin-inline-start:0;margin-bottom:1rem}.markdown .highlight table tr td:nth-child(1) pre{margin:0;padding-inline-end:0}.markdown .highlight table tr td:nth-child(2) pre{margin:0;padding-inline-start:0}.markdown details{padding:1rem;border:1px solid var(--gray-200);border-radius:.25rem}.markdown details summary{line-height:1;padding:1rem;margin:-1rem;cursor:pointer}.markdown details[open] summary{margin-bottom:0}.markdown figure{margin:1rem 0}.markdown figure figcaption p{margin-top:0}.markdown-inner>:first-child{margin-top:0}.markdown-inner>:last-child{margin-bottom:0}.markdown .book-expand{margin-top:1rem;margin-bottom:1rem;border:1px solid var(--gray-200);border-radius:.25rem;overflow:hidden}.markdown .book-expand .book-expand-head{background:var(--gray-100);padding:.5rem 1rem;cursor:pointer}.markdown .book-expand .book-expand-content{display:none;padding:1rem}.markdown .book-expand input[type=checkbox]:checked+.book-expand-content{display:block}.markdown .book-tabs{margin-top:1rem;margin-bottom:1rem;border:1px solid var(--gray-200);border-radius:.25rem;overflow:hidden;display:flex;flex-wrap:wrap}.markdown .book-tabs label{display:inline-block;padding:.5rem 1rem;border-bottom:1px transparent;cursor:pointer}.markdown .book-tabs .book-tabs-content{order:999;width:100%;border-top:1px solid var(--gray-100);padding:1rem;display:none}.markdown .book-tabs input[type=radio]:checked+label{border-bottom:1px solid var(--color-link)}.markdown .book-tabs input[type=radio]:checked+label+.book-tabs-content{display:block}.markdown .book-tabs input[type=radio]:focus+label{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}.markdown .book-columns{margin-left:-1rem;margin-right:-1rem}.markdown .book-columns>div{margin:1rem 0;min-width:10rem;padding:0 1rem}.markdown a.book-btn{display:inline-block;font-size:.875rem;color:var(--color-link);line-height:2rem;padding:0 1rem;border:1px solid var(--color-link);border-radius:.25rem;cursor:pointer}.markdown a.book-btn:hover{text-decoration:none}.markdown .book-hint.info{border-color:#6bf;background-color:rgba(102,187,255,.1)}.markdown .book-hint.warning{border-color:#fd6;background-color:rgba(255,221,102,.1)}.markdown .book-hint.danger{border-color:#f66;background-color:rgba(255,102,102,.1)} \ No newline at end of file diff --git a/resources/_gen/assets/scss/book.scss_e129fe35b8d0a70789c8a08429469073.json b/resources/_gen/assets/scss/book.scss_e129fe35b8d0a70789c8a08429469073.json new file mode 100644 index 0000000..fc62cc0 --- /dev/null +++ b/resources/_gen/assets/scss/book.scss_e129fe35b8d0a70789c8a08429469073.json @@ -0,0 +1 @@ +{"Target":"book.min.0356a007b16d20385fd8a4fa025ec8be3122d726acbce111d6af7545fd9a6d9a.css","MediaType":"text/css","Data":{"Integrity":"sha256-A1agB7FtIDhf2KT6Al7IvjEi1yasvOER1q91Rf2abZo="}} \ No newline at end of file diff --git a/themes/hugo-book b/themes/hugo-book new file mode 160000 index 0000000..3f1bccc --- /dev/null +++ b/themes/hugo-book @@ -0,0 +1 @@ +Subproject commit 3f1bcccbfb247da44ab5410a97576c0bf6da103b