<?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 Desmond Cheong on Medium]]></title>
        <description><![CDATA[Stories by Desmond Cheong on Medium]]></description>
        <link>https://medium.com/@desmondcheongzx?source=rss-fbd1952cf037------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rh0v2nroOn_g0L7IVPmw1g.png</url>
            <title>Stories by Desmond Cheong on Medium</title>
            <link>https://medium.com/@desmondcheongzx?source=rss-fbd1952cf037------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:19:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@desmondcheongzx/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[Dynamic program analysis in the Linux kernel]]></title>
            <link>https://desmondcheongzx.medium.com/dynamic-program-analysis-in-the-linux-kernel-e2176d25d34f?source=rss-fbd1952cf037------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2176d25d34f</guid>
            <category><![CDATA[linux-kernel]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Desmond Cheong]]></dc:creator>
            <pubDate>Sun, 30 May 2021 01:48:07 GMT</pubDate>
            <atom:updated>2021-05-30T01:48:07.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXNs8nP__qOL1-t65wN2gA.png" /></figure><p><a href="https://events.linuxfoundation.org/mentorship-session-dynamic-program-analysis/">Dynamic Program Analysis for Fun and Profit</a> with Dmitry Vyukov. Part of the LF Live: Mentorship Series.</p><p>Recently, I was accepted into the <a href="https://wiki.linuxfoundation.org/lkmp">Linux Kernel Mentorship Program</a>. If you’d told a younger Desmond that he’d be doing something like this, he would’ve been quite shocked because for the longest time the open source world had seemed so impenetrable. I am very grateful for this opportunity, and in a way, it’s a continuation of the long journey I embarked on since my earlier post on <a href="https://www.desmondcheong.com/blog/2021/01/01/a-goal-to-dive-into-cpython/">chasing large code bases</a>.</p><p>As part of this journey, and in the spirit of open source work and learning in public, I’ve decided to document my experience working with the Linux kernel. One of the first tasks that was assigned to me was to watch a webinar on <a href="https://events.linuxfoundation.org/mentorship-session-dynamic-program-analysis/">Dynamic Program Analysis</a>, and I thought it’d be great to share my notes in a blog post.</p><h3>Program analysis</h3><p>Program analysis is the process of automatically analyzing the properties of a program, such as its performance and correctness, as well as to extract information such as the program’s call graph or the flow of data. This is useful for detecting, or deliberately provoking, bugs to allow you to harden your system.</p><p>The goals of program analysis are quite similar to the goals of observability: we want to reduce time to insight into a system. But on top of this, program analysis also endeavors to detect bugs before they occur in the wild.</p><p>There’s also a need to draw a distinction between <em>dynamic </em>and <em>static </em>program analysis, as the two are used to target different classes of bugs. Dynamic program analysis captures the properties of a running program, or more specifically, a single execution of a running program. In contrast, static analysis uses the source code to capture properties that hold for all executions of the program. However, such an ambitious goals comes with trade-offs. Consider the following example that Dmitry posed:</p><pre>void func()<br>{<br>	char *p = malloc(10);<br>	p[20] = 1;<br>}</pre><p>This C function makes an out-of-bounds access to p[20]. This seems simple enough to catch as long as we take note of the size allocated to a buffer and compare this against all subsequent accesses to that buffer. However, let’s now consider this scenario:</p><pre>void func(int index)<br>{<br>	char *p = malloc(10);<br>	p[index] = 1;<br>}</pre><p>Just by making the index into the buffer a variable, things have gotten a lot more complicated. We can’t make any assumptions about how the index might be computed, and it could be computed in many different ways in many different parts of the source code. Imagine if, in the computation of the index, other arrays and indices were involved (meaning we’d have to go even further back to figure things out), or if multiple threads were involved, or if multiple function calls are involved, or if a cryptographic function was used. The task for static analysis becomes very intractable.</p><p>But what about a dynamic program analyzer? Why, all it needs to do is memorize the size of the heap block when it was first allocated, then whenever the heap block is accessed, we compare the index with the block size and report an out-of-bounds bug as needed.</p><p>The key insight here is that complex bugs now become possible to analyze, and all bug reports are true positives because the bug <em>actually happened</em>. The downside is that these bugs can only be caught if the particular tests being run manages to trigger them. That aside, having no false positives makes dynamic analysis bug reports very very valuable. Like the boy who cried wolf, an analyzer that raises too many false alarms will find itself being ignored. It’s not like there’s no shortage of other bugs to deal with.</p><p>However, if you can trust the program analyzer’s bug report, then you can immediately flag issues with various commits and stop them from being merged into production. Or, if it’s already too late, you at least know that your time is being well spent when you dive deep into a bug.</p><h3>Analysis tools</h3><p>Now that we know how great dynamic program analysis is, how do we do it?</p><p>Instrumentation.</p><p>There’s many debugging configuration settings in the kernel that help catch bugs at compile and run time. Here’s an example for list debugging.</p><h4>CONFIG_DEBUG_LIST</h4><p>Linked lists are a very important data structure, so the kernel implements a common API for kernel developers to use. To link any objects together, one simply embeds a list_head into the structure that defines the object:</p><pre>struct my_struct {<br>	struct list_head list;<br>	/* other fields here */<br>};</pre><p>Once this is done, you can then use the provided <a href="https://www.kernel.org/doc/html/v4.15/core-api/kernel-api.html">list management functions</a> to link your objects together. To ensure that your lists are set up properly, you can compile the kernel with CONFIG_DEBUG_LIST=y. Consider deleting entries from a linked list. If we take a look at include/linux/list.h, we&#39;ll see the following:</p><pre>#ifdef CONFIG_DEBUG_LIST<br>extern bool __list_add_valid(struct list_head *new,<br>			      struct list_head *prev,<br>			      struct list_head *next);<br>extern bool __list_del_entry_valid(struct list_head *entry);<br>#else<br>static inline bool __list_add_valid(struct list_head *new,<br>				struct list_head *prev,<br>				struct list_head *next)<br>{<br>	return true;<br>}<br>static inline bool __list_del_entry_valid(struct list_head *entry)<br>{<br>	return true;<br>}<br>#endif</pre><p>When CONFIG_DEBUG_LIST is set, we see that a __list_del_entry_valid() function is declared but not defined. In lib/list_debug.c, we see the following definition:</p><pre>bool __list_del_entry_valid(struct list_head *entry)<br>{<br>	struct list_head *prev, *next;</pre><pre>	prev = entry-&gt;prev;<br>	next = entry-&gt;next;</pre><pre>	if (CHECK_DATA_CORRUPTION(next == LIST_POISON1,<br>			&quot;list_del corruption, %px-&gt;next is LIST_POISON1 (%px)\n&quot;,<br>			entry, LIST_POISON1) ||<br>	    CHECK_DATA_CORRUPTION(prev == LIST_POISON2,<br>			&quot;list_del corruption, %px-&gt;prev is LIST_POISON2 (%px)\n&quot;,<br>			entry, LIST_POISON2) ||<br>	    CHECK_DATA_CORRUPTION(prev-&gt;next != entry,<br>			&quot;list_del corruption. prev-&gt;next should be %px, but was %px\n&quot;,<br>			entry, prev-&gt;next) ||<br>	    CHECK_DATA_CORRUPTION(next-&gt;prev != entry,<br>			&quot;list_del corruption. next-&gt;prev should be %px, but was %px\n&quot;,<br>			entry, next-&gt;prev))<br>		return false;</pre><pre>	return true;</pre><pre>}<br>EXPORT_SYMBOL(__list_del_entry_valid);</pre><p>Here, we see that in addition to list deletion, we also check that the invariant properties of a linked list still hold.</p><p>A comprehensive list of other debug configurations be found on <a href="https://linuxfoundation.org/wp-content/uploads/Dynamic-program-analysis_-LF-Mentorship.pdf">slide 23 of Dmitry’s presentation</a> onwards, but for convenience, I’ve also <a href="https://github.com/desmondcheongzx/cornplough/blob/main/notes/DEBUG.md">compiled them into a markdown list</a>.</p><p>In addition, Dmitry mentions that using functions such as BUG_ON() and WARN_ON() are also very helpful. These are the kernel equivalents of assert statements, and if you use them in your functions, you can ensure that any assumptions you make will be true (and if not, the kernel crashes or emits a warning). It also makes for strong documentation, because you don’t just tell yourself and other developers what should be the state of the program, you <em>assert</em> it.</p><h3>KASAN (Kernel Address SANitizer)</h3><p>KASAN is a tool (turned on by setting CONFIG_KASAN=y) to detect bad memory accesses, such as out-of-bounds errors, or use-after-free errors, for heap, stack, and global variables:</p><pre>p = kmalloc(10);<br>p[20] = 1; // out-of-bounds</pre><pre>kfree(p);<br>p[0] = 1; // use-after-free</pre><p>The problem with bad memory accesses is that you don’t realize there’s a problem until much later. As Dmitry elegantly puts it, you’d expect such bugs to make a program go boom. However, programs will happily write to out-of-bounds memory then carry on with other work. It’s only until the corrupted memory is used that we <em>might</em> experience a crash. And by that time, the source of our bug would have flowed down the river and we won’t know where to begin debugging.</p><p>KASAN makes the things that should go boom, well, go boom. Here’s the sample KASAN output from Dmitry’s slides:</p><pre>BUG: KASAN: use-after-free in remove_wait_queue<br>Write of size 8 by task syzkaller/10568</pre><pre>Call Trace:<br>list_del include/linux/list.h:107<br>__remove_wait_queue include/linux/wait.h:145<br>remove_wait_queue+0xfb/0x120 kernel/sched/wait.c:50<br>...<br>SYSC_exit_group kernel/exit.c:885</pre><pre>Allocated:<br>kmem_cache_alloc+0x10d/0x140 mm/slub.c:2517<br>sk_prot_alloc+0x69/0x340 net/core/sock.c:1329<br>sk_alloc+0x33/0x280 net/core/sock.c:1404<br>...<br>SYSC_socketpair net/socket.c:1281</pre><pre>Freed:<br>kmem_cache_free+0x161/0x180 mm/slub.c:2745<br>sk_prot_free net/core/sock.c:1374<br>...<br>SYSC_write fs/read_write.c:585</pre><p>Here we see the error that occurred (use-after-free), where it happened, the context in which it was called, where the memory in question was allocated, and when it was freed. Awfully convenient isn’t it.</p><p>How does this work under the hood? KASAN assigned a shadow byte for every 8 bytes of kernel memory. This shadow byte contains information on whether the kernel memory is good to access, or bad, meaning that it’s been freed or it’s out-of-bounds.</p><figure><img alt="Depiction of shadow memory. Each 8 bytes of kernel memory maps to a byte of shadow memory with a value from -1 to 8 depending on the number of good and bad kernel bytes." src="https://cdn-images-1.medium.com/max/1024/0*8LBNlo47335zvxut.png" /><figcaption><a href="https://linuxfoundation.org/wp-content/uploads/Dynamic-program-analysis_-LF-Mentorship.pdf">Dynamic Program Analysis for Fun and Profit</a>, slide 33</figcaption></figure><p>Then, during compilation, every memory access is instrumented to check that the accessed kernel memory locations are valid. For example, if we want to write to the address p:</p><pre>*p = 1;  // 8 bytes</pre><p>Then the compiler adds a check beforehand:</p><pre>shadow = p &gt;&gt; 3 + 0xdffffc0000000000;<br>if (*shadow)<br>	kasan_report8(p);<br>*p = 1;  // 8 bytes</pre><p>Now that we have a mechanism to ensure that only good memory locations are accessed, we modify our virtual addresses to catch errant memory accesses.</p><figure><img alt="Depiction of heap objects with KASAN. Heap objects now have red-zones at the ends of heap object boundaries." src="https://cdn-images-1.medium.com/max/1024/0*vqZsUJXg2f3Lk93U.png" /><figcaption><a href="https://linuxfoundation.org/wp-content/uploads/Dynamic-program-analysis_-LF-Mentorship.pdf">Dynamic Program Analysis for Fun and Profit</a>,slide 35</figcaption></figure><p>If we try to access memory that’s out-of-bounds, we’ll likely step into a red-zone and be alerted.</p><p>We can also add a delay between freeing and re-allocating memory (since memory is allocated last-in-first-out), to catch instances of using memory after it’s been freed. Presumably these use-after-free bugs happen close to when freeing happens (in terms of code, they’re probably just a few lines apart), so this delay would be effective.</p><figure><img alt="Depiction of quarantine for freed memory blocks. There is now a time delay between freeing a block (via kfree()) and reallocating the block (via kmalloc())." src="https://cdn-images-1.medium.com/max/1024/0*dmmsIrkp-LjbcuT6.png" /><figcaption><a href="https://linuxfoundation.org/wp-content/uploads/Dynamic-program-analysis_-LF-Mentorship.pdf">Dynamic Program Analysis for Fun and Profit</a>,slide 36</figcaption></figure><p>Of course, it’s important to note that these methods won’t catch <em>all</em> memory access bugs. But it catches many of them at the places where they’re likely to occur (at the ends of allocated memory, or right after memory has been freed), and indeed in practice KASAN has done very well and caught some 1000 bugs in the past few years. What’s important is that there are no false positives, so if you see a KASAN bug, you act on it; and there’s low barriers to adoption because it works out of the box, and has low overheads (~2x slowdown, and ~2x memory overheads).</p><h3>Conclusion</h3><p>So after all this discussion on dynamic program analysis, where does the “fun and profit” come in? This wasn’t explicitly discussed in the webinar, but I think it’s worth reflecting on for a bit.</p><p>The profit aspect is clear. Program analysis is a <strong>cost-effective</strong> way to find bugs. <em>Bugs are expensive</em>. They can take hours, days, or even months of developer effort to solve. But you know what’s an especially costly bug? One that’s been allowed to wreck havoc in the wild. If you can catch bugs when they happen (see: make things that should explode go boom), then you can fix it much more easily. Much better than trying to swim through <a href="https://en.wikipedia.org/wiki/Linux_kernel#Codebase">30 million lines of code</a>.</p><p>And the fun part? Well, it’s fun to have a clear and concrete challenge in front of you, isn’t it. If a program analysis tool takes out all the mystery and tells you that there’s a bug at such-and-such line, where the memory was allocated here, and freed over there, then all that’s left is for you to roll up your sleeves and get to it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2176d25d34f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a simple REPL in Go]]></title>
            <link>https://desmondcheongzx.medium.com/writing-a-simple-repl-in-go-b279e6f4469a?source=rss-fbd1952cf037------2</link>
            <guid isPermaLink="false">https://medium.com/p/b279e6f4469a</guid>
            <category><![CDATA[repl]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Desmond Cheong]]></dc:creator>
            <pubDate>Wed, 05 May 2021 00:14:20 GMT</pubDate>
            <atom:updated>2021-05-05T00:14:20.325Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I wanted to share a simple read-eval-print-loop (REPL) that I wrote as part of following <a href="https://cstack.github.io/db_tutorial/parts/part1.html">cstacks’ clone of sqlite</a>. I’d done this once in C++, but this time I was writing it in Go. What inspired me to write this post was my amazement at how effortless the whole process was. In less than an hour, we had a simple REPL set up, and as Go code tends to be, the code itself is highly readable.</p><p>First, some backstory: this past semester, I spent many hours working in Go to write distributed systems such a distributed file system, an implementation of <a href="https://raft.github.io/">Raft</a> (a consensus algorithm), and <a href="https://pdos.csail.mit.edu/~strib/docs/tapestry/tapestry_jsac03.pdf">Tapestry</a> (a distributed hash table. What I’ve found is that Go is just unreasonably fun to work with. It’s normal to come up against some pain points when learning a new language, and while there were some of these, the overall process was smooth and I found myself looking forward to working in Go every day.</p><p>So at the end of the semester, I bought a copy of <a href="http://www.gopl.io/">The Go Programming Language</a> and decided that the planned revamp of <a href="http://cs.brown.edu/courses/csci1270/">CS127 Database Management Systems</a> would be done in Go instead of Java.</p><p>Let’s start off by taking a look at the standard library packages we’ll be importing.</p><pre>package main</pre><pre>import (<br>	&quot;bufio&quot;<br>	&quot;fmt&quot;<br>	&quot;os&quot;<br>	&quot;os/exec&quot;<br>	&quot;strings&quot;<br>)</pre><p>There’s nothing very fancy we need here. In order, we have a package for buffered input/output, one for formatted input/output, two packages to interface with the operating system, and a string manipulation package.</p><p>We then write some functions to print common prompts. One for the regular prompt, and one in response to unknown commands.</p><pre>// cliName is the name used in the repl prompts<br>var cliName string = &quot;simpleREPL&quot;</pre><pre>// printPrompt displays the repl prompt at the start of each loop<br>func printPrompt() {<br>	fmt.Print(cliName, &quot;&gt; &quot;)<br>}</pre><pre>// printUnkown informs the user about invalid commands<br>func printUnknown(text string) {<br>	fmt.Println(text, &quot;: command not found&quot;)<br>}</pre><p>We can add in some hard-coded meta functions as well such as help and clear.</p><pre>// displayHelp informs the user about our hardcoded functions<br>func displayHelp() {<br>	fmt.Printf(<br>		&quot;Welcome to %v! These are the available commands: \n&quot;,<br>		cliName,<br>	)<br>	fmt.Println(&quot;.help    - Show available commands&quot;)<br>	fmt.Println(&quot;.clear   - Clear the terminal screen&quot;)<br>	fmt.Println(&quot;.exit    - Closes your connection to &quot;, dbName)<br>}</pre><pre>// clearScreen clears the terminal screen<br>func clearScreen() {<br>	cmd := exec.Command(&quot;clear&quot;)<br>	cmd.Stdout = os.Stdout<br>	cmd.Run()<br>}</pre><p>Normally a REPL might have to do some parsing, so we set up some helper functions to handle well-formed commands, and invalid commands. There’s nothing much here because this is a simple REPL, so we don’t actually support anything besides the hard-coded meta-commands for now.</p><pre>// handleInvalidCmd attempts to recover from a bad command<br>func handleInvalidCmd(text string) {<br>	defer printUnknown(text)<br>}</pre><pre>// handleCmd parses the given commands<br>func handleCmd(text string) {<br>	handleInvalidCmd(text)<br>}</pre><p>We might consider writing a helper function to clean up input. This removes all leading and trailing whitespace from the input, and converts everything to lowercase.</p><pre>// cleanInput preprocesses input to the db repl<br>func cleanInput(text string) string {<br>	output := strings.TrimSpace(text)<br>	output = strings.ToLower(output)<br>	return output<br>}</pre><p>And finally, we get to the main function where we set up a map from meta-commands to their respective helper functions, start scanning for standard input, and create the read-eval-print-loop.</p><pre>func main() {<br>	// Hardcoded repl commands<br>	commands := map[string]interface{}{<br>		&quot;.help&quot;:  displayHelp,<br>		&quot;.clear&quot;: clearScreen,<br>	}<br>	// Begin the repl loop<br>	reader := bufio.NewScanner(os.Stdin)<br>	printPrompt()<br>	for reader.Scan() {<br>		text := cleanInput(reader.Text())<br>		if command, exists := commands[text]; exists {<br>			// Call a hardcoded function<br>			command.(func())()<br>		} else if strings.EqualFold(&quot;.exit&quot;, text) {<br>			// Close the program on the exit command<br>			return<br>		} else {<br>			// Pass the command to the parser<br>			handleCmd(text)<br>		}<br>		printPrompt()<br>	}<br>	// Print an additional line if we encountered an EOF character<br>	fmt.Println()<br>}</pre><p>And that’s it, that’s all there is to it. No head-scratching about setting up input/output buffers, no suffering needed to map commands to helper functions. Just straight-forward no-nonsense code. Refreshing, isn’t it?</p><p>Here it is in its 84-line entirety:</p><pre>package main</pre><pre>import (<br>	&quot;bufio&quot;<br>	&quot;fmt&quot;<br>	&quot;os&quot;<br>	&quot;os/exec&quot;<br>	&quot;strings&quot;<br>)</pre><pre>// dbName is the name used in the repl prompts<br>var cliName string = &quot;simpleREPL&quot;</pre><pre>// printPrompt displays the repl prompt at the start of each loop<br>func printPrompt() {<br>	fmt.Print(cliName, &quot;&gt; &quot;)<br>}</pre><pre>// printUnkown informs the user about invalid commands<br>func printUnknown(text string) {<br>	fmt.Println(text, &quot;: command not found&quot;)<br>}</pre><pre>// displayHelp informs the user about our hardcoded functions<br>func displayHelp() {<br>	fmt.Printf(<br>		&quot;Welcome to %v! These are the available commands: \n&quot;,<br>		cliName,<br>	)<br>	fmt.Println(&quot;.help    - Show available commands&quot;)<br>	fmt.Println(&quot;.clear   - Clear the terminal screen&quot;)<br>	fmt.Println(&quot;.exit    - Closes your connection to &quot;, dbName)<br>}</pre><pre>// clearScreen clears the terminal screen<br>func clearScreen() {<br>	cmd := exec.Command(&quot;clear&quot;)<br>	cmd.Stdout = os.Stdout<br>	cmd.Run()<br>}</pre><pre>// handleInvalidCmd attempts to recover from a bad command<br>func handleInvalidCmd(text string) {<br>	defer printUnknown(text)<br>}</pre><pre>// handleCmd parses the given commands<br>func handleCmd(text string) {<br>	handleInvalidCmd(text)<br>}</pre><pre>// cleanInput preprocesses input to the db repl<br>func cleanInput(text string) string {<br>	output := strings.TrimSpace(text)<br>	output = strings.ToLower(output)<br>	return output<br>}</pre><pre>func main() {<br>	// Hardcoded repl commands<br>	commands := map[string]interface{}{<br>		&quot;.help&quot;:  displayHelp,<br>		&quot;.clear&quot;: clearScreen,<br>	}<br>	// Begin the repl loop<br>	reader := bufio.NewScanner(os.Stdin)<br>	printPrompt()<br>	for reader.Scan() {<br>		text := cleanInput(reader.Text())<br>		if command, exists := commands[text]; exists {<br>			// Call a hardcoded function<br>			command.(func())()<br>		} else if strings.EqualFold(&quot;.exit&quot;, text) {<br>			// Close the program on the exit command<br>			return<br>		} else {<br>			// Pass the command to the parser<br>			handleCmd(text)<br>		}<br>		printPrompt()<br>	}<br>	// Print an additional line if we encountered an EOF character<br>	fmt.Println()<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b279e6f4469a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving into CPython #1: what’s in an import (byte code and C source code)]]></title>
            <link>https://desmondcheongzx.medium.com/diving-into-cpython-1-whats-in-an-import-byte-code-and-c-source-code-6bf3ac90b49e?source=rss-fbd1952cf037------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bf3ac90b49e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Desmond Cheong]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 14:59:49 GMT</pubDate>
            <atom:updated>2021-05-05T00:15:10.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>Diving into CPython: what’s in an import (bytecode and C source code)</h3><h3>Afterword</h3><p><em>(To avoid burying the lede, I’ve shifted my reflections to the very top of this post). The exercise that follows in this post is one of my first attempts to untangle the innards of CPython. The benefits of this activity might not be immediately obvious, but in hindsight here’s what I got out of the exercise:</em></p><p><em>Firstly, it gave me the confidence to make my second pull request in CPython to </em><a href="https://github.com/python/cpython/pull/24159"><em>implement cache invalidation for zip importers</em></a><em>. It turned out that figuring out imports in the C interpreter was not particularly necessary for understanding the Python implementation of importlib and zipimport, but it did give me assurance that I could jump into the Python-end of things without becoming irrecoverably lost.</em></p><p><em>It also taught me a lot about how to read a large code base. Reading everything linearly would be an almost hopeless endeavour. Instead, when trying to understand code, you need to jump around to relevant definitions and function calls to build a mental model of the architecture in your head. Improving one’s skill at jumping around, and learning to use the tools that help you accomplish this — thank you, ctags and gdb — is imperative for improving one’s ability to contribute to a code base.</em></p><p><em>And finally, I learned that reading the code can trump documentation in terms of building context. There’s something more real and more authoritative about the code itself. I’ve looked over </em><a href="https://devguide.python.org/exploring/#cpython-source-code-layout"><em>CPython’s source code layout</em></a><em> multiple times, but it didn’t stick (or didn’t really mean anything to me) until I had to dive into the code itself.</em></p><p><em>Now, on to the post.</em></p><p>Today I want to walk through what happens when you import something in Python. If you want to follow along, I’m working through Python v3.10.0.a3 which can be found at <a href="https://github.com/python/cpython">https://github.com/python/cpython</a>. I’m documenting this as I go, so as of this sentence I have no idea what kind of ride we’re in for, but I have a feeling this is going to be fun.</p><h3>The code we’ll be exploring</h3><p>First of all, let’s write a simple script. We’re just going to import a single module, then print the value of an object in that module:</p><pre>import math<br>print(math.pi)</pre><p>This gives us the expected output 3.141592653589793. Seems pretty straight-forward right? Let’s take a look at the disassembled code.</p><pre>  1           0 LOAD_CONST               0 (0)<br>              2 LOAD_CONST               1 (None)<br>              4 IMPORT_NAME              0 (math)<br>              6 STORE_NAME               0 (math)</pre><pre>  2           8 LOAD_NAME                1 (print)<br>             10 LOAD_NAME                0 (math)<br>             12 LOAD_ATTR                2 (pi)<br>             14 CALL_FUNCTION            1<br>             16 POP_TOP<br>             18 LOAD_CONST               1 (None)<br>             20 RETURN_VALUE</pre><p>Right off the bat we notice that there’s some magic numbers being loaded in line 1. The bytecode contains two LOAD_CONST operations that load 0 and None onto the stack. To elucidate what these magic constants might represent, let&#39;s make some minor modifications to our test program. We&#39;ll also call a function from the math library for good measure.</p><pre>import math<br>from math import pi<br>print(pi)<br>x = math.ceil(1.5)<br>print(x)</pre><p>Our bytecode now looks like this:</p><pre>  1           0 LOAD_CONST               0 (0)<br>              2 LOAD_CONST               1 (None)<br>              4 IMPORT_NAME              0 (math)<br>              6 STORE_NAME               0 (math)</pre><pre>  2           8 LOAD_CONST               0 (0)<br>             10 LOAD_CONST               2 ((&#39;pi&#39;,))<br>             12 IMPORT_NAME              0 (math)<br>             14 IMPORT_FROM              1 (pi)<br>             16 STORE_NAME               1 (pi)<br>             18 POP_TOP</pre><pre>  3          20 LOAD_NAME                2 (print)<br>             22 LOAD_NAME                1 (pi)<br>             24 CALL_FUNCTION            1<br>             26 POP_TOP</pre><pre>  4          28 LOAD_NAME                0 (math)<br>             30 LOAD_METHOD              3 (ceil)<br>             32 LOAD_CONST               3 (1.5)<br>             34 CALL_METHOD              1<br>             36 STORE_NAME               4 (x)</pre><pre>  5          38 LOAD_NAME                2 (print)<br>             40 LOAD_NAME                4 (x)<br>             42 CALL_FUNCTION            1<br>             44 POP_TOP<br>             46 LOAD_CONST               1 (None)<br>             48 RETURN_VALUE</pre><h3>The IMPORT_NAME instruction</h3><p>We’re now in better shape to understand some of the machinery behind the import statement. Let’s pay attention to the first line. import math produces the following bytecode:</p><pre>  1           0 LOAD_CONST               0 (0)<br>              2 LOAD_CONST               1 (None)<br>              4 IMPORT_NAME              0 (math)<br>              6 STORE_NAME               0 (math)</pre><p>To reiterate, first 0 and None are pushed onto the stack. Then, IMPORT_NAME, and STORE_NAME are called. Let&#39;s trace what IMPORT_NAME does. Going into Python/ceval.c, we find the relevant case in the interpreter loop.</p><pre>        case TARGET(IMPORT_NAME): {<br>            PyObject *name = GETITEM(names, oparg);<br>            PyObject *fromlist = POP();<br>            PyObject *level = TOP();<br>            PyObject *res;<br>            res = import_name(tstate, f, name, fromlist, level);<br>            Py_DECREF(level);<br>            Py_DECREF(fromlist);<br>            SET_TOP(res);<br>            if (res == NULL)<br>                goto error;<br>            DISPATCH();<br>        }</pre><p>Let’s try to understand the first line. To do this, we’ll first need to build up some context. We first note that names is set to the value co-&gt;co_names (line 1431), where co = f-&gt;f_code (line 1386) gives us the code object of the current frame f, and co_names corresponds to &quot;a tuple containing the names used by the bytecode&quot; as documented <a href="https://docs.python.org/3.10/reference/datamodel.html#index-55">here</a>. In this case, names contains (&#39;math&#39;, &#39;pi&#39;, &#39;print&#39;, &#39;ceil&#39;, &#39;x&#39;). Additionally, we can see from the disassembled bytecode above that oparg currently has a value of 0, which we can verify by printing the value of oparg on running the code for IMPORT_NAME. (Why is this the case? Sounds like a topic for another post.)</p><p>Looking further up the file, we see the definition of the GETITEM() macro.</p><pre>#define GETITEM(v, i) PyTuple_GetItem((v), (i))</pre><p>The definition for this function can then be found in Objects/tupleobject.c:</p><pre>PyObject *<br>PyTuple_GetItem(PyObject *op, Py_ssize_t i)<br>{<br>    if (!PyTuple_Check(op)) {<br>        PyErr_BadInternalCall();<br>        return NULL;<br>    }<br>    if (i &lt; 0 || i &gt;= Py_SIZE(op)) {<br>        PyErr_SetString(PyExc_IndexError, &quot;tuple index out of range&quot;);<br>        return NULL;<br>    }<br>    return ((PyTupleObject *)op) -&gt; ob_item[i];<br>}</pre><p>Here, if (!PyTuple_Check(op)) and if (i &lt; 0 || i &gt;= Py_SIZE(op)) respectively check that the first argument given was a PyTuple object, and that the second argument is within the range of the given tuple&#39;s size. It then returns the ith item. As we can see, a lot of the code here is exception handling.</p><p>Phew. Okay, now where does that get us? We’ve now taken the 0th item from names, which is &#39;math&#39;, and assigned it to the name variable. It seems that this line of execution always gets the name of the module we&#39;re importing from. Indeed, peeking ahead at the execution of from math import pi, we see that this is still the case even though we&#39;ve modified the code.</p><pre>  2           8 LOAD_CONST               0 (0)<br>             10 LOAD_CONST               2 ((&#39;pi&#39;,))<br>             12 IMPORT_NAME              0 (math)<br>             14 IMPORT_FROM              1 (pi)<br>             16 STORE_NAME               1 (pi)<br>             18 POP_TOP</pre><p>Quickly going over the next few lines in the IMPORT_NAME instruction, we see more set-up code. After which, we pass these arguments into the import_name() function.</p><pre>        case TARGET(IMPORT_NAME): {<br>            PyObject *name = GETITEM(names, oparg);<br>            PyObject *fromlist = POP();<br>            PyObject *level = TOP();<br>            PyObject *res;<br>            res = import_name(tstate, f, name, fromlist, level);<br>            ...</pre><p>Here, POP() and TOP() are macros for accessing the stack.</p><pre>#define TOP()             (stack_pointer[-1])</pre><pre>#define POP()                  BASIC_POP()</pre><pre>#define BASIC_POP()       (*--stack_pointer)</pre><p>If you were wondering why POP() is defined in such a circuitous manner, it&#39;s because there&#39;s a lot of debugging and tracing code that we&#39;re just ignoring for now. From the above definitions, we see that TOP() returns the address of the object sitting at the top of the stack. POP() does the same, but it also decrements the stack pointer, which &quot;removes&quot; the object&#39;s address from the stack. Recall that we had previously pushed 0 and None onto the stack, this means that fromlist points to None, and level points to 0. level is a bit mysterious, but we won&#39;t go into that (it&#39;s related to the location of your module in your directory path, i.e. whether your module is located in a sub/parent directory). However, it makes sense that fromlist points to None, since we don&#39;t bring in and bind any objects from the math library. Quickly peeking at the bytecode for from math import pi we see how this differs. In this case fromlist points to (&#39;pi&#39;,).</p><pre>  2           8 LOAD_CONST               0 (0)<br>             10 LOAD_CONST               2 ((&#39;pi&#39;,))<br>             12 IMPORT_NAME              0 (math)<br>             14 IMPORT_FROM              1 (pi)<br>             16 STORE_NAME               1 (pi)<br>             18 POP_TOP</pre><p>Before we explore the import_name() function, let&#39;s wrap up our discussion of the IMPORT_NAME instruction.</p><pre>            ...            <br>            Py_DECREF(level);<br>            Py_DECREF(fromlist);<br>            SET_TOP(res);<br>            if (res == NULL)<br>                goto error;<br>            DISPATCH();</pre><p>The remaining lines in this instruction are the break-down operations. Presumably there were references made to level and fromlist in import_name(), so now that we&#39;ve exited the function, we decrease their reference counts by 1. This is important for the Python garbage collector to figure out whether it can free up the space taken up by these objects. Following this, we set the return value of import_name() to the top of the stack, and throw an error if the value is NULL. At the very end, DISPATCH(); prepares us for executing the next line of bytecode. What happens exactly? That&#39;s a topic for another post (likely coupled with a post on opargs).</p><h3>The import_name() function</h3><p>In the previous section, we discussed the set-up and break-down code for the IMPORT_NAME instruction, but all that was basically the preamble and denouement for the import_name() function. For starters, here&#39;s the full function in Python/ceval.c.</p><pre>static PyObject *<br>import_name(PyThreadState *tstate, PyFrameObject *f,<br>            PyObject *name, PyObject *fromlist, PyObject *level)<br>{<br>    _Py_IDENTIFIER(__import__);<br>    PyObject *import_func, *res;<br>    PyObject* stack[5];</pre><pre>    import_func = _PyDict_GetItemIdWithError(f-&gt;f_builtins, &amp;PyId___import__);<br>    if (import_func == NULL) {<br>        if (!_PyErr_Occurred(tstate)) {<br>            _PyErr_SetString(tstate, PyExc_ImportError, &quot;__import__ not found&quot;);<br>        }<br>        return NULL;<br>    }</pre><pre>    /* Fast path for not overloaded __import__. */<br>    if (import_func == tstate-&gt;interp-&gt;import_func) {<br>        int ilevel = _PyLong_AsInt(level);<br>        if (ilevel == -1 &amp;&amp; _PyErr_Occurred(tstate)) {<br>            return NULL;<br>        }<br>        res = PyImport_ImportModuleLevelObject(<br>                        name,<br>                        f-&gt;f_globals,<br>                        f-&gt;f_locals == NULL ? Py_None : f-&gt;f_locals,<br>                        fromlist,<br>                        ilevel);<br>        return res;<br>    }</pre><pre>    Py_INCREF(import_func);</pre><pre>    stack[0] = name;<br>    stack[1] = f-&gt;f_globals;<br>    stack[2] = f-&gt;f_locals == NULL ? Py_None : f-&gt;f_locals;<br>    stack[3] = fromlist;<br>    stack[4] = level;<br>    res = _PyObject_FastCall(import_func, stack, 5);<br>    Py_DECREF(import_func);<br>    return res;<br>}</pre><p>Let’s first follow _Py_IDENTIFIER() for a bit. It appears quite often in the code base, so this will do us some good. This is a macro defined in Include/cpython/object.h. The relevant definitions are as follows.</p><pre>typedef struct _Py_Identifier {<br>    const char* string;<br>    // Index in PyInterpreterState.unicode.ids.array. It is process-wide<br>    // unique and must be initialized to -1.<br>    Py_ssize_t index;<br>} _Py_Identifier;</pre><pre>#define _Py_static_string_init(value) { .string = value, .index = -1 }<br>#define _Py_static_string(varname, value)  static _Py_Identifier varname = _Py_static_string_init(value)<br>#define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname)</pre><p><em>Side note: within C macros, the ## symbols tell the preprocessor to combine the two tokens on either side of the ##, and the # symbol tells the preprocessor to convert the token into a string. i.e., PyId_##varname gives us the token PyId_varname, and #varname gives us the string “varname”. </em><a href="https://www.cprogramming.com/tutorial/cpreprocessor.html"><em>This</em></a><em> is a useful reference.</em></p><p>Going through the macros, _Py_IDENTIFIER() expands to Py_static_string(PyId___import__, &quot;__import__&quot;), which expands to static Py_Identifier PyId___import_ = _Py_static_string_init(&quot;__import__&quot;), and finally expands to static Py_Identifier PyId___import_ = { .string = &quot;__import__&quot;, .index = -1 }. Speculating a little bit, this gives us a new identifier for __import__ within the interpreter, which maybe probably interns the string &quot;__import__&quot;. It&#39;s a bit out of the way for us to discuss why this is needed, so we&#39;ll save this for another time. Now we&#39;ll see how it&#39;s used.</p><pre>static PyObject *<br>import_name(PyThreadState *tstate, PyFrameObject *f,<br>            PyObject *name, PyObject *fromlist, PyObject *level)<br>{<br>    _Py_IDENTIFIER(__import__);<br>    PyObject *import_func, *res;<br>    PyObject* stack[5];</pre><pre>    import_func = _PyDict_GetItemIdWithError(f-&gt;f_builtins, &amp;PyId___import__);<br>    ...</pre><p>Focusing on the definition of import_func, we see that we get an item out of the dictionary of` <a href="https://docs.python.org/3/library/builtins.html">built-in objects</a> within our current frame f-&gt;f_builtins. Since PyId___import__ contains the string &#39;__import__&#39;, this means we get the build-in function <a href="https://docs.python.org/3/library/functions.html#__import__">__import__</a>. This is followed by some error handling, in the event that we fail to extract the required function.</p><pre>    ...<br>    if (import_func == NULL) {<br>        if (!_PyErr_Occurred(tstate)) {<br>            _PyErr_SetString(tstate, PyExc_ImportError, &quot;__import__ not found&quot;);<br>        }<br>        return NULL;<br>    }<br>    ...</pre><p>What follows is an if block that, minus some error checking, runs PyImport_ImportModuleLevelObject then returns. After the if block, we seem to do some set-up and break-down in order to run _PyObject_FastCall(import_func, stack, 5). To smooth over some of the nitty gritty details, we can consider the code within the if block, and following the if block to produce the same effect, just that one is optimised and the other isn&#39;t.</p><p>I’ll explain why. Examining the code outside the if block, we perform some book-keeping for garbage collection, and create a stack to store relevant variables: name which has the value of &#39;math&#39;, the pointer to the global variables of our frame f-&gt;f_globals, the pointer to the local variables of our frame f-&gt;f_locals, the objects we&#39;re importing (in this case, either None or (&#39;pi&#39;,)), and the current level. We then pass along import_func, this stack, and the size of the stack to _PyObject_FastCall() which calls import_func with the given arguments and returns the result.</p><p><em>Another side note: we kind of glossed over the </em><em>_PyObject_FastCall() function. That&#39;s another deep rabbit hole to dive into that we&#39;ll leave for another time. For those who are curious, here&#39;s a hint: your entry-point should be somewhere inside </em><em>Include/cpython/abstract.h.</em></p><p>import_func contained the built-in __import__ function which lives in Python/bltinmodule.c.</p><pre>static PyObject *<br>builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)<br>{<br>    static char *kwlist[] = {&quot;name&quot;, &quot;globals&quot;, &quot;locals&quot;, &quot;fromlist&quot;,<br>                             &quot;level&quot;, 0};<br>    PyObject *name, *globals = NULL, *locals = NULL, *fromlist = NULL;<br>    int level = 0;</pre><pre>    if (!PyArg_ParseTupleAndKeywords(args, kwds, &quot;U|OOOi:__import__&quot;,<br>                    kwlist, &amp;name, &amp;globals, &amp;locals, &amp;fromlist, &amp;level))<br>        return NULL;<br>    return PyImport_ImportModuleLevelObject(name, globals, locals,<br>                                            fromlist, level);<br>}</pre><p>As we can see, the built-in import function also eventually calls PyImport_ImportModuleLevelObject.</p><h3>The PyImport_ImportModuleLevelObject function</h3><p>This function is defined in <a href="https://github.com/python/cpython/blob/1470edd6131c29b8a09ce012cdfee3afa269d553/Python/import.c#L1545-L1695">lines 1545–1695 of </a><a href="https://github.com/python/cpython/blob/1470edd6131c29b8a09ce012cdfee3afa269d553/Python/import.c#L1545-L1695">Python/import.c</a>. There are too many lines for us to copy here, but you can follow the link to take a look. There&#39;s a lot going on in this function. But thankfully, most of it is — you guessed it — error checking. The first line of interest appears around 40 lines down.</p><pre>    ...<br>    else {  /* level == 0 */<br>        if (PyUnicode_GET_LENGTH(name) == 0) {<br>            _PyErr_SetString(tstate, PyExc_ValueError, &quot;Empty module name&quot;);<br>            goto error;<br>        }<br>        abs_name = name;<br>        Py_INCREF(abs_name);<br>    }</pre><pre>    mod = import_get_module(tstate, abs_name);<br>    if (mod == NULL &amp;&amp; _PyErr_Occurred(tstate)) {<br>        goto error;<br>    }</pre><pre>    if (mod != NULL &amp;&amp; mod != Py_None) {<br>        if (import_ensure_initialized(tstate, mod, name) &lt; 0) {<br>            goto error;<br>        }<br>    }<br>    else {<br>        Py_XDECREF(mod);<br>        mod = import_find_and_load(tstate, abs_name);<br>        if (mod == NULL) {<br>            goto error;<br>        }<br>    }<br>    ...</pre><p>As previously noted, our current level is 0, hence we simply set abs_name to &#39;math&#39;, then call import_get_module. What&#39;s interesting to note is that the first time we run import math, this function returns NULL. On subsequent executions of import math, or from math import pi, mod is no longer NULL. This means that for the first execution, we have to run mod = import_find_and_load(tstate, abs_name);.</p><p>After retrieving the module, we then check if fromlist is empty. If it is, we do the following.</p><pre>    ...<br>    if (!has_from) {<br>        Py_ssize_t len = PyUnicode_GET_LENGTH(name);<br>        if (level == 0 || len &gt; 0) {<br>            Py_ssize_t dot;</pre><pre>            dot = PyUnicode_FindChar(name, &#39;.&#39;, 0, len, 1);<br>            if (dot == -2) {<br>                goto error;<br>            }</pre><pre>            if (dot == -1) {<br>                /* No dot in module name, simple exit */<br>                final_mod = mod;<br>                Py_INCREF(mod);<br>                goto error;<br>            }</pre><pre>            if (level == 0) {<br>                PyObject *front = PyUnicode_Substring(name, 0, dot);<br>                if (front == NULL) {<br>                    goto error;<br>                }</pre><pre>                final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);<br>                Py_DECREF(front);<br>            }<br>            else {<br>                Py_ssize_t cut_off = len - dot;<br>                Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);<br>                PyObject *to_return = PyUnicode_Substring(abs_name, 0,<br>                                                        abs_name_len - cut_off);<br>                if (to_return == NULL) {<br>                    goto error;<br>                }</pre><pre>                final_mod = import_get_module(tstate, to_return);<br>                Py_DECREF(to_return);<br>                if (final_mod == NULL) {<br>                    if (!_PyErr_Occurred(tstate)) {<br>                        _PyErr_Format(tstate, PyExc_KeyError,<br>                                      &quot;%R not in sys.modules as expected&quot;,<br>                                      to_return);<br>                    }<br>                    goto error;<br>                }<br>            }<br>        }<br>        else {<br>            final_mod = mod;<br>            Py_INCREF(mod);<br>        }<br>    }<br>    ...</pre><p>Since there is no ‘.’ in our module name, we simply set final_mod = mod then goto error, which cleans up our state and returns the value of final_mod.</p><pre>...<br>  error:<br>    Py_XDECREF(abs_name);<br>    Py_XDECREF(mod);<br>    Py_XDECREF(package);<br>    if (final_mod == NULL) {<br>        remove_importlib_frames(tstate);<br>    }<br>    return final_mod;<br>}</pre><p>If fromlist isn&#39;t empty, then we need to consider if a path has or hasn&#39;t been given. In from math import pi, we see that this isn&#39;t the case, so we simply set final_mod = mod, then do the same as above.</p><pre>    ...<br>    else {<br>        PyObject *path;<br>        if (_PyObject_LookupAttrId(mod, &amp;PyId___path__, &amp;path) &lt; 0) {<br>            goto error;<br>        }<br>        if (path) {<br>            Py_DECREF(path);<br>            final_mod = _PyObject_CallMethodIdObjArgs(<br>                        interp-&gt;importlib, &amp;PyId__handle_fromlist,<br>                        mod, fromlist, interp-&gt;import_func, NULL);<br>        }<br>        else {<br>            final_mod = mod;<br>            Py_INCREF(mod);<br>        }<br>    }<br>    ...</pre><p>So after all this work, we return final_mod, which is likely a PyModule object. We&#39;ll have to verify this. And of course, we swept some details under the rug, namely the import_get_module and import_find_and_load functions, so we&#39;ll need to inspect these too.</p><h3>The import_get_module function</h3><p>In Python/import.c, we find the import_get_module function.</p><pre>static PyObject *<br>import_get_module(PyThreadState *tstate, PyObject *name)<br>{<br>    PyObject *modules = tstate-&gt;interp-&gt;modules;<br>    if (modules == NULL) {<br>        _PyErr_SetString(tstate, PyExc_RuntimeError,<br>                         &quot;unable to get sys.modules&quot;);<br>        return NULL;<br>    }</pre><pre>    PyObject *m;<br>    Py_INCREF(modules);<br>    if (PyDict_CheckExact(modules)) {<br>        m = PyDict_GetItemWithError(modules, name);  /* borrowed */<br>        Py_XINCREF(m);<br>    }<br>    else {<br>        m = PyObject_GetItem(modules, name);<br>        if (m == NULL &amp;&amp; _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {<br>            _PyErr_Clear(tstate);<br>        }<br>    }<br>    Py_DECREF(modules);<br>    return m;<br>}</pre><p>We’re finally in more straight-forward territory here (or maybe I’m just getting used to how this code is laid out). PyObject *modules = tstate-&gt;interp-&gt;modules gets the current modules that have been imported into the interpreter.</p><p>We do some error checking, first to make sure that the list of modules isn’t NULL, then to check that the modules are stored as a dictionary. If these checks pass, we get the value using the name of the module as the key. This answers one of our earlier questions: import_get_module returns NULL the first time it&#39;s run because the math module hasn&#39;t been imported yet. To get the final piece of the story, we have to dig into import_find_and_load.</p><h3>The import_find_and_load function</h3><p>If you thought we were finally done with long functions, think again. import_find_and_load can be found in <a href="https://github.com/python/cpython/blob/1470edd6131c29b8a09ce012cdfee3afa269d553/Python/import.c#L1461-L1526">Python/import.c lines 1461–1526</a>. Again, we won&#39;t be copying the code here, but feel free to follow the link. We first note that once again, error checking and tracing makes up the bulk of the code here. The real magic happens in the places where we assign values to mod, which happens here:</p><pre>mod = _PyObject_CallMethodIdObjArgs(interp-&gt;importlib,<br>                                    &amp;PyId__find_and_load, abs_name,<br>                                    interp-&gt;import_func, NULL);</pre><p>Going down the rabbit hole, we find _PyObject_CallMethodIdObjArgs defined in Objects/call.c.</p><pre>PyObject *<br>_PyObject_CallMethodIdObjArgs(PyObject *obj,<br>                              struct _Py_Identifier *name, ...)<br>{<br>    PyThreadState *tstate = _PyThreadState_GET();<br>    if (obj == NULL || name == NULL) {<br>        return null_error(tstate);<br>    }</pre><pre>    PyObject *oname = _PyUnicode_FromId(name); /* borrowed */<br>    if (!oname) {<br>        return NULL;<br>    }</pre><pre>    PyObject *callable = NULL;<br>    int is_method = _PyObject_GetMethod(obj, oname, &amp;callable);<br>    if (callable == NULL) {<br>        return NULL;<br>    }<br>    obj = is_method ? obj : NULL;</pre><pre>    va_list vargs;<br>    va_start(vargs, name);<br>    PyObject *result = object_vacall(tstate, obj, callable, vargs);<br>    va_end(vargs);</pre><pre>    Py_DECREF(callable);<br>    return result;<br>}</pre><p><em>Yet another side note: the ellipses (…) operator represents a </em><a href="https://linuxprograms.wordpress.com/2008/03/07/c-variable-argument-list-access/"><em>variable argument list</em></a><em>. Notice that we passed in 5 arguments to </em><em>_PyObject_CallMethodIdObjArgs but only two parameters are declared. The rest of the arguments are obtained through </em><em>vargs.</em></p><p>Here, it seems that two lines are of particular interest: the call to _PyObject_GetMethod which sets our callable pointer, and the result of object_vacall(tstate, obj, callable, vargs), which is the return value we&#39;re ultimately looking for.</p><p>Jumping into _PyObject_GetMethod in Objects/object.c, we first note that it&#39;s been given the *obj = importlib module, *name = &#39;_find_and_load&#39; (as a PyUnicodeObject), and **method = callable (currently a NULL pointer) as its arguments. After going through some checks, we run the following function.</p><pre>*method = PyObject_GetAttr(obj, name);</pre><p>Which eventually runs:</p><pre>return (*tp-&gt;tp_getattro)(v, name);</pre><p>Since v = obj = importlib is a PyModule object, this brings us to the module_getattro function in Objects/moduleobject.c, which then calls the generic PyObject_GenericGetAttr function on importlib and &#39;_find_and_load`, which then calls _PyObject_GenericGetAttrWithDict(obj, name, NULL, 0), that finally gets importlib&#39;s _find_and_load function inside Lib/importlib/_bootstrap.py via a dictionary lookup of all of importlib&#39;s implemented functions and objects. This post is concerned with the bytecode and C source code portions of import&#39;s implementation, so we&#39;ll save an examination of _find_and_load for a future post.</p><p>Now that we’ve obtained the _find_and_load function, we pass this value back up all the way to _PyObject_CallMethodIdObjArgs in Objects/call.c. This was where we left off:</p><pre>    ...<br>    PyObject *callable = NULL;<br>    int is_method = _PyObject_GetMethod(obj, oname, &amp;callable);<br>    if (callable == NULL) {<br>        return NULL;<br>    }<br>    obj = is_method ? obj : NULL;</pre><pre>    va_list vargs;<br>    va_start(vargs, name);<br>    PyObject *result = object_vacall(tstate, obj, callable, vargs);<br>    va_end(vargs);</pre><pre>    Py_DECREF(callable);<br>    return result;<br>}</pre><p>callable now points to importlib._find_and_load, and we proceed to the next line of interest: object_vacall(tstate, obj, callable, vargs).</p><p>This brings us to Objects/call.c once again. Inside object_vacall(), we first do some set-up: check that the callable function is not null, and then assign the given vargs to a local stack. Finally, we called _PyObject_VectorcallTstate() on the thread state, the callable, our stack, and the number of arguments in the stack. We then clean up the stack from memory and return the result.</p><p>_PyObject_VectorcallTstate() brings us to Include/cpython/abstract.h:</p><pre>static inline PyObject *<br>_PyObject_VectorcallTstate(PyThreadState *tstate, PyObject *callable,<br>                           PyObject *const *args, size_t nargsf,<br>                           PyObject *kwnames)<br>{<br>    vectorcallfunc func;<br>    PyObject *res;</pre><pre>    assert(kwnames == NULL || PyTuple_Check(kwnames));<br>    assert(args != NULL || PyVectorcall_NARGS(nargsf) == 0);</pre><pre>    func = PyVectorcall_Function(callable);<br>    if (func == NULL) {<br>        Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);<br>        return _PyObject_MakeTpCall(tstate, callable, args, nargs, kwnames);<br>    }<br>    res = func(callable, args, nargsf, kwnames);<br>    return _Py_CheckFunctionResult(tstate, callable, res, NULL);<br>}</pre><p>There’s a few things to note here. We set func = PyVectorcall_Function(callable), then call res = func(...) on our arguments, and finally return the result of calling _Py_CheckFunctionResult(). Let&#39;s explore each in turn.</p><p>In Include/cpython/abstract.h, we get the definition of PyVectorcall_Function().</p><pre>static inline vectorcallfunc<br>PyVectorcall_Function(PyObject *callable)<br>{<br>    PyTypeObject *tp;<br>    Py_ssize_t offset;<br>    vectorcallfunc ptr;</pre><pre>    assert(callable != NULL);<br>    tp = Py_TYPE(callable);<br>    if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_VECTORCALL)) {<br>        return NULL;<br>    }<br>    assert(PyCallable_Check(callable));<br>    offset = tp-&gt;tp_vectorcall_offset;<br>    assert(offset &gt; 0);<br>    memcpy(&amp;ptr, (char *) callable + offset, sizeof(ptr));<br>    return ptr;<br>}</pre><p>We get the type of callable, which is, not surprisingly, PyFunction_Type. Looking at line 674 of Objects/funcobject.c, we see that the Py_TPFLAGS_HAVE_VECTORCALL flag has been set. So we copy the contents of the funcobject&#39;s vectorcall function that happens to be the _PyFunction_Vectorcall() function in Objects/call.c. This is then assigned to func, As a reminder, here we are now:</p><pre>static inline PyObject *<br>_PyObject_VectorcallTstate(PyThreadState *tstate, PyObject *callable,<br>                           PyObject *const *args, size_t nargsf,<br>                           PyObject *kwnames)<br>{<br>    vectorcallfunc func;<br>    PyObject *res;</pre><pre>    assert(kwnames == NULL || PyTuple_Check(kwnames));<br>    assert(args != NULL || PyVectorcall_NARGS(nargsf) == 0);</pre><pre>    func = PyVectorcall_Function(callable);<br>    if (func == NULL) {<br>        Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);<br>        return _PyObject_MakeTpCall(tstate, callable, args, nargs, kwnames);<br>    }<br>    res = func(callable, args, nargsf, kwnames);<br>    return _Py_CheckFunctionResult(tstate, callable, res, NULL);<br>}</pre><p>Hence, calling func(callable, args, nargsf, kwnames) means that we&#39;re really calling _PyFunction_Vectorcall(callable, args, nargsf, kwnames). Within _PyFunction_Vectorcall(), we extract the code object from the function, as well as other details such as the current state, global variables, closure etc. We then call the hot function function_code_fastcall_().</p><pre>            ...<br>            return function_code_fastcall(tstate, co,<br>                                          stack, PyTuple_GET_SIZE(argdefs),<br>                                          globals);<br>        }<br>        ...</pre><p>And here’s where the magic happens. We construct a frame given the arguments to function_code_fastcall(), then we call _PyEval_EvalFrame().</p><pre>    ...<br>    PyObject *result = _PyEval_EvalFrame(tstate, f, 0);<br>    ...</pre><p>This! This is our main interpreter loop! So what have we done? We took the importlib._find_and_load function, extracted its code object, and set the relevant items in the stack to the our desired arguments (the most import being &#39;math&#39; as the name of the module we want to import), then evaluated our import code on the current interpreter state and this argument.</p><p>But wait, hang on for a moment, I actually lied a bit. From _PyFunction_Vectorcall(), we might actually instead make a call to _PyEval_EvalCode() (not what happens when we run import math), but that&#39;s fine. This brings us back to Python/ceval.c (always a hint that something fun is about to happen), sets up a frame given the code and globals and variables we&#39;ve given it, then calls _PyEval_EvalFrame(), so we&#39;re back at the main interpreter loop again!</p><p>Ok, now we can move on. So we call importlib._find_and_load on our module name math. This returns a a PyModule object as we guessed. Quick recap, we now return this object all the way back to _PyObject_VectorcallTstate.</p><pre>static inline PyObject *<br>_PyObject_VectorcallTstate(PyThreadState *tstate, PyObject *callable,<br>                           PyObject *const *args, size_t nargsf,<br>                           PyObject *kwnames)<br>{<br>    vectorcallfunc func;<br>    PyObject *res;</pre><pre>    assert(kwnames == NULL || PyTuple_Check(kwnames));<br>    assert(args != NULL || PyVectorcall_NARGS(nargsf) == 0);</pre><pre>    func = PyVectorcall_Function(callable);<br>    if (func == NULL) {<br>        Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);<br>        return _PyObject_MakeTpCall(tstate, callable, args, nargs, kwnames);<br>    }<br>    res = func(callable, args, nargsf, kwnames);<br>    return _Py_CheckFunctionResult(tstate, callable, res, NULL);<br>}</pre><p>We finally call _Py_CheckFunctionResult(). As the name suggests, we do a bunch of error checking here, and if all of them pass, then we return the module object that we got. And that&#39;s it, we go all the way back up and we&#39;re now done exploring import_find_and_load.</p><h3>Back to the byte code</h3><p>We’ve covered a lot of ground in C, but it’s easy to get lost, so let’s zoom out a bit and go back to the byte code.</p><pre>  1           0 LOAD_CONST               0 (0)<br>              2 LOAD_CONST               1 (None)<br>              4 IMPORT_NAME              0 (math)<br>              6 STORE_NAME               0 (math)</pre><p>After all that work, we’ve finally covered the IMPORT_NAME instruction. Now the desired module is on the stack, and STORE_NAME binds the module name &#39;math&#39; to the module object. from math import pi then gives us</p><pre>  2           8 LOAD_CONST               0 (0)<br>             10 LOAD_CONST               2 ((&#39;pi&#39;,))<br>             12 IMPORT_NAME              0 (math)<br>             14 IMPORT_FROM              1 (pi)<br>             16 STORE_NAME               1 (pi)<br>             18 POP_TOP</pre><p>Here we see that the math module object is left on the top of the stack. Going back into ceval.c, we can take a look at what the IMPORT_FROM instruction does.</p><pre>        case TARGET(IMPORT_FROM): {<br>            PyObject *name = GETITEM(names, oparg);<br>            PyObject *from = TOP();<br>            PyObject *res;<br>            res = import_from(tstate, from, name);<br>            PUSH(res);<br>            if (res == NULL)<br>                goto error;<br>            DISPATCH();<br>        }</pre><p>We get the name ‘pi’ from the names in our frame, and the module that we left on the top of the stack. We then call res = import_from(tstate, from, name) before pushing the result onto the stack. In import_from(), the action happens here:</p><pre>    if (_PyObject_LookupAttr(v, name, &amp;x) != 0) {<br>        return x;<br>    }</pre><p>We simply import the ‘pi’ attribute from the math module object (it’s there in the dictionary of attributes in math, which you can see by running dir(math)). The pi object (of PyFloat_Type) is then pushed onto the stack. STORE_NAME then binds the name &#39;pi&#39; to the float object. This is followed by POP_TOP to remove the module from the stack. Within STORE_NAME, we actually left the module on the stack to avoid having to reload it for every object that we wanted to import from the module. If we had run from math import pi, ceil, the byte code would have looked like this instead:</p><pre>  2           8 LOAD_CONST               0 (0)<br>             10 LOAD_CONST               2 ((&#39;pi&#39;, &#39;ceil&#39;))<br>             12 IMPORT_NAME              0 (math)<br>             14 IMPORT_FROM              1 (pi)<br>             16 STORE_NAME               1 (pi)<br>             18 IMPORT_FROM              2 (ceil)<br>             20 STORE_NAME               2 (ceil)<br>             22 POP_TOP</pre><p>Moving on to the rest of the byte code. print(pi) gave us</p><pre>  3          20 LOAD_NAME                2 (print)<br>             22 LOAD_NAME                1 (pi)<br>             24 CALL_FUNCTION            1<br>             26 POP_TOP</pre><p>This loads the name ‘print’, followed by the name ‘pi’, then runs the CALL_FUNCTION instruction, which gets the function bounded to &#39;print&#39; and gives, as its argument, the object stored at &#39;pi&#39;, which is our float with value 3.141592653589793.</p><p>x = math.ceil(1.5) produces this byte code:</p><pre>  4          28 LOAD_NAME                0 (math)<br>             30 LOAD_METHOD              3 (ceil)<br>             32 LOAD_CONST               3 (1.5)<br>             34 CALL_METHOD              1<br>             36 STORE_NAME               4 (x)</pre><p>The only mysterious instruction here is LOAD_METHOD. This of course takes us back to Python/ceval.c, where we run int meth_found = _PyObject_GetMethod(obj, name, &amp;meth), with obj being our module, and name being &#39;ceil&#39;. Then, very simply, we point meth to PyObject_GetAttr(obj, name) since the &#39;ceil&#39; attribute in the math module points to the appropriate PyCFunction. We then call this method with the loaded constant 1.5, which pushes the value 2 onto the stack. We then call STORE_NAME which binds this value to the name &#39;x&#39;.</p><p>Finally, we run print(x), which produces byte code that&#39;s almost the same as print(pi). The only real difference being the last two lines:</p><pre>  5          38 LOAD_NAME                2 (print)<br>             40 LOAD_NAME                4 (x)<br>             42 CALL_FUNCTION            1<br>             44 POP_TOP<br>             46 LOAD_CONST               1 (None)<br>             48 RETURN_VALUE</pre><p>These lines just load the constant None, then returns this value. i.e. our program returns None before terminating.</p><h3>Back to the start</h3><p>We’ve covered a lot of ground in this post. It almost seems crazy how deep we had to go just to figure out <em>half</em> of the story of <em>only</em> the import statement when we run a simple program:</p><pre>import math<br>from math import pi<br>print(pi)<br>x = math.ceil(1.5)<br>print(x)</pre><p>We didn’t even consider any of the underlying Python implementation yet. And if you think that would be more straight-forward, think again. I can assure you, that due to bootstrapping problems (you need to import the import library), that’s going to be a wild wild ride.</p><p>But it would be a very curious and educating exercise.</p><h3>Afterword (again)</h3><p>I copied the afterword to the top of this post, but I’ll reiterate here for closure. The benefits of this activity might not have been immediately obvious, but here’s what I got out of it:</p><p>Firstly, it gave me the confidence to make my second pull request in CPython to <a href="https://github.com/python/cpython/pull/24159">implement cache invalidation for zip importers</a>. It turned out that figuring out imports in the C interpreter was not particularly necessary for understanding the Python implementation of importlib and zipimport, but it did give me assurance that I could jump into the Python-end of things without becoming irrecoverably lost.</p><p>It also taught me a lot about how to read a large code base. Reading everything linearly would be an almost hopeless endeavour. Instead, when trying to understand code, you need to jump around to relevant definitions and function calls to build a mental model of the architecture in your head. Improving one’s skill at jumping around, and learning to use the tools that help you accomplish this — thank you, ctags and gdb — is imperative for improving one’s ability to contribute to a code base.</p><p>And finally, I learned that reading the code can trump documentation in terms of building context. There’s something more real and more authoritative about the code itself. I’ve looked over <a href="https://devguide.python.org/exploring/#cpython-source-code-layout">CPython’s source code layout</a> multiple times, but it didn’t stick (or didn’t really mean anything to me) until I had to dive into the code itself.</p><p>And with that, thank you for joining me on this ride.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bf3ac90b49e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A goal to dive into CPython]]></title>
            <link>https://desmondcheongzx.medium.com/a-goal-to-dive-into-cpython-9545cac4f92d?source=rss-fbd1952cf037------2</link>
            <guid isPermaLink="false">https://medium.com/p/9545cac4f92d</guid>
            <dc:creator><![CDATA[Desmond Cheong]]></dc:creator>
            <pubDate>Fri, 01 Jan 2021 17:00:23 GMT</pubDate>
            <atom:updated>2021-01-01T17:08:24.130Z</atom:updated>
            <content:encoded><![CDATA[<p>Some time towards the end of the semester, I made it my goal to work my way up to contributing regularly and meaningfully to <a href="https://github.com/python/cpython">CPython</a>.</p><p>At the time when I first starting reading about the code base, it was not much more than an exciting form of procrastination: instead of doing my Neural Systems readings, I’d find myself staying up watching videos on CPython internals. It took awhile for me to realise what was happening, and now I’ve decided to go down a path that I have no desire to alter. I’ve decided to dedicate the last years of my university education to chasing this code base.</p><p>Why do I feel so strongly about this? It’s hard to pinpoint, but a few ideas have been stuck in my head that likely contributed to this decision.</p><p>Recently, I had a conversation with my computational probability instructor Professor Geman. He gave me two important pieces of advice: follow your nose, and get to the bottom of things.</p><p>Reflecting on this, I realised that for some time now, I haven’t exactly been following my nose. I’ve been going where others have expected me to go, and I’ve been chasing scents that other people seem to enjoy, even knowing that I’d been enticed by spicier things before.</p><p>More concretely, I realised that I’d been straying towards programming projects that I found less and less exciting. Still technically challenging, and still interesting, to be sure. But it became more uncommon for me to obsess over my work, and to feel hungry to code. This wouldn’t do. So I started to think back to the kind of programming that excited me, and noticed that I still felt that burning obsessiveness on occasion. I hadn’t been paying attention, but I’d felt it during my course on database management systems.</p><p>I am attracted to systems programming, and doing work that brings me closer to the metal. Such work, I’ve discovered, tends to make me feel like I’m… <em>relaxing into</em> the machine. It is a highly rewarding experience.</p><p>So to follow Professor Geman’s advice, I’m determined to chase this feeling down to the bottom of things. But to what problem should I devote my attention towards? Database systems? Tempting. I do plan to take a seminar with Professor Zdonik next semester to explore more topics in databases, and admittedly that could well evolve into something that might then take over my attention. But in the meanwhile, I came across the CPython repository.</p><p>I can’t remember what brought me there, maybe I had been trying to answer some student’s questions during office hours. But I do remember thinking that this project was humongous. I was also reminded that in my younger days, I did have a fascination with programming languages and compilers that I’d put aside as I pursued data science and machine learning at Brown. My interest was piqued.</p><p>It was then that I remembered an old blog post by Cal Newport on <a href="https://www.calnewport.com/blog/2009/06/03/the-pyramid-method-a-simple-strategy-for-becoming-exceptionally-good/">The Pyramid Method</a>. The idea is simple: to develop one’s interest and talent into expertise, pick a venue that accepts entry-level work, but with ample opportunities for growth as well as clear metrics for progress. Then, put your head down and get to it.</p><p>I am ambivalent about my development as a programmer and computer scientist. I know that I’m effective, and that I’m comfortable enough with machines that I can do many otherwise daunting things on the computer. At the same time, I know that I’ve also barely stretched my wings, and that as a fledgling I have much more to learn. One of my weaknesses is not having much experience working on truly massive and complex code bases. I’ve had some opportunity during my last internship experience, but since then, it’s been back to school work and personal projects. I believe that to mature as a programmer, it’s imperative to learn how to grapple with such code bases, and the onus is on me to develop these skills.</p><p>CPython is truly massive. It’s been around for some 26 years, and as of this writing has 1,424 contributors on Github, as well as 1.4k open pull requests, and ~54k reported issues. Following the python-dev and python-ideas mailing list, it is also clear that this project has many ideas for short/medium/long-term development. As the standard implementation for what’s become one of the most popular programming languages and one of the go-to languages for new programmers, the success of CPython is important to a staggering number of people. Moreover, the Python community is friendly towards newcomers and accepts entry-level work.</p><p>This means that a goal of contributing to CPython is both productive as a venue for polishing one’s programming skills, and meaningful in terms of helping humanity.</p><p>In the past week I made <a href="https://github.com/python/cpython/pull/23885">my first contribution to the project</a>. It was a minor bug, but the intent was to get a better understanding of the development process. I also wanted to kick myself into action as I’d been studying CPython and reading other books on programming in preparation for some time, but to no effect. Small as it was, I took pride in making sure I understood what change I was making, and added the relevant tests and documentation accordingly. I made the pull request with no small amount of trepidation. Over the next few days my pull request went through the review process, and polling how I felt internally, I realised that this was fun and, most importantly, it felt right. Like I was following my nose.</p><p>Now my plan is to finish a series of lectures on <a href="https://www.youtube.com/watch?v=LhadeL7_EIU">CPython’s internals</a> (in addition to getting distracted by <a href="https://www.youtube.com/watch?v=HVUTjQzESeo">other materials on Python</a>), then choose one area (maybe importlib?) and go for it. Next semester, I also plan to finally take the Compilers course at Brown.</p><h3>Final thoughts</h3><p>Of course, it’s hard to dedicate yourself to one thing. We are all creatures of many interests and conflicting motivations. We also like to hedge our bets. I had just started talking with a machine learning research group at Brown on a potential new project, and my humanity-centred robotics professor offered to work with me next semester to continue work on another project for a conference. These are both opportunities that I would’ve jumped on at the start of the fall semester.</p><p>But my nose is pointing to another direction, and I find that I must chase the name of this wind. I refuse to get lost again. I have to pursue the endeavours that set my heart on fire.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9545cac4f92d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A nostalgic cry for a country that could have been: a review of The Art of Charlie Chan Hock Chye]]></title>
            <link>https://desmondcheongzx.medium.com/a-nostalgic-cry-for-a-country-that-could-have-been-a-review-of-the-art-of-charlie-chan-hock-chye-72b807582640?source=rss-fbd1952cf037------2</link>
            <guid isPermaLink="false">https://medium.com/p/72b807582640</guid>
            <dc:creator><![CDATA[Desmond Cheong]]></dc:creator>
            <pubDate>Fri, 01 Jan 2021 02:02:36 GMT</pubDate>
            <atom:updated>2021-01-01T02:02:36.487Z</atom:updated>
            <content:encoded><![CDATA[<p>A thoroughly convincing storytelling feat. I was unable to see through Sonny Liew’s trick from the very start to the very end. It was only upon reading reviews that I learned of the secret to Chan Hock Chye’s life story. <a href="https://www.goodreads.com/book/show/25733982-the-art-of-charlie-chan-hock-chye">The Art of Charlie Chan Hock Chye</a> was at once a political statement, a nostalgic cry for various lost pieces of a nation, and a begrudging acknowledgement of how far Singapore has come.</p><p>Besides the story, the art itself is something to behold. I’ve always been a fan of illustrations and graphic novels, so it was a treat to see both a development of artistic ability as we follow Chan Hock Chye’s growth as an artist, as well as the myriad of art styles with which he presents his stories. If they are available, I would love to hang prints from this book in my room. In particular, the last panel of “Days of August” was enough to make me put down the book and reflect for awhile.</p><p>I’ve heard mixed reviews of this book. Someone who’s opinion I highly regard commented that he found the story quite boring, so perhaps it’s not for everyone. Personally, I found myself far too immersed in the struggles of Chan Hock Chye and Singapore to feel bored. Our stories might have started 60 years apart, but Chan Hock Chye’s life challenges strangely reflected back on my own.</p><p>If I had any critiques for this book, it would be that certain art pieces and commentaries were a little on the nose. One might also say that the arguments presented are very similar to many discussions that Singaporeans have online. However, this book has been out for a few years, and I’m not familiar with how online discourse was like back then. So it might well be that this book was one of the progenitors for the more daring political ideas we see today. At the very least, I’m certain that it nudged the discourse along. Nevertheless, I was willing to forgive the lack of subtlety during Chan Hock Chye’s early years, and fortunately his taste and delivery became much more refined as he developed as an artist. Till the very end, some parallels between comics and real life were more direct and forceful than I would have liked. Then again, as Chan Hock Chye might reply: “that’s how you tell stories.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72b807582640" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going on a trip with Murakami: a review of Kafka on the Shore]]></title>
            <link>https://desmondcheongzx.medium.com/going-on-a-trip-with-murakami-a-review-of-kafka-on-the-shore-b6e3dd177b9d?source=rss-fbd1952cf037------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6e3dd177b9d</guid>
            <dc:creator><![CDATA[Desmond Cheong]]></dc:creator>
            <pubDate>Wed, 30 Dec 2020 02:03:11 GMT</pubDate>
            <atom:updated>2020-12-30T02:03:11.995Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“‘In travelling, a companion, in life compassion’. So what does that really mean? In simple terms.”<br>“I think it means that chance encounters are what keep us going. In simple terms.”</em></p><p>In <a href="https://www.goodreads.com/book/show/4929.Kafka_on_the_Shore">Kafka on the Shore</a>, Murakami brings us into the world of a fifteen-year-old Japanese teenager Kafka Tamura, as he runs away from home to escape an omen. Kafka finds refuge at a library on the island of Shikoku, although he seems to be running towards his omen rather than away from it. Running parallel to Kafka’s story, Mr Nakata, an elderly man who can talk to cats but seems to be missing half his shadow, seems to trace Kafka’s path.</p><p>While I enjoyed this story, I can also see how it wouldn’t appeal to other kinds of readers. There’s no clear outcome or plot. In Kafka on the Shore, we follow two main story lines that run next to each other and get ever-so-slightly closer, even touching at certain points. One story line seemed to be driven by an Oedipus-like omen which gets fulfilled halfway into the story, and after which the plot seems to freeze in place before reversing. The other story line appears to play a supporting role in allowing the events in the first story line to progress, but at least here a final outcome seems to exist. However, this goal is doled out to us slowly, because the characters themselves don’t know what they’re working towards until each step is completed. Perhaps inanely, it sometimes feels like progress can <em>only</em> be made by chance.</p><p>This kind of plot can be frustrating at times, but I argue that Kafka on the Shore’s strength isn’t in its gripping plot, but rather in the atmosphere surrounding each chapter. It almost feels like Murakami had a particular feeling or idea he wanted to explore each chapter, and he’d put us in the right environment to experience it for just long enough. These experiences would then incidentally, and almost unwillingly, drive the plot forward.</p><p>As a result of this, character growth is quite a dubious thing in this novel. Only one character — Mr Hosino, seems to have undergone quite a change in tastes and mindset throughout the novel. Most other characters had mindsets that were amorphous in the first place, and remain amorphous at the end. In an almost meta manner, Kafka had a conversation with the librarian Oshima on <em>The Miner</em> by Natsume Soseki. Kafka points out that the hero of the story watches things happen, broods over his love affair, and comes out of the mine about the same as when he went in. Oshima asks if Kafka sees himself as someone like the hero of <em>The Miner</em>, which Kafka denies. But retrospectively, there might be some truth to this.</p><p>On another note, language-wise, this English translation is very interesting. Language almost seems like a character on its own. The text sometimes switches between normal narration and bolded, almost omniscient and prophesying narration, and tenses also seem to change from chapter to chapter, character to character, paragraph to paragraph, in a seemingly deliberate manner to achieve certain effects. If I could understand it, I would’ve loved to read the novel in its original Japanese, just to see how these tools were employed, and to observe the decisions that Philip Gabriel made in translating this text.</p><p>Overall, I had fun with this story. This was probably largely thanks to Mr Nakata, whose way of interacting with other characters felt so pure and transparent. I also enjoyed the mysticism that surrounded the story, especially because it detracts from Western systems of magic, and instead had a more East Asiatic quality to it, with its shadows, and entrance stones, and worlds hidden within forests. Many aspects of this mysticism ultimately go unexplained, which I feel was the most appropriate way to handle them. I’m definitely looking forward to reading another story by Murakami.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6e3dd177b9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the world of small things: a review of Gathering Moss]]></title>
            <link>https://desmondcheongzx.medium.com/exploring-the-world-of-small-things-a-review-of-gathering-moss-e60bb5ca232c?source=rss-fbd1952cf037------2</link>
            <guid isPermaLink="false">https://medium.com/p/e60bb5ca232c</guid>
            <dc:creator><![CDATA[Desmond Cheong]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 14:03:00 GMT</pubDate>
            <atom:updated>2020-12-29T14:03:00.281Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Part of the fascination of working with mosses is the chance to see if and when the ecological rules of the large transcend the boundaries of scale and still illuminate the behavior of the smallest beings. It is a search for order, a desire for a glimpse of the threads that hold the world together.</blockquote><blockquote><em>— Robin Wall Kimmerer</em></blockquote><p>In <a href="https://www.goodreads.com/book/show/87040.Gathering_Moss">Gathering Moss</a>, Robin Wall Kimmerer gives us a detailed account of the lives of mosses and their interactions with the world. She weaves together stories from her life and her myriad experiences with bryology, and approaches these from both a Western scientific perspective and Native American views on the world. It’s an interesting exercise. Understanding mosses requires an understanding of the unique set of challenges for life at extremely small scales. But there is also a need to understand the larger pattern of how the aggregation of these tiny beings affects the ecosystem at large. Reading this book, I was repeatedly surprised that mosses play such an important role in the world even though they usually disappear, almost unseen, into the background.</p><p>This is a deep dive into the world of small things that’s a fun and educating read for anyone who’s fascinated by the natural world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e60bb5ca232c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SpaceMaker]]></title>
            <link>https://desmondcheongzx.medium.com/spacemaker-f7fbbc4b89ec?source=rss-fbd1952cf037------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7fbbc4b89ec</guid>
            <dc:creator><![CDATA[Desmond Cheong]]></dc:creator>
            <pubDate>Wed, 02 Dec 2020 05:45:17 GMT</pubDate>
            <atom:updated>2020-12-02T14:59:46.105Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F482537350%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F482537350&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1005676478_1280.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/a195183f1f97b7214d6077e70d5aebbb/href">https://medium.com/media/a195183f1f97b7214d6077e70d5aebbb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0it-pnWLK9KIgeM9Ywy3Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lBzLTRg688uGkphDYZu9w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pf2MG7HW2oZvybm7PmpV1A.jpeg" /><figcaption>Front (left), back (centre), and side (right) views of SpaceMaker</figcaption></figure><h3>Concept</h3><p>The SpaceMaker bot started out as a concept to tacitly encourage social distancing. During the currant pandemic, everyone is constantly inundated with messages to maintain their distance. However, this system could use improvements. After months of hearing the same message, people get fatigued. Additionally, there is a natural impulse for humans to move closer when interacting or working together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fup_kyl-Bza4vqhL.JPG" /><figcaption>Initial sketch</figcaption></figure><p>Instead of relying on explicit warnings to maintain social distance, could we instead rely on innate social behaviours to achieve the same outcome? One instinct that humans have is to avoid moving objects, or to step away from objects that are steadily moving towards you. Another instinct is to follow the directions given by certain learned authoritative forms such as traffic signs. With SpaceMaker, we leverage the fact that traffic cones are used around the world to control movement as our means to tacitly encourage social distancing in an area.</p><p>However, as can be seen from the demo video, SpaceMaker has evolved beyond the scope of social distancing. It has become an exploration of automating and enriching the possibilities of space delimitation in both public and private spaces, for both traffic control (such as for <a href="https://en.wikipedia.org/wiki/Reversible_lane">reversible lanes</a>) and control of human movement.</p><h3>Iteration #1 — Moving the robot and initial designs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyCJolJmrdMIINlS0sG5Rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HouZwPZmltKRROh5x1EuCA.jpeg" /><figcaption>Initial mount design for SpaceMaker</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BrzcerZ1eD7Btsh-.jpg" /><figcaption>A sample of the various mounts produced</figcaption></figure><p>As a start, we received a robotic base that was already wired and came with its own DC motors. Our first step was to figure out how to make it move, and what form we want it to take on. Movement and distance sensing was solved by testing the effects of pin outputs one by one. As for the form, we wanted to make something tall and noticeable that could be mounted onto the robot. After making some cardboard prototypes with a precision knife, we settled on the cutout pattern included above for laser printing.</p><p>At this stage we experimented with many different heights of mounts to see what the limit was before SpaceMaker became too unstable.</p><p>Additionally, to explore the various movement patterns that SpaceMaker could employ to encourage social distancing, we tried the following movement modes.</p><h4>Tacit Space Maker Mode</h4><p>In Tacit Space Maker mode, SpaceMaker rotates until it finds two people standing too close too each other. It then repeatedly moves back and forth between the two people to encourage them to move apart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*JIJ846bk5KYEU83suLrmlw.gif" /><figcaption>Tacit space maker mode</figcaption></figure><h4>Gantry mode</h4><p>In Gantry mode, SpaceMaker waits until someone crosses its path. It then moves to the position that the person occupied, and waits there for a few seconds before moving back to its original position. This is meant to discourage people from following too closely behind someone else and can be used in places like entrances to buildings, or in front of elevators and escalators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*FBhz_kQnx76vrHgn.gif" /><figcaption>Gantry mode</figcaption></figure><h4>Iteration #1.1 Reliable ultrasound distance sensing</h4><p>One drawback of the ultrasound sensors we were using is that they’re really only mostly accurate within a certain distance. Thankfully this is familiar territory in machine learning and probabilistic methods where we have algorithms that are only probably approximately correct.</p><p>Let’s say that at some time step <em>t</em> we have a true distance <em>x</em> that produces noisy ultrasound readings <em>y</em> ~ Normal( <em>x</em>, <em>some variance</em>). These seem like valid assumptions to make, and if our readings do indeed follow this distribution, then we can take advantage of the Law of Large Numbers to estimate <em>x</em> by taking the average of all the ultrasounds readings <em>y</em> at time <em>t</em>. As the number of readings we take increases, the variance of our average decreases and we converge to the true distance <em>x</em>. However, we don’t want to carry out too many readings because each reading takes awhile to complete, which slows down our robot’s reaction time. So if our assumptions are valid, the Central Limit Theorem kicks in very fast when we sample from a normal distribution, and we only need a handful of readings to make a good estimation. Our improved ultrasound sensor performs as follows.</p><pre>int get_distance(int cur_trig, int cur_echo) {<br>  int sum = 0;<br>  int n_trials = 15;<br>  // fire the ultrasound multiple times and take the minimum reading<br>  for (int a = 0; a &lt; n_trials; ++a) {<br>    int distance = fire_ultrasound(cur_trig, cur_echo);<br>    sum += distance;<br>  }<br>  return distance / n_trials;<br>}</pre><p>We could have also explored using a hidden markov model with the true distance as the latent variable, and the ultrasound reading as the observed variable. Our true distance is allowed to change from state to state, but every true distance is correlated with the previous true distance. Moreover, ultrasound readings are correlated with the true distance at that point in time. We could even combine this method with the averaging method above. These dependencies should give us a model that’s resilient to noisy ultrasound readings. It would be interesting to see how accurate we could make our ultrasound readings using computation alone, but that’s an experiment for another time.</p><h3>Iteration #2 — Traffic cones and experimenting with form</h3><p>After our first iteration, I immediately received feedback that the outward appearance of the robot could be improved. As it was now, it wasn’t very readable in terms of how people should respond to it. It was suggested that perhaps covering the robot with a traffic cone would be perfect in terms of signalling to people that they should maintain their distance. We immediately acquired a set of 9 inch traffic cones to play around with this idea.</p><p>It was around this time that I also started working with a second robot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*m_-79Stspvm_Mn_A5-E1LA.gif" /><figcaption>Adding a second bot to the team</figcaption></figure><p>We continued experimenting with the form of SpaceMaker by using traffic cones of larger and larger sizes. Unfortunately, while 12-inch traffic cones started to reach the point where Spacemaker was properly covered up, we found that the motors were unable to keep up with the load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7fjM1hE3QwfSB8yR.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*o8s4RcEfzgBysVJY.gif" /><figcaption>(left) 9 inch and 12 inch traffic cones on SpaceMaker. (right) SpaceMaker struggling to move under load.</figcaption></figure><p>And so we switched from plastic cones to cloth cones to decrease the load. This helped, but not enough to allow SpaceMaker to move.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IIjmdUvbxlZB2DPp.JPG" /><figcaption>15.5 inch cloth traffic cone on SpaceMaker</figcaption></figure><h4>Iteration #2.1 Adding a second ultrasound sensor</h4><p>From the very first sketch it was apparent that keeping track of distances in multiple directions would be extremely helpful for maintaining equidistance. In terms of wiring another ultrasound sensor to the Arduino, this wasn’t any different from setting up the first ultrasound sensor. The main challenge here was laser cutting a holder to provide a stable platform for this rear ultrasound.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*lEYzHKwWcW2Gs2M_.PNG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E72sodZVCdTCrrDK.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ugp8b-auPrHGD2Th.jpg" /><figcaption>The mounts for a rear ultrasound sensor</figcaption></figure><h4>Equidistance mode</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*vRLnO1pDJ74eELHl37hjCw.gif" /><figcaption>Equidistance mode</figcaption></figure><p>Adding the second ultrasound enabled us to program an extra movement pattern on top of the two that we previously discussed. In equidistance mode, SpaceMaker tries to stay as far away from all objects that surround it. The idea is that one SpaceMaker maintains equidistance, but a population of SpaceMakers creates social distance, as people moving and interacting in a space are tacitly encouraged to navigate around the robots.</p><p>Because our current robot design only support bidirectional distance sensing and movements, we achieved equidistance by sampling distances along a rotating axis. i.e., SpaceMaker rotates ~1 quadrant every few seconds and moves back and forth accordingly to find an equilibrium point.</p><h3>Iteration #3 — Solving movement issues with more power and H-bridges</h3><p>In our previous iteration, we tried to increase the size of traffic cones used. The goal was to completely cover the robotic base that moves the cone and see whether that design works out better. However, immediately after mounting cones that were taller than 9 inches, we found that the load was too heavy for SpaceMaker and our robot refused to move.</p><p>Reading up on DC motors and measuring the voltage being fed into the motors of our robot, we realised that the stalling issue was a result of too little power being supplied. We first tried to overcome this by connecting portable powerbanks to the arduino in addition to the 2 x 1.5V AA batteries powering the mobile base. This improved the situation, but was still insufficient. Next, we purchased a H-bridge so that we could power our motors directly with a separate power source. This H-bridge would then be controlled via connections to the Arduino.</p><p>Installing this H-Bridge gave us even more freedom with our power source. We first moved on to a 9V battery. Increasing the voltage of our power source seemed to allow our motors to spin faster and we declared a premature victory. But in terms of solving our mobility issues, we actually regressed here. Although we’d switched to 9V batteries, we were using alkaline batteries that discharge slowly. When there’s no load, this isn’t an issue. But under load, DC motors require a large current to overcome stalling, so alkaline batteries wouldn’t do.</p><p>Switching to 2 x AA nickel metal hydride (NiMH) batteries, which discharge faster, showed improvements in the right direction so we scaled up to a 9.6V 2400mAh NiMH battery pack. The first time I plugged in this battery pack and saw how fast the robot ran, I laughed out of surprise. With that, our power management issues were resolved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gA_OXaG1psardf4J.JPG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qTZa180QToUaVe5t.JPG" /><figcaption>(left) Final platform to hold battery pack. (right) Platform removed to reveal wiring with H-bridge underneath.</figcaption></figure><h4>Iteration #3.1 — Safety concerns</h4><p>As we added more power, I started thinking about ways to turn the power on and off with a switch. The initial reasoning was to preserve battery charge to maximise the voltage that SpaceMaker was receiving. But around the time that I switched to the NiMH battery pack, my circuits started to smoke, and I melted through wires on multiple occasions.</p><p>This was now a question of safety and before continuing work with the new battery packs, we made sure to first solder on a switch between the battery pack and the H-bridge. This gave us an emergency power cut-off every time something went wrong. Next, we had to prevent things from going wrong in the first place.</p><p>Going through my logs on the burnt wires, I noticed that it was always the same wire that melted: a thin wire that connected the ground of the H-bridge to the ground of the Arduino board. I spent some time thinking about how I could remove this wire from the circuit, but it was a necessary connection for the Arduino board to control the relays and pulse width modulators in the H-bridge. I roped in my housemate who’s majoring in engineering, but neither of us could figure out what was going wrong in the circuit. So in the end we decided that if the wires were melting because there was too much current flowing through, we simply had to increase the resistance of the wires. Playing around, we found that a 330 ohm resistor, plus the use of much longer wires, was sufficient to prevent further mishaps, while still allowing sufficient current to flow through.</p><p>Finally, there was electrical interference between the Arduino board and the H-bridge that caused various unexpected behaviours and short-circuits. This was resolved by separating the two circuit boards with a non-conducting material.</p><h3>Iteration #4 — Going wireless</h3><p>Following the previous iteration, SpaceMaker is finally able to move under load and we were free to move on to other interesting questions. At the start of this project, I was curious about how a population of SpaceMakers might change the pattern of human movement and interaction within a space. I was also curious about what applications could be developed if we had the ability to communicate between SpaceMakers and/or a command centre (which could be another SpaceMaker). So it was finally time to jump into Bluetooth communication.</p><p>The Bluetooth modules I’d purchased had come without any accompanying documentation. Thankfully they seemed like standard HC-05 modules, and by using the many tutorials, YouTube videos, and fora available, we managed to set up a Bluetooth connection between our Arduino and a laptop/smartphone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*ICnkuiqrX79X93Nc.gif" /><figcaption>Wireless control</figcaption></figure><p>This was also the stage where we were pretty familiar with the system and its shortcomings, so we also made many other tweaks. For example, adjusting the length of spacers below the robot to improve the balance provided by ball bearings; removing the default wires to the mobile chassis and simplifying the wiring for our sensors and actuators; adding a platform above the circuit boards to protect the wiring as well as provide a stable base for holding the battery packs and loose components in place.</p><h4>Iteration #4.1 On-the-fly pulse-width modulation</h4><p>As our prototype became more fleshed out and the deadline for the final video drew nearer, we had to start testing out SpaceMaker in different terrains. However, outdoor terrains were challenging because slopes and debris would often cause SpaceMaker to stall. Thankfully, we’d just spent weeks scaling up the amount of power available to our DC motors, so stalling issues could now be solved by increasing the power supplied to each motor via pulse-width modulation (PWM) according to their performance.</p><p>To improve the convenience of fine-tuning the PWM as well as to add the ability to adjust the PWM as we moved from terrain to terrain, I added a switch to the Bluetooth input loop. Now, in addition to movement commands, we could simply send numeric characters to SpaceMaker via Bluetooth in order to adjust the power being sent to each motor. It’s a little crude, but it worked for our circumstances.</p><pre>void check_bt() {<br>  if (EEBlue.available()) {<br>    char bt_val = EEBlue.read();<br>    switch(bt_val) {<br>      ...<br>      case &#39;2&#39;:<br>        l_power += 25;<br>        analogWrite(pwm_l, l_power);<br>        break;<br>      case &#39;1&#39;:<br>        l_power -= 5;<br>        analogWrite(pwm_l, l_power);<br>        break;<br>      case &#39;9&#39;:<br>        r_power += 25;<br>        analogWrite(pwm_r, r_power);<br>        break;<br>      case &#39;8&#39;:<br>        r_power -= 5;<br>        analogWrite(pwm_r, r_power);<br>        break;<br>    }<br>  }<br>}</pre><h3>Creating the demo video</h3><p>At this point, we had a working prototype and it was time to create a demo video. Throughout the prototyping process, I had thought of SpaceMaker as a social distancing robot, as originally envisioned. However, as we worked on the prototype and the various technical challenges came to light, it became clear that we would need a lot more technical progress (most notably, the ability to use multiple SpaceMakers and/or more complicated sensing patterns) before some of these ideas become feasible. I also wasn’t convinced that social distancing was the right use case for this robot, and slowly lost interest in that idea.</p><p>Then, after many nights spent thinking about this, I started to wonder whether SpaceMaker could be used to expand the range of use cases for existing traffic cones. This eventually led to the idea of proximity-based traffic cones in parking lots that would enable users such as homeowners, pass holders, and handicapped drivers to reserve parking spaces.</p><p>I also drew inspiration from a colleague’s project for a <a href="https://hiloni25.tumblr.com/post/635750285256572928/smart-sign">smart sign</a>. I thought that it would be interesting to make a mobile version of the smart sign, which would be a natural extension of SpaceMaker’s current design because traffic cones already serve as a form of warning, and we had already established a wireless connection between SpaceMaker and smartphones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SiA46_xnwz8If8_N.JPG" /><figcaption>Initial rough storyboard</figcaption></figure><p>Finally, there was the actual filming of these ideas. This turned out to be a productive process in terms of ideation. When explaining the concept of the video to my film crew (my housemates), I needed to pinpoint the ideas that I wanted to convey and the scenes we would need to achieve this. At the same time, the team pointed out where some ideas didn’t make much sense, or where they could be improved or better presented. In the process, the concepts being presented became much more refined compared to my original rough story board. This goes to show how we slowly become over familiar with a concept while we work, which makes us blind to various shortcomings. In times like these, outside perspectives are imperative to improve the design and communication of an idea.</p><h3>Future directions</h3><p>As the semester came to a close, we had to start wrapping up our projects. However, if there were one truism that we’ve learnt from this course, it would be that every iteration informs the next iteration. True enough, after making my final prototype and hearing my colleagues’ critiques, I’m left with many ideas to try out. Someday, if I have the itch to work on a hardware project again, I might well implement some of these improvements. But for now here are my thoughts.</p><h4>Form</h4><p>Throughout the development of SpaceMaker, there has been consistent feedback on how its form could be experimented with or improved. In particular, the size of the traffic cone that SpaceMaker uses could make a big difference in how it’s read. Previously we faced various constraints with the size of the cones we could use with SpaceMaker because heavy loads made the robot stall. However, now that the motor issues have been resolved, we’re freed up to experiment.</p><p>What would happen if SpaceMaker was completely enveloped in a traffic cone? In this case, people would either expect SpaceMaker to be an ordinary traffic cone; or, when they’ve had enough interactions with SpaceMaker, they might start assuming that every traffic cone around them has the potential for movement. To try out this idea, we would either have to purchase a large enough traffic cone (a full 28&quot; cone perhaps?), or construct such a cone. We could then use one of our earlier mounting systems to attach this cone to SpaceMaker, then attach its ultrasound sensors to the exterior surface of the cone, or drill holes for the ultrasound sensors.</p><h4>Multiple robots + collective behaviour</h4><p>One of the original goals for this project was to have multiple SpaceMaker bots interacting and communicating with each other. It eventually became clear that there were other pressing issues to work on before this would be possible, so this idea was shelved for the time being. However, I believe this is still an interesting problem, and one rich with possibilities. Thinking through some of the ideas in <a href="https://www.goodreads.com/book/show/9856806-collective-animal-behavior">collective animal behaviour</a>, a mobile Arduino with a distance sensor should be more than capable of producing rich collective behaviour patterns. We wouldn’t even need to enable Bluetooth communication between each SpaceMaker unit. It would be interesting to explore some theoretical questions in this area, as well as translate them to some productive application.</p><h4>Mechanical improvements</h4><p>Watching SpaceMaker move, it’s immediately noticeable that it moves in fits and starts. Moreover, because it brakes abruptly, it is prone to falling over when moving on a slope. As it is, the mechanical issues currently limit the potential use cases for SpaceMaker. Even for the use cases presented in the demo video, multiple takes had to be filmed because SpaceMaker would occasionally move erratically or tip itself over. However, some colleagues mentioned that this motion was endearing and I do agree that I would like some of this character to remain in future iterations. A natural solution to this dilemma would be to solve the mechanical issues that SpaceMaker currently faces, then add human-like movements afterwards. Some potential ideas are discussed below.</p><ol><li><strong>Smoother pulse-width modulation.</strong> One reason for the jerky movements is that we currently only have one power setting for movement. This means that starting and stopping motions are all-or-nothing and thus abrupt. If we instead slowly ramped up the power and then tapered it off as a movement starts and stops, then SpaceMaker would also move more smoothly.</li><li><strong>Add a gearbox.</strong> Even if we could taper off the power fed to our motors as a movement ends, the start of a movement still poses a challenge. DC motors, under load and in a high friction environment, require a lot of current to avoid stalling. This means that slowly ramping up power wouldn’t produce a smooth start because the robot wouldn’t even be able to start moving until a threshold is reached. And once that threshold is reached, we start moving abruptly and quickly. To solve this, we can use a gearbox with a high gear ratio when a movement begins. This ensures that we can smoothly generate sufficient torque to move even at slow starting speeds.</li><li><strong>Larger wheels.</strong> Currently, due to the small diameter of the wheels, cracks and bumps cause SpaceMaker to stumble and even stall. Larger wheels would address this problem, however they can only be installed in tandem with adding a gearbox, otherwise we wouldn’t be able to generate sufficient torque to move.</li><li><strong>Improved weight distribution.</strong> To improve the overall balance of SpaceMaker, we can either increase the diameter of the base, or shift its centre of gravity downwards. We could lower its centre of gravity by shifting heavier components such as the two battery packs down onto the base chassis. Another option would be to add ballast to the robot.</li></ol><h3>Final remarks</h3><p>Coming from a software background, I was caught completely off guard by the complexities involved in working with hardware. On top of working with ideas and code, there were questions of design, material, weight, circuits, power, and all sorts of other physical considerations to take note of. In light of all this complexity, it was very important to move back-and-forth, side-to-side, from rough sketches to higher and higher resolution prototypes. Otherwise the challenges would have felt overwhelming.</p><p>This has been a rich lesson in ideation and prototyping and I hope to carry this experience into the many projects and discussions to come in life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yv4QZtIC79WTgwWt.JPG" /></figure><p><em>Originally published at </em><a href="https://github.com/desmondcheongzx/SpaceMaker-Bot"><em>http://github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7fbbc4b89ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You, your humanity, and technology: review of You Are Not a Gadget]]></title>
            <link>https://desmondcheongzx.medium.com/you-your-humanity-and-technology-review-of-you-are-not-a-gadget-6421e9fc7e33?source=rss-fbd1952cf037------2</link>
            <guid isPermaLink="false">https://medium.com/p/6421e9fc7e33</guid>
            <category><![CDATA[jaron-lanier]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[review]]></category>
            <category><![CDATA[philosophy]]></category>
            <dc:creator><![CDATA[Desmond Cheong]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 16:32:23 GMT</pubDate>
            <atom:updated>2020-07-30T16:38:51.504Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/266/0*_n05kzb1DqXFmTII.jpg" /></figure><blockquote>The vast fanning out of the fates of these words will take place almost entirely in the lifeless world of pure information. Real human eyes will read these words in only a tiny minority of the cases.</blockquote><blockquote>And yet it is you, the person, the rarity of my readers, I hope to reach.</blockquote><blockquote>The words in this book are written for people, not computers.</blockquote><blockquote>I want to say: You have to be somebody before you can share yourself.</blockquote><blockquote><em>- Jaron Lanier, ending comments in the preface to </em><a href="https://www.goodreads.com/book/show/6683549-you-are-not-a-gadget"><em>You Are Not a Gadget</em></a></blockquote><p>I highly recommend this book for all technologists, and for anyone concerned about the role of technology in the future of culture, the economy, and our humanity.</p><p>This is not simply a book about technology, or a warning call against social media. This is a deep dive into the meaning of person-hood in a world overrun by the philosophy of technological open culture. I’m convinced that in reading this book, even if you walk away with a continued support for open culture, you will walk away with a clearer picture of society and your own humanity.</p><p>I don’t necessarily agree with every line of thought or proposed solution by Jaron Lanier. But I value his writing for the strength of his vision, and the eye-opening discussion of what the internet <em>could have been</em>, from the perspective of a technologist who was in the thick of the action when it happened. It’s insidious that many of us grew up with, and have been habituated to, the current state of technology, so we don’t realise that all these constructs and protocols are merely just that. Constructs. Designed and perpetuated by humans. And also changeable by humans.</p><p>This book has me thinking about a holistic and long-term view of technology more than any other book I’ve read, technical or non-technical. I’m still in the process of deconstructing and reconstructing my worldview on technology, and taking the steps to refine those beliefs and to stamp my own vision onto reality. But I’ve not felt a clearer mission than ever as a computer scientist to fight for a paradigm of technology that will ultimately be pro-human.</p><p><em>Originally published at </em><a href="https://www.desmondcheong.com/blog/2020/07/31/you-your-humanity-and-technology-review-of-you-are-not-a-gadget/"><em>https://www.desmondcheong.com</em></a><em> on July 30, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6421e9fc7e33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An accountant’s rise to power: review of The Traitor Baru Cormorant]]></title>
            <link>https://desmondcheongzx.medium.com/an-accountants-rise-to-power-review-of-the-traitor-baru-cormorant-7e32618e4d89?source=rss-fbd1952cf037------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e32618e4d89</guid>
            <category><![CDATA[the-traitor]]></category>
            <category><![CDATA[seth-dickinson]]></category>
            <category><![CDATA[review]]></category>
            <dc:creator><![CDATA[Desmond Cheong]]></dc:creator>
            <pubDate>Mon, 27 Jul 2020 16:17:48 GMT</pubDate>
            <atom:updated>2020-07-30T16:43:15.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*RHChhS5gV-ISt3sHnyi_ug.jpeg" /></figure><blockquote>“What do you do?”<br>“I try to save my home. Everything I do. For Taranoke.”<br>“You’ve come a long way to do it.”</blockquote><blockquote><em>- Baru and an ilykari priestess</em></blockquote><p>In The Traitor Baru Cormorant, Seth Dickinson crafts an unforgiving world filled with endless games of intrigue. Characters fight for power through weapons of economics, secrets, physical prowess, war, sexuality, and science. No sidelong glance is innocent, and no words can be taken at face value. The twists and turns of the plots within plots bring us on a journey complete with its moments of exhilaration, and moments of excruciatingly well-orchestrated devastation. It’s as if the author savours the act of twisting a blade in his readers’ hearts.</p><blockquote>This is the truth. You will know because it hurts.</blockquote><p>At the heart of the book is the contest between colonisers and liberators. The Traitor opens with Baru’s childhood account of the colonisation of her homeland by the Masquerade. This subjugation doesn’t happen dramatically with guns and steel, but slowly, through the weapons of trade, education, and plague. And later, upon leaving her homeland Taranoke, we are shown a more matured progression of Masquerade Colonisation through Aurdwynn. From the start, and continuing throughout the book, we are presented with both the benefits of the scientifically advanced Masquerade’s rule (commerce, sanitation, education, etc), but also the accompanying costs (loss of autonomy, genocide, criminalisation of cultural norms and practices, etc). The internal conflict of these trade-offs plays out repeatedly in this book, clashing in a pattern that grows ever larger. We are invited to observe the Masquerade’s final test for Baru Cormorant, a savant selected and groomed by the Masquerade, to subjugate a foreign land. Along the way, we bear witness to her sometimes clever, sometimes miscalculated navigation and manipulation of these colonial tensions. She decides early on, that her best chance at overthrowing her colonial oppressors would be through treachery from a position of power. And throughout her endeavours, we are constantly reminded that she is but one of the many players on the board.</p><p>The exploration of these themes of colonisation are brought to life only because we see the conflicts raging through interesting characters. Without speaking too much about the roles and loyalties of each character, I’ll simply say that even with a cast full of dukes and duchesses with their followers and children, technocrats and their assistants, and not to mention characters that appear early in the book but are only mentioned in passing later; even with such a large cast, the reader is able to get a good sensing for each of them. Moreover, each character feels like an independent player on the board with their own missions and motivations. Instead of a story with clear protagonists and antagonists, everyone is both a potential ally and a potential antagonist. The stakes in this story are never low, the characters are well aware of it, and Seth Dickinson never lets us forget it.</p><p>After a good book, I usually wish I could forget everything that happened so that I may reread the story with the pleasure of first-times. After finishing The Traitor, I found myself filled with this same desire. But this time, I didn’t just want to reread the book for the first time, I wanted to return to a time when my heart didn’t ache so much. Because on a board with so many players, so many games of power and divided loyalties, victories and losses can only happen hand-in-hand. As an accountant, Baru herself must have known all along, even if she tricked herself into forgetting it, that the numbers ultimately have to be balanced.</p><p>Let it be clear though. My devastation is nothing but praise for the author Seth Dickinson, and for the traitor Baru Cormorant.</p><p><em>Originally published at </em><a href="https://www.desmondcheong.com/blog/2020/07/28/an-accountants-rise-to-power-review-of-the-traitor-baru-cormorant/"><em>https://www.desmondcheong.com</em></a><em> on July 28, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e32618e4d89" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>