[컴][웹] 간단하게 주기적으로 message 를 수신하는 web page

EventSource / cors / jsonp / different host / subscribe model /


tornado

EventSource object | Javascript


EventSource object 로 server 에 연결(subscribe) 을 해서 주기적으로 event 를 받을 수 있다. 자세한 동작은 일단 생략한다. ref. 2 에서 어느정도 설명을 해준다.


different domain

domain 이 다른 곳에 event 를 날려주는 server 가 있어도 무리없이 사용할 수 있다. 보통 html(javascript) 에서 다른 domain 인 경우는 보안을 이유로 ajax 요청이 되지 않는다. 그래서 jsonp 등(일반적으로 Cross-Origin Resource Sharing 이라고 이야기하는 방법)을 이용한다.

하지만 이 EventSource 는 그런 것의 제약을 받지 않는다. [ref. 1]

아래처럼 다른 domain 인 경우에는 다른 domain 을 uri 로 적어주면 된다.

var evtSource = new EventSource("//api.example.com/ssedemo.php", { withCredentials: true } );

evtSource.addEventListener("ping", function(e) {
  var newElement = document.createElement("li");
 
  var obj = JSON.parse(e.data);
  newElement.innerHTML = "ping at " + obj.time;
  eventList.appendChild(newElement);
}, false);


이렇게 다른 domain 에 대한 제약이 없어서 좋은 점은 기존의 web server 와 관계없이 새로운 event 처리를 하는 server 를 사용할 수 있다는 점이다. 그러면 주기적인 push event 등을 처리하는 server 를 따로 둘 수 있다.



Server side event vs WebSocket

event driven page 를 만들 땐 SSE 를 사용해도 되고, WebSocket 을 사용해도 된다. 개인적으로는 필요한 부분은 단방향이라서, 양방향 통신이 되는 WebSocket 이 굳이 필요하지 않았다.

아래는 SSE 와 WebSocket 을 간략하게 정리했다.

SSE

  1. 2009년 4월 23 일 WHATWG 에서 승인했다. [ref. 7] 
  2. 하지만 SSE 가 좀 더 간편하다. 
  3. 그리고 http protocol 위에서 구현되었다. 
  4. 단방향 통신
  5. client 의 connection 이 종료되었는지 여부를 알 수는 없다.(http 라서 당연한 것일지도.)


WebSocket

  1. 반면에 WebSocket 은 Tcp/ip 로 다른 port 를 사용한다. 그래서 이 port 가 firewall 에 의해 막혀 있을 수도 있고, 
  2. 이 녀석을 이용하려면, protocol 을 또 정의해야 한다. (ref. 5 에서 좀 더 다양한 의견을 확인할 수 있다.)
  3. 양방향 통신
from: https://usp.technology/specification/mtp/websocket/websocket-session-handshake.png


See Also

  1. WebSockets vs Server-Sent-Events vs Long-Polling vs WebRTC vs WebTransport | RxDB - JavaScript Database

Reference

  1. Using server-sent events - Web APIs | MDN
  2. Stream Updates with Server-Sent Events - HTML5 Rocks
  3. Asynchronous connections - RethinkDB
  4. Build a real time data push engine using Python and Rethinkdb | IMPYTHONIST
  5. SSE vs Websockets - Streamdata.io
  6. Lessons Learned Architecting Realtime Applications | Lincoln Loop
  7. Python and Real-time Web | Eat at Joe's
  8. Tornado server-sent events · GitHub : tornado 로 SSE 구현 예제.
  9. Building RESTful APIs with Tornado | Dr Dobb's

[컴][웹] V8 에서 JavaScript 의 pipeline

v8 engine 의 동작 / 동작원리 / 크롬 자바스크립트 엔진 / 크롬 엔진 / 크롬 렌더링 엔진 /



V8 에서 JavaScript 의 pipeline

v5.9 이전의 pipeline

from: https://v8.dev/blog/ignition-interpreter

