ACTIVE-STATE POWER MANAGEMENT
활성 상태 전원 관리(Active-State Power Management)는 외장 콤포넌트 고속 연결(Peripheral Component Interconnect Express)
(PCI Express 또는 PCIe) 서브시스템의 전원 소비를 PICe 연결로 접속된 장치가 사용중이 아닐 때 저전력 상태로 변경해서 절약함.
ASPM은 연결의 양 종단의 전원 상태를 제어하며, 연결의 한쪽 끝에 있는 장치가 완전히 전원이 켜져있는 상태일지라도 전력 소비를 줄여준다.
ASPM이 활성화되면,
서로 다른 전원 상태에 있는 연결 양 끝단의 장치들이 상태를 변경해야 하기 떄문에 지연 시간이 발생.
ASPM은 전원 상태를 결정하는 데 3가지 정책을 사용:
default
PICe 연결의 전원 상태를 시스템의 펌웨어(예: BIOS)에 지정된 디폴트 상태로 설정. 이는 ASPM의 디폴트 상태를 의미한다.
powersave
ASPM을 성능 감소를 감수하고라도 가능한 한 전력을 덜 소비하도록 설정한다.
performance
ASPM을 비활성화해서 PCIe 연결이 최대 성능을 발휘하도록 설정.
ASPM 정책은 /sys/module/pcie_aspm/parameters/policy에 설정 확인.
시스템 부팅시 pcie_aspm 커널 매개변수를 사용해 설정할 수도 있음.
pcie_aspm=off이라고 하면 ASPM을 비활성화하며,
pcie_aspm=force는 ASPM을, 심지어는 ASPM을 지원하지 않는 장치에 대해서 까지, 활성화하므로 주의가 필요 함.
주의
pcie_aspm=force를 설정하면,
ASPM을 지원하지 않는 하드웨어로 인해 시스템이 멈출 수 있다.
pcie_aspm=force를 지정하기 전에, 시스템의 모든 PCIe 하드웨어가 ASPM을 지원하는지 확인한다.
부트로드 수정
sudo vi /etc/default/grub
GRUB_CMDLINE_LINUX_DEFAULT="quiet pcie_aspm=performance splash"
reboot
컴맨드 라인 확인
cat /proc/cmdline
quiet pcie_aspm=performance splash
카테고리
asm
(27)
bootloader_x86_grub
(1)
C
(92)
compile
(11)
config
(76)
CPP
(13)
CSS
(1)
debugging
(7)
gimp
(1)
Go
(1)
html
(1)
Java
(1)
JavaScript
(1)
kernel
(19)
LibreOffice
(3)
Linux system progamming
(21)
MFC
(1)
opencv
(4)
OpenGL
(1)
PHP
(1)
Python
(4)
qemu
(29)
shell
(3)
socket
(7)
troubleshooting
(2)
ubuntu18.04
(2)
windows
(1)
2018/12/12
2018/12/11
socket 파일 전송 서버
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <ctype.h>
void error(const char *msg){
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, port_number;
socklen_t clilen;
char buffer[1024];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
port_number = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port_number);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd, 5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
FILE *fp;
int ch = 0;
fp = fopen("Hean_receive.txt","a");
int words;
read(newsockfd, &words, sizeof(int));
//printf("Passed integer is : %d\n" , words); //Ignore , Line for Testing
while(ch != words){
read(newsockfd, buffer, 1024);
fprintf(fp, " %s", buffer);
//printf(" %s %d " , buffer , ch); //Line for Testing , Ignore
ch++;
}
printf("The file was received successfully\n");
printf("The new file created is Korea_HeaNam Full Name");
close(newsockfd);
close(sockfd);
return 0;
}
// compile: gcc -o server server.c
// ./server 9999
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <ctype.h>
void error(const char *msg){
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, port_number;
socklen_t clilen;
char buffer[1024];
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
port_number = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port_number);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd, 5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
FILE *fp;
int ch = 0;
fp = fopen("Hean_receive.txt","a");
int words;
read(newsockfd, &words, sizeof(int));
//printf("Passed integer is : %d\n" , words); //Ignore , Line for Testing
while(ch != words){
read(newsockfd, buffer, 1024);
fprintf(fp, " %s", buffer);
//printf(" %s %d " , buffer , ch); //Line for Testing , Ignore
ch++;
}
printf("The file was received successfully\n");
printf("The new file created is Korea_HeaNam Full Name");
close(newsockfd);
close(sockfd);
return 0;
}
// compile: gcc -o server server.c
// ./server 9999
socket 파일 전송 클라이언트
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include<ctype.h>
void error(const char *msg){
perror(msg);
exit(0);
}
int main(int argc, char *argv[]){
int sockfd, port_number, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[1024];
if (argc < 3){
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
port_number = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(port_number);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
bzero(buffer,1024);
FILE *f;
int words = 0;
char c;
f=fopen("HeaN.txt","r");
while((c=getc(f))!=EOF){ //Counting No of words in the file
fscanf(f , "%s" , buffer);
if(isspace(c)||c=='\t')
words++;
}
//printf("Words = %d \n" , words); //Ignore
write(sockfd, &words, sizeof(int));
rewind(f);
/* fseek(f, 0L, SEEK_END); // tells size of the file. Not rquired for the functionality in code.
int sz = ftell(f); //Just written for curiosity.
printf("Size is %d \n" , sz);
rewind(f);
*/
char ch ;
while(ch != EOF){
fscanf(f , "%s" , buffer);
//printf("%s\n" , buffer); //Ignore
write(sockfd,buffer,1024);
ch = fgetc(f);
}
printf("The file was sent successfully");
close(sockfd);
return 0;
}
// compile: gcc -o client client.c
// ./client 127.0.0.1 9999
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include<ctype.h>
void error(const char *msg){
perror(msg);
exit(0);
}
int main(int argc, char *argv[]){
int sockfd, port_number, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[1024];
if (argc < 3){
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
port_number = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(port_number);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
bzero(buffer,1024);
FILE *f;
int words = 0;
char c;
f=fopen("HeaN.txt","r");
while((c=getc(f))!=EOF){ //Counting No of words in the file
fscanf(f , "%s" , buffer);
if(isspace(c)||c=='\t')
words++;
}
//printf("Words = %d \n" , words); //Ignore
write(sockfd, &words, sizeof(int));
rewind(f);
/* fseek(f, 0L, SEEK_END); // tells size of the file. Not rquired for the functionality in code.
int sz = ftell(f); //Just written for curiosity.
printf("Size is %d \n" , sz);
rewind(f);
*/
char ch ;
while(ch != EOF){
fscanf(f , "%s" , buffer);
//printf("%s\n" , buffer); //Ignore
write(sockfd,buffer,1024);
ch = fgetc(f);
}
printf("The file was sent successfully");
close(sockfd);
return 0;
}
// compile: gcc -o client client.c
// ./client 127.0.0.1 9999
vim + ctags + cscope + taglist 연동
사용방법.
잘 정리 된 국내 사이트 참고 http://vlee.kr/946
vim 명령 모드에서 다음을 입력
:cs [명령]
– 명령
help : 도움말
예제 : :cs help / :cs
add : 새 데이타 베이스 더하기
사용법 : add file|dir [pre-path] [flags]
예제 : :cs add ./cscope.out
show : 연결 보여주기
사용법 : show
예제 : :cs show
kill : 연결 끊기
사용법 : kill # (#은 연결된 데이타베이스 번호로 show 를 통해 확인 가능)
예제 : :cs kill 0
reset : 모든 연결 초기화
사용법 : reset
예제 : :cs reset
find : Query for a pattern
사용법 : find c|d|e|f|g|i|s|t name
0 또는 s C 심볼 검색
1 또는 g 전역 선언만 검색
2 또는 d 이 함수에 의해 호출되는 함수들 검색
3 또는 c 이 함수를 호출하는 함수들 검색
4 또는 t 텍스트 문자열을 검색
5 또는 e 확장 정규식을 사용하여 검색
7 또는 f 파일 이름을 검색
8 또는 i 이 파일을 인클루드하는 파일 검색
예제: :cs find s start_kernel
:cn 다음 태그
:cp 이전 태그
cscope 직접 실행
cscope DB가 존재하는 디렉토리에서 다음을 입력
$ cscope -d
다음과 같은 메뉴에서 입력을 할 수 있다.
Find this C symbol : ctags와 마찬가지로 C 심볼(변수, 함수, 매크로, 구조체)들을 찾는다.
Find this global definition : 전역 선언만 검색
Find functions called by this function : 이 함수에 의해 호출되는 함수를 검색
Find functions calling this function : 이 함수를 호출하는 함수를 검색
Find this text string : 텍스트 문자열을 검색
Change this text string : 문자열을 검색해서 변경
Find this egrep pattern : 정규식을 이용해서 소스코드 검색
Find this file : 특정이름을 포함한 파일을 모두 검색
Find files #including this file : 특정헤더를 포함시키는 모든 소스코드를 검색
프로그램에서 빠져나오고 싶으면 ctrl + d 입력, tab을 누르면 검색메뉴로 돌아갈 수 있다.
taglist
vim 명령 모드에서 다음을 입력
:Tlist
창이 분리되고 왼쪽에 함수, 매크로 등의 목록이 나온다. ctrl + w + w 로 창간 이동이 가능하며 태그 리스트 창에서 특정 함수 명이나 매크로에 커서를 갖다 놓고 enter를 치면 해당 함수나 매크로가 선언되어 잇는 곳으로 이동 한다.
taglist 창을 닫기 위해선 taglist 창으로 이동 하여 vim 명령 모드에서 :q 를 입력한다.
잘 정리 된 국내 사이트 참고 http://vlee.kr/946
vim 명령 모드에서 다음을 입력
:cs [명령]
– 명령
help : 도움말
예제 : :cs help / :cs
add : 새 데이타 베이스 더하기
사용법 : add file|dir [pre-path] [flags]
예제 : :cs add ./cscope.out
show : 연결 보여주기
사용법 : show
예제 : :cs show
kill : 연결 끊기
사용법 : kill # (#은 연결된 데이타베이스 번호로 show 를 통해 확인 가능)
예제 : :cs kill 0
reset : 모든 연결 초기화
사용법 : reset
예제 : :cs reset
find : Query for a pattern
사용법 : find c|d|e|f|g|i|s|t name
0 또는 s C 심볼 검색
1 또는 g 전역 선언만 검색
2 또는 d 이 함수에 의해 호출되는 함수들 검색
3 또는 c 이 함수를 호출하는 함수들 검색
4 또는 t 텍스트 문자열을 검색
5 또는 e 확장 정규식을 사용하여 검색
7 또는 f 파일 이름을 검색
8 또는 i 이 파일을 인클루드하는 파일 검색
예제: :cs find s start_kernel
:cn 다음 태그
:cp 이전 태그
cscope 직접 실행
cscope DB가 존재하는 디렉토리에서 다음을 입력
$ cscope -d
다음과 같은 메뉴에서 입력을 할 수 있다.
Find this C symbol : ctags와 마찬가지로 C 심볼(변수, 함수, 매크로, 구조체)들을 찾는다.
Find this global definition : 전역 선언만 검색
Find functions called by this function : 이 함수에 의해 호출되는 함수를 검색
Find functions calling this function : 이 함수를 호출하는 함수를 검색
Find this text string : 텍스트 문자열을 검색
Change this text string : 문자열을 검색해서 변경
Find this egrep pattern : 정규식을 이용해서 소스코드 검색
Find this file : 특정이름을 포함한 파일을 모두 검색
Find files #including this file : 특정헤더를 포함시키는 모든 소스코드를 검색
프로그램에서 빠져나오고 싶으면 ctrl + d 입력, tab을 누르면 검색메뉴로 돌아갈 수 있다.
taglist
vim 명령 모드에서 다음을 입력
:Tlist
창이 분리되고 왼쪽에 함수, 매크로 등의 목록이 나온다. ctrl + w + w 로 창간 이동이 가능하며 태그 리스트 창에서 특정 함수 명이나 매크로에 커서를 갖다 놓고 enter를 치면 해당 함수나 매크로가 선언되어 잇는 곳으로 이동 한다.
taglist 창을 닫기 위해선 taglist 창으로 이동 하여 vim 명령 모드에서 :q 를 입력한다.
커널 분석 추가 vimrc 설정
vim 설정
VIM 플러그인들을 관리 할 수 있도록 돕는 플러그인.
VIM 내에서 플러그인 검색, 설치, 업데이트, 삭제 등의 작업이 가능
git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
플로그인 검색 및 자동 설치 Keymap
: VundleSearch
Keymap
i : Install plugin
c : Clean up
s : Search
R : Reload list
수동 플러그인 설정
vi .vimrc
set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
" 바닥글
Plugin 'vim-airline/vim-airline'
" 바닥글 추가, 삭제, 변경 정보 확인.
Plugin 'tpope/vim-fugitive'
" 문법 체크
Plugin 'scrooloose/syntastic'
" IDE 파일 Tree
Plugin 'nerdtree'
" git 관리 파일 변경 부분 확인
Plugin 'airblade/vim-gitgutter'
" 색상 테마 적용
Plugin 'nanotech/jellybeans.vim'
" 커피스크립트 Synatx
Plugin 'kchmck/vim-coffee-script'
" vimshell
Plugin 'shougo/vimshell.vim'
Plugin 'vimproc.vim'
call vundle#end() " required
filetype plugin indent on " required
map <Leader>nt <ESC>:NERDTree<CR>
color jellybeans
플러그인 적용
vi vim
:PluginInstall
플로그인 삭제
vi .vimrc
Plugin 이름 삭제
:PluginClena
설치 플로그인 기능 활성화
:NERDTree
:NERDTreeToggle on/off
vimshell 설치
git clone https://github.com/Shougo/vimshell.vim.git ~/.vim/bundle/VimShell.vim
cd ~/.vim/bundle/VimShell.vim
sudo apt-get install ctags cscope exuberant-ctags
cscope: 코드를 탐색하는 데 사용됩니다 (함수 간 전환 등).
ctags: Tagbar플러그인을 위해 필요하고 그리고 Omni completion(vim의 자동 완성 메카니즘); 네비게이션에도 사용할 수 있음.
커널 소스 scripts/tags.sh 커널 분석 데이터베이스 스크립트.
============================================
스크립트를 직접 실행하는 대신 커널 작성 규칙 make cscope, make tags 규칙을 사용한다.
예:
make O=. ARCH=arm SUBARCH=omap2 COMPILED_SOURCE=1 cscope tags
옵션 설명
O=.
- 절대 경로를 사용
(생성 된 cscope/ctags 색인 파일을 커널 디렉토리 외부로 로드하려는 경우 유용함. 예: 트리 외부 커널 모듈 개발 용).
상대 경로 (즉, 커널 디렉토리에서만 개발)를 사용하려면 해당 매개 변수를 생략한다.
ARCH=...
- 인덱싱 할 CPU 아키텍처를 선택
- ARCH=arm, arch/arm/
SUBARCH=...
- 인덱싱 할 하위 아키텍처 (예: 보드 관련 파일)를 선택
- 예를 들어, 디렉토리 와 인덱스 SUBARCH=omap2만 인덱싱되면 나머지 머신과 플랫폼은 무시된다.
- arch/arm/mach-omap2/ arch/arm/plat-omap/ 이 플랫폼만 관련해 인덱싱 색인 정보를 만든다.
COMPILED_SOURCE=1
- 컴파일 된 파일 만 색인한다.
- 일반적으로 빌드에 사용 된 소스 파일에만 관심이 있으므로(따라서 컴파일 됨). 빌드되지 않은 파일도 같이 색인화하려면이 옵션을 생략한다.
cscope
- cscope 색인을 만드는 규칙
tags
- ctags 인덱스를 만드는 규칙
수동 생성 색인
=============
스크립트 동작에 문제가 있을 경우 수동으로 생성한다.
http://cscope.sourceforge.net/large_projects.html
먼저 cscope.files색인을 생성하려는 모든 파일을 나열하는 파일 을 작성한다.
예를 들어,
다음 명령을 사용하여 ARM 아키텍처(arch/arm)에 대한 파일을 나열 하고 특히 OMAP 플랫폼(나머지 플랫폼은 제외하고 탐색을 쉽게 유지할 수 있음)을 사용한다.
vi cscope.files
find $dir \
-path "$dir/arch*" -prune -o \
-path "$dir/tmp*" -prune -o \
-path "$dir/Documentation*" -prune -o \
-path "$dir/scripts*" -prune -o \
-path "$dir/tools*" -prune -o \
-path "$dir/include/config*" -prune -o \
-path "$dir/usr/include*" -prune -o \
-type f \
-not -name '*.mod.c' \
-name "*.[chsS]" -print > cscope.files
find $dir/arch/arm \
-path "$dir/arch/arm/mach-*" -prune -o \
-path "$dir/arch/arm/plat-*" -prune -o \
-path "$dir/arch/arm/configs" -prune -o \
-path "$dir/arch/arm/kvm" -prune -o \
-path "$dir/arch/arm/xen" -prune -o \
-type f \
-not -name '*.mod.c' \
-name "*.[chsS]" -print >> cscope.files
find $dir/arch/arm/mach-omap2/ \
$dir/arch/arm/plat-omap/ \
-type f \
-not -name '*.mod.c' \
-name "*.[chsS]" -print >> cscope.files
vi cscope.files
x86 아키텍처 (arch/x86)에서는 다음과 같은 것을 사용한다.
find $dir \
-path "$dir/arch*" -prune -o \
-path "$dir/tmp*" -prune -o \
-path "$dir/Documentation*" -prune -o \
-path "$dir/scripts*" -prune -o \
-path "$dir/tools*" -prune -o \
-path "$dir/include/config*" -prune -o \
-path "$dir/usr/include*" -prune -o \
-type f \
-not -name '*.mod.c' \
-name "*.[chsS]" -print > cscope.files
find $dir/arch/x86 \
-path "$dir/arch/x86/configs" -prune -o \
-path "$dir/arch/x86/kvm" -prune -o \
-path "$dir/arch/x86/lguest" -prune -o \
-path "$dir/arch/x86/xen" -prune -o \
-type f \
-not -name '*.mod.c' \
-name "*.[chsS]" -print >> cscope.files
변수 설명
dir변수는 다음 값 중 하나를 가질 수 있다:
- .: 커널 소스 코드 디렉토리에서만 작업한다면; 이 경우 해당 명령은 커널 소스 코드의 루트 디렉토리에서 실행해야 한다.
- 커널 소스 코드 디렉토리의 절대 경로: 트리를 벗어난 커널 모듈을 개발할 경우; 이 경우 스크립트는 어디서나 실행할 수 있다.
위의 첫 번째 옵션 (dir =.)을 사용하고 있다.
모듈을 개발하지 않기 때문에 dir =. 을 사용함.
cscope.files파일이 준비되면 실제 인덱싱을 실행한다.
cscope -b -q -k
옵션 설명
-k매개 변수는 C 표준 라이브러리를 색인하지 않도록 지시한다.(커널은 C 표준을 사용하지 않는다.)
ctags인덱스 데이터베이스 생성한다.
이 단계를 가속화하기 위해 이미 만들어 둔 cscope.files을 사용한다
ctags -L cscope.files
cscope및 ctags인덱스 데이터베이스가 새롭게 생성된다.
cscope.files은 더이상 필요하지 않기 때문에 삭제한다.
rm -f cscope.files
생성된 다음 파일에는 색인 데이터베이스(cscope및 ctags)가 들어 있다.
- cscope.in.out
- cscope.out
- cscope.po.out
- tags
커널 vim 플러그인 설치
=====================
참고: vim8 native package loading 사용 가능.
native package loading : https://shapeshed.com/vim-packages/
pathogen.vim 플러그인 설치
https://github.com/tpope/vim-pathogen
~/.vim/bundle/ 상태 유지 하면서 설치 한다.
mkdir -p ~/.vim/autoload && curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim
vi .vimrc
execute pathogen#infect()
아무런 설정이 없다면 3줄 추가.
vi .vimrc
execute pathogen#infect()
syntax on
filetype plugin indent on
vim cscope 맵 설치
==================
현재 cscope 지원한다.
:help cscope
지정한 기호를 사용해 파일 이동 가능.
:cs f g kfree
단축키 사용.
cscope_maps.vim
https://github.com/joe-skb7/cscope-maps
git clone https://github.com/joe-skb7/cscope-maps.git ~/.vim/bundle/cscope-maps
커서를 일부 함수에 놓고 다음 키를 차례로 누르면 구현 부분으로 찾아간다.
Ctrl+\
g
키 맵핑에 관련해 다음 사이트를 참고한다.
https://github.com/joe-skb7/cscope-maps/blob/master/plugin/cscope_maps.vim#L52
ctags 참고
========
#define 선언을 찾을 때 탐색 하는 방법.
#define 커서 이동 후 다음 키를 순서대로 누른다.
g
Ctrl + ]
g
ctrl - ]
cscope 참고
===========
:cs f t struct device {
위의 명령은 특정 구조체 선언 스타일 (커널에서 사용됨)임.
다른 코딩 스타일을 가진 프로젝트에서는 작동하지 않을 수 있음.
out-of-tree 모듈 개발 노트
=========================
외부 트리 모듈을 개발할 경우 커널 디렉토리에서 데이터베이스 cscope와 ctags데이터베이스를 로드해야 한다.
외부 cscope 데이터베이스 로드:
:cs add /path/to/your/kernel/cscope.out
외부 ctags 데이터베이스 로드:
:set tags=/path/to/your/kernel/tags
커널 개발 지원 전용 vimrc 변경.
=============================
열 81 수직 적용(커널 코딩은 줄 길이를 최대 80 문자로 유지해야 함)
" 80 characters line
set colorcolumn=81
"execute "set colorcolumn=" . join(range(81,335), ',')
highlight ColorColumn ctermbg=Black ctermfg=DarkRed
80 열 이상을 강조 표시하려면 "execute "set colorcolumn=" . join(range(81,335), ',') 주석 처리 해제.
후행 공백은 커널 코딩 스타일에 의해 금지되므로 강조 표시 할 수 있다.
" Highlight trailing spaces
" http://vim.wikia.com/wiki/Highlight_unwanted_spaces
highlight ExtraWhitespace ctermbg=red guibg=red
match ExtraWhitespace /\s\+$/
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches()
커널 코딩 스타일 플러그인
=======================
https://github.com/vivien/vim-linux-coding-style
vi .vimrc
Plugin 'vim-linux-coding-style'
Plugin 'bogado/file-line'
나중 커널용 구성시 참고해 볼 만한 플러그인
https://github.com/vim-syntastic/syntastic
https://github.com/Valloric/YouCompleteMe
Omni completion
Vim 7 (및 그 이상)은 이미 자동 완성 지원 기능을 내장하고 있다.
자세한 내용 http://vimdoc.sourceforge.net/htmldoc/version7.html#new-omni-completion
큰 프로제그에서는 느리게 동작한다.
만약 사용한다면 .vimrc 내용 추가.
" Enable OmniCompletion
" http://vim.wikia.com/wiki/Omni_completion
filetype plugin on
set omnifunc=syntaxcomplete#Complete
" Configure menu behavior
" http://vim.wikia.com/wiki/VimTip1386
set completeopt=longest,menuone
inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
inoremap <expr> <C-n> pumvisible() ? '<C-n>' :
\ '<C-n><C-r>=pumvisible() ? "\<lt>Down>" : ""<CR>'
inoremap <expr> <M-,> pumvisible() ? '<C-n>' :
\ '<C-x><C-o><C-n><C-p><C-r>=pumvisible() ? "\<lt>Down>" : ""<CR>'
" Use Ctrl+Space for omni-completion
" https://stackoverflow.com/questions/510503/ctrlspace-for-omni-and-keyword-completion-in-vim
inoremap <expr> <C-Space> pumvisible() \|\| &omnifunc == '' ?
\ "\<lt>C-n>" :
\ "\<lt>C-x>\<lt>C-o><c-r>=pumvisible() ?" .
\ "\"\\<lt>c-n>\\<lt>c-p>\\<lt>c-n>\" :" .
\ "\" \\<lt>bs>\\<lt>C-n>\"\<CR>"
imap <C-@> <C-Space>
" Popup menu hightLight Group
highlight Pmenu ctermbg=13 guibg=LightGray
highlight PmenuSel ctermbg=7 guibg=DarkBlue guifg=White
highlight PmenuSbar ctermbg=7 guibg=DarkGray
highlight PmenuThumb guibg=Black
" Enable global scope search
let OmniCpp_GlobalScopeSearch = 1
" Show function parameters
let OmniCpp_ShowPrototypeInAbbr = 1
" Show access information in pop-up menu
let OmniCpp_ShowAccess = 1
" Auto complete after '.'
let OmniCpp_MayCompleteDot = 1
" Auto complete after '->'
let OmniCpp_MayCompleteArrow = 1
" Auto complete after '::'
let OmniCpp_MayCompleteScope = 0
" Don't select first item in pop-up menu
let OmniCpp_SelectFirstItem = 0
자동 완성 기능은 ctrl + space 사용.
색상 지정
=========
vi .bashrc
export TERM="xterm-256color"
vi .vimrc
set t_Co=256
색 구성 표 작성
==============
~/.vim/colors
현재 jellybeans.vim 구성 됨
cd .vim/colors
wget https://github.com/w0ng/vim-hybrid/blob/master/colors/hybrid.vim
cd ~/.vim/bundle
git clone git://github.com/altercation/vim-colors-solarized.git
mv vim-colors-solarized ~/.vim/bundle/
어두운 배경 설정
syntax enable
set background=dark
colorscheme solarized
밝은 배경 설정
syntax enable
set background=light
colorscheme solarized
원하는 색상 지정
vi .vimrc
Plugin 'mrkn256.vim'
Plugin 'hybrid.vim'
GUI eclipse IDE 사용 방법 분석
=============================
https://wiki.eclipse.org/HowTo_use_the_CDT_to_navigate_Linux_kernel_source
taglist 설치
============
wget http://vim-taglist.sourceforge.net/ 최신 버전 다운로드
플러그인 적용
$ mkdir ~/.vim
$ unzip taglist.zip
스크립트 생성
vim mktrace.sh
#!/bin/sh
rm -rf cscope.files cscope.files
rm -rf tags
find . \( -name '*.c' -o -name '*.cpp' -o -name '*.cc' -o -name '*.h' -o -name '*.s' -o -name '*.S' -o -name '*.asm' \) -print > cscope.files
ctags -R
cscope -i cscope.files
.vimrc 설정
vi .vimrc
" cscope 설정
set csprg=/usr/bin/cscope
set csto=0
set cst
set nocsverb
if filereadable("./cscope.out")
cs add cscope.out
else
cs add /usr/src/linux/cscope.out
endif
set csverb
vim 셀 접근
: VimShell
창 분할
vs, sp
VIM 플러그인들을 관리 할 수 있도록 돕는 플러그인.
VIM 내에서 플러그인 검색, 설치, 업데이트, 삭제 등의 작업이 가능
git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim
플로그인 검색 및 자동 설치 Keymap
: VundleSearch
Keymap
i : Install plugin
c : Clean up
s : Search
R : Reload list
수동 플러그인 설정
vi .vimrc
set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
" 바닥글
Plugin 'vim-airline/vim-airline'
" 바닥글 추가, 삭제, 변경 정보 확인.
Plugin 'tpope/vim-fugitive'
" 문법 체크
Plugin 'scrooloose/syntastic'
" IDE 파일 Tree
Plugin 'nerdtree'
" git 관리 파일 변경 부분 확인
Plugin 'airblade/vim-gitgutter'
" 색상 테마 적용
Plugin 'nanotech/jellybeans.vim'
" 커피스크립트 Synatx
Plugin 'kchmck/vim-coffee-script'
" vimshell
Plugin 'shougo/vimshell.vim'
Plugin 'vimproc.vim'
call vundle#end() " required
filetype plugin indent on " required
map <Leader>nt <ESC>:NERDTree<CR>
color jellybeans
플러그인 적용
vi vim
:PluginInstall
플로그인 삭제
vi .vimrc
Plugin 이름 삭제
:PluginClena
설치 플로그인 기능 활성화
:NERDTree
:NERDTreeToggle on/off
vimshell 설치
git clone https://github.com/Shougo/vimshell.vim.git ~/.vim/bundle/VimShell.vim
cd ~/.vim/bundle/VimShell.vim
sudo apt-get install ctags cscope exuberant-ctags
cscope: 코드를 탐색하는 데 사용됩니다 (함수 간 전환 등).
ctags: Tagbar플러그인을 위해 필요하고 그리고 Omni completion(vim의 자동 완성 메카니즘); 네비게이션에도 사용할 수 있음.
커널 소스 scripts/tags.sh 커널 분석 데이터베이스 스크립트.
============================================
스크립트를 직접 실행하는 대신 커널 작성 규칙 make cscope, make tags 규칙을 사용한다.
예:
make O=. ARCH=arm SUBARCH=omap2 COMPILED_SOURCE=1 cscope tags
옵션 설명
O=.
- 절대 경로를 사용
(생성 된 cscope/ctags 색인 파일을 커널 디렉토리 외부로 로드하려는 경우 유용함. 예: 트리 외부 커널 모듈 개발 용).
상대 경로 (즉, 커널 디렉토리에서만 개발)를 사용하려면 해당 매개 변수를 생략한다.
ARCH=...
- 인덱싱 할 CPU 아키텍처를 선택
- ARCH=arm, arch/arm/
SUBARCH=...
- 인덱싱 할 하위 아키텍처 (예: 보드 관련 파일)를 선택
- 예를 들어, 디렉토리 와 인덱스 SUBARCH=omap2만 인덱싱되면 나머지 머신과 플랫폼은 무시된다.
- arch/arm/mach-omap2/ arch/arm/plat-omap/ 이 플랫폼만 관련해 인덱싱 색인 정보를 만든다.
COMPILED_SOURCE=1
- 컴파일 된 파일 만 색인한다.
- 일반적으로 빌드에 사용 된 소스 파일에만 관심이 있으므로(따라서 컴파일 됨). 빌드되지 않은 파일도 같이 색인화하려면이 옵션을 생략한다.
cscope
- cscope 색인을 만드는 규칙
tags
- ctags 인덱스를 만드는 규칙
수동 생성 색인
=============
스크립트 동작에 문제가 있을 경우 수동으로 생성한다.
http://cscope.sourceforge.net/large_projects.html
먼저 cscope.files색인을 생성하려는 모든 파일을 나열하는 파일 을 작성한다.
예를 들어,
다음 명령을 사용하여 ARM 아키텍처(arch/arm)에 대한 파일을 나열 하고 특히 OMAP 플랫폼(나머지 플랫폼은 제외하고 탐색을 쉽게 유지할 수 있음)을 사용한다.
vi cscope.files
find $dir \
-path "$dir/arch*" -prune -o \
-path "$dir/tmp*" -prune -o \
-path "$dir/Documentation*" -prune -o \
-path "$dir/scripts*" -prune -o \
-path "$dir/tools*" -prune -o \
-path "$dir/include/config*" -prune -o \
-path "$dir/usr/include*" -prune -o \
-type f \
-not -name '*.mod.c' \
-name "*.[chsS]" -print > cscope.files
find $dir/arch/arm \
-path "$dir/arch/arm/mach-*" -prune -o \
-path "$dir/arch/arm/plat-*" -prune -o \
-path "$dir/arch/arm/configs" -prune -o \
-path "$dir/arch/arm/kvm" -prune -o \
-path "$dir/arch/arm/xen" -prune -o \
-type f \
-not -name '*.mod.c' \
-name "*.[chsS]" -print >> cscope.files
find $dir/arch/arm/mach-omap2/ \
$dir/arch/arm/plat-omap/ \
-type f \
-not -name '*.mod.c' \
-name "*.[chsS]" -print >> cscope.files
vi cscope.files
x86 아키텍처 (arch/x86)에서는 다음과 같은 것을 사용한다.
find $dir \
-path "$dir/arch*" -prune -o \
-path "$dir/tmp*" -prune -o \
-path "$dir/Documentation*" -prune -o \
-path "$dir/scripts*" -prune -o \
-path "$dir/tools*" -prune -o \
-path "$dir/include/config*" -prune -o \
-path "$dir/usr/include*" -prune -o \
-type f \
-not -name '*.mod.c' \
-name "*.[chsS]" -print > cscope.files
find $dir/arch/x86 \
-path "$dir/arch/x86/configs" -prune -o \
-path "$dir/arch/x86/kvm" -prune -o \
-path "$dir/arch/x86/lguest" -prune -o \
-path "$dir/arch/x86/xen" -prune -o \
-type f \
-not -name '*.mod.c' \
-name "*.[chsS]" -print >> cscope.files
변수 설명
dir변수는 다음 값 중 하나를 가질 수 있다:
- .: 커널 소스 코드 디렉토리에서만 작업한다면; 이 경우 해당 명령은 커널 소스 코드의 루트 디렉토리에서 실행해야 한다.
- 커널 소스 코드 디렉토리의 절대 경로: 트리를 벗어난 커널 모듈을 개발할 경우; 이 경우 스크립트는 어디서나 실행할 수 있다.
위의 첫 번째 옵션 (dir =.)을 사용하고 있다.
모듈을 개발하지 않기 때문에 dir =. 을 사용함.
cscope.files파일이 준비되면 실제 인덱싱을 실행한다.
cscope -b -q -k
옵션 설명
-k매개 변수는 C 표준 라이브러리를 색인하지 않도록 지시한다.(커널은 C 표준을 사용하지 않는다.)
ctags인덱스 데이터베이스 생성한다.
이 단계를 가속화하기 위해 이미 만들어 둔 cscope.files을 사용한다
ctags -L cscope.files
cscope및 ctags인덱스 데이터베이스가 새롭게 생성된다.
cscope.files은 더이상 필요하지 않기 때문에 삭제한다.
rm -f cscope.files
생성된 다음 파일에는 색인 데이터베이스(cscope및 ctags)가 들어 있다.
- cscope.in.out
- cscope.out
- cscope.po.out
- tags
커널 vim 플러그인 설치
=====================
참고: vim8 native package loading 사용 가능.
native package loading : https://shapeshed.com/vim-packages/
pathogen.vim 플러그인 설치
https://github.com/tpope/vim-pathogen
~/.vim/bundle/ 상태 유지 하면서 설치 한다.
mkdir -p ~/.vim/autoload && curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim
vi .vimrc
execute pathogen#infect()
아무런 설정이 없다면 3줄 추가.
vi .vimrc
execute pathogen#infect()
syntax on
filetype plugin indent on
vim cscope 맵 설치
==================
현재 cscope 지원한다.
:help cscope
지정한 기호를 사용해 파일 이동 가능.
:cs f g kfree
단축키 사용.
cscope_maps.vim
https://github.com/joe-skb7/cscope-maps
git clone https://github.com/joe-skb7/cscope-maps.git ~/.vim/bundle/cscope-maps
커서를 일부 함수에 놓고 다음 키를 차례로 누르면 구현 부분으로 찾아간다.
Ctrl+\
g
키 맵핑에 관련해 다음 사이트를 참고한다.
https://github.com/joe-skb7/cscope-maps/blob/master/plugin/cscope_maps.vim#L52
ctags 참고
========
#define 선언을 찾을 때 탐색 하는 방법.
#define 커서 이동 후 다음 키를 순서대로 누른다.
g
Ctrl + ]
g
ctrl - ]
cscope 참고
===========
:cs f t struct device {
위의 명령은 특정 구조체 선언 스타일 (커널에서 사용됨)임.
다른 코딩 스타일을 가진 프로젝트에서는 작동하지 않을 수 있음.
out-of-tree 모듈 개발 노트
=========================
외부 트리 모듈을 개발할 경우 커널 디렉토리에서 데이터베이스 cscope와 ctags데이터베이스를 로드해야 한다.
외부 cscope 데이터베이스 로드:
:cs add /path/to/your/kernel/cscope.out
외부 ctags 데이터베이스 로드:
:set tags=/path/to/your/kernel/tags
커널 개발 지원 전용 vimrc 변경.
=============================
열 81 수직 적용(커널 코딩은 줄 길이를 최대 80 문자로 유지해야 함)
" 80 characters line
set colorcolumn=81
"execute "set colorcolumn=" . join(range(81,335), ',')
highlight ColorColumn ctermbg=Black ctermfg=DarkRed
80 열 이상을 강조 표시하려면 "execute "set colorcolumn=" . join(range(81,335), ',') 주석 처리 해제.
후행 공백은 커널 코딩 스타일에 의해 금지되므로 강조 표시 할 수 있다.
" Highlight trailing spaces
" http://vim.wikia.com/wiki/Highlight_unwanted_spaces
highlight ExtraWhitespace ctermbg=red guibg=red
match ExtraWhitespace /\s\+$/
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches()
커널 코딩 스타일 플러그인
=======================
https://github.com/vivien/vim-linux-coding-style
vi .vimrc
Plugin 'vim-linux-coding-style'
Plugin 'bogado/file-line'
나중 커널용 구성시 참고해 볼 만한 플러그인
https://github.com/vim-syntastic/syntastic
https://github.com/Valloric/YouCompleteMe
Omni completion
Vim 7 (및 그 이상)은 이미 자동 완성 지원 기능을 내장하고 있다.
자세한 내용 http://vimdoc.sourceforge.net/htmldoc/version7.html#new-omni-completion
큰 프로제그에서는 느리게 동작한다.
만약 사용한다면 .vimrc 내용 추가.
" Enable OmniCompletion
" http://vim.wikia.com/wiki/Omni_completion
filetype plugin on
set omnifunc=syntaxcomplete#Complete
" Configure menu behavior
" http://vim.wikia.com/wiki/VimTip1386
set completeopt=longest,menuone
inoremap <expr> <CR> pumvisible() ? "\<C-y>" : "\<C-g>u\<CR>"
inoremap <expr> <C-n> pumvisible() ? '<C-n>' :
\ '<C-n><C-r>=pumvisible() ? "\<lt>Down>" : ""<CR>'
inoremap <expr> <M-,> pumvisible() ? '<C-n>' :
\ '<C-x><C-o><C-n><C-p><C-r>=pumvisible() ? "\<lt>Down>" : ""<CR>'
" Use Ctrl+Space for omni-completion
" https://stackoverflow.com/questions/510503/ctrlspace-for-omni-and-keyword-completion-in-vim
inoremap <expr> <C-Space> pumvisible() \|\| &omnifunc == '' ?
\ "\<lt>C-n>" :
\ "\<lt>C-x>\<lt>C-o><c-r>=pumvisible() ?" .
\ "\"\\<lt>c-n>\\<lt>c-p>\\<lt>c-n>\" :" .
\ "\" \\<lt>bs>\\<lt>C-n>\"\<CR>"
imap <C-@> <C-Space>
" Popup menu hightLight Group
highlight Pmenu ctermbg=13 guibg=LightGray
highlight PmenuSel ctermbg=7 guibg=DarkBlue guifg=White
highlight PmenuSbar ctermbg=7 guibg=DarkGray
highlight PmenuThumb guibg=Black
" Enable global scope search
let OmniCpp_GlobalScopeSearch = 1
" Show function parameters
let OmniCpp_ShowPrototypeInAbbr = 1
" Show access information in pop-up menu
let OmniCpp_ShowAccess = 1
" Auto complete after '.'
let OmniCpp_MayCompleteDot = 1
" Auto complete after '->'
let OmniCpp_MayCompleteArrow = 1
" Auto complete after '::'
let OmniCpp_MayCompleteScope = 0
" Don't select first item in pop-up menu
let OmniCpp_SelectFirstItem = 0
자동 완성 기능은 ctrl + space 사용.
색상 지정
=========
vi .bashrc
export TERM="xterm-256color"
vi .vimrc
set t_Co=256
색 구성 표 작성
==============
~/.vim/colors
현재 jellybeans.vim 구성 됨
cd .vim/colors
wget https://github.com/w0ng/vim-hybrid/blob/master/colors/hybrid.vim
cd ~/.vim/bundle
git clone git://github.com/altercation/vim-colors-solarized.git
mv vim-colors-solarized ~/.vim/bundle/
어두운 배경 설정
syntax enable
set background=dark
colorscheme solarized
밝은 배경 설정
syntax enable
set background=light
colorscheme solarized
원하는 색상 지정
vi .vimrc
Plugin 'mrkn256.vim'
Plugin 'hybrid.vim'
GUI eclipse IDE 사용 방법 분석
=============================
https://wiki.eclipse.org/HowTo_use_the_CDT_to_navigate_Linux_kernel_source
taglist 설치
============
wget http://vim-taglist.sourceforge.net/ 최신 버전 다운로드
플러그인 적용
$ mkdir ~/.vim
$ unzip taglist.zip
스크립트 생성
vim mktrace.sh
#!/bin/sh
rm -rf cscope.files cscope.files
rm -rf tags
find . \( -name '*.c' -o -name '*.cpp' -o -name '*.cc' -o -name '*.h' -o -name '*.s' -o -name '*.S' -o -name '*.asm' \) -print > cscope.files
ctags -R
cscope -i cscope.files
.vimrc 설정
vi .vimrc
" cscope 설정
set csprg=/usr/bin/cscope
set csto=0
set cst
set nocsverb
if filereadable("./cscope.out")
cs add cscope.out
else
cs add /usr/src/linux/cscope.out
endif
set csverb
vim 셀 접근
: VimShell
창 분할
vs, sp
vimrc 설정 내용
.vimrc
set nocompatible " 오리지날 VI와 호환하지 않음
set autoindent " 자동 들여쓰기
set cindent " C 프로그래밍용 자동 들여쓰기
set smartindent " 스마트한 들여쓰기
set wrap
set nowrapscan " 검색할 때 문서의 끝에서 처음으로 안돌아감
set nobackup " 백업 파일을 안만듬
set noswapfile
set ruler " 화면 우측 하단에 현재 커서의 위치(줄,칸) 표시
set shiftwidth=4 " 자동 들여쓰기 4칸
set number " 행번호 표시, set nu 도 가능
set fencs=ucs-bom,utf-8,euc-kr.latin1 " 한글 파일은 euc-kr로, 유니코드는 유니코드로
set fileencoding=utf-8 " 파일저장인코딩
set tenc=utf-8 " 터미널 인코딩
set hlsearch " 검색어 강조, set hls 도 가능
set ignorecase " 검색시 대소문자 무시, set ic 도 가능
set tabstop=4 " 탭을 4칸으로
set lbr
set incsearch " 키워드 입력시 점진적 검색
set cursorline " 편집 위치에 커서 라인 설정
set laststatus=2 " 상태바 표시를 항상한다
syntax on " 구문강조 사용
filetype indent on " 파일 종류에 따른 구문강조
set background=dark " 하이라이팅 lihgt / dark
colorscheme jellybeans " vi 색상 테마 설정
set backspace=eol,start,indent " 줄의 끝, 시작, 들여쓰기에서 백스페이스시 이전줄로
set history=1000 " vi 편집기록 기억갯수 .viminfo에 기록
highlight Comment term=bold cterm=bold ctermfg=4 " 코멘트 하이라이트
set mouse=a " vim에서 마우스 사용
set t_Co=256 " 색 조정
set background=dark
colorscheme hybrid
set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'Tagbar'
" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
" 바닥글
Plugin 'vim-airline/vim-airline'
" 바닥글 추가, 삭제, 변경 정보 확인.
Plugin 'tpope/vim-fugitive'
" 문법 체크
Plugin 'scrooloose/syntastic'
" IDE 파일 Tree
Plugin 'nerdtree'
" git 관리 파일 변경 부분 확인
Plugin 'airblade/vim-gitgutter'
" 색상 테마 적용
Plugin 'nanotech/jellybeans.vim'
Plugin 'mrkn256.vim'
Plugin 'hybrid.vim'
" 커피스크립트 Synatx
Plugin 'kchmck/vim-coffee-script'
Plugin 'DoxygenToolkit.vim'
" vimshell
Plugin 'shougo/vimshell.vim'
Plugin 'vimproc.vim'
Plugin 'kernel-coding-style'
Plugin 'unite.vim'
Plugin 'bogado/file-line'
Plugin 'cscope-maps'
call vundle#end() " required
filetype plugin indent on " required
execute pathogen#infect()
" 키 맵핑
" <F1> 폴딩
"map <F1> v]}zf
map <F1> :tabnew<cr>
" <F2> 창이동
map <F2> <C-w><C-w>
" <F3> NERDTree
map <F3> :NERDTreeToggle<cr>
" <F4> Tlist
"map <F4> :Tlist<cr>
map <F4> :TagbarToggle<cr>
" <F5> [i 정의 내용 보여주기
map <F5> [i
" <F6> gd 변수 선언으로 이동
map <F6> gd
" <F7> shell
map <F7> :VimShell<cr>
" <F8> Dox
map <F8> :Dox<cr>
" bnext, bprev
map <F11> :bp<cr>
map <F12> :bn<cr>
" tabn
map <S-Tab> gt<cr>
" bnext
map <S-F1> :bnext<cr>
" shift + p키에 파일 검색을 등록하고 shift + b에 buffer 목록 열기
nmap <S-p> :Unite file_rec/async<cr>
nmap <S-b> :Unite buffer<cr>
color jellybeans
set csverb
" 열 81 수직 적용(커널 코딩은 줄 길이를 최대 80 문자로 유지해야 함)
" 80 characters line
set colorcolumn=81
execute "set colorcolumn=" . join(range(81,335), ',')
highlight ColorColumn ctermbg=Black ctermfg=DarkRed
" 80 열 이상을 강조 표시하려면 "execute "set colorcolumn=" . join(range(81,335), ',') 주석 처리 해제.
"
" 후행 공백은 커널 코딩 스타일에 의해 금지되므로 강조 표시 할 수 있다.
" Highlight trailing spaces
" http://vim.wikia.com/wiki/Highlight_unwanted_spaces
highlight ExtraWhitespace ctermbg=red guibg=red
match ExtraWhitespace /\s\+$/
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches()
set nocompatible " 오리지날 VI와 호환하지 않음
set autoindent " 자동 들여쓰기
set cindent " C 프로그래밍용 자동 들여쓰기
set smartindent " 스마트한 들여쓰기
set wrap
set nowrapscan " 검색할 때 문서의 끝에서 처음으로 안돌아감
set nobackup " 백업 파일을 안만듬
set noswapfile
set ruler " 화면 우측 하단에 현재 커서의 위치(줄,칸) 표시
set shiftwidth=4 " 자동 들여쓰기 4칸
set number " 행번호 표시, set nu 도 가능
set fencs=ucs-bom,utf-8,euc-kr.latin1 " 한글 파일은 euc-kr로, 유니코드는 유니코드로
set fileencoding=utf-8 " 파일저장인코딩
set tenc=utf-8 " 터미널 인코딩
set hlsearch " 검색어 강조, set hls 도 가능
set ignorecase " 검색시 대소문자 무시, set ic 도 가능
set tabstop=4 " 탭을 4칸으로
set lbr
set incsearch " 키워드 입력시 점진적 검색
set cursorline " 편집 위치에 커서 라인 설정
set laststatus=2 " 상태바 표시를 항상한다
syntax on " 구문강조 사용
filetype indent on " 파일 종류에 따른 구문강조
set background=dark " 하이라이팅 lihgt / dark
colorscheme jellybeans " vi 색상 테마 설정
set backspace=eol,start,indent " 줄의 끝, 시작, 들여쓰기에서 백스페이스시 이전줄로
set history=1000 " vi 편집기록 기억갯수 .viminfo에 기록
highlight Comment term=bold cterm=bold ctermfg=4 " 코멘트 하이라이트
set mouse=a " vim에서 마우스 사용
set t_Co=256 " 색 조정
set background=dark
colorscheme hybrid
set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'Tagbar'
" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
" 바닥글
Plugin 'vim-airline/vim-airline'
" 바닥글 추가, 삭제, 변경 정보 확인.
Plugin 'tpope/vim-fugitive'
" 문법 체크
Plugin 'scrooloose/syntastic'
" IDE 파일 Tree
Plugin 'nerdtree'
" git 관리 파일 변경 부분 확인
Plugin 'airblade/vim-gitgutter'
" 색상 테마 적용
Plugin 'nanotech/jellybeans.vim'
Plugin 'mrkn256.vim'
Plugin 'hybrid.vim'
" 커피스크립트 Synatx
Plugin 'kchmck/vim-coffee-script'
Plugin 'DoxygenToolkit.vim'
" vimshell
Plugin 'shougo/vimshell.vim'
Plugin 'vimproc.vim'
Plugin 'kernel-coding-style'
Plugin 'unite.vim'
Plugin 'bogado/file-line'
Plugin 'cscope-maps'
call vundle#end() " required
filetype plugin indent on " required
execute pathogen#infect()
" 키 맵핑
" <F1> 폴딩
"map <F1> v]}zf
map <F1> :tabnew<cr>
" <F2> 창이동
map <F2> <C-w><C-w>
" <F3> NERDTree
map <F3> :NERDTreeToggle<cr>
" <F4> Tlist
"map <F4> :Tlist<cr>
map <F4> :TagbarToggle<cr>
" <F5> [i 정의 내용 보여주기
map <F5> [i
" <F6> gd 변수 선언으로 이동
map <F6> gd
" <F7> shell
map <F7> :VimShell<cr>
" <F8> Dox
map <F8> :Dox<cr>
" bnext, bprev
map <F11> :bp<cr>
map <F12> :bn<cr>
" tabn
map <S-Tab> gt<cr>
" bnext
map <S-F1> :bnext<cr>
" shift + p키에 파일 검색을 등록하고 shift + b에 buffer 목록 열기
nmap <S-p> :Unite file_rec/async<cr>
nmap <S-b> :Unite buffer<cr>
color jellybeans
set csverb
" 열 81 수직 적용(커널 코딩은 줄 길이를 최대 80 문자로 유지해야 함)
" 80 characters line
set colorcolumn=81
execute "set colorcolumn=" . join(range(81,335), ',')
highlight ColorColumn ctermbg=Black ctermfg=DarkRed
" 80 열 이상을 강조 표시하려면 "execute "set colorcolumn=" . join(range(81,335), ',') 주석 처리 해제.
"
" 후행 공백은 커널 코딩 스타일에 의해 금지되므로 강조 표시 할 수 있다.
" Highlight trailing spaces
" http://vim.wikia.com/wiki/Highlight_unwanted_spaces
highlight ExtraWhitespace ctermbg=red guibg=red
match ExtraWhitespace /\s\+$/
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches()
2018/12/10
Linux system programming 시스템 콜
리눅스 시스템 호출 흐름도
Application Program
1. Read(fd, buffer, count);
2. glib wrapper funciton
read(...){
syscall(SYS_read,fd,buff,count),
...
}
3. Trap Handler
system_call
---
---
---
4. System call Service routine
SYS_read(){
---
---
return error
}
응답은 역순
4. System call Service routine
SYS_read(){
---
---
return error
}
3. Trap Handler
system_call
---
---
---
2. glib wrapper funciton
read(...){
syscall(SYS_read,fd,buff,count),
...
}
1. Read(fd, buffer, count);
Compile
=========
Source code file(S)
gcc -E hello.c 1> hello.i
Preprocessed code file(s)
gcc -S hello.i
Assembly code(s)
gcc -c hello.s
Linked(ld)
gcc -hello.o -o myexe
Executable file (myexe)
특정 형식의 실행 가능 이미지로 2 차 저장소에 저장
Loader
Process Address Space in main memory
메인 메모리의 주소 공간 처리
버전 확인.
shell> gcc --version
hellow.c
shell> cat hellow.c
#include <stdio.h>
int main(){
printf("Welcome to system Programming with Korea HeaNam...\n");
return 0;
}
compile: 전처리 정보 확인 컴파일
shell> gcc -E hellow.c 1> hello.i
생성된 파일 확인
shell> less hello.i
전처리 위치
shell> ls /usr/include
어셈블러 버전 지정 컴파일
shell> gcc -S hello.i -std=c11
-std=c11 버전 확인
shell> man 7 standards
디버깅 활성화 컴파일
shell> gcc -c -ggdb hello.s
hello.o 오브젝트 파일 생성.
라이브러리 확인
shell> man 7 libc
cd /usr/lib/x86_64-linux-gnu
동적 라이브 러리 검색
shell> ls | grep libc.so
정적 라이브 러리 검색
shell> ls | grep libc.a
printf 라이브 러리 확인
shell> ar -t libc.a | grep printf.o
실행 파일 동적 라이브러리 사용 생성 -lc==lib c 기본 경로 연결
shell> gcc hello.c -o dynamicexe -lc
실행 파일 정적 라이브러리 사용 생성 --static
shell> gcc hello.c -o staticexe -lc --static
크기 확인
shell> ls -lh dynamicexe staticexe
-rwxrwxr-x 1 linuxlee linuxlee 8.2K 12월 9 23:13 dynamicexe
-rwxrwxr-x 1 linuxlee linuxlee 825K 12월 9 23:13 staticexe
오브젝트 파일 형식 분석
======================
오브젝트 elf 파일 형식 -h 헤더 내용 추출
shell> readelf -h hello.o
오브텍트 elf 파일 형식 -a 전체 내용 추출
shell> readelf -a hello.o
오브텍트 elf 파일 형식 -S 섹션 내용 추출
shell> readelf -S hello.o
헤더 덤프
shell> objdump -h hello.o
디버그 덤프
shell> objdump -D hello.o
가단하게 덤프
shell> objdump -d hello.o
머신 지정 덤프
shell> objdump -d -M intel hello.o
gdb
===
shell> gcc -ggdb hello.c
shell> gdb -q ./a.out
메인 세션 어셈블러 확인
(gdb) disassemble main
Dump of assembler code for function main:
0x000000000000063a <+0>: push %rbp
0x000000000000063b <+1>: mov %rsp,%rbp
0x000000000000063e <+4>: lea 0xa3(%rip),%rdi # 0x6e8
0x0000000000000645 <+11>: callq 0x510 <puts@plt>
0x000000000000064a <+16>: mov $0x0,%eax
0x000000000000064f <+21>: pop %rbp
0x0000000000000650 <+22>: retq
End of assembler dump.
머신 CPU 지정 어셈블러 확인
(gdb) set disassembly-flavor intel
(gdb) disassemble main
Dump of assembler code for function main:
0x000000000000063a <+0>: push rbp
0x000000000000063b <+1>: mov rbp,rsp
0x000000000000063e <+4>: lea rdi,[rip+0xa3] # 0x6e8
0x0000000000000645 <+11>: call 0x510 <puts@plt>
0x000000000000064a <+16>: mov eax,0x0
0x000000000000064f <+21>: pop rbp
0x0000000000000650 <+22>: ret
End of assembler dump.
레지스터 확인
(gdb) break main
Breakpoint 1 at 0x63e: file hello.c, line 4.
(gdb) run
Starting program: /home/linuxlee/language/systemprogramming/01/a.out
Breakpoint 1, main () at hello.c:4
4 printf("Welcome to system Programming with Korea HeaNam...\n");
(gdb) info registers
rax 0x55555555463a 93824992233018
rbx 0x0 0
rcx 0x555555554660 93824992233056
rdx 0x7fffffffdc98 140737488346264
rsi 0x7fffffffdc88 140737488346248
rdi 0x1 1
rbp 0x7fffffffdba0 0x7fffffffdba0
rsp 0x7fffffffdba0 0x7fffffffdba0
r8 0x7ffff7dd0d80 140737351847296
r9 0x7ffff7dd0d80 140737351847296
r10 0x2 2
r11 0x3 3
r12 0x555555554530 93824992232752
r13 0x7fffffffdc80 140737488346240
r14 0x0 0
r15 0x0 0
rip 0x55555555463e 0x55555555463e <main+4>
eflags 0x246 [ PF ZF IF ]
cs 0x33 51
ss 0x2b 43
ds 0x0 0
es 0x0 0
fs 0x0 0
gs 0x0 0
전체 레지스터 확인(실수 연산 확인)
(gdb) info all-registers
(gdb) c
Continuing.
Welcome to system Programming with Korea HeaNam...
[Inferior 1 (process 22554) exited normally]
(gdb) q
메모리 맵 확인
shell> readelf -h hello.o
shell> readelf -S hello.o
시스템 콜 프로그램
==============
1:일반 명령어
2:시스템 호출
3:C 표준 라이브러리 함수들
4:특수 파일 (보통 /dev 에서 발견되는 장치 파일)과 드라이버
5:파일 형식과 convensions
6:게임과 화면 보호기
7:기타
8:시스템 관리 명령어와 데몬
시스템 콜 맨 페이지
man 2 intro
man syscalls
man 2 write
기본 함수 사용 시스템 콜
======================
shell> vi wrapper_lee.c
#include <unistd.h>
int main(void){
char str[] = {"Welcome to System Programming with Korea HeaNam...\n"};
int rv = write(1, str, sizeof str);
return rv;
}
shell> gcc wrapper_lee.c
./a.out
Welcome to System Programming with Korea HeaNam...
shell> echo $?
52
소스 코드 return rv; 를 돌려준 값이다.
syscall 함수 사용
===================
shell> man 2 sycall
x86-64 rdi rsi rdx r10 r8 r9 -
shell> less /usr/include/x86_64-linux-gnu/asm/unistd_64.h
shell> cat syscall.c
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
int main(void){
char str[]={"Welcome to System Programming with Korea HeaNam...\n"};
int rv = syscall(1, 1, str, sizeof str);
return rv;
}
shell> gcc syscall.c
shell> a.out
Welcome to System Programming with Korea HeaNam...
shell> echo $?
52
assembly system write call
===========================
shell> gcc -o syscall.c
shell> ./a.out
shell> echo $?
52
cat syscall.nasm
global main
SECTION .data
msg: db "Welcome to System Programming with Korea HeaNam...", 0Ah, 0h
len_msg: equ $ - msg
SECTION .text
main:
mov rax,1
mov rdi,1
mov rsi,msg
mov rdx,len_msg
syscall ; write(1, msg, len_msg);
mov r15, rax
mov rax,60
mov rdi,r15
syscall ; exit(52)
shell> nasm -f elf64 syscall.nasm
shell> ld syscall.o -o myexe1
shell> myexe1
Welcome to System Programming with Korea HeaNam...
shell> echo $?
52
Application Program
1. Read(fd, buffer, count);
2. glib wrapper funciton
read(...){
syscall(SYS_read,fd,buff,count),
...
}
3. Trap Handler
system_call
---
---
---
4. System call Service routine
SYS_read(){
---
---
return error
}
응답은 역순
4. System call Service routine
SYS_read(){
---
---
return error
}
3. Trap Handler
system_call
---
---
---
2. glib wrapper funciton
read(...){
syscall(SYS_read,fd,buff,count),
...
}
1. Read(fd, buffer, count);
Compile
=========
Source code file(S)
gcc -E hello.c 1> hello.i
Preprocessed code file(s)
gcc -S hello.i
Assembly code(s)
gcc -c hello.s
Linked(ld)
gcc -hello.o -o myexe
Executable file (myexe)
특정 형식의 실행 가능 이미지로 2 차 저장소에 저장
Loader
Process Address Space in main memory
메인 메모리의 주소 공간 처리
버전 확인.
shell> gcc --version
hellow.c
shell> cat hellow.c
#include <stdio.h>
int main(){
printf("Welcome to system Programming with Korea HeaNam...\n");
return 0;
}
compile: 전처리 정보 확인 컴파일
shell> gcc -E hellow.c 1> hello.i
생성된 파일 확인
shell> less hello.i
전처리 위치
shell> ls /usr/include
어셈블러 버전 지정 컴파일
shell> gcc -S hello.i -std=c11
-std=c11 버전 확인
shell> man 7 standards
디버깅 활성화 컴파일
shell> gcc -c -ggdb hello.s
hello.o 오브젝트 파일 생성.
라이브러리 확인
shell> man 7 libc
cd /usr/lib/x86_64-linux-gnu
동적 라이브 러리 검색
shell> ls | grep libc.so
정적 라이브 러리 검색
shell> ls | grep libc.a
printf 라이브 러리 확인
shell> ar -t libc.a | grep printf.o
실행 파일 동적 라이브러리 사용 생성 -lc==lib c 기본 경로 연결
shell> gcc hello.c -o dynamicexe -lc
실행 파일 정적 라이브러리 사용 생성 --static
shell> gcc hello.c -o staticexe -lc --static
크기 확인
shell> ls -lh dynamicexe staticexe
-rwxrwxr-x 1 linuxlee linuxlee 8.2K 12월 9 23:13 dynamicexe
-rwxrwxr-x 1 linuxlee linuxlee 825K 12월 9 23:13 staticexe
오브젝트 파일 형식 분석
======================
오브젝트 elf 파일 형식 -h 헤더 내용 추출
shell> readelf -h hello.o
오브텍트 elf 파일 형식 -a 전체 내용 추출
shell> readelf -a hello.o
오브텍트 elf 파일 형식 -S 섹션 내용 추출
shell> readelf -S hello.o
헤더 덤프
shell> objdump -h hello.o
디버그 덤프
shell> objdump -D hello.o
가단하게 덤프
shell> objdump -d hello.o
머신 지정 덤프
shell> objdump -d -M intel hello.o
gdb
===
shell> gcc -ggdb hello.c
shell> gdb -q ./a.out
메인 세션 어셈블러 확인
(gdb) disassemble main
Dump of assembler code for function main:
0x000000000000063a <+0>: push %rbp
0x000000000000063b <+1>: mov %rsp,%rbp
0x000000000000063e <+4>: lea 0xa3(%rip),%rdi # 0x6e8
0x0000000000000645 <+11>: callq 0x510 <puts@plt>
0x000000000000064a <+16>: mov $0x0,%eax
0x000000000000064f <+21>: pop %rbp
0x0000000000000650 <+22>: retq
End of assembler dump.
머신 CPU 지정 어셈블러 확인
(gdb) set disassembly-flavor intel
(gdb) disassemble main
Dump of assembler code for function main:
0x000000000000063a <+0>: push rbp
0x000000000000063b <+1>: mov rbp,rsp
0x000000000000063e <+4>: lea rdi,[rip+0xa3] # 0x6e8
0x0000000000000645 <+11>: call 0x510 <puts@plt>
0x000000000000064a <+16>: mov eax,0x0
0x000000000000064f <+21>: pop rbp
0x0000000000000650 <+22>: ret
End of assembler dump.
레지스터 확인
(gdb) break main
Breakpoint 1 at 0x63e: file hello.c, line 4.
(gdb) run
Starting program: /home/linuxlee/language/systemprogramming/01/a.out
Breakpoint 1, main () at hello.c:4
4 printf("Welcome to system Programming with Korea HeaNam...\n");
(gdb) info registers
rax 0x55555555463a 93824992233018
rbx 0x0 0
rcx 0x555555554660 93824992233056
rdx 0x7fffffffdc98 140737488346264
rsi 0x7fffffffdc88 140737488346248
rdi 0x1 1
rbp 0x7fffffffdba0 0x7fffffffdba0
rsp 0x7fffffffdba0 0x7fffffffdba0
r8 0x7ffff7dd0d80 140737351847296
r9 0x7ffff7dd0d80 140737351847296
r10 0x2 2
r11 0x3 3
r12 0x555555554530 93824992232752
r13 0x7fffffffdc80 140737488346240
r14 0x0 0
r15 0x0 0
rip 0x55555555463e 0x55555555463e <main+4>
eflags 0x246 [ PF ZF IF ]
cs 0x33 51
ss 0x2b 43
ds 0x0 0
es 0x0 0
fs 0x0 0
gs 0x0 0
전체 레지스터 확인(실수 연산 확인)
(gdb) info all-registers
(gdb) c
Continuing.
Welcome to system Programming with Korea HeaNam...
[Inferior 1 (process 22554) exited normally]
(gdb) q
메모리 맵 확인
shell> readelf -h hello.o
shell> readelf -S hello.o
시스템 콜 프로그램
==============
1:일반 명령어
2:시스템 호출
3:C 표준 라이브러리 함수들
4:특수 파일 (보통 /dev 에서 발견되는 장치 파일)과 드라이버
5:파일 형식과 convensions
6:게임과 화면 보호기
7:기타
8:시스템 관리 명령어와 데몬
시스템 콜 맨 페이지
man 2 intro
man syscalls
man 2 write
기본 함수 사용 시스템 콜
======================
shell> vi wrapper_lee.c
#include <unistd.h>
int main(void){
char str[] = {"Welcome to System Programming with Korea HeaNam...\n"};
int rv = write(1, str, sizeof str);
return rv;
}
shell> gcc wrapper_lee.c
./a.out
Welcome to System Programming with Korea HeaNam...
shell> echo $?
52
소스 코드 return rv; 를 돌려준 값이다.
syscall 함수 사용
===================
shell> man 2 sycall
x86-64 rdi rsi rdx r10 r8 r9 -
shell> less /usr/include/x86_64-linux-gnu/asm/unistd_64.h
shell> cat syscall.c
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
int main(void){
char str[]={"Welcome to System Programming with Korea HeaNam...\n"};
int rv = syscall(1, 1, str, sizeof str);
return rv;
}
shell> gcc syscall.c
shell> a.out
Welcome to System Programming with Korea HeaNam...
shell> echo $?
52
assembly system write call
===========================
shell> gcc -o syscall.c
shell> ./a.out
shell> echo $?
52
cat syscall.nasm
global main
SECTION .data
msg: db "Welcome to System Programming with Korea HeaNam...", 0Ah, 0h
len_msg: equ $ - msg
SECTION .text
main:
mov rax,1
mov rdi,1
mov rsi,msg
mov rdx,len_msg
syscall ; write(1, msg, len_msg);
mov r15, rax
mov rax,60
mov rdi,r15
syscall ; exit(52)
shell> nasm -f elf64 syscall.nasm
shell> ld syscall.o -o myexe1
shell> myexe1
Welcome to System Programming with Korea HeaNam...
shell> echo $?
52
2018/12/09
asm keyboard input
section .data
text1 db "what is you name? "
text2 db "Hello, "
section .bss
name resb 16
section .text
global _start
_start:
call _printText1
call _getName
call _printText2
call _printName
mov rax, 60
mov rdi, 0
syscall
_getName:
mov rax, 0
mov rdi, 0
mov rsi, name
mov rdx, 16
syscall
ret
_printText1:
mov rax, 1
mov rdi, 1
mov rsi, text1
mov rdx, 18
syscall
ret
_printText2:
mov rax, 1
mov rdi, 1
mov rsi, text2
mov rdx, 7
syscall
ret
_printName:
mov rax, 1
mov rdi, 1
mov rsi, name
mov rdx, 16
syscall
ret
text1 db "what is you name? "
text2 db "Hello, "
section .bss
name resb 16
section .text
global _start
_start:
call _printText1
call _getName
call _printText2
call _printName
mov rax, 60
mov rdi, 0
syscall
_getName:
mov rax, 0
mov rdi, 0
mov rsi, name
mov rdx, 16
syscall
ret
_printText1:
mov rax, 1
mov rdi, 1
mov rsi, text1
mov rdx, 18
syscall
ret
_printText2:
mov rax, 1
mov rdi, 1
mov rsi, text2
mov rdx, 7
syscall
ret
_printName:
mov rax, 1
mov rdi, 1
mov rsi, name
mov rdx, 16
syscall
ret
; compile : nasm -f elf64 input_hello.asm -o input_hello.o
; ld input_hello.o -o input_hello
asm 이동, 호출, 비교
1. Flags
• 플래그는 레지스터와 마찬가지로 데이터를 보유한다.
• 플래그는 1 비트 씩만 보유한다. false 또는 True
• 개별 플래그는 더 큰 레지스터의 일부임.
2. Pointers
• 포인터 레지스터 또한 데이터를 보유한다.
• 포인터가 데이터를 가리키면, 메모리 주소를 보유한다는 것을 의미한다.
3. Control Flow
• 모든 코드는 기본적으로 위에서 아래로 실행된다. 프로그램이 흐르는 방향을 제어 흐름이라고 한다.
• 추출 레지스터 rip는 실행될 다음 명령어의 주소를 보유한다. 각 명령 후, 제어 흐름이 위에서 자연스럽게 흐르도록 1 씩 증가한다.
4. Jump
• jump를 사용하면 레이블 기반으로 다른 코드 부분으로 이동할 수 있다.
• jump는 프로그램 흐름을 전환하는데 사용한다.
• jmp lable <- rip 레지스터에 "label" 값으로 로드한다.
5. Comparisons
• 비교를 통해 프로그램을 특정 조건에 따라 다른 경로를 취할 수 있다.
• 비교는 레지스터에서 수행.
• 비교 일반적 형식
cmp register, register/value
cmp rax, 23
cmp rax, rbx
5.1 Comparisons with Flags
• 비교가 이루어지면 특정 플래그가 설정된다.
5.2 Conditional Jumps
• 비교가 이루어지면 조건부 점프를 할 수 있다.
• 코드의 조건부 점프는 jump 작성 되며, jmp로 대체할 수 있다.
• 아래 코드 rax 레지스터의 값이 23인 경우에만 “_doThis” 레이블의 주소로 이동하다.
cmp rax, 23
je _doThis
• 아래 코드 rax 레지스터의 값이 rbx 레지스트의 값보다 큰 경우에만 레이블 “_doThis”의 주소로 이동한다.
cmp rax, rbx
jg _doThis
6. Registers as Pointers
기본 레지스터는 포인터로 처리 될 수 있다.
레지스터를 포인터로 처리하려면 “rax”가 “[rax]” 되도록 레지스터 이름을 대괄호로 묶는다.
mov rax, rbx
rbx 레지스터의 값을 rax 레지스터에 로드한다.
mov rax, rbx
rbx 레지스터의 값을 rax 레지스터에 로드한다.
mov rax, [rbx]
rbx 레지스터가 가리키는 값을 rax 레지스터에 로드한다.
7. Calls
• 호출은 점프와 본질적 동일한 모양을 가진다.
• “call”을 사용하면 호출이 이루어진 원래 위치는 “ret”를 사용해 반환한다.
• print 코드 부분 “Hello, World” 자체 섹션으로 이동 후 해당 섹션이 호출 된다.
• 이를 서부 루틴 이라 한다.
• 플래그는 레지스터와 마찬가지로 데이터를 보유한다.
• 플래그는 1 비트 씩만 보유한다. false 또는 True
• 개별 플래그는 더 큰 레지스터의 일부임.
| Flag Symbol | Description |
| CF | Carry |
| PF | Parity |
| ZF | Zero |
| SF | Sign |
| OF | Overflow |
| AF | Adjust |
| IF | Interrupt Enabled |
2. Pointers
• 포인터 레지스터 또한 데이터를 보유한다.
• 포인터가 데이터를 가리키면, 메모리 주소를 보유한다는 것을 의미한다.
| Pointer Name | Meaning | Description |
| rip (eip, ip) | Index pointer | 제어 흐름에서 실행될 다음 주소를 가리킴. |
| Rrsp (esp, sp) | Stack pointer | 스택의 최상위 주소 가리킴 |
| Rrbp (ebp, bp) | Stack base pointer | 스택의 맨 아래를 가리킴 |
…
|
…
|
...
|
• 모든 코드는 기본적으로 위에서 아래로 실행된다. 프로그램이 흐르는 방향을 제어 흐름이라고 한다.
• 추출 레지스터 rip는 실행될 다음 명령어의 주소를 보유한다. 각 명령 후, 제어 흐름이 위에서 자연스럽게 흐르도록 1 씩 증가한다.
4. Jump
• jump를 사용하면 레이블 기반으로 다른 코드 부분으로 이동할 수 있다.
• jump는 프로그램 흐름을 전환하는데 사용한다.
• jmp lable <- rip 레지스터에 "label" 값으로 로드한다.
5. Comparisons
• 비교를 통해 프로그램을 특정 조건에 따라 다른 경로를 취할 수 있다.
• 비교는 레지스터에서 수행.
• 비교 일반적 형식
cmp register, register/value
cmp rax, 23
cmp rax, rbx
5.1 Comparisons with Flags
• 비교가 이루어지면 특정 플래그가 설정된다.
cmp
a, b
|
|
a=b
|
ZF
= 1
|
A
!= b
|
ZF
= 0
|
-
|
SF
= msb(a-b
|
...
|
...
|
5.2 Conditional Jumps
• 비교가 이루어지면 조건부 점프를 할 수 있다.
• 코드의 조건부 점프는 jump 작성 되며, jmp로 대체할 수 있다.
Jump
symbol(signed)
|
Jump
symbol(unsigned)
|
Results
of cmp a,b
|
je
|
-
|
a
= b
|
jne
|
-
|
a
!= b
|
jg
|
ja
|
a
> b
|
jge
|
jae
|
a
>= b
|
ji
|
jb
|
a
< b
|
jle
|
jbe
|
a
<= b
|
jz
|
-
|
a
= 0
|
jnz
|
-
|
a
!= 0
|
jo
|
-
|
Overflow
occurred
|
jno
|
-
|
Overflow
did not occur
|
js
|
-
|
jump
if signed
|
jns
|
-
|
jump
if not signed
|
cmp rax, 23
je _doThis
• 아래 코드 rax 레지스터의 값이 rbx 레지스트의 값보다 큰 경우에만 레이블 “_doThis”의 주소로 이동한다.
cmp rax, rbx
jg _doThis
6. Registers as Pointers
기본 레지스터는 포인터로 처리 될 수 있다.
레지스터를 포인터로 처리하려면 “rax”가 “[rax]” 되도록 레지스터 이름을 대괄호로 묶는다.
mov rax, rbx
rbx 레지스터의 값을 rax 레지스터에 로드한다.
mov rax, rbx
rbx 레지스터의 값을 rax 레지스터에 로드한다.
mov rax, [rbx]
rbx 레지스터가 가리키는 값을 rax 레지스터에 로드한다.
7. Calls
• 호출은 점프와 본질적 동일한 모양을 가진다.
• “call”을 사용하면 호출이 이루어진 원래 위치는 “ret”를 사용해 반환한다.
• print 코드 부분 “Hello, World” 자체 섹션으로 이동 후 해당 섹션이 호출 된다.
• 이를 서부 루틴 이라 한다.
C 구조체 재 사용 설정 추가 위치 접근
#include <stdio.h>
struct catsFavs{
char *food;
char *friend;
};
typedef struct cat{
const char *name;
const char *breed;
int avgHeightCm;
int avgWeightLbs;
struct catsFavs favoriteThings;
} cat;
void getCatFavs(cat theCat){
printf("\n");
printf("%s loves %s and his friend is %s\n\n",
theCat.name,
theCat.favoriteThings.food,
theCat.favoriteThings.friend);
}
void setCatWeightPtr(cat *theCat, int newWeight){
(*theCat).avgWeightLbs = newWeight;
printf("The weight was changed to %d\n\n", (*theCat).avgWeightLbs);
printf("The weight was changed to %d\n\n", theCat->avgWeightLbs);
}
void main(void){
cat juju = {"juju", "persian", 25, 9, {"meat", "joe camp"}};
setCatWeightPtr(&juju, 11);
printf("The Weight in Main() %d\n\n", juju.avgWeightLbs);
}
struct catsFavs{
char *food;
char *friend;
};
typedef struct cat{
const char *name;
const char *breed;
int avgHeightCm;
int avgWeightLbs;
struct catsFavs favoriteThings;
} cat;
void getCatFavs(cat theCat){
printf("\n");
printf("%s loves %s and his friend is %s\n\n",
theCat.name,
theCat.favoriteThings.food,
theCat.favoriteThings.friend);
}
void setCatWeightPtr(cat *theCat, int newWeight){
(*theCat).avgWeightLbs = newWeight;
printf("The weight was changed to %d\n\n", (*theCat).avgWeightLbs);
printf("The weight was changed to %d\n\n", theCat->avgWeightLbs);
}
void main(void){
cat juju = {"juju", "persian", 25, 9, {"meat", "joe camp"}};
setCatWeightPtr(&juju, 11);
printf("The Weight in Main() %d\n\n", juju.avgWeightLbs);
}
C 구조체 재 추가 사용 설정
#include <stdio.h>
struct catsFavs {
char *food;
char *friend;
};
typedef struct cat {
const char *name;
const char *breed;
int avaHeightCm;
int avgWeightLbs;
struct catsFavs favoriteThings;
} cat;
void getCatFavs(cat theCat){
printf("\n");
printf("%s loves %s and his friend is %s\n\n",
theCat.name,
theCat.favoriteThings.food,
theCat.favoriteThings.friend);
}
void setCatWeight(cat theCat, int newWeight){
theCat.avgWeightLbs = newWeight;
printf("The weight was changed to %d\n\n", theCat.avgWeightLbs);
}
void main(void){
cat juju = {"Juju", "Persian", 25, 9, {"meat", "joe Camp"}};
getCatFavs(juju);
setCatWeight(juju, 11);
printf("The Weight in Main() %d\n\n", juju.avgWeightLbs);
}
struct catsFavs {
char *food;
char *friend;
};
typedef struct cat {
const char *name;
const char *breed;
int avaHeightCm;
int avgWeightLbs;
struct catsFavs favoriteThings;
} cat;
void getCatFavs(cat theCat){
printf("\n");
printf("%s loves %s and his friend is %s\n\n",
theCat.name,
theCat.favoriteThings.food,
theCat.favoriteThings.friend);
}
void setCatWeight(cat theCat, int newWeight){
theCat.avgWeightLbs = newWeight;
printf("The weight was changed to %d\n\n", theCat.avgWeightLbs);
}
void main(void){
cat juju = {"Juju", "Persian", 25, 9, {"meat", "joe Camp"}};
getCatFavs(juju);
setCatWeight(juju, 11);
printf("The Weight in Main() %d\n\n", juju.avgWeightLbs);
}
C 구조체 선언 추가
#include <stdio.h>
struct catsFavs {
char *food;
char *friend;
};
typedef struct cat {
const char *name;
const char *breed;
int abaHeightCm;
int abgWeightLbs;
struct catsFavs favoriteThings;
} cat;
void getCatFavs(cat theCat){
printf("\n");
printf("%s loves %s and his friend is %s\n\n",
theCat.name,
theCat.favoriteThings.food,
theCat.favoriteThings.friend);
}
void main(void){
cat juju = {"Juju", "Persian", 25, 9, {"meat", "joe Camp"}};
getCatFavs(juju);
}
struct catsFavs {
char *food;
char *friend;
};
typedef struct cat {
const char *name;
const char *breed;
int abaHeightCm;
int abgWeightLbs;
struct catsFavs favoriteThings;
} cat;
void getCatFavs(cat theCat){
printf("\n");
printf("%s loves %s and his friend is %s\n\n",
theCat.name,
theCat.favoriteThings.food,
theCat.favoriteThings.friend);
}
void main(void){
cat juju = {"Juju", "Persian", 25, 9, {"meat", "joe Camp"}};
getCatFavs(juju);
}
C 구조체 자원 재사용 및 메모리 무작위 위치 확인
#include <stdio.h>
struct cat {
const char *name;
const char *breed;
int avgHeightCm;
int avgWeightLbs;
};
void getCatInfo(struct cat theCat){
printf("\n");
printf("Name: %s\n\n", theCat.name);
printf("Breed: %s\n\n", theCat.breed);
printf("Avg Height: %d cm\n\n", theCat.avgHeightCm);
printf("Avg Weight: %d lbs\n\n", theCat.avgWeightLbs);
}
void getMemoryLocations(struct cat theCat){
printf("Name Location: %s\n\n", theCat.name);
printf("Breed Location: %s\n\n", theCat.breed);
printf("Height Location: %d\n\n", &theCat.avgHeightCm);
printf("Weight Location: %d\n\n", &theCat.avgWeightLbs);
}
void main(void){
struct cat juju = {"Juju", "Persian", 45, 50};
getCatInfo(juju);
struct cat juju2 = juju;
getMemoryLocations(juju);
getMemoryLocations(juju2);
struct cat {
const char *name;
const char *breed;
int avgHeightCm;
int avgWeightLbs;
};
void getCatInfo(struct cat theCat){
printf("\n");
printf("Name: %s\n\n", theCat.name);
printf("Breed: %s\n\n", theCat.breed);
printf("Avg Height: %d cm\n\n", theCat.avgHeightCm);
printf("Avg Weight: %d lbs\n\n", theCat.avgWeightLbs);
}
void getMemoryLocations(struct cat theCat){
printf("Name Location: %s\n\n", theCat.name);
printf("Breed Location: %s\n\n", theCat.breed);
printf("Height Location: %d\n\n", &theCat.avgHeightCm);
printf("Weight Location: %d\n\n", &theCat.avgWeightLbs);
}
void main(void){
struct cat juju = {"Juju", "Persian", 45, 50};
getCatInfo(juju);
struct cat juju2 = juju;
getMemoryLocations(juju);
getMemoryLocations(juju2);
}
C 구조체 선언 및 호출
#include <stdio.h>
struct cat {
const char *name;
const char *breed;
int avgHeightCm;
int avgWeightLbs;
};
void getCatInfo(struct cat theCat){
printf("\n");
printf("Name: %s\n\n", theCat.name);
printf("Breed: %s\n\n", theCat.breed);
printf("Avg Height: %d cm\n\n", theCat.avgHeightCm);
printf("Avg Weight: %d lbs\n\n", theCat.avgWeightLbs);
}
void main(void){
struct cat juju = {"Juju", "persian", 45, 132};
getCatInfo(juju);
}
struct cat {
const char *name;
const char *breed;
int avgHeightCm;
int avgWeightLbs;
};
void getCatInfo(struct cat theCat){
printf("\n");
printf("Name: %s\n\n", theCat.name);
printf("Breed: %s\n\n", theCat.breed);
printf("Avg Height: %d cm\n\n", theCat.avgHeightCm);
printf("Avg Weight: %d lbs\n\n", theCat.avgWeightLbs);
}
void main(void){
struct cat juju = {"Juju", "persian", 45, 132};
getCatInfo(juju);
}
C 구조체 선언
#include <stdio.h>
struct cat {
const char *name;
const char *breed;
int avgHeightCm;
int avgWeightLbs;
};
int main(void){
struct cat juju = {"Juju", "Persian", 30, 164};
printf("name = %s\n\n", juju.name);
printf("species %s\n\n", juju.breed);
printf("Height = %dcm\n\n", juju.avgHeightCm);
printf("Weight = %dLb\n\n", juju.avgWeightLbs);
}
struct cat {
const char *name;
const char *breed;
int avgHeightCm;
int avgWeightLbs;
};
int main(void){
struct cat juju = {"Juju", "Persian", 30, 164};
printf("name = %s\n\n", juju.name);
printf("species %s\n\n", juju.breed);
printf("Height = %dcm\n\n", juju.avgHeightCm);
printf("Weight = %dLb\n\n", juju.avgWeightLbs);
}
C key value 에서 value 변경.
#include <stdio.h>
#include <stdlib.h>
void generateTwoRandomNums(int random1, int random2){
random1 = rand() % 50 + 1;
random2 = rand() % 50 + 1;
printf("New random1 in function = %d\n\n", random1);
printf("New random2 in function = %d\n\n", random2);
}
void pointerRandomNumbers(int* random1, int* random2){
*random1 = rand() % 50 + 1;
*random2 = rand() % 50 + 1;
printf("New random1 in pointer function = %d\n\n", *random1);
printf("New random2 in pointer function = %d\n\n", *random2);
}
void main(void){
int random1 = 0, random2 = 0;
generateTwoRandomNums(random1, random2);
printf("random1 = %d\n\n", random1);
printf("random2 = %d\n\n", random2);
random1 = 0, random2 = 0;
printf("Main Before Function Call\n\n");
printf("random1 = %d : random2 = %d\n\n", random1, random2);
pointerRandomNumbers(&random1, &random2);
printf("Main After Function Call\n\n");
printf("random1 = %d : random2 = %d\n\n", random1, random2);
}
#include <stdlib.h>
void generateTwoRandomNums(int random1, int random2){
random1 = rand() % 50 + 1;
random2 = rand() % 50 + 1;
printf("New random1 in function = %d\n\n", random1);
printf("New random2 in function = %d\n\n", random2);
}
void pointerRandomNumbers(int* random1, int* random2){
*random1 = rand() % 50 + 1;
*random2 = rand() % 50 + 1;
printf("New random1 in pointer function = %d\n\n", *random1);
printf("New random2 in pointer function = %d\n\n", *random2);
}
void main(void){
int random1 = 0, random2 = 0;
generateTwoRandomNums(random1, random2);
printf("random1 = %d\n\n", random1);
printf("random2 = %d\n\n", random2);
random1 = 0, random2 = 0;
printf("Main Before Function Call\n\n");
printf("random1 = %d : random2 = %d\n\n", random1, random2);
pointerRandomNumbers(&random1, &random2);
printf("Main After Function Call\n\n");
printf("random1 = %d : random2 = %d\n\n", random1, random2);
}
C key value
#include <stdio.h>
#include <stdlib.h>
void generateTwoRandomNums(int random1, int random2){
random1 = rand() % 50 + 1;
random2 = rand() % 50 + 1;
printf("New random1 in function = %d\n\n", random1);
printf("New random2 in function = %d\n\n", random2);
}
void pointerRandomNumbers(int* random1, int* random2){
*random1 = rand() % 50 + 1;
*random2 = rand() % 50 + 1;
printf("New random1 in pointer function = %d\n\n", *random1);
printf("New random2 in pointer function = %d\n\n", *random2);
}
void main(void){
int random1 = 0, random2 = 0;
generateTwoRandomNums(random1, random2);
printf("random1 = %d\n\n", random1);
printf("random2 = %d\n\n", random2);
random1 = 0, random2 = 0;
printf("Main Before Function Call\n\n");
printf("random1 = %d : random2 = %d\n\n", random1, random2);
pointerRandomNumbers(&random1, &random2);
printf("Main After Function Call\n\n");
printf("random1 = %d : random2 = %d\n\n", random1, random2);
}
#include <stdlib.h>
void generateTwoRandomNums(int random1, int random2){
random1 = rand() % 50 + 1;
random2 = rand() % 50 + 1;
printf("New random1 in function = %d\n\n", random1);
printf("New random2 in function = %d\n\n", random2);
}
void pointerRandomNumbers(int* random1, int* random2){
*random1 = rand() % 50 + 1;
*random2 = rand() % 50 + 1;
printf("New random1 in pointer function = %d\n\n", *random1);
printf("New random2 in pointer function = %d\n\n", *random2);
}
void main(void){
int random1 = 0, random2 = 0;
generateTwoRandomNums(random1, random2);
printf("random1 = %d\n\n", random1);
printf("random2 = %d\n\n", random2);
random1 = 0, random2 = 0;
printf("Main Before Function Call\n\n");
printf("random1 = %d : random2 = %d\n\n", random1, random2);
pointerRandomNumbers(&random1, &random2);
printf("Main After Function Call\n\n");
printf("random1 = %d : random2 = %d\n\n", random1, random2);
}
C 배열 선언 후 무작위 메모리 위치 값 확인(즉 2차 정보(목차) 생성)
#include <stdio.h>
void main(void){
int random1 = 23, random2 = 27;
printf("random1 = %p : random2 = %p\n\n", &random1, &random2);
printf("Size of int %ld\n\n", sizeof(int));
int * pRandom1 = &random1;
printf("Pointer %p\n\n", pRandom1);
printf("Value %ld\n\n", pRandom1);
printf("Value %d\n\n", *pRandom1);
int primeNumbers[] = {2,3,5,7};
printf("First index : %d\n\n", primeNumbers[0]);
printf("First index with * : %d\n\n", *primeNumbers);
printf("Second index with * : %d\n\n", *(primeNumbers + 1));
char * students[4] = {"Lee", "hyung", "young", "tae"};
for(int i = 0; i < 4; i++){
printf("key=%s : memory value=%ld\n\n", students[i], &students[i]);
}
}
void main(void){
int random1 = 23, random2 = 27;
printf("random1 = %p : random2 = %p\n\n", &random1, &random2);
printf("Size of int %ld\n\n", sizeof(int));
int * pRandom1 = &random1;
printf("Pointer %p\n\n", pRandom1);
printf("Value %ld\n\n", pRandom1);
printf("Value %d\n\n", *pRandom1);
int primeNumbers[] = {2,3,5,7};
printf("First index : %d\n\n", primeNumbers[0]);
printf("First index with * : %d\n\n", *primeNumbers);
printf("Second index with * : %d\n\n", *(primeNumbers + 1));
char * students[4] = {"Lee", "hyung", "young", "tae"};
for(int i = 0; i < 4; i++){
printf("key=%s : memory value=%ld\n\n", students[i], &students[i]);
}
}
C 무작위 할당된 메모리 위치 확인
#include <stdio.h>
void main(void){
int random1 = 18, random2 = 19;
printf("randl = %p\n\n : random2 = %p\n\n", &random1, &random2);
printf("Size of int %ld\n\n", sizeof(int));
int * pRandom1 = &random1;
printf("Pointer %p\n\n", pRandom1);
printf("Value %ld\n\n", pRandom1);
printf("Value %d\n\n", *pRandom1);
}
void main(void){
int random1 = 18, random2 = 19;
printf("randl = %p\n\n : random2 = %p\n\n", &random1, &random2);
printf("Size of int %ld\n\n", sizeof(int));
int * pRandom1 = &random1;
printf("Pointer %p\n\n", pRandom1);
printf("Value %ld\n\n", pRandom1);
printf("Value %d\n\n", *pRandom1);
}
C 메모리 자원 무작위 할당 확인.
#include <stdio.h>
#include <stdlib.h>
void main(void){
int random1 = 12, random2 = 15;
printf("random1 = %p : random2 = %p\n\n", &random1, &random2);
printf("random1 = %d : random2 = %d\n\n", &random1, &random2);
printf("Size of int %ld\n\n", sizeof(random1));
}
#include <stdlib.h>
void main(void){
int random1 = 12, random2 = 15;
printf("random1 = %p : random2 = %p\n\n", &random1, &random2);
printf("random1 = %d : random2 = %d\n\n", &random1, &random2);
printf("Size of int %ld\n\n", sizeof(random1));
}
피드 구독하기:
글 (Atom)
