<?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 Denys Sedchenko on Medium]]></title>
        <description><![CDATA[Stories by Denys Sedchenko on Medium]]></description>
        <link>https://medium.com/@dsedchenko?source=rss-86821b8a6bc6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gSfrUPhQuX3rNoz4S1AQXw.jpeg</url>
            <title>Stories by Denys Sedchenko on Medium</title>
            <link>https://medium.com/@dsedchenko?source=rss-86821b8a6bc6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:30:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dsedchenko/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[Cutting through the CVE noise: Building a distroless image for Alloy]]></title>
            <link>https://medium.com/grafana-labs/cutting-through-the-cve-noise-building-a-distroless-image-for-alloy-7a12e9595b3a?source=rss-86821b8a6bc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a12e9595b3a</guid>
            <category><![CDATA[grafana-alloy]]></category>
            <category><![CDATA[container-security]]></category>
            <category><![CDATA[software-security]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Denys Sedchenko]]></dc:creator>
            <pubDate>Fri, 04 Dec 2026 16:43:03 GMT</pubDate>
            <atom:updated>2026-12-04T16:43:03.444Z</atom:updated>
            <content:encoded><![CDATA[<p><em>See how our research led us to shrink the container image for our open source telemetry collector, reducing its attack surface and the CVE triage burden.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H1TYCZ9dBz0Ar6hkjIQYzw.png" /></figure><p>Managing CVEs is a crucially important part of building software.</p><p>First-party vulnerabilities are very rare in Alloy, our open source telemetry collector. However, there is a constant stream of potential vulnerabilities coming from upstream dependencies, the golang language itself, and the underlying Linux distribution packages used within a container image.</p><p>Most third-party vulnerabilities aren’t actionable in Alloy, but each risk needs to be carefully evaluated, so the Alloy team is constantly monitoring and triaging newly published CVEs.</p><p>And that burden grows as we ship more software, including utilities and libraries Alloy doesn’t use at runtime.</p><p>To address this challenge, we researched ways to shrink our container image to reduce its attack surface and CVE triage burden. The result is a distroless Alloy image that has 80% less CVEs and is 21% smaller.</p><p>In this post, we explain the requirements that shaped it, the options we evaluated and why we rejected some of them, and how the final image compares with the default.</p><h3>The security and maintenance costs of extra packages</h3><p>Before we get into what we built, let’s first look closer at what led us here.</p><h3>Attack vector</h3><p>The standard Alloy container image uses Ubuntu as a base and inherits all 95 packages it ships out of the box. Those packages include compression utilities, userspace tools, unused libraries such as ncurses, and even a Perl language interpreter.</p><p>Besides image-size bloat, all that ballast exposes significant security risks. If a bad actor discovers a remote code execution path, those packages can serve as a post-exploitation attack surface.</p><p>For example, with Bash or Perl, the <a href="https://www.microsoft.com/en-us/security/blog/2024/04/17/attackers-exploiting-new-critical-openmetadata-vulnerabilities-on-kubernetes-clusters/">attacker can steal secrets</a>, read environment variables, or spawn reverse shells.</p><h3>Maintenance burden</h3><p>Each package present in our images is a source of CVEs that need to be triaged. Examples from the earlier Alloy releases include:</p><ul><li>CVE-2026–27456: TOCTOU in util-linux</li><li>CVE-2026–33845: Flaw in GnuTLS</li><li>CVE-2025–45582: GNU Tar</li></ul><p>If the finding affects a component that is not used by Alloy and a fix is not available in a repository, we still need to be able to back that assertion with a thorough, documented investigation.</p><h3>Looking for a solution</h3><p>Once we understood the limitations of our previous approach, we began looking for new ways to improve Alloy.</p><h3>Alloy container requirements</h3><p>In terms of what can’t change, there are a few elements Alloy absolutely needs in order to run in a container:</p><ul><li>Core C runtime: glibc, libdl, libpthead — cgo runtime, needed to load dynamic libraries</li><li>libsystemd0 and friends: Used by loki.source.journal at runtime</li><li>tzdata: Time zone conversion</li><li>CA certificates: TLS verification</li><li>POSIX shell interpreter: needed for bundled otelcol and otel-supervisor scripts that are used for Alloy in <a href="https://grafana.com/blog/bridging-alloy-and-opentelemetry-the-otel-engine-is-now-in-public-preview">OTel mode</a></li></ul><h3>Constraints and requirements</h3><p>Unlike regular containerized applications, Alloy has a set of additional requirements that need to be accounted for:</p><ul><li><strong>Architecture support:</strong> Besides standard arm64 and aarch64, Alloy supports PowerPC 64-bit and IBM S390x architectures, which are not very common.</li><li><strong>Dependency management:</strong> Alloy exposes a variety of components, some of which require certain native libraries via dynamic linking at runtime. Dependencies for core components need to be bundled into an image, ideally via a package manager.</li><li><strong>Security:</strong> The upstream should provide patched versions of affected packages on time.</li><li><strong>Compatibility:</strong> Users must be able to bring their own libraries for optional Alloy components, such as client libraries for <a href="https://grafana.com/docs/alloy/latest/reference/components/prometheus/prometheus.exporter.oracledb/">Prometheus Oracle exporter</a>, therefore image should be glibc-based and FHS compliant.</li><li><strong>Transparency:</strong> Security scanners like Trivy should be able to discover system dependencies and report any findings for them. Ideally, the option should provide an option to generate SBOM for system packages.</li></ul><p>With a checklist of requirements, we went to assess options available.</p><h3>Pure distroless</h3><p>The first candidate we evaluated was the distroless Debian image from Google, but that option was quickly rejected as it didn’t match our checklist:</p><p><strong>Security:</strong> During our original evaluation on August 20, 2026, Trivy reported worse results than ubuntu:noble base, although neither had critical findings:</p><figure><img alt="Table comparing known vulnerabilities in two base images by severity. cc-debian13 has 0 critical, 23 medium, and 8 low CVEs. ubuntu:noble has 0 critical, 21 medium, and 4 low CVEs." src="https://cdn-images-1.medium.com/max/1024/1*9rxtEIPBAfWiWM19jGRmjg.png" /></figure><p><em>We include this historical snapshot to explain the findings that informed our decision at the time. It does not reflect the current scan results.</em></p><p><strong>Dependency management:</strong> The image has no package manager out of the box, all native dependencies have to be copied and installed manually — for example, by borrowing files from standard Debian in a multi-stage build.</p><p>There’s a reason package managers exist, however. Doing this manually is a fragile, error-prone process that can easily lead to broken images if dependencies (or transitive dependencies) change.</p><p>Although that class of issue will be captured with image smoke tests, it creates a maintenance burden that can be avoided with other options.</p><p><strong>Transparency:</strong> Most security scanners like Trivy infer a list of system packages in a container, by scanning package manager outputs files such as var/lib/dpkg/status.</p><p>As we’re copying files manually, we would need to either reconstruct that file ourselves or manually maintain a separate SBOM file that lists source packages.</p><h3>Minimal images</h3><p>We considered Alpine Linux, which is one of the most popular base images for containers. It’s minimal and ships a package manager, so we don’t need to deal with manual dependency copy.</p><p>Unfortunately this option was also a no-go as Alpine uses musl instead of glibc, which doesn’t match our previously discussed <strong>compatibility</strong> criteria.</p><h3>Thinking outside of the box</h3><p>In pursuit of a perfect solution, we turned our gaze to Nix, which provides a <a href="https://nix.dev/tutorials/nixos/building-and-running-docker-images.html">built-in way</a> to build slim container images.</p><p>On a paper, Nix looks like a (almost) perfect solution from security standpoint:</p><p><strong>Dependency management:</strong></p><ul><li>Nix flake declares all dependencies; no need to manually tinker with files</li><li>The final image only contains what’s there; no unexpected dependencies</li></ul><p><strong>Security:</strong></p><ul><li>Nixpkgs contains the most up-to-date versions of packages, even faster than ArchLinux</li><li>Nix pins dependencies and keeps a lock file out of the box, providing a deterministic hermetic build</li></ul><p><strong>Transparency:</strong></p><ul><li>Nix ecosystem provides tools like sbomnixto generate SBOMs</li></ul><p>Unfortunately we had to pass on that option due to multiple problems:</p><p><strong>Learning curve:</strong> Maintainers need to learn a new unfamiliar toolchain and configuration language to make routine changes.</p><p><strong>Architecture support:</strong> The main Nix binary cache server only provides binaries for arm64 and amd64. For s390x and PowerPC, we would need to resort to cross-compilation.</p><p>Although actions like DeterminateSystems/magic-nix-cache-actioncould help to address this problem, modern security requirements demand clean builds to prevent cache poisoning.</p><p><strong>Compatibility:</strong> Nix isn’t FHS-compliant and it puts libraries in non-standard locations. Alloy itself is currently built outside of Nix. This can lead to a problem when Alloy couldn’t load external libraries in runtime with dlopen() without setting a correct LD_LIBRARY_PATH .</p><h3>Hybrid approach</h3><p>So, after all this, could we still find a distroless image, install necessary dependencies with a package manager, and keep all our requirements? Luckily the answer is yes.</p><p>We discovered two interesting projects — <a href="https://github.com/canonical/chisel">Chisel</a> from Canonical and <a href="https://www.redhat.com/en/blog/introduction-ubi-micro">UBI Micro</a> from Red Hat. Both projects implement a similar concept: build your own system root that only contains necessary packages, but only at container build time, and export it as an output image.</p><p>Here is a small Dockerfile to explain the idea:</p><pre># 1. Build the Go binary which depends on libsqlite3 in runtime.<br>FROM golang:1.25 AS build<br>WORKDIR /src<br>COPY main.go .<br>RUN go build -o /hello .<br><br># 2. Cut a minimal root filesystem out of Ubuntu packages.<br>FROM golang:1.25 AS slicer<br>ARG UBUNTU_RELEASE<br>RUN go install github.com/canonical/chisel/cmd/chisel@latest<br><br>RUN mkdir /rootfs \<br>    &amp;&amp; chisel cut --release &quot;ubuntu-24.04&quot; --root /rootfs \<br>        base-files_base \<br>        libc6_libs \<br>        libsqlite3-0_libs<br><br>COPY --from=build /hello /rootfs/hello<br><br># 3. Final image: nothing but the sliced rootfs.<br>FROM scratch<br>COPY --from=slicer /rootfs/ /<br>ENTRYPOINT [&quot;/hello&quot;]</pre><p>The idea is very similar to how we, as developers, make container images for our applications with multi-stage builds. The only difference is that, here we build a whole container root filesystem.</p><p>UBI Micro works the same way as Chisel, but uses the RHEL package base. Between two options, we selected Chisel as we currently use Ubuntu as a base image.</p><h3>Conclusion</h3><p>Ubuntu Chiseled and Red Hat UBI Micro were both able to meet our full list of constraints, and Chiseled edged out the competition as it’s more similar to our existing builds. While the other options we evaluated were each interesting potential solutions, they were not able to satisfy all of Alloy’s build requirements.</p><p>Here is a comparison between a default and distroless Alloy images:</p><figure><img alt="Comparison of grafana/alloy v1.21.3 and its distroless variant: smaller size, fewer packages, fewer CVEs." src="https://cdn-images-1.medium.com/max/1024/1*wZ2Lch_6IolbaSrl3z_Fug.png" /></figure><p>As a result, the current distroless image is 22% smaller, has 85% less packages, and 80% less CVEs.</p><h3>FAQ</h3><h3>When will the image be available?</h3><p>The image is available under a separate -distroless tag since Alloy v1.20.0.</p><h3>Do you plan to replace the main Alloy image?</h3><p>Currently the image is available under a separate tag, but eventually we would like to provide the distroless as our primary image.</p><h3>Should I use the distroless Alloy image?</h3><p>Yes, treat it as your default. It’s a drop-in replacement that shrinks your attack surface and saves your security team from triaging false-positive scanner alerts.</p><p>As we plan to make distroless the default Alloy image, adopting it now gives you time to validate your deployment and prepare for that transition.</p><h3>Are there any breaking changes?</h3><p>There are no explicit breaking changes, and for most use-cases, the image is a drop-in replacement. In a few cases when you need to customize the image, for example to install additional libraries or add process capabilities to run beyla.epbf in a rootless environment you may need to follow a different set of steps.</p><p>Please see <a href="https://github.com/grafana/alloy/issues/6662#issuecomment-5719373096">this Github Issue</a> for an example on how to customize the distroless image.</p><h3>Can I use the image in the Alloy Helm chart?</h3><p>You can switch to distroless image by setting image.distroless to true in your value.yaml.</p><p>The option is available since Alloy Helm chart version v1.15.0</p><h3>How can I debug an Alloy pod running a distroless image?</h3><p>Although we bundle a Dash shell interpreter, it doesn’t contain common command-like tools like cp, cat, mkdir, etc.</p><p>Therefore to debug a running pod, we suggest using the kubectl debug <a href="https://kubernetes.io/docs/tasks/debug/debug-application/debug-running-pod/">here</a>.</p><p><em>Enjoy technical deep dives and stories from the Grafana community?</em><a href="https://medium.com/grafana-labs"><em> Follow Unprompted</em></a><em> for more.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a12e9595b3a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/grafana-labs/cutting-through-the-cve-noise-building-a-distroless-image-for-alloy-7a12e9595b3a">Cutting through the CVE noise: Building a distroless image for Alloy</a> was originally published in <a href="https://medium.com/grafana-labs">Unprompted, by Grafana Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arch Linux Setup Guide For MacBookPro11,5 (MacBook Pro Mid 2015)]]></title>
            <link>https://dsedchenko.medium.com/arch-linux-setup-guide-for-macbookpro11-5-macbook-pro-mid-2015-f53bb87dc99b?source=rss-86821b8a6bc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f53bb87dc99b</guid>
            <category><![CDATA[macbook-pro]]></category>
            <category><![CDATA[arch-linux]]></category>
            <category><![CDATA[amd-gpu]]></category>
            <category><![CDATA[linux-mac]]></category>
            <category><![CDATA[macbook-linux]]></category>
            <dc:creator><![CDATA[Denys Sedchenko]]></dc:creator>
            <pubDate>Wed, 30 Apr 2025 08:32:12 GMT</pubDate>
            <atom:updated>2025-05-02T04:49:02.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GiiSQno_5pkZ4WKkG1Bw9g.png" /></figure><p>This article is a collection of caveats necessary to get Arch Linux up and running on old Intel MacBooks with AMD GPUs.</p><p>Steps here are based on various articles and hours of painful debugging.</p><p>Article skips full Arch setup process, focusing only on MacBook-specific steps.</p><p>This article assumes that you’re using:</p><ul><li>PipeWire as audio server.</li><li>Wayland with Hyprland as a compositor.</li></ul><h3>Table Of Contents</h3><h4><a href="#9595">Bootloader</a></h4><ul><li><a href="#94d9">rEFInd Installation</a></li><li><a href="#9bcf">Set Apple OS</a></li><li><a href="#2a51">Extra Boot Arguments</a></li><li><a href="#3c01">Setting Up rEFInd as default bootloader</a></li></ul><h4><a href="#67b5">Network</a></h4><ul><li><a href="#a7db">NetworkManager</a></li><li><a href="#92a1">Broadcom</a></li></ul><h4><a href="#ada5">GPU Power Management</a></h4><ul><li><a href="#975f">UDev Rules</a></li><li><a href="#1683">Kernel Modules Parameters</a></li><li><a href="#0357">Use integrated GPU on boot using gpu-switch</a></li><li><a href="#44db">HDMI Audio Power</a></li><li><a href="#ff39">Turning OFF discrete GPU</a></li><li><a href="#b157">Disable dGPU on boot</a></li><li><a href="#308a">Using integrated GPU for Wayland</a></li></ul><h4><a href="#f370">Power Efficiency</a></h4><ul><li><a href="#efaf">Battery Monitoring</a></li><li><a href="#cf9b">Automatic CPU Power Profile</a></li><li><a href="#379f">Manual Power Profiles Management</a></li></ul><h3>Sources</h3><p>Information in this article is based on following sources:</p><ul><li><a href="https://wiki.t2linux.org/guides/hybrid-graphics/">https://wiki.t2linux.org/guides/hybrid-graphics/</a></li><li><a href="https://github.com/Dunedan/mbp-2016-linux">https://github.com/Dunedan/mbp-2016-linux</a></li><li><a href="https://wiki.archlinux.org/title/MacBookPro11,x">https://wiki.archlinux.org/title/MacBookPro11,x</a></li><li><a href="https://github.com/pandeiro/arch-on-air">https://github.com/pandeiro/arch-on-air</a></li></ul><h3>Bootloader</h3><p>Apple introduces certain limitations for non-macOS systems, such as inability to use Intel GPU.</p><p>The most convenient way to bypass them is using <strong>rEFInd </strong>bootloader.<br>rEFInd handles MacOS version spoofing, SIP and other stuff out of the box.</p><h4>rEFInd Installation</h4><p>Install rEFInd by following instructions from <a href="https://wiki.archlinux.org/title/REFInd">ArchWiki</a>.</p><p>Don’t forget to add Linux boot configuration into rEFInd config file /boot/EFI/refind/refind.conf</p><h4>Set Apple OS</h4><p>Apple blocks access to integrated Intel GPU for any non-macOS operating system.</p><p>rEFInd provides a way to workaround this with spoof_osx_version config parameter.</p><p>Open /boot/EFI/refind/refind.conf and add a following parameter:</p><pre>spoof_osx_version 12.7</pre><h4>Extra Boot Arguments</h4><p>Add following options to your Arch Linux menu entry in rEFInd config:</p><pre>data=writeback libata.force=1:noncq acpi_mask_gpe=0x06 acpi_osi=Darwin i915.modeset=1 amdgpu.modeset=0 amdgpu.runpm=1</pre><h4>Setting Up rEFInd as default bootloader</h4><p>Unlike Grub or systemd-boot, rEFInd places itself into a non-standard directory inside EFI partition.</p><p>Use efibootmgr to add rEFInd as boot entry:</p><pre>efibootmgr -c -L &#39;rEFInd Boot Manager&#39; -l &#39;\EFI\refind\refind_x64.efi&#39;</pre><p>Also, I recommend removing old macOS boot entries using <em>efibootmgr</em> to avoid having long boot delays.</p><h3>Network</h3><h4>NetworkManager</h4><p>NetworkManager won’t let you to connect to a WiFI without a proper dbus session and keychain provider.</p><p>The simplest and most reliable way is to use iwd instead:</p><pre>pacman -S iwd<br>systemctl disable --now NetworkManager<br>systemctl enable --now systemd-resolved<br>systemctl enable --now systemd-networkd<br>systemctl enable --now iwd</pre><p>Check <a href="https://wiki.archlinux.org/title/Iwd">this ArchWiki page</a> for instructions how to connect to a WiFi network.</p><h4>Broadcom</h4><p>You might encounter issues related to missing Broadcom firmware.</p><p>In that case, installing broadcom-wlmight help:</p><pre>paru broadcom-wl-dkms </pre><p>Then, create /etc/modprobe.d/broadcom-wl-dkms.conf:</p><pre>blacklist brcm80211</pre><h3>GPU Power Management</h3><p>Unfortunately AMD Cape-Verde gGPUs <strong>don’t support</strong> dynamic power management. This means, dGPU has to be shut down manually in order to save battery.</p><h4><strong>UDev Rules</strong></h4><p>Create /etc/udev/rules.d/30-amdgpu-pm.rules</p><pre>ACTION==&quot;add&quot;, SUBSYSTEM==&quot;drm&quot;, DRIVERS==&quot;amdgpu&quot;, ATTR{device/power/control}=&quot;auto&quot;<br>ACTION==&quot;add&quot;, SUBSYSTEM==&quot;drm&quot;, DRIVERS==&quot;amdgpu&quot;, ATTR{device/power_dpm_force_performance_level}=&quot;low&quot;</pre><h4><strong>Kernel Modules Parameters</strong></h4><p>Go to /etc/modprobe.d and create a couple of files.</p><p><strong>amdgpu.conf:</strong></p><pre>options amdgpu modeset=0<br>options amdgpu enable_psr=1<br>options amdgpu si_support=1<br>options amdgpu cik_support=1<br>options amdgpu runpm=1</pre><p><strong>radeon.conf:</strong></p><pre>options radeon si_support=0<br>options radeon cik_support=0<br>options radeon runpm=1</pre><p>Then, run sudo mkinitcpio -P to apply changes.</p><h4><strong>Use integrated GPU on boot using </strong><a href="https://github.com/0xbb/gpu-switch"><strong>gpu-switch</strong></a></h4><p>Install gpu-switch tool from AUR using Paru:</p><pre>paru gpu-switch</pre><p>Then, use it to set iGPU as a primary GPU. This allows to turn off discrete GPU.</p><p>Note: Operation takes affect only after reboot.</p><pre>sudo gpu-switch -i</pre><h4><strong>HDMI Audio Power</strong></h4><p>The last thing that prevents us from being able to fully turn off a dGPU it active HDMI audio device used by WirePlumber (or PulseAudio if you’re not using PipeWire).</p><p>This prevents vgaswitcheroo kernel module to put a device into D3 cold state.</p><p>Create a ~/.config/wireplumber/wireplumber.conf.d/50-disable-dgpu-hdmi.conf file with following contents:</p><pre># disable the HDA function on the Radeon R9 M370X (PCI 01:00.1)<br>monitor.alsa.rules = [<br>  {<br>    matches = [<br>      { &quot;device.name&quot; = &quot;alsa_card.pci-0000_01_00.1&quot; }<br>    ]<br>    actions = { update-props = { device.disabled = true } }<br>  }<br>]</pre><p>After, restart WirePlumber using systemctl --user restart wireplumber</p><h4><strong>Turning OFF discrete GPU</strong></h4><p>Both GPUs are controlled using Apple’s GMUX. Mux and GPUs power state can be consrolled using <a href="https://docs.kernel.org/gpu/vga-switcheroo.html">vga-switcheroo</a> kernel module:</p><pre># set to integrated<br>sudo sh -c &#39;echo IDG &gt; /sys/kernel/debug/vgaswitcheroo/switch&#39;<br><br># turn off dGPU<br>sudo sh -c &#39;echo OFF &gt; /sys/kernel/debug/vgaswitcheroo/switch&#39;<br><br># print mux power states.<br># ensure that &quot;DIS&quot; is &quot;OFF&quot; and &quot;DIS-Audio&quot; is &quot;DynOff&quot;<br>sudo cat /sys/kernel/debug/vgaswitcheroo/switch</pre><p>Output of /sys/kernel/vgaswitcheroo/switch should look like this:</p><pre>0:IGD:+:Pwr:0000:00:02.0<br>1:DIS: :Off:0000:01:00.0<br>2:DIS-Audio: :DynOff:0000:01:00.1</pre><h4><strong>Disable dGPU on boot</strong></h4><p>Create oneshot systemd unit in /etc/systemd/system/dgpu-poweroff.service</p><pre>[Unit]<br>Description=Disable discrete GPU (vgaswitcheroo OFF)<br>Requires=sys-kernel-debug.mount<br>After=sys-kernel-debug.mount<br><br>[Service]<br>Type=oneshot<br>ExecStart=/bin/sh -c &#39;echo OFF &gt; /sys/kernel/debug/vgaswitcheroo/switch&#39;<br><br>[Install]<br>WantedBy=multi-user.target suspend.target   # run at boot and after resume</pre><p>Them, start the service:</p><pre>sudo systemctl daemon-reload<br>sudo systemctl enable --now dgpu-poweroff.service</pre><h4><strong>Using integrated GPU for Wayland</strong></h4><p>Find PCI ID of your GPUs:</p><pre>$ lspci | grep VGA<br>00:02.0 VGA compatible controller: Intel Corporation Crystal Well Integrated Graphics Controller (rev 08)<br>01:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Venus XT [Radeon HD 8870M / R9 M270X/M370X] (rev 83)</pre><p>Check what DRI card maps to PCI IDs:</p><pre>$ ls -l /dev/dri/by-path<br>total 0<br>lrwxrwxrwx 1 root root  8 Apr 23 03:14 pci-0000:00:02.0-card -&gt; ../card1<br>lrwxrwxrwx 1 root root 13 Apr 23 03:14 pci-0000:00:02.0-render -&gt; ../renderD128<br>lrwxrwxrwx 1 root root  8 Apr 23 03:14 pci-0000:01:00.0-card -&gt; ../card0<br>lrwxrwxrwx 1 root root 13 Apr 23 03:14 pci-0000:01:00.0-render -&gt; ../renderD129</pre><p>In my case, card1 is Intel and card0 is AMD.</p><p>To make Intel GPU a preferred GPU for Hyprland, add following into a ~/.config/hypr/hyprland.conf :</p><pre># Prefer iGPU<br>env = AQ_DRM_DEVICES,/dev/dri/card1</pre><h3>Power Efficiency</h3><p>Even with disabled AMD GPU, MacBook still consumes about 15–20 watts (which is a lot).</p><p>Although there are a lot of things that can be tweaked, the most basic thing to address is setting a correct CPU power profile.</p><h4>Battery Monitoring</h4><p>I recommend using <a href="https://github.com/svartalf/rust-battop">battop</a> tool to monitor power consumption during power optimization.</p><h4>Automatic CPU Power Profile</h4><p>The auto-cpufreq daemon allows automatic CPU power profile configuration based on battery capacity and charging status.</p><p><strong>Pros:</strong></p><ul><li>Automatic power profile management.</li></ul><p><strong>Cons:</strong></p><ul><li>By default it will put CPU into a power save mode when not connected to a charger. This will cause a drastic performance decrease.</li><li>Written in Python and consumes 20MB of RAM which is quite a lot for a simple CPU frequency daemon.</li></ul><p><strong>Installation:</strong></p><pre>paru auto-cpufreq<br>sudo systemctl enable --now auto-cpufreq</pre><p>Attention: do not choose auto-cpufreq-git as it&#39;s broken.</p><h4>Manual Power Profiles Management</h4><p>power-profiles-deamon package provides DBus service and a tool to switch between CPU profiles.</p><pre>sudo pacman -S power-profiles-daemon<br>sudo systemctl enable --now power-profiles-daemon.service</pre><p>Later, you can change power profile to power saver, performance or balanced:</p><pre>powerprofilesctl set power-saver<br>powerprofilesctl set balanced</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f53bb87dc99b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Go packages for Windows on ARM]]></title>
            <link>https://dsedchenko.medium.com/building-go-packages-for-windows-on-arm-d181fa4e3bfc?source=rss-86821b8a6bc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d181fa4e3bfc</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[windows-on-arm]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[cgo]]></category>
            <dc:creator><![CDATA[Denys Sedchenko]]></dc:creator>
            <pubDate>Sun, 16 Jun 2024 21:59:22 GMT</pubDate>
            <atom:updated>2024-09-30T17:53:59.401Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Cross-compiling Go packages for Windows on ARM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*xVuaXK68ALHVtmDa.png" /></figure><p>Recently, Qualcomm announced <a href="https://www.qualcomm.com/products/mobile/snapdragon/pcs-and-tablets/laptop-device-finder">list of laptops</a> that will have their new Snapdragon X Elite chip which claim to have the same performance as Apple’s M3 processor.</p><p>This means that in a near future, market will see more and more Windows on ARM laptops and we as developers should be prepared to that.</p><p>This article is structured in Q&amp;A sections to briefly explain the topic.</p><h3>WoA can emulate x86, isn’t it?</h3><p>Although Windows on ARM (WoA) supports x86 and x86–64 emulation, some features like vector instructions (like AVX2) might be not supported, also emulation brings some performance penalty.</p><p>People who use libraries like <a href="https://github.com/minio/simdjson-go">simdjson</a> might be at risk.</p><h3>Doesn’t Go already support cross compilation?</h3><p>Go offers out-of-box cross compilation support, including ARM64 for Windows, but this doesn’t cover CGO.</p><p>That means, any program that uses CGO libraries like <a href="https://github.com/mattn/go-sqlite3">sqlite3</a> will require C and/or C++ toolchain for cross-compilation.</p><h3>Okay, isn’t MinGW already cover that?</h3><p>Most popular solution for cross-compilation from Windows and Linux is MinGW.</p><p>Unfortunately, MinGW doesn’t support ARM64 target.</p><p><a href="https://www.msys2.org/wiki/arm64/">MSYS2</a> toolchain provide ARM support but available only for Windows.</p><p>That means that in order to build programs for Windows on ARM on a Linux machine, a different option should be considered as MinGW doesn’t support arm64 target.</p><h3>So how do I build a program with CGO for WoA?</h3><p>Don’t worry, this case is already covered.</p><p>There is a llvm-based alternative toolchain that supports WoA — <a href="https://github.com/mstorsjo/llvm-mingw">llvm-mingw</a>.</p><p>Unfortunately it’s not available in most distros except <a href="https://aur.archlinux.org/packages/mingw-w64-llvm">Arch Linux</a>, but you still can download prebuilt binaries from releases page.</p><h3>Is there a more convenient way to use llvm-mingw?</h3><p>Yes, sure!</p><p>There is a special <a href="https://github.com/x1unix/docker-go-mingw/">Docker image</a> with toolchain for all Windows architectures — amd64, x86 and <strong>arm64</strong>.</p><p>Image is called x1unix/go-mingw and offers arm64 target support since go 1.21.</p><p>Image uses MinGW for x86 and llvm-mingw for arm64 target.</p><h3>How to use it?</h3><p>It’s quite simple, just pull the image and call go build command with GOARCH=arm64 environment variable.</p><p>For example, let’s take a simple WinAPI CGO example from <a href="https://github.com/x1unix/docker-go-mingw/tree/master/example/hello">here</a>:</p><pre>package main<br><br>/*<br>#cgo LDFLAGS: -lkernel32<br>#include &lt;windows.h&gt;<br>#include &lt;stdio.h&gt;<br><br>// Function to show a MessageBox using WinAPI to test that CGO is working.<br>void hello() {<br>  SYSTEM_INFO si;<br>  ZeroMemory( &amp; si, sizeof(SYSTEM_INFO));<br>  GetSystemInfo( &amp; si);<br>  char * arch;<br>  switch (si.wProcessorArchitecture) {<br>  case PROCESSOR_ARCHITECTURE_AMD64:<br>    arch = &quot;AMD64&quot;;<br>    break;<br>  case PROCESSOR_ARCHITECTURE_INTEL:<br>    arch = &quot;x86&quot;;<br>    break;<br>  case PROCESSOR_ARCHITECTURE_ARM:<br>    arch = &quot;ARM&quot;;<br>    break;<br>  case PROCESSOR_ARCHITECTURE_ARM64:<br>    arch = &quot;ARM64&quot;;<br>    break;<br>  case PROCESSOR_ARCHITECTURE_IA64:<br>    arch = &quot;IA&quot;;<br>    break;<br>  default:<br>    arch = &quot;Unknown&quot;;<br>    break;<br>  }<br><br>  char message[30];<br>  sprintf(message, &quot;Hello from CGO on %s&quot;, arch);<br><br>  MessageBox(NULL, message, &quot;Hello World&quot;, MB_OK);<br>}<br>*/<br>import &quot;C&quot;<br>import &quot;fmt&quot;<br><br>func main() {<br>    fmt.Println(&quot;Calling C function to open a MessageBox...&quot;)<br>    C.hello()<br>}</pre><p>Now let’s build an example using Docker image:</p><pre># Go version to use. WoA supported since Go 1.21.<br>export GO_VERSION=1.22<br><br>docker run --rm -it -e GOARCH=arm64 \<br>    -v .:/go/work -w /go/work \<br>    x1unix/go-mingw:$GO_VERSION \<br>    go build -o hello.exe .</pre><h3>Result</h3><p>After building a program, let’s try to run it inside any VM with Windows on Arm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/0*xmhHuq5hneNNIU5y.png" /></figure><p>Parallels Workstation is used for this example.</p><h3>How can I integrate this into my CI?</h3><p>As this is a plain Docker image, it can be easily used both in GitHub Actions and Gitlab CI.</p><p>Please check CI templates <a href="https://github.com/x1unix/docker-go-mingw/tree/master/example/ci">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d181fa4e3bfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Web Assembly Internals — Part 2]]></title>
            <link>https://towardsdev.com/go-web-assembly-internals-part-2-f0f9a74dbd7c?source=rss-86821b8a6bc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0f9a74dbd7c</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Denys Sedchenko]]></dc:creator>
            <pubDate>Fri, 04 Nov 2022 07:23:17 GMT</pubDate>
            <atom:updated>2022-11-17T15:35:55.813Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Go WebAssembly Internals — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*VVKPMdUX8WtXqDPTBd-7Uw.png" /></figure><p>In <a href="https://x1unix.medium.com/go-webassembly-internals-part-1-a7ccdafe6822">previous article</a> we covered how to build a simple Go program, interact with host environment by wrapping Go functions as JavaScript functions and how JS-to-Go call magic works under the hood.</p><p>This article will cover how Go runtime access global JavaScript objects and helper functions from wasm_exec.js glue-code library and how this mechanism can be exploited to link external JavaScript functions directly to our programs.</p><h3>WebAssembly Import Object</h3><p>Although WebAssembly programs are isolated and have no direct access to a browser (or other host environment), each module can <a href="https://developer.mozilla.org/en-US/docs/WebAssembly/Understanding_the_text_format#importing_functions_from_javascript">import</a> symbols (usually functions) during instantiation that can be used to communicate with outside world.</p><p>All module dependencies to import have to be provided in a form of an object with a symbol name as key and function as a value.</p><p>On WASM program side, module should do an import with import statement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5090a7a5292812c97112d04baa040bbe/href">https://medium.com/media/5090a7a5292812c97112d04baa040bbe/href</a></iframe><p>Browser will link import object to a program during module instantiation process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aab221a9f568fd6bc6f95efac86841c9/href">https://medium.com/media/aab221a9f568fd6bc6f95efac86841c9/href</a></iframe><h3>Go Runtime Dependencies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*v756_CdNj7go2NGd.png" /><figcaption><em>Go WebAssembly module imports</em></figcaption></figure><p>Each Go program import a couple of runtime dependencies from import object prepared by Go helper class provided from <a href="https://github.com/golang/go/blob/master/misc/wasm/wasm_exec.js">wasm_exec.js</a> file.</p><p>Most of those functions are used for syscall/js package but also there are a few core Go runtime dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*aTRfbf09gigRlLNU.png" /><figcaption><em>Import object in </em><em>wasm_exec.js</em></figcaption></figure><p>Each imported function accepts current program stack pointer and may manipulate with go program memory inside this.mem field of Go helper class and return result.</p><p>We also see to what exact Go function is will be linked and what params it will return by function key name and comments left above function declarations.</p><h3>Linking Imported Function</h3><p>Lets have a look at declaration of <a href="https://github.com/golang/go/blob/master/src/syscall/js/js.go#L212">syscall/js.stringVal</a> function which present in import object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5974a1fe514cd49b1740ee0565c3af64/href">https://medium.com/media/5974a1fe514cd49b1740ee0565c3af64/href</a></iframe><p>The stringVal function doesn&#39;t have //go:linkname or other compiler directives, so how Go linker know that function implementation is defined in import object?</p><p>Function implementation is defined in a separate file js_js.s in the same folder. File is written in a <a href="https://go.dev/doc/asm">Go assembler language</a> and contains body for each syscall/js dependency.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d294b36226eda0c7de1894cb2a6546a4/href">https://medium.com/media/d294b36226eda0c7de1894cb2a6546a4/href</a></iframe><p>The CallImport instruction is used to declare and call function imports. Under the hood, Go compiler will generate an import statement with a path that corresponds to a function (including package name).</p><p>There is a <a href="https://github.com/golang/go/issues/38248">proposal</a> to replace CallImport instruction with a more convenient //go:wasmimport compiler directive.</p><h3>Importing Custom Functions</h3><p>All information above allows to define and link custom functions directly to a Go program. Execution of such calls are much cheaper from performance standpoint and Go programs and don’t require global namespace pollution (function shouldn’t be present in window object).</p><p>The main downside of this approach is that we have to manually deal with Go program stack, manually read and write data into program memory.</p><p>Lets write and import a simple multiplication function. Function will accept 2 integers and will return a result.</p><p>Full example source code is available in <a href="https://github.com/x1unix/go-wasm-imports-example">this repo</a>.</p><h3>Go Program</h3><p>Our program will consist of 2 files: a main Go file and accompanying Go assembly file with WASM import.</p><p>Program will import and call multiply function which is written in JavaScript.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0af9c88c75eb18d9ac40323f493d83c7/href">https://medium.com/media/0af9c88c75eb18d9ac40323f493d83c7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d14b14928e0e7d8d00a93493c0c7e226/href">https://medium.com/media/d14b14928e0e7d8d00a93493c0c7e226/href</a></iframe><p>The textflag.h file is available in $GOROOT/src/runtime directory.</p><h4>Building Program</h4><p>Set GOOS and GOARCH environment variables to build a program as WebAssembly module:</p><pre>GOOS=js GOARCH=wasm go build -o main.wasm main.go</pre><h3>Writing Wrapper</h3><p>Go SDK provides a wasm_exec.js file with Go helper class that implements Go WebAssembly ABI for browsers and contains an import object that needs to be modified.</p><p>Copy of the file is available in $GOROOT/misc/wasm/wasm_exec.js.</p><p>Lets extend Go class with a small wrapper which will allow exporting custom functions without touching original Go class implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5da8473565ff30dee0f10e05f341e589/href">https://medium.com/media/5da8473565ff30dee0f10e05f341e589/href</a></iframe><h3>Function Implementation</h3><p>Create a main.mjs file that will import and run our WebAssembly program.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bed3641ba6e30d03697598247d68b134/href">https://medium.com/media/bed3641ba6e30d03697598247d68b134/href</a></iframe><h4>Reading arguments</h4><p>The sp argument is a stack pointer address which is passed to each imported function. Values of first and second integers should be manually obtained from stack.</p><p>Go class has mem property which is an instance of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView">DataView</a> interface. As MDN documentation says:</p><blockquote><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView"><em>DataView</em></a><em> provides a low-level interface for reading and writing different number values into program memory without having to care about platform endianness.</em></blockquote><p>The this.mem.getInt32 method accepts offset and boolean parameter to indicate that our value is stored in little endian format.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fab80b6993b5fd10bc42c8607978a715/href">https://medium.com/media/fab80b6993b5fd10bc42c8607978a715/href</a></iframe><h4>Returning result</h4><p>Result of the function should be put in memory after the last argument on stack.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f6c08a2d16e318cf6839771a8360829/href">https://medium.com/media/3f6c08a2d16e318cf6839771a8360829/href</a></iframe><h3>Final Result</h3><p>Lets run our WebAssembly module with multiply function implementation inside Node.js.</p><p><strong>Attention:</strong> for Node.js 18 and below, <a href="https://github.com/PeculiarVentures/webcrypto">WebCrypto API polyfil</a> is required.</p><pre>$ node ./main.mjs</pre><pre>Got call from Go: { a1: 3, a2: 4, result: 12 }<br>Multiply result: 12</pre><p>Full example source code with polyfill is available in <a href="https://github.com/x1unix/go-wasm-imports-example">this repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0f9a74dbd7c" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/go-web-assembly-internals-part-2-f0f9a74dbd7c">Go Web Assembly Internals — Part 2</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go WebAssembly Internals — Part 1]]></title>
            <link>https://towardsdev.com/go-webassembly-internals-part-1-a7ccdafe6822?source=rss-86821b8a6bc6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7ccdafe6822</guid>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Denys Sedchenko]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 04:17:40 GMT</pubDate>
            <atom:updated>2023-01-16T03:01:03.054Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Go WebAssembly Internals — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*D_VEqLMr2aGsi_Ms.jpg" /></figure><p>In Go 1.11 was introduced WebAssembly support. WebAssembly is a binary executable format that was primary designed to run in web browsers but later started to become popular on other targets such as <a href="https://www.cncf.io/blog/2021/08/25/webassembly-serverless-functions-in-aws-lambda/">serverless</a> and even <a href="https://www.docker.com/blog/docker-wasm-technical-preview/">Docker</a>.</p><p>This series or articles will cover some Go internals that used to communicate with host JavaScript environment, its limitations and hacks that can be achieved by exploiting some undocumented features used for Go runtime internal purpose.</p><p>This first article will cover basics of syscall/js package and how Go code invocation from JS works.</p><p><strong>Update:</strong> The <a href="https://x1unix.medium.com/go-web-assembly-internals-part-2-f0f9a74dbd7c">next article</a> is already available!</p><h3>WebAssembly Communication Model</h3><p>By default, WebAssembly doesn’t have direct access to host system (JS world in our case), it can’t directly access <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model">DOM</a>, <a href="https://developer.mozilla.org/ru/docs/Web/API/Window">BOM</a> ( window object) and other JS APIs.</p><p>Each WebAssembly module has to declare a list of imported and exported symbols.</p><p>Imported symbols usually used to communicate with a browser (or other host environment) and and are linked by a browser during WebAssembly module instantiation. WebAssembly module caller on JS side should pass those symbols as import object.</p><p>Exports are used to export module symbols (functions usually) to be executed from JavaScript.</p><p>Unlike Go, <a href="https://emscripten.org/docs/porting/connecting_cpp_and_javascript/Interacting-with-code.html">Emscripten</a> or <a href="https://rustwasm.github.io/wasm-bindgen/contributing/design/exporting-rust.html">Rust</a> provide convenient way to import or export symbols from our program.</p><p>Go uses imports and exports for it’s internal purposes and out of box doesn’t provide a convenient way to link Go program functions to exports. I will cover this topic more in depth in next series.</p><h3>Code Sample</h3><p>The only way to communicate with JavaScript world is to interact with global namespace ( window or globalThis), attaching or obtaining values from it using syscall/js package.</p><p>Go provides way to wrap Go functions to JavaScript callable functions using js.FuncOf and assigning them to JS objects (usually global object like window) that can be used to call Go code from JS.</p><p>Let’s create a simple Go program that will export a simple greeter function that will print a simple “hello world” message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8854172fa1c6f5666c3fb3f011db85c6/href">https://medium.com/media/8854172fa1c6f5666c3fb3f011db85c6/href</a></iframe><p>Program should be compiled for WebAssembly architecture with this command:</p><pre>GOOS=js GOARCH=wasm go build main.go</pre><h3>Run a program</h3><p>Let’s try to run this program. For demonstration purposes, I already created a snippet on Better Go Playground which allows executing Go programs in WASM environment — <a href="https://goplay.tools/snippet/sNWAb8yhHtu">https://goplay.tools/snippet/sNWAb8yhHtu</a>.</p><p>Open the <a href="https://goplay.tools/snippet/sNWAb8yhHtu">snippet</a>, and select WebAssembly environment as shown on a screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1Hb_IkAWJRomXlY9" /></figure><p>Then, click button. Our program will notify that it’s running and expecting greeter function to be called.</p><p>Open browser DevTools by pressing F12 key and go to <strong>Console</strong> tab and call our greeter function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r9O8XezW5vVi9UsO" /></figure><p>As you see, our function is working, but how this magic actually works?</p><h3>JavaScript Invocation Internals</h3><p>To execute Go WebAssembly program, Go SDK provides a small glue-code file wasm_exec.js which is located in $GOROOT/misc/wasm/wasm_exec.js.</p><p>It provides a window.Go object helper which will manage all JS-to-Go communication and will provide access to all JS objects. The syscall/js.FuncOf function using this helper for wrapping Go functions and making them callable from JavaScript.</p><h3>Exporting Go Function</h3><p>The js.FuncOf method wraps function to make it callable from JS. Wrapped function is put in specific internal map and have ID assigned to them. When function will be called from JS, wrapper will create an event with call information which will be routed to destination function by ID.</p><p>All wrapped Go functions are registered in map inside of syscall/js package. Map key is function ID which will be used to find target function.</p><p>Here is a very abstract explanation of how is working:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c593ffe591ac3b6aab0818e7a2b15fa/href">https://medium.com/media/5c593ffe591ac3b6aab0818e7a2b15fa/href</a></iframe><h3>Go Function Wrapper Anatomy</h3><p>Let’s take a look, how our exported window.greeter function looks like. This function was created by go._makeFuncWrapper method which was called by Go at previous step.</p><p>JavaScript allows to get function’s source code by calling window.greeter.toString(). Here is how our greeter function is actually look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30e1cec7de5ce62b086ec9b3816b290b/href">https://medium.com/media/30e1cec7de5ce62b086ec9b3816b290b/href</a></iframe><p>As you see, under the hood it will call Go wasm_exec.js helper object, register an event with Go function and it&#39;s arguments and will resume a program to handle the request.</p><h3>Invoking Target Go Function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*pks9qKExWVr2fg2P" /></figure><p>When Go function wrapper is called from JavaScript, under the hood wrapper takes passed index of a function, creates an event with passed arguments and stores it in go._pendingEvent.</p><p>After that, it will “awake” Go by calling internal Go function wasm_export_resume which is exported by every Go WebAssembly binary as resume function.</p><p>wasm_export_resume calls a global event handler function handleEvent() which is located at syscall/js package.</p><p>handleEvent reads target function ID and call arguments from _pendingEvent property of JS Go object where we put all function call information inside Go function wrapper.</p><p>Then, it gets target Go function from funcs map, calls it and writes call result back to go._pendingEvent.result property. Result of event is retuned by JS wrapper function.</p><h3>Conclusion</h3><p>As this article shows, it’s easy to export and call Go functions from JavaScript but Go function invocation process quite complex and requires context switching which is an expensive procedure.</p><p>The <a href="https://x1unix.medium.com/go-web-assembly-internals-part-2-f0f9a74dbd7c">next article</a> will cover process of how Go communicates with JavaScript world under the hood and obtains values from JavaScript world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7ccdafe6822" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/go-webassembly-internals-part-1-a7ccdafe6822">Go WebAssembly Internals — Part 1</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>