원래는 baseline compiler(위의 그림에서 Ignition 과 Full codegen 의 위치에 있는 것이라 여기면 될 듯 하다.) 가 machine code 를 빠르게 만들고, 이 code 가 실행되는 동안에 이 code를 분석하고 일부를 optimizing compiler 가 optimized code 로 다시 compile 한다.

이 때 사용되는 2개의 optimizing compiler 가 crankshaft, turbofan 이다.

  • TurboFan : Ignition의 bytecode를 바로 최적화된 machine code 로 바꿀 수 있다.[ref. 4]
  • Crankshaft: 소스코드를 다시 컴파일을 해서 최적화된 machine code 를 만든다.[ref. 4]
참고로, v5.9 부터 Full-codegen 과 Crankshaft 는 사용하지 않는다.[ref. 4]

Ignition 의 등장

그런데 이 상황에서 Ignition 을 만들어서 "baseline compiler 가 machine code 를 만드는 것"을 대신해서 Bytecode 를 만들게 했다.

Ignition 는 처음에 모바일에서 사용하기 위해서 만들었다.[ref. 4]  JIT 가 만든 machine code 의 size 가 커서 메모리를 너무 잡아먹었기 때문이다.  Ignition 에 의해서 chrome tab 마다 메모리를 약 5% 정도 아꼈다.

Ignition 은 bytecode 를 생성하는 compiler 이고, 이녀석은 이전의 baseline compiler 를 대체한다.  Ignition 이 bytecode 를 만들때도 당연히 최적화를 한다.

이 Ignition 은 register machine 이다. 이것은 stack machine 과 다르다. 이건 내 생각이지만, 안드로이드의 경험이 덕을 본듯 하다. (stack-based vs register-based)

Ignition 이 생기면서 고성능의 interpreter 가 생겼고 이 녀석이 Ignition 이 만든 bytecode 를 실행해주는데, 실제웹사이트에서 속도가 이전의 baseline compiler 가  만든 code 의 속도에 근접한다.

See Also

  1. V8 관련 글들

References

  1. Ignition · V8 : ignition 에 대한 여러자세한 설명들의 link 들이 있다.
  2. Firing up the Ignition interpreter · V8
  3. Home · v8/v8 Wiki · GitHub
  4. Launching Ignition and TurboFan · V8
  5. TurboFan · V8 : turbofan 에 대한 정보들이 모여 있다.


[컴][자료] Computer Science 관련 학습 자료

컴공 공부 자료 / 컴싸 자료 / 컴사 자료 / CS study resource / 공부 자료 / 이북 / ebook / 동영상 강의 / 동강 / study resources /학습 자료 / 커리큘럼 /유투브 자료 / youtube / 공부 / build / cs공부

ebook

site

실습 자료

컴퓨터공학 커리큘럼 동영상

build your own 시리즈

다음 내용들을 만드는 자료들이 있다.

3D Renderer/ Augmented Reality/ BitTorrent Client/ Blockchain / Cryptocurrency/ Bot/ Command-Line Tool/ Database/ Docker/ Emulator / Virtual Machine/ Front-end Framework / Library/ Game/ Git/ Network Stack/ Neural Network/ Operating System/ Physics Engine/ Programming Language/ Regex Engine/ Search Engine/ Shell/ Template Engine/ Text Editor/ Visual Recognition System/ Voxel Engine/ Web Search Engine/ Web Server/ Uncategorized  

Computer Graphics

 


[웹][컴] Digging into the TurboFan JIT 번역




TurboFan JIT

TurboFan JIT 은 이름에서 알 수 있듯이 Just In Time interpreter(runtime, vm 뭐라고 부르든 상관없을듯) 라고 보면 될 듯 하다.

ref. 1 은 TurboFan 의 design 에 대한 이야기이다. 여기서는 ref. 1 의 이야기를 정리하는 수준으로 작성할 것이다. 자세한 이야기는 ref. 1을 확인하자.

이전에 쓰던 JIT 이 CrankShft JIT 이다.
  • CrankShaft JIT --> TurboFan JIT

