<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by 7FrogTW on Medium]]></title>
        <description><![CDATA[Stories by 7FrogTW on Medium]]></description>
        <link>https://medium.com/@7FrogTW?source=rss-e3880fe8f62b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*I8a9Ld0yloNLjMusfRAKAw.jpeg</url>
            <title>Stories by 7FrogTW on Medium</title>
            <link>https://medium.com/@7FrogTW?source=rss-e3880fe8f62b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:19:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@7FrogTW/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[PowerPC — syscall 踩雷大全]]></title>
            <link>https://medium.com/@7FrogTW/powerpc-syscall-%E8%B8%A9%E9%9B%B7%E5%A4%A7%E5%85%A8-75b5d477ac0b?source=rss-e3880fe8f62b------2</link>
            <guid isPermaLink="false">https://medium.com/p/75b5d477ac0b</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[powerpc]]></category>
            <dc:creator><![CDATA[7FrogTW]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 03:59:32 GMT</pubDate>
            <atom:updated>2024-03-23T03:23:53.186Z</atom:updated>
            <content:encoded><![CDATA[<h3>PowerPC — syscall 踩雷大全</h3><h4>Linux Kernel 針對 powerpc 的程式碼一直不斷在更新，因此新舊版本之間的差距非常大，這篇文章將介紹我在橫跨 v4.4 ~ v5.7 的 kernel 之間所遇到的各種問題。</h4><p><a href="https://medium.com/@7FrogTW/powerpc-symbol-address-resolution-4da9f685e383">上一篇文章</a>中我提到藉由 kprobe 拿到 symbol address 時所遇到的各種問題，以及 powerpc 的 TOC 所造成的問題，其實 TOC 在舊版的 kernel 中也扮演著關鍵角色，最近發現我們的 PPC code 在舊版 kernel 運行時，只要一進入 system call 就會引發 crash，要深入探討發生的原因，我們需要一步步抽絲剝繭…</p><p>在深入探討 system call 流程之前，我們需要先了解 sys_call_table 是什麼，一般來說 sys_call_table 只是一個 array of function pointer， 我們用 syscall number 當作 index 就可以在 sys_call_table 上找到相對應的 handle function, 例如我們拿 NR_open 當作 index， 就可以在 sys_call_table[NR_open] 上拿到 sys_open function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*ayE3hV9pBTK6tAhEW5XR0w.png" /><figcaption>sys_call_table</figcaption></figure><p>然而 powerpc 在 kernel v5.0 以前卻是把 sys_call_table 和 compat_sys_call_table 編在一起，所以我們應該用 sys_call_table[NR*2] 的方式來取得 handler，而不是用 sys_call_table[NR] 來取得，如下圖:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*oRZucHK-SluXHwggbxYfxg.png" /><figcaption>powerpc 在 v5.0 以前的 sys_call_table</figcaption></figure><p>接下來可以看看 kernel 舊版的 syscall 進入流程:</p><pre>system_call:   /* label this so stack traces look sane */<br>/*<br> * Need to vector to 32 Bit or default sys_call_table here,<br> * based on caller&#39;s run-mode / personality.<br> */<br> ld r11,SYS_CALL_TABLE@toc(2)<br> andi. r10,r10,_TIF_32BIT<br> beq 15f<br> addi r11,r11,8 /* use 32-bit syscall entries */<br> clrldi r3,r3,32<br> clrldi r4,r4,32<br> clrldi r5,r5,32<br> clrldi r6,r6,32<br> clrldi r7,r7,32<br> clrldi r8,r8,32<br>15:<br> slwi r0,r0,4<br> ldx r12,r11,r0 /* Fetch system call handler [ptr] */<br> mtctr   r12<br> bctrl   /* Call handler */</pre><ol><li>sys_call_table 的 address 被放進 r11</li><li>檢查 current thread info 是否有開啟 _TIF_32BIT</li><li>若有開啟，先把 r11 + 8, 再把 r3-r8 的 32–63 bits 清除 (r3-r8 代表 function 的參數 1–6)</li><li>把 r0 (system call number) left shift 4 bits(乘以16) 當作 offset，從 r11 + offset 取得 function pointer 後放入 r12</li><li>將 r12 的直放入 count register, 並 branch 到該 address</li></ol><p>這邊可以把 sys_call_table 想像成兩個不同的 columns，若沒有開啟 _TIF_32BIT 則會使用第0個 column， 反之則會使用第1個 column (r11 + 8)， 每個 column 的 entries 之間相差 16 bytes，這就是為什麼會需要把 r0 left shift 4 bits 來當作 offset.</p><p>看懂這一段，我們已經對 powerpc system call 有初步了解，然而當我們 disassemble system call handler，我們對系統的了解又更上一層樓:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*ZfruDIiqHpY8fpUbZymrdg.png" /></figure><p>以上圖的 sys_open 來說，當 kernel 準備 branch 進去，會執行：</p><ol><li>將 c0000000003aa960 放進 r12</li><li>將 r12 的值放進 CTR (count register)</li><li>branch to CTR</li></ol><p>為什麼要先放入 r12 是因為 function 的 GEP (Global Entry Point) 會先用 r12 來計算 r2，r2 在 powerpc 中也就代表 TOC 的 address，其實在 kernel 裡面這個 TOC 都是指向同樣的 address， 首先我們可以來看看另一個 system call sys_openat:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*yt5yEO3bbElx1caPqlG2Xw.png" /></figure><p>這邊可以看到 sys_openat 的第一個 instruction 一樣是</p><pre>addis 2, 12, 228</pre><p>然後第二個 instruction 的 addi 比 sys_open 少了 80 bytes (27056-26976), 這 80 bytes 其實就是因為兩邊的 r12 都指向自己 function 的 GEP 所造成的差值:</p><pre>0xc0000000003aa9b0 - 0xc0000000003aa960 = 0x50 = 80</pre><p>所以我們可以知道所有 kernel function 的 r2 最終都是指向同一個 TOC address.</p><h4>說了這麼多，道理我們都懂，只是問題到底出在哪裡？</h4><p>為了要能夠偷偷監測我們關注的 syscall 有沒有被呼叫，我們會把 sys_call_table 上真正的 handler 換成我們 kernel module 內的 function，這個 function 會收集 syscall 相關的參數再 call 回真正的 syscall handler，讓系統可以沒有察覺的正確運行。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*1qoLtD0jsSbHMdw-cqGJTg.png" /></figure><p>Step 1 — 從 kernel 進入到我們 kernel module handler 時，r12 是指向我們 handler 的 address，並且根據 r12 重新計算出 r2，這時候所算出來的 r2 跟前面所提到的 TOC address 不一樣，因為 kernel module 內的 TOC 和 kernel 內的 TOC 不同。將 kernel module disassemble 後，我們可以看到 compiler 把 TOC address offset 放在每個 function 的 GEP 之前的 8 個 bytes，這是因為編譯時期開啟了 -mcmodel=large 導致的，以下圖為例， ld r2, -8(r12) 就是從 0x0000000000001c70 取值， add r2, r2, r12 把取出來的值再加上 0x0000000000001c78 當作 TOC address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*i8Vccobpske5AemybjwwlQ.png" /></figure><p>Step 2 — 當我們要 call 進 real syscall handler 時，因為我們是 branch 到 real syscall handler 的 GEP，前兩個 instructions 會再次重新計算 TOC， 這次的 TOC 會指向 kernel 的 TOC address.</p><p>Step 3 — 當我們從 real syscall handler 回到 replaced syscall handler 時，我們會需要把 r2 再恢復成 kernel module 的 TOC，這時候會發現 compiler 很巧妙地先將 r2 存在 stack 中，等到 return 回來時再從 stack 中把值 load 回 r2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*cN3OkGUnyRF27RzM0Z4u4w.png" /></figure><p>Step 4 — 當我們從 replaced syscall handler 回到 kernel 時，需注意這時的 r2 仍然指向 kernel module 的 TOC， 但是因為 kernel 會假設 sys_call_table 中所儲存的 handler 都是 kernel function， 所以它也同時假設從 syscall handler return 時，r2 仍然是指向 kernel 的 TOC， 而且為了提升效率，kernel 在呼叫後續的 kernel function 時直接跳進該 function 的 LEP (Local Entry Point)，所以 r2 沒有被重新計算:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*nVVIEiU3TIQ42WW44c9Ssg.png" /></figure><p>這麼一來，一但跳進去的 kernel function 有使用 r2 拿取任何資料，就很有可能會發生 kernel crash 或是系統異常….</p><p>為了要解決這個問題，我們把 replaced syscall handler 改寫成 assembly code，這樣我們才可以充分控制，把 system call 進來時的 r2 先存在 stack，在離開 replaced syscall handler 時再恢復，這樣就可以確保系統運作無誤。</p><p>在 v5.7 以後，kernel 將這段 assembly code 部分重組成 C code，實際呼叫 system call handler 的地方變成用 C code 實作，這樣的好處是編譯出來的 assembly code 會在進入/離開 handler 時 save/load r2，解決了r2不一致的問題:</p><p><a href="https://github.com/torvalds/linux/blob/a4145ce1e7bc247fd6f2846e8699473448717b37/arch/powerpc/kernel/syscall.c#L150-L174">linux/arch/powerpc/kernel/syscall.c at a4145ce1e7bc247fd6f2846e8699473448717b37 · torvalds/linux</a></p><p>commit:</p><p><a href="https://github.com/torvalds/linux/commit/68b34588e2027f699a3c034235f21cd19356b2e6">powerpc/64/sycall: Implement syscall entry/exit logic in C · torvalds/linux@68b3458</a></p><h4>最終大魔王</h4><p>v5.7 以前的 kernel 針對某些 syscalls 會在進入前先把 non-volatile registers(r14 — r31) 存在 stack 上，參考:</p><p><a href="https://github.com/torvalds/linux/blob/7111951b8d4973bda27ff663f2cf18b663d15b48/arch/powerpc/kernel/entry_64.S#L466">linux/arch/powerpc/kernel/entry_64.S at 7111951b8d4973bda27ff663f2cf18b663d15b48 · torvalds/linux</a></p><p>這對我們來說的困難點是我們不可能在 Step 2 的時候再把 r1 改成當初進入 Step 1 時的 stack address，因為這樣我們就會失去目前的 stack address，後續的 functions 只要有用到 stack 上的東西就會導致 crash 或是系統異常…</p><p>我們目前能做的事情是在我們的 assembly code 裡面針對這些 syscalls 做特殊處理，在一進入我們的 handler 時就先 save non-volatile registers ，因為此時的 r1 還指向 kernel 的 stack address，等到後面要 call real syscall handler 時，我們直接 call sys_fork/sys_vfork/sys_clone 而不是 ppc_fork/ppc_vfork/ppc_clone，否則 kernel 會使用到錯誤的 stack address.</p><p>這個問題在 v5.7 以後被修掉，變成所有的 syscalls 都會先 save non-volatile registers，雖然整體效能可能下降，但是卻減少了我們對特殊 syscalls 需要做的處理，詳情請見 commit:</p><p><a href="https://github.com/torvalds/linux/commit/965dd3ad307671d06471da0e9a44f3a194167d26">powerpc/64/syscall: Remove non-volatile GPR save optimisation · torvalds/linux@965dd3a</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75b5d477ac0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2023 心得回顧]]></title>
            <link>https://medium.com/@7FrogTW/2023-%E5%BF%83%E5%BE%97%E5%9B%9E%E9%A1%A7-57f1280d7a4a?source=rss-e3880fe8f62b------2</link>
            <guid isPermaLink="false">https://medium.com/p/57f1280d7a4a</guid>
            <dc:creator><![CDATA[7FrogTW]]></dc:creator>
            <pubDate>Fri, 05 Jan 2024 10:46:27 GMT</pubDate>
            <atom:updated>2024-01-05T11:00:39.164Z</atom:updated>
            <content:encoded><![CDATA[<p>2022 的 8.9 月，我才剛換了租屋處、也轉到了新的 team, 感覺一切都在變動中，也不知道該如何為這一年作結</p><p>如果硬要說的話，我當時肯定覺得 2022 是個極為糟糕的一年，要說 2022 讓我最印象深刻的兩件事情:</p><p>第一件事情是搬家的時候，我把東西差不多都搬到新的租屋處後，我在兩人曾一起生活的地方度過最後一晚，空空如也的房間裡面，記憶像幻燈片一閃而過，那種又酸又甜又苦又鹹的複雜感情是什麼，我到現在都還沒搞清楚</p><p>第二件事情是某個禮拜四下午,我突然好想逃離當時的生活，messenger 打開一問，麻吉沒有二話跟我一起出發，穿越了中橫之後我們疲憊地躺在花蓮海邊，一通通電話開始詢問哪裡還有空房可以住，晚上的時候，市區無預警放起煙火，近到感覺房子都要被炸了，我看著他說:「哦，原來你就是我的小幸運。」</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lpLgF1v6w1e_DrYvOdIQg.jpeg" /></figure><p>經歷過 2022 的風風雨雨，我當時給自己的目標是學會和自己相處、學著去理解自己的感受，不把自己照顧好了，我要怎麼照顧其他人？</p><p>對我來說 2023 年的主題一直圍繞在人際關係上面</p><p>我一直記得有一陣子我因為一些事情大受打擊，我跟朋友說也許我永遠都不夠好、也不會值得任何人來愛我，他說:「你如果想要別人來愛你，那你就先去付出你的愛。」</p><p>聽完之後我大受啟發，一夜之間我好像終於長大成人了，在這一年裡我也對心裡真正覺得重要的人做了各式各樣的付出，但是這麼做並不是因為我想要得到更好的回應，而是因為我知道他們一定會打從心裡感到快樂。</p><p>2023 最有感的收穫是人與人的連結感，因為身邊的朋友，我認識了更多朋友、也做了很多好玩的事情:</p><ul><li>第一次去爬百岳、住山屋</li><li>第一次去跑101垂直馬拉松</li><li>第一次參加社內程式競賽就被同事扛進決賽</li></ul><p>有沒有解鎖人生成就並不是最重要的，而是這些經歷都是真正開心的回憶</p><p>如果沒有我身邊優秀的朋朋，這些事情是不可能實現的。</p><p>工作上，終於開始覺得一切都上軌道，不論是進度上、內容上、team 內的氛圍我都很喜歡，也覺得自己終於開始發揮影響力，很期待2024可以持續推出更多新 features</p><p>羽球，在不斷內捲的過程和日以繼夜的挫敗感中，我終於感受到自己有些許的成長，真的很感謝自己沒有放棄這個運動，不然我就無法再和高中的同學們產生連結、也沒有機會再認識更多的人。</p><p>閱讀，2023 年是我第一次把一本心理相關的書籍讀完，也許是外在的幫助已經無法解決許許多多問題，只好向內探索問題的根源，以下節錄自書籍 《蛤蟆先生去看心理師》:</p><blockquote>「沒有一種批判比自我批判更強烈，也沒有一個法官比我們自己更嚴苛。」蒼鷺答道。</blockquote><blockquote>「天哪，你是說我們會懲罰自己？」</blockquote><blockquote>「會嚴厲地懲罰，包括折磨自己，在極端案例裡，甚至會施以極刑。但問題是，即便對自己輕判，這種譴責和懲罰也可能伴隨一生，變成無期徒刑。」</blockquote><blockquote>「那我能做什麼？」蛤蟆問，「我的日子還很長，如果真有自我懲罰，我不要一直那樣下去，我想過得快樂一點兒。蒼鷺，我該怎麼做，你能幫我嗎？」</blockquote><blockquote>「這麼說也許有些殘酷，蛤蟆，能幫你的人是你自己，也只有你自己。有許多問題需要你向自己發問。比如你能停止自我批判嗎？你能對自己好一些嗎？也許最重要的問題是，你能開始愛自己嗎？」</blockquote><p>如果問我嚴厲的父母因為希望孩子變好而責怪或是懲罰他們，我一定會反對這種方式，但是我看完這本書才發現我也會用相同的方式來對待自己。</p><p>回頭看 2022 年給自己的目標，問自己我是否已經成為一個夠好的人了？</p><p>我覺得答案是否定的，我還是無法避免地在很多時候對自己有批判性的想法、也常常對自己感到很憤怒，但是至少這次我很確定的是，就算是我再爛，還是會有無助時的靠山、願意真心交流的人、可以一起狂歡亂玩的朋友，再次感謝 2024 還願意陪在身邊的人，有你們真好。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57f1280d7a4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PowerPC - symbol address resolution]]></title>
            <link>https://medium.com/@7FrogTW/powerpc-symbol-address-resolution-4da9f685e383?source=rss-e3880fe8f62b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4da9f685e383</guid>
            <category><![CDATA[powerpc]]></category>
            <category><![CDATA[linux-kernel]]></category>
            <dc:creator><![CDATA[7FrogTW]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 16:45:23 GMT</pubDate>
            <atom:updated>2023-06-13T06:06:20.051Z</atom:updated>
            <content:encoded><![CDATA[<h4>最近為了要讓 team 內的 kernel modules 能跑在 PowerPC 上，花了些時間在實驗和研究，這篇文章將介紹我遇到的一些問題。</h4><h3>How to steal symbols from kernel?</h3><p>故事從如何偷到 kernel symbol 說起，因為kernel 中有大量 non-export functions, 這些 functions 是 kernel developers 沒有開放給其他 module 使用的，</p><p>在 build kernel module的時候，kernel 會檢查所有使用到的 symbols, 如果使用了沒有被 export 出來的 symbol, 就會被 kernel 攔截下來.</p><p>Non-export function:</p><pre>ERROR: modpost: &quot;copy_to_kernel_nofault&quot; [/tmp/krodatalab/kmod/kpatching.ko] undefined!</pre><p>Non-export object:</p><pre>ERROR: modpost: &quot;init_mm&quot; [/tmp/krodatalab/kmod/kpatching.ko] undefined!</pre><p>為了要使用沒有被 export 的 symbols, 我們會在自己的 module 中為每個 symbol 建立一個分身, 這個分身最終將指向真正 symbol 的 address,</p><p>為了要取得這個 address, 我們會用 register_kprobe 註冊空的 callback 到我們想取得的 symbol 上面，再從 return 的 structure 中提取出我們要的 symbol address.</p><p>所以最後我們的確沒有在 kernel module 中使用到 non-export symbols, 我們只是使用了 module 內的分身們，但這些分身們其實可以做到和本尊一樣的事情!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*NdhRd32mzNTg71uLuZ8Wkg.png" /></figure><p>因為這招我們在 X86 和 ARM 的機器上已經使用多時，也沒遇過什麼災情，所以在 PowerPC 上 crash 的時候我從來沒懷疑過會是 register_kprobe 的問題，所以接下來就是不斷翻文件、翻 kernel code 、改 module 、crash 的輪迴…</p><p>一直到有一天我突發奇想，因為我可以拿到 export function 的 address, 那我拿某個 address 出來和 register_kprobe 的結果比較看看是否一樣:</p><pre>[171362.628864] ip_set_get_ip4_port : 0xc008000003106538<br>[171362.628869] ip_set_get_ip4_port_cloned : 0xc008000003106544</pre><p>這邊可以看到 register_kprobe 拿到的 address 比原本的 function 多了 12 個 bytes, 而且 PowerPC 每個 instruction 是 4 個 bytes, 所以中間插了 3 個 instructions 是什麼用途呢？</p><p>trace code 之後可以找到 kernel/kprobe.c 中的一段 code:</p><pre>kprobe_opcode_t * __weak kprobe_lookup_name(const char *name,<br>     unsigned int __unused)<br>{<br> return ((kprobe_opcode_t *)(kallsyms_lookup_name(name)));<br>}</pre><p>這邊巧妙的點是這 function 被標示為 weak symbol, 意思是當有其他 function 實作存在時，則這裡的實作就不復存在 ; 反之，function 就以這個實作為準。</p><p>在 kernel source code 中搜尋一下這個 function 的其他實作:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9EtNWylA3EJ1z0Sa_Q4stA.png" /></figure><p>Bingo! 原來只有 PowerPC 在 kprobe address lookup 時有特殊實作，意思是這個 weak symbol 在 PowerPC 上將被取代，難怪在 X86 和 ARM 上面不會遇到一樣的問題…</p><p>接下來看看 arch/powerpc/kernel/kprobes.c 中的實作：</p><pre>kprobe_opcode_t *kprobe_lookup_name(const char *name, unsigned int offset)<br>{<br> kprobe_opcode_t *addr = NULL;<br><br>#ifdef PPC64_ELF_ABI_v2<br> /* PPC64 ABIv2 needs local entry point */<br> addr = (kprobe_opcode_t *)kallsyms_lookup_name(name);<br> if (addr &amp;&amp; !offset) {<br>#ifdef CONFIG_KPROBES_ON_FTRACE<br>  unsigned long faddr;<br>  /*<br>   * Per livepatch.h, ftrace location is always within the first<br>   * 16 bytes of a function on powerpc with -mprofile-kernel.<br>   */<br>  faddr = ftrace_location_range((unsigned long)addr,<br>           (unsigned long)addr + 16);<br>  if (faddr)<br>   addr = (kprobe_opcode_t *)faddr;<br>  else<br>#endif<br>   addr = (kprobe_opcode_t *)ppc_function_entry(addr);<br>...</pre><p>這裡我會分成兩個部分來說明，第一個部分是當 kernel 沒有開啟 CONFIG_KPROBES_ON_FTRACE 的情形，第二部分是有開啟的情形。</p><h3>Global Entry &amp; Local Entry</h3><p>如果繼續 trace code, 看到 arch/powerpc/include/asm/code-patching.h 裡面關於 ppc_function_entry 的實作：</p><pre>static inline unsigned long ppc_function_entry(void *func)<br>{<br>#ifdef PPC64_ELF_ABI_v2<br> u32 *insn = func;<br><br> /*<br>  * A PPC64 ABIv2 function may have a local and a global entry<br>  * point. We need to use the local entry point when patching<br>  * functions, so identify and step over the global entry point<br>  * sequence.<br>  *<br>  * The global entry point sequence is always of the form:<br>  *<br>  * addis r2,r12,XXXX<br>  * addi  r2,r2,XXXX<br>  *<br>  * A linker optimisation may convert the addis to lis:<br>  *<br>  * lis   r2,XXXX<br>  * addi  r2,r2,XXXX<br>  */<br> if ((((*insn &amp; OP_RT_RA_MASK) == ADDIS_R2_R12) ||<br>      ((*insn &amp; OP_RT_RA_MASK) == LIS_R2)) &amp;&amp;<br>     ((*(insn+1) &amp; OP_RT_RA_MASK) == ADDI_R2_R2))<br>  return (unsigned long)(insn + 2);<br> else<br>  return (unsigned long)func;<br>...</pre><p>這個 function 可以檢查任意 address 的前兩個 instructions 是不是這樣的 layout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*aQBZJhUbtsICq7yib5eWXw.png" /></figure><p>左右兩邊其實要達到的目的是一樣的，就是計算一個正確的 address 並且放入 r2, r2 在 PowerPC 中是用來作為 TOC (Table of Contents) pointer, TOC 是 powerPC 中特有的機制，顧名思義就是一個用來儲存資料的表，一些可以由 compiler 預算好的 function address 或是各種常數都會被放在這裡，以我自己實驗的結果看來，每個 function 都有自己的 TOC, 然而對 kernel 來說為了節省空間卻未必是這樣。</p><p>而對於每個 function 來說，上圖中標示的 symbol address 就是這個 function 的 <strong>global entry</strong>, 而 symbol address + 8 的位址就是這個 function 的 <strong>local entry</strong>.</p><p>如果有 PowerPC 機器或是虛擬機的也可以在上面撰寫簡單的範例程式並觀察編譯後的結果:</p><p><a href="https://godbolt.org/z/zeEY4q9sM">Compiler Explorer - C (cppc64leg1220)</a></p><p>至於為什麼 kprobe 要使用 local entry 而非 global entry?</p><p>這邊我也還沒完全理解，但我猜是因為 kernel 在 kprobe pre-handler 執行完後，要執行 probed function 時可以確定 TOC pointer 不用改變(使用同一個 table)，所以直接用 local entry 當 probed function address，這樣可以不用再次計算 TOC pointer 的位置進而提升效能。</p><h3>How does ftrace affect kprobe function address?</h3><p>ftrace 的運作原理是藉由 compiler 的 -pg 選項，在每個 function 的進入點插入一段 code 去呼叫 _mcount 來記錄 function call stack.</p><p>為了更加了解 ftrace 的運作，以剛剛的 ip_set_get_ipv4_port function 為例， 因為藉由 kprobe 拿到的 function address 比原有的 function address 多了 12 bytes, 所以我倒回去把這 16 bytes 的 instructions 印出來看看:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34KVcPE2BWdj7mL33SnBug.png" /></figure><p>再經過一些工人智慧的計算，可以看出 function 的樣貌:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J2AN37gOeqEitJKiZgRHRg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*d7VcBUl7hPOlqOvvVxrdDw.png" /></figure><p>這邊很有趣的點是 nop 指令是會被動態替換的，如果我們藉由以下方式開啟 ftrace: echo function &gt; /sys/kernel/debug/tracing/current_tracer , 並再次觀察 instructions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4DgZP9qxWMTwyXx8l0m_A.png" /></figure><p>可以看到 nop instruction 被換掉了，被換成什麼呢？其實就是 bl _mcount :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*rVMzKBJocyug5K7p5g0Cww.png" /></figure><p>再看回來被 kprobe 跳過的 instructions, 除了前面提到 global entry 對於 TOC pointer 的計算被跳過了之外，還有 mflr r0 也一起被跳過，mflr 指令是 Move From Link Register 的意思，因為 bl 指令除了 Branch 到指定 address 之外還會將 Link Register 設定為下一個 instruction (方便之後用 blr 跳回)，所以通常 bl _mcount 之後還會緊跟著一樣的 mflr r0 指令，所以前面的 mflr r0 也被 kprobe 一起跳過了。</p><h3><strong>Epilogue</strong></h3><p>其實我在 kernel module 中不斷遇到的 crash 問題很可能是因為我是從 kernel module 中直接呼叫 non-export function, 所以 TOC pointer 應該要被更新但沒被更新(因為直接呼叫到 local entry)，TOC pointer 沒被更新就有可能導致後續的 instruction 拿到不存在或是不正確的資料。</p><p>通常在軟體架構已經確定的情況下，我們很容易用既有的框架、手法去處理問題，因為使用方式簡單，就不用去思考底層的實作方式，但有時候也因此掉入思考盲區，忽略了真正問題的發生點。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4da9f685e383" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High performance server — static file serving]]></title>
            <link>https://medium.com/@7FrogTW/high-performance-server-static-file-serving-967363685407?source=rss-e3880fe8f62b------2</link>
            <guid isPermaLink="false">https://medium.com/p/967363685407</guid>
            <dc:creator><![CDATA[7FrogTW]]></dc:creator>
            <pubDate>Sat, 02 Jul 2022 11:38:38 GMT</pubDate>
            <atom:updated>2022-07-02T11:38:38.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>High performance server — static file serving</h3><p>When it comes to server IO, there are plenty of concepts to talk about. How to handle IO efficiently? How to boost IO performance?</p><p>In this article, I want to talk about how to choose appropriate system calls for static file serving.</p><h3>Read / Write Model</h3><p>The most intuitive way is to use read / write combination to read file into memory buffer and write to socket fd.</p><p>The problem of this approach is that we need to call read / write multiple times when a request comes in, but most of the time, this file is not modified.</p><p>From the following diagram, we can see there are 4 times of data copy in a read / write pair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*TzxTXsM7i1OL2WhH-ooaDQ.png" /><figcaption>read / write model</figcaption></figure><h3><strong>Mmap / Write Model</strong></h3><p>The first improvement comes to my mind is using mmap to map static files into a memory region, so we don’t need to read it every time when a request come in.</p><p>When request of a static file comes in the first time, we mmap it and store the corresponding memory buffer. In the following requests, we just need to write out the corresponding memory buffer to socket fd, it’s like a caching mechanism.</p><p>From the following diagram, we can see there are still 3 times of data copy when request of a static file first comes in, but only 2 times of data copy (write) in the following requests of a static file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*epRi8XjxDioEfKe7iqOqyA.png" /><figcaption>mmap / write model</figcaption></figure><p>The drawback of this approach is that we can’t modify those static files after the first request, because those files are already mapped into memory buffer, so we need another approach to handle this kind of situation.</p><h3>Sendfile Model</h3><p>Basically, sendfile is used to directly send a file from one fd to another fd, so we can save the CPU cycles and efforts to manage buffer, read buffer and write buffer in user space.</p><p>The sendfilesystem call is defined as:</p><pre>ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);</pre><p>After we opened a file, we can get the fd of this file, then we pass in file fd as argument in_fd and pass in socket fd as argument out_fd.</p><p>From the following diagram, we can see only 2 data copy are needed, which is the cheapest among the models we described.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*HekadGPvQk6Fsojx-qsm7A.png" /><figcaption>sendfile model</figcaption></figure><p>Unfortunately, io_uring doesn’t provide a function like io_uring_prep_sendfile , we need to use io_uring_prep_splice to implement this.</p><p>From the comment in liburing.h line 328, we can see why io_uring_prep_sendfile is not provided:</p><pre>* This splice operation can be used to implement sendfile by splicing to an<br> * intermediate pipe first, then splice to the final destination.<br> * In fact, the implementation of sendfile in kernel uses splice internally.<br> *<br>...</pre><p>To use io_uring_prep_splice , we need to prepare two pipe fd beforehand, one for pipe write and another for pipe read.</p><p>I use pipe2 system call to create it, svr-&gt;pipfds[0] is the read fd and svr-&gt;pipefds[1] is the write fd:</p><pre>#ifdef WATCH_STATIC_FILES<br>    if (UNLIKELY(__pipe2(svr-&gt;pipefds, O_CLOEXEC | O_NONBLOCK) &lt; 0)) {<br>        LOG_ERROR(&quot;Failed to create pipe fd\n&quot;);<br>        goto FREE;<br>    }<br>#endif</pre><p>After we have pipe fds, we are ready to use io_uring_prep_splice , the flow is illustrated in the following diagram. Firstly, splice from file fd to write fd of pipe, secondly, splice from read fd of pipe to socket fd.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*dQ_nWBBoohPIDjDZFJijkg.png" /><figcaption>splice flow</figcaption></figure><p>Here is a simple code snippet:</p><pre>#ifdef WATCH_STATIC_FILES<br>                io_uring_push_send((struct io_uring *)conn-&gt;svr-&gt;ring, conn-&gt;fd,<br>                                   fresstr-&gt;buf, fresstr-&gt;len, (void *)conn,<br>                                   MSG_MORE, IOSQE_IO_LINK);<br>                io_uring_push_splice((struct io_uring *)conn-&gt;svr-&gt;ring,<br>                                     res.file_fd, 0, conn-&gt;svr-&gt;pipefds[1], -1,<br>                                     res.file_sz, (void *)conn, IOSQE_IO_LINK);<br>                io_uring_push_splice((struct io_uring *)conn-&gt;svr-&gt;ring,<br>                                     conn-&gt;svr-&gt;pipefds[0], -1, conn-&gt;fd, -1,<br>                                     res.file_sz, (void *)conn, 0);</pre><p>The first io_uring_push_send is to send HTTP start-line and all the header fields.</p><p>The IO_SQE_IO_LINK flag is used to force multiple IO operations be executed in order.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=967363685407" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High performance server — GCC section attribute]]></title>
            <link>https://medium.com/@7FrogTW/l4-server-lab-%E5%95%8F%E9%A1%8C%E9%9B%9C%E8%A8%98-1539f7859647?source=rss-e3880fe8f62b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1539f7859647</guid>
            <dc:creator><![CDATA[7FrogTW]]></dc:creator>
            <pubDate>Fri, 06 May 2022 15:08:53 GMT</pubDate>
            <atom:updated>2022-07-01T07:34:42.217Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*VjRW8GaW7EqxSL3VrGjJ8A.png" /></figure><h4>前言</h4><p>大約五個月前開始了 <strong>l4-server-lab</strong> 這個專案，當時的目標很單純: 建立一個高效能的 TCP server!</p><p>為什麼叫做<strong> l4-server-lab</strong> ?</p><p>l4 就是 layer 4 的意思，包含 TCP/UDP…等 protocol, server 就是 server, lab 是因為當時本來只是想寫來玩玩兒，沒想到後來想做的東西在這個基礎上一直增加…</p><p>這個專案很有趣的地方:</p><ol><li>他是個 pure C 的專案</li><li>針對 x86_64 實作 coroutine swapper，這是用 assembly code 來達成</li><li>使用 io_uring 當作 IO Model, 我一直想玩這個新的 kernel feature 很久了，為了他還把 mac 灌成 Ubuntu…</li><li>部份 syscall 是不透過 glibc 的，而是直接使用 x86 的 assembly，這麼做的原因之前在 twitter 裡有寫過: <a href="https://twitter.com/JackyyinTW/status/1496808950355804163?s=20&amp;t=lP-s4y_S_xSkknF_vMeeLQ">https://twitter.com/JackyyinTW/status/1496808950355804163?s=20&amp;t=lP-s4y_S_xSkknF_vMeeLQ</a></li></ol><p>當然這個專案的基底還有很多值得優化的地方，包含 IO / context switch / multi-threads…等，那些才是真正最困難的部份，但我想要先讓這個專案有辦法被測量和簡單地使用(被我自己)，所以我決定實作 layer 7 的 HTTP protocol.</p><h4>HTTP Router</h4><p>回憶起以前寫 Node.js 的 Express framework 時，我們可以多麼容易地去定義一個 router:</p><pre>router.get(&#39;/&#39;, (req, res) =&gt; { <br>  // Do something<br>})</pre><p>為了要做到這件事情，我們會需要滿足以下條件：</p><ol><li>一個用來儲存 router 資訊的資料結構</li><li>在 compile-time 完成儲存的動作，因為 router 在 process 啟動前就已經確定</li><li>這個資料結構需要 cross 多個 compilation units，因為最後我們的這包可能會是一個 static 或 dynamic library，這時候使用者會 link with 這包 library，router 很可能是定義在使用者端的</li><li>當 HTTP request 進來，我們可以 iterate 這些 routers 並找到適合的那一個</li></ol><p>參考了一些專案後，我發現可以利用 GCC 的 section attribute 來建立一個 global 的 storage，並且這個空間最後會由 linker 在 link 階段加入</p><p>經過一些努力和 macro 的奇計淫巧，我們現在可以得到這種形式的 router 語法:</p><pre>ROUTER(/simple/y)<br>{<br>  // Do something here<br>}</pre><p>其實跟 Express 已經很接近，但我們還需要再加上 HTTP method…</p><h4>問題浮現</h4><p>其實這個修改只是把儲存 router 的 struct 加上一個 method 欄位，但這個操作會直接導致我在 iterate 所有 routers 的時候產生 Segmentation Fault:</p><pre>// Before<br>struct router {<br>    const char *path;<br>    route_handler *fp;<br>};</pre><pre>// After<br>struct router {<br>    const char *path;<br>    route_handler *fp;<br>    int method;<br>};</pre><p>從 gdb 去看 crash 的地方是斷在 multiarch/strcmp-avx2.S 的第 102 行，推測這應該是 glibc 所實做的 <a href="https://code.woboq.org/userspace/glibc/sysdeps/x86_64/multiarch/strcmp-avx2.S.html#102">strcmp assembly code</a> :</p><pre>vpcmpeqd        (%rsi), %ymm1, %ymm0</pre><p>當時直覺是因為我沒有實做 floating-point registers 的 coroutine swap，所以導致 glibc 要使用這些 registers 會存取到怪怪的地址，但當我把 ymm系列的 registers 都實做完後問題仍然發生在這一行，所以我開始懷疑 (%rsi) 的地址是否合法</p><p>vpcmpeqd (%rsi), %ymm1, %ymm0 會比較 %ymm1 和 %ymm0 的每一個 bytes並且依序寫入 %(rsi) 中:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*ZG_4NKeZeglhp5a4fsRzPg.png" /></figure><p>根據 x86 的 calling convention, rsi 就是傳入 strcmp 的第二個參數，所以我把傳進去的參數都印出來，發現真的有一些奇怪的值被傳入，這也就代表 router 的 iterator 並沒有正確地在 iterate 我們的 routers，也就是說我們的 struct 雖然是 20 個 bytes，但他排列在記憶體中因為 alignment 的關係使得每個 struct 之間有間隔，所以 iterate 的 pointer 可能會存取到一些不合理的資料…</p><p>原來 linker 為了效能會自動幫 sections 裡的 object 做 memory alignment，所以一個 20 bytes 的 object 很可能會被排到 32 bytes 的 address boundary…</p><p>為了這個問題所作的修改:</p><p><a href="https://github.com/JackyYin/l4-server-lab/commit/7ccd39c930186016a45f283d98be22262f40fe08">feat: support user-defined method and path · JackyYin/l4-server-lab@7ccd39c</a></p><p>完成之後我們可以很開心地這樣定義 router:</p><pre>ROUTER(GET, /simple/x)<br>{<br>  // Do Something<br>}</pre><p>下一步，目前的想法是新增 serve static files 的 router，這樣才可以更方便加入一些前端元素，然後看能不能用 Vue 顯示一些簡單又花俏的小玩意兒。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1539f7859647" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Assembly — function & stack alignment]]></title>
            <link>https://medium.com/@7FrogTW/assembly-function-stack-alignment-cc2389ff0cef?source=rss-e3880fe8f62b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc2389ff0cef</guid>
            <category><![CDATA[assembly]]></category>
            <dc:creator><![CDATA[7FrogTW]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 08:41:39 GMT</pubDate>
            <atom:updated>2022-01-06T08:44:53.934Z</atom:updated>
            <content:encoded><![CDATA[<h3>Assembly — function &amp; stack alignment</h3><h4>前言</h4><p>前幾個月因為公司使用的 compiler 更新，踩到跟 compiler optimization 有關的坑，當時需要比較優化前後產生的 assembly code 有什麼差異，並找出是哪一條優化產生了非預期的結果，因而被迫重新熟悉 assembly code。</p><p>最近因為自己的 side project 需要有 coroutine 功能，但是覺得 glibc 的 ucontext或是 setjmp/ longjmp都不夠合用，於是又想到用 assembly 來造個輪子，關於 coroutine 的介紹留到之後補充。</p><p>本篇文章將介紹 x86_64 架構下 function 和 stack 的使用及注意事項。</p><h4>function parameters</h4><p>通常當我們在撰寫高階語言時，不太會注意到 function parameters 的數量及順序，但這在 assembly 中卻相當重要。</p><p>x86_64 中關於 calling convention 的規定，非浮點數的參數(包含 pointers) 會依照 %rdi<em>, </em><em>%rsi, </em><em>%rdx, </em><em>%rcx, </em><em>%r8, </em><em>%r9</em>的順序由 registers 帶入 function 中;浮點數的參數會依照 xmm0 ~ xmm7 的順序由 registers 帶入 function 中。</p><p>而超過這個範圍的參數會被推入 stack 上，並且須由 caller 在 function return 後自行清理。</p><p>需要認知到的是在撰寫高階語言時，也應考慮到參數數量的問題，過多的參數會導致動用到 stack 去傳遞參數，因為 register 和 memory access 的速度有極大落差，這會導致整體執行時間變慢很多，詳見下圖金字塔:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*6VqLpbI6jy7hbb-gkysX7Q.png" /><figcaption>Memory Hierarchy, Reference: <a href="https://hackmd.io/@sysprog/c-memory?type=view">https://hackmd.io/@sysprog/c-memory?type=view</a></figcaption></figure><h4>callee-save registers</h4><p>x86_64 的 calling convention 中有規定某些 registers 在進入 function 之後應當被保存，就是所謂的 callee-save registers，其中包含: %rbp , %rbx , %r12 , %r13, %r14 , %r15 。</p><p>通常這些 registers 仍然能被使用，但會先把舊的值寫到 stack 上再使用，等 function 要離開時再恢復。</p><h4>stack alignment</h4><p>進入本篇我覺得最重要也最難理解的部分，這就是我在寫 coroutine 時踩到的一個大坑。</p><p>x86_64 的 calling convention 規定 %rsp 在 call 之前需要 align 在 16 bytes 的 memory boundary 上，意思是 %rsp 所指向的 address 需要是 16 bytes 的倍數。</p><p>通常來說有幾種狀況會強烈建議做好 stack alignment:</p><ol><li>在 macOS 平台運行，因為 macOS 對於 stack alignment 有更嚴格檢查</li><li>你 call 的 function 是外部函式庫，像是 glibc 的 printf 或是其他 system call</li><li>你 call 的 function 有使用到 AVX 系列的 instructions</li></ol><p>這裡我想先解釋 call 這個指令，參考以下程式碼，當 main function 執行到 call f 時，會先把下一行的 xor rax, rax 的位址 push 進 stack 中，並且跳轉到 function f, 等到 function f 呼叫 ret 時，便會 pop 出這個指令的位址，並且跳轉回到第七行。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5984f051b2a5699fbd91a898b5347ab/href">https://medium.com/media/e5984f051b2a5699fbd91a898b5347ab/href</a></iframe><p>乍看之下很簡單，但需知道在 call 被呼叫之後 %rsp 因為會多一個 return address，所以 address 會 +8 bytes，所以如果有遵守慣例，通常在所有 function 一進入時 %rsp 都不會是 16 的倍數。</p><p>知道 call 的運作之後，還有一點需知道的是 %rsp 會在進入 main function 前就在 16 bytes alignments 上，所以當進入 main function 後， %rsp 已經在 16n + 8，這時呼叫自定義的 function 沒有關係，但是若呼叫像是 glibc的 function 就可能直接噴一個 segmentation fault。</p><p>macOS 相較於 Linux 平台有更嚴格的 stack alignment 檢查，所以想要看到噴出 seg fault 的話可以用 macOS 測試，程式碼:</p><pre>   1   │           global    _main<br>   2   │           extern    _puts<br>   3   │           default   rel<br>   4   │<br>   5   │           section   .text<br>   6   │ _main:<br>   7   │           mov       rdi, message<br>   8   │           call      _puts<br>   9   │           ret<br>  10   │ message:<br>  11   │           db        &quot;5&quot;, 0</pre><p>編譯及執行 :</p><pre>nasm -fmacho64 call_mac.asm &amp;&amp; gcc call_mac.o &amp;&amp; ./a.out</pre><p>應會看到類似以下結果:</p><pre>[1]    37847 segmentation fault  ./a.out</pre><p>接下來可以針對以下 C code 的產出來觀查:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e72ad1435afef220ad8ef4542562f80/href">https://medium.com/media/5e72ad1435afef220ad8ef4542562f80/href</a></iframe><p>編譯 (gcc version 9.3.0 (Ubuntu 9.3.0–17ubuntu1~20.04)):</p><pre>gcc -o test.S -fomit-frame-pointer -S stack.c</pre><p>產出 (部分):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74b5cc450c0b41e1549d3c478c0e1759/href">https://medium.com/media/74b5cc450c0b41e1549d3c478c0e1759/href</a></iframe><p>可以看到所有 call instructions 之前都會有 subq xxx, %rsp ，因為 stack 的 memory layout 是由高位往低位發展，所以 subq 等同於 push ，stack 空間增大。</p><p>不論是 subq $8, %rsp 或是 subq $24, %rsp 其實都是為了 stack alignment，前面說到進入 function 後， call 會 push 另外 8 bytes 的 return address，所以此時 %rsp會在 16n + 8 的位址，因此再次呼叫 call之前再補上 16n + 8 bytes( $8 /%24)就會剛好是 16 的倍數。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc2389ff0cef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[2021 心得回顧]]></title>
            <link>https://medium.com/@7FrogTW/2021-%E5%BF%83%E5%BE%97%E5%9B%9E%E9%A1%A7-eb6e2451a9?source=rss-e3880fe8f62b------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb6e2451a9</guid>
            <dc:creator><![CDATA[7FrogTW]]></dc:creator>
            <pubDate>Sun, 02 Jan 2022 15:53:25 GMT</pubDate>
            <atom:updated>2022-01-02T15:53:25.738Z</atom:updated>
            <content:encoded><![CDATA[<p>2021的尾聲，我常常在想要如何為這一年寫下結語，又要以什麼樣的期待來開啟新的一年？</p><h4>回顧</h4><p>動盪，這一年經歷了換工作，才在新公司上班一個月就因為疫情大爆發而逃回新竹遠端工作 3 個多月。</p><p>休養，因為3個月的 WFH 、新公司文化和我們 team 目前沒有前輩的關係，讓我常常覺得工作步調比較慢，相對來說有很多時間可以留給自己，我想這對我來說是一件好事，可以更好地達到 work-life balance.</p><p>改變，因為才到新崗位沒多久前輩就離開了，所以我就變成了這個 team 的最資深員工，之後帶著台大資工的學妹一邊開發一邊摸索，這件事情對我來說有兩層意義，一方面是我終於開始接觸到 C/C++ 的正式工作經驗、另一方面是我也開始學習怎麼帶人。</p><p>最重要的，回饋，除了開始提攜後輩之外，也開始貢獻開源專案，看著 merged PR 慢慢變多，就會覺得自己對社會也有所貢獻。</p><h4>展望</h4><p>一直以來我都不是對生活會有太多規劃的人，不過也許我現在先寫下，等到明年時便可再次對照和現在的想法和心境有何不同。</p><p>目標：</p><ul><li>多寫一些文章，技術或是非技術都好</li><li>繼續完成現在做的 side project，並且發技術分享</li><li>繼續貢獻開源專案</li><li>繼續打羽球(趁現在還能?)</li></ul><p>明年因為一些原因，也許會去澳洲工作，新的一年，更大的風浪又無情地拍打過來，也希望屆時我可以順利找到我心目中理想的工作。</p><p>到了這個年紀，慢慢瞭解了自己，不是那種才華洋溢的人、也不是那種多有天份的人，以前的一個好朋友曾經跟我說過要習慣<strong>低成就感</strong>，我那時一直不懂，但我現在漸漸可以理解，做一件事情，常常做、每天做，在其中找到樂趣、找到方法，這樣一定可以緩慢地成長，如果做什麼事情都想要一蹴而就，那反而會因為不當的期待而太早放棄。</p><p>到了這個年紀，不管是家人或是朋友，還留在身邊的那些大概就是會一起走一輩子的人，選擇與取捨，不要把時間和精力再花在不理解或是不珍惜自己的人身上，人生這麼短，更應該去選擇適合自己的環境以及朋友，一個人的時候，常常會想到過去做過的那些錯事，我很了解自己背負的罪以及自己的不完美，所以更加努力要變成更好的人，同時也更加感激還願意留在身邊的人，一起成長或是一起浪費時光都是一種幸福。</p><p>2021 的最後，心裡充滿滿足和感謝，謝謝出現在身邊的每一個人，今年的我過得很幸福，謝謝。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb6e2451a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[如何使用Vault做到DB帳密租借及自動汰換]]></title>
            <link>https://medium.com/@7FrogTW/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8vault%E5%81%9A%E5%88%B0db%E5%B8%B3%E5%AF%86%E7%A7%9F%E5%80%9F%E5%8F%8A%E8%87%AA%E5%8B%95%E6%B1%B0%E6%8F%9B-2a338fc00f42?source=rss-e3880fe8f62b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a338fc00f42</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[vault]]></category>
            <dc:creator><![CDATA[7FrogTW]]></dc:creator>
            <pubDate>Sat, 04 Jan 2020 13:49:31 GMT</pubDate>
            <atom:updated>2020-01-04T13:52:58.437Z</atom:updated>
            <content:encoded><![CDATA[<h3>前言</h3><p>前陣子因為看了幾篇大大們所寫文章,也剛好在想有沒有更好的方式可以管理機密性的環境變數,像是AWS的access key或是DB連線資訊、API KEY或是私鑰等等,所以開始接觸<a href="https://github.com/hashicorp/vault">vault</a>這個神秘的東西,vault是由鼎鼎大名的hashicorp開發的大型開源專案,我實際實作的層面只是九牛一毛而已,接下來會介紹如何建立一個vault DEV server,並且用node做到自動租借mongoDB連線。</p><h3>建立Vault DEV Server</h3><p>首先先來看專案目錄下的.env檔,裡面定義了一些我等下要用到的環境變數:</p><pre>VAULT_TOKEN=myroot<br>VAULT_PORT=8200</pre><pre>MONGO_HOST=host.docker.internal<br>MONGO_PORT=27017<br>MONGO_USERNAME=root<br>MONGO_PASSWORD=root<br>MONGO_DATABASE=test</pre><p>MONGO相關的環境變數現在還不著急,</p><p>接著來看我定義要啟動vault的 docker-compose.yml:</p><pre>version: &#39;3.5&#39;</pre><pre>services:<br>  vault:<br>    image: vault<br>    ports:<br>      - &#39;${VAULT_PORT}:8200&#39;<br>    cap_add:<br>      - IPC_LOCK<br>    environment:<br>      - VAULT_DEV_ROOT_TOKEN_ID=${VAULT_TOKEN}</pre><p>然後在專案下面執行:</p><pre>docker-compose up</pre><p>如此一來,vault DEV server就啟動拉～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*EEWkNQNK3w3puBRszAC_Sw.jpeg" /></figure><h3>Vault Secret Engine</h3><p>接下來需要的就是跑一些vault command來設定mongoDB secret engine,這邊我都參考自: <a href="https://www.vaultproject.io/docs/secrets/databases/mongodb.html">vault官方文件</a>, 因為每次跑起來都打指令太麻煩了,所以索性寫了一支shell script:</p><pre>#!/bin/sh</pre><pre>export $(grep -v &#39;^#&#39; .env | xargs)<br>export VAULT_ADDR=<a href="http://localhost:${VAULT_PORT">http://localhost:${VAULT_PORT</a>}</pre><pre>docker-compose up -d<br>echo ${VAULT_TOKEN} | vault login -</pre><pre>vault secrets enable database</pre><pre>vault write database/config/my-mongodb-database \<br>  plugin_name=mongodb-database-plugin \<br>  allowed_roles=&quot;my-role&quot; \<br>  connection_url=&quot;mongodb://${MONGO_USERNAME}:${MONGO_PASSWORD}@${MONGO_HOST}:${MONGO_PORT}/admin&quot;</pre><pre>vault write database/roles/my-role \<br>  db_name=my-mongodb-database \<br>  creation_statements=&#39;{ &quot;db&quot;: &quot;admin&quot;, &quot;roles&quot;: [{&quot;role&quot;: &quot;readWrite&quot;, &quot;db&quot;: &quot;&#39;&quot;${MONGO_DATABASE}&quot;&#39;&quot;}]}&#39; \<br>  default_ttl=&quot;5s&quot; \<br>  max_ttl=&quot;10s&quot;</pre><p>這邊我把docker-compose的指令也夾在裡面了,但有時候docker-compose up 指令跑太慢了,會導致下面的vault指令失敗(因為vault API還沒準備好),所以如果怕失敗可以拆出來,另外需要注意為了方便觀察,我把ttl時間調短成5秒,所以一次租借DB帳密的租期為5秒,如果shell script成功執行,那前置作業也算告成拉～</p><h3>Programming</h3><p>接下來就是我用Nodejs做自動租借和query mongoDB的部分,分為有自動換發的測試和無自動換發的測試,</p><p>以下是有自動換發的版本, 我測試的方式是每三秒自動汰換帳號密碼、建立連線並且每秒做一次query:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F06fDamtU_S0%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D06fDamtU_S0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F06fDamtU_S0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5f7f9d31379cc0e3b6be55ae37e67f2/href">https://medium.com/media/e5f7f9d31379cc0e3b6be55ae37e67f2/href</a></iframe><p>影片中可以看到每3秒都有取得一個新的連線資訊,並且每秒的query可以正常執行,再來看看實際上連線過期的話會造成什麼影響:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwPTVoX7eFVk%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwPTVoX7eFVk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwPTVoX7eFVk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b18af34b8dd758e6c3dd476dfb4dc16/href">https://medium.com/media/5b18af34b8dd758e6c3dd476dfb4dc16/href</a></iframe><p>可以看到雖然我只取得一次mongoDB連線,但在這組帳號密碼過期後,一樣沒辦法對DB進行query了</p><h3>結論</h3><p>所以survey了那麼多,嘗試了那麼多,為何還沒把這套機制帶進公司?主要是有幾點疑慮:</p><ol><li>當DB帳密過期的那瞬間,如果剛好有request進來然後我在跟vault要帳密要到一半,那是不是會影響到使用者?</li><li>程式端雖然不必存DB連線的帳號密碼,但仍然需要存vault的token,那我洩漏vault token是不是更慘? 除非vault有辦法對每個token都給予不同存取權限</li><li>目前對vault掌握度還不夠高,到時候production真的出問題導致連線都斷掉,不是玩火自焚嗎XD</li></ol><p>以上有任何不了解歡迎討論也可參考我的repo,感謝耐心閱讀!</p><p><a href="https://github.com/JackyYin/vault-demo">JackyYin/vault-demo</a></p><p>此篇文章參考自:</p><p><a href="https://medium.com/@tasslin/%E7%95%B6kubernetes%E9%81%87%E8%A6%8Bvault-e9adbcee5d54">https://medium.com/@tasslin/%E7%95%B6kubernetes%E9%81%87%E8%A6%8Bvault-e9adbcee5d54</a></p><p><a href="https://medium.com/getamis/vault-dynamic-credentials-fd651d6c28a9">https://medium.com/getamis/vault-dynamic-credentials-fd651d6c28a9</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a338fc00f42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Base64]]></title>
            <link>https://medium.com/@7FrogTW/introduction-to-base64-7a9978c51570?source=rss-e3880fe8f62b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a9978c51570</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[base64]]></category>
            <category><![CDATA[binary]]></category>
            <dc:creator><![CDATA[7FrogTW]]></dc:creator>
            <pubDate>Fri, 20 Dec 2019 17:16:53 GMT</pubDate>
            <atom:updated>2019-12-22T02:53:49.786Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction to Base64 Encode</h3><p>This article will show my understanding of base64 encode and how computer interpret and form characters.</p><h3>What happened when we type text in our computer ?</h3><p>As a software developer, we have all heard of ASCII code, UTF-8, Base64 encode…etc, I see those as ways of interpreting characters.</p><p>For example, when computer receive a string like this:</p><pre>APPLE</pre><p>it will be converted to a computer readable language like this:</p><pre>01000001 01010000 01010000 01001100 01000101</pre><p>Each English alphabet take exactly 8 bits in both ASCII and UTF-8 encode.</p><h3><strong>Base64 Encode</strong></h3><p>When we are talking about convert something to base64 string, we are actually rearrange the underlying bits to many 6 bits groups and convert it back to string.</p><p>Why 6 bits ? Because 2 to the power of 6 equals 64, means we have 64 spaces to form different characters.</p><p>So, according to the bits above, we can rearrange the bits like this:</p><pre>010000 010101 000001 010000 010011 000100 0101[00]<br>// two 0 in [] means padding<br>// remember to pad if bits can&#39;t be divided by 6</pre><p>According to the table below, we are able to form the base64 string like this:</p><pre>Q V B Q T E U =</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZ-zM0MDdiWi__bECJfW0g.png" /></figure><h3>But wait, why is there a ‘=’ in the end of the string?</h3><p>I think this is a hack for converting back the string to binary, the “=” is used to represent how many 0 are added, when there are two 0 added, one “=” will be pushed to the back of the base64 string.When computer convert back the string to binary, the added 0 and “=” will be truncated.</p><pre>const buf1 = Buffer.from(&#39;APPLE&#39;)<br>const base64Str = buf1.toString(&#39;base64&#39;)<br>const buf2 = Buffer.from(base64Str, &#39;base64&#39;)<br>console.log(Buffer.compare(buf1, buf2)) // 0</pre><h3>Real Life Example</h3><p>I have always heard of storing image as a base64 string in database. Though I never tried before, my intuition told me there are many flaws of using this approach.</p><p>Many people believe that base64 is a decompression mechanism, but the size of base64 string is actually approximately 4/3 time larger than the original pic. That’s assume that we store an average 1MB large original picture in DB, we have to pull at least 1.333 GB for only1000 rows of data, not to mention the string size limit of column.</p><p>To prove and clarify my assumption, I have made a demo project. In this project, I do 3 parallel tasks, each convert an image to base64 string, open a mongoDB connection and upload the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yL97cQp5U2Jf4iGmXLPjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*358FhbllcWnbEJNU6y61-w.png" /></figure><p>After several sampling, I found that image5 (the largest) will always take 0.5 ~ 1 times more of time than the second one when upload and 1~ 2 times more of time when query.</p><p>So the data size does matter. In my opinion , store large image in S3 would be better.</p><h3>Conclusion</h3><p>Although understand the underlying mechanism of base64 won’t help a lots in software development and architecture design, I am still glad to dig in and understand the most basic part of computer science. Check my repo below if you are curious about my implementation and thanks for reading.</p><p><a href="https://github.com/JackyYin/base64-demo.git">JackyYin/base64-demo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a9978c51570" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>