<?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 Jeremy Rose on Medium]]></title>
        <description><![CDATA[Stories by Jeremy Rose on Medium]]></description>
        <link>https://medium.com/@nornagon?source=rss-564335d4cff6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*H24FcUXUR_E_RZtd.png</url>
            <title>Stories by Jeremy Rose on Medium</title>
            <link>https://medium.com/@nornagon?source=rss-564335d4cff6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:54:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nornagon/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[A libc++ Odyssey]]></title>
            <link>https://nornagon.medium.com/a-libc-odyssey-973e51649063?source=rss-564335d4cff6------2</link>
            <guid isPermaLink="false">https://medium.com/p/973e51649063</guid>
            <category><![CDATA[chrome]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[electron]]></category>
            <dc:creator><![CDATA[Jeremy Rose]]></dc:creator>
            <pubDate>Wed, 28 Apr 2021 19:18:25 GMT</pubDate>
            <atom:updated>2024-04-08T23:36:29.890Z</atom:updated>
            <content:encoded><![CDATA[<p>Alrighty folks, buckle up and get ready to learn some x86 assembly and V8 internals. I want to tell you about how I spent yesterday beating my head against a problem we ran into while upgrading the version of Chromium used in Electron, and finally figured out the fix.</p><blockquote>This was originally an internal essay published to the Electron Maintainers group. For context, Electron continually tracks the latest version of Chromium, generally landing an update into the main branch once every week or two. Some upgrades are more difficult than others.</blockquote><p>Let’s set the scene. Chromium is probably the largest and most complex C++ codebase in the world. Even not counting any of its 300+ dependencies, Chromium itself contains over 11 megalines of C and C++. So it’s not terribly surprising then that its build configuration is similarly complex. Chromium’s build system uses a version of Clang and LLVM taken from tip-of-tree, the latest and greatest in compiler technology. It depends on features in Clang that aren’t yet in released versions of Clang — the latest Chromium code will fail to build on stable versions of Clang. And if that wasn’t cutting-edge enough, Chromium also declines to use the standard C++ runtime library, opting instead to use a fairly new reimplementation of the C++ standard library called, confusingly, <a href="https://libcxx.llvm.org/">libc++</a>. The reasons for this are varied and mostly boring. But, having tried it, we also know that Chromium does not build without this fancy custom C++ standard library.</p><p>So, okay, Chromium’s build process is complicated. But that’s fine, Chromium comes with instructions for how to build it, in the form of <a href="https://gn.googlesource.com/gn/">GN</a> files. We follow those instructions, we use the fancy compiler and the custom standard library when we build Electron. It works fine. What’s the problem?</p><p>Well, let me show you. In the latest Chromium upgrade PR in Electron, we started seeing this error:</p><pre># Fatal error in ../../v8/src/api/api-inl.h, line 131<br># Debug check failed: that == nullptr || v8::internal::Object( *reinterpret_cast&lt;const v8::internal::Address*&gt;(that)).IsJSArrayBuffer().</pre><p>This error was showing up in the tests we have that check that native node modules work. Your alarm bells might be ringing already: are the native node modules also built with the fancy compiler and the custom standard library and all that stuff? Dear reader, they are not. But, uh, mostly it works fine anyway? This test used to pass, in any case. So what’s going on here?</p><p>Let’s look at the test that’s failing. It’s a <a href="https://github.com/nodejs/nan">nan</a> test with two parts; a JavaScript part and a C++ part. The relevant JavaScript part looks like this:</p><pre>var zeros = new Uint8Array(5)<br>t.same(bindings.ReadU8(zeros), [0,0,0,0,0])</pre><p>And the corresponding C++ part that is the code behind bindings.ReadU8 in the above is:</p><pre>NAN_METHOD(ReadU8) {<br>  TypedArrayContents&lt;uint8_t&gt; data(info[0]);</pre><pre>  // … this function has other things in it, but as we’ll see in a<br>  // moment, the above line is where the failure happens.<br>}</pre><p>So let’s look the stack trace. I ran the failing test under lldb to get a more detailed stack trace, and here’s what I saw.</p><pre>* frame #0: Abort() at platform-posix.cc:502:5 [opt]<br>  frame #1: V8_Fatal() at logging.cc:167:3 [opt]<br>  frame #2: DefaultDcheckHandler() at logging.cc:57:3 [opt]<br>  frame #3: GetBackingStore() [inlined] OpenHandle at api-inl.h:131:1 [opt]<br>  frame #4: GetBackingStore() at api.cc:3784 [opt]<br>  frame #5: Nan::TypedArrayContents::TypedArrayContents() at nan_typedarray_contents.h:45:41 [opt]<br>  frame #6: ReadU8() [inlined] at nan_typedarray_contents.h:20:31 [opt]<br>  frame #7: ReadU8() at typedarrays.cpp:17 [opt]</pre><pre>[…]</pre><p>Alrighty, so we’re crashing in the bindings.ReadU8() call. Something in the constructor of Nan::TypedArrayContents is calling v8::ArrayBuffer::GetBackingStore(), and something in there is hitting a DCHECK. Specifically, the DCHECK that’s failing is v8::internal::Object(*reinterpret_cast&lt;const v8::internal::Address*&gt;(that)).IsJSArrayBuffer(), which is basically checking that the thing passed to it is actually an ArrayBuffer.</p><p>It is, of course, impossible for this DCHECK to be firing.</p><h4>Stage 1: Denial</h4><p>Here’s the calling code, in <a href="https://github.com/nodejs/nan/blob/7c3fc6884666bd19b597ea58a99f51f2f4860c4e/nan_typedarray_contents.h#L15-L37">nan_typedarray_contents.h</a>, slightly abridged:</p><pre>if (from-&gt;IsArrayBufferView()) {<br>  v8::Local&lt;v8::ArrayBufferView&gt; array =<br>    v8::Local&lt;v8::ArrayBufferView&gt;::Cast(from);<br>  v8::Local&lt;v8::ArrayBuffer&gt; buffer = array-&gt;Buffer();<br>  data = static_cast&lt;char*&gt;(buffer-&gt;GetBackingStore()-&gt;Data());</pre><p>i.e. we (1) check that from is an ArrayBufferView, (2) get the underlying ArrayBuffer by calling array-&gt;Buffer(), then (3) call buffer-&gt;GetBackingStore() on that object. It is step (3) here which triggers the DCHECK: GetBackingStore() thinks this is not an ArrayBuffer. It absolutely, definitely is, though. I verified this in a few different ways:</p><ul><li>I printed out the result of calling buffer-&gt;IsArrayBuffer(). It’s true.</li><li>I compiled V8 with its internal debug printing code enabled, and asked the debugger to print the value of buffer. It replied that buffer was a JSArrayBuffer.</li><li>I changed the test function in C++ to return its first argument, then printed it out from JS, and saw that it was a UInt8Array.</li></ul><p>So why is this DCHECK failing? How could it possibly be failing? The thing is definitely a JSArrayBuffer, so why is IsJSArrayBuffer returning false inside of V8???</p><p>At this time I paged <a href="https://medium.com/u/d68d0c03adbf">Samuel Attard</a> who kindly Zoomed with me while I sobbed into the debugger. And by “debugger”, I of course mean printf. I added two printf calls, one in nan_typedarray_contents.h right before the failing call to GetBackingStore(), and one inside GetBackingStore() itself. To explain what I saw I have to take a q̶u̶i̶c̶k (lol sorry) detour into some V8 internals. It’ll only hurt a bit, I promise.</p><h4>Integers All the Way Down</h4><p>When interacting with V8 from C++, it’s very common to want to have a handle to an object, kind of like a pointer. v8::Local is what represents this kind of handle in C++. So what exactly is v8::Local? Is it a pointer? To what does it point? Let’s take a look at <a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/include/v8.h;l=199;drc=16d9298a9c1f06ed8192c31baaef9c9cb1a4484c">the source code</a> and find out:</p><pre>// in v8/include/v8.h<br>template &lt;class T&gt;<br>class Local {<br> public:<br>  V8_INLINE T* operator-&gt;() const { return val_; }<br>  // … etc.<br> private:<br>  T* val_;<br>}</pre><p>That’s all! Local&lt;T&gt; wraps a pointer to T. It overrides operator-&gt; so that if you have a Local&lt;T&gt; called x, then x-&gt;Foo() calls T::Foo() on the underlying pointer. In our case, T is ArrayBuffer. So what does ArrayBuffer::GetBackingStore do? (<a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/src/api/api.cc;l=3782-3791;drc=5e39dac724c6fd116b10137c0aa8d8334c999459">src</a>)</p><pre>std::shared_ptr&lt;v8::BackingStore&gt; v8::ArrayBuffer::GetBackingStore() {<br>  i::Handle&lt;i::JSArrayBuffer&gt; self = Utils::OpenHandle(this);<br>  std::shared_ptr&lt;i::BackingStore&gt; backing_store =<br>    self-&gt;GetBackingStore();<br>  // …<br>}</pre><p>Interesting! The only thing it does with this is to call Utils::OpenHandle on it. Simplifying a little <a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/src/api/api-inl.h;l=119-129;drc=85819a30dd841f3e786adf1cf0ce0ed2a02fb56f">macro expansion</a>, this is what Utils::OpenHandle looks like:</p><pre>v8::internal::Handle&lt;v8::internal::JSArrayBuffer&gt;<br>Utils::OpenHandle(const v8::ArrayBuffer* that) {<br>  DCHECK(that == nullptr ||<br>      v8::internal::Object(<br>        *reinterpret_cast&lt;const v8::internal::Address*&gt;(that))<br>        .IsJSArrayBuffer());<br>  return v8::internal::Handle&lt;v8::internal::JSArrayBuffer&gt;(<br>    reinterpret_cast&lt;v8::internal::Address*&gt;(<br>      const_cast&lt;v8::ArrayBuffer*&gt;(that)));<br>}</pre><p>Whoa! That’s our DCHECK that’s failing! And … what’s this reinterpret_cast?? It looks like it takes our v8::ArrayBuffer*, which is this from ArrayBuffer::GetBackingStore() and interprets it as a pointer to a v8::Internal::Address. What’s a v8::internal::Address?</p><pre>typedef uintptr_t Address;</pre><p>uintptr_t is an unsigned integer type large enough to hold a pointer. So Address is … a number?? That’s a bit surprising! So, to recap, here’s what’s going on:</p><ol><li>Local&lt;ArrayBuffer&gt; is roughly the same as ArrayBuffer*</li><li>ArrayBuffer::GetBackingStore takes this and passes it to Utils::OpenHandle</li><li>Utils::OpenHandle reinterprets this, which is of type ArrayBuffer*, as Address*</li><li>Address is the same as uintptr_t</li><li>So Utils::OpenHandle is interpreting this as a uintptr_t*</li></ol><p>So basically ArrayBuffer is the same as uintptr_t??? Local&lt;ArrayBuffer&gt; is really just a pointer to an integer in disguise!</p><figure><img alt="“Wait, it’s all just numbers?” / “Always has been” (astronaut meme)" src="https://cdn-images-1.medium.com/max/888/0*20gyDjLud7MtqWfR.jpg" /></figure><p>Okay, so what does Utils::OpenHandle do next? It dereferences the uintptr_t*, and passes the resulting integer to v8::internal::Object(), then calls IsJSArrayBuffer on the Object.</p><p>We’re uh, pretty deep in the weeds here, so I wanted to take a moment to remember what drove us to this clearly insane point. We have some code that calls an ArrayBuffer method on an ArrayBuffer, but that method insists it’s actually not being called on an ArrayBuffer. It uses IsJSArrayBuffer to check that. So somehow IsJSArrayBuffer is returning the wrong thing. Okay. Probably take a moment to breathe and get a coffee or something. I’ll wait.</p><p>☕️️️ ☕️ ☕️</p><h4>Ultimately Graspable</h4><p>Alright, feeling refreshed? Here we go again. Let’s look at the definition of IsJSArrayBuffer. It’s actually <a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/src/objects/objects-inl.h;l=76-78;drc=3f9ff062b053155df7897f199e80a8bafe7c34df">defined by some macros</a>, but I’ll expand them for clarity here:</p><pre>bool Object::IsJSArrayBuffer() const {<br>  return IsHeapObject() &amp;&amp;<br>    HeapObject::cast(*this).IsJSArrayBuffer();<br>}</pre><p>Using a debugger, I stepped very carefully through this code, instruction by instruction, and discovered that <em>we never even get to HeapObject::IsJSArrayBuffer</em>. IsHeapObject() returns false! What does Object::IsHeapObject do? (<a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/src/objects/tagged-impl.h;l=74-75;drc=85819a30dd841f3e786adf1cf0ce0ed2a02fb56f">src 1</a>, <a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/src/objects/tagged-impl.h;l=89-94;drc=85819a30dd841f3e786adf1cf0ce0ed2a02fb56f">src 2</a>)</p><pre>// Returns true if this tagged value is a strong pointer to a HeapObject.<br>constexpr inline bool IsHeapObject() const { return IsStrong(); }<br>constexpr inline bool IsStrong() const {<br>  CONSTEXPR_DCHECK(kCanBeWeak ||<br>    (!IsSmi() == HAS_STRONG_HEAP_OBJECT_TAG(ptr_)));<br>  return kCanBeWeak ? HAS_STRONG_HEAP_OBJECT_TAG(ptr_) : !IsSmi();<br>}</pre><p>In this particular case kCanBeWeak is false (proving this is left as an exercise to the reader), so this is the same as calling !IsSmi(). I’m leaving aside for the moment the details of exactly what a “heap object” or a “tagged value” or a “strong pointer” are, because frankly, I have no idea. I’m just following the code where it leads. So let’s take a look at IsSmi(): (<a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/src/objects/tagged-impl.h;l=69-70;drc=85819a30dd841f3e786adf1cf0ce0ed2a02fb56f">src 1</a>, <a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/src/common/globals.h;l=959-960;drc=85819a30dd841f3e786adf1cf0ce0ed2a02fb56f">src 2</a>, <a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/include/v8-internal.h;l=43-46;drc=7a62cceb72cd9d9b95cf2517accb29c665a60330">src 3</a>)</p><pre>// Returns true if this tagged value is a Smi.<br>constexpr bool IsSmi() const { return HAS_SMI_TAG(ptr_); }</pre><pre>// ...</pre><pre>#define HAS_SMI_TAG(value) \<br> ((static_cast&lt;i::Tagged_t&gt;(value) &amp; ::i::kSmiTagMask) == ::i::kSmiTag)</pre><pre>// ...</pre><pre>// Tag information for Smi.<br>const int kSmiTag = 0;<br>const int kSmiTagSize = 1;<br>const intptr_t kSmiTagMask = (1 &lt;&lt; kSmiTagSize) — 1;</pre><p>This is some bit twiddling fanciness that boils down to: if the lowest bit of ptr_ is 0, then this is a “smi”. Otherwise it’s not.</p><p>We know that IsHeapObject is returning <em>false</em> for us. Which means that !IsSmi() is false. <em>Which means that </em><em>IsSmi() is returning true!!</em></p><h4><em>Our ArrayBuffer is a Smi?????</em></h4><p>At this point I googled “<a href="https://medium.com/fhinkel/v8-internals-how-small-is-a-small-integer-e0badc18b6da">v8 smi</a>” and it turns out “smi” in V8’s parlance means “small integer”, i.e. a JS number that’s an integer within a certain range. So, somehow, this ArrayBuffer object, which is definitely an ArrayBuffer, is being seen to be a JS number.</p><p>ngl, I was pretty completely flummoxed by now. But I have this stubborn belief that everything that happens on a computer is, ultimately, possible to understand. So I kept going.</p><h4>What Even Are Computers</h4><p>Okay, fine. So the lowest bit of ptr_ is 0, which causes IsSmi() to return true. Where does ptr_ come from?</p><p>Remember this from Utils::OpenHandle?</p><pre>DCHECK(that == nullptr ||<br>    v8::internal::Object(<br>      *reinterpret_cast&lt;const v8::internal::Address*&gt;(that))<br>      .IsJSArrayBuffer());</pre><p>Let’s look at the <a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/src/objects/objects.h;l=273-276;drc=eed0d27c2f774b3adbc85d0a5fb30a8cf0f018a8">definition</a> of v8::internal::Object():</p><pre>class Object<br>  : public TaggedImpl&lt;HeapObjectReferenceType::STRONG, Address&gt; {<br> public:<br>  explicit constexpr Object(Address ptr) : TaggedImpl(ptr) {}</pre><p>That passes its argument (promisingly called ptr!) to TaggedImpl(): (<a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/src/objects/tagged-impl.h;l=38;drc=85819a30dd841f3e786adf1cf0ce0ed2a02fb56f">src</a>)</p><pre>template &lt;HeapObjectReferenceType kRefType, typename StorageType&gt;<br>class TaggedImpl {<br> public:<br>  explicit constexpr TaggedImpl(StorageType ptr) : ptr_(ptr) {}</pre><p>There it is! So ptr_ is the v8::internal::Address, aka uintptr_t, that was passed to v8::internal::Object!</p><p>Now we have enough background to understand what it was I printed out with those two printf calls, and why the answer made me even more confused.</p><h4>Advanced Debugging Techniques</h4><p>Here’s the first printf call I added, in nan_typedarray_contents.h, before we call out to GetBackingStore():</p><pre> v8::Local&lt;v8::ArrayBuffer&gt; buffer = array-&gt;Buffer();<br>+v8::ArrayBuffer* addr = *buffer;<br>+uintptr_t* addr_as_uintptr = reinterpret_cast&lt;uintptr_t*&gt;(addr);<br>+<br>+fprintf(stderr, “addr of buffer = %08lx\n”, *addr_as_uintptr);<br> data = static_cast&lt;char*&gt;(buffer-&gt;GetBackingStore()-&gt;Data())<br>   + byte_offset;</pre><p>The effect of this is to print out the value of the v8::internal::Address that’s underlying buffer.</p><p>The second printf call was inside v8::ArrayBuffer::GetBackingStore. For this one I just copied the code out of the failing DCHECK in Utils::OpenHandle:</p><pre> std::shared_ptr&lt;v8::BackingStore&gt;<br> v8::ArrayBuffer::GetBackingStore() {<br>+  fprintf(stderr, “addr inside v8::AB::GBS = %lx\n”,<br>+  *reinterpret_cast&lt;const v8::internal::Address*&gt;(this));<br>   i::Handle&lt;i::JSArrayBuffer&gt; self = Utils::OpenHandle(this);</pre><p>The effect of this is also to print out the value of the v8::internal::Address that’s underlying the ArrayBuffer.</p><p>These two printf calls should print the same value.</p><p>Here’s what they printed when I recompiled and ran the test:</p><pre>addr of buffer = 4f084b8c9d<br>addr inside v8::AB::GBS = 4f00000070</pre><p>I logged off.</p><h4>In mov, Veritas</h4><p>The next day, after having regained my composure, and having reaffirmed my belief that everything on a computer is ultimately graspable, I decided that C++ must be lying to me. You know what never lies? x86 assembly. It was time to peel away the illusion of pointers and objects and methods, and get down to the movs and jmps. In mov, veritas.</p><blockquote>Also, as a side note, we now know why IsSmi was returning true: the low bit of 0x4f00000070 is 0, so it passes the HAS_SMI_TAG check. It’s just that that’s … not the Address of our object.</blockquote><p>I loaded up the test in lldb:</p><pre>$ (cd ../third_party/nan/test/js; lldb ~/work/electron/src/out/Testing/Electron.app/Contents/MacOS/Electron -- typedarrays-test.js)<br>(lldb) ▊</pre><p>I set a breakpoint immediately before the call to GetBackingStore():</p><pre>(lldb) b nan_typedarray_contents.h:39</pre><p>and ran the test:</p><pre>(lldb) r</pre><p>It stopped at my breakpoint, and I typed the command to lift the veil:</p><pre>(lldb) disassemble<br>typedarrays.node`Nan::TypedArrayContents&lt;unsigned char&gt;::TypedArrayContents:<br>   [...]<br>   0x11b7af8c8 &lt;+104&gt;: movq 0x739(%rip), %rax ; (void *): __stderrp<br>   0x11b7af8cf &lt;+111&gt;: movq (%rax), %rdi<br>   0x11b7af8d2 &lt;+114&gt;: movq (%rbx), %rdx<br>   0x11b7af8d5 &lt;+117&gt;: leaq 0x641(%rip), %rsi ; “addr of buffer = %08lx\n”<br>   0x11b7af8dc &lt;+124&gt;: xorl %eax, %eax<br>   0x11b7af8de &lt;+126&gt;: callq 0x11b7afd62 ; symbol stub for: fprintf<br>   0x11b7af8e3 &lt;+131&gt;: leaq -0x38(%rbp), %rdi<br>-&gt; 0x11b7af8e7 &lt;+135&gt;: movq %rbx, %rsi<br>   0x11b7af8ea &lt;+138&gt;: callq 0x11b7afca2 ; symbol stub for: v8::ArrayBuffer::GetBackingStore()<br>   [...]</pre><p>Now we’re talking. Three quick things about x86 assembly, if you’ve not seen it much before: first, things prefixed with % are registers. so %rip, %rax, %rdi etc. are all registers, each holds a 64-bit integer. Second, most instructions put their result in the 2nd argument. So for example, movq %rbx, %rsi copies the value of the register %rbx into the register %rsi. Third, (%rax) means “the value in memory at the address contained in %rax”, i.e. it’s a dereference, like *foo in C++.</p><p>Looking at the above disassembly, we can guess a couple of things:</p><ul><li>%rbx contains the uintptr_t* that we called addr_as_uintptr. This isn’t the v8::internal::Address itself, it’s a pointer to a bit of memory that holds that address. movq (%rbx), %rdx fetches the Address out of RAM and puts it in %rdx. We guess this because it happens before callq 0x11a7c6d5c, which lldb has helpfully annotated is the address for the fprintf function, and because %rbx is also referenced before the call to v8::ArrayBuffer::GetBackingStore.</li><li>This code is passing this to v8::ArrayBuffer::GetBackingStore in the register %rsi. We guess this because right before the callq instruction that jumps to the code for v8::ArrayBuffer::GetBackingStore, we see movq %rbx, %rsi, which copies the value of %rbx into %rsi. So the calling code is “setting up” for the GetBackingStore() to run by putting the value this in the right place.</li></ul><p>This might sound weird because this isn’t something you pass to a function in C++! But that information still has to get to the function somehow. On POSIX systems, the convention is that it’s passed as if it were the first argument to the function, which happens to be, also by <a href="https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI">convention</a>, the %rdi register. (But wait, we’re seeing this passed through %rsi…? Our spidey senses are tingling now.)</p><p>We can confirm that %rbx points to the same address that was printed out by our debugging printf call by asking lldb what’s in all the registers:</p><pre>(lldb) register read<br>General Purpose Registers:<br>   rax = 0x000000000000001c<br>   rbx = 0x000000011b8713d0<br>   rcx = 0xecc0c702c36f00e1<br>   rdx = 0x0000000000000000<br>   rdi = 0x00007ffeefbfdf98<br>   rsi = 0x00000000000120a8<br>   [...]</pre><p>rbx contains the value 0x000000011b8713d0, which isn’t what we expected (0x4f084b8c9d), but that’s because it’s not the uintptr_t itself, it’s a pointer to that (uintptr_t*). Let’s dereference it:</p><pre>(lldb) p (void*)*(uintptr_t*)0x000000011b8713d0<br>(void *) $0 = 0x0000004f084b8c9d</pre><p>Ah, there we go. (The (void*) is there to get lldb to print out the value in hex.)</p><p>Alrighty, so %rbx contains the address of our Address, and it’s going to get put into %rsi and then we’re going to jump into v8::ArrayBuffer::GetBackingStore. Let’s see what happens when we do, stepping one instruction at a time with si:</p><pre>(lldb) si</pre><p>after a detour through libdyld.dylib to resolve the function address, we eventually end up in v8::ArrayBuffer::GetBackingStore, and run disassemble again:</p><pre>(lldb) disassemble<br>Electron Framework`::GetBackingStore():<br>   [...]<br>   0x101cf725a &lt;+10&gt;: movq %rdi, %r14<br>   0x101cf725d &lt;+13&gt;: movq 0x9bacc04(%rip), %rax ; (void *): __stderrp<br>   0x101cf7264 &lt;+20&gt;: movq (%rax), %rdi<br>   0x101cf7267 &lt;+23&gt;: movq (%r14), %rdx<br>   0x101cf726a &lt;+26&gt;: leaq 0x897e8fd(%rip), %rsi ; “v8::AB::GBS %lx\n”<br>   0x101cf7271 &lt;+33&gt;: xorl %eax, %eax<br>-&gt; 0x101cf7273 &lt;+35&gt;: callq 0x10a4c6ed6 ; symbol stub for: fprintf</pre><p>… NOW WAIT A DANG MINUTE. The Nan::TypedArrayContents code put this into %rsi. But this code doesn’t read %rsi at all! In fact it <em>overwrites</em> %rsi at &lt;+26&gt;! This code is printing the value of %rdi!</p><p>No wonder it’s printing different things! It’s because it’s printing different things! 😬</p><h4>At Least it’s Not DNS</h4><p>How could this happen? When I write this in ArrayBuffer::GetBackingStore(), the compiler generates code that reads the value of the register %rdi, but the calling code in Nan::TypedArrayContents thinks it’s supposed to put this into %rsi. What’s going on here???</p><p>This would be a good moment to recall that Nan::TypedArrayContents is part of the native module we’re building, and is built by the system clang++ compiler, using the GNU libstdc++ standard library, whereas ArrayBuffer::GetBackingStore is built by Chromium’s clang++ compiler, using the LLVM libc++ standard library.</p><p>But… this used to work, right? This only started failing when we rolled chromium last week! What happened? Well, let’s check the logs of the roll which broke it (which <a href="https://medium.com/u/d68d0c03adbf">Samuel Attard</a> kindly bisected for me): it broke when we rolled chromium from <a href="https://chromium.googlesource.com/chromium/src/+log/1f252b391a40e2681b0d9aff6497b7401863d1fc..90.0.4415.0?n=10000">1f252b391..90.0.4415.0</a>.</p><p>… uh okay, there are over 5,000 commits in that range. What if we just look for changes in the //build directory? That’s where compiler configuration is mostly stored, so hopefully, this looking like a compiler configuration thing, what broke it is <a href="https://chromium.googlesource.com/chromium/src/+log/1f252b391a40e2681b0d9aff6497b7401863d1fc..90.0.4415.0/build?n=10000">in there somewhere</a>.</p><p>And, ding ding ding! Here we are, look at this!</p><pre>3f200c0d Roll src/buildtools/third_party/libc++/trunk/ d9040c75c..69897abe2 (1149 commits) by Reid Kleckner · 8 weeks ago</pre><p>Holy heck! This Chromium roll included an update of the bundled libc++ library that included <em>over one thousand commits</em> to libc++! That’s <a href="https://chromium.googlesource.com/external/github.com/llvm/llvm-project/libcxx/+log/d9040c75cfea5928c804ab7c235fed06a63f743a..69897abe2d4eae76816211fb408a07ba9b9e801f?n=10000">over a year of work</a> in libc++. No wonder something broke. In fact, things broke in Chromium too, because you can see in the changelog that they reverted this commit after it landed, then fixed some stuff and landed it again.</p><p>Alright, so Chromium updated libc++. That seems like it could be the cause of this breakage, maybe. But how do we confirm that? We could try reverting this libc++ update in Chromium and rebuilding, but we can’t resist progress forever. Instead, let’s try building the native module with the same compiler and standard library as Electron itself. If it’s a problem with mismatched compiler and/or standard library, then that should fix it, right?</p><p>A “proper” fix for this would mean teaching node-gyp how to use the Chromium clang++ and libc++, but I have no idea how node-gyp works so I’m just going to hack it. I know that make respects environment variables called CXX and CXXFLAGS to set the path to the C++ compiler executable and extra flags to pass to it, so I’ll use those. I want to set it to use the clang++ compiler that’s used to build Electron, and all the same -fwhatever and -DWHATEVER flags that GN passes to the compiler. After a little trial and error, and copy-pasting things out of out/Testing/obj/electron/electron_lib.ninja, I ended up with something like this:</p><pre>$ export CXX=&quot;.../src/third_party/llvm-build/Release+Asserts/bin/clang++&quot;<br>$ export CXXFLAGS=&quot;-DV8_DEPRECATION_WARNINGS -DDCHECK_ALWAYS_ON=1 -D_LIBCPP_HAS_NO_ALIGNED_ALLOCATION -DCR_XCODE_VERSION=1240 -DCR_CLANG_REVISION=\&quot;llvmorg-13-init-3462-gfe5c2c3c-2\&quot; -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D_FORTIFY_SOURCE=2 -D_LIBCPP_ABI_UNSTABLE -D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS -D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS -D_LIBCPP_ENABLE_NODISCARD -D_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS -D_LIBCPP_DEBUG=0 -DCR_LIBCXX_REVISION=8fa87946779682841e21e2da977eccfb6cb3bded -D__ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES=0 -DNDEBUG -DNVALGRIND -DDYNAMIC_ANNOTATIONS_ENABLED=0 -DV8_USE_EXTERNAL_STARTUP_DATA -DNODE_WANT_INTERNALS=1 -DELECTRON_PRODUCT_NAME=\&quot;Electron\&quot; -DELECTRON_PROJECT_NAME=\&quot;electron\&quot; -DENABLE_IPC_FUZZER -DWEBP_EXTERN=extern -DUSE_EGL -D_WTL_NO_AUTOMATIC_NAMESPACE -DTOOLKIT_VIEWS=1 -DU_USING_ICU_NAMESPACE=0 -DU_ENABLE_DYLOAD=0 -DUSE_CHROMIUM_ICU=1 -DU_ENABLE_TRACING=1 -DU_ENABLE_RESOURCE_TRACING=0 -DU_STATIC_IMPLEMENTATION -DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_FILE -DSK_FAVOR_WUFFS_V_0_3_OVER_V_0_2 -DSK_CODEC_DECODES_PNG -DSK_CODEC_DECODES_WEBP -DSK_ENCODE_PNG -DSK_ENCODE_WEBP -DSK_USER_CONFIG_HEADER=\&quot;../../skia/config/SkUserConfig.h\&quot; -DSK_GL -DSK_CODEC_DECODES_JPEG -DSK_ENCODE_JPEG -DSK_HAS_WUFFS_LIBRARY -DSK_SUPPORT_GPU=1 -DSK_GPU_WORKAROUNDS_HEADER=\&quot;gpu/config/gpu_driver_bug_workaround_autogen.h\&quot; -DSK_BUILD_FOR_MAC -DSK_METAL -DGOOGLE_PROTOBUF_NO_RTTI -DGOOGLE_PROTOBUF_NO_STATIC_INITIALIZER -DHAVE_PTHREAD -DWEBRTC_ENABLE_AVX2 -DWEBRTC_NON_STATIC_TRACE_EVENT_HANDLERS=0 -DWEBRTC_CHROMIUM_BUILD -DWEBRTC_POSIX -DWEBRTC_MAC -DABSL_ALLOCATOR_NOTHROW=1 -DWEBRTC_USE_BUILTIN_ISAC_FIX=0 -DWEBRTC_USE_BUILTIN_ISAC_FLOAT=1 -DWEBRTC_HAVE_SCTP -DNO_MAIN_THREAD_WRAPPING -DLEVELDB_PLATFORM_CHROMIUM=1 -DLEVELDB_PLATFORM_CHROMIUM=1 -DV8_ENABLE_CHECKS -DV8_COMPRESS_POINTERS -DV8_COMPRESS_POINTERS_IN_SHARED_CAGE -DV8_31BIT_SMIS_ON_64BIT_ARCH -DV8_DEPRECATION_WARNINGS -DCPPGC_CAGED_HEAP -DV8_ENABLE_CHECKS -DV8_COMPRESS_POINTERS -DV8_COMPRESS_POINTERS_IN_SHARED_CAGE -DV8_31BIT_SMIS_ON_64BIT_ARCH -DV8_DEPRECATION_WARNINGS -DCPPGC_CAGED_HEAP -DV8_ENABLE_CHECKS -DV8_COMPRESS_POINTERS -DV8_COMPRESS_POINTERS_IN_SHARED_CAGE -DV8_31BIT_SMIS_ON_64BIT_ARCH -DV8_DEPRECATION_WARNINGS -DCPPGC_CAGED_HEAP -DV8_ENABLE_CHECKS -DV8_COMPRESS_POINTERS -DV8_COMPRESS_POINTERS_IN_SHARED_CAGE -DV8_31BIT_SMIS_ON_64BIT_ARCH -DV8_DEPRECATION_WARNINGS -DCPPGC_CAGED_HEAP -DHAVE_INSPECTOR=1 -DHAVE_OPENSSL=1 -DOPENSSL_NO_SSL_TRACE=1 -DNODE_HAVE_I18N_SUPPORT=1 -DNODE_USE_V8_PLATFORM=0 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -D_DARWIN_USE_64_BIT_INODE=1 -DCRASHPAD_ZLIB_SOURCE_EXTERNAL -DFLATBUFFERS_LOCALE_INDEPENDENT=0 -fno-delete-null-pointer-checks -fno-ident -fno-strict-aliasing -fstack-protector -fcolor-diagnostics -fmerge-all-constants -fcrash-diagnostics-dir=../../tools/clang/crashreports -mllvm -instcombine-lower-dbg-declare=0 -fcomplete-member-pointers -arch x86_64 -Wno-builtin-macro-redefined -D__DATE__= -D__TIME__= -D__TIMESTAMP__= -Xclang -fdebug-compilation-dir -Xclang . -no-canonical-prefixes -Wall -Werror -Wextra -Wimplicit-fallthrough -Wunreachable-code -Wthread-safety -Wextra-semi -Wunguarded-availability -Wno-missing-field-initializers -Wno-unused-parameter -Wno-c++11-narrowing -Wno-unneeded-internal-declaration -Wno-undefined-var-template -Wno-psabi -Wno-ignored-pragma-optimize -Wno-implicit-int-float-conversion -Wno-final-dtor-non-final-class -Wno-builtin-assume-aligned-alignment -Wno-deprecated-copy -Wno-non-c-typedef-for-linkage -Wno-max-tokens -O2 -fno-omit-frame-pointer -gdwarf-4 -g1 -isysroot sdk/xcode_links/MacOSX11.1.sdk -mmacosx-version-min=10.11.0 -ftrivial-auto-var-init=pattern -fvisibility=hidden -Xclang -add-plugin -Xclang find-bad-constructs -Xclang -plugin-arg-find-bad-constructs -Xclang checked-ptr-as-trivial-member -Wheader-hygiene -Wstring-conversion -Wtautological-overlap-compare -DPROTOBUF_ALLOW_DEPRECATED=1 -Wno-shorten-64-to-32 -Wno-microsoft-include&quot;<br>$ make -C ~/work/electron/src/third_party/nan/test/build typedarrays</pre><p>Holy robot vomit. This failed at first because it turns on the find-bad-constructs clang plugin which doesn’t like some things in nan, so I removed those flags and a couple of others, and eventually it built a typedarrays.node module. I ran the test again and…</p><p>… it worked!! THANK FUCK.</p><h4>The Road to Victory</h4><p>Okay, so which of those ten million flags is actually responsible for fixing this problem? I tried building with just the Chromium clang++ and none of the fancy flags, and the error came back, so one of those flags must be important. I narrowed it down by deleting half the flags, rebuilding and rerunning until I zeroed in on the flag responsible:</p><pre>-D_LIBCPP_ABI_UNSTABLE</pre><p>Building with Chromium’s clang++ and this flag present is enough to produce a typedarrays.node that functions at least well enough to pass nan’s tests. Phew! So uh, how do we turn this into something we can commit to the roller branch?</p><p>Let’s figure out what’s responsible for setting this flag. <a href="https://source.chromium.org/search?q=_LIBCPP_ABI_UNSTABLE">Searching on s.c.o</a> leads us to <a href="https://source.chromium.org/chromium/chromium/src/+/master:build/config/c++/BUILD.gn;l=40;drc=342591b64f6b81d84ed1a0e4b1c56309e1a5ed41">this line in //build/config/c++/BUILD.gn</a>:</p><pre>if (libcxx_abi_unstable) {<br>  defines += [ “_LIBCPP_ABI_UNSTABLE” ]<br>}</pre><p>Well, interesting. Can we convince libcxx_abi_unstable to be false? That would mean Electron would be building <em>without</em> this flag, so maybe a node module also built without this flag would work?</p><p>libcxx_abi_unstable turns out to be a build argument, so we can try setting libcxx_abi_unstable = false in args.gn to build Electron without the _LIBCPP_ABI_UNSTABLE flag.</p><p>And <a href="https://github.com/electron/electron/pull/28009/commits/dd975328a0e96d84960079613238621a08dc9056">there you have it</a>:</p><pre>--- a/build/args/all.gn<br>+++ b/build/args/all.gn<br>@@ -19,4 +19,7 @@<br> dawn_enable_vulkan_validation_layers = false<br>+# This breaks native node modules<br>+libcxx_abi_unstable = false<br>+<br> is_cfi = false</pre><p>This fixes the problem (and exposes a different problem, but this essay is already about ten times too long, so I’m not going to go into that).</p><p>🎉</p><h4>What Now?</h4><p>Ultimately, it is asking for trouble to be building dynamically-linked native node modules that use C++ features across the dynamic link boundary with a different compiler. The C++ ABI is huge and complicated, and as we have discovered at great length today, varies between compilers, and even based on what #defines are used.</p><p>There are two ways to resolve this:</p><ol><li>Build C++ native modules using the same clang++ and libc++ as Electron itself, or</li><li>Don’t call C++ things across the dynamic link boundary.</li></ol><p>Honestly, I think (2) is the best way forward. <a href="https://nodejs.org/api/n-api.html">N-API</a> in Node.js provides exactly this: a stable C (not C++) ABI for interacting with V8 and Node without relying on the enormous, varied and moving target that is the C++ ABI. Modules built with N-API would not encounter this kind of problem, because they stick to the C ABI, which is much smaller, simpler and more stable. This is an ecosystem problem, though, and so it will take a long time to shift people away from C++-based systems like Nan and towards N-API.</p><p>(1) is also possible, though. I think we can provide some support in tools like electron-rebuild to download &amp; configure the Chromium compiler toolchain, instead of using the system one. It will significantly complicate electron-rebuild, but it will also probably eliminate most issues like this one.</p><h4>Extra Credit</h4><p>I’m still curious though. I want to know what the heck _LIBCPP_ABI_UNSTABLE does, and why it causes a mismatch in what register this is passed in. As mentioned, this essay is already too long so I’m going to leave some tantalizing hints and let you follow up on them if you desire. _LIBCPP_ABI_UNSTABLE is a proxy for a <a href="https://source.chromium.org/chromium/chromium/src/+/master:buildtools/third_party/libc++/trunk/include/__config;l=71;drc=33b3b1b9fe529f4c5b66b580ae7778503abeb7ba">whole bunch of other </a><a href="https://source.chromium.org/chromium/chromium/src/+/master:buildtools/third_party/libc++/trunk/include/__config;l=71;drc=33b3b1b9fe529f4c5b66b580ae7778503abeb7ba">#defines</a>. I tried building the native module without _LIBCPP_ABI_UNSTABLE but just each of those individual flags, and it turned out _LIBCPP_ABI_ENABLE_SHARED_PTR_TRIVIAL_ABI was enough to generate compatible code. That’s only referenced in <a href="https://source.chromium.org/chromium/chromium/src/+/master:buildtools/third_party/libc++/trunk/include/memory;l=2623;drc=1ac9f093d2eebc7de2708ad57640d3751a7d6f2b">one place</a> in libc++, where it causes __attribute__((trivial_abi)) to be added to shared_ptr and weak_ptr. What is trivial_abi? Well, it’s a <a href="https://quuxplusone.github.io/blog/2018/05/02/trivial-abi-101/">relatively new clang feature</a> that involves %rsi and %rdi. Hmmmm!</p><blockquote>Thanks to <a href="https://medium.com/u/154886f41afd">Keeley Hammond</a> for reviewing drafts of this article, and to Deepak Mohan for encouraging me to publish it as a blog post.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=973e51649063" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Electron’s ‘remote’ module considered harmful]]></title>
            <link>https://nornagon.medium.com/electrons-remote-module-considered-harmful-70d69500f31?source=rss-564335d4cff6------2</link>
            <guid isPermaLink="false">https://medium.com/p/70d69500f31</guid>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Jeremy Rose]]></dc:creator>
            <pubDate>Wed, 09 Oct 2019 17:48:14 GMT</pubDate>
            <atom:updated>2020-02-06T00:20:18.317Z</atom:updated>
            <content:encoded><![CDATA[<p>[EDIT]: I gave a talk on this at Covalence Conf 2020, which you can watch <a href="https://www.youtube.com/watch?v=0lb7AxaucZI&amp;list=PLhSaNgmcIodCuiyY5fHIH-dIm9FhrNj9X&amp;index=9&amp;t=0s">here</a> if you’d like!</p><p>Since the very earliest versions of Electron, the remote module has been the go-to tool for communicating between the main and renderer processes. The basic premise is this: from the renderer process, you ask remote for a handle to an object in the main process. Then you can use that handle just as if it were a normal JavaScript object in the renderer process—calling methods, awaiting promises, and registering event handlers. All the IPC calls between the renderer and main process are handled for you behind the scenes. Super convenient!</p><p>… until it isn’t. Almost every nontrivial Electron app that has used the remote module—Slack included—has ended up regretting their decision. Here’s why.</p><h4>#1 — It‘s slow.</h4><p>Electron, being based on Chromium, inherits Chromium’s multi-process model. There are one or several <em>renderer processes</em>, which are responsible for rendering HTML/CSS and running JS in the context of a page, and a single <em>main process</em>, which is responsible for coordinating all the renderers and executing certain operations on their behalf.</p><p>When a renderer process accesses a remote object, for example to read a property or call a function, the renderer process sends a message to the main process asking it to execute that operation, and then blocks waiting for the response. That means that while the renderer is waiting for the result, it can’t do anything but twiddle its thumbs. No parsing incoming network data, no rendering, no handling timers. It’s just waiting.</p><p>The average time to access a property on a remote object is about 0.1 ms on my machine. For comparison, accessing a property on an object that’s local to the renderer takes about 0.00001 ms [<a href="https://gist.github.com/ffd4d89e056a6b2162db6434e7628d94">replicate</a>]. Remote objects are <em>ten thousand times slower</em> than local objects. Let me put that in big text, because it’s important.</p><blockquote>Remote objects are <strong><em>ten thousand</em></strong><em> times slower</em> than local objects.</blockquote><p>Doing one or two of these 0.1 ms calls every now and then isn’t really a problem—0.1 ms is still pretty fast compared to the 16 ms you get if you want to stay inside a single frame. That’s a budget of 160 calls to remote objects per frame, assuming you’re not doing anything else.</p><p>… but it’s really easy to accidentally be making many more remote calls than you might expect. For example, consider the following code, which imagines a custom domain object present in the main process being manipulated from a renderer:</p><pre>// Main process<br>global.thing = {<br>  rectangle: {<br>    getBounds() { return { x: 0, y: 0, width: 100, height: 100 } }<br>    setBounds(bounds) { /* ... */ }<br>  }<br>}</pre><pre>// Renderer process<br>const thing = remote.getGlobal(&#39;thing&#39;)<br>const { x, y, width, height } = thing.rectangle.getBounds()<br>thing.rectangle.setBounds({ x, y, width, height: height + 100 })</pre><p>Executing this code in the renderer process involves <em>nine</em> round-trip IPC messages:</p><ol><li>the initial getGlobal() call, which returns a proxy object,</li><li>getting the rectangle property from thing, which returns another proxy object,</li><li>invoking getBounds() on the rectangle, which returns a third proxy object,</li><li>getting the x property of the bounds,</li><li>getting the y property of the bounds,</li><li>getting the width property of the bounds,</li><li>getting the height property of the bounds,</li><li>getting the rectangle property of thing again, which returns the same proxy object as we got in (2),</li><li>invoking setBounds with the new value.</li></ol><p>These three lines of code—not a single loop!—take nearly a whole millisecond to execute. A millisecond is a <a href="https://gist.github.com/jboner/2841832">long time</a>.</p><p>It’s certainly possible to optimize this code to reduce the number of IPC messages needed to accomplish this particular task (and in fact, some special internal Electron data structures like the bounds object returned from BrowserWindow.getBounds have <a href="https://github.com/electron/electron/blob/11cd0db86b5207160d05d831a7143bc479fce54f/lib/browser/remote/server.js#L87">magic properties</a> that make them a bit more efficient). But code like this can easily find its way into the dusty corners of your app and end up producing a “death by a thousand cuts” effect—code that seems unsuspicious on inspection is in fact much slower than it appears. This problem is compounded by the fact that those proxy objects can end up in all sorts of places if they’re returned from the function that created them, resulting in those slow remote IPCs being invoked from places very far from the initial call to remote.getGlobal().</p><h4>#2 — It creates the potential for confusing timing issues.</h4><p>We generally think of JavaScript as being single-threaded (the new <a href="https://nodejs.org/api/worker_threads.html">worker threads</a> module in Node aside). That is, while your code is running, no other things can be happening. This is still true in Electron, but when using the remote module, there is some subtle trickiness which can result in race conditions where you don’t expect them to exist. For example, consider this relatively common JavaScript pattern:</p><pre>obj.doThing()<br>obj.on(&#39;thing-is-done&#39;, () =&gt; {<br>  doNextThing()<br>})</pre><p>Where doThing kicks off some process that will eventually trigger the thing-is-done event. The http module in Node is a good example of a module that’s commonly used in this way. This is safe in normal JavaScript because there’s no way that the thing-is-done event can be triggered until your code is finished running.</p><p>If obj is a proxy to a remote object, however, then this code contains a race condition. Say doThing is an operation that can complete very quickly. When we call obj.doThing() on the proxy object in the renderer process, the remote module sends off an IPC to the main process under the hood. doThing() is then invoked in the main process, and it kicks off whatever thing it does, returning undefined as the return value to the renderer process. Now there are two threads of execution: the main process, which is doing thing, and the renderer process, which is about to send a message to the main process requesting that an event handler be added to obj. If thing completes especially quickly, it may happen that the thing-is-done event is triggered in the main process before the message arrives informing the main process that the renderer process is interested in that event.</p><figure><img alt="Sequence diagram representing previously-described race condition." src="https://cdn-images-1.medium.com/max/549/1*vrb7jdTWb-04JWCGQnk6kg.png" /><figcaption>Race condition between Main and Renderer process leading to unexpected behavior.</figcaption></figure><p>Both the main process and the renderer process here are single-threaded, normal JavaScript. But the interaction between them causes a race condition where the event is triggered <em>between</em> the call to doThing() and the call to on(&#39;thing-is-done&#39;).</p><p>If that seems confusing and subtle, that’s because it is. Electron’s own test suite contained many different versions of this kind of race condition until a recent drive to reduce test flakiness ferreted them out.</p><h4>#3 — Remote objects are subtly different to regular objects.</h4><p>When you ask for an object from the remote module, you get back a proxy object—one that stands in for the real object on the other side. The remote module does its best to make that object seem as if that object were really present in the current process, and it does a pretty good job, but there are a lot of weird edge cases that make remote objects different in ways that will work fine the first 99 times and fail in some sort of extremely difficult-to-debug way on the 100th. Here are a few examples:</p><ol><li>Prototype chains aren’t mirrored between processes. So, for instance, remote.getGlobal(&#39;foo&#39;).constructor.name === &quot;Proxy&quot;, instead of the real name of the constructor on the remote side. Anything remotely clever involving prototypes is guaranteed to explode if it touches a remote object.</li><li>NaN and Infinity aren’t correctly handled by the remote module. If a remote function returns NaN, the proxy in the renderer process will return undefined instead.</li><li>Return values from callbacks that run in the renderer process aren’t communicated back to the main process. When you pass a function as a callback to a remote method, then calling that callback from the main process will always return undefined, regardless of what the method in the renderer process returns. This is because the main process cannot block waiting for the renderer process to return a result.</li></ol><p>Chances are, you won’t encounter any of these subtle differences when you’re using the remote module for the first time. Or maybe even the hundredth time. But by the time you’ve come to realize that some corner-case of how the remote module works is causing the bug you’ve been trying to figure out for the list six hours, it’ll be too late to easily change the decision to use remote.</p><h4>#4 — It’s a security vulnerability waiting to happen.</h4><p>A lot of Electron apps never intentionally run untrusted code. However, it’s still a wise precaution to enable sandboxing in your app—it’s quite common to display arbitrary user-controlled images, for example, and it’s not unheard of for, say, PNG decoding to contain <a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-7317">bugs</a>.</p><p>But a sandboxed renderer is only as secure as the main process makes it. The renderer communicates with the main process to request that actions be performed on its behalf—for example, opening a new window or saving a file. When the main process receives such a request, it makes a determination about whether the renderer ought to be allowed to do that thing, and if not, it will ignore the request and unceremoniously shut down the renderer process for bad behavior. (Or possibly just deny the request, depending on how severe the infraction is.) There’s a clear security boundary here: no matter what the renderer process asks, the main process is in charge of deciding whether or not to allow it.</p><p>The remote module tears a great big Mack truck-sized hole in this security boundary. If a renderer process can send requests to the main process that say “please get this global variable and call this method”, then it’s possible for a compromised renderer process to formulate and send a request to ask the main process to do whatever it wants. Effectively, the remote module makes sandboxing almost useless. Electron provides an option to <a href="https://electronjs.org/docs/tutorial/security#15-disable-the-remote-module">disable the </a><a href="https://electronjs.org/docs/tutorial/security#15-disable-the-remote-module">remote module</a>, and if you’re using the sandbox in your app, you should definitely also be disabling remote.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqx9AAHAf1svIVlARB2aXA.jpeg" /><figcaption>The size of the security hole that ‘remote’ represents.</figcaption></figure><p>I haven’t even touched on a major class of issue: the inherent complexity of remote&#39;s implementation. Bridging JS objects between processes is no small task: consider, for example, that remote must propagate reference counts between processes to prevent objects from being GC’d in the other process. This task is challenging enough that it can’t be accomplished without <a href="https://github.com/electron/electron/blob/11cd0db86b5207160d05d831a7143bc479fce54f/lib/browser/remote/server.js">hefty bookkeeping</a> and <a href="https://github.com/electron/electron/blob/11cd0db86b5207160d05d831a7143bc479fce54f/shell/common/api/remote/object_life_monitor.cc">delicate</a> slabs of C++ (though it may become possible to do with pure JavaScript once <a href="https://v8.dev/features/weak-references">WeakRef</a>s are available). Even with all that machinery, remote doesn’t (and very likely never will) be able to correctly GC cyclic references. Few people in the world fully understand the implementation of remote, and fixing bugs that occur in it is Very Hard™.</p><p>The remote module is slow, race-condition-prone, produces objects that are subtly different to regular JS objects, and is a huge security liability. Don’t use it in your app.</p><h3>OK then, what should I do instead?</h3><p>Ideally, you should minimize the usage of IPC in your app—it’s better to keep as much work as you can in the renderer process. If you need to communicate between multiple windows in the same origin, you can use window.open() and script them synchronously, just the same as you can on the Web. For communicating between windows in different origins, there’s postMessage.</p><p>But when you really just need to call a function in the main process, I’d recommend you use the new <a href="https://github.com/electron/electron/blob/v7.0.0-beta.4/docs/api/ipc-renderer.md#ipcrendererinvokechannel-args">ipcRenderer.invoke()</a> method that’s available as of Electron 7. It works similarly to the venerable ipcRenderer.sendSync(), but it’s asynchronous—meaning that it won’t block other things from happening in the renderer. Here’s an example of converting from a remote-based system for loading a file to one based on ipcRenderer.invoke():</p><p><strong>Before, with remote:</strong></p><pre>// Main<br>global.api = {<br>  loadFile(path, cb) {<br>    if (!pathIsOK(path)) return cb(&quot;forbidden&quot;, null)<br>    fs.readFile(path, cb)<br>  }<br>}</pre><pre>// Renderer<br>const api = remote.getGlobal(&#39;api&#39;)<br>api.loadFile(&#39;/path/to/file&#39;, (err, data) =&gt; {<br>  // ... do something with data ...<br>})</pre><p><strong>After, with invoke:</strong></p><pre>// Main<br>ipcMain.handle(&#39;read-file&#39;, async (event, path) =&gt; {<br>  if (!pathIsOK(path)) throw new Error(&#39;forbidden&#39;)<br>  const buf = await fs.promises.readFile(path)<br>  return buf<br>})</pre><pre>// Renderer<br>const data = await ipcRenderer.invoke(&#39;read-file&#39;, &#39;/path/to/file&#39;)<br>// ... do something with data ...</pre><p><strong>Or, using ipcRenderer.send (for Electron 6 and older):</strong></p><p>Note that this approach can only handle a single outstanding request at a time, unless you do some bookkeeping to track which response belongs to which request. (invoke() handle matching responses to requests automatically.)</p><pre>// Main<br>ipcMain.on(&#39;read-file&#39;, async (event, path) =&gt; {<br>  if (!pathIsOK(path))<br>    return event.sender.send(&#39;read-file-complete&#39;, &#39;forbidden&#39;)<br>  const buf = await fs.promises.readFile(path)<br>  event.sender.send(&#39;read-file-complete&#39;, null, buf)<br>})</pre><pre>// Renderer<br>ipcRenderer.send(&#39;read-file&#39;, &#39;/path/to/file&#39;)<br>ipcRenderer.on(&#39;read-file-complete&#39;, (event, err, data) =&gt; {<br>  // ... do something with data ...<br>})<br>// Note that only one request can be made at a time, or else<br>// the responses might get confused.</pre><p>This is a small example, and what you need to do with IPC may be more complicated and not translate so neatly to invoke. But writing your IPC handlers this way will leave you with a clearer, easier-to-debug, more robust, and more secure app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70d69500f31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chrome Tracing for Fun and Profit]]></title>
            <link>https://medium.com/several-people-are-coding/chrome-tracing-for-fun-and-profit-a15ec83aa908?source=rss-564335d4cff6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15ec83aa908</guid>
            <category><![CDATA[chrome]]></category>
            <category><![CDATA[electron]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Jeremy Rose]]></dc:creator>
            <pubDate>Wed, 12 Jun 2019 19:23:37 GMT</pubDate>
            <atom:updated>2019-06-12T19:23:37.046Z</atom:updated>
            <content:encoded><![CDATA[<p>You might have used Chrome’s Developer Tools to profile your JavaScript to improve performance or find bottlenecks. DevTools is fantastic, but there’s a lot of potentially useful information that the performance panel doesn’t capture. Enter Chrome Tracing: a tool that’s built into Chrome (and Electron) that can collect a huge variety of detailed performance data. At Slack, we use Chrome Tracing to diagnose complex performance issues, and hopefully after reading this, you’ll be able to as well.</p><p>Chrome Tracing consists of two important parts: first, a system for collecting performance-relevant information from the browser itself; and second, a tool for inspecting and analyzing that information. You can try it out for yourself right now by opening <a href="/service/chrome://tracing">chrome://tracing</a> in Chrome. Go ahead and click ‘Record’, select a category (or leave the default ‘Web Developer’ option selected), do something in Chrome, then come back to the tracing tab and click ‘Stop’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0nzVLLW3IujyAkrB5vr-w.png" /><figcaption>chrome://tracing can record a bewildering array of different kinds of data.</figcaption></figure><p>Once your recording is complete and the data is loaded, you’ll be greeted by the delightfully candy-colored analysis interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSZzzPt3RgzJREQ3O7PuYg.png" /><figcaption>Doesn’t it look delicious?</figcaption></figure><p>If you click the ‘Save’ button in the top-left, you’ll get a file that you can open up in your favorite text editor — since it’s just JSON. Chrome Tracing can fill this file with all sorts of useful information, from sampled stack traces of JavaScript code to network logging data and even screenshots of your page as it’s being (re-)rendered. But by far the most common kind of data in here is produced by specifically annotated TRACE_EVENT code in Chromium. These aren’t exactly stack traces — they’re performance-relevant events that Chromium developers have identified and annotated by hand. In fact, if you click on the magnifying glass to the right of the event title in the info panel, you’ll be taken to the point in Chromium’s source code where that annotation is defined. For example, <a href="https://cs.chromium.org/chromium/src/cc/trees/layer_tree_host.cc?l=784&amp;rcl=b7fd2f2e53b73242ca32ed77c52a2eacfe8afb3f">here’s the source</a> for the LayerTreeHost::DoUpdateLayers annotation.</p><p>When you take into account all the factors that can have an effect on your app’s performance — OS version, CPU, GPU, memory, disk speed, network conditions, other currently running software, and so on— it turns out every desktop environment is as unique as a snowflake. It’s often impossible to exactly replicate a user’s environment to reproduce an issue they might be seeing. When Slack receives a report of a performance issue in its desktop app, we ask the user to trigger a special command that collects a performance trace through the Chrome Tracing system (using the <a href="https://electronjs.org/docs/api/content-tracing">contentTracing API in Electron</a>). With the user’s permission, the trace is securely uploaded to Slack’s servers, where engineers can inspect the trace and hopefully track down the underlying problem. When we’ve completed our review, we delete the trace data.</p><blockquote>You can only change what you can perceive. Without tools to observe the world with which we interact, we are powerless to change it.</blockquote><p>DevTools should always be your first port of call for understanding and debugging a performance issue — but sometimes it doesn’t provide the answers you were looking for. Chrome Tracing lets you record a much wider array of performance-relevant data about the browser, so it can be helpful when tracking down a performance issue that isn’t strictly JavaScript-related; for instance, GPU issues or cases where one process is waiting on another process. As an example, in Electron apps, a common source of performance issues is over-eager communication (especially synchronous IPC) between the main and renderer processes.</p><p>It’s possible to collect trace data programmatically in Electron via the <a href="https://electronjs.org/docs/api/content-tracing">contentTracing API</a>. The contentTracing API lets you specify what categories of tracing data you want recorded — the categories that you can pass to the API are the same ones that are listed in the chrome://tracing UI (the ones in the ‘disabled by default’ column are prefixed with disabled-by-default-, so e.g. if you want to record v8 sample data, you’ll need to specify disabled-by-default-v8.cpu_profiler). If you don’t specify what categories to include, Electron will record everything that’s not disabled by default, which can be a useful way to find out what categories of data you care about — you can click on an event in the tracing UI to see what category it belongs to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*YsAUin3Nc_alTPtrq8poNA.png" /><figcaption>The ‘ipc’ category is a useful one for debugging performance issues that cross between the browser and renderer processes.</figcaption></figure><p>Here’s an example of setting up a trace that records all the default tracing categories, and additionally records V8 sampling data in the renderer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c57df633a8b941c94d85a183f1d01108/href">https://medium.com/media/c57df633a8b941c94d85a183f1d01108/href</a></iframe><p>To demonstrate what this looks like, I’ve built a simple test app that simulates something that might be hard to debug with the standard DevTools trace. In the test app, the renderer process delegates some CPU-intensive work to the browser process. In a real app, there are lots of reasons you might do something similar: for instance, spell-checking can be quite memory intensive, so you might want to load up the spell-checking dictionary just once in the main process, and have all renderer processes delegate the work of actually checking spelling to the main process. In this test app, though, we just busy-wait for a second.</p><p>I built this example with <a href="https://github.com/electron/fiddle">Electron Fiddle</a>, which is a great way to test out quick examples. Go ahead and install Fiddle, and when you’re done, load up the <a href="https://gist.github.com/abc2d0136bb17ea213f9a756e0ccbd42">example work-doing app</a> by pasting the Gist URL in the Load Fiddle box.</p><p>Try it yourself: first, open up DevTools with Cmd+Opt+I (or Ctrl+Shift+I). Switch to the ‘performance’ tab, start a recording in DevTools, and press the ‘do work’ button. Stop the recording and inspect the resulting trace. What’s using up the CPU?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HU6JzCLrdmenTyXG56JNRA.png" /><figcaption>The Devtools profile doesn’t tell the whole story.</figcaption></figure><p>It’s hard to say, because DevTools just shows a big gap. You could maybe try to guess what’s happening here, but it’s much easier to use Chrome Tracing.</p><p>Try tracing this again, but this time, use the ‘start recording’ button in the example app instead of DevTools. This will trigger Electron’s contentTracing API. Once the app is recording, click the ‘do work’ button, and when it’s done, click ‘stop recording’. The folder containing the resulting trace.json file will open (which is accomplished by Electron’s shell.openItem API). Open chrome://tracing in a Chrome tab, and drag that trace.json file into the chrome://tracing window. You’ll see something that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSHP5KPU4czXTqTOCg3lrg.png" /><figcaption>The trace that Electron recorded includes events from the main process as well as the renderer process.</figcaption></figure><p>The AtomFrameHostMsg_Message event tells us that the main process is processing an IPC message, in this case for about 1,000 ms. Unfortunately, Electron doesn’t currently support sampling V8 stack traces in the main process, though there is <a href="https://github.com/electron/electron/issues/18372">an issue tracking the feature</a>. Often, though, just the information that the main process is handling an IPC event is enough to figure out what’s going on.</p><p>The performance panel in DevTools uses the same infrastructure as Chrome Tracing under the hood to collect the information it displays. The file formats are the same — you can save a profile from DevTools and open it in chrome://tracing and vice-versa. When you record a performance profile in DevTools, it signals the Chrome Tracing infrastructure to begin recording with a <a href="https://cs.chromium.org/chromium/src/third_party/blink/renderer/devtools/front_end/timeline/TimelineController.js?l=46&amp;rcl=977fa8c33a878dd5e9f33ef5aa036aff86932e24">predefined set of categories</a>.</p><p>The Chrome Tracing API is fantastically useful for tracking down performance issues in Slack’s desktop application, but not all of Slack’s users use our Electron app. This raises an obvious question: how can we go about debugging performance issues on users’ machines in the browser?</p><p>There’s an exciting new API that’s being worked on right now by the WICG which would allow JavaScript to <em>self-profile</em>. You can read up on the current proposal <a href="https://github.com/WICG/js-self-profiling">here</a>, but the gist of it is that you would be able to start a ‘profiler’, specifying a sampling frequency and other options, and when it’s done you’ll receive a blob of performance information that you can relay back to the server for later analysis.</p><p>Chrome Tracing is a powerful tool for diagnosing and understanding complex performance issues in web apps and Electron apps. I’ve only scratched the surface of what it can do here — it can record screenshots and DOM trees, for instance! — and there’s a lot more info on the <a href="https://www.chromium.org/developers/how-tos/trace-event-profiling-tool">Chromium developer site</a> if you want to get deeper into the capabilities of the system. But you have everything you need to get started now.</p><p>If working on Electron, building desktop applications with a mix of C++ and JavaScript, and optimizing web apps are things you find interesting, you might enjoy <a href="https://slack.com/careers">working with us at Slack</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15ec83aa908" width="1" height="1" alt=""><hr><p><a href="https://medium.com/several-people-are-coding/chrome-tracing-for-fun-and-profit-a15ec83aa908">Chrome Tracing for Fun and Profit</a> was originally published in <a href="https://medium.com/several-people-are-coding">Several People Are Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are more people eating plant-based diets?]]></title>
            <link>https://nornagon.medium.com/are-more-people-eating-plant-based-diets-9d2d0dfa43f?source=rss-564335d4cff6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d2d0dfa43f</guid>
            <category><![CDATA[vegan]]></category>
            <category><![CDATA[climate-change]]></category>
            <category><![CDATA[vegetarian]]></category>
            <category><![CDATA[food]]></category>
            <category><![CDATA[diet]]></category>
            <dc:creator><![CDATA[Jeremy Rose]]></dc:creator>
            <pubDate>Mon, 17 Sep 2018 05:20:29 GMT</pubDate>
            <atom:updated>2018-09-17T05:20:29.663Z</atom:updated>
            <content:encoded><![CDATA[<p>Earlier this year, I read <a href="https://www.drawdown.org/"><em>Drawdown</em></a>, a survey of tools and techniques for addressing climate change ranked by impact. It’s an exceptionally well-researched book and you should read it, but what I want to talk about today is the part of the book that had the most impact on me personally.</p><p>The first thing that usually comes to mind when you think about solutions to climate change is renewable energy. But nearly half of the top 20 solutions that <em>Drawdown</em> identifies are related to food, and taken together, changes to the way we produce and eat food account for an impact more than 30% larger than changes to the way we generate electricity.</p><p>In particular, <em>Drawdown </em>estimates that the impact of <a href="https://www.drawdown.org/solutions/food/plant-rich-diet">shifting to a diet rich in plants</a> is the 4th-highest-impact of all the 100 solutions they examined, and projects that reducing meat consumption could result in a total reduction in CO₂-equivalent emissions of over 65,000,000,000 tons over the years from 2020–2050. To put that in perspective, that’s comparable to what <em>Drawdown</em> estimates will be the impact of shifting to solar power. It’s six times the estimated impact of shifting to electric vehicles. And it would account for about as much less carbon in the atmosphere as does the ocean, which sequesters about 2.5 Gt/y [<a href="https://www.earth-syst-sci-data-discuss.net/5/1107/2012/essdd-5-1107-2012.pdf">1</a>]. <em>The ocean</em>. All of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2cdTdFEUGbvGdg-8vb6Kg.jpeg" /></figure><p>Since I read <em>Drawdown</em>, I’ve been paying much closer attention to the amount of animal products that I eat. I don’t eat zero meat, but I’ve substantially reduced the amount of meat I eat, now at about one meal per week. And I’m wondering if other people are doing the same.</p><p>I know that the Baader-Meinhof effect will mean I’m more aware of stores and restaurants offering plant-based options, so it will seem to me subjectively that there’s a growing movement of plant-based food even if there isn’t. Data on vegetarianism and veganism is surprisingly difficult to pin down—studies report anything from 4% to 13% of Americans are vegan or vegetarian[<a href="https://www.npr.org/sections/13.7/2017/06/28/532880755/is-a-no-meat-world-really-better">2</a>]—and it’s even harder to find data on people like me who aren’t vegetarian <em>per se</em>, but are choosing to eat less meat. Things get even trickier when you try to correlate those numbers between countries.</p><p>Google Trends is far from an authoritative data source, but perhaps it can be a proxy as part of a broader investigation into whether plant-rich diets are on the rise. I looked at trends for searches for veganism, reasoning that I usually search for those things when I’m eating out in a place I’m unfamiliar with, and that it probably correlates with the number of people who are doing the same sort of thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpO2zhDTiPkQCyjytXHE_w.png" /><figcaption>Searches in the topic “Veganism” in the U.S. over the last 5 years. <a href="https://trends.google.com/trends/explore?date=today%205-y&amp;geo=US&amp;q=%2Fm%2F07_hy">Google Trends</a>.</figcaption></figure><p>It’s a little difficult to parse this chart, but it looks roughly like veganism is about twice as popular in the U.S. now as it was in 2013. And the trend holds up for other geographies than the U.S., too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O0cUmkfANJr2Ou-n0Yy9Iw.png" /><figcaption>Google Trends for Veganism, <a href="https://trends.google.com/trends/explore?date=today%205-y&amp;geo=JP&amp;q=%2Fm%2F07_hy">Japan</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8Sdns_K2EMxv0TqJllfgw.png" /><figcaption>Google Trends for Veganism, <a href="https://trends.google.com/trends/explore?date=today%205-y&amp;geo=AU&amp;q=%2Fm%2F07_hy">Australia</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lxSYFLhmC2tRcR2M9a_Tqw.png" /><figcaption>Google Trends for Veganism, <a href="https://trends.google.com/trends/explore?date=today%205-y&amp;q=%2Fm%2F07_hy">Worldwide</a></figcaption></figure><p>Google Trends only reports data about people who use Google, which notably excludes China (<a href="https://theintercept.com/2018/08/01/google-china-search-engine-censorship/">for now</a>) and, largely, India. That’s more than 2 billion people in the world missing from this analysis. China has a rapidly growing middle class who often associate meat with wealth and status. India also has a rapidly growing middle class, but has a large number of adherents to Dharmic religions such as Jainism, Buddhism and Hinduism which prohibit the consumption of meat and as such, India is about 30% vegetarian already.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/0*rZsAq03TXtdudfUT.png" /><figcaption>Vegetarian and non-vegetarian marks, required labelling for packaged foods in India.</figcaption></figure><p>These graphs would suggest that plant-based diets are on the rise in Western countries, and rapidly so—2x in 5 years is an incredible rate of growth.</p><p>Let’s consult another source of data to see if these trends correlate! I grabbed the OECD’s data on <a href="https://data.oecd.org/agroutput/meat-consumption.htm">meat consumption</a>, which includes kilograms-per-capita data for 43 countries going back to 1990. The built-in graphing function on the OECD website wouldn’t show me summed meat consumption across types of meat (poultry, beef, etc.) so I downloaded the raw data and plotted it myself. The data for beef didn’t go back before 2000 for some countries, so I’ve plotted just the years 2000–2017.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R7K-WlHZS9ai0wBpDqNdhw.png" /><figcaption><a href="https://data.oecd.org/agroutput/meat-consumption.htm">OECD</a> (2018), Meat consumption (indicator). doi: 10.1787/fa290fd0-en (Accessed on 16 September 2018).</figcaption></figure><p>This chart tells another story. While it looks like people in Europe and the U.S. are eating about the same amount of meat as they always have, people living in Brazil, Russia, India, China and South Africa (BRICS) are eating nearly 30% more meat than they did 20 years ago (though interestingly, meat consumption in India remains low). Worldwide, per-capita meat consumption is up 15% since 2000.</p><p>So it seems that while enthusiasm for plant-based diets is growing in the West (who are by far the hungriest for meat), it isn’t yet an entrant into the cultures of the Global South (which contains vastly more people). Even though the average person in China consumes half as much meat as the average person in the U.S., there are four times as many people living in China.</p><p>I don’t know what it will look like for plant-rich diets to take off in China, or Brazil, but it probably won’t look like veganism in the West.</p><p>Climate change isn’t a problem that any one of us can have a significant impact on in our personal lives. The scale of the problem is such that effective actions are those at the scale of thousands to millions of people. But eating a plant-rich diet is by far the most impactful change you can make yourself, way way more than recycling or changing your lightbulbs. And you’ll be living your values every time you eat a meal. Assuming you value the continued existence of human life on Earth, that is.</p><p>You don’t have to eat 100% vegan—as my wife Cole says, if everyone ate vegan half the time, it’d be like half of us were vegan!—but you do have to start now. We’re running out of time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*psn361a9C7ztm5TQ.jpg" /><figcaption>Of course, aside from contributing substantially to the possibility of future human life on Earth, eating a plant-based diet is also <a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3662288/">healthier</a> and will make you more attractive. Guaranteed.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d2d0dfa43f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Math for Game Developers: Parameterised Easing]]></title>
            <link>https://nornagon.medium.com/math-for-game-developers-parameterised-easing-9336a50c816d?source=rss-564335d4cff6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9336a50c816d</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Jeremy Rose]]></dc:creator>
            <pubDate>Mon, 12 Mar 2018 21:52:48 GMT</pubDate>
            <atom:updated>2018-03-12T21:52:48.120Z</atom:updated>
            <content:encoded><![CDATA[<h4>Or, How The Crap Do I Make That Curve?!</h4><p>Sometimes I get an idea in my head that requires a particular kind of mathematical function: say, a cosine, or a logarithm, or a polynomial. Since I don’t have much of a background in mathematics, it’s more likely that I know the <em>shape</em> of function I want, but not how to write it down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLY2HI7sxZS6Z4l-lakQqQ.jpeg" /><figcaption>How do I get the computer to make this curve?</figcaption></figure><p>If I’m lucky, some dusty corner of my mind will shake off the cobwebs that have been accumulating there since first year algebra and offer itself in service, saying something useful like “Uh… maybe try tanh?”</p><p>But today I was unlucky. I wanted something kind of like a square wave, but not as harsh. A sine wave was too smooth, and a square wave was not smooth enough. Surely there must be some mathematical incantation I can utter that will solve this problem! I had the idea that I wanted to start with a sine wave and “squash” it, so the bits between 0 and 1 were a bit closer to 1, and the bits between 0 and –1 were closer to –1.</p><p>My mathematical dust-gatherers had good intentions, saying things like “doesn’t squaring a number in [0,1] make it smaller, but in [1,∞) make it larger? Is that helpful?” and “doesn’t a sigmoid function look kind of like an S? Your curve has S-looking things in it, maybe a sigmoid would be useful.” But it turned out none of them had what I was looking for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*hR2-zZx8uYrRAjst59ZMxA.png" /><figcaption>Look at all these functions I don’t want.</figcaption></figure><p>OK, so my math-rememberers weren’t working. Time to go to first principles. If I had some function <em>squash</em>(<em>x</em>), which pushed values in [-1,1] away from 0 and towards the edges of the range, what would its properties be? First, I know that <em>squash</em>(0)<em> = </em>0<em>.</em> Also, <em>squash</em>(1)<em> = </em>1 and <em>squash</em>(–1)<em> = </em>–1. And then some values in between: <em>squash</em>(0.5) should be a bit closer to 1, say 0.6. And <em>squash</em>(–0.5) should be a bit closer to –1, by the same amount as 0.5 got pushed towards 1. I plotted out the points just like in 9th-grade.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*1KR_Rl0G1clXh9CDcNazqg.jpeg" /><figcaption>Is that right, Mr. Scovell?</figcaption></figure><p>As I was looking at the picture I’d drawn, a lightbulb went off in my head: that looks kind of like Photoshop’s “curves” UI! A quick search and a helpful StackOverflow answer suggested Bezier splines, and from there I found <a href="http://cubic-bezier.com/">cubic-bezier.com</a> which let me draw some curves like I wanted, and also some curves that I didn’t want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*Rgm9ype3DTrAtCnfVsr7-g.png" /><figcaption>Not the S curve I was looking for.</figcaption></figure><p>Some <a href="https://github.com/Michaelangel007/easing">other pages</a> had “ease-in-out” functions for quadratic, cubic, quartic and so on, but I wanted to be able to tune the sharpness of the curve all the way from a straight line (no squashing at all) to a square wave (squash everything &lt; 0 to –1, and everything ≥ 0 to +1), smoothly. I wanted a parameter I could tune to say how sharp the curve was. I wanted cubic-and-a-half, or quartic-minus-a-bit.</p><p>I didn’t find the equation written down anywhere, so I figured it out. After a few dead ends, here’s what I came up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*fIjOUr97p9rvWlPPDqJ34A.png" /><figcaption>This function probably has some clever name given to it in 1928 by a Swiss guy, but I don’t know it.</figcaption></figure><p><em>k</em> here is the “squashedness” of the curve, where 1 is a straight line, and ∞ is a step function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*I2RbDZNojEOYc8mw7qiMyg.png" /><figcaption>Squashedness levels, from 1 to 5.</figcaption></figure><p>Feed the cosine into it, <em>et voila</em>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*KIVb5t4awESD0wgYPm_s9Q.png" /><figcaption>squash(3, cos(x)). No thanks to you, math-dust-gatherers.</figcaption></figure><p>I can imagine this sort of function being useful for all kinds of things other than squashing cosines. You could run it over a generated terrain to make the cliffs harsher, and valleys wider, or use it in an animation to control “snappiness”. I’m going to use it to control light levels in a day-night cycle. If you use it, for making a game or otherwise, let me know on Twitter! I’m <a href="https://twitter.com/nornagon">@nornagon</a> there, you should follow me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9336a50c816d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to finish something]]></title>
            <link>https://nornagon.medium.com/how-to-finish-something-78a74ec1f4f0?source=rss-564335d4cff6------2</link>
            <guid isPermaLink="false">https://medium.com/p/78a74ec1f4f0</guid>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Jeremy Rose]]></dc:creator>
            <pubDate>Thu, 22 Feb 2018 06:12:27 GMT</pubDate>
            <atom:updated>2018-02-22T06:12:27.237Z</atom:updated>
            <content:encoded><![CDATA[<p>stop procrastinating<br>procrastinate more<br> — — — (to avoid something more important)<br>focus<br>chip away at it<br>decide to do less<br>accept it<br> —— (as it is)<br>publish it<br>smile at it<br>write about it<br>be proud of it</p><p>forget it</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78a74ec1f4f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synaptograph gets checkboxes]]></title>
            <link>https://nornagon.medium.com/synaptograph-gets-checkboxes-f6ef6c84c957?source=rss-564335d4cff6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6ef6c84c957</guid>
            <category><![CDATA[mindmap]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[Jeremy Rose]]></dc:creator>
            <pubDate>Sat, 23 Sep 2017 22:36:29 GMT</pubDate>
            <atom:updated>2017-09-23T22:36:29.500Z</atom:updated>
            <content:encoded><![CDATA[<h4>(And some other stuff.)</h4><p>A year and a half ago I started working on a mind mapping tool called <a href="https://medium.com/@nornagon/mind-mapping-244d301fbadc">Synaptograph</a>, heavily inspired by the wonderful <a href="https://www.exobrain.co/">Exobrain</a>, but quickly <a href="https://medium.com/@nornagon/the-doldrums-29a962e6ce26">ran out of steam</a>. This week, with joy, I picked it up again.</p><p>I keep notes of various kinds in about five different places right now. I write things on paper, I jot things down on my phone in Notes.app, I save articles I want to keep in Pinboard, I save papers and images in Dropbox, and I have more than a few NOTES.md files lying around in my code repositories. And lately, I’ve been using Synaptograph to sketch out and explore new ideas. So that makes <em>six</em> places that I might have put something I wanted to remember.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9-Xble3aHoAuROEpanJpw.png" /><figcaption>Exploring an idea for a game in Synaptograph</figcaption></figure><p>Each of those six tools has its own advantages and disadvantages, but none really matches well with how my brain seems to want to arrange information. Paper gets lost, or isn’t at hand when I need it. Pinboard is an abyss, as are Dropbox folders full of papers. I forget that NOTES.md exists. Notes.app is very linear.</p><p>I want Synaptograph to be a tool that meshes really well with the way I think, that lets me feel like I transferred part of my mind into an external medium. I want to be able to capture all the different things I’m thinking about when I’m working on something, whether it’s something I need to remember to do, or an article I think might be relevant later and my notes on why, or a group of half-formed thoughts about a possible future direction, or a few paragraphs of explanation of how something could work.</p><p>It’s not quite there yet, but this week I added two small features that move Synaptograph a little way in that direction.</p><p>The first is checkboxes. I use these on paper all the time, and having them in Synaptograph means that for simple things that don’t need much in the way of sequencing, I can just put them directly into the mind map. To add a checkbox to a node, just write “[ ]” at the beginning of the text. It will automatically turn into a checkbox as soon as you press enter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*dx1GDykE9Hp1RBMK10yhdw.gif" /></figure><p>I’ve been using these a lot for tracking what I want to get done in Synaptograph itself, and it’s been working great for that purpose. One thing I really like is having to-do items in a free-flowing two-dimensional layout, rather than a list. For personal projects I work on, there’s very rarely a total ordering on tasks that need doing. A list forces you to choose what comes before what else. When you lay things out in two dimensions, it’s much harder to put in fake ordering when there isn’t any.</p><p>The second feature I added this week is links. Synaptograph now recognizes URLs, and will properly turn them into links, shortening them if necessary to keep the node text from stomping all over the map. Clicking on the icon next to the link takes you to the linked page, and clicking on the text lets you edit the URL (just like any other node).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*yjedN1g5961vP_RUMj275Q.gif" /></figure><p>There’s a bunch more stuff I want to add, but these two small features are a good start towards making Synaptograph work more like my brain does.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6ef6c84c957" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TIL: L5 society]]></title>
            <link>https://nornagon.medium.com/til-l5-society-3781525a14e3?source=rss-564335d4cff6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3781525a14e3</guid>
            <category><![CDATA[space-exploration]]></category>
            <category><![CDATA[space]]></category>
            <category><![CDATA[nasa]]></category>
            <dc:creator><![CDATA[Jeremy Rose]]></dc:creator>
            <pubDate>Tue, 12 Sep 2017 17:43:10 GMT</pubDate>
            <atom:updated>2017-09-12T17:43:10.865Z</atom:updated>
            <content:encoded><![CDATA[<p>The <a href="http://www.nss.org/settlement/L5news/index.html">L5 society</a> was a group in the 70&#39;s–80&#39;s that advocated for the colonization of space, in particular the Earth-Luna L5 Lagrange point. They were heavily inspired by Gerard O’Neill’s book <em>The High Frontier</em>, which described how technology already available at that time could be employed to build an orbital colony vessel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*3hTcLhPvWsQPDBoLzrEJtg.png" /><figcaption>The indisputably rad logo of the L5 society</figcaption></figure><p>O’Neill proposed a cylindrical colony design, with a pair of 8km×32km cylinders rotating in opposite directions at about 3rpm to approximate Earth’s gravity. The counter-rotation would cancel out the gyroscopic force, helping to keep the station properly aligned with the sun.</p><p>(Though 3rpm sounds like it would be a little sickening! Look at that painting below, and imagine the sun zipping around all three of those window sections every 20 seconds. That’s about 3 seconds from left to right of each section. I guess you’d get used to it, but I bet new arrivals would spend a few days staring intently at their feet.)</p><p>Getting something that big out of Earth’s atmosphere and gravity well would be next to impossible, so O’Neill proposed building the stations using materials that were already conveniently placed—on the Moon or from an asteroid. From there, you’d ferry the stuff over to Earth-Luna L5 and construct the station in-situ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6l-b7ychNE7VR5aNoM9Dg.jpeg" /><figcaption>A cylindrical rotating space colony, proposed by Gerard O’Neill in 1976. Painting by Rick Guidice, courtesy NASA.</figcaption></figure><p>The L5 society counts as one of its great victories the non-signing of the <a href="http://www.unoosa.org/oosa/en/ourwork/spacelaw/treaties/intromoon-agreement.html">Moon Treaty</a> by the US. I’m not sure that’s entirely a good thing—I think humans should work together to enter space more-or-less unified, not scrabbling to seek profit and sell the Moon to the highest bidder. It turns out to have been more or less a moot point thus far, since launch costs and political iciness re: space exploration in the 80&#39;s up to the present have prevented any significant excursions, but with <a href="http://www.spacex.com/falcon-heavy">Falcon Heavy</a> set to fly in November and <a href="https://www.blueorigin.com/new-glenn">New Glenn</a> hot on its heels we might find we have renewed interest in regulating who can do what in space. A free-for-all doesn’t seem like it would end well.</p><p>The L5 society is no longer, but in its place is the <a href="http://www.nss.org/">National Space Society</a>, advocating for the dream of living and working in space from its adorably 90&#39;s web page.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3781525a14e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TIL: Triangle grids]]></title>
            <link>https://nornagon.medium.com/til-triangle-grids-133ed47cc807?source=rss-564335d4cff6------2</link>
            <guid isPermaLink="false">https://medium.com/p/133ed47cc807</guid>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[today-i-learned]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jeremy Rose]]></dc:creator>
            <pubDate>Mon, 14 Aug 2017 16:57:16 GMT</pubDate>
            <atom:updated>2017-08-14T16:57:16.170Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been jamming on a little game prototype with a friend that uses a triangle grid. Figuring out how to set up the coordinate system has been a bit of a nightmare; triangles are super weird! We’ve currently got it set up so that each row of triangles shares a <em>y</em> coordinate, and then the <em>x</em> coordinates are a bit wonky depending on which <em>y</em> you’re at. Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fr5Iljp_fBeT_ZF7QY49fg.jpeg" /><figcaption>I’m calling this system “square-packed” coordinates.</figcaption></figure><p>This is handy for storing the map in memory, but not very nice at all for answering questions like “how far away are these two triangles from one another” or “what triangle did the player click” or even just “where do I draw this triangle”. In this coordinate system, (0,0) and (2,1) have two other triangles between them, but (1,0) and (3,1) share a common point. So figuring out what’s adjacent to a triangle depends on the particular place that triangle is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*4XwnnMZt42p-qAmjzSvJNQ.png" /><figcaption>Shearing squares into rhombuses, then subdividing them. From Amit Patel’s excellent <a href="http://www-cs-students.stanford.edu/~amitp/game-programming/grids/">Thoughts on Grids</a>.</figcaption></figure><p>Amit Patel, of course, has <a href="http://www-cs-students.stanford.edu/~amitp/game-programming/grids/">thought about</a> <a href="http://simblob.blogspot.com/2007/06/distances-on-triangular-grid.html">this problem</a>. He suggests a coordinate system like a skewed square grid, where you divide each square in two across its diagonal. In this system, there are three coordinates: <em>x</em>, <em>y</em>, and <em>R</em>. The <em>x</em> and <em>y</em> coordinates tell you which rhombus you’re in, and the <em>R</em> coordinate tells you whether you’re in the lower-left triangle half of the rhombus or the upper-right one, so it’s just a binary 0 or 1. (Amit labels the two options <em>L</em> and <em>R</em>, but that seems a little confusing because the name of the 3rd coordinate is also <em>R</em>.)</p><p>The sheared-square coordinate system is a lot easier to work with for figuring out where the player clicked, because it’s just a little <a href="https://en.wikipedia.org/wiki/Affine_transformation">matrix math</a> to un-shear the world and then you can use regular square grid math to figure out the <em>x</em> and <em>y</em>, and then you just need to figure out whether you’re in the bottom-left or top-right half of the square (i.e. unsheared rhombus), and that gets you your <em>R</em> value. The (<em>x</em>,<em> y</em>,<em> R</em>) system isn’t so great for computing distances, though, so Amit wrote <a href="http://simblob.blogspot.com/2007/06/distances-on-triangular-grid.html">another article about that</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H93oUmCSUo7LebgihzrRgA.jpeg" /><figcaption>My extremely high-quality illustration of a triangle coordinate system that’s useful for calculating distances.</figcaption></figure><p>The idea with this system is that the distance between any two triangles is the number of lines you’d need to cross when walking from one to the other. It’s a little like the Manhattan distance on square grids.</p><p>The (<em>a</em>, <em>b</em>, <em>c</em>) system I drew above is a little redundant, though: for any (<em>a</em>, <em>b</em>) pair, there’s only two possible values for <em>c</em>. For example, if <em>a</em> = 0 and <em>b</em> = 0, then <em>c</em> must be either 0 or 1. This is pretty much the same thing as the <em>R</em> coordinate in the (<em>x</em>, <em>y</em>, <em>R</em>) system, but instead of always being 0 or 1, it’s one of two adjacent numbers depending on where in the grid you are. In the system I drew above, the <em>c</em> coordinate is always equal to either (<em>–a – b</em>) or<br>(–<em>a </em>– <em>b </em>+ 1).</p><p>None of these three systems seems quite natural to me. The square-packed system uses just two coordinates, which seems right for a two-dimensional grid, where the others use three coordinates, with one of them being restricted to one of two values. The sheared-square system has a weird binary third coordinate whose geometric meaning is somewhat opaque. The (<em>a</em>, <em>b</em>, <em>c</em>) system’s coordinates are all clearly geometrically meaningful, but its third coordinate is oddly constrained, like the sheared-square system. It’s a little surprising to me that hex grids <a href="http://www.redblobgames.com/grids/hexagons/">work out to be much simpler</a>, and are amenable to storing just two coordinates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=133ed47cc807" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Today I Learned: buoyant peninsulas, the free store]]></title>
            <link>https://nornagon.medium.com/today-i-learned-buoyant-peninsulas-the-free-store-9c707eb3f65a?source=rss-564335d4cff6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c707eb3f65a</guid>
            <category><![CDATA[san-francisco]]></category>
            <category><![CDATA[today-i-learned]]></category>
            <category><![CDATA[geology]]></category>
            <category><![CDATA[procedural-generation]]></category>
            <dc:creator><![CDATA[Jeremy Rose]]></dc:creator>
            <pubDate>Sun, 23 Jul 2017 06:38:06 GMT</pubDate>
            <atom:updated>2017-07-23T06:39:14.095Z</atom:updated>
            <content:encoded><![CDATA[<p>I went to the San Francisco Public Library today (which is just across the road from my house — it’s a crime I don’t visit there more often!) to see what I could find in the way of books on plate tectonics. I found <em>Continental Drift and Plate Tectonics</em> by William Glen, published 1975, which had some wonderful diagrams in it.</p><p>I learned that there are two broad classes of material that the Earth’s crust tends to be made from: dense basaltic rock which makes up the ocean floor and is about 10 km thick, and lighter granitic rock that makes up continental mass, and is about 25 km thick most places. All the crusty bits are floating on a sort-of-solid goop called the asthenosphere, above which the rock cools down enough to be solid and below which the rock is under so much pressure that it solidifies. So the asthenosphere is kind of like the lubricant that lets the plates slide around.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3QiZkXoaPGUk04FVppUXg.jpeg" /><figcaption>Continental Drift and Plate Tectonics<em>, William Glen. Published 1975 by Bell &amp; Howell Company.</em></figcaption></figure><p>I tried out a simulation approach for getting bits of crust to float around and bash into each other by scattering points around a slowly shifting vector field, but I’m not particularly happy with the results so far. I added in some more factors like ‘springs’ between bits of crust to get them to stick together and behave a bit more solidly, but the whole thing still really reflects the underlying simplex noise a lot. I think there’s more tweaking to be had here before I move on to a different approach—I haven’t tried to model subduction at all yet, for example — but I’m not especially hopeful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*pSb5kuaCDeGc8_SfJnqQNQ.png" /><figcaption>Making continents by shifting around bits of crust atop a molten vector field</figcaption></figure><p>One really cool thing I learned about from Glen’s book was that Scandinavia is <em>rising up out of the Earth</em>. A few tens of millennia ago, Scandinavia was covered in glaciers and ice sheets. Water is pretty heavy, so all that ice pressed the Scandinavian peninsula down into the asthenosphere, like pushing down on a rubber duck in the bath. All the ice melted, though, so now the whole lot is slowly bobbing back up out of the magma. It’s rising about a centimetre a year, and it’s got about another 150 metres to go. Finland gains 7 square kilometres a year.</p><h4>The free shop</h4><p>Cole and I went on a walk around Haight-Ashbury today with <a href="https://www.detour.com/">Detour</a>, which was excellent and I highly recommend checking out Detour’s other walks (they have a bunch of them, all over the world! … but not in Australia yet.) The tour was a lot deeper and more thoughtful than I was expecting.</p><p>As Peter Coyote narrated our ambling through the Haight, he told us about the Diggers, an anarchist improv theatre group of which he was a founding member. I’d heard about the Diggers before, in particular their serving free food in Golden Gate park, but I didn’t know about the <a href="http://diggers.org/free_store.htm">free store</a> they ran. It was a garage in the Haight (which we walked past!) and it was a shop where everything was free. That’s it, really. Just a free store.</p><p>The anti-capitalist stance of the Diggers turned out not to be sustainable in the heavily capitalist environment of the US, but a lot of their other thinking has solidified into nationwide policy. Coyote attributes the widespread implementation of addiction treatment programs in the present day to the Digger-adjacent Haight Ashbury Free Clinics, founded by David E. Smith, which treated drug addictions in the 60s without a license to do so (since nobody would give them one). The clinic still operates, in the same building it was founded in.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c707eb3f65a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>