TurboFan 의 장점-layered architecture

  • 아래 3개를 좀 더 명확하게 분리 시켰다. --> 좀 더 명확하고, 견고한 code 를 가능하게 한다.
    • source-level language (JavaScript)
    • the VM's capabilities (V8)
    • the architecture's intricacies (from x86 to ARM to MIPS)
  • 최적화기능들(optimizations)과 기능(feature)들을 구현시 효과적으로 할 수 있다.
    • code 가 architecture-dependent backend 들과 분리돼서, 새롭게 추가되는 Javascript 의 기능들을 추가하기 수월해 졌다.
  • 좀 더 효과적인 unit test 를 작성할 수 있다.
  • code 도 줄여준다.(CrankShaft 에서 13,000~16,000 라인이던 부분이 3,000 라인 미만)
  • 여러 architecture 의 engineer 가 좀 더 효율적으로 작업할 수 있게 해준다.

좀 더 수준높은 최적화 방법들

TurboFan JIT 은 이전의 CrankShaft 보다 좀 더 발전된 기술을 이용해서 좀 더 공격적인 optimization 들을 한다.
  • Sea of Nodes IR: 디자인의 핵심은 코드의 "좀 더 유연해진 Sea of Nodes IR(internal representation)" 이다. 이것이 좀 더 효과적인 "reordering" 과 "최적화(optimization)" 을 가능하게 해준다.
  • TurboFan 은 범위 분석(Numerical range analysis) 을 통해 number-crunching code 를 이해하는 것을 돕는다.
  • The graph-based IR : graph 의 기반한 IR 은 대부분의 최적화기능들이 "simple local reductions" 들로 표현되는 것을 가능하게 해준다. simple local reductions 은 독립적으로 작성하고 테스트하기 좀 더 쉽다. 최적화 엔진은 이 local rules 들을 체계적이고, 빈틈없이 적용한다.
  • graphical representation  을 벗어나는 것은  코드를 loop 에서 덜 자주 사용되는 path들로 옮기기 위해 "혁신적은 scheduling 알고리즘"을 사용한다.
  • 이 알고리즘은 reordering freedom 을 이용한다.
  • architecture-specific optimizations: 최종적으로, 복잡한 "instruction selection" 같은 architecture-specific 최적화 기능들은 좋은 품질의 code 를 위해 각 target platform 의 기능들(features)을 이용한다.

See Also

[컴][웹] V8 컴파일 하기

v8 engine compilation / v8 chrome engine / 브라우저 엔진 컴파일 / javascript engine / js engine v8


v8 compilation

컴퓨터환경

  • CPU : i3-2100 CPU@3.10GHz
  • RAM : 8GB
  • DISK : SATA3(6Gb/s), 7200RPM, 16MB

windows 에서 빌드

절차

  1. python 설치
  2. python 경로를 PATH 환경변수에 추가
  3. Visual Studio 설치(약 40분)
  4. Windows 10 SDK 설치
  5. depot_tools 설치
  6. path 설정
  7. gclient
  8. fetch v8(약 10분)
    1. 만약 update 한다면, gclient sync
  9. gn gen --ide=vs out/MyV8

python 2.7.15

python 을 설치하고 환경변수 PATH 에 path 를 추가하자.

pip install pypiwin32

win32 module 을 third-party toolchain 에서 사용한다. 그래서 필요하다.

Visual Studio 설치

windows 에서 v8 를 build 하려면 compiler 가 설치되어 있어야 한다. 여기서는 Visual Studio 2017 Community version 을 사용할 것이다.
  • 버전: Visual Studio 2017 (>=15.7.2) 또는 2019 (>=16.0.0) 가 필요[ref. 1]
"C++를 사용한 데스크톱 개발" 을 선택하고, 설치 세부정보 에서 "x86 및 x64용 Visual C++ MFC" 를 추가한다. 아래 command line 으로 바로 설치할 수 있다.
vs_community.exe --add Microsoft.VisualStudio.Workload.NativeDesktop --add Microsoft.VisualStudio.Component.VC.ATLMFC --includeRecommended

