<?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 AlysonN on Medium]]></title>
        <description><![CDATA[Stories by AlysonN on Medium]]></description>
        <link>https://medium.com/@alysonn?source=rss-c976df4e1e52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Mct4Vp9UKEjhdWPaItYTvA.jpeg</url>
            <title>Stories by AlysonN on Medium</title>
            <link>https://medium.com/@alysonn?source=rss-c976df4e1e52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:35:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alysonn/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[ByFrost in Development — Releasing the Source Code]]></title>
            <link>https://itnext.io/byfrost-in-development-releasing-the-source-code-42508dbaaf6f?source=rss-c976df4e1e52------2</link>
            <guid isPermaLink="false">https://medium.com/p/42508dbaaf6f</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[indexing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[codebase]]></category>
            <dc:creator><![CDATA[AlysonN]]></dc:creator>
            <pubDate>Sat, 19 Nov 2022 11:02:18 GMT</pubDate>
            <atom:updated>2022-11-21T17:47:20.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>ByFrost in Development — Releasing the Source Code</h3><p>Yup, it’s finally time. And it works… sorta. Okay not entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*vrlQVB5SXaC9OKNIp2f-Mg.png" /><figcaption>Found it yet?</figcaption></figure><p>You read right reader! I’m releasing everything I’ve worked on up to this point with ByFrost. The repo will be linked at the end of the article and brace yourself, it’s a mess.</p><p>For this article, I’ll walk through how to use what’s already there, the learnings and pitfalls of each and, you guessed it, how I’m gonna make it better on my (not second, but) third attempt.</p><p>Putting it bluntly, I grossly underestimated just how hard what I’m trying to do would actually be.</p><p>I decided to release the first of the two as it’s more ready for prime time than the seond attempt and is a great “demo” for what’s possilble. As for the secret third one, I’ll be spending the next couple of months working of of the knowledge I’d gained here. ByFrost was originally meant to be the first component in the project I actually wanted it to be but I figured that the way things were going, it was never gonna work. Especially not with targeting Golang first.</p><p>This article will be in three parts; the description of V1 and what how V2 sorta works and what I’ll be doing in my third attempt. I didn’t bother releasing V2 because the state it’s in is just sad… accurate as it is.</p><p>So, let’s get into it.</p><h3>ByFrost V1 — The Scrappy Underdog</h3><p>This version was the very first iteration and was based on the release video I made in the initial post <a href="https://medium.com/itnext/introducing-byfrost-a-source-code-path-visualizer-2d64002d1f9a">Introducing Byfrost</a>.</p><h4><strong>Overall Architecture</strong></h4><p>This version was incredibly naive, only expanding on function libraries, ignroing things like struct members and methods.</p><p>It went something like this; consider this code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*XG6joeI_9RagNNlGppjUeg.png" /></figure><p>V1 would scan main and blindly look for the pattern ID (in this case is fmt )and then a DOT ( . ) and then on the next token it finds (in this case, an ID called LocalPrintln ), it would then scan all packages detected in this directory pointed to by fmt. Using the absolute path to the project we’re currently in, the path to this package would be established; if your absolute path to the root of your current Go project is /Users/alyson/newproject , then the path to fmt would now be /Users/alyson/newproject/localprint/fmt . This directory would be scanned for func LocalPrintln and then build a view for it.</p><p>Pretty straightforward but this approach was pretty dumb.</p><p>Dumb but also really really fast. No structural information is needed to be remembered so parsing is as simple as a read call with start and end indexes. We don’t need to know anything; not its return type, not its parameters, nothing.</p><h4><strong>The Drawbacks</strong></h4><p>This might be an obvious one to the observant eye but the biggest one is the lack of relationship knowledge between structures. This method isn’t entirely useful for things like datatypes that call methods because then we’d have to track variable declaration and assignments and understand when they were created and/or destroyed and understand their scope and so on.</p><p>A very hard problem indeed.</p><p>The honourable mention of this drawback I guess would be the fact that you can’t even think of expanding… I guess… stacked method calls. Unpacking something like value.Call().To().Me() would be impossible without a complete overhaul. Never mind things like when a function call is passed in as a parameter to a function.</p><p>So this caused the first drastic need for a rewrite as I soon discovered that a lot of Go programs use method calls almost as their bread and butter.</p><p>So, on to V2</p><h3>Byfrost V2 — Formalizing this Bad Boi</h3><p>The conclusion drawn? Structure! Structure is the backbone of intelligent indexing.</p><p>Gone with the scrappiness of glorified text files and onwards with a full blown (not really) compiler! Yeah! I’m a compiler developer now bois!!</p><p>But jokes aside, I actually had to dig into the intricacies of compilation and structuring tokens and abstract syntax trees in a way that preserved relationship info..</p><p>So let’s see what that looks like and talk about a few of my new structures.</p><h4>The Env</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*_oC8pNq6ctnu_DBZudfPmA.png" /></figure><p>A lot bigger than I thought the image would be but this should give a good idea of what I was going for. Each package in V2 has this structure:</p><ul><li>Package is the package name</li><li>Package path is its absolute path from root</li><li>IDRegistry is just a quicker lookup for symbols in this package with the key being the ID and the value being what type it is to speed up searching. So for example, main would have its value is Function .</li><li>ImportList is a list of all the imports in this package.</li><li>Functions is all the functions in this package.</li><li>Structs are all the structs in this package (the Struct struct has Function members to support their methods).</li><li>GlobalVars are all the global variables in this function.</li></ul><p>This is the basic idea behind V2.</p><h4>The Drawback</h4><p>This one was the best attempt thus far and probably closest to the “correct” version of this tool. It indexes everything from function imports to methods. Most of my issues, I now assume, stem from my lack of understanding as to how Go compiles.</p><p>Unlike C that compiles from top to bottom (you can’t use anything unless its been declared <strong>above</strong> the place its being used physically in the file for old-school optimization reasons), Go and many modern languages have an “open season” policy where things can be declared anywhere and used anywhere provided they exist somewhere. Everything, Everywhere, All at Once/I couldn’t help myself.</p><p>This led to a lot of loops and source file reading to first read in all the type s and then all functions and then all global variables to ensure everything that needed things were always avaliable when needed.</p><p>A side effect of this is that on reasonably small projects, ByFrost could show you everything, but on large projects, scanning the codebase takes forever and this tool becomes completely unusable because it just halted.</p><p>Now, there’s obvious optimizations to this approach I only thought of after the fact, maybe scan in one direction and when things are declared, cache them until their definition is found and so on but that just patched over the fundamental misunderstanding of Go’s compilation that I suspect would’ve eventually brought me back to a similar issue in some other way or form.</p><h3>What’s Next? ByFrost V3 — (re)Introducing By(C?)Frost</h3><p>So that’s the first two versions. The code’s a spaghetti pile of garbage that might be tricky to follow but I wanted to show you all how far I got (and also to prove that this isn’t vapourware of course).</p><p>There’s compilation instructions so you can try it out.</p><p>So, what am I doing next? Well, I’m still working on ByFrost. I might change its name. I’ve decided to make it work for C instead and possibly write it in C as well.</p><p>The real aim I was going for with ByFrost was an eventual “timeless debugging” experience in a visual UI. The idea being seamless traversal and inspection of code execution as it happened. Though similar, I’m not aiming for a binary analysis tool, this will be strictly for development as you’d have to have the source code you’re inspecting readily available.</p><h4>The Big Issues with Starting at Go</h4><p>This is a big reason as to why I’m dropping Go is that it’s a really complicated language. For this type of analysis I’m aiming to achieve, a direct mapping of the executable machine code to the source code has to be accurate and relatively fast to extrapolate.</p><p>C is in that beautiful realm where there are direct Assembly-equivalent constructs for C structures and concepts; in short, a good C/Assembly programmer can look at C and have a very good idea of what its ASM output will look like (optimizations notwithstanding) and vice versa.</p><h3>Check out the Codebase</h3><p>So that’s what I’ll be doing. Starting over in C. Suck a bit but I know what I need to do now.</p><p>As for how to run the code; let’s get into it.</p><h4>How to Run ByFrost</h4><p>You’ll need two terminals.</p><h4>Running the backend</h4><p>It’s pretty straightforward. Upon no function arguments you’ll get the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gF4gYTe1Ih7VFEuS1Nikw.png" /></figure><p>An example execution will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*bcQeKFCJnf3xjhMmj_YaxQ.png" /></figure><p>Will run this current project.</p><h4><strong>NOTE: your project as its named in your go.mod file has to match the name of the directory its currently in. I didn’t bother to make this dynamic because I’m lazy.</strong></h4><p>You’’ll then see a bunch of printouts I neglected to delete that I once used for debugging; ignore these.</p><p>Next go to the web directory and under byfrost-frontend , execute the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*DdoeCGPKjZiRyZP-1IQUyg.png" /></figure><p>Finally, visit localhost:4200/indexer and you should see a screen similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZeoUpZhB9_AGWfAMutIsA.png" /><figcaption>Source code for ByFrostV1</figcaption></figure><p>Note that only names highlighted in yellow and aqua-blue can be clicked on and expanded. Native package imports aren’t expandable, only local packages.</p><p>Once expanded, click on the labels under Visible on the right as they apppear and see how it feels.</p><p>You can give it a spin here: <a href="https://github.com/AlysonBee/ByfrostV1">https://github.com/AlysonBee/ByfrostV1</a></p><p>Until ByFrost returns!</p><p>Alyson</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42508dbaaf6f" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/byfrost-in-development-releasing-the-source-code-42508dbaaf6f">ByFrost in Development — Releasing the Source Code</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ByFrost in Development —Three Steps Back and One Step Forward (Update Article)]]></title>
            <link>https://itnext.io/byfrost-in-development-three-steps-back-and-one-step-forward-update-article-3a522b70912e?source=rss-c976df4e1e52------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a522b70912e</guid>
            <category><![CDATA[programming-tools]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[AlysonN]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 19:58:04 GMT</pubDate>
            <atom:updated>2022-09-21T14:11:24.393Z</atom:updated>
            <content:encoded><![CDATA[<p>Progress but also setbacks but mostly setbacks and a bit of progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pX2AxY-ueWeARSbimksBA.png" /><figcaption>A much easier experience</figcaption></figure><p>But first… progress update:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FbjwlMocVZ4s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DbjwlMocVZ4s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FbjwlMocVZ4s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/038bf991762ade1ae8b2bd989aea696c/href">https://medium.com/media/038bf991762ade1ae8b2bd989aea696c/href</a></iframe><p><strong>NOTE: This article is just an update on Byfrost’s progress as opposed to the architectural stuff and changes I usually post about which I’ll post about soon. I just got a bit exciteable with this progress and couldn’t help but write about it 😶.</strong></p><p>So, I’ve been coding Byfrost for a few months at this point and all these months later, I have to conclude that, wow… it’s kinda incredibly difficult. I initially started this project to build myself a tool that would make indexing any codebase I came across a UI dream but the further I get, the longer the road ahead to a V1 seems to get. Every time I add a new thing it seems to open up like nine more holes; adding dynamic camera movement when expanding a function introduced the need to go back up the callstack, that then introduced the need for a sort of helper nav bar that would have a display of everything so you could hop to it from anywhere, that now introduces the need to have that side panel navigation tied to backclicks as using the mouse gets exhausting on a trackpad and so on.</p><p>I guess the real problem is reaching a point where it’s comforably usable and I can get really productive with it. Right now, not being able to expand class methods and submethods (the this.that().another().before() I don’t know what these are called) hinders this a lot because Go projects are riddled with these. Starting with C would’ve probably been a safer bet but hindsight.</p><p>The thing that makes this so hard I think is that I find myself writing a huge chunk of Go’s compiler frontend and then having to represent it in a sort of “flat” structure as opposed to an AST while retaining its heirarchical structure. This idea’s ran rings around my brain.</p><p>Anyway, this is just a “road so far” to give an update on the progress of this project. Everything added to from the last article is mainly UI stuff and nothing particularly tied to indexing so I won’t really go into anything this post.</p><h4>Okay… let’s try this again…</h4><p>For now, there’s at least 4 things I wanna check off my list before feeling confident in a V1. I’m sure this time. I know, I know, I’ve said this before but this time I got it!</p><p>These are:</p><ul><li><strong>1 Degree struct/method dereferencing</strong> — the 1-degree part is really important. It turns out expanding one of these function.functionA().funcitonB() is kinda really hard and I haven’t come up with a comfortable way which might need a massive overhaul so for now, this’ll take a back seat. 1 degree specifically means something like os.File</li><li><strong>Function and Struct Info — </strong>You might’ve noticed that Function goes here (someday) placeholder. Well, that’s where info on things like a struct you’ve currently clicked on will go. No point in expanding out a struct in a graph as it isn’t necessarily part of control flow, but it’s a point of interest.</li><li>(<strong>Nice to have) Expansion of system methods — </strong>currently only packages relative to the project’s root are dereferenced. Expanding fmt and os and log isn’t supported. This one’s not bad because all it entails is doing to Go’s native library directory what’s already being done ot the relative project directory. My only concern is the noise this might add. At the very least, I never need to expand out system methods and functions.</li><li><strong>Mapping</strong> — ah yes, these pesky mapping blocks I just can’t seem to get a grasp on no matter how hard I try. This still clearly needs to be addressed although this problem is more annoying than difficult and I’m happy to push it own the queue until the above is sorted.</li></ul><p>I think that should be everything for now.</p><p>All that other stuff like making it an Electron app or a plugin is just too far off right now as the lexer/parser’s taken up all my energy and time and is giving me endless amounts of trouble.</p><p>The goal right now is to get to something that’s intuitively useful to use. Unfortunately that involves implementing a large part of the language itself. I’d find myself experimenting with it and just forgetting that some things aren’t clickable and it’d totally kill my immersion.</p><p>I also think that after Go, I’ll be in a better position to create a mandate of sorts for integrating new languages. The absence of an AST being generated after parsing is a pretty interesting problem I think only really needs to be solved once and then can be replicated.</p><h4>If You’d Like to Try It Out</h4><p>Also, I’m experimenting with testing this application I’m making and inviting others to sign up to try it out. There’s a few collaborative features I want to experiment with; things like causal analysis features to help with live debugging. I think this could be really valuable to overall workflow. If you’re keen to, it’d be great to have some early users to give this a go. The first version will just be a callstack visualizer. If that sounds like something you reckon would make your life a bit easier, feel free to drop your email in <a href="https://docs.google.com/forms/d/e/1FAIpQLSc1CMPgolrYY7tmdXc2UQaXll-l2s_9z8oKKMEgjLrSe1gpCQ/viewform">this Google form</a>.</p><p>Alright, that’s all.</p><p>Till my next update sometime before the heat death of the universe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a522b70912e" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/byfrost-in-development-three-steps-back-and-one-step-forward-update-article-3a522b70912e">ByFrost in Development —Three Steps Back and One Step Forward (Update Article)</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Byfrost in Development 4 (or 3, I forget)— It’s Kinda Sorta Coming Together]]></title>
            <link>https://itnext.io/byfrost-in-development-4-or-3-i-forget-its-kinda-sorta-coming-together-273f498f8dfb?source=rss-c976df4e1e52------2</link>
            <guid isPermaLink="false">https://medium.com/p/273f498f8dfb</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ide]]></category>
            <dc:creator><![CDATA[AlysonN]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 20:25:14 GMT</pubDate>
            <atom:updated>2022-08-30T07:01:30.410Z</atom:updated>
            <content:encoded><![CDATA[<h3>Byfrost in Development 4(or 3, I forget) — It’s Kinda Sorta Coming Together</h3><p>It’s starting to look like an actual thing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5_AgfeDiD3Zsj42XtlymQ.png" /></figure><p>We’re not quite there yet but it’s starting to look pretty damn good. The graph logic is in need of some tweaking as well as some limitations although I think for now, it’s safe to leave it alone and resort to gathering data on how users navigate codebases with this in the first place to determine these limits. When I say limits I mean things like how many functions can be expanded from a single function at a time, if main calls 8 different functions, should those all be expandable? Should those branches all be collapsed if it becomes clear a user’s decided to head down a certain path, should they be cached so that they can be expanded back to their previous state should a user start down one path only to change their minds and head down another? That sort of thing.</p><p>Making a great codebase navigation experience is turning out to be quite the tricky problem to make simple.</p><p>So for this update, I’ll be leaving graphing aside for now as that’s an ongoing internal debate and focus on the final big change; actually porting a language and making this thing a usable V1.</p><p>Before that, a quick stock take on the road so far.</p><p>As always, a demo video:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkbyVEODm7SQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkbyVEODm7SQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkbyVEODm7SQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/62c25029ec11249c95ccdb21e3668175/href">https://medium.com/media/62c25029ec11249c95ccdb21e3668175/href</a></iframe><h3>How Are We Doing?</h3><p>Here’s a short list of a few changes I impulsively made in a possible state of rage and frustration:</p><ul><li><strong>Colour scheme</strong> — The first is the colour scheme. Like in the screenshot and demo above, I’ve decided to make everything completely black primarily because it was late one night and my retinas were on fire so I made it all dark mode and it was a lot easier to work with. This will be customisable though. It wasn’t too hard to do and I like this aesthetic because Vim is better than Nano (don’t “@” me though).</li><li><strong>Crossing lines </strong>— This is one of the things I’ll be attempting to fix but currently struggling to do so efficiently. The method I have now doesn’t scale at all so that’ll have to be addressed. I suspect I’ll be able to reduce the amount of noise caused by at least a limited amount of crossing lines but getting rid of them entirely seems unlikely. Dare I say it, this problem’s just too hard for me.</li></ul><p>And next, a list of drastic changes I decided to make going forward:</p><ul><li><strong>Porting away from Angular </strong>— Originally I started with Angular as I was new to frontend and JavaScript/TypeScript and it being the framework of my day job’s frontend engineering core, I figured it’d be a great way to start; I’d be able to pick up experience at work and be able to get help on things I got stuck with but I feel like Angular’s becoming a liability. All the benefits I was hoping to gain from it aren’t shining through at all. I can’t use directives or bindings and the only thing I’m making use of is an ngFor. Installing libraries with all its version mismatching is too much of a hassle (though this is unclear as to whether ths is actually just a JavaScript thing) and I’ve had to come up with my own workarounds for a lot of things I was hoping Angular would just do for me; Google’s code-prettify being a betrayal I’ll never forget. I’m currently learning VueJS as I’ve heard great things about it but I also don’t know what I don’t know but if it ends up being even a little easier for this project than Angular, then I’m all for it, if not, I learnt a new frontend framework for my skillset.</li><li><strong>Making an Electron Desktop App </strong>— This one’s mainly come from trying to quell an inconvenience I noticed when trying to work with developing this thing and also making sure I got to replay the chorus to Way of Life from Persona 3 Portable that was playing on YouTube a few hundred or so times. The goal to make this a plugin feels quite far away considering all I need to still get to, having this in the browser and having to rotate between the tabs I need to use (like YouTube) and then find this tab and rotate back to my IDE feels a bit untidy, especially because I have like a million tabs open at any point. Separating this out of the browser into something else not in the browser is an easy hack for now.</li><li><strong>Adding a Menu</strong> — I need a UI for selecting things like entrypoints of where to start indexing from and where to set the root path of the project before starting as well as a way to save state as, right now, refreshing the browser erases everything you’ve done.</li></ul><p>I do wonder if I should’ve put a little more work into planning all this out now that I’m actually here. I’ve had to do a lot of backtracking and refactoring over the past few weeks that’s set back all my optimstic timelines by a lot I reckon.</p><p>I wonder how bad it is that I can’t tell what “a lot” means.</p><p>But let’s talk about the next big addition. I think after this final piece, a lot of what I’ll be doing will be cleaning up what I have. I don’t imagine I’ll drop a V1 already ported to Vue.</p><h3>Porting Go — The Tree-Sitter Library</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3lbhcAV-IqAwGw_dCRgcg.png" /><figcaption>check it out at <a href="https://tree-sitter.github.io/tree-sitter/">https://tree-sitter.github.io/tree-sitter/</a></figcaption></figure><p>So, for my first trick, I will be porting Golang and also designing a language porting library of sorts to make it easier for anyone else to port their language to this indexer. Now, this is a pretty bold claim to make considering that this itself has the potential to be its own separate large undertaking but I’m happy to burn that bridge once I’ve crossed it.</p><p>But on to things a little more immediate; what exactly is this Tree-Sitter I’ve advertised above?</p><p>Well, it’s a C API for lexing and parsing various languages and generating an abstract syntax tree for them. A perfect fit for Byfrost as this is the exact kind of problem I’m having. This is gonna be the new backend for language parsing — somehow. Though history’s taught me I should probably be a bit more deliberate about how I go about planning complicated things like this.</p><p>As it stands, everything I’ve been using up to this point isn’t gonna work so well. I have a hardcoded a C lexer and parser that’s barely working which I’ve been using in my demoes up to this point but now it’s time to get serious and make something real that I can use on a real, functioning codebase.</p><p>That’s what I’ll be up to for the next few weeks I suppose.</p><h3>At Current Time…</h3><p>Adding this part in retrospect as some time’s passed since I started writing this.</p><p>I was able to get a user test done and added extra functionality from that experience; one being highligting for all the “clickable” things. Tt seemed finding things wasn’t as intutivive as I thought it would be without some sort of “prompt”, at least not in all cases. I’m debating this being togglable by pressing a hotkey like CTRL or something.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bybIqZtIV9iN7mHIplxSxg.png" /><figcaption>Link highlighting</figcaption></figure><p>The second thing I concluded is that I need to put extra work into my code block positioning. Doing this well is turning out ot be incredibly difficult. Determining where blocks go once you expand a prompt’s been really complicated to get right and calculating the collision of each block’s running rings around me. I’ll be doing this alongside porting Go as I suspect I’ll be at this for a while.</p><p>An example of what this looks like would be something like;</p><p>This in one run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_hk0GezpI2sjQo5oFGoYDA.png" /><figcaption>Best case positioning</figcaption></figure><p>But then things go haywire when a larger block already exists:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJJEkYR7ZLJkce1SiQmfpA.png" /><figcaption>Worst case positioning</figcaption></figure><p>So I’ll continue polishing up positioning for a while.</p><h3>Interested in trying Byfrost out?</h3><p>It’s been a while since I announced this project and there seems to be interested in y’all trying it out but I wanted to get a feel for those of you interested in giving it a go. Call it a “customer survey” if you will. I forgot you could just make Google forms for this sorta thing.</p><p>If you are interested in formalising your… err… place in line, I’ve made a short Google form for you to gimme your deets if you’re down for Byfrost on launch day. It’ll also help me decide how to think about language porting. I suspect that’ll be an ongoing problem when this is finally ready for primetime.</p><p>You can check it out <a href="https://docs.google.com/forms/d/e/1FAIpQLSc1CMPgolrYY7tmdXc2UQaXll-l2s_9z8oKKMEgjLrSe1gpCQ/viewform">here</a>,</p><p>Anyway, that’s all for now.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=273f498f8dfb" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/byfrost-in-development-4-or-3-i-forget-its-kinda-sorta-coming-together-273f498f8dfb">Byfrost in Development 4 (or 3, I forget)— It’s Kinda Sorta Coming Together</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Byfrost in Development 2— Let’s Talk About Pathing]]></title>
            <link>https://itnext.io/byfrost-in-development-2-lets-talk-about-pathing-ba3ce67686db?source=rss-c976df4e1e52------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba3ce67686db</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[pathfinding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[AlysonN]]></dc:creator>
            <pubDate>Tue, 02 Aug 2022 19:54:37 GMT</pubDate>
            <atom:updated>2022-08-03T13:57:42.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>Byfrost in Development (sort of) — Let’s Talk About Pathing</h3><p>Sweet Jeebus do I hate pathing problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30_OOfxrtjsl66NwggrB9Q.jpeg" /><figcaption>Why can’t this thing just be done already…</figcaption></figure><p>NOTE: This is a follow up article to my previous update: <a href="https://itnext.io/byfrost-in-development-1-an-indexing-graph-b696282c734d">Byfrost Source Code Visualizer in Development 1 — An Indexing Graph </a>. Trust me, the backstory matters.</p><p>It’s funny how I set out to build the best indexer out there for programming languages to improve engineering productivity and be hailed as the one true second coming of Grace Hopper only to then be smacked in the face with putting myself through a Become Less Garbage at Frontend Engineering 101 course over the past few weeks. Hubris is a terrible thing indeed 🙈.</p><p>Putting it shortly; I haven’t indexed in weeks and I’m kinda getting tearfully annoyed. 😭</p><p>Good friends of mine have started to notice this too; trolling me with a “hey, let’s promote Alyson to Frontend Engineer, she’s doing so much design stuff, she’d be pefect for it.” Dammit, that’s not the point of all my hard work Jonathan! Look! Look at my indexing!! Sure, it doesn’t work!! I need to get the UI work done but look!!! LOOOOK!!!</p><p>Dear god, please don’t move me to frontend…</p><p>And with that undignified intro out of the way, let’s get into it.</p><h3>Let’s talk about Pathing</h3><p>Pathing is a class of comupter science problems most commonly used in robotics that entails finding an efficient path from point A to point B. The path between point A and B is littered with obstacles and the idea is to get your… err… self-driving car from point A to B with the most efficient routing arund all obstacles possible. This is what we’ll be talking about today. Self-driving car — I mean efficient pathing.</p><p>See, I think Teslas are great but I’m more of a Comma AI gal myself (please give me a job 🥺, I promise I’m good).</p><p>The placing of function blocks on the UI is a pretty obvious pathing problem I was kinda hoping a JS library would be able to just solve but I can’t keep assuming this I guess. I mean, I guess that’s also a good thing if we’re gonna be all optimistic and positive about misfortune; post release of this tool, I’m gonna be adding a bunch of features to this which will probably force me to have as much control over everything as possible so let’s code a positioning system.</p><p>But let’s look at what this week’s progress looks like:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-oJZ1Q6xdTk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-oJZ1Q6xdTk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-oJZ1Q6xdTk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5daf102ece503154a0a401ae044d216a/href">https://medium.com/media/5daf102ece503154a0a401ae044d216a/href</a></iframe><p>The version above isn’t really clever in any way. It’s just a simple flex-decoration:row styling on a DIV which makes all the DIVs align themselves in a somewhat automated and unpredictable way. Only problem is that the draw line library doesn’t see those DIVs as having changed or shifted so that won’t work, tragically (really was hoping for that easy win). But on the bright side, this was good for morale because I can tangibly see this working incredibly well! And my morale is suffering under the weight of all the extra “stuff” I have to keep adding in for the UI. I haven’t even started porting Go yet🥲.</p><p>And now with that artificial progress out of the way, let’s actually solve this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*TV_RaC8WhvZKj_hEdpGJ3g.jpeg" /><figcaption>I just wanted to work on language problems…</figcaption></figure><h4>The Problem</h4><p>So what exactly is the problem?</p><p>Well, we need to be able to cleverly place each code display panel on the UI in a specific pattern that makes them easy to read and that also never cross each other. Crossing can make things quite convoluted and complicated to read the more displays get added and the more lines between those displays are drawn.</p><p>So not this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fS5Q_q7D9GJQsQjberGCxw.png" /><figcaption>The idea being that the order of expanded panels mirrors the top-to-bottom that they appear like in the function. So <strong>helloworld</strong> would be “above” <strong>read_file</strong></figcaption></figure><p>Along with the crossing wires, as blocks are expanded, there won’t be any dynamic shifting of already generated blocks. This one I actually got from feedback I picked up from Reddit and a few other engineers I talked to about this. As more blocks are added, previous blocks already generated won’t be shifted to make space for new ones. It’s kinda disorienting.</p><p>So not this either:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKXuG0z8VQSc%3Fstart%3D11%26feature%3Doembed%26start%3D11&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKXuG0z8VQSc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKXuG0z8VQSc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b62b20b9ab865f600304847582af7c5e/href">https://medium.com/media/b62b20b9ab865f600304847582af7c5e/href</a></iframe><p>Like the styling, pathing and block layering will be controlled by the backend. Each body of code will have its coordinates determined for it in a sort of hypothetical grid managed in memory before being sent to the frontend. The reason for managing it in the backend is so that the positioning of displays is strictly controlled; related code blocks are grouped closer together than unrelated ones. This type of logic requires direct effort on my part of somekind to establish the rrelationships between DIVs, no matter how automated any library I use may be. <a href="https://itnext.io/byfrost-in-development-1-an-indexing-graph-b696282c734d">It’s similar to the ID problem I had with expanding the correct function calls</a>. This is especially because the DIVs in the frontend aren’t related to each other in any frontend sense (i.e DIVs have no children etc.) and, so far, relational information is controled by the backend (this will make sense if you read the <strong>Approach 3 </strong>sub heading in the previous ByFrost development article you can find <a href="https://itnext.io/byfrost-in-development-1-an-indexing-graph-b696282c734d">here</a>… I’m not kidding, you really should go read the previous installment of this tech blog update if you haven’t. I think it’s pretty good… okay it’s alright… I mean.. it’s not terrible).</p><p>A block structure will look something like this:</p><pre>type DisplayCoordinates struct {<br>  Name   string<br>  XAxis  int<br>  YAxis  int<br>  Height int<br>  Width  int<br>}</pre><p>This struct will then be attached to each function body before being sent to the frontend.</p><ul><li>New blocks that become added to this hypothetical grid become the new “obstacles” for our pathfinding algorithm to dart around. It shouldn’t be intense as blocks unrelated to each other will actively steer clear of one another’s paths.</li><li>This might get expensive for really large codebases being indexed so I’m hoping this is idea of a grid in the backend might just be a debug thing for myself that I can just stop using eventually when I’m certain things work.</li><li>The distance of blocks in this backend grid will correspond to the pixel position values of the divs in the frontend (with some extra constant pixel values added to each because… safety).</li></ul><p>I’ll go into greater detail in the <strong>The Algorithm</strong> section.</p><p>With the rules of engagement sorted, let’s go into how this is gonna be done. Consider this a public design doc because as I’m writing this, it’s becoming more and more clear to me that I have no idea what I’m gonna do to handle this right now. Last actual grid project I did similar to this was that insufferable Zappy project at 42. Damn, I really wish I could do this next part in C…</p><p>THAT WAS A JOKE!!! Probably… my mental state is collapsing/send help.</p><h3>The Algorithm</h3><p>I suspect I actually am gonna make a debugger that I can use to visualise how things look in the backend grid before new panels are sent to the frontend. I’m losing a bit of confidence just thinking about trying to fly blind on this thing so that’ll be included in this brief design too.</p><p>I’ll be doing two things.</p><ul><li>Modifying each function’s… err… <em>metadata (?) </em>to contain its height and width. The height and width are determined by the number of characters “across” on a function that expand out the furthest and by the number of newlines in a block respectively. Example:</li></ul><pre>           width: 36<br>height:3 |------------------------------------|<br>-         char hello(world) {                 |<br>-            return this_is_a_long_function() |<br>-         }</pre><p>In this example this_is_a_long_function() expands out the furtherst and not the function definition.</p><ul><li>Have a separate dynamic 2 dimensional debug grid. This grid will solely exist to assist with validating the correctness of the position of function blocks as they will appear when sent to the frontend. This service will have to have an interactive debugger built into it so I can see what I’m doing. Following on from the “main() expanding with read_file()”, that call stack would look like this for my debugging (very unrealistic widths but you get the idea).</li></ul><pre>[&#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;]<br>[&#39;.&#39;, &#39;.&#39;, &#39;main&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;]<br>[&#39;.&#39;, &#39;.&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;]<br>[&#39;.&#39;, &#39;.&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;]<br>[&#39;.&#39;, &#39;.&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;]<br>[&#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;]<br>[&#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;read_file&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;]<br>[&#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;]<br>[&#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;.&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;, &#39;X&#39;]</pre><p>The positioning of blocks in the grid will determine what positional values each function DIV will have in the frontend. For example, if a function is forced to start at.. I don’t know x:728,y:450 , this will end up translating to a DIV position of left:800px, top:500 or something; I don’t know how this scales yet so this is just an estimation.</p><p>The algo I write will be bias to expanding from left to right, matching how we read things in English. Also, the further outwards our functions expand, blocks will start to move diagonal right down in an attempt to keep things in one view as much as possible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pud6vVzjuYJtEgmV96W-g.png" /><figcaption>Everything arching downwards as oppsed ot completely across</figcaption></figure><p>This feels nice to read. Having things arch just a little bit not only looks sorta cool, it allows us to hold a lot of information on a single screen. As opposed to if it just went horizontally outward.</p><p>When more than one path is being expanded, the same rule will apply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFVVLw3JaeMkd6fauSxdkQ.png" /><figcaption><strong>Code path 1 </strong>expands in one direction, <strong>Code path 2</strong> starts elswewhere out of the way of<strong> Code path 1’</strong>s flow</figcaption></figure><p>This will require a bit of messing with to get working well and I’ll probably be trialing and erroring this bad boi for many nights to come.</p><p>I suspect I’ll have to determine a lot of the controlling of the UI’s placed elements manually. I also suspect the algo parameters I have; for both arching the displays and ensuring the path lines don’t cross, might be quite strict for some out-of-the-box library or system to conform to without some work but that’s okay, probably.</p><p>Having said that lats bit, there’s one more honourable mention I’d like to add that I found out about midway through penning this piece.</p><h3>D3.js: Data Driven Document</h3><p>A friend of mine alerted me to this library. It’s good for making graphs. I’ve decided to try this out to see if it makes my life even a tiny bit easier. It also has some pretty cool effect too (kinda wanna give off a cool futuristic vibe to users of this thing so why not 😁). This is the next library I’ll be digging into to see if it can give me what I need to make a magically beautiful UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X2clFO-GC-90T3eQ3QLr1g.png" /><figcaption>It’s got a pretty landing page too! Check it out <a href="https://d3js.org/">here</a></figcaption></figure><p>There’s not much about this approach that I can add here as I just found out about this but I’ll talk about it when I eventually implement something nice.</p><h3>We’re Almost There!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*u_qj70MB3BZa6JuA8z0ylQ.gif" /><figcaption>A premature victory dance!!</figcaption></figure><p>That’s all I got for this last update. I’m far better and faster at writing language tools than I am at this UI stuff and because of this, I’d <em>like</em> to assume that all the silly frontend shenanigans are over after this final big update. Because once this is done, all I need to do is port Go and that’s a walk in the park after the wild rabbit hole Angular pushed me down.</p><p>That’ll finally finally bring me to shipping something for you guys to try out! We’re almost there but today’s not that day!</p><p>Till next time!</p><p>Nope, still no links. But they’re coming soon! I promise!!</p><p>Alyson</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba3ce67686db" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/byfrost-in-development-2-lets-talk-about-pathing-ba3ce67686db">Byfrost in Development 2— Let’s Talk About Pathing</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Byfrost Source Code Visualizer in Development 1— An Indexing Graph]]></title>
            <link>https://itnext.io/byfrost-in-development-1-an-indexing-graph-b696282c734d?source=rss-c976df4e1e52------2</link>
            <guid isPermaLink="false">https://medium.com/p/b696282c734d</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[AlysonN]]></dc:creator>
            <pubDate>Sun, 24 Jul 2022 11:47:58 GMT</pubDate>
            <atom:updated>2022-07-25T14:40:20.509Z</atom:updated>
            <content:encoded><![CDATA[<p>This title could be better but this does have a lot to do with graphs so it’s at least not false advertising.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kxqucvFtbdWUU3v6z5N-w.jpeg" /><figcaption>But first, a picture of a Bifrost-looking thing!</figcaption></figure><p>This follows on from my initial article where I announced my source code path visualiser here; <a href="https://itnext.io/introducing-byfrost-a-source-code-path-visualizer-2d64002d1f9a">Introducing Byfrost-A Source Code Path Visualizer</a>.</p><p>So Byfrost’s development has finally kicked off to a lot of fanfare and unearned praised showered upon yours truly across Reddit and right here on Medium! I love the excitement around this tool and so I figured I’d keep you all updated with the harrowing, palpitation-inducing tragedies of trying to build an indexer from scratch. So sit back, relax and peer behind the curtain and in absolutely no time, you too might have an idea of what contributing to this beautiful nightmare will be when it comes time for the theme park to open.</p><p>So, what have I been up to in the past two weeks since dropping that bombshell? A lot and then suddenly nothing at all and then everything at once! I’m pleased to announce that we’ve got a working backend!! 🎉 The functionality so far:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FqdO5C4I7fbI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqdO5C4I7fbI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FqdO5C4I7fbI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/db41cfac2d52be0d801f9188709714dc/href">https://medium.com/media/db41cfac2d52be0d801f9188709714dc/href</a></iframe><p>UI needs a lot of positioning work but the core is up and running!</p><p>Before we hop into the nitty gritties, let’s go over some backpeldles quick: I won’t be supporting C first after all. I said this a bit in what I hesitate to call Q&amp;As on Reddit that this tool would support C as a first language and now I’ve decided that I will indeed not be doing that after all. 🤔. It turns out C is a lot harder to parse than I originally thought. It’s deceptive because the lack of structures made me assume this would be easy to do but that was a lie.</p><p>Another is that this would be a plugin. Yes and also no. It’ll be a web app but also a plugin but also a web app because I kinda need this immediately and I haven’t learnt plugin development. But you’ll be able to pick your poison someday.</p><p>Okay let’s get started!</p><h4>What I’ll be discussing in today’s update</h4><p>I’ve become extremely productive since intially announcing this little project that an insane amount of ground has been covered. Because of this, I’ll be keeping things as “overview” as possible to get the ideas behind the indexer across without turning this into a novel.</p><p>I’ll be going over:</p><ul><li>Overall architecture of the indexer — sort of (EDIT: in retrospect I shelved a lot of the detail because this article became too long)</li><li>The indexing approach and relating function labels to respective functions</li></ul><p>The system’s written with a Golang backend and an Angular frontend. Why Go and Angular? It’s the languages of my day job so it’s the only stack I could pick up in a timely manner. I mean I’m a Go engineer by trade and wow, that Angular sure did a number on my will to live lemme tell ya. Though I made use of an Angular frontend, I accidentally made my frontend rendering structures framework-agnostic, mainly because I couldn’t get a lot of HTML on-the-fly rendering done with Angular’s many directives and builtin Angular “stuff” packed in. I’ll go into detail about this in the <strong>Approaches</strong> section below.</p><h3>The Frontend — The Battle With Angular</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X86zzdXODaL1Mdyf40iRPQ.jpeg" /><figcaption>It’s as epic as it looks</figcaption></figure><p>Oh boy, did this part kick me in the teeth multiple times. I’m not a frontend engineer at all and had to learn the craft to a somewhat competent degree in a matter of weeks to pull this off and I’m gonna say it; frontend is harder than backend — HOLD ON! LEMME EXPLAIN! PUT THE FRYING PAN DOWN BRIAN!! (That’s probably not your name but I figured I’d freak out all the readers named “Brian”).</p><p>I find frontend akin to telling a painter to paint the Monalisa from scratch and exclusively following instructions you’ve poorly written on murky newspaper while drunk and suffering from fresh heartbreak. I was bewildered by diffiicult most of the simpler looking things ended up being. With on-the-fly large scale HTML rendering, turns out you need a bit of trickery here and there to not spaghetti your code into oblivion.</p><h3>The Approaches</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*aSZreGq5tBsfoxwGHDE48w.jpeg" /><figcaption>…hmmm….</figcaption></figure><p>Here I’ll go over the three approaches I took, why they failed and eventually why the last one was successful. This will cover a lot of the struggles I had with Angular.</p><p><strong>Approach 1: Runtime Component Generation</strong></p><p>The first approach that made intuitive sense to me was make an Angular component that would represent a single code display panel. Something like this;</p><pre>export class ByFrost implements whatever {<br>  ...<br>}</pre><p>And this would hold everything. It would have variables for that would make up a single program panel.</p><p>Something like;</p><pre>let filePath: string = &quot;&lt;a (click)=&quot;openFile()&quot;&gt;main.c&lt;/a&gt;&quot;</pre><pre>let sourceCode: string = &quot;int main(int argc char **argv)\n{\n\t&lt;a (click)=\&quot;newComponent()\&quot;&gt;printf&lt;/a&gt;(\&quot;hello world\&quot;);\n\treturn (0);...</pre><p>The filePath being… well… the file path and the sourceCode … you get the idea.</p><p>Only problem with this approach is that it turns out those directives (the (click)=&quot;openFile&quot; ) and the other one can’t be rendered during runtime like that and are compile-time exclusive niceties. See; those are the Angular “stuff” I mentioned earlier (directives or something). What they do is that they’d bind those a tags to those target functions which would trigger in the background when clicked. openFile would trigger a function called openFile that you specify to trigger when clicked. Same story with printf . For printf a new component that contains its source code would be generated and appended to the original ByFrost component. That was the idea; open the file when the path is clicked; and create a new function component when a function is clicked.</p><p>Super easy. How hard could it be, really?</p><p>Oh the foreshadowing…</p><p>This, my friends, turns out is a <em>very very very veeeeeerryyy</em> hard and is an incredibly bad idea.</p><p>Turns out you can’t actually do this. I discovered after countless hours of crying over this that runtime compilation of those Angular tags/directives/etc really isn’t possible. Not really. And I went all in on this approach; partly because it made me feel like a real compiler engineer and I could vindicate all the years I’ve spent trying to be one. I was even looking into Angular’s Just-in-Time compiler to see if I could force it to compile these at runtime. And I’d have gone into Angular source code to force a fix too (and rendered my entire Angular setup trash as it would break the CLI and everything that makes Angular not terrible) but I stopped and decided to spend the rest of the afternoon watching Top Gun: Maverick in cinema instead. Great movie.</p><p><strong>Approach 2: Using innerHTML for Rendering</strong></p><p>This is close to what I eventually ended up settling on but my first attempts had similar problems. I wasn’t generating new components this time. No, this time, I’d just have a massive list of HTML strings representing code display panels that would output in an Angular ngFor loop.</p><p>This was somewhat of an improvement; things were rendering but I still had the issue of my renders not compiling the Angular functions and tags.</p><p>I was completely at my wits end. After all the fanfare; all the years of struggling to build my indexing tool. Was the road finally over?</p><p><strong>Approach 3: Prepare All Frontend Functionality in the Backend</strong></p><p>This new way of thinking about this came about when talking to another fellow backend engineer. I ran into a few hiccups that I won’t go into too much detail with here as this article’s gonna get pretty long. The approach here consisted of removing the usage of Angular components in the HTML altogether; this was never gonna work because dynamic HTML rendering is an absolute must for this and those never compiled. Removing the Angular “stuff” worked out pretty well actually. The final final problem with this approach was that rendering HTML source code as a super long string and then managing the relationship dynamic between functions and the functions that those parent functions called got messy pretty quickly. I couldn’t get any of the function calls to remember what function their parent was and who they were related to.</p><p>Take this simple example:</p><pre>void first() {<br>   toRepeat();<br>}</pre><pre>void second() {<br>   toRepeat();<br>}</pre><p>Once toRepeat is clicked to be expanded, without a heirarchical structure in the HTML, there was no way to see which function toReturn ‘s call came from. It had no parent. A lost, aimless child, wandering in darkness within darkness…</p><p>However, racking my brain over this final problem, I was hit by a stroke of genius…</p><h3>The Backend — Filesystem, My Dearly Beloved</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*tDV3ofXrMEQKIToZJWta-Q.jpeg" /><figcaption>Ahh… this brings back memories.</figcaption></figure><p>Old-school readers might remember my old <a href="https://github.com/AlysonBee/GoVirtualFilesystem">Go Virtual Filesystem</a> project from about a year ago. That taught me a lot about handling heirarchical relationships in a tree data structure pretty well in Go.</p><p>This was exactly that kind of problem. The bodies of functions were directories and the functions those function bodies called were subdirectories.</p><p>This is how I’d do it. This is how I’d establish relationships between functions and their children function calls.</p><p>With this new paradigm, this program:</p><pre>int  main() {<br>  helloworld(&quot;test&quot;);<br>  read_file(&quot;test2&quot;);<br>}</pre><pre>char  helloworld(char i) {<br>  testing(42);<br>  return &#39;c&#39;;<br>}</pre><pre>int read_file(char *filename) {<br> helloworld(filename[0]);<br> return (0);<br>}</pre><pre>int testing(int i) {<br> return (0);<br>}</pre><p>Would be translated into the following tree structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i0WXRpdCP5cG6Bs56zbYMQ.png" /></figure><p>Each function would have a unique path attached to it denoting that function heirarchy. read_file ‘s unique path would be main.read_file and its call to helloworld would have main.read_file.helloworld as its path and so on.</p><p>The Go structure supporting this functionality would look like this;</p><pre>type Display struct {<br> name    string    //  read_file<br> path    string    //  main.read_file</pre><pre> active    bool    //  when function expands, this is true.<br> rawTokens []*Token</pre><pre>  // Display{<br>  //   name:&quot;hellowworld&quot;, <br>  //   path: &quot;main.read_file.hellowworld&quot;<br>  // ...  }<br>  childDisplays map[string]*Display<br>}</pre><p>The name being the name of current function, like main with the childDisplays holding their own displays for the functions main calls; in our example, the displays for read_file and helloworld . active is used for collapsing logic. When a function is clicked, this value will determine if it’s to be expanded or collapsed. Finally, we have rawTokens . These hold all the tokens in an array that will visually make up the current function and hold UI config information that Angular will interpret to make it pretty.</p><p>rawTokens is built up from the lexer and parsing stages but serve an extra purpose of determining which labels are clickable in the frontend and, in future, will hold styling information for the syntax highlighting I have to build by hand (you’ll see why in a bit). So that’ll be covered in a future article when we go over that.</p><p>With this, each function link held by the pathvalue above will, in the frontend, attach a unique ID to each function label call that, when clicked, would instantly identify exactly which path has been expanded on. This also makes accurate function path collapsing possible too. So when you click on an already expanded function, clicking it again will set active to false and when this happens, a recursive looping of all that current function’s children will be parsed and all set to false as well, triggering Angular to delete them in the UI.</p><p>With that final tweak, this also allows each of the panels to be their own clean, standalone selves and take on the following shape;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*1TF_bAP4fBrPTO5OgO-IoQ.png" /></figure><p>I like this design for each of the function panels because this means that, from a UI perspective, each individual block could be styled without them stepping all over each other. It also makes adding and remove code blocks increidbly easy to do because HTML DIV bodies aren’t related to each other (no nesting of children or anything like that).</p><p>This also makes the frontend framework-agnostic to a large extent. As no Angular-specific structures are being used, this could easily be ported to React or even JQuery (heaven forbid). I didn’t know this would happen when I initially set out but it’s a happy accident. It’ll make styling a lot easier too.</p><p>And that wraps up the road so far. Next I’ll cover some honourable mentions that I wasn’t able to find natural place for in the article.</p><h3>Some Honourable Mentions</h3><p>This ended up being the hardest thing I think I’ve ever done. Frontend’s turning out to be quite a monster and the amount of roadblocks I’ve been running into is quite something.</p><p>For some honourable mentions, I’d like to cover some of those; problems I ran into and strategies I tried to get over them. I’ll also go over the future of integrating new language support and turning all of this from a web app to a plugin.</p><ul><li><strong>Drawing Lines </strong>— this is by far the one thing that splitting up the frontend HTML displays ended benefitting immensely. Initially I was going to use some hacky svg approach of drawing them manually by hand — perhaps calculate where each panel would appear in real time and then draw some choppy line towards it. But using traditional JavaScript with Angular calling the shots is something I still struggle with. Doing simple things like referencing HTML elements with getElementByIdand copying code off of StackOverflow (because of course I did) for targeting the line destinations just never worked. I suspected it was traditional JS steppnig all over Angular. Thankfully there’s a great library called linear-line for Angular that did the trick. Using without the relationship issue of bundling HTML DIVs to parents saved me a lot of suffering. And then there was importing libraries into Angular… kill me now… 💀.</li><li><strong>Syntax Highlighting — </strong>Okay so I’m genuinely offended by this one because this was supposed to be an easy low-hanging fruit; go online download some of that sweet <a href="https://ace.c9.io/">Ace editor </a>action I used for my Go virtual filesystem’s text editor, switch it to readonly and bam, early lunch. Unfortunately not — turns out adding Ace disables all my buttons so clicking on functions no longer expanded anything. Not to worry though, Google has a fancy library called <a href="https://code.google.com/archive/p/google-code-prettify/">Prettify</a> <em>except it’s garbage!</em> Seriously, how is highlighting this hard to do! This didn’t go so well either. Though in all fairness, I’m sure the library works just fine if it’s not be forced into Angular so unceremoniously or something. This time round I kept on running into syntax highlighting issues of my text not changing color and sometimes not “switching on” here and there so screw it. I’m first-principles-ing this bad boi. In C’s case if we think of Vim’s highlighting; datatypes are green, control flow statements are yellow, literals are pink, so I’m making my own syntax highlighting and it’s gonna be a dream to use. I have a spec in the works for how this is gonna work because I have no choice but to get it right for launch day. How hard could it be…</li><li><strong>The Language API</strong> — This is something that’s also gonna need a lot of attention and a some formal spec too. So far, adding languages is very very difficult because they’re all so different. I decided to drop C and focus on Go as it has a native parser library for itself. I thought C would be easier because of its lack of structures but it’s deceptively messy and I couldn’t find an opensource parser I could dismantle for my needs. Plugging in all languages under the sun’s gonna be a monstrous task. It’d be great to get help from compiler developers on this aspect.</li><li><strong>Making it a plugin </strong>— For now, I’ll be keeping it a web app for the first version while polishing up a plugin for VSCode because that’s hard…</li></ul><p>And that’s the long and short for now. I got a lot of work done over the past three weeks and covered way too much ground to be able to unpack all of it in a single article and even still, this article’s easily the longest I’ve ever written.</p><h3>The Roadmap</h3><p>As for what’s left on the roadmap before a first initial alpha release we’ve got:</p><ul><li><strong>Syntax highlighting</strong> — only one theme for now as I flesh out the library and approach to syntax highlighting.</li><li><strong>Go porting </strong>— this tool will only be available for Go when it drops. Go’s the language I use in my daily life and it has parser support. This healthy support will also help in determining a sort of standard for the language API or service or whatever.</li><li><strong>Code panel positioning and sizing</strong> — This is slightly tricky as right now, all panels are seemingly the same size and flow down the page. Making them spread out rightwards in a more “readable” style is the final feature to deliver on Byfrost.</li></ul><p>And that’s all I have for the first Byfrost in Development post.</p><p>I’ll be posting more updates and preparing an alpha to send out for some early testing. If you’re keen to give it a spin, I’ll set up somewhere you can sign-up to give it a Go (see what I did there).</p><p>And of course, a Github repo’s still on the way.</p><p>Chat soon! 👋</p><p>Alyson</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b696282c734d" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/byfrost-in-development-1-an-indexing-graph-b696282c734d">Byfrost Source Code Visualizer in Development 1— An Indexing Graph</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Byfrost-A Source Code Path Visualizer]]></title>
            <link>https://itnext.io/introducing-byfrost-a-source-code-path-visualizer-2d64002d1f9a?source=rss-c976df4e1e52------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d64002d1f9a</guid>
            <category><![CDATA[codebase]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[new-codebase]]></category>
            <dc:creator><![CDATA[AlysonN]]></dc:creator>
            <pubDate>Sun, 03 Jul 2022 15:54:02 GMT</pubDate>
            <atom:updated>2022-07-30T08:06:14.276Z</atom:updated>
            <content:encoded><![CDATA[<p>Okay so the name might change as time goes on but hear me out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGHkpxzlnzwfR6yBG1JgWw.jpeg" /><figcaption>I know, I know. The genericness of these is getting out of hand</figcaption></figure><p>It’s been a long time coming reader. The elusive indexing tool I’ve been attemtping to build for so long is finally upon us. What I hesitate to call It’s a cute little idea I’ve been mulling over for a while and figured it’s high time I finally took a stab at pulling it off. My power level’s risen significantly over the past few months too; my language parsing and compiler skills have improved (probably). How difficult could this really actually be, right?</p><p>So without further ado, I introduce for to you for your appraisal; the Byfrost Indexer!</p><h3>Code Indexing — What is this exactly?</h3><p>I loosely call it this because I can’t think of anything more descriptive. The core project revolves around indexing a codebase; grabbing all its functions, variables and everything that makes up the codebase and organizing it in a conrollable structure of somekind.</p><p>Every IDE does this pretty well — the indexing part I mean; GoLand, VSCode, IntelliJ, Visual Studio among others. Some command line utilities do this incredibly well too, OSX’s <em>ag</em> utility comes to mind. And for most use cases for the everyday developer makin’ their way down town, these tools suffice pretty damn well. I myself perfer to use ag for all codebase searches because I too like to live dangerously, you see.</p><p>Which segues nicely into the crux of the matter and why I’ve been dreaming up the ultimate codebase indexing tool for the most epic developer experience for so very long.</p><h3>Code Indexing — What is yours exactly?</h3><p>The problem goes like this; learning a new codebase and finding where things are is a bit of an artform. From hacking together a bunch of indexing techniques to committing a control flow you’re going down to memory, to hopping between various files in your code editor to get a sense of what a program is doing, things can get pretty out of hand, especially if the code you’re reading is large, undocumented and a bit all over the place.</p><p>So then I had an idea…</p><p>I’m reminded of the pretty great reverse engineering tools and how they go about visualizing the branching flows of binary files with some runtime data on variable information thrown in for great value for money 🌠. This made me wonder; why wasn’t this done for source code files. 🤔? As engineers, we spend a lot more time reading code than writing it and my hacky approach of ag-ing it worked pretty well for me but it got to me quite a bit when I would start out trying to contribute to opensource or when starting out at a new job and understanding the control flow of everything felt like pulling teeth.</p><p>I found a few good tools for this; Sourcetrail being one of them but I wanted something even easier to work with. Something that would make reading code as intuitive and as simple as reading… well… reading a book really. The ultimate reading experience!</p><p>I couldn’t think of why this was a terrible idea so I’ve decided to build my own!</p><h3>Introducing the Byfrost Indexer!!</h3><p>Behold!! The indexer at its finest!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKXuG0z8VQSc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKXuG0z8VQSc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKXuG0z8VQSc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9069b2412f0714d8cc2238d6c678140/href">https://medium.com/media/b9069b2412f0714d8cc2238d6c678140/href</a></iframe><p>So what is Byfrost? My unique spin on the source code indexing experience. I wanted something that both felt cool to use and relatively straightforward to intutiviely understand. I also wanted something I could use with my IDE (I don’t know how this is gonna work yet but as a plugin, this would be pretty sick as an assist).</p><p>So a few core ideas I settled on for this design:</p><ul><li><strong>No files </strong>— The idea is to solely focus on reading the path various functions and data structures as they are used, abstracting everything else in the those files away. But if I want to go to that specific function, there’s a file path and name just above the block of code that will open specific location in your editor when clicked.</li><li><strong>As little extras as possible </strong>— I feel when exploring a codebase, I’m often exploring for a very specific reasons. To make this as intuitive as possible, I decided to keep it to just exploring a code path statically as live tracing for a first version is overkill and kinda sorta really hard. So all that works is being able to read a block of code and clicking on the symbol to expand (like turning the pages of an epic, albeit poorly written novel! 😃)</li><li><strong>Collaboration</strong> — The last detail is keeping to the idea of collaborating (specifically communicating) across multiple engineers. It’s easier to present and talk about a large codebase in collaborative settings like on Google Meets when you’re able to show the flow of a program (and your thought processes) to other engineers.</li></ul><p>The three core ideas above drive my thought process for the first version of my super awesome indexing tool. But also, I wanted to make something that looks and feels super cool to use too. My frontend skills aren’t up to scratch yet but they’re getting there.</p><h3>Okay But Why Byfrost?</h3><p>It’s a Psycho-Pass reference. Trust me, the name will make sense when you see the reference, I promise! It’s a cool reference!</p><p>And that’s it. This is my new new project I’ll be working on for a long while. It’s nowhere near ready for primetime but I wanted to get first impressions on this concept from other developers and get a sense of what y’all think of this kind of codebase reading and indexing approach.</p><p>Yup, see you soon!</p><p>More updates coming soon (probably)!</p><blockquote>EDIT: So I’ve been struggling to make continuation on this article because it has a follow-up but i have no way to link them, per se, so I’ll post a link to the first Byfrost in Development post you can find here: <a href="https://itnext.io/byfrost-in-development-1-an-indexing-graph-b696282c734d">https://itnext.io/byfrost-in-development-1-an-indexing-graph-b696282c734d</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d64002d1f9a" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/introducing-byfrost-a-source-code-path-visualizer-2d64002d1f9a">Introducing Byfrost-A Source Code Path Visualizer</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Play with (Meta)Compilers — Designing an Automated Scanner]]></title>
            <link>https://itnext.io/lets-play-with-meta-compilers-designing-an-automated-scanner-2ffe2e0e609c?source=rss-c976df4e1e52------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ffe2e0e609c</guid>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[compiler-design]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[AlysonN]]></dc:creator>
            <pubDate>Sun, 08 Aug 2021 13:37:53 GMT</pubDate>
            <atom:updated>2021-08-09T09:33:22.209Z</atom:updated>
            <content:encoded><![CDATA[<h3>Let’s Play with (Meta)Compilers — Designing an Automated Scanner</h3><p>and other terrifying things… 😨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*oI2te2d-g8txaOU8vSxN5Q.jpeg" /><figcaption>It’s like making a cake…. but also not really</figcaption></figure><p>What can I tell you reader, where filesystems fail to captivate my imagination, compilers just do it for me. Seriously, I spent most of the entirety of last year attempting to make one. It was a fun project but I ultimately failed because compilers are very much theory heavy and you really need to go into them with a clear and concise plan.</p><p>I didn’t have a clear and concise plan and sorta kinda barely knew what I was saying or doing. This became evident when I finally worked up the courage to visit the r/Compilers subreddit and ask grueling questions I’d been wrestling with and oh boy did that go wrong.</p><p>See reader, compilers are so theoretically dense that when talking about certain things you’re struggling with, you’ll soon realize that speaking in CompSci speak is the best way to truly get by in these here parts. It’s not uncommon you’ll see different bodies of code from multiple compiler developers that look quite different from each other but instantly make sense when spoken about in the lingo to anyone reading them. It’s actually pretty daunting at first; battling with knowing the difference between scanning and parsing and lexing and exactly how the rules of abstract syntax tree generation works for certain languages and grammars, the list of things you’ll inevitably miss is almost endless.</p><p>So naturally I interpreted that as a challenged and decided to try my hand at breaking all of these things down so maybe one day when time travel’s a thing, I’ll send a message to my past self and maybe her first go at it won’t be so traumatic.</p><p>Another important thing I guess is worth mentioning is that my theoretical computer science knowledge was quite hard won in the sense that I was forced to teach this stuff to myself in a vacuum; equal parts because I was afraid of the open internet and asking for stuff and equal parts picking the wrong books to get started with, often starting with some leaps and bounds outside of my foundational skill.</p><p>So, this new new article series (yup, we doing this again!), I’ll be going into the design and implementation of a custom compiler generator I’ve been working on for a few weeks now. What is a compiler generator you ask? Well, it’s like if you fused Lex, Yacc and Protocol Buffers and ended up with something infinitely worse and malformed and probably tastes pretty bad if you spread it on toast, or at least mine will probably be 😄 . We’ll cover this in a little bit, I promise 😅</p><p>All in all, it’s the hardest technical challenge I’ve given myself and talking about it publicly will also help in checking myself and ensuring I grasp this stuff if I can make it make sense and if better compiler developers than I can vet my work.</p><p>And without further ado, let’s get started!</p><h4><strong>What Exactly is a Compiler Generator</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*303_fDrnJJ3FQBCIXjyE0Q.png" /><figcaption>How did I get here again…? 😵</figcaption></figure><p>Before we begin, I found that a glossary of some kind might be valuable. I found myself tripping over terms I’d keep on using without ever getting to explain them in a way that didn’t break the flow of this reasonably dense article. So here’s some helpful terms to know before we get into the meat ‘n potatoes of things.</p><ul><li><strong>Deterministic Finite Automata (DFA) </strong>— This is the science of pattern matching. Conceptually, these are directed graphs with nodes called states. When a string is parsed and checked against a specific DFA’s pattern, with each character in the string that gets evaluated at each point in the DFA, should the current state accept the current character, a new state is traversed towards in the DFA. This process repeats until the input string is exhausted; should the final character of a string not end on an accepting state, the pattern is rejected by the DFA.</li></ul><p>Example DFA:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*uZ1UlbHuS63PQaKGeYmv6A.jpeg" /></figure><p>To give the above DFA as an example, the final state (to the far right with a double circle) is the accepting state. State a is our start state. Our transitions in state a tell us that if our next input is 0 then we stay in state a , if it’s 1 instead, we’ll traverse into state b . Observing this pattern, we can guess that whatever the string ends up being, all acceptable strings end with either 10 or 000. Automata theory’s quite a lot to get through but for this article, this basic understanding will suffice.</p><ul><li><strong>Lex </strong>— this is a tool used for automating scanner generation and was a large inspiration for this project. It too makes use of a specification file for its scanner generator and exclusively generates C code that, when further compiled, creates your tokenizer. You can learn more about it in detail here: <a href="https://en.wikipedia.org/wiki/Lex_(software)">https://en.wikipedia.org/wiki/Lex_(software)</a></li><li><strong>Regex </strong>— A regular expression; this is a format of characters and symbols that specify a string pattern to be searched for. In this project it’s used as a substitute for DFA implementation in code. DFAs can be converted into regular expressions and vice versa.</li><li><strong>Abstract Syntax Trees(ASTs) </strong>— A tree-like structure of tokens laid out in a specific way that demonstrates order of precedence when evaluating the programming language’s semantics (or it’s “meaning”). This won’t be covered but I name drop it now and then 😅.</li></ul><p>The idea behind a compiler generator or <em>metacompiler </em>is the idea of being able to write the specification (or spec) for any kind of language, pass it into a generator and a compiler for that language is created. Pretty cool, right?</p><p>The possibilities for failure are almost endless.</p><p>Our metacompiler project will be divided into three main components which can be worked on in individual pieces as long as each part’s output format matches the next part’s input format. Compilers have this structure already but we’ll be taking it a step further by automating the generation of each of these components.</p><p>The three parts are:</p><ul><li><strong>The Frontend</strong> — The part of the compiler responsible for ingesting source code, verifying the semantic correctness of the tokens according to the spec of the language and sending the output (sometimes as an abstract syntax tree) to the next layer.</li><li><strong>The middleware </strong>— This part is responsible for intermediate code generation; this code is a sort of pseudocode of assembly-like instructions completely unrelated to any real assembly language or architecture. This lets you get an idea of the eventual assembly output and play around with optimizations without committing to an architecture. This step can consist of multiple sub-steps layered on top of each other if the optimization process is complex.</li><li><strong>The Backend</strong> — This is the part where we convert our intermediate code into the target machine’s native assembly for actual execution or further compilation to object code then to an executable, whichever floats your boat.</li></ul><p>This is what we’ll be spending the next couple of months attempting to build.</p><p>Note: some people find the use of the phrase “frontend” for something like a compiler (that seems quite backend-y) to be confusing. The term is sometimes used to describe the “front” part of a large system with multiple layers — just a fun fact I learnt this week at work :D.</p><p>So then, let’s talk about what we’ll be doing first.</p><h4>The Frontend — Let’s Make a Scanner</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*3s1959tbNLd7tXxQXdZf4A.jpeg" /><figcaption>See? It’s funny because… it’s HTML… because frontend… 😶</figcaption></figure><p>So, first thing’s first, the scanner. We’re gonna make a scanner that can take in a spec file and one or more source files and, using the rules we specify in that spec file, tokenize the source code; turning each valid “word” in the language into a single token. If you’re familiar with lex then you might recognize a little bit of what I’m going for here.</p><p>A token can be anything from single character like = or a to a whole string like &quot;hello world&quot;. Each token is classified by two values; its <em>literal value</em> and its <em>type</em>; so the token &quot;hello world&quot; ‘s literal value is &quot;hello world&quot; and its type is that its a STRING or a LITERAL, the token + ‘s value is + and its type is PLUS and so on.</p><p>There are special groups of tokens that are classified as RESERVED . These are words that the language uses specifically for its functionality, features and constructs. Consider the difference in most languages between the words; if , while and for and then the words _x, hello42 and this_is_a_function . The former are often used for functionality (for if statements, while and for loops respectively) while the latter are considered for variables and/or function names. The former tokens would have a single type such as RESERVED or KEYWORD while the latter would be classified as IDENTIFIERS .</p><p>Note: you can sometimes give each keyword its own unique type; such as if having the type of IF and while having the type of WHILE . If later parts of your compiler require this level of clarity, then there’s no harm in it but it’s advisable that all unimportant alphanumeric tokens be left under a single type like ID or IDENTIFIER as they’ll often be subject to the same ruleset despite different naming. I do this a lot out of fear of the ambiguity of merely using KEYWORD for different values that do different things coming back to bite me.</p><p>Now with that brief intro out of the way, let’s talk about the kind of process we’ll be undertaking to automate the process of generating scanners for anything we’d like.</p><p>The approach we’ll be using relies on a concept known as <strong>Table Driven Scanning </strong>in compiler theory.</p><h4>But What is Table Driven Scanning?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*HVgQcEUehiAt7NfhGII7aw.jpeg" /><figcaption>Coffee always tastes better when you’re sitting at a fancy table ☕️ 😁</figcaption></figure><p>Table driven scanners is one of the three common scanner development approaches (the other two being Direct Coded Scanners and Hand Coded Scanners). This approach makes use of three in-memory tables and stores all the info needed to successfully scan a target language in them. This approach is seemingly quite frowned upon because of cache access issues because of all that data in memory but it’s perfect for our needs, though I’ll probably end up paying in some way for this eventually. This approach relies on predetermined tables with all the rules and info needed to parse our target language. Our spec file will be designed to fit into these tables, though a few modifications will be made to make it work a little easier with code and regexing.</p><p>As its name implies, this type of scanning relies on the use of tables; three to be precise; one that stores all the DFAs used to process our language (DFA table), another for pairing token values with their token types (Token table) and one that identifies and classes types of characters in the input (Classifier table); things like a-zA-Z being alphabetic and 0-9 being digits . We’ll throw this last table out for our implementation as it doesn’t need to be a table on its own.</p><p>The basic algorithm for table driven scanning looks something like this:</p><pre>tables = initTables()<br>acceptedStates = stack()</pre><pre>currentToken = &quot;&quot;<br>while c = NextChar(){<br>   if c == EOL<br>      break<br>   <br>   currentToken.append(c)<br>   if tables.DFA_match(currentToken) is true {<br>      push currentToken to acceptedStates<br>   else if tables.DFA_match(currentToken) is false {<br>      if acceptedState is not empty<br>          currentToken = acceptedStates.pop()<br>          c = rollBack() input to last accepted state<br>          break<br>      else<br>          return error</pre><pre>if currentToken in tables.tokenTypes <br>    return token value and token type<br>else<br>    return invalid token error</pre><p>This basically encapsulates the idea behind the concept of table driven scanning; relying on the access of information saved in tables to help our scanner make decisions.</p><p>We’re gonna do this but modify the algorithm a bit to suit our custom needs.</p><h4>Our Heavily Modified Version</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*r8RVqQQxj5X-mm4k19Pdgg.gif" /><figcaption>MODIFICATIONS! HELL YEA!! 💥</figcaption></figure><p>Ours will use the same premise in terms of the loop implementation and rollbacking, except the DFA_table will just be a dictionary of accepting regexes (a regex table, if you will); the key being the regex pattern and the value being the regex pattern’s identifier. We’re cramming the DFA table and the Classifier table into one single better MODIFIED AWESOME Regex table! HELL YEAH!!</p><p>The only additional table we’ll add is a tweaked version of the Regex table with the exception being that this one being designed to work with regexes that use delimited patterns; so a Delim table. This extra table seemed necessary to handle things like regex matching strings and comments; the &quot; at the start of a token alters the rules of regex pattern matching by accepting any and all characters, ignoring all other matching patterns until it sees another &quot; . I made this a separate table because it ended up doing some pretty breaky things when I tried to group it in with other single-token regex patterns.</p><p>And lastly, we’ll add a token table for all the token types.</p><p>And with our three tables decided; regexes, delims and token types, the last piece of the puzzle for our setup is to talk about the implementation I’ll be going for and, of course, what the spec file will look like.</p><h4><strong>The Road So Far</strong></h4><p>I’ll save code implementation for another article as this was quite a lot to unpack but I’ll end here by showing some pseudocode, a working spec file 😃.</p><p><strong>The Pseudocode</strong></p><p>It goes something like this</p><pre>savedTokens = tokenList()<br>tables = tables()<br>sourceCode = &quot;&quot;<br>acceptedState = stack()<br></pre><pre>function scanner() <br>    tables = createFromSpecFile(specFile)<br>    sourecCode = readSourceFiles()<br>    <br>    while sourceCode not at EOF<br>        scan()<br>        </pre><pre>function scan()<br>    currentToken = &quot;&quot;<br>    while c = nextChar()<br>        if c == EOF {<br>           break        <br>        }<br>        currentToken += c<br>        if currentToken in tables.Regex_table<br>           save currentToken and c position in acceptedState<br>        else <br>           if acceptedState not empty<br>              currentToken, c = acceptedState.pop()<br>              break<br>          else<br>              return error</pre><pre>    if currentToken not in tables.Tokentype<br>       return error<br>    else<br>       savedTokens.add(currentToken, tables.Tokentype[currentToken])</pre><pre><br>scanner()</pre><p>So it’s almost an exact copy/paste of the methodology used in table driven scanning anyway but the devil’s in the details of managing tables and working with regexes and functions to simulate DFA traversal but more on those some other time. 😅</p><p>Minus a lot of gory details, my implementation looks like this but in Go.</p><p><strong>The Spec file</strong></p><p>The spec file format that the program intakes is formatted like the ones below.</p><pre># classifiers<br>[classifier tokens go here]<br>%%<br># delims<br>[delim tokens here]<br>%%<br># tokenTypes<br>[and token types here</pre><p>And presto, like magic, we have our spec format ready to go. Let’s take a look at what it looks like if we were to spec the C langauge;</p><pre># Classifier<br><br>alphabet    [_a-zA-Z]<br>digit       [0-9]<br>number      {digit}+<br>newline     %NEWLINE<br>word        {alphabet}({alphabet}|{digit})*<br>symbols     [-+/\*&amp;!\|\{\}=&gt;&lt;:^;,]<br>equ         ([+-/=*!&amp;\|]|((&gt;)?&gt;)|((&lt;)?&lt;))?=<br>left        (&lt;)?&lt;<br>right       (&gt;)?&gt;<br>brackets    [\[\]\(\)]<br>comment     //.*{newline}<br>mcomment    /\*.*\*/<br>float       [0-9]+((\.[0-9]*)|e((\+|-)?[0-9]+))<br>hex         0[xX][a-fA-Z0-9]+<br>string      &quot;.*&quot;<br>char        &#39;[(\&#39;)(\t)(\n)]|(.*)&#39;<br>arrow       -&gt;<br><br>%%<br><br># Delim<br>&#39;     {char}<br>&quot;     {string}<br>//    {comment}<br>/\*   {mcomment}<br><br>%%<br><br># TokenType<br><br>{string}    STRING<br>{number}    INTEGER<br>{word}      ID<br>{char}      CH<br>char        CHAR<br>int         INT<br>long        LONG<br>void        VOID<br>unsigned    UNSIGNED<br>*           STAR<br>...</pre><p>how about x86 assembly (the OSX version anyway)</p><pre># Classifiers</pre><pre>alphabet   [_a-zA-Z]<br>digit      [0-9]<br>number     {digit}+<br>hex        {digit}+h<br>word       {alphabet}({alphabet}|{digit})*<br>label      _{alphabet}({alphabet}|{digit})*:<br>colon      :<br>newline    %NEWLINE<br>comma      ,<br>brackets   [\[\]]<br>space      %SPACE<br>gen_regs   [er][abcd]x<br>small_regs [abcd][lhx]<br>push       push(a)?<br>pop        pop(a)?<br>hex        0[xX][a-fA-F0-9]+<br>comment    ;.*{newline}<br>string     &quot;.*&quot;<br>char       &#39;.*&#39;</pre><pre>%%<br># delim</pre><pre>;      {comment}<br>&quot;      {string}<br>&#39;      {char}<br>0[xX]  {hex}</pre><pre>%%<br># tokenType</pre><pre>{string}  STRING<br>{word}    ID<br>section   SECTION<br>extern    EXTERN<br>include   INCLUDE<br>_data     DATA<br>_text     TEXT<br>_bss      BSS<br>db        DB<br>dq        DQ<br>dw        DW<br>mov       MOV<br>cmp       CMP<br>rax       GREG64<br>rbx       GREG64<br>rcx       GREG64<br>rdx       GREG64<br>eax       GREG32<br>ebx       GREG32<br>ecx       GREG32<br>edx       GREG32<br>ax        GREG16<br>bx        GREG16<br>cx        GREG16<br>dx        GREG16<br>al        GREG8<br>ah        GREG8<br>bl        GREG8<br>bh        GREG8<br>cl        GREG8<br>ch        GREG8<br>dl        GREG8<br>dh        GREG8<br>push      PUSH<br>pop       POP<br>pusha     PUSHA<br>,         COLON<br>popa      POPA<br>int       INT<br>[         OPENBRACKET<br>]         CLOSEBRACKET</pre><p>It takes in a specification of acceptable tokens in a file with 3 sections separated by a &amp;&amp; , each section goes in its specified table (classifiers are for our regex table).</p><p>We’ll add in a config file for our generator as I’ve already foreseen the need for various configs in future.</p><p>Right now, all it has is a single line</p><pre>spec:{specfile name}</pre><p>and it’s all set to parse that language.</p><p>And now, here’s a quick demo of a working version of the scanner</p><p><strong>EDIT</strong>: so I only caught after recording that the demo didn’t record my mouse scrolls as I used asciinema so there’s a lot of… inaction, those gaps were me scrolling. But you can feel free to give it a spin after this article; project link is at the end of the article. There’s also a clearer version in my repo’s README 😓</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FPZu5DaVDvz7D8A4TbT%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FPZu5DaVDvz7D8A4TbT%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FPZu5DaVDvz7D8A4TbT%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="253" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9d881c52942ad6071defe75e677bfb6/href">https://medium.com/media/f9d881c52942ad6071defe75e677bfb6/href</a></iframe><p>And that’s where we are! 😄.</p><p>I hope you enjoyed this article and I hope it was comprehensible. I’m testing my ability to translate complex computer sciencey stuff. If you find any inaccuracies in my info, please let me know so I can throw in a quick edit. I’ll go into my code implementation in later articles as it’s a lot and I’m constantly cleaning it up and refining it as I plan later components of the project.</p><p>A small feature I’m adding is init code that will generate default regexes in newly created spec files as they can be quite daunting and are also similar across many languages.</p><p>Let me know what you think of my project. You can check it out here.</p><p><a href="https://github.com/AlysonBee/CompilerGenerator">GitHub - AlysonBee/CompilerGenerator: A repo for my current compiler project</a></p><p>And of course, the book that inspired it all: <a href="https://www.amazon.com/Engineering-Compiler-Keith-Cooper/dp/012088478X">https://www.amazon.com/Engineering-Compiler-Keith-Cooper/dp/012088478X</a></p><p>Happy reading! 👋</p><p>AlysonN</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ffe2e0e609c" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/lets-play-with-meta-compilers-designing-an-automated-scanner-2ffe2e0e609c">Let’s Play with (Meta)Compilers — Designing an Automated Scanner</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Virtual Filesystem — Rounding it up]]></title>
            <link>https://alysonn.medium.com/virtual-filesystem-rounding-it-up-a08368c7dfe6?source=rss-c976df4e1e52------2</link>
            <guid isPermaLink="false">https://medium.com/p/a08368c7dfe6</guid>
            <category><![CDATA[filesystem]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[AlysonN]]></dc:creator>
            <pubDate>Sat, 10 Jul 2021 10:28:19 GMT</pubDate>
            <atom:updated>2021-07-10T10:28:19.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>Virtual Filesystem — Rounding it up</h3><p>An abrupt end to an otherwise not so epic journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*SKqX8qiIcsG_RToH0PvWEA.jpeg" /><figcaption>Me trying my best to finish this project…</figcaption></figure><p>Okay so admittedly I didn’t really know how to round this off. I had one component left to go (the image maker/reader) but then a bunch of life events threw me off my flow in a pretty big way. I lost a bunch of the carefully curated momentum I had going for myself, then proceeded to spend the three or so months ignoring my problems and plough through Persona 3, 4, 5 and 5 Strikers. Was it worth it? It totally was, those games are fantastic. Would I do it again? Probably. What happens to me now? I’m currently thinking of my next lengthy project. Though before moving onto it I wanted to round this one off. I wasn’t able to finish it but I did want to give it closure, I was also on the final step of Ver1 so it would be remiss of me to just not end it.</p><h4>Taking Stock</h4><p>The Go Virtual Filesystem. Ah, what a project. It was reasonably ambitious for my first project in Go, I’ll admit that wholeheartedly. But also at the same time, it made the concept of writing a filesystem turn out to be not so hard because of all the hand-holding the language does for you more than it would it, say, C. I think overall to get the best learning experience in terms of writing a filesystem, it would be best to do it in C because the concept of manually having to control buffers, inodes, flushes to disc and so on I think are important learning details if your goal is strictly educational. And since it’s been a long time, I’d like to spend this article giving a brief overview of each component, what I’d like to think I learnt from it and hopefully you did too and what I think could be built on top of it should I ever revisit this project.</p><h3>1. User management</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFqYiZ3sz-vTyRZkHUyIpA.jpeg" /></figure><p>Creating our Foundation : <a href="https://itnext.io/a-virtual-filesystem-in-go-creating-our-foundation-9af62b0e82db">https://itnext.io/a-virtual-filesystem-in-go-creating-our-foundation-9af62b0e82db</a></p><p>Our First Feature : <a href="https://alysonn.medium.com/a-virtual-filesystem-in-go-our-first-features-dea8699d7d2d">https://alysonn.medium.com/a-virtual-filesystem-in-go-our-first-features-dea8699d7d2d</a></p><p>This was the first of the components I worked on. It consisted of the laughably simple “user registration” screen that simply prompted you for a name and sent you on your way. There’s absolutely no security in this system; anyone could make anything on it. Just pop your name in and hit enter and you’re good to go.</p><p>It could potentially be expanded upon with a sort of IAM system (Identity and Access Management). Think a system that ties a certain privilege level to a single user and allows any directories with matching privilege levels to be accessible. Maybe the user also has a sort of access tag; and this tag allows them to make specific files that are only visible to users that have the same tag.</p><h3>2. Shell creation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i8oa_EmFbkl1iLlEdAvuQQ.jpeg" /></figure><p>And a Shell Too I guess: <a href="https://alysonn.medium.com/go-virtual-filesystem-and-a-shell-too-i-guess-25d4f357d8ad">https://alysonn.medium.com/go-virtual-filesystem-and-a-shell-too-i-guess-25d4f357d8ad</a></p><p>I’m reminded of the nightmare I endured when having to design a shell from scratch when I was studying and this entire section can be used to relive that horrifying experience.</p><p>My initial shell is directly built alongside the filesystem with built-in functionality for shell navigation (cd), file listing (ls), clearing screen and a few other niceties.</p><p>A great extension to this would be to find a way to decouple the shell even further. Maybe this makes it easier to integrate completely new, filesystem specific commands as separate programs (?). Another neat idea could be to make admin shell specific tools; maybe throw some user database manipulation functionality to add, edit and remove users from our bootleg IAM system.</p><p>Some additions can be purely cosmetic too; a colored prompt similar to zsh or file scrolling.</p><p>Admittedly because of how I built the VFS, I couldn’t think of any practical way to make the shell its own standalone object with an identity separate from the entire system. I really wanted to though, I thought it would be kinda cool having two separate projects in one. I quite enjoyed writing a shell back in the day, when it wasn’t making me cry and spend the last of my dinner money for the week on shameful amounts of McDonald’s comfort food.</p><h3>3. Filesystem Initialization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0TB0kLTQoOtxwM3LeOyWSA.jpeg" /></figure><p>Completing Filesystem Initialization: <a href="https://itnext.io/virtual-filesystem-in-go-completing-filesystem-initialization-2470e3bd8243">https://itnext.io/virtual-filesystem-in-go-completing-filesystem-initialization-2470e3bd8243</a></p><p>I promise the actual contents of this subject are a lot clearer than that lazy heading suggests. This was the the meat of the challenge; creating our files and folders in the correct order as copied from the host filesystem. This part I found incredibly interesting because this is the detail that made Go’s beautiful simplicity completely obvious to me in a way it wasn’t entirely up until this point. I’d been dreading the tedium of handling nested structs inside arrays that had structs that had more arrays.</p><p>The idea went like this; there was a single struct for a single directory. Inside this struct were an array of file structs; these structs held info on editable files; think their contents, file sizes, unique hashes and so on. Another list of structs inside a directory structs were (you guessed it) an array of directory structs; these represented the subdirectories found inside a directory.</p><p>Frightening as this seemed at the time, my thinking was filtered through the lens of attempting this in C. And in C, we have pointers and memory allocation and manual memory management, details that made any endeavor trickier than it ought to be. But no, this was Go. Doing this sorta just.. well.. it just worked. I don’t really know what else to say.</p><p>And now reader, here comes the plot twist reader so brace yourself.</p><p>This next part was possibly a massive mistake.</p><p>I won’t add any further details about what I’d do to improve this section; we’ll get to that later on. Because the only way this detail could be improved is to be erased from existence.</p><h3>4. Writing a Text Editor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pWFWfvlha06tRH7heM5xrw.png" /></figure><p>Adding a Text Editor: <a href="https://itnext.io/virtual-filesystem-in-go-completing-filesystem-initialization-2470e3bd8243">https://itnext.io/virtual-filesystem-in-go-completing-filesystem-initialization-2470e3bd8243</a></p><p>This turned out to be an incredibly interesting problem, especially because I work on Windows. This component took an incredibly long time because of host system incompatibility issues I kept running into.</p><p>The plan went as such; go online, find a Vim like text editor (for it is always Vim), take its code and bury it deep into the confines of the filesystem’s depths and presto, it would work like magic. So far so peaches and gravy. I even found a Github repo for a project called kilo-in-go that was the famous Vim-like Kilo editor written in Go.</p><p>Things were going well. Perhaps a little too well?</p><p>I’d go into the source code and start forcefully shoving it into my filesystem as fast as I could hoping to catch my deadline. My first official hurdle; the Kilo editor uses very very very native system calls unique to Unix-like operating systems. The long story short about these system calls (or syscalls) is that they helped with controlling things like interrupts (your Ctrl+Cs and Ctrl+Ss) as well as the behavior of that flickering prompt you see in your terminal which would be used as prompt inside the editor (I’ll link to more info on syscalls at the end of this article, it’s quite the read). Windows didn’t share any with Unix systems. I couldn’t even find these equivalents because who does systems programming in Windows I guess… :(.</p><p>My final strategy was to use the web browser as my text editor which ended up being the method I went with. I had to quickly learn to throw together a website in Go overnight, threw in a bit of JavaScript, found a text editor JS framework, got Ctrl+S for saving working and overall tried to make it the most Sublime experience I could (see what I did there :D?).</p><p>I guess the only improvement I can honestly think of would be to make different text editor options based on your filesystem. I’d still integrate the kilo-in-go editor and use that when on a Unix system and then the web version when on Windows. I still think the Kilo one would’ve been easier to manage because I could directly work with the code and affect its integration directly whereas the web version, I sorta felt that I just had to deal with what I got. I really felt like my filesystem gave me attitude and it kinda hurt my feelings and I couldn’t do anything to punish it back and I thought that was unfair.</p><h3>5 Filesystem Image File</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*JhVlgqVeFE04banM_14r5A.png" /></figure><p>The Image File Format: <a href="https://alysonn.medium.com/go-virtual-filesystem-the-image-file-format-failed-attempt-1-4d015a5e800f">https://alysonn.medium.com/go-virtual-filesystem-the-image-file-format-failed-attempt-1-4d015a5e800f</a></p><p>And this is where our journey comes to an end. Equal parts in fault to my suddenly turbulent personal life, equal parts I really should’ve thought all of this through a bit more.</p><p>And now we’ll talk further about the disastrous mistake to make the filesystem’s structure from recursive structs in arrays inside structs. I’d been struggling with this the most because I could safely pack all my data into an image file. The packing was simple enough; first pack all files, then save the name of the directory we’re in, enter the array of directories, do the same to each in the array recursively until we reach the very bottom of the tree.</p><p>Unpacking was always the problem.</p><p>Everything I tried never seemed to work mainly because the structure I’d given the packed files (namely first a directory, then a list of files, then a directory deep, then it’s list of files, then an even deeper directory and so on). I’d packed them in a depth-first approach where a breadth first would’ve probably been easier to work with. The main issue was controlling how we’d go backwards.</p><p>I’ll give a more concrete example.</p><p>Say the directory we’re currently in is /first/second/third/fourth levels deep and then right after that, we have a directory first/fifth level right after that. We’d have to go back two directories. It gets worse because, sure, I could’ve just split the strings, and then count how many directories back I had to travel, but all of this was in a single bytestream; basically right after the end of this string would be contents of a file.</p><p>I found this a lot easier to think about rather than to pull off, especially because of the mess that the recursive structure I’d given my filesystem caused in my brain. It led to messy, unmaintainable code that I’d get confused working with way too often.</p><p>I also feel that because of the size of the redesign I’d want to give the filesystem, it would be better off to just move on to a version 2 with a better design and a few more of the shiny stuff I’d want to have originally added. It also helped that this was the final component to the first version in the first place so I feel no guilt :D.</p><h3>And That’s It</h3><p>I’m a little bummed out that I never got it working perfectly but I’d want to redo it anyway. It reached a point that I simply wasn’t enjoying it very much. My “short” hiatus from the project stifled my momentum and I’ve been struggling to get back to feeling enthusiastic about this project for a while since so I’ve decided to leave it here.</p><p>Filesystems are pretty cool and I feel a little guilty for not having implemented it without the complexities of inodes and disc blocks though for now, my curiosity about the topic’s been satisfied.</p><p>Thank you reader for sticking with these articles through my sudden erroneous schedule. I’ll be cleaning up the filesystem repo in the coming days and will begin work on my next project soon.</p><p>Hopefully this time my planning is a bit better ‘:D.</p><p>Edit: so I don’t know what I want to make next. I’ll try to work on smaller projects I can finish in short periods of time to keep my momentum fresh and pushes frequent.</p><p>I’ll also be polishing up the VFS repo I made to round it off: <a href="https://github.com/AlysonBee/GoVirtualFilesystem">https://github.com/AlysonBee/GoVirtualFilesystem</a></p><p>Cheers</p><p>Alyson</p><p>Here’s a few helpful resource I consulted for my doomed expedition down this dreaded path:</p><p>Syscall (System call) stuff : <a href="https://en.wikipedia.org/wiki/System_call">https://en.wikipedia.org/wiki/System_call</a></p><p>Kilo-in-go: <a href="https://github.com/bediger4000/kilo-in-go">https://github.com/bediger4000/kilo-in-go</a></p><p>Inodes: <a href="https://en.wikipedia.org/wiki/Inode">https://en.wikipedia.org/wiki/Inode</a></p><p>Great books on filesystems:</p><p>Practical Filesystem Design : <a href="https://www.amazon.com/Practical-System-Design-Dominic-Giampaolo/dp/1558604979">https://www.amazon.com/Practical-System-Design-Dominic-Giampaolo/dp/1558604979 </a>— This one I found would’ve been useful if I’d actually gone through the entire thing but I mostly just used it as reference material to ensure I was using my lingo correctly.</p><p>UNIX System Programming : <a href="https://www.amazon.com/Unix-System-Programming-Keith-Haviland/dp/0201877589">https://www.amazon.com/Unix-System-Programming-Keith-Haviland/dp/0201877589</a>--This one I used mainly for the shell stuff and also, admittedly, read it a long time ago but the principals about how shells work and make use of command line tools is helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a08368c7dfe6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Virtual Filesystem — Adding A Text Editor]]></title>
            <link>https://itnext.io/go-virtual-filesystem-adding-a-text-editor-176f082e0109?source=rss-c976df4e1e52------2</link>
            <guid isPermaLink="false">https://medium.com/p/176f082e0109</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[filesystem]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[text-editor]]></category>
            <dc:creator><![CDATA[AlysonN]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 16:18:52 GMT</pubDate>
            <atom:updated>2021-04-13T11:20:12.981Z</atom:updated>
            <content:encoded><![CDATA[<h3>Go Virtual Filesystem — Adding A Text Editor</h3><p>Think of this as project inside a project because this is gonna hard…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2yTUxD4bID1c4SmfE0_Zw.png" /></figure><p>We’re back at it this week reader! Contrary to my previous announcement on what would happen next, protobuf (Protocol Buffers) is being benched this week. I started working on it but then I started playing Persona 4 and found myself unable to stop. There’s just something about role playing a person with incredibly poor time management skills that I just found so engaging and hard to tear myself away from.</p><p>But let’s get into this week’s topic; text editors.</p><p>It’s funny because I decided to work on the editor because it seemed easier than the filesystem image; how hopelessly naïve of me.</p><h3>The Tried (and Failed) Strategies</h3><ol><li><strong>Breaking apart kilo-in-go and shoving it into my filesystem</strong></li></ol><p>I made three iterations of a text editor; each one constantly making me rethink the massive amount of work I was about to be forced to do. The first brilliant idea I had was to take the kilo-in-go editor (see the repo :<a href="https://github.com/bediger4000/kilo-in-go">https://github.com/bediger4000/kilo-in-go</a>), go into its source code, tear it to pieces and then rebuild those pieces directly into my filesystem source code and we’d have a vim-like editor ready to go.</p><p>A great plan in theory and I would’ve gotten away with it too if it wasn’t for the fact that Windows insists on being different from everyone else. Yup, I was completely foiled by architecture differences between Windows and Linux/Mac because the system calls that make the kilo editor work don’t exist in Windows at all.</p><p>So even if I did integrate it in, it would work in Linux but not in Windows.</p><p><strong>The Takeaway</strong>:</p><p>When I eventually (possibly) get to implementing the OS specific differences to make my filesystem truly agnostic (see also the / and \\ differences in file pathing), adding the Kilo editor back for Linux users I still think would be a cool idea and a fun weekend project.</p><p><strong>2. Running the editor in a browser window (the Flask version)</strong></p><p>My uncontrollable fear of web programming made this method a bit of a bitter pill to swallow because this seemed like the only option. But as I was on a deadline (which I’m fully aware I missed), I opted to betray your trust and my own dignity and reverted to writing this little bit in Python (a not so virtual filesystem in Go after all).</p><p>The plan was a little bit complicated as mixing the two languages together seemed a bit untidy and sluggish. The control flow would look something like this:</p><ul><li>The user types open filename in the filesystem.</li><li>The contents of the targeted file’s content field would be written to a local file on the host operating system’s disk called TEST .</li><li>Using the Golang function exec.Command() , the Flask python app would then be run in the background.</li><li>Flask, using the ace text editor JavaScript library would read the contents of the TEST file and display it in the browser at 127.0.0.1:5000 .</li><li>When working in the browser editor Ctrl+S is mapped to sending the editor’s content to the Flask backend, where it will be written to TEST .</li><li>On exiting the browser and the Flask app, the filesystem would resume it’s execution, reading the newly saved contents from TEST and writing it into the appropriate filename file structure’s content field.</li><li>TEST is deleted.</li></ul><p>So far so peaches and gravy except the moment it was time to turn off the Flask application, using Ctrl+C would exit everything; the filesystem included.</p><p>And in the end I couldn’t get away with not learning how to web dev in Go. So the new plan would be to grind through tutorial hell on Go web programming in preparation and after a quick training montage, it was time to take another stab at it.</p><h3>The End Result — a working editor</h3><p>The end result wasn’t bad, it runs something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*QKVUIp7dvrqTVxbjUlN6mA.png" /><figcaption>Running the open command in the filesystem shell</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2W2W0prrjdfuNyzySGej5g.png" /><figcaption>Opens shell.go in the browser using the ace text editor Javascript framework.</figcaption></figure><p>And just like that we have a fully functional text editor with Ctrl+S mapped to file saving where closing the browser tab also closes the file.</p><h4>A Go Web Server</h4><p>Using the same idea I had for the flask server, my plan was to do the exact same thing but in Go. This would also allow me to drop a lot of the ugly parts of the design; one big one being that pesky TEST file and relying on writing and reading from it. Everything being in Go would allow us to keep everything neatly confined the the machinations of the filesystem’s internals.</p><p>So now, open would trigger the start of a web server once we’ve confirmed that the file we want to edit exists in the first place.</p><pre>func (fs  * fileSystem) open(filename string) error {<br> if _, exists := fs.files[filename]; exists {<br>  editingFile = fs.files[filename]<br>  editor()<br> } else {<br>  fmt.Println(filename, &quot;: file doesn&#39;t exist.&quot;)<br> }<br> return nil<br>}</pre><p>In the above code, we start by first determining that the file we want to edit exists and if it does, assign it to the global variable editingFile as the file we’ll be work on and then finally calling the aptly named editor() function which would do the rest.</p><h4>The Text Editor Server</h4><p>Our text editor runs a small webserver that opens up at port 127.0.0.1:5000 to reveal the contents of the current file we’re working on in text editor form.</p><p>This function consists of two important parts. The first ensures that Ctrl+C is disabled in your terminal. I found this an interesting user experience issue in that the friends I tested it on insisted on using Ctrl+C in the terminal to kill the text editor. This of course just exited the entire filesystem so I had to ban this usage entirely with a helpful terminal message if you tried…</p><pre>Interrupt cancelled. Close text editor tab at :127.0.0.1:5000</pre><p>The full source code for the editor is as follows.</p><pre>func editor() {<br> mux := http.NewServeMux()<br> c := make(chan os.Signal, 1)<br> signal.Notify(c, os.Interrupt)<br> go func() {<br>  for sig := range c {<br>   fmt.Println(&quot;Interrupt cancelled. Close text editor tab at :127.0.0.1:5000;&quot;, sig)<br>  }<br> }()</pre><pre>openbrowser(&quot;<a href="http://127.0.0.1:5000/">http://127.0.0.1:5000</a>&quot;)<br> server := http.Server{Addr: &quot;:5000&quot;, Handler: mux}<br> mux.HandleFunc(&quot;/&quot;, indexHandler)<br> mux.HandleFunc(&quot;/save&quot;, saveHandler)<br> mux.HandleFunc(&quot;/shutdown&quot;, shutDown)<br> server.ListenAndServe()<br>}</pre><p>The first part of the browser does just that; it takes the value of SIGINT (Signal Interrupt) which is Ctrl+C and removes its functionality. So every time Ctrl+C is hit, the code</p><pre>fmt.Println(&quot;Interrupt cancelled. Close text editor tab at :127.0.0.1:5000;&quot;, sig)</pre><p>is run instead.</p><p>The next function openbrowser is responsible for opening the editor in a browser immediately after you’ve typed open filename in the terminal. Its the most natural way I found I could simulate opening up a text editor instantly. Navigating after typing open just felt silly so I threw this in there.</p><p>The last few components are the handleFunc methods. These essentially tie functions to their respective endpoints so any time these URLs were either visited or requested in some way, those actions would trigger the code in these mentioned function handlers; indexHandler handles the main text editor, saveHandler handles the saving of files and shutDown handles the shutting down of the server when it’s time to close our editor and move on.</p><p>To avoid making this article too long and making this into another basic web dev Go tutorial, I’ll end off the description of general server stuff here and move on to the editor specifics. If you’d like to know more about web devving in Go, I highly recommend the tutorial by Freshman Tech which can be found here; <a href="https://freshman.tech/web-development-with-go/">https://freshman.tech/web-development-with-go/</a>. I did this one in preparation for this article and I can say it’s one of the best I’ve ever done.</p><p>Okay, onwards to a bit of JavaScript.</p><h4>Let’s Web Dev a Bit</h4><p>I think it’s worth going over a few of the web stuff that I found quite challenging; equally partly because of my lack of skill in the browser and also because the ace editor’s JS library’s a beautiful, hidden and largely undocumented gem which I’m hoping to give a bit of exposure to.</p><p>I’m not kidding guys, I absolutely love this library.</p><p>So let’s go over the ace editor code a bit.</p><h4>All Things ACE</h4><p>The Ace JS library allows you to build a text editor UI directly into your website that looks similar to Sublime Text Editor it its design. It can be found here: <a href="https://ace.c9.io/">https://ace.c9.io/</a>.</p><p>Example ace editor code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EA30sYCZcTPvhocNscU2Iw.png" /><figcaption>The source code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgiX9iLsWGyK0n4Y4LttKQ.png" /><figcaption>The output</figcaption></figure><p>The main thing to bear in mind when trying to make a browser editor is first being able to template the “source code” portion so your code can stay dynamic. Think of using something like jinja with Flask or the template package in Go. You could replace the code in the HTML above at line 17 to 20 with something like this;</p><pre>&lt;div id=&quot;editor&quot;&gt;{{ source_code }}&lt;/div&gt;</pre><p>with the accompanying backend code looking something like this.</p><pre>var source_code = open(&quot;source_file.go&quot;)<br>return Render(&quot;editor.html&quot;, source_code=source_code)</pre><p>The above is poorly written pseudocode just for getting the idea across of how this would work and how I did it. Go’s templating system needs a little more work if you’ve never worked with it before and it looks a little different but the ideas are quite similar.</p><p>To talk about the specific code used for this article, this can be found in the indexHandler function;</p><pre>func indexHandler(w http.ResponseWriter, r *http.Request) {<br> buf := &amp;bytes.Buffer{}<br> <br> source := &amp;sourceCode{<br>  Code: string(editingFile.content),<br>  Ext: &quot;golang&quot;,<br> }<br> err := tpl.Execute(buf, source)<br> if err != nil {<br>  fmt.Println(&quot;Error&quot;)<br>  http.Error(w, err.Error(), http.StatusInternalServerError)<br>  return<br> }<br> buf.WriteTo(w)<br>}</pre><p>The important details is the souceCode struct initializer and the tpl.Execute line. In short; the sourceCode object will be passed into the HTML and it’s values Code and Ext will be the dynamic elements in the text editor responsible for displaying the source code of the opened file and the Ext will be responsible for assigning the correct editor coloring and highlighting based on the language you’re using. Here it’s hardcoded to golang … just because…</p><p>In the HTML; you can find them on line 17 and 25 respectively (here’s hoping that I never added an ENTER anywhere in the code accidentally).</p><pre>&lt;div id=&quot;editor&quot;&gt;{{ .Code }}&lt;/div&gt;<br>...</pre><pre>editor.session.setMode(&quot;ace/mode/{{ .Ext }}&quot;);</pre><p>Another part of the editor that I added to make it more user friendly and similar to your run of the mill editors was the remapping of the Ctrl+S shortcut which, when used in the browser, would give you the option to save the web page you’re currently on.</p><p>This wasn’t gonna suffice so I changed this too.</p><h4>Quick Saving</h4><p>I was both surprised and also unsurprised to find that you could override something as timeless as Ctrl+S to make it do your bidding. All it took was a mapping of Ctrl+S that would send the contents of the editor div ( &lt;div id=&quot;editro&quot;&gt; ) to an endpoint via an AJAX call (I think you say it like that).</p><p>It goes something like this</p><pre>if ((window.navigator.platform.match(&quot;Mac&quot;) ? e.metaKey : e.ctrlKey)  &amp;&amp; e.keyCode == 83) {<br>        e.preventDefault();<br>        console.log(editor.getValue())<br>        $.ajax({<br>            type: &#39;POST&#39;,<br>            url: &#39;/save&#39;,<br>            contentType: &#39;application/json;charset=UTF-8&#39;,<br>            data: JSON.stringify({&#39;data&#39;: editor.getValue()}),<br>            success: function() {<br>                console.log(&quot;success&quot;)<br>            }<br>        });<br>...</pre><p>This code above first checks that the correct keys are pressed simultaneously (ensuring that ctrl is replaced with cmd depending on whether you’re working on a Macbook or not).</p><p>Right after that, the current contents of the editor, stored in editor.getValue() is passed into an AJAX post request and sent to the URL responsible for the /save endpoint in our backend.</p><p>Our /save value’s saveHandler functionality looks like this in our Go backend.</p><pre>func saveHandler(w http.ResponseWriter, r *http.Request) {<br>        if r.Method == &quot;POST&quot; {<br>                var data map[string]string<br>                json.NewDecoder(r.Body).Decode(&amp;data)<br>                editingFile.content = []byte(data[&quot;data&quot;])<br>        }<br>}</pre><p>This function runs the moment the /save endpoint is navigated to or a request is made to it.</p><p>In the above we check if a POST request has been sent through from the frontend (which only happens when we press Ctrl+S). We inspect the contents of the request body, which has our edited source code. This code then overwrites the previous version of itself which, in the code above, is stored in the editingFile.content value.</p><p>Thus, our file is saved and we can…</p><h4>Exit(ing and how it works)</h4><p>Another new thing I didn’t know JavaScript to allow you to do. You can determine a function trigger upon the browser closing. I really just needed the close function to give back functionality to the shell (which is blocked and can’t be exited as long as a tab that displays 127.0.0.1:5000 hasn’t been closed properly — so no redirecting, you have to press the ‘x’).</p><p>This required more JQuery magic.</p><p>Here’s the code:</p><pre>$(window).on(&quot;beforeunload&quot;, function() { <br>        $.ajax({<br>                type: &#39;POST&#39;,<br>                url: &#39;/shutdown&#39;,<br>                contentType: &#39;application/json;charset=UTF-8&#39;,<br>                data: JSON.stringify({&#39;data&#39;:&#39;exiting&#39;})</pre><pre>})    <br>    })</pre><p>Here, we’re tying functionality to the current browser window’s unloading behavior; so basically what happens the moment we close it. We have another AJAX call, this time to the /shutdown endpoint. It just shuts down the web server in the backend that’s keeping the editor running as well as unblocks the shell.</p><pre>func shutDown(w http.ResponseWriter, r *http.Request) {<br>     if r.Method == &quot;POST&quot; {<br>        server.Shutdown(context.Background())<br>     }<br> }</pre><p>Same deal as before; the moment we get a post request from the /shutdown endpoint, we trigger a server shutdown and return functionality to the shell.</p><p>And that’s our overall control flow of our text editor.</p><p>Give it a try in the latest version of the Filesystem (inside src/05 in the Github repo). Run the filesystem, setup a name and run open with any filename as an argument.</p><p>Our text editor is done. And just like that, we’ve got one final function to add to round off version 1 of the filesystem.</p><h3>The Home Stretch</h3><p>This was a lot to go through but we’ve finally made it to our final feature before I decide on whether to expand or stop on this project.</p><p>So far, our filesystem is very very basic. We can only have one user at a time, we can only read files and edit existing files and no security whatsoever.</p><p>The last thing we’d need to implement is that dreaded filesystem image saving and I guess clean up the code a bit. Removing a function here, abstracting a method there…</p><p>Overall, this project’s been a lot of fun but it also feels a lot more basic compared to what I’d imagined this would eventually be. It was fun writing this in a completely new language entirely and I’m comfortable enough in Go to be quite productive in it because of this too.</p><p>So then reader, keep reading these a little longer as we wrap things up.</p><p>Till next week.</p><p>As always links for this article:</p><p>The progress so far; <a href="https://github.com/AlysonBee/GoVirtualFilesystem/tree/master/src/05">https://github.com/AlysonBee/GoVirtualFilesystem/tree/master/src/05</a></p><p>The Ace text editor JS library/framework; <a href="https://ace.c9.io/">https://ace.c9.io/</a></p><p>Freshman Tech — How To Build Your First Web Application with Go : <a href="https://freshman.tech/web-development-with-go/">https://freshman.tech/web-development-with-go/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=176f082e0109" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/go-virtual-filesystem-adding-a-text-editor-176f082e0109">Go Virtual Filesystem — Adding A Text Editor</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fun Times Binary Patching the Mach-O Format]]></title>
            <link>https://alysonn.medium.com/fun-times-binary-patching-the-mach-o-format-fb1dad7bc090?source=rss-c976df4e1e52------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb1dad7bc090</guid>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[walkthrough]]></category>
            <dc:creator><![CDATA[AlysonN]]></dc:creator>
            <pubDate>Thu, 25 Mar 2021 16:21:51 GMT</pubDate>
            <atom:updated>2021-03-25T16:21:51.589Z</atom:updated>
            <content:encoded><![CDATA[<p>And a half-working solution</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UKeBMe9MDV5bLjEw" /><figcaption>I’m gonna look into making my own images soon.</figcaption></figure><p>No filesystem this week because I never made it on time. It turns out the things that are left to do are actually pretty hard. So this week I’ve decided to indulge myself a little bit in my other, once-favorite hobby; reverse engineering (sort of). I actually wrote this article quite a long time ago but never got to publishing it. It’s from a time when I had access to an OSX operating system and wanted to dig deeper into its internals. It always felt so different compared to Linux in ways that felt silly and that just gripped me in a way.</p><p>So let’s call this my love letter to the OSX operating system. This one’s a full walkthrough of an attempt I made at patching code into a binary on Mac. Hope you enjoy. Also, I failed at this too but it was a lot of fun 😃.</p><p>Let’s take things back a year or so.</p><p>I found this small achievement a significant steppingstone in my career as a casual reverse engineer (dammit, I love that phrase). I mean casual because those who know me also know how much I can’t bring myself to go all in because of my aversion to complex RE tools like IDA or Ghidra. I find them complex partly because of my love of the simple things in tech like vim and iTerm, but also the bottleneck that having poor eyesight causes to my workflow.</p><p>I liked this project because for what I was trying to achieve, a simple text editor and gcc were all I needed to get the job done.</p><p>So let’s get into the what, why and how.</p><h4>Patching the Mach-O Format for Fun and (almost certainly not) Profit</h4><p>Let’s assess the target we’ll be lining up in our crosshairs; his name is Woody Woodpacker, a 42 school project that did quite the number of my sleep schedule and self-esteem. The one project I just couldn’t beat no matter how hard I tried and how many books I read. I’d say things are different this time round but you already read this far and you know how this ends. But just like any other daredevil, I get paid for the attempt. :D</p><p>The goal of the original project was to take this output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*J2MfwycfGNySD2DIMqxmgA.png" /></figure><p>And then after patching the binary, make it produce this;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*HzhafPd40v1KjsLMbvf1lA.png" /></figure><p>without recompilation of any kind.</p><p>Sorcery at its finest.</p><p>I wanted to achieve the same thing but with the Mach-O format as the original project was to target the ELF format that’s supported by Linux systems. I figured it might actually be easier in comparison because the format seemed so much easier to grasp. Naivete at it’s finest.</p><h4>The Mach-O File Format</h4><p>Let’s catch you up on a few basics of how the Mach-O format is structured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*xOR1oXYA8NP3cryWqw2Vow.png" /></figure><p>This is the basic layout. For those in the know it must look a lot less of a meatier challenge than the ELF or even PE format because in comparison it’s relatively basic. We can think of it in three pieces; the <strong>Header</strong>, <strong>Load Commands</strong> and the <strong>Data </strong>sections.</p><p>The only pieces of info that’ll be reasonably glossed over here are about the Load Commands as they’re the main focus for figuring this thing out.</p><p>Also, no Go (or source code snippets) this week as I opted to code my solution in pure C. It’s a process I undertake when I’m looking to truly understand a technical concept because, in my opinion, it highlights the tiny details that a parse over with a tool might keep hidden and abstracted away. All my code will be linked at the end of this article so you can check it out if you’re interested.</p><p>Let’s get started with the first little program I wrote.</p><p>Here I wrote a program to show me every single section of the binary with each section’s start and end values. It’s output looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*1Ez8pHQsMKxjPbT2DYB_YA.png" /><figcaption>Mind the typos, it was a long night.. :(</figcaption></figure><p>Basically, those segments marked LOAD_COMMAND are all the Load Commands in the binary. They all have unique names but writing the names of all the ones we didn’t need wasn’t necessary so we left those out.</p><p>The names that all start with “__” are the names of various sections which are referenced in some way or another in the LOAD_COMMAND sections. Under the hood, I got all their offsets by observing them in their respective Load Command blocks that have the info.</p><p>The start and end index values tell us where these specific blocks of code are in the program; where they start and end relative to the start of the file.</p><p>These details were extremely important for the first approach I came up with where I found relatively minor success. Although, I’m not entirely convinced it was all for nothing.</p><p>So here’s how it went.</p><h4>The First Approach</h4><p>When a binary file or program is executed (think ls, python3, cat, env etc.), the code that actually runs exists in the __text section inside the __TEXT segment which is located somewhere in the Load Commands section of the binary file. Or at least the Load Commands have info on where these sections actually are with respect to their offsets from the start of the file.</p><p>The __TEXT segment has a __text section which, in turn, has offset information about where exactly the executable code in the file is stored.</p><p>My first bright idea was to see if it was possible to simply add my own custom code to this section and run it.</p><p>The code to be attached had to be written completely in Assembly to ensure it was as small as possible. My first test was relatively quite small. It didn’t do anything, I just needed to ensure that everything still worked after its insertion.</p><p>So, the target C code we’d be infectin — I mean editing looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*STvmIp78a7OzKMUHAWOnyQ.png" /></figure><p>And it’s assembly output after a quick compilation with gcc is;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*geHiWESWPnFZOBYrXqRKrw.png" /><figcaption>This is just the code section. This file’s a lot bigger.</figcaption></figure><p>And lastly, the code I wrote that I’d use to patch the binary above;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*csLREQFC7GbvLjQ9KJ5MDg.png" /><figcaption>NOP is an instruction that basically does nothing. There’s more to it sure but for this article, that explanation will do.</figcaption></figure><p>And a patch later, we have a successful prepend to the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*A5tCpqyMim_Rf3WXPZriYA.png" /></figure><p>But I’m sure you would’ve noticed that there’s a glaring issue with my newly patched version when compared to its predecessor’s output.</p><p>Yup. In the previous, pre-patched output, the string value at address 0x100000ed4 is not only no longer at this position in the newly patched binary (it’s been shifted to 0x100000ed8, by the 4 NOP bytes I prepended), it also no longer has its string value.</p><p>Something’s gone horribly wrong and this binary no longer works.</p><h4>Finding Another Way</h4><p>Note: a header file in C is a way of importing separate functions in other files and objects into your program. These files (that end with a .h) tend to have a lot of helpful info if you’re trying to debug native C/C++ code on your system.</p><p>After further reading the loader.h header file that contains info on the structs needed to parse the binary, I discovered that there was a Load Command value I neglected. One called LC_MAIN. LC_MAIN points to the starting address of C’s main() function — the entrypoint — and where it is in the binary. This is basically where the program actually starts running. It doesn’t start at the very top of the __text section as I thought it did. Because my NOP bytes shifted every value down by 4, all these offsets were completely wrong, mangling the binary.</p><p>Sure, I could’ve just experimented with updating LC_MAIN’s entry offset value by 4 bytes to accommodate my NOP values but I started to wonder if there were more invisible numbers and offsets I’d have neglected to update. Prepending wasn’t going to work. Or at least, not with the current skill and knowledge I had over the format.</p><p>So, after posting my problems on Reddit and StackOverflow and a few mugs of coffee later I finally had something to go on; the Mach-O file format had a lot of <strong>code caves.</strong></p><p>And I mean a <em>lot</em>.</p><h4>Caves! Caves Everywhere!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S5ruNGbAtaKCb8t6Yh_bZg.jpeg" /><figcaption>Here’s a pretty picture of a cave to break the monotony of this post.</figcaption></figure><p>A code cave is a specific section in a binary that’s filled with a lot of NULLs. That’s programmer speak for “nothing happens here” and is represented as a bunch of ‘’0’s. This is great for patching because it implies that we can do whatever we want and we won’t be penalized with breaking binaries. We can’t break anything because nothing’s meant to run in these positions anyway.</p><p>This is an example of a few code caves in the ‘ls’ utility. See all those inviting zeroes? My patch is gonna go in one of those.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bP1sOHl6dahJzB7ImKHj5w.png" /><figcaption>Output on running `hexdump -D /bin/ls` on OSX</figcaption></figure><p>And so I decided on my target. We were gonna go for a big one; we’ll be patching LS.</p><p>So, I proceeded to write yet another tool. This time, it finds all code caves in the binary file and shows me how big each cave is as well as its start index.</p><p>Its output isn’t glamorous but let’s face it, I was hacking away at this point as frustration hit fever pitch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*hakUSwpfl-xQ4WOrp3OPYw.png" /><figcaption>The code caves inside the ‘ls’ utility.</figcaption></figure><p>I kinda feel a little guilty for phoning it in the way I did with this one. But basically, see all those dashes lined up? Those are contiguous sections of long strings of zeroes (I didn’t use ‘0’s for the output because it started to hurt my eyes after a while). These are the caves with their starting index values.</p><p>All I had to do now is find a cave that was bigger than the size of the code I wanted to patch in. And considering the size of my patching efforts, I had a few options. Maybe out of paranoia or something, I opted for a rule in which any code that would be patched had to be as close to the __TEXT,__text section as it could be. I felt I knew a lot more about all the sections near and around that part of the binary than anything too far away from that so crashes would be a lot easier to debug.</p><p>The section of code I was going to patch started at index 1849. That section that went on forever and ever. So, I had my target, now for the patch. I wanted something a little more elaborate to christen my upcoming conquest over the format that’s eluded me for so long.</p><p>And here it is;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*ZPJJ0ZgaTWzmRzm-vosxcQ.png" /></figure><p>Sure, it’s a classic “hello world’, but there’s a lot of subtle tricks to it that make it relatively different to the standard Assembly “hello world” that takes a bit of understanding of stacks frames and how they work in execution and such (if you’d like to know more, feel free to drop me a message… Or I could, you know, link you to an article on it or whatever).</p><p>Apart from the hello world string itself, that exceptionally large number on line 18 is significant and we’ll spend some time talking about it.</p><p>After fiddling with LLDB (OSX’s binary debugger) a little bit — the details in this are enough to make a separate blog entry entirely — I was able to determine that the entry point for the main() function is the value of that exceptionally large number at line 18. After figuring that out, the rest of the patch was easy to write.</p><p>The basic anatomy of the patch goes like this:</p><p>⦁ Find the largest code cave and save its index.</p><p>⦁ Find the LC_MAIN segment in the binary and change its entry offset to point to this saved index as it’s starting point.</p><p>⦁ Patch my assembly code’s bytes at the code cave’s index.</p><p>⦁ Run the program.</p><p>My program would start, jump to my patch, run my “hello world”, then at the end, jump back to the original main’s code and run that. Patch successful with flawless execution!</p><p>And then…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*7b72hqtMW1x32X2__zVYJA.png" /><figcaption>A segmentation fault is basically a crash… :/</figcaption></figure><p>It crashed but I don’t think this was a complete fail, not entirely. I’d made significant progress. I got the first part of the code to run; tt printed my “Hello World”. But why did it fail? I thought I’d patched in LC_MAIN’s original address into the code pretty accurately. I had to go back into LLDB. But then something even stranger happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*aD4EW7WvSXG0eFLEJimKhA.png" /></figure><p>It runs just fine inside LLDB which was strange at first.</p><p>It took me a while to realize that parent/child process issues were happening.</p><p>How debuggers work is that once they’re run, they make a separate process for the programs they attach to.</p><p>The address I had for the LC_MAIN (that massive number on line 18 of my patch) was relative to where in memory it is when LLDB is running it. The number I got wasn’t its true address but the address it got when it was run inside LLDB. Basically this would never work outside of LLDB or at least I’d have to know how to figure out how much address padding LLDB adds to the files it attaches itself to.</p><h4>In Conclusion</h4><p>That’s that. A new thing to research on my journey towards perfectly patching the Mach-O format. In the end, I never got it working completely but partly. It’s not really useful if it needs a debugger to work but I’ll come back to this some other time. It was a fun project at the time and perhaps now I could actually go back and beat it as I’m a lot better at this engineering stuff than I was when I attempted this.</p><p>Or perhaps not. My filesystem won’t build itself.</p><p>So we’re back to it next week (incidentally, if you’re new, check out my filesystem project and articles. You can start at it’s Github page: <a href="https://github.com/AlysonBee/GoVirtualFilesystem">https://github.com/AlysonBee/GoVirtualFilesystem</a>)</p><p>Alright, that’s it.</p><p>Cheers 😃</p><p>Links to all this article’s stuff:</p><p>My first attempt: <a href="https://github.com/AlysonBee/Articles/tree/master/01_OSX_patching/cstring_section_patcher">https://github.com/AlysonBee/Articles/tree/master/01_OSX_patching/cstring_section_patcher</a></p><p>The code that neatly dumps segments out: <a href="https://github.com/AlysonBee/Articles/tree/master/01_OSX_patching/dump_osx_file_segments">https://github.com/AlysonBee/Articles/tree/master/01_OSX_patching/dump_osx_file_segments</a></p><p>The Code Cave semi-perfect (not even close) packer: <a href="https://github.com/AlysonBee/Articles/tree/master/01_OSX_patching/code_cave_patcher">https://github.com/AlysonBee/Articles/tree/master/01_OSX_patching/code_cave_patcher</a></p><p>Mach-O file format basics: <a href="https://en.wikipedia.org/wiki/Mach-O">https://en.wikipedia.org/wiki/Mach-O</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb1dad7bc090" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>