Windows 10 SDK 설치 - Debugging Tools

version 10.0.17134 이상의 Windows 10 SDK 가 설치되어 있어야 한다.
아래에서 setup 을 download 하고, "Debugging Tools for Windows" 를 선택하자.
그러면 아래 경로에서 .msi 를 찾을 수 있다. 이녀석을 실행해서 Debugging Tools 를 설치하자.
  • 64bit용 : <Windows Kits>\10\WindowsSDK\Installers\X86 Debuggers And Tools-x64_en-us.msi

depot_tools

depot_tools 를 설치하자. 참고로 python 은 이미 설치되어 있었다.
  1. depot_tools.zip 를 다운받아서 압축을 풀자. 여기서는 c:\v8\depot_tools\ 에 풀었다.
  2. 이 경로를 PATH 환경변수에 추가하자.
  3. DEPOT_TOOLS_WIN_TOOLCHAIN 변수를 설정하고, 0으로 set 하자. 0 으로 set 하면 이미설치된 Visual Studio 를 사용한다는 뜻이다.
  4. gclient 를 실행하자. metrics.cfg 를 만들어준다.
    c:\v8\depot_tools\>gclient

windows defender 에 '제외'(exclusion) 추가

빌드 속도의 향상을 위해 v8 src directory 를 '제외' 항목에 추가하자. (참고)

fetch v8

이 명령어로 checkout 을 하게 된다. 처음에 git source 를 받을 때 사용한다.
> cd c:\v8\v8_chromium
> fetch v8

참고로, fetch chromium 은 desktop chromium 의 소스를 가져온다.  잘 못 알아서, fetch chromium 을 했는데, master 소스를 가져오는데에만 2시간 55분 정도 소요됐다. 그 후에 다른 관련 소스를 또 받아오는데 25분정도가 더 소요됐다.

HDD는 최소 25GB 는 사용된 듯 하다. ref. 1 을 보면 build 에 최소 100GB 가 필요하다고 한다.

v8 은 그래서 아래 경로에 fetch 가 됐다. v8 source code 의 크기만 1.8GB 정도가 된다.
  • c:\v8_chromium\src\v8
그 다음 nacl(Google Native Client) tools 를 download 한다.

마지막으로 아래처럼 username 을 물어본다. 그냥 enter 를 치면, build 를 시도하다 실패한다.

Username for 'https://chrome-internal.googlesource.com':

________ running 'C:\Python27\python.exe v8/build/vs_toolchain.py update' in 'c:\v8\v8_engine'



No downloadable toolchain found. In order to use your locally installed version of Visual Studio to build Chrome please set DEPOT_TOOLS_WIN_TOOLCHAIN=0.
For details search for DEPOT_TOOLS_WIN_TOOLCHAIN in the instructions at https://chromium.googlesource.com/chromium/src/+/master/docs/windows_build_instructions.md


Traceback (most recent call last):
  File "v8/build/vs_toolchain.py", line 502, in <module>
    sys.exit(main())
  File "v8/build/vs_toolchain.py", line 498, in main
    return commands[sys.argv[1]](*sys.argv[2:])
  File "v8/build/vs_toolchain.py", line 444, in Update
    subprocess.check_call(get_toolchain_args)
  File "C:\Python27\lib\subprocess.py", line 190, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['C:\\Python27\\python.exe', 'c:\\v8\\v8_engine\\v8\\third_party\\depot_tools\\win_toolchain\\get_toolchain_if_necessary.py', '--output-json', 'c:\\v8\\v8_engine\\v8\\build\\win_toolchain.json', '3bc0ec615cf20ee342f3bc29bc991b5ad66d8d2c']' returned non-zero exit status 1
Error: Command 'C:\\Python27\\python.exe v8/build/vs_toolchain.py update' returned non-zero exit status 1 in c:\v8\v8_engine
Hook ''C:\Python27\python.exe' v8/build/vs_toolchain.py update' took 601.97 secs
Traceback (most recent call last):
  File "c:\v8\depot_tools\\fetch.py", line 306, in <module>
    sys.exit(main())
  File "c:\v8\depot_tools\\fetch.py", line 301, in main
    return run(options, spec, root)
  File "c:\v8\depot_tools\\fetch.py", line 295, in run
    return checkout.init()
  File "c:\v8\depot_tools\\fetch.py", line 137, in init
    self.run_gclient(*sync_cmd)
  File "c:\v8\depot_tools\\fetch.py", line 82, in run_gclient
    return self.run(cmd_prefix + cmd, **kwargs)
  File "c:\v8\depot_tools\\fetch.py", line 71, in run
    subprocess.check_call(cmd, **kwargs)
  File "C:\Python27\lib\subprocess.py", line 190, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '('C:\\Python27\\python.exe', 'c:\\v8\\depot_tools\\gclient.py', 'sync', '--with_branch_heads')' returned non-zero exit status 2

c:\v8\v8_engine>

gclient sync

추후에 source 를 최신으로 update 할 때 사용하면 된다.
c:\v8\v8_engine\v8>gclient sync
Syncing projects: 100% (24/24), done.
Running hooks:  75% (21/28) clang
________ running 'C:\Python27\python.exe v8/tools/clang/scripts/update.py' in 'c:\v8\v8_engine'
Downloading https://commondatastorage.googleapis.com/chromium-browser-clang/Win/clang-349417-2.tgz .......... Done.
Copying C:\Program Files (x86)/Microsoft Visual Studio/2017/Community\DIA SDK\bin\amd64\msdia140.dll to c:\v8\v8_engine\v8\third_party\llvm-build\Release+Asserts\bin
Hook ''C:\Python27\python.exe' v8/tools/clang/scripts/update.py' took 19.46 secs
Running hooks: 100% (28/28), done.

c:\v8\v8_engine\v8>

gn gen --ide=vs out/MyV8

chromium 은 ninja 를 사용한다. depot_tools 를 설치하면 같이 설치된다. gn 을 실행하면 .ninja 를 만들어준다. (자세한 내용은 여기 를 참고하자.)

여기서는 Visual Studio 에서 build 를 할 것이라서 --ide=vs 를 추가해 줬다.
c:\v8\v8_engine\v8>gn gen --ide=vs out\MyV8
Generating Visual Studio projects took 277ms
Done. Made 132 targets from 76 files in 9360ms

c:\v8\v8_engine\v8>

이제 아래 경로에 .sln file 이 생성됐다.
  • c:\v8\v8_engine\v8\out\MyV8\all.sln
몇몇 관련 project 를 filetering 하려면 아래 처럼 하면 된다. 하지만 이 option 은 chromium 같이 큰 프로젝트를 열때나 필요할 듯 하다. v8 project 만 열때는 필요치 않았다.
gn gen --ide=vs --filters=//third_party/v8/* --no-deps out\Default

open .sln(약 60분)

이제 위에서 생성된 all.sln 파일을 더블클릭해서 Visual Studio 를 열자. 그리고 build 를 하면 된다. build 를 하면 내부적으로 ninja 를 호출해서 build 를 하게 된다.

여기서는 v8_hello_world 를 build 했다. 대략 60분 정도가 소요됐다.

error case : visual studio 2015 --> visual studio 2017

v8 build 를 위해서 visual studio 의 version 을 upgrade 한 경우는 stdio.h 등의 header files 가 include 가 안되는 경우가 있다. 이때는 Windows SDK 버전을 재설정 해주자.

v8_hello_world.exe 실행

이제 아래 path 에 v8_hello_world.exe 가 생성됐다. 이 녀석을 실행하면 아래처럼 결과가 나온다.
c:\a\programming\v8\v8_engine\v8\out\MyV8>v8_hello_world.exe
Hello, World!
3 + 4 = 7

debug mode

당영한 이야기지만, 만약 이 v8_hello_world 를 디버그 모드로 실행하고 싶다면, solution explorer 에서 v8_hello_world project 에서 context menu(마우스 오른쪽 버튼) 을 눌러서 debug 를 해야 한다.

See Also

  1.  V8 에서 JavaScript 의 pipeline
  2. V8 관련 글들

References

  1. Checking out and Building Chromium for Windows
  2. v8/v8.git - Git at Google

[컴] 테크기업에게 무엇이 적합할까 Teams ? slack ?



테크기업에게 적합한 협업툴

ref. 1 에서 UC 는 microsoft teams 같은 tool 을 이야기 하는듯 하고, 협업툴(team collaboration tool)은 "슬랙" 같은 tool 을 이야기 한다.

테크기업에게 협업툴이 더 잘 맞을 것이라는 이야기가 있어서 가져와 봤다.

451 리서치(451 Research)의 수석 애널리스트 라울 카스타논 마르티네즈

마르티네즈는 "비즈니스 특성상 UC(Unified Communication, 통합 커뮤니케이션)보다 협업 솔루션이 더 잘 맞는 곳들도 있다. 스타트업이나 디지털 네이티브 기업들이 그 예다. 단순히 직원 가운데 IT 전문가 비율이 높아서만은 아니다. 지식 노동자의 비중이 높을수록, 그리고 엔지니어 및 개발자 직원 기반이 강세일수록 협업 솔루션이 더 적합하다. 이들의 커뮤니케이션 방식에 더 잘 맞기 때문이다. 이런 이유로 UC에서 협업 툴로 이전하는 기업들도 많을 것이라 생각한다"고 말했다.[ref. 1]

“There are some companies that because of the nature of their business, could be well suited for that,” Castañón Martínez said, such as startups or digital native companies. “Not just because they tend to be more tech-savvy or tech-oriented than other companies, but mainly because of the type of workers. If they have a higher percentage of knowledge workers, and they are in a stage where they might have a strong employee base of engineers and developers, it just makes sense because that is how they communicate. So, I think that we might see some shift in that sense.”

Teams Demo


Slack Demo



개인적인 의견

개인적으로 둘다 안사용하는 것보다는 좋다고 생각한다.

하지만 굳이 선택을 하라면, slack 쪽이 더 좋다. 확장성도 좋고, 사용성도 좋다. Teams 는 써보지 않았지만, demo 비디오로 봤을때 기존의 우리가 많이 사용하던 tool 이다. 그것의 장점은 정리가 잘 될 수 있다라고 생각하는데(물론 요새 많이 바뀌었긴 하지만)문제는 대다수의 사람들을 그 정리된 interface 에 맞추려 하는 것이다.

IT회사에서 일할때 대체로 사람들은 자료정리에 시간을 보내지 않는다. 그렇기에 당연히 slack 이 낫다. 하지만 하나의 단점이라면, 채팅으로 되어 있어 불필요한 대화들도 같이 들어가 있기에 추후에 자료를 정리하고 싶은 순간이 오기는 한다.


References

  1. 블로그 | 2019년 협업 소프트웨어 시장, '춘추전국시대가 온다' - CIO Korea
  2. Collaboration 2019: Teams, Slack and what’s coming | Computerworld

[컴][OS] ELF file format

리눅스 파일포맷 / 실행 파일 포맷 / 규격 / 파일 규격

ELF format

ELF file format 에 관한 얘기를 해보자.

elf header 관련 정보들

일단 여기서 이야기하는 것은 아주 첫 부분이다. 자세한 정보들은 아래 링크를 참고하자.

ELF type

ELF file 은 여러가지 모양(type)이 가능한데,
그 중에 주요한 3가지 type 이 있다.
  1. relocatable file
  2. executable file
  3. shared object file

일단 다른것은 생각하지 말고, 흔히 windows 에서 얘기하는 .exe 같은 executable file 에 대해서 살펴보자.

ELF executable

ELF file 안에는 아래같은 요소가 들어간다.
  1. ELF header : 언제나 ELF file 의 가장 처음에 위치
  2. Program header table
  3. Segment
  4. Section
  5. Section header table.

ELF header 는 항상 처음에 위치하지만, 하지만 다른 것들의 위치는 고정되어 있지 않다.

<그림필요>

ELF header

먼저 이 ELF header 에 대해 얘기 해보자.

역시 위치가 고정되어 있기 때문에 elf file 를 까봐도 찾기가 가장 편할 것이다. 일단 코드상으로는 아래와 같다.

code

e_ident[] Identification indexes
Name Value Purpose
EI_MAG0 0 File identification
EI_MAG1 1 File identification
EI_MAG2 2 File identification
EI_MAG3 3 File identification
EI_CLASS 4 File class
EI_DATA 5 Data encoding
EI_VERSION 6 File Version
EI_PAD 7 Start of padding bytes
EI_NIDENT 16 e_ident[]

struct
#define EI_NIDENT    16
typedef struct{
    unsigned char    e_ident[EI_NIDENT];      /*Magic number and other info */
    ElfN_Half       e_type;                         /*Object file type */
    ElfN_Half       e_machine;                   /* Architecture */
    ElfN_Word       e_version;                     /* Object file version */
    ElfN_Addr       e_entry;                       /* Entry point virtual address */
    ElfN_Off        e_phoff;                       /* Program header table file offset */
    ElfN_Off        e_shoff;                        /* Section headr table file offset */
    ElfN_Word       e_flags;                        /* Processor-specific flags */
    ElfN_Half       e_ehsize;                      /* ELF header size in bytes */
    ElfN_Half       e_phentsize;                 /* Program header table entry size */
    ElfN_Half       e_phnum;                    /* Program header entry count */
    ElfN_Half       e_shentsize;                  /* Section header table entry size */
    ElfN_Half       e_shnum;                      /* Sectino header table entry count */
    ElfN_Half       shstrndx;                      /* Sectino header string table index */
} Elf32_Ehdr


binaries

실제로는 어떻게 이 값이 hex 로 저장되어 있는지 살펴보자.

<그림>

확대


당연한 이야기지만 이 구조체 structure 를 보면 header에 어떤 것들이 들어있는지 알 수 있다.


아래와 같은 elf file 이 있다고 하자.
0x7f, 0x45, 0x4c, 0x46, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x28, 0x00, ...
e_ident
처음 16개의 byte 들(e_ident[EI_NIENT])을 살펴보자.

  • EI_MAG*
    • 0x7f, 0x45, 0x4c, 0x46
    • 처음 4개는 이 파일이 ELF object file 인 것을 알려주는 magic number 이다.
  • EI_CLASS
    • 그 다음 byte, 즉 5번째 byte 는 file 의 class 를 나타낸다.
    • ELF file 이 다양한 사이즈의 머신에서 가져다 쓸 수 있게 하기 위해서 이 ELF file 이 어떤 machine 에서 작동하는 놈이다라는 것을 알려줄 필요가 있다.
      • '1'은 32-bit objects 라는 것(ELFCLASS32)을 알려주며,
      • '2'는 64-bit objects 라는 것(ELFCLASS64)을 알려준다.
  • EI_DATA
    • 6번째 BYTE는 encoding type 을 알려준다.
      • '1'(ELFDATA2LSB) : little-endian
      • '2'(ELFDATA2MSB) : big-endian
  • EI_VERSION
    • 7번째 byte 는 ELF header version 을 알려준다.
    • 보통 '1'(EV_CURRENT) 를 사용한다.
  • EI_PAD
    • 8번째 byte 부터  끝까지 '0'으로 채워져 있는데, 그냥 의미없이 채워넣은 것이다, 즉 padding 이다. 흔히 하는 말로 reserved, 예약되어 있는 것이다.
    • (EI_PAD 이 값이 현재 '7'인데, 만약 header에 들어갈 값이 더 생긴다면 당연히 EI_PAD 값을 큰 수로 변경해야 한다.)
e_type
17번째 byte 와 18번째 byte 는 지금 ELF file 의 format 을 알려준다.
자세한 사항은 놔두고, 일단 여기서는 executable file 이기 때문에 '2' 가 된다.