blog/atom.xml (view raw)
1<?xml version="1.0" encoding="UTF-8"?>
2<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
3 <title>Lonami's Site - My Blog</title>
4 <link href="https://lonami.dev/blog/atom.xml" rel="self" type="application/atom+xml"/>
5 <link href="https://lonami.dev/blog/"/>
6 <generator uri="https://www.getzola.org/">Zola</generator>
7 <updated>2021-02-19T00:00:00+00:00</updated>
8 <id>https://lonami.dev/blog/atom.xml</id>
9 <entry xml:lang="en">
10 <title>Writing our own Cheat Engine: Unknown initial value</title>
11 <published>2021-02-19T00:00:00+00:00</published>
12 <updated>2021-02-19T00:00:00+00:00</updated>
13 <link href="https://lonami.dev/blog/woce-3/" type="text/html"/>
14 <id>https://lonami.dev/blog/woce-3/</id>
15 <content type="html"><p>This is part 3 on the <em>Writing our own Cheat Engine</em> series:</p>
16<ul>
17<li><a href="/blog/woce-1">Part 1: Introduction</a> (start here if you're new to the series!)</li>
18<li><a href="/blog/woce-2">Part 2: Exact Value scanning</a></li>
19<li>Part 3: Unknown initial value</li>
20</ul>
21<p>In part 2 we left off with a bit of a cliff-hanger. Our little program is now able to scan for an exact value, remember the couple hundred addresses pointing to said value, and perform subsequent scans to narrow the list of addresses down until we're left with a handful of them.</p>
22<p>However, it is not always the case that you have an exact value to work with. The best you can do in these cases is guess what the software might be storing. For example, it could be a floating point for your current movement speed in a game, or an integer for your current health.</p>
23<p>The problem with this is that there are far too many possible locations storing our desired value. If you count misaligned locations, this means there is a different location to address every single byte in memory. A program with one megabyte of memory already has a <em>million</em> of addresses. Clearly, we need to do better than performing one million memory reads<sup class="footnote-reference"><a href="#1">1</a></sup>.</p>
24<p>This post will shift focus a bit from using <code>winapi</code> to possible techniques to perform the various scans.</p>
25<h2 id="unknown-initial-value">Unknown initial value</h2>
26<details open><summary>Cheat Engine Tutorial: Step 3</summary>
27<blockquote>
28<p>Ok, seeing that you've figured out how to find a value using exact value let's move on to the next step.</p>
29<p>First things first though. Since you are doing a new scan, you have to click on New Scan first, to start a new scan. (You may think this is straighforward, but you'd be surprised how many people get stuck on that step) I won't be explaining this step again, so keep this in mind
30Now that you've started a new scan, let's continue</p>
31<p>In the previous test we knew the initial value so we could do a exact value, but now we have a status bar where we don't know the starting value.
32We only know that the value is between 0 and 500. And each time you click 'hit me' you lose some health. The amount you lose each time is shown above the status bar.</p>
33<p>Again there are several different ways to find the value. (like doing a decreased value by... scan), but I'll only explain the easiest. &quot;Unknown initial value&quot;, and decreased value.
34Because you don't know the value it is right now, a exact value wont do any good, so choose as scantype 'Unknown initial value', again, the value type is 4-bytes. (most windows apps use 4-bytes)click first scan and wait till it's done.</p>
35<p>When it is done click 'hit me'. You'll lose some of your health. (the amount you lost shows for a few seconds and then disappears, but you don't need that)
36Now go to Cheat Engine, and choose 'Decreased Value' and click 'Next Scan'
37When that scan is done, click hit me again, and repeat the above till you only find a few.</p>
38<p>We know the value is between 0 and 500, so pick the one that is most likely the address we need, and add it to the list.
39Now change the health to 5000, to proceed to the next step.</p>
40</blockquote>
41</details>
42<h2 id="dense-memory-locations">Dense memory locations</h2>
43<p>The key thing to notice here is that, when we read memory from another process, we do so over <em>entire regions</em>. A memory region is represented by a starting offset, a size, and a bunch of other things like protection level.</p>
44<p>When running the first scan for an unknown value, all we need to remember is the starting offset and size for every single region. All the candidate locations that could point to our value fall within this range, so it is enough for us to store the range definition, and not every location within it.</p>
45<p>To gain a better understanding of what this means, let's come up with a more specific scenario. With our current approach of doing things, we store an address (<code>usize</code>) for every location pointing to our desired value. In the case of unknown values, all locations are equally valid, since we don't know what value they should point to yet, and any value they point to is good. With this representation, we would end up with a very large vector:</p>
46<pre><code class="language-rust" data-lang="rust">let locations = vec![0x2000, 0x2001, ..., 0x20ff, 0x2100];
47</code></pre>
48<p>This representation is dense. Every single number in the range <code>0x2000..=0x2100</code> is present. So why bother storing the values individually when the range is enough?:</p>
49<pre><code class="language-rust" data-lang="rust">let locations = EntireRegion { range: 0x2000..=0x2100 };
50</code></pre>
51<p>Much better! With two <code>usize</code>, one for the starting location and another for the end, we can indicate that we care about all the locations falling in that range.</p>
52<p>In fact, some accessible memory regions immediately follow eachother, so we could even compact this further and merge regions which are together. But due to their potential differences with regards to protection levels, we will not attempt to merge regions.</p>
53<p>We don't want to get rid of the old way of storing locations, because once we start narrowing them down, we will want to go back to storing just a few candidates. To keep things tidy, let's introduce a new <code>enum</code> representing either possibility:</p>
54<pre><code class="language-rust" data-lang="rust">use std::ops::Range;
55
56pub enum CandidateLocations {
57 Discrete {
58 locations: Vec&lt;usize&gt;,
59 },
60 Dense {
61 range: Range&lt;usize&gt;,
62 }
63}
64</code></pre>
65<p>Let's also introduce another <code>enum</code> to perform the different scan types. For the time being, we will only worry about looking for <code>i32</code> in memory:</p>
66<pre><code class="language-rust" data-lang="rust">pub enum Scan {
67 Exact(i32),
68 Unknown,
69}
70</code></pre>
71<h2 id="storing-scanned-values">Storing scanned values</h2>
72<p>When scanning for exact values, it's not necessary to store the value found. We already know they're all the same, for example, value <code>42</code>. However, if the value is unknown, we do need to store it so that we can compare it in a subsequent scan to see if the value is the same or it changed. This means the value can be &quot;any within&quot; the read memory chunk:</p>
73<pre><code class="language-rust" data-lang="rust">pub enum Value {
74 Exact(i32),
75 AnyWithin(Vec&lt;u8&gt;),
76}
77</code></pre>
78<p>For every region in memory, there will be some candidate locations and a value (or value range) we need to compare against in subsequent scans:</p>
79<pre><code class="language-rust" data-lang="rust">pub struct Region {
80 pub info: winapi::um::winnt::MEMORY_BASIC_INFORMATION,
81 pub locations: CandidateLocations,
82 pub value: Value,
83}
84</code></pre>
85<p>With all the data structures needed setup, we can finally refactor our old scanning code into a new method capable of dealing with all these cases. For brevity, I will omit the exact scan, as it remains mostly unchanged:</p>
86<pre><code class="language-rust" data-lang="rust">use winapi::um::winnt::MEMORY_BASIC_INFORMATION;
87
88...
89
90// inside `impl Process`
91pub fn scan_regions(&amp;self, regions: &amp;[MEMORY_BASIC_INFORMATION], scan: Scan) -&gt; Vec&lt;Region&gt; {
92 regions
93 .iter()
94 .flat_map(|region| match scan {
95 Scan::Exact(n) =&gt; todo!(&quot;old scan implementation&quot;),
96 Scan::Unknown =&gt; {
97 let base = region.BaseAddress as usize;
98 match self.read_memory(region.BaseAddress as _, region.RegionSize) {
99 Ok(memory) =&gt; Some(Region {
100 info: region.clone(),
101 locations: CandidateLocations::Dense {
102 range: base..base + region.RegionSize,
103 },
104 value: Value::AnyWithin(memory),
105 }),
106 Err(_) =&gt; None,
107 }
108 }
109 })
110 .collect()
111}
112</code></pre>
113<p>Time to try it out!</p>
114<pre><code class="language-rust" data-lang="rust">impl CandidateLocations {
115 pub fn len(&amp;self) -&gt; usize {
116 match self {
117 CandidateLocations::Discrete { locations } =&gt; locations.len(),
118 CandidateLocations::Dense { range } =&gt; range.len(),
119 }
120 }
121}
122
123...
124
125fn main() {
126 // -snip-
127
128 println!(&quot;Scanning {} memory regions&quot;, regions.len());
129 let last_scan = process.scan_regions(&amp;regions, Scan::Unknown);
130 println!(
131 &quot;Found {} locations&quot;,
132 last_scan.iter().map(|r| r.locations.len()).sum::&lt;usize&gt;()
133 );
134}
135</code></pre>
136<pre><code>Scanning 88 memory regions
137Found 3014656 locations
138</code></pre>
139<p>If we consider misaligned locations, there is a lot of potential addresses where we could look for. Running the same scan on Cheat Engine yields <code>2,449,408</code> addresses, which is pretty close. It's probably skipping some additional regions that we are considering. Emulating Cheat Engine to perfection is not a concern for us at the moment, so I'm not going to investigate what regions it actually uses.</p>
140<h2 id="comparing-scanned-values">Comparing scanned values</h2>
141<p>Now that we have performed the initial scan and have stored all the <code>CandidateLocations</code> and <code>Value</code>, we can re-implement the &quot;next scan&quot; step to handle any variant of our <code>Scan</code> enum. This enables us to mix-and-match any <code>Scan</code> mode in any order. For example, one could perform an exact scan, then one for decreased values, or start with unknown scan and scan for unchanged values.</p>
142<p>The tutorial suggests using &quot;decreased value&quot; scan, so let's start with that:</p>
143<pre><code class="language-rust" data-lang="rust">pub enum Scan {
144 Exact(i32),
145 Unknown,
146 Decreased, // new!
147}
148</code></pre>
149<p>Other scanning modes, such as decreased by a known amount rather than any decrease, increased, unchanged, changed and so on, are not very different from the &quot;decreased&quot; scan, so I won't bore you with the details.</p>
150<p>I will use a different method to perform a &quot;rescan&quot;, since the first one is a bit more special in that it doesn't start with any previous values:</p>
151<pre><code class="language-rust" data-lang="rust">pub fn rescan_regions(&amp;self, regions: &amp;[Region], scan: Scan) -&gt; Vec&lt;Region&gt; {
152 regions
153 .iter()
154 .flat_map(|region| match scan {
155 Scan::Decreased =&gt; {
156 let mut locations = Vec::new();
157 match region.locations {
158 CandidateLocations::Dense { range } =&gt; {
159 match self.read_memory(range.start, range.end - range.start) {
160 Ok(memory) =&gt; match region.value {
161 Value::AnyWithin(previous) =&gt; {
162 memory
163 .windows(4)
164 .zip(previous.windows(4))
165 .enumerate()
166 .step_by(4)
167 .for_each(|(offset, (new, old))| {
168 let new = i32::from_ne_bytes([
169 new[0], new[1], new[2], new[3],
170 ]);
171 let old = i32::from_ne_bytes([
172 old[0], old[1], old[2], old[3],
173 ]);
174 if new &lt; old {
175 locations.push(range.start + offset);
176 }
177 });
178
179 Some(Region {
180 info: region.info.clone(),
181 locations: CandidateLocations::Discrete { locations },
182 value: Value::AnyWithin(memory),
183 })
184 }
185 _ =&gt; todo!(),
186 },
187 _ =&gt; todo!(),
188 }
189 }
190 _ =&gt; todo!(),
191 }
192 }
193 _ =&gt; todo!(),
194 })
195 .collect()
196}
197</code></pre>
198<p>If you've skimmed over that, I do not blame you. Here's the summary: for every existing region, when executing the scan mode &quot;decreased&quot;, if the previous locations were dense, read the entire memory region. On success, if the previous values were a chunk of memory, iterate over the current and old memory at the same time, and for every aligned <code>i32</code>, if the new value is less, store it.</p>
199<p>It's also making me ill. Before I leave a mess on the floor, does it work?</p>
200<pre><code class="language-rust" data-lang="rust">std::thread::sleep(std::time::Duration::from_secs(10));
201let last_scan = process.rescan_regions(&amp;last_scan, Scan::Decreased);
202println!(
203 &quot;Found {} locations&quot;,
204 last_scan.iter().map(|r| r.locations.len()).sum::&lt;usize&gt;()
205);
206</code></pre>
207<pre><code class="language-rust" data-lang="rust">Found 3014656 locations
208Found 177 locations
209</code></pre>
210<p>Okay, great, let's clean up this mess…</p>
211<h2 id="refactoring">Refactoring</h2>
212<p>Does it also make you uncomfortable to be writing something that you know will end up <em>huge</em> unless you begin refactoring other parts right now? I definitely feel that way. But I think it's good discipline to push through with something that works first, even if it's nasty, before going on a tangent. Now that we have the basic implementation working, let's take on this monster before it eats us alive.</p>
213<p>First things first, that method is inside an <code>impl</code> block. The deepest nesting level is 13. I almost have to turn around my chair to read the entire thing out!</p>
214<p>Second, we're nesting four matches. Three of them we care about: scan, candidate location, and value. If each of these <code>enum</code> has <code>S</code>, <code>C</code> and <code>V</code> variants respectively, writing each of these by hand will require <code>S * C * V</code> different implementations! Cheat Engine offers 10 different scans, I can think of at least 3 different ways to store candidate locations, and another 3 ways to store the values found. That's <code>10 * 3 * 3 = 90</code> different combinations. I am not willing to write out all these<sup class="footnote-reference"><a href="#2">2</a></sup>, so we need to start introducing some abstractions. Just imagine what a monster function you would end with! The horror!</p>
215<p>Third, why is the scan being executed in the process? This is something that should be done in the <code>impl Scan</code> instead!</p>
216<p>Let's begin the cleanup:</p>
217<pre><code class="language-rust" data-lang="rust">pub fn rescan_regions(&amp;self, regions: &amp;[Region], scan: Scan) -&gt; Vec&lt;Region&gt; {
218 todo!()
219}
220</code></pre>
221<p>I already feel ten times better.</p>
222<p>Now, this method will unconditionally read the entire memory region, even if the scan or the previous candidate locations don't need it<sup class="footnote-reference"><a href="#3">3</a></sup>. In the worst case with a single discrete candidate location, we will be reading a very large chunk of memory when we could have read just the 4 bytes needed for the <code>i32</code>. On the bright side, if there <em>are</em> more locations in this memory region, we will get read of them at the same time<sup class="footnote-reference"><a href="#4">4</a></sup>. So even if we're moving more memory around all the time, it isn't <em>too</em> bad.</p>
223<pre><code class="language-rust" data-lang="rust">regions
224 .iter()
225 .flat_map(
226 |region| match self.read_memory(region.info.BaseAddress as _, region.info.RegionSize) {
227 Ok(memory) =&gt; todo!(),
228 Err(err) =&gt; {
229 eprintln!(
230 &quot;Failed to read {} bytes at {:?}: {}&quot;,
231 region.info.RegionSize, region.info.BaseAddress, err,
232 );
233 None
234 }
235 },
236 )
237 .collect()
238</code></pre>
239<p>Great! If reading memory succeeds, we want to rerun the scan:</p>
240<pre><code class="language-rust" data-lang="rust">Ok(memory) =&gt; Some(scan.rerun(region, memory)),
241</code></pre>
242<p>The rerun will live inside <code>impl Scan</code>:</p>
243<pre><code class="language-rust" data-lang="rust">pub fn rerun(&amp;self, region: &amp;Region, memory: Vec&lt;u8&gt;) -&gt; Region {
244 match self {
245 Scan::Exact(_) =&gt; self.run(region.info.clone(), memory),
246 Scan::Unknown =&gt; region.clone(),
247 Scan::Decreased =&gt; todo!(),
248 }
249}
250</code></pre>
251<p>An exact scan doesn't care about any previous values, so it behaves like a first scan. The first scan is done by the <code>run</code> function (it contains the implementation factored out of the <code>Process::scan_regions</code> method), which only needs the region information and the current memory chunk we just read.</p>
252<p>The unknown scan leaves the region unchanged: any value stored is still valid, because it is unknown what we're looking for.</p>
253<p>The decreased scan will have to iterate over all the candidate locations, and compare them with the current memory chunk. But this time, we'll abstract this iteration too:</p>
254<pre><code class="language-rust" data-lang="rust">impl Region {
255 fn iter_locations&lt;'a&gt;(
256 &amp;'a self,
257 new_memory: &amp;'a [u8],
258 ) -&gt; impl Iterator&lt;Item = (usize, i32, i32)&gt; + 'a {
259 match &amp;self.locations {
260 CandidateLocations::Dense { range } =&gt; range.clone().step_by(4).map(move |addr| {
261 let old = self.value_at(addr);
262 let new = i32::from_ne_bytes([
263 new_memory[0],
264 new_memory[1],
265 new_memory[2],
266 new_memory[3],
267 ]);
268 (addr, old, new)
269 }),
270 _ =&gt; todo!(),
271 }
272 }
273}
274</code></pre>
275<p>For a dense candidate location, we iterate over all the 4-aligned addresses (fast scan for <code>i32</code> values), and yield <code>(current address, old value, new value)</code>. This way, the <code>Scan</code> can do anything it wants with the old and new values, and if it finds a match, it can use the address.</p>
276<p>The <code>value_at</code> method will deal with all the <code>Value</code> variants:</p>
277<pre><code class="language-rust" data-lang="rust">fn value_at(&amp;self, addr: usize) -&gt; i32 {
278 match &amp;self.value {
279 Value::AnyWithin(chunk) =&gt; {
280 let base = addr - self.info.BaseAddress as usize;
281 let bytes = &amp;chunk[base..base + 4];
282 i32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
283 }
284 _ =&gt; todo!(),
285 }
286}
287</code></pre>
288<p>This way, <code>iter_locations</code> can easily use any value type. With this, we have all <code>enum</code> covered: <code>Scan</code> in <code>rerun</code>, <code>CandidateLocation</code> in <code>iter_locations</code>, and <code>Value</code> in <code>value_at</code>. Now we can add as many variants as we want, and we will only need to update a single <code>match</code> arm for each of them. Let's implement <code>Scan::Decreased</code> and try it out:</p>
289<pre><code class="language-rust" data-lang="rust">pub fn rerun(&amp;self, region: &amp;Region, memory: Vec&lt;u8&gt;) -&gt; Region {
290 match self {
291 Scan::Decreased =&gt; Region {
292 info: region.info.clone(),
293 locations: CandidateLocations::Discrete {
294 locations: region
295 .iter_locations(&amp;memory)
296 .flat_map(|(addr, old, new)| if new &lt; old { Some(addr) } else { None })
297 .collect(),
298 },
299 value: Value::AnyWithin(memory),
300 },,
301 }
302}
303</code></pre>
304<pre><code>Found 3014656 locations
305Found 223791 locations
306</code></pre>
307<p>Hmm… before we went down from <code>3014656</code> to <code>177</code> locations, and now we went down to <code>223791</code>. Where did we go wrong?</p>
308<p>After spending several hours on this, I can tell you where we went wrong. <code>iter_locations</code> is always accessing the memory range <code>0..4</code>, and not the right address. Here's the fix:</p>
309<pre><code class="language-rust" data-lang="rust">CandidateLocations::Dense { range } =&gt; range.clone().step_by(4).map(move |addr| {
310 let old = self.value_at(addr);
311 let base = addr - self.info.BaseAddress as usize;
312 let bytes = &amp;new_memory[base..base + 4];
313 let new = i32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
314 (addr, old, new)
315}),
316</code></pre>
317<h2 id="going-beyond">Going beyond</h2>
318<p>Let's take a look at other possible <code>Scan</code> types. Cheat Engine supports the following initial scan types:</p>
319<ul>
320<li>Exact Value</li>
321<li>Bigger than…</li>
322<li>Smaller than…</li>
323<li>Value between…</li>
324<li>Unknown initial value</li>
325</ul>
326<p>&quot;Bigger than&quot; and &quot;Smaller than&quot; can both be represented by &quot;Value between&quot;, so it's pretty much just three.</p>
327<p>For subsequent scans, in addition to the scan types described above, we find:</p>
328<ul>
329<li>Increased value</li>
330<li>Increased value by…</li>
331<li>Decreased value</li>
332<li>Decreased value by…</li>
333<li>Changed value</li>
334<li>Unchanged value</li>
335</ul>
336<p>Not only does Cheat Engine provide all of these scans, but all of them can also be negated. For example, &quot;find values that were not increased by 7&quot;. One could imagine to also support things like &quot;increased value by range&quot;. For the increased and decreased scans, Cheat Engine also supports &quot;at least xx%&quot;, so that if the value changed within the specified percentage interval, it will be considered.</p>
337<p>What about <code>CandidateLocations</code>? I can't tell you how Cheat Engine stores these, but I can tell you that <code>CandidateLocations::Discrete</code> can still be quite inefficient. Imagine you've started with a scan for unknown values and then ran a scan for unchanged valueus. Most values in memory will have been unchanged, but with our current implementation, we are now storing an entire <code>usize</code> address for each of these. One option would be to introduce <code>CandidateLocations::Sparse</code>, which would be a middle ground. You could implement it like <code>Dense</code> and include a vector of booleans telling you which values to consider, or go smaller and use a bitstring or bit vector. You could use a sparse vector data structure.</p>
338<p><code>Value</code> is very much like <code>CandidateLocations</code>, except that it stores a value to compare against and not an address. Here we can either have an exact value, or an older copy of the memory. Again, keeping a copy of the entire memory chunk when all we need is a handful of values is inefficient. You could keep a mapping from addresses to values if you don't have too many. Or you could shrink and fragment the copied memory in a more optimal way. There's a lot of room for improvement!</p>
339<p>What if, despite all of the efforts above, we still don't have enough RAM to store all this information? The Cheat Engine Tutorial doesn't use a lot of memory, but as soon as you try scanning bigger programs, like games, you may find yourself needing several gigabytes worth of memory to remember all the found values in order to compare them in subsequent scans. You may even need to consider dumping all the regions to a file and read from it to run the comparisons. For example, running a scan for &quot;unknown value&quot; in Cheat Engine brings its memory up by the same amount of memory used by the process scanned (which makes sense), but as soon as I ran a scan for &quot;unchanged value&quot; over the misaligned values, Cheat Engine's disk usage skyrocketed to 1GB/s (!) for several seconds on my SSD. After it finished, memory usage went down to normal. It was very likely writing out all candidate locations to disk.</p>
340<h2 id="finale">Finale</h2>
341<p>There is a lot of things to learn from Cheat Engine just by observing its behaviour, and we're only scratching its surface.</p>
342<p>In the next post, we'll tackle the fourth step of the tutorial: Floating points. So far, we have only been working with <code>i32</code> for simplicity. We will need to update our code to be able to account for different data types, which will make it easy to support other types like <code>i16</code>, <code>i64</code>, or even strings, represented as an arbitrary sequence of bytes.</p>
343<p>As usual, you can <a href="https://github.com/lonami/memo">obtain the code for this post</a> over at my GitHub. You can run <code>git checkout step3</code> after cloning the repository to get the right version of the code. This version is a bit cleaner than the one presented in the blog, and contains some of the things described in the <a href="https://lonami.dev/blog/woce-3/#going-beyond">Going beyond</a> section. Until next time!</p>
344<h3 id="footnotes">Footnotes</h3>
345<div class="footnote-definition" id="1"><sup class="footnote-definition-label">1</sup>
346<p>Well, technically, we will perform a million memory reads<sup class="footnote-reference"><a href="#5">5</a></sup>. The issue here is the million calls to <code>ReadProcessMemory</code>, not reading memory per se.</p>
347</div>
348<div class="footnote-definition" id="2"><sup class="footnote-definition-label">2</sup>
349<p>Not currently. After a basic implementation works, writing each implementation by hand and fine-tuning them by treating each of them as a special case could yield significant speed improvements. So although it would be a lot of work, this option shouldn't be ruled out completely.</p>
350</div>
351<div class="footnote-definition" id="3"><sup class="footnote-definition-label">3</sup>
352<p>You could ask the candidate locations where one should read, which would still keep the code reasonably simple.</p>
353</div>
354<div class="footnote-definition" id="4"><sup class="footnote-definition-label">4</sup>
355<p>You could also optimize for this case by determining both the smallest and largest address, and reading enough to cover them both. Or apply additional heuristics to only do so if the ratio of the size you're reading compared to the size you need isn't too large and abort the joint read otherwise. There is a lot of room for optimization here.</p>
356</div>
357<div class="footnote-definition" id="5"><sup class="footnote-definition-label">5</sup>
358<p>(A footnote in a footnote?) The machine registers, memory cache and compiler will all help lower this cost, so the generated executable might not actually need that many reads from RAM. But that's getting way too deep into the details now.</p>
359</div>
360</content>
361 </entry>
362 <entry xml:lang="en">
363 <title>Writing our own Cheat Engine: Exact Value scanning</title>
364 <published>2021-02-12T00:00:00+00:00</published>
365 <updated>2021-02-19T00:00:00+00:00</updated>
366 <link href="https://lonami.dev/blog/woce-2/" type="text/html"/>
367 <id>https://lonami.dev/blog/woce-2/</id>
368 <content type="html"><p>This is part 2 on the <em>Writing our own Cheat Engine</em> series:</p>
369<ul>
370<li><a href="/blog/woce-1">Part 1: Introduction</a> (start here if you're new to the series!)</li>
371<li>Part 2: Exact Value scanning</li>
372<li><a href="/blog/woce-3">Part 3: Unknown initial value</a></li>
373</ul>
374<p>In the introduction, we spent a good deal of time enumerating all running processes just so we could find out the pid we cared about. With the pid now in our hands, we can do pretty much anything to its corresponding process.</p>
375<p>It's now time to read the process' memory and write to it. If our process was a single-player game, this would enable us to do things like setting a very high value on the player's current health pool, making us invincible. This technique will often not work for multi-player games, because the server likely knows your true current health (the most you could probably do is make the client render an incorrect value). However, if the server is crappy and it trusts the client, then you're still free to mess around with your current health.</p>
376<p>Even if we don't want to write to the process' memory, reading is still very useful. Maybe you could enhance your experience by making a custom overlay that displays useful information, or something that makes noise if it detects the life is too low, or even simulating a keyboard event to automatically recover some mana when you're running low.</p>
377<p>Be warned about anti-cheat systems. Anything beyond a basic game is likely to have some protection measures in place, making the analysis more difficult (perhaps the values are scrambled in memory), or even pinging the server if it detects something fishy.</p>
378<p><strong>I am not responsible for any bans!</strong> Use your brain before messing with online games, and don't ruin the fun for everyone else. If you get caught for cheating, I don't want to know about it.</p>
379<p>Now that all <a href="https://www.urbandictionary.com/define.php?term=script%20kiddie">script kiddies</a> have left the room, let's proceed with the post.</p>
380<h2 id="exact-value-scanning">Exact Value scanning</h2>
381<details open><summary>Cheat Engine Tutorial: Step 2</summary>
382<blockquote>
383<p>Now that you have opened the tutorial with Cheat Engine let's get on with the next step.</p>
384<p>You can see at the bottom of this window is the text Health: xxx. Each time you click 'Hit me' your health gets decreased.</p>
385<p>To get to the next step you have to find this value and change it to 1000</p>
386<p>To find the value there are different ways, but I'll tell you about the easiest, 'Exact Value': First make sure value type is set to at least 2-bytes or 4-bytes. 1-byte will also work, but you'll run into an easy to fix problem when you've found the address and want to change it. The 8-byte may perhaps works if the bytes after the address are 0, but I wouldn't take the bet. Single, double, and the other scans just don't work, because they store the value in a different way.</p>
387<p>When the value type is set correctly, make sure the scantype is set to 'Exact Value'. Then fill in the number your health is in the value box. And click 'First Scan'. After a while (if you have a extremely slow pc) the scan is done and the results are shown in the list on the left</p>
388<p>If you find more than 1 address and you don't know for sure which address it is, click 'Hit me', fill in the new health value into the value box, and click 'Next Scan'. Repeat this until you're sure you've found it. (that includes that there's only 1 address in the list.....)</p>
389<p>Now double click the address in the list on the left. This makes the address pop-up in the list at the bottom, showing you the current value. Double click the value, (or select it and press enter), and change the value to 1000.</p>
390<p>If everything went ok the next button should become enabled, and you're ready for the next step.</p>
391<p>Note: If you did anything wrong while scanning, click &quot;New Scan&quot; and repeat the scanning again. Also, try playing around with the value and click 'hit me'</p>
392</blockquote>
393</details>
394<h2 id="our-first-scan">Our First Scan</h2>
395<p>The Cheat Engine tutorial talks about &quot;value types&quot; and &quot;scan types&quot; like &quot;exact value&quot;.</p>
396<p>The <strong>value types</strong> will help us narrow down <em>what</em> we're looking for. For example, the integer type <code>i32</code> is represented in memory as 32 bits, or 4 bytes. However, <code>f32</code> is <em>also</em> represented by 4 bytes, and so is <code>u32</code>. Or perhaps the 4 bytes represent RGBA values of a color! So any 4 bytes in memory can be interpreted in many ways, and it's up to us to decide which way we interpret the bytes in.</p>
397<p>When programming, numbers which are 32-bit wide are common, as they're a good (and fast) size to work with. Scanning for this type is often a good bet. For positive numbers, <code>i32</code> is represented the same as <code>u32</code> in memory, so even if the value turns out to not be signed, the scan is likely to work. Focusing on <code>i32</code> will save us from scanning for <code>f32</code> or even other types, like interpreting 8 bytes for <code>i64</code>, <code>f64</code>, or less bytes like <code>i16</code>.</p>
398<p>The <strong>scan types</strong> will help us narrow down <em>how</em> we're looking for a value. Scanning for an exact value means what you think it does: interpret all 4 bytes in the process' memory as our value type, and check if they exactly match our value. This will often yield a lot of candidates, but it will be enough to get us started. Variations of the exact scan include checking for all values below a threshold, above, in between, or even just… unknown.</p>
399<p>What's the point of scanning for unknown values if <em>everything</em> in memory is unknown? Sometimes you don't have a concrete value. Maybe your health pool is a bar and it nevers tell you how much health you actually have, just a visual indicator of your percentage left, even if the health is not stored as a percentage. As we will find later on, scanning for unknown values is more useful than it might appear at first.</p>
400<p>We can access the memory of our own program by guessing random pointers and trying to read from them. But Windows isolates the memory of each program, so no pointer we could ever guess will let us read from the memory of another process. Luckily for us, searching for &quot;read process memory winapi&quot; leads us to the <a href="https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory"><code>ReadProcessMemory</code></a> function. Spot on.</p>
401<pre><code class="language-rust" data-lang="rust">pub fn read_memory(&amp;self, addr: usize, n: usize) -&gt; io::Result&lt;Vec&lt;u8&gt;&gt; {
402 todo!()
403}
404</code></pre>
405<p>Much like trying to dereference a pointer pointing to released memory or even null, reading from an arbitrary address can fail for the same reasons (and more). We will want to signal this with <code>io::Result</code>. It's funny to note that, even though we're doing something that seems wildly unsafe (reading arbitrary memory, even if the other process is mutating it at the same time), the function is perfectly safe. If we cannot read something, it will return <code>Err</code>, but if it succeeds, it has taken a snapshot of the memory of the process, and the returned value will be correctly initialized.</p>
406<p>The function will be defined inside our <code>impl Process</code>, since it conveniently holds an open handle to the process in question. It takes <code>&amp;self</code>, because we do not need to mutate anything in the <code>Process</code> instance. After adding the <code>memoryapi</code> feature to <code>Cargo.toml</code>, we can perform the call:</p>
407<pre><code class="language-rust" data-lang="rust">let mut buffer = Vec::&lt;u8&gt;::with_capacity(n);
408let mut read = 0;
409
410// SAFETY: the buffer points to valid memory, and the buffer size is correctly set.
411if unsafe {
412 winapi::um::memoryapi::ReadProcessMemory(
413 self.handle.as_ptr(),
414 addr as *const _,
415 buffer.as_mut_ptr().cast(),
416 buffer.capacity(),
417 &amp;mut read,
418 )
419} == FALSE
420{
421 Err(io::Error::last_os_error())
422} else {
423 // SAFETY: the call succeeded and `read` contains the amount of bytes written.
424 unsafe { buffer.set_len(read as usize) };
425 Ok(buffer)
426}
427</code></pre>
428<p>Great! But the address space is somewhat large. 64 bits large. Eighteen quintillion, four hundred and forty-six quadrillion, seven hundred and forty-four trillion, seventy-three billion, seven hundred and nine million, five hundred and fifty-one thousand, six hundred and sixteen<sup class="footnote-reference"><a href="#1">1</a></sup> large. You gave up reading that, didn't you? Anyway, 18'446'744'073'709'551'616 is a <em>big</em> number.</p>
429<p>I am not willing to wait for the program to scan over so many values. I don't even have 16 <a href="https://en.wikipedia.org/wiki/Orders_of_magnitude_(data)">exbibytes</a> of RAM installed on my laptop yet<sup class="footnote-reference"><a href="#2">2</a></sup>! What's up with that?</p>
430<h2 id="memory-regions">Memory regions</h2>
431<p>The program does not actually have all that memory allocated (surprise!). Random-guessing an address is extremely likely to point out to invalid memory. Reading from the start of the address space all the way to the end would not be any better. And we <strong>need</strong> to do better.</p>
432<p>We need to query for the memory regions allocated to the program. For this purpose we can use <a href="https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualqueryex"><code>VirtualQueryEx</code></a>.</p>
433<blockquote>
434<p>Retrieves information about a range of pages within the virtual address space of a specified process.</p>
435</blockquote>
436<p>We have enumerated things before, and this function is not all that different.</p>
437<pre><code class="language-rust" data-lang="rust">fn memory_regions(&amp;self) -&gt; io::Result&lt;winapi::um::winnt::MEMORY_BASIC_INFORMATION&gt; {
438 let mut info = MaybeUninit::uninit();
439
440 // SAFETY: the info structure points to valid memory.
441 let written = unsafe {
442 winapi::um::memoryapi::VirtualQueryEx(
443 self.handle.as_ptr(),
444 std::ptr::null(),
445 info.as_mut_ptr(),
446 mem::size_of::&lt;winapi::um::winnt::MEMORY_BASIC_INFORMATION&gt;(),
447 )
448 };
449 if written == 0 {
450 Err(io::Error::last_os_error())
451 } else {
452 // SAFETY: a non-zero amount was written to the structure
453 Ok(unsafe { info.assume_init() })
454 }
455}
456</code></pre>
457<p>We start with a base address of zero<sup class="footnote-reference"><a href="#3">3</a></sup> (<code>std::ptr::null()</code>), and ask the function to tell us what's in there. Let's try it out, with the <code>impl-debug</code> crate feature in <code>Cargo.toml</code>:</p>
458<pre><code class="language-rust" data-lang="rust">dbg!(process.memory_regions());
459</code></pre>
460<pre><code>&gt;cargo run
461Compiling memo v0.1.0
462
463error[E0277]: `winapi::um::winnt::MEMORY_BASIC_INFORMATION` doesn't implement `std::fmt::Debug`
464 --&gt; src\main.rs:185:5
465 |
466185 | dbg!(process.memory_regions());
467 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `winapi::um::winnt::MEMORY_BASIC_INFORMATION` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
468</code></pre>
469<p>That's annoying. It seems not everything has an <code>impl std::fmt::Debug</code>, and <a href="https://github.com/retep998/winapi-rs/issues/548#issuecomment-355278090">you're supposed to send a PR</a> if you want it to have debug, even if the <code>impl-debug</code> feature is set. I'm surprised they don't auto-generate all of this and have to rely on manually adding <code>Debug</code> as needed? Oh well, let's get rid of the feature and print it out ourselves:</p>
470<pre><code>eprintln!(
471 &quot;Region:
472 BaseAddress: {:?}
473 AllocationBase: {:?}
474 AllocationProtect: {:?}
475 RegionSize: {:?}
476 State: {:?}
477 Protect: {:?}
478 Type: {:?}&quot;,
479 region.BaseAddress,
480 region.AllocationBase,
481 region.AllocationProtect,
482 region.RegionSize,
483 region.State,
484 region.Protect,
485 region.Type,
486);
487</code></pre>
488<p>Hopefully we don't need to do this often:</p>
489<pre><code>&gt;cargo run
490 Compiling memo v0.1.0
491 Finished dev [unoptimized + debuginfo] target(s) in 0.60s
492 Running `target\debug\memo.exe`
493
494Region:
495 BaseAddress: 0x0
496 AllocationBase: 0x0
497 AllocationProtect: 0
498 RegionSize: 65536
499 State: 65536
500 Protect: 1
501 Type: 0
502</code></pre>
503<p>Awesome! There is a region at <code>null</code>, and the <code>AllocationProtect</code> of zero indicates that &quot;the caller does not have access&quot; when the region was created. However, <code>Protect</code> is <code>1</code>, and that is the <em>current</em> protection level. A value of one indicates <a href="https://docs.microsoft.com/en-us/windows/win32/memory/memory-protection-constants"><code>PAGE_NOACCESS</code></a>:</p>
504<blockquote>
505<p>Disables all access to the committed region of pages. An attempt to read from, write to, or execute the committed region results in an access violation.</p>
506</blockquote>
507<p>Now that we know that the first region starts at 0 and has a size of 64 KiB, we can simply query for the page at <code>(current base + current size)</code> to fetch the next region. Essentially, we want to loop until it fails, after which we'll know there are no more pages<sup class="footnote-reference"><a href="#4">4</a></sup>:</p>
508<pre><code class="language-rust" data-lang="rust">pub fn memory_regions(&amp;self) -&gt; Vec&lt;winapi::um::winnt::MEMORY_BASIC_INFORMATION&gt; {
509 let mut base = 0;
510 let mut regions = Vec::new();
511 let mut info = MaybeUninit::uninit();
512
513 loop {
514 // SAFETY: the info structure points to valid memory.
515 let written = unsafe {
516 winapi::um::memoryapi::VirtualQueryEx(
517 self.handle.as_ptr(),
518 base as *const _,
519 info.as_mut_ptr(),
520 mem::size_of::&lt;winapi::um::winnt::MEMORY_BASIC_INFORMATION&gt;(),
521 )
522 };
523 if written == 0 {
524 break regions;
525 }
526 // SAFETY: a non-zero amount was written to the structure
527 let info = unsafe { info.assume_init() };
528 base = info.BaseAddress as usize + info.RegionSize;
529 regions.push(info);
530 }
531}
532</code></pre>
533<p><code>RegionSize</code> is:</p>
534<blockquote>
535<p>The size of the region beginning at the base address in which all pages have identical attributes, in bytes.</p>
536</blockquote>
537<p>…which also hints that the value we want is &quot;base address&quot;, not the &quot;allocation base&quot;. With these two values, we can essentially iterate over all the page ranges:</p>
538<pre><code class="language-rust" data-lang="rust">dbg!(process.memory_regions().len());
539</code></pre>
540<pre><code>&gt;cargo run
541 Compiling memo v0.1.0
542 Finished dev [unoptimized + debuginfo] target(s) in 0.63s
543 Running `target\debug\memo.exe`
544
545[src\main.rs:189] process.memory_regions().len() = 367
546</code></pre>
547<p>That's a lot of pages!</p>
548<h2 id="protection-levels">Protection levels</h2>
549<p>Let's try to narrow the amount of pages down. How many pages aren't <code>PAGE_NOACCESS</code>?</p>
550<pre><code class="language-rust" data-lang="rust">dbg!(process
551 .memory_regions()
552 .into_iter()
553 .filter(|p| p.Protect != winapi::um::winnt::PAGE_NOACCESS)
554 .count());
555</code></pre>
556<pre><code>295
557</code></pre>
558<p>Still a fair bit! Most likely, there are just a few interleaved <code>NOACCESS</code> pages, and the rest are allocated each with different protection levels. How much memory do we need to scan through?</p>
559<pre><code class="language-rust" data-lang="rust">dbg!(process
560 .memory_regions()
561 .into_iter()
562 .filter(|p| p.Protect != winapi::um::winnt::PAGE_NOACCESS)
563 .map(|p| p.RegionSize)
564 .sum::&lt;usize&gt;());
565</code></pre>
566<pre><code>4480434176
567</code></pre>
568<p>Wait, what? What do you mean over 4 GiB? The Task Manager claims that the Cheat Engine Tutorial is only using 2.1 MB worth of RAM! Perhaps we can narrow down the <a href="https://docs.microsoft.com/en-us/windows/win32/memory/memory-protection-constants">protection levels</a> a bit more. If you look at the scan options in Cheat Engine, you will notice the &quot;Memory Scan Options&quot; groupbox. By default, it only scans for memory that is writable, and doesn't care if it's executable or not:</p>
569<pre><code class="language-rust" data-lang="rust">let mask = winnt::PAGE_EXECUTE_READWRITE
570 | winnt::PAGE_EXECUTE_WRITECOPY
571 | winnt::PAGE_READWRITE
572 | winnt::PAGE_WRITECOPY;
573
574dbg!(process
575 .memory_regions()
576 .into_iter()
577 .filter(|p| (p.Protect &amp; mask) != 0)
578 .map(|p| p.RegionSize)
579 .sum::&lt;usize&gt;());
580</code></pre>
581<p>Each memory protection level has its own bit, so we can OR them all together to have a single mask. When ANDing this mask with the protection level, if any bit is set, it will be non-zero, meaning we want to keep this region.</p>
582<p>Don't ask me why there isn't a specific bit for &quot;write&quot;, &quot;read&quot;, &quot;execute&quot;, and there are only bits for combinations. I guess this way Windows forbids certain combinations.</p>
583<pre><code>2580480
584</code></pre>
585<p>Hey, that's close to the value shown by the Task Manager! A handfull of megabytes is a lot more manageable than 4 entire gigabytes.</p>
586<h2 id="actually-running-our-first-scan">Actually running our First Scan</h2>
587<p>Okay, we have all the memory regions from which the program can read, write, or execute. Now we also can read the memory in these regions:</p>
588<pre><code class="language-rust" data-lang="rust">let regions = process
589 .memory_regions()
590 .into_iter()
591 .filter(|p| (p.Protect &amp; mask) != 0)
592 .collect::&lt;Vec&lt;_&gt;&gt;();
593
594println!(&quot;Scanning {} memory regions&quot;, regions.len());
595
596regions.into_iter().for_each(|region| {
597 match process.read_memory(region.BaseAddress as _, region.RegionSize) {
598 Ok(memory) =&gt; todo!(),
599 Err(err) =&gt; eprintln!(
600 &quot;Failed to read {} bytes at {:?}: {}&quot;,
601 region.RegionSize, region.BaseAddress, err,
602 ),
603 }
604})
605</code></pre>
606<p>All that's left is for us to scan for a target value. To do this, we want to iterate over all the <a href="https://doc.rust-lang.org/stable/std/primitive.slice.html#method.windows"><code>slice::windows</code></a> of size equal to the size of our scan type.</p>
607<pre><code class="language-rust" data-lang="rust">let target: i32 = ...;
608let target = target.to_ne_bytes();
609
610// -snip-
611
612// inside the Ok match, replacing the todo!() -- this is where the first scan happens
613Ok(memory) =&gt; memory
614 .windows(target.len())
615 .enumerate()
616 .for_each(|(offset, window)| {
617 if window == target {
618 println!(
619 &quot;Found exact value at [{:?}+{:x}]&quot;,
620 region.BaseAddress, offset
621 );
622 }
623 })
624</code></pre>
625<p>We convert the 32-bit exact target value to its memory representation as a byte array in <a href="https://doc.rust-lang.org/stable/std/primitive.i32.html#method.to_ne_bytes">native byte order</a>. This way we can compare the target bytes with the window bytes. Another option is to interpret the window bytes as an <code>i32</code> with <code>from_be_bytes</code>, but <code>slice::windows</code> gives us slices of type <code>&amp;[u8]</code>, and <code>from_be_bytes</code> wants an <code>[u8; 4]</code> array, so it's a bit more annoying to convert.</p>
626<p>This is enough to find the value in the process' memory!</p>
627<pre><code>Found exact value at [0x10000+aec]
628Failed to read 12288 bytes at 0x13f8000: Only part of a ReadProcessMemory or WriteProcessMemory request was completed. (os error 299)
629Found exact value at [0x14f0000+3188]
630Found exact value at [0x14f0000+ac74]
631...
632Found exact value at [0x10030e000+1816]
633Found exact value at [0x7ff8f7b93000+441a]
634...
635Found exact value at [0x7ff8fb381000+4023]
636</code></pre>
637<p>The tutorial starts out with health &quot;100&quot;, which is what I scanned. Apparently, there are nearly a hundred of <code>100</code>-valued integers stored in the memory of the tutorial.</p>
638<p>Attentive readers will notice that some values are located at an offset modulo 4. In Cheat Engine, this is known as &quot;Fast Scan&quot;, which is enabled by default with an alignment of 4. Most of the time, values are aligned in memory, and this alignment often corresponds with the size of the type itself. For 4-byte integers, it's common that they're 4-byte aligned.</p>
639<p>We can perform a fast scan ourselves with <a href="https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.step_by"><code>step_by</code></a><sup class="footnote-reference"><a href="#5">5</a></sup>:</p>
640<pre><code class="language-rust" data-lang="rust">memory
641 .windows(target.len())
642 .enumerate()
643 .step_by(4)
644 .for_each(...)
645</code></pre>
646<p>As a bonus, over half the addresses are gone, so we have less results to worry about<sup class="footnote-reference"><a href="#6">6</a></sup>.</p>
647<h2 id="next-scan">Next Scan</h2>
648<p>The first scan gave us way too many results. We have no way to tell which is the correct one, as they all have the same value. What we need to do is a <em>second</em> scan at the <em>locations we just found</em>. This way, we can get a second reading, and compare it against a new value. If it's the same, we're on good track, and if not, we can discard a location. Repeating this process lets us cut the hundreds of potential addresses to just a handful of them.</p>
649<p>For example, let's say we're scanning our current health of <code>100</code> in a game. This gives us over a hundred addresses that point to the value of <code>100</code>. If we go in-game and get hit<sup class="footnote-reference"><a href="#7">7</a></sup> by some enemy and get our health down to, say, <code>99</code> (we have a lot of defense), we can then read the memory at the hundred memory locations we found before. If this second reading is not <code>99</code>, we know the address does not actually point to our health pool and it just happened to also contain a <code>100</code> on the first scan. This address can be removed from the list of potential addresses pointing to our health.</p>
650<p>Let's do that:</p>
651<pre><code class="language-rust" data-lang="rust">// new vector to hold the locations, before getting into `memory.windows`' for-each
652let mut locations = Vec::with_capacity(regions.len());
653
654// -snip-
655
656// updating the `println!(&quot;Found exact value...&quot;)` to store the location instead.
657if window == target {
658 locations.push(region.BaseAddress as usize + offset);
659}
660
661// -snip-
662
663// performing a second scan on the locations the first scan found.
664let target: i32 = ...;
665let target = target.to_ne_bytes();
666locations.retain(|addr| match process.read_memory(*addr, target.len()) {
667 Ok(memory) =&gt; memory == target,
668 Err(_) =&gt; false,
669});
670
671println!(&quot;Now have {} locations&quot;, locations.len());
672</code></pre>
673<p>We create a vector to store all the locations the first scan finds, and then retain those that match a second target value. You may have noticed that we perform a memory read, and thus a call to the Windows API, for every single address. With a hundred locations to read from, this is not a big deal, but oftentimes you will have tens of thousands of addresses. For the time being, we will not worry about this inefficiency, but we will get back to it once it matters:</p>
674<pre><code>Scanning 98 memory regions
675Which exact value to scan for?: 100
676Failed to read 12288 bytes at 0x13f8000: Only part of a ReadProcessMemory or WriteProcessMemory request was completed. (os error 299)
677...
678Found 49 locations
679Which exact value to scan for next?: 99
680Now have 1 locations
681</code></pre>
682<p>Sweet! In a real-world scenario, you will likely need to perform these additional scans a couple of times, and even then, there may be more than one value left no matter what.</p>
683<p>For good measure, we'll wrap our <code>retain</code> in a <code>while</code> loop<sup class="footnote-reference"><a href="#8">8</a></sup>:</p>
684<pre><code class="language-rust" data-lang="rust">while locations.len() != 1 {
685 let target: i32 = ...;
686 let target = target.to_ne_bytes();
687 locations.retain(...);
688}
689</code></pre>
690<h2 id="modifying-memory">Modifying memory</h2>
691<p>Now that we have very likely locations pointing to our current health in memory, all that's left is writing our new desired value to gain infinite health<sup class="footnote-reference"><a href="#9">9</a></sup>. Much like how we're able to read memory with <code>ReadProcessMemory</code>, we can write to it with <a href="https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory"><code>WriteProcessMemory</code></a>. Its usage is straightforward:</p>
692<pre><code class="language-rust" data-lang="rust">pub fn write_memory(&amp;self, addr: usize, value: &amp;[u8]) -&gt; io::Result&lt;usize&gt; {
693 let mut written = 0;
694
695 // SAFETY: the input value buffer points to valid memory.
696 if unsafe {
697 winapi::um::memoryapi::WriteProcessMemory(
698 self.handle.as_ptr(),
699 addr as *mut _,
700 value.as_ptr().cast(),
701 value.len(),
702 &amp;mut written,
703 )
704 } == FALSE
705 {
706 Err(io::Error::last_os_error())
707 } else {
708 Ok(written)
709 }
710}
711</code></pre>
712<p>Similar to how writing to a file can return short, writing to a memory location could also return short. Here we mimic the API for writing files and return the number of bytes written. The documentation indicates that we could actually ignore the amount written by passing <code>ptr::null_mut()</code> as the last parameter, but it does no harm to retrieve the written count as well.</p>
713<pre><code class="language-rust" data-lang="rust">let new_value: i32 = ...;
714locations
715 .into_iter()
716 .for_each(|addr| match process.write_memory(addr, &amp;new_value) {
717 Ok(n) =&gt; eprintln!(&quot;Written {} bytes to [{:x}]&quot;, n, addr),
718 Err(e) =&gt; eprintln!(&quot;Failed to write to [{:x}]: {}&quot;, addr, e),
719 });
720</code></pre>
721<p>And just like that:</p>
722<pre><code>Now have 1 location(s)
723Enter new memory value: 1000
724Failed to write to [15d8b90]: Access is denied. (os error 5)
725</code></pre>
726<p>…oh noes. Oh yeah. The documentation, which I totally didn't forget to read, mentions:</p>
727<blockquote>
728<p>The handle must have <code>PROCESS_VM_WRITE</code> and <code>PROCESS_VM_OPERATION</code> access to the process.</p>
729</blockquote>
730<p>We currently open our process with <code>PROCESS_QUERY_INFORMATION</code> and <code>PROCESS_VM_READ</code>, which is enough for reading, but not for writing. Let's adjust <code>OpenProcess</code> to accomodate for our new requirements:</p>
731<pre><code class="language-rust" data-lang="rust">winapi::um::processthreadsapi::OpenProcess(
732 winnt::PROCESS_QUERY_INFORMATION
733 | winnt::PROCESS_VM_READ
734 | winnt::PROCESS_VM_WRITE
735 | winnt::PROCESS_VM_OPERATION,
736 FALSE,
737 pid,
738)
739</code></pre>
740<p>Behold:</p>
741<pre><code>Now have 1 location(s)
742Enter new memory value: 1000
743Written 4 bytes to [15d8b90]
744</code></pre>
745<p><img src="https://user-images.githubusercontent.com/6297805/107829541-3f4f2d00-6d8a-11eb-87c4-e2f2d505afbc.png" alt="Tutorial complete with memo" /></p>
746<p>Isn't that active <em>Next</em> button just beautiful?</p>
747<h2 id="finale">Finale</h2>
748<p>This post somehow ended up being longer than part one, but look at what we've achieved! We completed a step of the Cheat Engine Tutorial <em>without using Cheat Engine</em>. Just pure Rust. Figuring out how a program works and reimplementing it yourself is a great way to learn what it's doing behind the scenes. And now that this code is yours, you can extend it as much as you like, without being constrained by Cheat Engine's UI. You can automate it as much as you want.</p>
749<p>And we're not even done. The current tutorial has nine steps, and three additional graphical levels.</p>
750<p>In the next post, we'll tackle the third step of the tutorial: Unknown initial value. This will pose a challenge, because with just 2 MiB of memory, storing all the 4-byte aligned locations would require 524288 addresses (<code>usize</code>, 8 bytes). This adds up to twice as much memory as the original program (4 MiB), but that's not our main concern, having to perform over five hundred thousand API calls is!</p>
751<p>Remember that you can <a href="https://github.com/lonami/memo">obtain the code for this post</a> over at my GitHub. You can run <code>git checkout step2</code> after cloning the repository to get the right version of the code.</p>
752<h3 id="footnotes">Footnotes</h3>
753<div class="footnote-definition" id="1"><sup class="footnote-definition-label">1</sup>
754<p>I did in fact use an online tool to spell it out for me.</p>
755</div>
756<div class="footnote-definition" id="2"><sup class="footnote-definition-label">2</sup>
757<p>16 GiB is good enough for my needs. I don't think I'll ever upgrade to 16 EiB.</p>
758</div>
759<div class="footnote-definition" id="3"><sup class="footnote-definition-label">3</sup>
760<p>Every address we query should have a corresponding region, even if it's not allocated or we do not have access. This is why we can query for the memory address zero to get its corresponding region.</p>
761</div>
762<div class="footnote-definition" id="4"><sup class="footnote-definition-label">4</sup>
763<p>Another option is to <a href="https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsysteminfo"><code>GetSystemInfo</code></a> to determine the <code>lpMinimumApplicationAddress</code> and <code>lpMaximumApplicationAddress</code> and only work within bounds.</p>
764</div>
765<div class="footnote-definition" id="5"><sup class="footnote-definition-label">5</sup>
766<p>Memory regions are page-aligned, which is a large power of two. Our alignment of 4 is much lower than this, so we're guaranteed to start off at an aligned address.</p>
767</div>
768<div class="footnote-definition" id="6"><sup class="footnote-definition-label">6</sup>
769<p>If it turns out that the value was actually misaligned, we will miss it. You will notice this if, after going through the whole process, there are no results. It could mean that either the value type is wrong, or the value type is misaligned. In the worst case, the value is not stored directly but is rather computed with something like <code>maximum - stored</code>, or XORed with some magic value, or a myriad other things.</p>
770</div>
771<div class="footnote-definition" id="7"><sup class="footnote-definition-label">7</sup>
772<p>You could do this without getting hit, and just keep on repeating the scan for the same value over and over again. This does work, but the results are suboptimal, because there are also many other values that didn't change. Scanning for a changed value is a better option.</p>
773</div>
774<div class="footnote-definition" id="8"><sup class="footnote-definition-label">8</sup>
775<p>You could actually just go ahead and try to modify the memory at the hundred addresses you just found, although don't be surprised if the program starts to misbehave!</p>
776</div>
777<div class="footnote-definition" id="9"><sup class="footnote-definition-label">9</sup>
778<p>Okay, we cannot fit infinity in an <code>i32</code>. However, we can fit sufficiently large numbers. Like <code>1000</code>, which is enough to complete the tutorial.</p>
779</div>
780</content>
781 </entry>
782 <entry xml:lang="en">
783 <title>Writing our own Cheat Engine: Introduction</title>
784 <published>2021-02-07T00:00:00+00:00</published>
785 <updated>2021-02-19T00:00:00+00:00</updated>
786 <link href="https://lonami.dev/blog/woce-1/" type="text/html"/>
787 <id>https://lonami.dev/blog/woce-1/</id>
788 <content type="html"><p>This is part 1 on the <em>Writing our own Cheat Engine</em> series:</p>
789<ul>
790<li>Part 1: Introduction</li>
791<li><a href="/blog/woce-2">Part 2: Exact Value scanning</a></li>
792<li><a href="/blog/woce-3">Part 3: Unknown initial value</a></li>
793</ul>
794<p><a href="https://cheatengine.org/">Cheat Engine</a> is a tool designed to modify single player games and contains other useful tools within itself that enable its users to debug games or other applications. It comes with a memory scanner, (dis)assembler, inspection tools and a handful other things. In this series, we will be writing our own tiny Cheat Engine capable of solving all steps of the tutorial, and diving into how it all works underneath.</p>
795<p>Needless to say, we're doing this for private and educational purposes only. One has to make sure to not violate the EULA or ToS of the specific application we're attaching to. This series, much like cheatengine.org, does not condone the illegal use of the code shared.</p>
796<p>Cheat Engine is a tool for Windows, so we will be developing for Windows as well. However, you can also <a href="https://stackoverflow.com/q/12977179/4759433">read memory from Linux-like systems</a>. <a href="https://github.com/scanmem/scanmem">GameConqueror</a> is a popular alternative to Cheat Engine on Linux systems, so if you feel adventurous, you could definitely follow along too! The techniques shown in this series apply regardless of how we read memory from a process. You will learn a fair bit about doing FFI in Rust too.</p>
797<p>We will be developing the application in Rust, because it enables us to interface with the Windows API easily, is memory safe (as long as we're careful with <code>unsafe</code>!), and is speedy (we will need this for later steps in the Cheat Engine tutorial). You could use any language of your choice though. For example, <a href="https://lonami.dev/blog/ctypes-and-windows/">Python also makes it relatively easy to use the Windows API</a>. You don't need to be a Rust expert to follow along, but this series assumes some familiarity with C-family languages. Slightly advanced concepts like the use of <code>unsafe</code> or the <code>MaybeUninit</code> type will be briefly explained. What a <code>fn</code> is or what <code>let</code> does will not be explained.</p>
798<p><a href="https://github.com/cheat-engine/cheat-engine/">Cheat Engine's source code</a> is mostly written in Pascal and C. And it's <em>a lot</em> of code, with a very flat project structure, and files ranging in the thousand lines of code each. It's daunting<sup class="footnote-reference"><a href="#1">1</a></sup>. It's a mature project, with a lot of knowledge encoded in the code base, and a lot of features like distributed scanning or an entire disassembler. Unfortunately, there's not a lot of comments. For these reasons, I'll do some guesswork when possible as to how it's working underneath, rather than actually digging into what Cheat Engine is actually doing.</p>
799<p>With that out of the way, let's get started!</p>
800<h2 id="welcome-to-the-cheat-engine-tutorial">Welcome to the Cheat Engine Tutorial</h2>
801<details open><summary>Cheat Engine Tutorial: Step 1</summary>
802<blockquote>
803<p>This tutorial will teach you the basics of cheating in video games. It will also show you foundational aspects of using Cheat Engine (or CE for short). Follow the steps below to get started.</p>
804<ol>
805<li>Open Cheat Engine if it currently isn't running.</li>
806<li>Click on the &quot;Open Process&quot; icon (it's the top-left icon with the computer on it, below &quot;File&quot;.).</li>
807<li>With the Process List window now open, look for this tutorial's process in the list. It will look something like &gt; &quot;00001F98-Tutorial-x86_64.exe&quot; or &quot;0000047C-Tutorial-i386.exe&quot;. (The first 8 numbers/letters will probably be different.)</li>
808<li>Once you've found the process, click on it to select it, then click the &quot;Open&quot; button. (Don't worry about all the &gt; other buttons right now. You can learn about them later if you're interested.)</li>
809</ol>
810<p>Congratulations! If you did everything correctly, the process window should be gone with Cheat Engine now attached to the &gt; tutorial (you will see the process name towards the top-center of CE).</p>
811<p>Click the &quot;Next&quot; button below to continue, or fill in the password and click the &quot;OK&quot; button to proceed to that step.)</p>
812<p>If you're having problems, simply head over to forum.cheatengine.org, then click on &quot;Tutorials&quot; to view beginner-friendly &gt; guides!</p>
813</blockquote>
814</details>
815<h2 id="enumerating-processes">Enumerating processes</h2>
816<p>Our first step is attaching to the process we want to work with. But we need a way to find that process in the first place! Having to open the task manager, look for the process we care about, noting down the process ID (PID), and slapping it in the source code is not satisfying at all. Instead, let's enumerate all the processes from within the program, and let the user select one by typing its name.</p>
817<p>From a quick <a href="https://ddg.gg/winapi%20enumerate%20all%20processes">DuckDuckGo search</a>, we find an official tutorial for <a href="https://docs.microsoft.com/en-us/windows/win32/psapi/enumerating-all-processes">Enumerating All Processes</a>, which leads to the <a href="https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-enumprocesses"><code>EnumProcesses</code></a> call. Cool! Let's slap in the <a href="https://crates.io/crates/winapi"><code>winapi</code></a> crate on <code>Cargo.toml</code>, because I don't want to write all the definitions by myself:</p>
818<pre><code class="language-toml" data-lang="toml">[dependencies]
819winapi = { version = &quot;0.3.9&quot;, features = [&quot;psapi&quot;] }
820</code></pre>
821<p>Because <a href="https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-enumprocesses"><code>EnumProcesses</code></a> is in <code>Psapi.h</code> (you can see this in the online page of its documentation), we know we'll need the <code>psapi</code> crate feature. Another option is to search for it in the <a href="https://docs.rs/winapi/"><code>winapi</code> documentation</a> and noting down the parent module where its stored.</p>
822<p>The documentation for the method has the following remark:</p>
823<blockquote>
824<p>It is a good idea to use a large array, because it is hard to predict how many processes there will be at the time you call <strong>EnumProcesses</strong>.</p>
825</blockquote>
826<p><em>Sidenote: reading the documentation for the methods we'll use from the Windows API is extremely important. There's a lot of gotchas involved, so we need to make sure we're extra careful.</em></p>
827<p>1024 is a pretty big number, so let's go with that:</p>
828<pre><code class="language-rust" data-lang="rust">use std::io;
829use std::mem;
830use winapi::shared::minwindef::{DWORD, FALSE};
831
832pub fn enum_proc() -&gt; io::Result&lt;Vec&lt;u32&gt;&gt; {
833 let mut pids = Vec::&lt;DWORD&gt;::with_capacity(1024);
834 let mut size = 0;
835 // SAFETY: the pointer is valid and the size matches the capacity.
836 if unsafe {
837 winapi::um::psapi::EnumProcesses(
838 pids.as_mut_ptr(),
839 (pids.capacity() * mem::size_of::&lt;DWORD&gt;()) as u32,
840 &amp;mut size,
841 )
842 } == FALSE
843 {
844 return Err(io::Error::last_os_error());
845 }
846
847 todo!()
848}
849</code></pre>
850<p>We allocate enough space<sup class="footnote-reference"><a href="#2">2</a></sup> for 1024 <code>pids</code> in a vector<sup class="footnote-reference"><a href="#3">3</a></sup>, and pass a mutable pointer to the contents to <code>EnumProcesses</code>. Note that the size of the array is in <em>bytes</em>, not items, so we need to multiply the capacity by the size of <code>DWORD</code>. The API likes to use <code>u32</code> for sizes, unlike Rust which uses <code>usize</code>, so we need a cast.</p>
851<p>Last, we need another mutable variable where the amount of bytes written is stored, <code>size</code>.</p>
852<blockquote>
853<p>If the function fails, the return value is zero. To get extended error information, call <a href="https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-getlasterror"><code>GetLastError</code></a>.</p>
854</blockquote>
855<p>That's precisely what we do. If it returns false (zero), we return the last OS error. Rust provides us with <a href="https://doc.rust-lang.org/stable/std/io/struct.Error.html#method.last_os_error"><code>std::io::Error::last_os_error</code></a>, which essentially makes that same call but returns a proper <code>io::Error</code> instance. Cool!</p>
856<blockquote>
857<p>To determine how many processes were enumerated, divide the <em>lpcbNeeded</em> value by <code>sizeof(DWORD)</code>.</p>
858</blockquote>
859<p>Easy enough:</p>
860<pre><code class="language-rust" data-lang="rust">let count = size as usize / mem::size_of::&lt;DWORD&gt;();
861// SAFETY: the call succeeded and count equals the right amount of items.
862unsafe { pids.set_len(count) };
863Ok(pids)
864</code></pre>
865<p>Rust doesn't know that the memory for <code>count</code> items were initialized by the call, but we do, so we make use of the <a href="https://doc.rust-lang.org/stable/std/vec/struct.Vec.html#method.set_len"><code>Vec::set_len</code></a> call to indicate this. The Rust documentation even includes a FFI similar to our code!</p>
866<p>Let's give it a ride:</p>
867<pre><code class="language-rust" data-lang="rust">fn main() {
868 dbg!(enum_proc().unwrap().len());
869}
870</code></pre>
871<pre><code>&gt;cargo run
872 Compiling memo v0.1.0
873 Finished dev [unoptimized + debuginfo] target(s) in 0.20s
874 Running `target\debug\memo.exe`
875[src\main.rs:27] enum_proc().unwrap().len() = 178
876</code></pre>
877<p>It works! But currently we only have a bunch of process identifiers, with no way of knowing which process they refer to.</p>
878<blockquote>
879<p>To obtain process handles for the processes whose identifiers you have just obtained, call the <a href="https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess"><code>OpenProcess</code></a> function.</p>
880</blockquote>
881<p>Oh!</p>
882<h2 id="opening-a-process">Opening a process</h2>
883<p>The documentation for <code>OpenProcess</code> also contains the following:</p>
884<blockquote>
885<p>When you are finished with the handle, be sure to close it using the <a href="https://lonami.dev/blog/woce-1/closehandle"><code>CloseHandle</code></a> function.</p>
886</blockquote>
887<p>This sounds to me like the perfect time to introduce a custom <code>struct Process</code> with an <code>impl Drop</code>! We're using <code>Drop</code> to cleanup resources, not behaviour, so it's fine. <a href="https://internals.rust-lang.org/t/pre-rfc-leave-auto-trait-for-reliable-destruction/13825">Using <code>Drop</code> to cleanup behaviour is a bad idea</a>. But anyway, let's get back to the code:</p>
888<pre><code class="language-rust" data-lang="rust">use std::ptr::NonNull;
889use winapi::ctypes::c_void;
890
891pub struct Process {
892 pid: u32,
893 handle: NonNull&lt;c_void&gt;,
894}
895
896impl Process {
897 pub fn open(pid: u32) -&gt; io::Result&lt;Self&gt; {
898 todo!()
899 }
900}
901
902impl Drop for Process {
903 fn drop(&amp;mut self) {
904 todo!()
905 }
906}
907</code></pre>
908<p>For <code>open</code>, we'll want to use <code>OpenProcess</code> (and we also need to add the <code>processthreadsapi</code> feature to the <code>winapi</code> dependency in <code>Cargo.toml</code>). It returns a <code>HANDLE</code>, which is a nullable mutable pointer to <code>c_void</code>. If it's null, the call failed, and if it's non-null, it succeeded and we have a valid handle. This is why we use Rust's <a href="https://doc.rust-lang.org/stable/std/ptr/struct.NonNull.html"><code>NonNull</code></a>:</p>
909<pre><code class="language-rust" data-lang="rust">// SAFETY: the call doesn't have dangerous side-effects.
910NonNull::new(unsafe { winapi::um::processthreadsapi::OpenProcess(0, FALSE, pid) })
911 .map(|handle| Self { pid, handle })
912 .ok_or_else(io::Error::last_os_error)
913</code></pre>
914<p><code>NonNull</code> will return <code>Some</code> if the pointer is non-null. We map the non-null pointer to a <code>Process</code> instance with <code>Self { .. }</code>. <code>ok_or_else</code> converts the <code>Option</code> to a <code>Result</code> with the error builder function we provide if it was <code>None</code>.</p>
915<p>The first parameter is a bitflag of permissions we want to have. For now, we can leave it as zero (all bits unset, no specific permissions granted). The second one is whether we want to inherit the handle, which we don't, and the third one is the process identifier. Let's close the resource handle on <code>Drop</code> (after adding <code>handleapi</code> to the crate features):</p>
916<pre><code class="language-rust" data-lang="rust">// SAFETY: the handle is valid and non-null.
917unsafe { winapi::um::handleapi::CloseHandle(self.handle.as_mut()) };
918</code></pre>
919<p><code>CloseHandle</code> can actually fail (for example, on double-close), but given our invariants, it won't. You could add an <code>assert!</code> to panic if this is not the case.</p>
920<p>We can now open processes, and they will be automatically closed on <code>Drop</code>. Does any of this work though?</p>
921<pre><code class="language-rust" data-lang="rust">fn main() {
922 let mut success = 0;
923 let mut failed = 0;
924 enum_proc().unwrap().into_iter().for_each(|pid| match Process::open(pid) {
925 Ok(_) =&gt; success += 1,
926 Err(_) =&gt; failed += 1,
927 });
928
929 eprintln!(&quot;Successfully opened {}/{} processes&quot;, success, success + failed);
930}
931</code></pre>
932<pre><code>&gt;cargo run
933 Compiling memo v0.1.0
934 Finished dev [unoptimized + debuginfo] target(s) in 0.36s
935 Running `target\debug\memo.exe`
936Successfully opened 0/191 processes
937</code></pre>
938<p>…nope. Maybe the documentation for <code>OpenProcess</code> says something?</p>
939<blockquote>
940<p><code>dwDesiredAccess</code></p>
941<p>The access to the process object. This access right is checked against the security descriptor for the process. This parameter can be <strong>one or more</strong> of the process access rights.</p>
942</blockquote>
943<p>One or more, but we're setting zero permissions. I told you, reading the documentation is important<sup class="footnote-reference"><a href="#4">4</a></sup>! The <a href="https://docs.microsoft.com/en-us/windows/win32/procthread/process-security-and-access-rights">Process Security and Access Rights</a> page lists all possible values we could use. <code>PROCESS_QUERY_INFORMATION</code> seems to be appropriated:</p>
944<blockquote>
945<p>Required to retrieve certain information about a process, such as its token, exit code, and priority class</p>
946</blockquote>
947<pre><code class="language-rust" data-lang="rust">OpenProcess(winapi::um::winnt::PROCESS_QUERY_INFORMATION, ...)
948</code></pre>
949<p>Does this fix it?</p>
950<pre><code class="language-rust" data-lang="rust">&gt;cargo run
951 Compiling memo v0.1.0
952 Finished dev [unoptimized + debuginfo] target(s) in 0.36s
953 Running `target\debug\memo.exe`
954Successfully opened 69/188 processes
955</code></pre>
956<p><em>Nice</em>. It does solve it. But why did we only open 69 processes out of 188? Does it help if we run our code as administrator? Let's search for <code>cmd</code> in the Windows menu and right click to Run as administrator, then <code>cd</code> into our project and try again:</p>
957<pre><code>&gt;cargo run
958 Finished dev [unoptimized + debuginfo] target(s) in 0.01s
959 Running `target\debug\memo.exe`
960Successfully opened 77/190 processes
961</code></pre>
962<p>We're able to open a few more, so it does help. In general, we'll want to run as administrator, so normal programs can't sniff on what we're doing, and so that we have permission to do more things.</p>
963<h2 id="getting-the-name-of-a-process">Getting the name of a process</h2>
964<p>We're not done enumerating things just yet. To get the &quot;name&quot; of a process, we need to enumerate the modules that it has loaded, and only then can we get the module base name. The first module is the program itself, so we don't need to enumerate <em>all</em> modules, just the one is enough.</p>
965<p>For this we want <a href="https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-enumprocessmodules"><code>EnumProcessModules</code></a> and <a href="https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-getmodulebasenamea"><code>GetModuleBaseNameA</code></a>. I'm using the ASCII variant of <code>GetModuleBaseName</code> because I'm too lazy to deal with UTF-16 of the <code>W</code> (wide, unicode) variants.</p>
966<pre><code class="language-rust" data-lang="rust">use std::mem::MaybeUninit;
967use winapi::shared::minwindef::HMODULE;
968
969pub fn name(&amp;self) -&gt; io::Result&lt;String&gt; {
970 let mut module = MaybeUninit::&lt;HMODULE&gt;::uninit();
971 let mut size = 0;
972 // SAFETY: the pointer is valid and the size is correct.
973 if unsafe {
974 winapi::um::psapi::EnumProcessModules(
975 self.handle.as_ptr(),
976 module.as_mut_ptr(),
977 mem::size_of::&lt;HMODULE&gt;() as u32,
978 &amp;mut size,
979 )
980 } == FALSE
981 {
982 return Err(io::Error::last_os_error());
983 }
984
985 // SAFETY: the call succeeded, so module is initialized.
986 let module = unsafe { module.assume_init() };
987 todo!()
988}
989</code></pre>
990<p><code>EnumProcessModules</code> takes a pointer to an array of <code>HMODULE</code>. We could use a <code>Vec</code> of capacity one to hold the single module, but in memory, a pointer a single item can be seen as a pointer to an array of items. <code>MaybeUninit</code> helps us reserve enough memory for the one item we need.</p>
991<p>With the module handle, we can retrieve its base name:</p>
992<pre><code class="language-rust" data-lang="rust">let mut buffer = Vec::&lt;u8&gt;::with_capacity(64);
993// SAFETY: the handle, module and buffer are all valid.
994let length = unsafe {
995 winapi::um::psapi::GetModuleBaseNameA(
996 self.handle.as_ptr(),
997 module,
998 buffer.as_mut_ptr().cast(),
999 buffer.capacity() as u32,
1000 )
1001};
1002if length == 0 {
1003 return Err(io::Error::last_os_error());
1004}
1005
1006// SAFETY: the call succeeded and length represents bytes.
1007unsafe { buffer.set_len(length as usize) };
1008Ok(String::from_utf8(buffer).unwrap())
1009</code></pre>
1010<p>Similar to how we did with <code>EnumProcesses</code>, we create a buffer that will hold the ASCII string of the module's base name<sup class="footnote-reference"><a href="#5">5</a></sup>. The call wants us to pass a pointer to a mutable buffer of <code>i8</code>, but Rust's <code>String::from_utf8</code> wants a <code>Vec&lt;u8&gt;</code>, so instead we declare a buffer of <code>u8</code> and <code>.cast()</code> the pointer in the call. You could also do this with <code>as _</code>, and Rust would infer the right type, but <code>cast</code> is neat.</p>
1011<p>We <code>unwrap</code> the creation of the UTF-8 string because the buffer should contain only ASCII characters (which are also valid UTF-8). We could use the <code>unsafe</code> variant to create the string, but what if somehow it contains non-ASCII characters? The less <code>unsafe</code>, the better.</p>
1012<p>Let's see it in action:</p>
1013<pre><code class="language-rust" data-lang="rust">fn main() {
1014 enum_proc()
1015 .unwrap()
1016 .into_iter()
1017 .for_each(|pid| match Process::open(pid) {
1018 Ok(proc) =&gt; match proc.name() {
1019 Ok(name) =&gt; println!(&quot;{}: {}&quot;, pid, name),
1020 Err(e) =&gt; println!(&quot;{}: (failed to get name: {})&quot;, pid, e),
1021 },
1022 Err(e) =&gt; eprintln!(&quot;failed to open {}: {}&quot;, pid, e),
1023 });
1024}
1025</code></pre>
1026<pre><code>&gt;cargo run
1027 Compiling memo v0.1.0
1028 Finished dev [unoptimized + debuginfo] target(s) in 0.32s
1029 Running `target\debug\memo.exe`
1030failed to open 0: The parameter is incorrect. (os error 87)
1031failed to open 4: Access is denied. (os error 5)
1032...
1033failed to open 5940: Access is denied. (os error 5)
10345608: (failed to get name: Access is denied. (os error 5))
1035...
10361704: (failed to get name: Access is denied. (os error 5))
1037failed to open 868: Access is denied. (os error 5)
1038...
1039</code></pre>
1040<p>That's not good. What's up with that? Maybe…</p>
1041<blockquote>
1042<p>The handle must have the <code>PROCESS_QUERY_INFORMATION</code> and <code>PROCESS_VM_READ</code> access rights.</p>
1043</blockquote>
1044<p>…I should've read the documentation. Okay, fine:</p>
1045<pre><code class="language-rust" data-lang="rust">use winapi::um::winnt;
1046OpenProcess(winnt::PROCESS_QUERY_INFORMATION | winnt::PROCESS_VM_READ, ...)
1047</code></pre>
1048<pre><code>&gt;cargo run
1049 Compiling memo v0.1.0 (C:\Users\L\Desktop\memo)
1050 Finished dev [unoptimized + debuginfo] target(s) in 0.35s
1051 Running `target\debug\memo.exe`
1052failed to open 0: The parameter is incorrect. (os error 87)
1053failed to open 4: Access is denied. (os error 5)
1054...
10559348: cheatengine-x86_64.exe
10563288: Tutorial-x86_64.exe
10578396: cmd.exe
10584620: firefox.exe
10597964: cargo.exe
106010052: cargo.exe
10615756: memo.exe
1062</code></pre>
1063<p>Hooray 🎉! There's some processes we can't open, but that's because they're system processes. Security works!</p>
1064<h2 id="finale">Finale</h2>
1065<p>That was a fairly long post when all we did was print a bunch of pids and their corresponding name. But in all fairness, we also laid out a good foundation for what's coming next.</p>
1066<p>You can <a href="https://github.com/lonami/memo">obtain the code for this post</a> over at my GitHub. At the end of every post, the last commit will be tagged, so you can <code>git checkout step1</code> to see the final code for any blog post.</p>
1067<p>In the <a href="/blog/woce-2">next post</a>, we'll tackle the second step of the tutorial: Exact Value scanning.</p>
1068<h3 id="footnotes">Footnotes</h3>
1069<div class="footnote-definition" id="1"><sup class="footnote-definition-label">1</sup>
1070<p>You could say I simply love reinventing the wheel, which I do, but in this case, the codebase contains <em>far</em> more features than we're interested in. The (apparent) lack of structure and documentation regarding the code, along with the unfortunate <a href="https://github.com/cheat-engine/cheat-engine/issues/60">lack of license</a> for the source code, make it a no-go. There's a license, but I think that's for the distributed program itself.</p>
1071</div>
1072<div class="footnote-definition" id="2"><sup class="footnote-definition-label">2</sup>
1073<p>If it turns out that there are more than 1024 processes, our code will be unaware of those extra processes. The documentation suggests to perform the call again with a larger buffer if <code>count == provided capacity</code>, but given I have under 200 processes on my system, it seems unlikely we'll reach this limit. If you're worried about hitting this limit, simply use a larger limit or retry with a larger vector.</p>
1074</div>
1075<div class="footnote-definition" id="3"><sup class="footnote-definition-label">3</sup>
1076<p>C code would likely use <a href="https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalalloc"><code>GlobalAlloc</code></a> here, but Rust's <code>Vec</code> handles the allocation for us, making the code both simpler and more idiomatic. In general, if you see calls to <code>GlobalAlloc</code> when porting some code to Rust, you can probably replace it with a <code>Vec</code>.</p>
1077</div>
1078<div class="footnote-definition" id="4"><sup class="footnote-definition-label">4</sup>
1079<p>This will be a recurring theme.</p>
1080</div>
1081<div class="footnote-definition" id="5"><sup class="footnote-definition-label">5</sup>
1082<p>…and similar to <code>EnumProcesses</code>, if the name doesn't fit in our buffer, the result will be truncated.</p>
1083</div>
1084</content>
1085 </entry>
1086 <entry xml:lang="en">
1087 <title>Data Mining, Warehousing and Information Retrieval</title>
1088 <published>2020-07-03T00:00:00+00:00</published>
1089 <updated>2020-07-03T00:00:00+00:00</updated>
1090 <link href="https://lonami.dev/blog/university/" type="text/html"/>
1091 <id>https://lonami.dev/blog/university/</id>
1092 <content type="html"><p>During university, there were a few subjects where I had to write blog posts for (either as evaluable tasks or just for fun). I thought it was really fun and I wanted to preserve that work here, with the hopes it's interesting to someone.</p>
1093<p>The posts series were auto-generated from the original HTML files and manually anonymized later.</p>
1094<ul>
1095<li><a href="/blog/mdad">Data Mining and Data Warehousing</a></li>
1096<li><a href="/blog/ribw">Information Retrieval and Web Search</a></li>
1097</ul>
1098</content>
1099 </entry>
1100 <entry xml:lang="en">
1101 <title>My new computer</title>
1102 <published>2020-06-19T00:00:00+00:00</published>
1103 <updated>2020-07-03T00:00:00+00:00</updated>
1104 <link href="https://lonami.dev/blog/new-computer/" type="text/html"/>
1105 <id>https://lonami.dev/blog/new-computer/</id>
1106 <content type="html"><p>This post will be mostly me ranting about setting up a new laptop, but I also just want to share my upgrade. If you're considering installing Arch Linux with dual-boot for Windows, maybe this post will help. Or perhaps you will learn something new to troubleshoot systems in the future. Let's begin!</p>
1107<p>Last Sunday, I ordered a Asus Rog Strix G531GT-BQ165 for 900€ (on a 20% discount) with the following specifications:</p>
1108<ul>
1109<li>Intel® Core i7-9750H (6 cores, 12MB cache, 2.6GHz up to 4.5GHz, 64-bit)</li>
1110<li>16GB RAM (8GB*2) DDR4 2666MHz</li>
1111<li>512GB SSD M.2 PCIe® NVMe</li>
1112<li>Display 15.6&quot; (1920x1080/16:9) 60Hz</li>
1113<li>Graphics NVIDIA® GeForce® GTX1650 4GB GDDR5 VRAM</li>
1114<li>LAN 10/100/1000</li>
1115<li>Wi-Fi 5 (802.11ac) 2x2 RangeBoost</li>
1116<li>Bluetooth 5.0</li>
1117<li>48Wh battery with 3 cells</li>
1118<li>3 x USB 3.1 (GEN1)</li>
1119</ul>
1120<p>I was mostly interested in a general upgrade (better processor, disk, more RAM), although the graphics card is a really nice addition which will allow me to take some time off on more games. After using it for a bit, I really love the feel of the keyboard, and I love the lack of numpad! (No sarcasm, I really don't like numpads.)</p>
1121<p>This is an upgrade from my previous laptop (Asus X554LA-XX822T), which I won in a competition before entering university in a programming challenge. It has served me really well for the past five years, and had the following specifications:</p>
1122<ul>
1123<li>Intel® Core™ i5-5200U</li>
1124<li>4GB RAM DDR3L 1600MHz (which I upgraded to have 8GB)</li>
1125<li>1TB HDD</li>
1126<li>Display 15.6&quot; (1366x768/16:9)</li>
1127<li>Intel® HD Graphics 4400</li>
1128<li>LAN 10/100/1000</li>
1129<li>Wifi 802.11 bgn</li>
1130<li>Bluetooth 4.0</li>
1131<li>Battery 2 cells</li>
1132<li>1 x USB 2.0</li>
1133<li>2 x USB 3.0</li>
1134</ul>
1135<p>Prior to this one, I had a Lenovo (also won in the same competition of the previous year), and prior to that (just for the sake of history), it was HP Pavilion, AMD A4-3300M processor, which unfortunately ended with heating problems. But that's very old now.</p>
1136<h2 id="laptop-arrival">Laptop arrival</h2>
1137<p>The laptop arrived 2 days ago at roughly 19:00, which I put charged for 3 hours as the book said. The day after, nightmares began!</p>
1138<p>Trying to boot it the first two times was fun, as it comes with a somewhat loud sound on boot. I don't know why they would do this, and I immediately turned it off in the BIOS.</p>
1139<h2 id="installation-journey">Installation journey</h2>
1140<p>I spent all of yesterday trying to setup Windows and Arch Linux (and didn't even finish, it took me this morning too and even now it's only half functional). I absolutely <em>hate</em> the amount of partitions the Windows installer creates on a clean disk. So instead, I first went with Arch Linux, and followed the <a href="https://wiki.archlinux.org/index.php/Installation_guide">installation guide on the Arch wiki</a>. Pre-installation, setting up the wireless network, creating the partitions and formatting them went all good. I decided to avoid GRUB at first and go with rEFInd, but alas I missed a big warning on the wiki and after reboot (I would later find out) it was not mounting root properly, so all I had was whatever was in the Initramfs. Reboot didn't work, so I had to hold the power button.</p>
1141<p>Anyway, once the partitions were created, I went to install Windows (there was a lot of back and forth burning different <code>.iso</code> images on the USB, which was a bit annoying because it wasn't the fastest thing in the world). This was pretty painless, and the process was standard: select advanced to let me choose the right partition, pick the one, say &quot;no&quot; to everything in the services setup, and done. But this was the first Windows <code>.iso</code> I tried. It was an old revision, and the drivers were causing issues when running (something weird about their <code>.dll</code>, manually installing the <code>.ini</code> driver files seemed to work?). The Nvidia drivers didn't want to be installed on such an old revision, after updating everything I could via Windows updates. So back I went to burning a newer Windows <code>.iso</code> and going through the same process again…</p>
1142<p>Once Windows was ready and I verified that I could boot to it correctly, it was time to have a second go at Arch Linux. And I went through the setup at least three times, getting it wrong every single time, formatting root every single time, redownloading the packages every single pain. If only had I known earlier what the issue was!</p>
1143<p>Why bother with Arch? I was pretty happy with Linux Mint, and I lowkey wanted to try NixOS, but I had used Arch before and it's a really nice distro overall (up-to-date, has AUR, quite minimal, imperative), except for trying to install rEFInd while chrooted…</p>
1144<p>In the end I managed to get something half-working, I still need to properly configure WiFi and pulseaudio in my system but hey it works.</p>
1145<p>I like to be able to dual-boot Windows and Linux because Linux is amazing for productivity, but unfortunately, some games only work fine on Windows. Might as well have both systems and use one for gaming, while the other is my daily driver.</p>
1146<h2 id="setting-up-arch-linux">Setting up Arch Linux</h2>
1147<p>This is the process I followed to install Arch Linux in the end, along with a brief explanation on what I think the things are doing and why we are doing them. I think the wiki could do a better job at this, but I also know it's hard to get it right for everyone. Something I do dislike is the link colour, after opening a link it becomes gray and it's a lot easier to miss the fact that it is a link in the first place, which was tough when re-reading it because some links actually matter a lot. Furthermore, important information may just be a single line, also easy to skim over. Anyway, on to the installation process…</p>
1148<p>The first thing we want to do is configure our keyboard layout or else the keys won't correspond to what we expect:</p>
1149<pre><code class="language-sh" data-lang="sh">loadkeys es
1150</code></pre>
1151<p>Because we're on a recent system, we want to verify that UEFI works correctly. If we see files listed, then it works fine:</p>
1152<pre><code class="language-sh" data-lang="sh">ls /sys/firmware/efi/efivars
1153</code></pre>
1154<p>The next thing we want to do is configure the WiFi, because I don't have any ethernet cable nearby. To do this, we check what network interfaces our laptop has (we're looking for the one prefixed with &quot;w&quot;, presumably for wireless, such as &quot;wlan0&quot; or &quot;wlo1&quot;), we set it up, scan for available wireless network, and finally connect. In my case, the network has WPA security so we rely on <code>wpa_supplicant</code> to connect, passing the SSID (network name) and password:</p>
1155<pre><code class="language-sh" data-lang="sh">ip link
1156ip link set &lt;IFACE&gt; up
1157iw dev &lt;IFACE&gt; scan | less
1158wpa_supplicant -B -i &lt;IFACE&gt; -c &lt;(wpa_passphrase &lt;SSID&gt; &lt;PASS&gt;)
1159</code></pre>
1160<p>After that's done, pinging an IP address like &quot;1.1.1.1&quot; should Just Work™, but to be able to resolve hostnames, we need to also setup a nameserver. I'm using Cloudflare's, but you could use any other:</p>
1161<pre><code class="language-sh" data-lang="sh">echo nameserver 1.1.1.1 &gt; /etc/resolv.conf
1162ping archlinux.org
1163^C
1164</code></pre>
1165<p>If the ping works, then network works! If you still have issues, you may need to <a href="https://wiki.archlinux.org/index.php/Network_configuration#Static_IP_address">manually configure a static IP address</a> and add a route with the address of your, well, router. This basically shows if we have any address, adds a static address (so people know who we are), shows what route we have, and adds a default one (so our packets know where to go):</p>
1166<pre><code class="language-sh" data-lang="sh">ip address show
1167ip address add &lt;YOUR ADDR&gt;/24 broadcast + dev &lt;IFACE&gt;
1168ip route show
1169ip route add default via &lt;ROUTER ADDR&gt; dev &lt;IFACE&gt;
1170</code></pre>
1171<p>Now that we have network available, we can enable NTP to synchronize our system time (this may be required for network operations where certificates have a validity period, not sure; in any case nobody wants a wrong system time):</p>
1172<pre><code class="language-sh" data-lang="sh">timedatectl set-ntp true
1173</code></pre>
1174<p>After that, we can manage our disk and partitions using <code>fdisk</code>. We want to define partitions to tell the system where it should live. To determine the disk name, we first list them, and then edit it. <code>fdisk</code> is really nice and reminds you at every step that help can be accessed with &quot;m&quot;, which you should constantly use to guide you through.</p>
1175<pre><code class="language-sh" data-lang="sh">fdisk -l
1176fdisk /dev/&lt;DISK&gt;
1177</code></pre>
1178<p>The partitions I made are the following:</p>
1179<ul>
1180<li>A 100MB one for the EFI system.</li>
1181<li>A 32GB one for Linux' root <code>/</code> partition.</li>
1182<li>A 200GB one for Linux' home <code>/home</code> partition.</li>
1183<li>The rest was unallocated for Windows because I did this first.</li>
1184</ul>
1185<p>I like to have <code>/home</code> and <code>/</code> separate because I can reinstall root without losing anything from home (projects, music, photos, screenshots, videos…).</p>
1186<p>After the partitions are made, we format them in FAT32 and EXT4 which are good defaults for EFI, root and home. They need to have a format, or else they won't be usable:</p>
1187<pre><code class="language-sh" data-lang="sh">mkfs.fat -F32 /dev/&lt;DISK&gt;&lt;PART1&gt;
1188mkfs.ext4 /dev/&lt;DISK&gt;&lt;PART2&gt;
1189mkfs.ext4 /dev/&lt;DISK&gt;&lt;PART3&gt;
1190</code></pre>
1191<p>Because the laptop was new, there was no risk to lose anything, but if you're doing a install on a previous system, be very careful with the partition names. Make sure they match with the ones in <code>fdisk -l</code>.</p>
1192<p>Now that we have usable partitions, we need to mount them or they won't be accessible. We can do this with <code>mount</code>:</p>
1193<pre><code class="language-sh" data-lang="sh">mount /dev/&lt;DISK&gt;&lt;PART2&gt; /mnt
1194mkdir /mnt/efi
1195mount /dev/&lt;DISK&gt;&lt;PART1&gt; /mnt/efi
1196mkdir /mnt/home
1197mount /dev/&lt;DISK&gt;&lt;PART3&gt; /mnt/home
1198</code></pre>
1199<p>Remember to use the correct partitions while mounting. We mount everything so that the system knows which partitions we care about, which we will let know about later on.</p>
1200<p>Next step is to setup the basic Arch Linux system on root, which can be done with <code>pacstrap</code>. What follows the directory is a list of packages, and you may choose any you wish (at least add <code>base</code>, <code>linux</code> and <code>linux-firmware</code>). These can be installed later, but I'd recommend having them from the beginning, just in case:</p>
1201<pre><code class="language-sh" data-lang="sh">pacstrap /mnt base linux linux-firmware sudo vim-minimal dhcpcd wpa_supplicant man-db man-pages intel-ucode grub efibootmgr os-prober ntfs-3g
1202</code></pre>
1203<p>Because my system has an intel CPU, I also installed <code>intel-ucode</code>.</p>
1204<p>Next up is generating the <code>fstab</code> file, which we tell to use UUIDs to be on the safe side through <code>-U</code>. This file is important, because without it the system won't know what partitions exist and will happily only boot with the initramfs, without anything of what we just installed at root. Not knowing this made me restart the entire installation process a few times.</p>
1205<pre><code class="language-sh" data-lang="sh">genfstab -U /mnt &gt;&gt; /mnt/etc/fstab
1206</code></pre>
1207<p>After that's done, we can change our root into our mount point and finish up configuration. We setup our timezone (so DST can be handled correctly if needed), synchronize the hardware clock (to persist the current time to the BIOS), uncomment our locales (exit <code>vim</code> by pressing ESC, then type <code>:wq</code> and press enter), generate locale files (which some applications need), configure language and keymap, update the hostname of our laptop and what indicate what <code>localhost</code> means…</p>
1208<pre><code class="language-sh" data-lang="sh">ln -sf /usr/share/zoneinfo/&lt;REGION&gt;/&lt;CITY&gt; /etc/localtime
1209hwclock --systohc
1210vim /etc/locale.gen
1211locale-gen
1212echo LANG=es_ES.UTF-8 &gt; /etc/locale.conf
1213echo KEYMAP=es &gt; /etc/vconsole.conf
1214echo &lt;HOST&gt; /etc/hostname
1215cat &lt;&lt;EOF &gt; /etc/hosts
1216127.0.0.1 localhost
1217::1 localhost
1218127.0.1.1 &lt;HOST&gt;.localdomain &lt;HOST&gt;
1219EOF
1220</code></pre>
1221<p>Really, we could've done all of this later, and the same goes for setting root's password with <code>passwd</code> or creating users (some of the groups you probably want are <code>power</code> and <code>wheel</code>).</p>
1222<p>The important part here is installing GRUB (which also needed the <code>efibootmgr</code> package):</p>
1223<pre><code class="language-sh" data-lang="sh">grub-install --target=x86_64-efi --efi-directory=/efi --bootloader-id=GRUB
1224</code></pre>
1225<p>If we want GRUB to find our Windows install, we also need the <code>os-prober</code> and <code>ntfs-3g</code> packages that we installed earlier with <code>pacstrap</code>, and with those we need to mount the Windows partition somewhere. It doesn't matter where. With that done, we can generate the GRUB configuration file which lists all the boot options:</p>
1226<pre><code class="language-sh" data-lang="sh">mkdir /windows
1227mount /dev/&lt;DISK&gt;&lt;PART5&gt; /windows
1228grub-mkconfig -o /boot/grub/grub.cfg
1229</code></pre>
1230<p>(In my case, I installed Windows before completing the Arch install, which created an additional partition in between).</p>
1231<p>With GRUB ready, we can exit the chroot and reboot the system, and if all went well, you should be greeted with a choice of operating system to use:</p>
1232<pre><code class="language-sh" data-lang="sh">exit
1233reboot
1234</code></pre>
1235<p>If for some reason you need to find what mountpoints were active prior to rebooting (to <code>unmount</code> them for example), you can use <code>findmnt</code>.</p>
1236<p>Before GRUB I tried rEFInd, which as I explained had issues with for missing a warning. Then I tried systemd-boot, which did not pick up Arch at first. That's where the several reinstalls come from, I didn't want to work with a half-worked system so I mostly redid the entire process quite a few times.</p>
1237<h2 id="migrating-to-the-new-laptop">Migrating to the new laptop</h2>
1238<p>I had a external disk formatted with NTFS. Of course, after moving every file I cared about from my previous Linux install caused all the permissions to reset. All my <code>.git</code> repositories, dirty with file permission changes! This is going to take a while to fix, or maybe I should just <code>git config core.fileMode false</code>. Here is a <a href="https://stackoverflow.com/a/2083563">lovely command</a> to sort them out on a per-repository basis:</p>
1239<pre><code class="language-sh" data-lang="sh">git diff --summary | grep --color 'mode change 100644 =&gt; 100755' | cut -d' ' -f7- | xargs -d'\n' chmod -x
1240</code></pre>
1241<p>I never realized how much I had stored over the years, but it really was a lot. While moving things to the external disk, I tried to do some cleanup, such as removing some build artifacts which needlessly occupy space, or completely skipping all the binary application files. If I need those I will install them anyway. The process was mostly focused on finding all the projects and program data that I did care about, or even some game saves. Nothing too difficult, but definitely time consuming.</p>
1242<h2 id="tuning-arch">Tuning Arch</h2>
1243<p>Now that our system is ready, install <code>pacman-contrib</code> to grab a copy of the <code>rankmirrors</code> speed. It should help speed up the download of whatever packages you want to install, since it will help us <a href="https://wiki.archlinux.org/index.php/Mirrors#List_by_speed">rank the mirrors by download speed</a>. Making a copy of the file is important, otherwise whenever you try to install something it will fail saying it can't find anything.</p>
1244<pre><code class="language-sh" data-lang="sh">cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.backup
1245sed -i 's/^#Server/Server/' /etc/pacman.d/mirrorlist.backup
1246rankmirrors -n 6 /etc/pacman.d/mirrorlist.backup | tee /etc/pacman.d/mirrorlist
1247</code></pre>
1248<p>This will take a while, but it should be well worth it. We're using <code>tee</code> to see the progress as it goes.</p>
1249<p>Some other packages I installed after I had a working system in no particular order:</p>
1250<ul>
1251<li><code>xfce4</code> and <code>xorg-server</code>. I just love the simplicity of XFCE.</li>
1252<li><code>xfce4-whiskermenu-plugin</code>, a really nice start menu.</li>
1253<li><code>xfce4-pulseaudio-plugin</code> and <code>pavucontrol</code>, to quickly adjust the audio with my mouse.</li>
1254<li><code>xfce4-taskmanager</code>, a GUI alternative I generally prefer to <code>htop</code>.</li>
1255<li><code>pulseaudio</code> and <code>pulseaudio-alsa</code> to get nice integration with XFCE4 and audio mixing.</li>
1256<li><code>firefox</code>, which comes with fonts too. A really good web browser.</li>
1257<li><code>git</code>, to commit <del>crimes</del> code.</li>
1258<li><code>code</code>, a wonderful editor which I used to write this blog entry.</li>
1259<li><code>nano</code>, so much nicer to write a simple commit message.</li>
1260<li><code>python</code> and <code>python-pip</code>, my favourite language to toy around ideas or use as a calculator.</li>
1261<li><code>telegram-desktop</code>, for my needs on sharing memes.</li>
1262<li><code>cmus</code> and <code>mpv</code>, a simple terminal music player and media player.</li>
1263<li><code>openssh</code>, to connect into any VPS I have access to.</li>
1264<li><code>base-devel</code>, necessary to build most projects I'll find myself working with (or even compiling some projects Rust which I installed via <code>rustup</code>).</li>
1265<li><code>flac</code>, <code>libmad</code>, <code>opus</code>, and <code>libvorbis</code>, to be able to play more audio files.</li>
1266<li><code>inkscape</code>, to make random drawings.</li>
1267<li><code>ffmpeg</code>, to convert media or record screen.</li>
1268<li><code>xclip</code>, to automatically copy screenshots to my clipboard.</li>
1269<li><code>gvfs</code>, needed by Thunar to handle mounting and having a trash (perma-deletion by default can be nasty sometimes).</li>
1270<li><code>noto-fonts</code>, <code>noto-fonts-cjk</code>, <code>noto-fonts-extra</code> and <code>noto-fonts-emoji</code>, if you don't want missing gliphs everywhere.</li>
1271<li><code>xfce4-notifyd</code> and <code>libnotify</code>, for notifications.</li>
1272<li><code>cronie</code>, to be able to <code>crontab -e</code>. Make sure to <code>system enable cronie</code>.</li>
1273<li><code>xarchiver</code> (with <code>p7zip</code>, <code>zip</code>, <code>unzip</code> and <code>unrar</code>) to uncompress stuff.</li>
1274<li><code>xreader</code> to read <code>.pdf</code> files.</li>
1275<li><code>sqlitebrowser</code> is always nice to tinker around with SQLite databases.</li>
1276<li><code>jre8-openjdk</code> if you want to run Java applications.</li>
1277<li><code>smartmontools</code> is nice with a SSD to view your disk statistics.</li>
1278</ul>
1279<p>After that, I configured my Super L key to launch <code>xfce4-popup-whiskermenu</code> so that it opens the application menu, pretty much the same as it would on Windows, moved the panels around and configured them to my needs, and it feels like home once more.</p>
1280<p>I made some mistakes while <a href="https://wiki.archlinux.org/index.php/Systemd-networkd">configuring systemd-networkd</a> and accidentally added a service that was incorrect, which caused boot to wait for it to timeout before completing. My boot time was taking 90 seconds longer because of this! <a href="https://www.reddit.com/r/archlinux/comments/4nv9yi/my_arch_greets_me_now_with_a_start_job/">The solution was to remove said service</a>, so this is something to look out for.</p>
1281<p>In order to find what was taking long, I had to edit the <a href="https://wiki.archlinux.org/index.php/kernel_parameters">kernel parameters</a> to remove the <code>quiet</code> option. I prefer seeing the output on what my computer is doing anyway, because it gives me a sense of progress and most importantly is of great value when things go wrong. Another interesting option is <code>noauto,x-systemd.automount</code>, which makes a disk lazily-mounted. If you have a slow disk, this could help speed things up.</p>
1282<p>If you see a service taking long, you can also use <code>systemd-analyze blame</code> to see what takes the longest, and <code>systemctl list-dependencies</code> is also helpful to find what services are active.</p>
1283<p>My <code>locale charmap</code> was spitting out a bunch of warnings:</p>
1284<pre><code class="language-sh" data-lang="sh">$ locale charmap
1285locale: Cannot set LC_CTYPE to default locale: No such file or directory
1286locale: Cannot set LC_MESSAGES to default locale: No such file or directory
1287locale: Cannot set LC_ALL to default locale: No such file or directory
1288ANSI_X3.4-1968
1289</code></pre>
1290<p>…ANSI encoding? Immediately I added the following to <code>~/.bashrc</code> and <code>~/.profile</code>:</p>
1291<pre><code class="language-sh" data-lang="sh">export LC_ALL=en_US.UTF-8
1292export LANG=en_US.UTF-8
1293export LANGUAGE=en_US.UTF-8
1294</code></pre>
1295<p>For some reason, I also had to edit <code>xfce4-terminal</code>'s preferences in advanced to change the default character encoding to UTF-8. This also solved my issues with pasting things into the terminal, and also proper rendering! I guess pastes were not working because it had some characters that could not be encoded.</p>
1296<p>To have working notifications, I added the following to <code>~/.bash_profile</code> after <code>exec startx</code>:</p>
1297<pre><code class="language-sh" data-lang="sh">systemctl --user start xfce4-notifyd.service
1298</code></pre>
1299<p>I'm pretty sure there's a better way to do this, or maybe it's not even necessary, but this works for me.</p>
1300<p>Some of the other things I had left to do was setting up <code>sccache</code> to speed up Rust builds:</p>
1301<pre><code class="language-sh" data-lang="sh">cargo install sccache
1302echo export RUSTC_WRAPPER=sccache &gt;&gt; ~/.bashrc
1303</code></pre>
1304<p>Once I had <code>cargo</code> ready, installed <code>hacksaw</code> and <code>shotgun</code> with it to perform screenshots.</p>
1305<p>I also disabled the security delay when downloading files in Firefox because it's just annoying, in <code>about:config</code> setting <code>security.dialog_enable_delay</code> to <code>0</code>, and added the <a href="https://alisdair.mcdiarmid.org/kill-sticky-headers/">Kill sticky headers</a> to my bookmarks (you may prefer <a href="https://github.com/t-mart/kill-sticky">the updated version</a>).</p>
1306<p>The <code>utils-linux</code> comes with a <code>fstrim</code> utility to <a href="https://wiki.archlinux.org/index.php/Solid_state_drive#Periodic_TRIM">trim the SSD weekly</a>, which I want enabled via <code>systemctl enable fstrim.timer</code> (you may also want to <code>start</code> it if you don't reboot often). For more SSD tips, check <a href="https://easylinuxtipsproject.blogspot.com/p/ssd.html">How to optimize your Solid State Drive</a>.</p>
1307<p>If the sound is funky prior to reboot, try <code>pulseaudio --kill</code> and <code>pulseaudio --start</code>, or delete <code>~/.config/pulse</code>.</p>
1308<p>I haven't been able to get the brightness keys to work yet, but it's not a big deal, because scrolling on the power manager plugin of Xfce does work (and also <code>xbacklight</code> works, or writing directly to <code>/sys/class/backlight/*</code>).</p>
1309<h2 id="tuning-windows">Tuning Windows</h2>
1310<p>On the Windows side, I disabled the annoying Windows defender by running (<kbd>Ctrl+R</kbd>) <code>gpedit.msc</code> and editing:</p>
1311<ul>
1312<li><em>Computer Configuration &gt; Administrative Templates &gt; Windows Components &gt; Windows Defender » Turn off Windows Defender » Enable</em></li>
1313<li><em>User Configuration &gt; Administrative Templates &gt; Start Menu and Taskbar » Remove Notifications and Action Center » Enable</em></li>
1314</ul>
1315<p>I also updated the <a href="https://github.com/WindowsLies/BlockWindows/raw/master/hosts"><code>hosts</code> file</a> (located at <code>%windir%\system32\Drivers\etc\hosts</code>) with the hope that it will stop some of the telemetry.</p>
1316<p>Last, to have consistent time on Windows and Linux, I changed the following registry key for a <code>qword</code> with value <code>1</code>:</p>
1317<pre><code>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation\RealTimeIsUniversal
1318</code></pre>
1319<p>(The key might not exist, but you can create it if that's the case).</p>
1320<p>All this time, my laptop had the keyboard lights on, which have been quite annoying. Apparently, they also can cause <a href="https://www.reddit.com/r/ValveIndex/comments/cm6pos/psa_uninstalldisable_aura_sync_lighting_if_you/">massive FPS drops</a>. I headed over to <a href="https://rog.asus.com/downloads/">Asus Rog downloads</a>, selected Aura Sync…</p>
1321<pre><code class="language-md" data-lang="md"># Not Found
1322
1323The requested URL /campaign/aura/us/Sync.html was not found on this server.
1324
1325Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
1326</code></pre>
1327<p>…great! I'll just find the <a href="https://www.asus.com/campaign/aura/global/">Aura site</a> somewhere else…</p>
1328<pre><code class="language-md" data-lang="md"># ASUS
1329
1330# We'll be back.
1331
1332Hi, our website is temporarily closed for service enhancements.
1333
1334We'll be back shortly.Thank you for your patience!
1335</code></pre>
1336<p>Oh come on. After waiting for the next day, I headed over, downloaded their software, tried to install it and it was an awful experience. It felt like I was purposedly installing malware. It spammed and flashed a lot of <code>cmd</code>'s on screen as if it was a virus. It was stuck at 100% doing that and then, Windows blue-screened with <code>KERNEL_MODE_HEAP_CORRUPTION</code>. Amazing. How do you screw up this bad?</p>
1337<p>Well, at least rebooting worked. I tried to <a href="https://answers.microsoft.com/en-us/windows/forum/all/unable-to-uninstall-asus-aura-sync-utility/e9bec36c-e62f-4773-80be-88fb68dace16">uninstall Aura, but of course that failed</a>. Using the <a href="https://support.microsoft.com/en-us/help/17588/windows-fix-problems-that-block-programs-being-installed-or-removed">troubleshooter to uninstall programs</a> helped me remove most of the crap that was installed.</p>
1338<p>After searching around how to disable the lights (because <a href="https://rog.asus.com/forum/showthread.php?112786-Option-to-Disable-Aura-Lights-on-Strix-G-series-(G531GT)-irrespective-of-OSes">my BIOS did not have this setting</a>), I stumbled upon <a href="https://rog.asus.com/us/innovation/armoury_crate/">&quot;Armoury Crate&quot;</a>. Okay, fine, I will install that.</p>
1339<p>The experience wasn't much better. It did the same thing with a lot of consoles flashing on screen. And of course, it resulted in another blue-screen, this time <code>KERNEL_SECURITY_CHECK_FAILURE</code>. To finish up, the BSOD kept happening as I rebooted the system. <del>Time to reinstall Windows once more.</del> After booting and crashing a few more times I could get into secure mode and perform the reinstall from there, which saved me from burning the <code>.iso</code> again.</p>
1340<p>Asus software might be good, but the software is utter crap.</p>
1341<p>After trying out <a href="https://github.com/wroberts/rogauracore">rogauracore</a> (which didn't list my model), it worked! I could disable the stupid lights from Linux, and <a href="https://gitlab.com/CalcProgrammer1/OpenRGB/-/wikis/home">OpenRGB</a> also works on Windows which may be worth checking out too.</p>
1342<p>Because <code>rougauracore</code> helped me and they linked to <a href="https://github.com/linuxhw/hw-probe/blob/master/README.md#appimage">hw-probe</a>, I decided to <a href="https://linux-hardware.org/?probe=0e3e48c501">run it on my system</a>, with the hopes it is useful for other people.</p>
1343<h2 id="closing-words">Closing words</h2>
1344<p>I hope the installation journey is at least useful to someone, or that you enjoyed reading about it all. If not, sorry!</p>
1345</content>
1346 </entry>
1347 <entry xml:lang="en">
1348 <title>Tips for Outpost</title>
1349 <published>2020-05-10T00:00:00+00:00</published>
1350 <updated>2020-05-22T00:00:00+00:00</updated>
1351 <link href="https://lonami.dev/blog/tips-outpost/" type="text/html"/>
1352 <id>https://lonami.dev/blog/tips-outpost/</id>
1353 <content type="html"><p><a href="https://store.steampowered.com/app/1127110/Outpost/">Outpost</a> is a fun little game by Open Mid Interactive that has popped in recently in my recommended section of Steam, and I decided to give it a try.</p>
1354<p>It's a fun tower-defense game with progression, different graphics and random world generation which makes it quite fun for a few hours. In this post I want to talk about some tips I found useful to get past night 50.</p>
1355<h2 id="build-pattern">Build Pattern</h2>
1356<p>At first, you may be inclined to design a checkerboard pattern like the following, where &quot;C&quot; is the Crystal shrine, &quot;S&quot; is a stone launcher and &quot;B&quot; is a booster:</p>
1357<p><img src="https://lonami.dev/blog/tips-outpost/outpost-bad-pattern.svg" alt="Bad Outpost build pattern" /></p>
1358<p>Indeed, this pattern will apply <strong>4</strong> boosts to every turret, but unfortunately, the other 4 slots of the booster are wasted! This is because boosters are able to power 8 different towers, and you really want to maximize that. Here's a better design:</p>
1359<p><img src="https://lonami.dev/blog/tips-outpost/outpost-good-pattern.svg" alt="Good Outpost build pattern" /></p>
1360<p>The shrine's tower does get boosted, but it's still not really worth it to boost it. This pattern works good, and it's really easy to tile: just repeat the same 3x3 pattern.</p>
1361<p>Nonetheless, we can do better. What if we applied multiple boosters to the same tower while still applying all 8 boosts?</p>
1362<p><img src="https://lonami.dev/blog/tips-outpost/outpost-best-pattern.svg" alt="Best Outpost build pattern" /></p>
1363<p>That's what peak performance looks like. You can actually apply multiple boosters to the same tower, and it works great.</p>
1364<p>Now, is it really worth it building anywhere except around the shrine? Not really. You never know where a boss will come from, so all sides need a lot of defense if you want to stand a chance.</p>
1365<p>The addition of traps in 1.6 is amazing. You want to build these outside your strong &quot;core&quot;, mostly to slow the enemies down so your turrets have more time to finish them off. Don't waste boosters on the traps, and build them at a reasonable distance from the center (the sixth tile is a good spot):</p>
1366<p><img src="https://lonami.dev/blog/tips-outpost/outpost-trap-pattern.svg" alt="Trap Outpost build pattern" /></p>
1367<p>If you gather enough materials, you can build more trap and cannon layers outside, roughly at enough distance to slow them for enough duration until they reach the next layer of traps, and so on. Probably a single gap of &quot;cannon, booster, cannon&quot; is enough between trap layers, just not in the center where you need a lot of fire power.</p>
1368<h2 id="talents">Talents</h2>
1369<p>Talents are the way progression works in the game. Generally, after a run, you will have enough experience to upgrade nearly all talents of roughly the same tier. However, some are worth upgrading more than others (which provide basically no value).</p>
1370<p>The best ones to upgrade are:</p>
1371<ul>
1372<li>Starting supplies. Amazing to get good tools early.</li>
1373<li>Shrine shield. Very useful to hold against tough bosses.</li>
1374<li>Better buildings (cannon, boosters, bed and traps). They're a must to deal the most damage.</li>
1375<li>Better pickaxe. Stone is limited, so better make good use of it.</li>
1376<li>Better chests. They provide an insane amount of resources early.</li>
1377<li>Winter slow. Turrets will have more time to deal damage, it's perfect.</li>
1378<li>More time. Useful if you're running out, although generally you enter nights early after having a good core anyway.</li>
1379<li>More rocks. Similar to a better pickaxe, more stone is always better.</li>
1380</ul>
1381<p>Some decent ones:</p>
1382<ul>
1383<li>In-shrine turret. It's okay to get past the first night without building but not much beyond that.</li>
1384<li>Better axe and greaves. Great to save some energy and really nice quality of life to move around.</li>
1385<li>Tree growth. Normally there's enough trees for this not to be an issue but it can save some time gathering wood.</li>
1386<li>Wisps. They're half-decent since they can provide materials once you max out or max out expensive gear.</li>
1387</ul>
1388<p>Some okay ones:</p>
1389<ul>
1390<li>Extra XP while playing. Generally not needed due to the way XP scales per night, but can be a good boost.</li>
1391<li>Runestones. Not as reliable as chests but some can grant more energy per day.</li>
1392</ul>
1393<p>Some crap ones:</p>
1394<ul>
1395<li>Boosts for other seasons. I mean, winter is already the best, no use there.</li>
1396<li>Bow. The bow is very useless at the moment, it's not worth your experience.</li>
1397<li>More energy per bush. Not really worth hunting for bushes since you will have enough energy to do well.</li>
1398</ul>
1399<h2 id="turrets">Turrets</h2>
1400<p>Always build the highest tier, there's no point in anything lower than that. You will need to deal a lot of damage in a small area, which means space is a premium.</p>
1401<h2 id="boosters">Boosters</h2>
1402<p>If you're very early in the game, I recommend alternating both the flag and torch in a checkerboard pattern where the boosters should go in the pattern above. This way your towers will get extra speed and extra range, which works great.</p>
1403<p>When you're in mid-game (stone launchers, gears and campfires), I do not recommend using campfires. The issue is their range boost is way too long, and the turrets will miss quite a few shots. It's better to put all your power into fire speed for increased DPS, at least near the center. If you manage to build too far out and some of the turrets hardly ever shoot, you may put campfires there.</p>
1404<p>In end-game, of course alternate both of the highest tier upgrades. They are really good, and provide the best benefit / cost ratio.</p>
1405<h2 id="gathering-materials">Gathering Materials</h2>
1406<p>It is <strong>very</strong> important to use all your energy every day! Otherwise it will go to waste, and you will need a lot of materials.</p>
1407<p>As of 1.6, you can mine two things at once if they're close enough! I don't know if this is intended or a bug, but it sure is great.</p>
1408<p>Once you're in mid-game, your stone-based fort should stand pretty well against the nights on its own. After playing for a while you will notice, if your base can defend a boss, then it will have no issue carrying you through the nights until the next boss. You can (and should!) spend the nights gathering materials, but only when you're confident that the night won't run out.</p>
1409<p>Before the boss hits (every fifth night), come back to your base and use all of your materials. This is the next fort upgrade that will carry it the five next nights.</p>
1410<p>You may also speed up time during night, but make sure you use all your energy before hand. And also take care, in the current version of the game speeding up time only speeds up monster movement, not the fire rate or projectile speed of your turrets! This means they will miss more shots and can be pretty dangerous. If you're speeding up time, consider speeding it up for a little bit, then go back to normal until things are more calm, and repeat.</p>
1411<p>If you're in the end-game, try to rush for chests. They provide a huge amount of materials which is really helpful to upgrade all your tools early so you can make sure to get the most out of every rock left in the map.</p>
1412<p>In the end-game, after all stone has been collected, you don't really need to use all of your energy anymore. Just enough to have enough wood to build with the remaining stone. This will also be nice with the bow upgrades, which admitedly can get quite powerful, but it's best to have a strong fort first.</p>
1413<h2 id="season">Season</h2>
1414<p>In my opinion, winter is just the best of the seasons. You don't <em>really</em> need that much energy (it gets tiresome), or extra tree drops, or luck. Slower movement means your turrets will be able to shoot enemies for longer, dealing more damage over time, giving them more chance to take enemies out before they reach the shrine.</p>
1415<p>Feel free to re-roll the map a few times (play and exit, or even restart the game) until you get winter if you want to go for The Play.</p>
1416<h2 id="gear">Gear</h2>
1417<p>In my opinion, you really should rush for the best pickaxe you can afford. Stone is a limited resource that doesn't regrow like trees, so once you run out, it's over. Better to make the best use out of it with a good pickaxe!</p>
1418<p>You may also upgrade your greaves, we all known faster movement is a <em>really</em> nice quality of life improvement.</p>
1419<p>Of course, you will eventually upgrade your axe to chop wood (otherwise it's wasted energy, really), but it's not as much of a priority as the pickaxe.</p>
1420<p>Now, the bow is completely useless. Don't bother with it. Your energy is better spent gathering materials to build permanent turrets that deal constant damage while you're away, and the damage adds up with every extra turret you build.</p>
1421<p>With regards to items you carry (like sword, or helmet), look for these (from best to worst):</p>
1422<ul>
1423<li>Less minion life.</li>
1424<li>Chance to not consume energy.</li>
1425<li>+1 turret damage.</li>
1426<li>Extra energy.</li>
1427<li>+1 drop from trees or stones.</li>
1428<li>+1 free wood or stone per day.</li>
1429</ul>
1430<p>Less minion life, nothing to say. You will need it near end-game.</p>
1431<p>The chance to not consume energy is better the more energy you have. With a 25% chance not to consume energy, you can think of it as 1 extra energy for every 4 energy you have on average.</p>
1432<p>Turret damage is a tough one, it's <em>amazing</em> mid-game (it basically doubles your damage) but falls short once you unlock the cannon where you may prefer other items. Definitely recommended if you're getting started. You may even try to roll it on low tiers by dying on the second night, because it's that good.</p>
1433<p>Extra energy is really good, because it means you can get more materials before it gets too rough. Make sure you have built at least two beds in the first night! This extra energy will pay of for the many nights to come.</p>
1434<p>The problem with free wood or stone per day is that you have, often, five times as much energy per day. By this I mean you can get easily 5 stone every day, which means 5 extra stone, whereas the other would provide just 1 per night. On a good run, you will get around 50 free stone or 250 extra stone. It's a clear winner.</p>
1435<p>In end-game, more quality of life are revealing chests so that you can rush them early, if you like to hunt for them try to make better use of the slot.</p>
1436<h2 id="closing-words">Closing words</h2>
1437<p>I hope you enjoy the game as much as I do! Movement is sometimes janky and there's the occassional lag spikes, but despite this it should provide at least a few good hours of gameplay. Beware however a good run can take up to an hour!</p>
1438</content>
1439 </entry>
1440 <entry xml:lang="en">
1441 <title>Python ctypes and Windows</title>
1442 <published>2019-06-19T00:00:00+00:00</published>
1443 <updated>2019-06-19T00:00:00+00:00</updated>
1444 <link href="https://lonami.dev/blog/ctypes-and-windows/" type="text/html"/>
1445 <id>https://lonami.dev/blog/ctypes-and-windows/</id>
1446 <content type="html"><p><a href="https://www.python.org/">Python</a>'s <a href="https://docs.python.org/3/library/ctypes.html"><code>ctypes</code></a> is quite a nice library to easily load and invoke C methods available in already-compiled <a href="https://en.wikipedia.org/wiki/Dynamic-link_library"><code>.dll</code> files</a> without any additional dependencies. And I <em>love</em> depending on as little as possible.</p>
1447<p>In this blog post, we will walk through my endeavors to use <code>ctypes</code> with the <a href="https://docs.microsoft.com/en-us/windows/desktop/api/">Windows API</a>, and do some cool stuff with it.</p>
1448<p>We will assume some knowledge of C/++ and Python, since we will need to read and write a bit of both. Please note that this post is only an introduction to <code>ctypes</code>, and if you need more information you should consult the <a href="https://docs.python.org/3/library/ctypes.html">Python's documentation for <code>ctypes</code></a>.</p>
1449<p>While the post focuses on Windows' API, the code here probably applies to unix-based systems with little modifications.</p>
1450<h2 id="basics">Basics</h2>
1451<p>First of all, let's learn how to load a library. Let's say we want to load <code>User32.dll</code>:</p>
1452<pre><code class="language-python" data-lang="python">import ctypes
1453
1454ctypes.windll.user32
1455</code></pre>
1456<p>Yes, it's that simple. When you access an attribute of <code>windll</code>, said library will load. Since Windows is case-insensitive, we will use lowercase consistently.</p>
1457<p>Calling a function is just as simple. Let's say you want to call <a href="https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setcursorpos"><code>SetCursorPos</code></a>, which is defined as follows:</p>
1458<pre><code class="language-c" data-lang="c">BOOL SetCursorPos(
1459 int X,
1460 int Y
1461);
1462</code></pre>
1463<p>Okay, it returns a <code>bool</code> and takes two inputs, <code>x</code> and <code>y</code>. So we can call it like so:</p>
1464<pre><code class="language-python" data-lang="python">ctypes.windll.user32.SetCursorPos(100, 100)
1465</code></pre>
1466<p>Try it! Your cursor will move!</p>
1467<h2 id="funky-stuff">Funky Stuff</h2>
1468<p>We can go a bit more crazy and make it form a spiral:</p>
1469<pre><code class="language-python" data-lang="python">import math
1470import time
1471
1472for i in range(200):
1473 x = int(500 + math.cos(i / 5) * i)
1474 y = int(500 + math.sin(i / 5) * i)
1475 ctypes.windll.user32.SetCursorPos(x, y)
1476 time.sleep(0.05)
1477</code></pre>
1478<p>Ah, it's always so pleasant to do random stuff when programming. Sure makes it more fun.</p>
1479<h2 id="complex-structures">Complex Structures</h2>
1480<p><code>SetCursorPos</code> was really simple. It took two parameters and they both were integers. Let's go with something harder. Let's go with <a href="https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendinput"><code>SendInput</code></a>! Emulating input will be a fun exercise:</p>
1481<pre><code class="language-c" data-lang="c">UINT SendInput(
1482 UINT cInputs,
1483 LPINPUT pInputs,
1484 int cbSize
1485);
1486</code></pre>
1487<p>Okay, <code>LPINPUT</code>, what are you? Microsoft likes to prefix types with what they are. In this case, <code>LP</code> stands for &quot;Long Pointer&quot; (I guess?), so <code>LPINPUT</code> is just a Long Pointer to <a href="https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-taginput"><code>INPUT</code></a>:</p>
1488<pre><code class="language-c" data-lang="c">typedef struct tagINPUT {
1489 DWORD type;
1490 union {
1491 MOUSEINPUT mi;
1492 KEYBDINPUT ki;
1493 HARDWAREINPUT hi;
1494 } DUMMYUNIONNAME;
1495} INPUT, *PINPUT, *LPINPUT;
1496</code></pre>
1497<p>Alright, that's new. We have a <code>struct</code> and <code>union</code>, two different concepts. We can define both with <code>ctypes</code>:</p>
1498<pre><code class="language-python" data-lang="python">INPUT_MOUSE = 0
1499INPUT_KEYBOARD = 1
1500INPUT_HARDWARE = 2
1501
1502class INPUT(ctypes.Structure):
1503 _fields_ = [
1504 ('type', ctypes.c_long),
1505 ...
1506 ]
1507</code></pre>
1508<p>Structures are classes that subclass <code>ctypes.Structure</code>, and you define their fields in the <code>_fields_</code> class-level variable, which is a list of tuples <code>(field name, field type)</code>.</p>
1509<p>The C structure had a <code>DWORD type</code>. <code>DWORD</code> is a <code>c_long</code>, and <code>type</code> is a name like any other, which is why we did <code>('type', ctypes.c_long)</code>.</p>
1510<p>But what about the union? It's anonymous, and we can't make anonymous unions (<em>citation needed</em>) with <code>ctypes</code>. We will give it a concrete name and a type.</p>
1511<p>Before defining the union, we need to define its inner structures, <a href="https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-tagmouseinput"><code>MOUSEINPUT</code></a>, <a href="https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-tagkeybdinput"><code>KEYBDINPUT</code></a> and <a href="https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-taghardwareinput"><code>HARDWAREINPUT</code></a>. We won't be using them all, but since they count towards the final struct size (C will choose the largest structure as the final size), we need them, or Windows' API will get confused and refuse to work (personal experience):</p>
1512<pre><code class="language-python" data-lang="python">class MOUSEINPUT(ctypes.Structure):
1513 _fields_ = [
1514 ('dx', ctypes.c_long),
1515 ('dy', ctypes.c_long),
1516 ('mouseData', ctypes.c_long),
1517 ('dwFlags', ctypes.c_long),
1518 ('time', ctypes.c_long),
1519 ('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong))
1520 ]
1521
1522
1523class KEYBDINPUT(ctypes.Structure):
1524 _fields_ = [
1525 ('wVk', ctypes.c_short),
1526 ('wScan', ctypes.c_short),
1527 ('dwFlags', ctypes.c_long),
1528 ('time', ctypes.c_long),
1529 ('dwExtraInfo', ctypes.POINTER(ctypes.c_ulong))
1530 ]
1531
1532
1533class HARDWAREINPUT(ctypes.Structure):
1534 _fields_ = [
1535 ('uMsg', ctypes.c_long),
1536 ('wParamL', ctypes.c_short),
1537 ('wParamH', ctypes.c_short)
1538 ]
1539
1540
1541class INPUTUNION(ctypes.Union):
1542 _fields_ = [
1543 ('mi', MOUSEINPUT),
1544 ('ki', KEYBDINPUT),
1545 ('hi', HARDWAREINPUT)
1546 ]
1547
1548
1549class INPUT(ctypes.Structure):
1550 _fields_ = [
1551 ('type', ctypes.c_long),
1552 ('value', INPUTUNION)
1553 ]
1554</code></pre>
1555<p>Some things to note:</p>
1556<ul>
1557<li>Pointers are defined as <code>ctypes.POINTER(inner type)</code>.</li>
1558<li>The field names can be anything you want. You can make them more &quot;pythonic&quot; if you want (such as changing <code>dwExtraInfo</code> for just <code>extra_info</code>), but I chose to stick with the original naming.</li>
1559<li>The union is very similar, but it uses <code>ctypes.Union</code> instead of <code>ctypes.Structure</code>.</li>
1560<li>We gave a name to the anonymous union, <code>INPUTUNION</code>, and used it inside <code>INPUT</code> with also a made-up name, <code>('value', INPUTUNION)</code>.</li>
1561</ul>
1562<p>Now that we have all the types we need defined, we can use them:</p>
1563<pre><code class="language-python" data-lang="python">KEYEVENTF_KEYUP = 0x0002
1564
1565def press(vk, down):
1566 inputs = INPUT(type=INPUT_KEYBOARD, value=INPUTUNION(ki=KEYBDINPUT(
1567 wVk=vk,
1568 wScan=0,
1569 dwFlags=0 if down else KEYEVENTF_KEYUP,
1570 time=0,
1571 dwExtraInfo=None
1572 )))
1573 ctypes.windll.user32.SendInput(1, ctypes.byref(inputs), ctypes.sizeof(inputs))
1574
1575
1576for char in 'HELLO':
1577 press(ord(char), down=True)
1578 press(ord(char), down=False)
1579</code></pre>
1580<p>Run it! It will press and release the keys <code>hello</code> to type the word <code>&quot;hello&quot;</code>!</p>
1581<p><code>vk</code> stands for &quot;virtual key&quot;. Letters correspond with their upper-case ASCII value, which is what we did above. You can find all the available keys in the page with all the <a href="https://docs.microsoft.com/en-us/windows/desktop/inputdev/virtual-key-codes">Virtual Key Codes</a>.</p>
1582<h2 id="dynamic-inputs-and-pointers">Dynamic Inputs and Pointers</h2>
1583<p>What happens if a method wants something by reference? That is, a pointer to your thing? For example, <a href="https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getcursorpos"><code>GetCursorPos</code></a>:</p>
1584<pre><code class="language-c" data-lang="c">typedef struct tagPOINT {
1585 LONG x;
1586 LONG y;
1587} POINT, *PPOINT, *NPPOINT, *LPPOINT;
1588
1589BOOL GetCursorPos(
1590 LPPOINT lpPoint
1591);
1592</code></pre>
1593<p>It wants a Long Pointer to <a href="https://docs.microsoft.com/en-us/windows/desktop/api/windef/ns-windef-point"><code>POINT</code></a>. We can do just that with <code>ctypes.byref</code>:</p>
1594<pre><code class="language-python" data-lang="python">class POINT(ctypes.Structure):
1595 _fields_ = [
1596 ('x', ctypes.c_long),
1597 ('y', ctypes.c_long)
1598 ]
1599
1600
1601def get_mouse():
1602 point = POINT()
1603 ctypes.windll.user32.GetCursorPos(ctypes.byref(point))
1604 # pass our point by ref ^^^^^
1605 # this lets GetCursorPos fill its x and y fields
1606
1607 return point.x, point.y
1608
1609
1610while True:
1611 print(get_mouse())
1612 time.sleep(0.05)
1613</code></pre>
1614<p>Now you can track the mouse position! Make sure to <code>Ctrl+C</code> the program when you're tired of it.</p>
1615<p>What happens if a method wants a dynamically-sized input?</p>
1616<pre><code class="language-python" data-lang="python">buffer = ctypes.create_string_buffer(size)
1617</code></pre>
1618<p>In that case, you can create an in-memory <code>buffer</code> of <code>size</code> with <code>ctypes.create_string_buffer</code>. It will return a character array of that size, which you can pass as a pointer directly (without <code>ctypes.byref</code>).</p>
1619<p>To access the buffer's contents, you can use either <code>.raw</code> or <code>.value</code>:</p>
1620<pre><code class="language-python" data-lang="python">entire_buffer_as_bytes = buffer.raw
1621up_until_null = buffer.value
1622</code></pre>
1623<p>When the method fills in the data, you can <code>cast</code> your buffer back into a pointer of a concrete type:</p>
1624<pre><code class="language-python" data-lang="python">result_ptr = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_long))
1625</code></pre>
1626<p>And you can de-reference pointers with <code>.contents</code>:</p>
1627<pre><code class="language-python" data-lang="python">first_result = result_ptr.contents
1628</code></pre>
1629<h2 id="arrays">Arrays</h2>
1630<p>Arrays are defined as <code>type * size</code>. Your linter may not like that, and if you don't know the size beforehand, consider creating a 0-sized array. For example:</p>
1631<pre><code class="language-python" data-lang="python"># 10 longs
1632ten_longs = (ctypes.c_long * 10)()
1633for i in range(10):
1634 ten_longs[i] = 2 ** i
1635
1636# Unknown size of longs, e.g. inside some Structure
1637longs = (ctypes.c_long * 0)
1638
1639# Now you know how many longs it actually was
1640known_longs = ctypes.cast(
1641 ctypes.byref(longs),
1642 ctypes.POINTER(ctypes.c_long * size)
1643).contents
1644</code></pre>
1645<p>If there's a better way to initialize arrays, please let me know.</p>
1646<h2 id="wintypes">wintypes</h2>
1647<p>Under Windows, the <code>ctypes</code> module has a <code>wintypes</code> submodule. This one contains definitions like <code>HWND</code> which may be useful and can be imported as:</p>
1648<pre><code class="language-python" data-lang="python">from ctypes.wintypes import HWND, LPCWSTR, UINT
1649</code></pre>
1650<h2 id="callbacks">Callbacks</h2>
1651<p>Some functions (I'm looking at you, <a href="https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumwindows"><code>EnumWindows</code></a>) ask us to pass a callback. In this case, it wants a <a href="https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms633498(v=vs.85)"><code>EnumWindowsProc</code></a>:</p>
1652<pre><code class="language-c" data-lang="c">BOOL EnumWindows(
1653 WNDENUMPROC lpEnumFunc,
1654 LPARAM lParam
1655);
1656
1657BOOL CALLBACK EnumWindowsProc(
1658 _In_ HWND hwnd,
1659 _In_ LPARAM lParam
1660);
1661</code></pre>
1662<p>The naive approach won't work:</p>
1663<pre><code class="language-python" data-lang="python">def callback(hwnd, lParam):
1664 print(hwnd)
1665 return True
1666
1667ctypes.windll.user32.EnumWindows(callback, 0)
1668# ctypes.ArgumentError: argument 1: &lt;class 'TypeError'&gt;: Don't know how to convert parameter 1
1669# Aww.
1670</code></pre>
1671<p>Instead, you must wrap your function as a C definition like so:</p>
1672<pre><code class="language-python" data-lang="python">from ctypes.wintypes import BOOL, HWND, LPARAM
1673
1674EnumWindowsProc = ctypes.WINFUNCTYPE(BOOL, HWND, LPARAM)
1675
1676def callback(hwnd, lParam):
1677 print(hwnd)
1678 return True
1679
1680# Wrap the function in the C definition
1681callback = EnumWindowsProc(callback)
1682
1683ctypes.windll.user32.EnumWindows(callback, 0)
1684# Yay, it works.
1685</code></pre>
1686<p>You may have noticed this is what decorators do, wrap the function. So…</p>
1687<pre><code class="language-python" data-lang="python">from ctypes.wintypes import BOOL, HWND, LPARAM
1688
1689@ctypes.WINFUNCTYPE(BOOL, HWND, LPARAM)
1690def callback(hwnd, lParam):
1691 print(hwnd)
1692 return True
1693
1694ctypes.windll.user32.EnumWindows(callback, 0)
1695</code></pre>
1696<p>…will also work. And it is a <em>lot</em> fancier.</p>
1697<h2 id="closing-words">Closing Words</h2>
1698<p>With the knowledge above and some experimentation, you should be able to call and do (almost) anything you want. That was pretty much all I needed on my project anyway :)</p>
1699<p>We have been letting Python convert Python values into C values, but you can do so explicitly too. For example, you can use <code>ctypes.c_short(17)</code> to make sure to pass that <code>17</code> as a <code>short</code>. And if you have a <code>c_short</code>, you can convert or cast it to its Python <code>.value</code> as <code>some_short.value</code>. The same applies for integers, longs, floats, doubles… pretty much anything, char pointers (strings) included.</p>
1700<p>If you can't find something in their online documentation, you can always <a href="https://github.com/BurntSushi/ripgrep"><code>rg</code></a> for it in the <code>C:\Program Files (x86)\Windows Kits\10\Include\*</code> directory.</p>
1701<p>Note that the <code>ctypes.Structure</code>'s that you define can have more methods of your own. For example, you can write them a <code>__str__</code> to easily view its fields, or define a <code>@property</code> to re-interpret some data in a meaningful way.</p>
1702<p>For enumerations, you can pass just the right integer number, make a constant for it, or if you prefer, use a <a href="https://docs.python.org/3/library/enum.html#enum.IntEnum"><code>enum.IntEnum</code></a>. For example, <a href="https://docs.microsoft.com/en-us/windows-hardware/manufacture/desktop/dism/dismloglevel-enumeration"><code>DismLogLevel</code></a> would be:</p>
1703<pre><code class="language-python" data-lang="python">class DismLogLevel(enum.IntEnum):
1704 DismLogErrors = 0
1705 DismLogErrorsWarnings = 1
1706 DismLogErrorsWarningsInfo = 2
1707</code></pre>
1708<p>And you <em>should</em> be able to pass <code>DismLogLevel.DismLogErrors</code> as the parameter now.</p>
1709<p>If you see a function definition like <code>Function(void)</code>, that's C's way of saying it takes no parameters, so just call it as <code>Function()</code>.</p>
1710<p>Make sure to pass all parameters, even if they seem optional they probably still want a <code>NULL</code> at least, and of course, read the documentation well. Some methods have certain pre-conditions.</p>
1711<p>Have fun hacking!</p>
1712</content>
1713 </entry>
1714 <entry xml:lang="en">
1715 <title>Shattered Pixel Dungeon</title>
1716 <published>2019-06-03T00:00:00+00:00</published>
1717 <updated>2019-06-03T00:00:00+00:00</updated>
1718 <link href="https://lonami.dev/blog/pixel-dungeon/" type="text/html"/>
1719 <id>https://lonami.dev/blog/pixel-dungeon/</id>
1720 <content type="html"><p><a href="https://shatteredpixel.com/shatteredpd/">Shattered Pixel Dungeon</a> is the classic roguelike RPG game with randomly-generated dungeons. As a new player, it was a bit frustrating to be constantly killed on the first levels of the dungeon, but with some practice it's easy to reach high levels if you can kill the first boss.</p>
1721<h2 id="basic-tips">Basic Tips</h2>
1722<p>The game comes with its own tips, but here's a short and straight-forward summary:</p>
1723<ul>
1724<li><strong>Don't rush into enemies</strong>. Abuse doors and small corridors to kill them one by one. You can use the clock on the bottom left to wait a turn without moving.</li>
1725<li><strong>Explore each level at full</strong>. You will find goodies and gain XP while doing so.</li>
1726<li><strong>Upon finding a special room</strong> (e.g. has a chest but is protected by piranhas), drink all potions that you found in that level until there's one that helps you (e.g. be invisible so piranhas leave you alone). There is guaranteed to be a helpful one per level with special rooms.</li>
1727<li><strong>Drink potions as early as possible</strong>. Harmful potions do less damage on early levels (and if you die, you lose less). This will keep them identified early for the rest of the game.</li>
1728<li><strong>Read scrolls as early as possible</strong> as well. This will keep them identified. It may be worth to wait until you have an item which may be cursed and until the level is clear, because some scrolls clean curses and others alert enemies.</li>
1729<li><strong>Food and health are resources</strong> that you have to <em>manage</em>, not keep them always at full. Even if you are starving and taking damage, you may not need to eat <em>just yet</em>, since food is scarce. Eat when you are low on health or in possible danger.</li>
1730<li><strong>Piranhas</strong>. Seriously, just leave them alone if you are melee. They're free food if you're playing ranged, though.</li>
1731<li><strong>Prefer armor over weapons</strong>. And make sure to identify or clean it from curses before wearing anything!</li>
1732<li><strong>Find a dew vial early</strong>. It's often a better idea to store dew (health) for later than to use it as soon as possible.</li>
1733</ul>
1734<h2 id="bosses">Bosses</h2>
1735<p>There is a boss every 5 levels.</p>
1736<ul>
1737<li><strong>Level 5 boss</strong>. Try to stay on water, but don't let <em>it</em> stay on water since it will heal. Be careful when he starts enraging.</li>
1738<li><strong>Level 10 boss</strong>. Ranged weapons are good against it.</li>
1739<li><strong>Level 15 boss</strong>. I somehow managed to tank it with a health potion.</li>
1740<li><strong>Level 20 boss</strong>. I didn't get this far just yet. You are advised to use scrolls of magic mapping in the last levels to skip straight to the boss, since there's nothing else of value.</li>
1741<li><strong>Level 25 boss</strong>. The final boss. Good job if you made it this far!</li>
1742</ul>
1743<h2 id="mage">Mage</h2>
1744<p>If you followed the basic tips, you will sooner or later make use of two scrolls of upgrade in a single run. This will unlock the mage class, which is ridiculously powerful. He starts with a ranged-weapon, a magic missile wand, which is really helpful to keep enemies at a distance. Normally, you want to use this at first to surprise attack them soon, and if you are low on charges, you may go melee on normal enemies if you are confident.</p>
1745<h2 id="luck">Luck</h2>
1746<p>This game is all about luck and patience! Some runs will be better than others, and you should thank and pray the RNG gods for them. If you don't, they will only give you cursed items and not a single scroll to clean them. So, good luck and enjoy playing!</p>
1747</content>
1748 </entry>
1749 <entry xml:lang="en">
1750 <title>Installing NixOS, Take 2</title>
1751 <published>2019-02-15T00:00:00+00:00</published>
1752 <updated>2019-02-16T00:00:00+00:00</updated>
1753 <link href="https://lonami.dev/blog/installing-nixos-2/" type="text/html"/>
1754 <id>https://lonami.dev/blog/installing-nixos-2/</id>
1755 <content type="html"><p>This is my second take at installing NixOS, after a while being frustrated with Arch Linux and the fact that a few kernel upgrades ago, the system crashed randomly from time to time. <code>journalctl</code> did not have any helpful hints and I thought reinstalling could be worthwhile anyway.</p>
1756<p>This time, I started with more knowledge! The first step is heading to the <a href="https://nixos.org">NixOS website</a> and downloading their minimal installation CD for 64 bits. I didn't go with their graphical live CD, because their <a href="https://nixos.org/nixos/manual">installation manual</a> is a wonderful resource that guides you nicely.</p>
1757<p>Once you have downloaded their <code>.iso</code>, you should probably verify it's <code>sha256sum</code> and make sure that it matches. The easiest thing to do in my opinion is using an USB to burn the image in it. Plug it in and check its device name with <code>fdisk -l</code>. In my case, it was <code>/dev/sdb</code>, so I went ahead with it and ran <code>dd if=nixos.iso of=/dev/sdb status=progress</code>. Make sure to run <code>sync</code> once that's done.</p>
1758<p>If either <code>dd</code> or <code>sync</code> seem &quot;stuck&quot; in the end, they are just flushing the changes to disk to make sure all is good. This is normal, and depends on your drives.</p>
1759<p>Now, reboot your computer with the USB plugged in and make sure to boot into it. You should be welcome with a pretty screen. Just select the first option and wait until it logs you in as root. Once you're there you probably want to <code>loadkeys es</code> or whatever your keyboard layout is, or you will have a hard time with passwords, since the characters are all over the place.</p>
1760<p>In a clean disk, you would normally create the partitions now. In my case, I already had the partitions made (100MB for the EFI system, where <code>/boot</code> lives, 40GB for the root <code>/</code> partition with my old Linux installation, and 700G for <code>/home</code>), so I didn't need to do anything here. The manual showcases <code>parted</code>, but I personally use <code>fdisk</code>, which has very helpful help I check every time I use it.</p>
1761<p><strong>Important</strong>: The <code>XY</code> in <code>/dev/sdXY</code> is probably different in your system! Make sure you use <code>fdisk -l</code> to see the correct letters and numbers!</p>
1762<p>With the partitions ready in my UEFI system, I formatted both <code>/</code> and <code>/boot</code> just to be safe with <code>mkfs.ext4 -L nixos /dev/sda2</code> and <code>mkfs.fat -F 32 -n boot /dev/sda1</code> (remember that these are the letters and numbers used in my partition scheme). Don't worry about the warning in the second command regarding lowercase letters and Windows. It's not really an issue.</p>
1763<p>Now, since we gave each partition a label, we can easily mount them through <code>mount /dev/disk/by-label/nixos /mnt</code> and, in UEFI systems, be sure to <code>mkdir -p /mnt/boot</code> and <code>mount /dev/disk/by-label/boot /mnt/boot</code>. I didn't bother setting up swap, since I have 8GB of RAM in my laptop and that's really enough for my use case.</p>
1764<p>With that done, we will now ask the configuration wizard to do some work for us (in particular, generate a template) with <code>nixos-generate-config --root /mnt</code>. This generates a very well documented file that we should edit right now (and this is important!) with whatever editor you prefer. I used <code>vim</code>, but you can change it for <code>nano</code> if you prefer.</p>
1765<p>On to the configuration file, we need to enable a few things, so <code>vim /mnt/etc/nixos/configuration.nix</code> and start scrolling down. We want to make sure to uncomment:</p>
1766<pre><code># We really want network!
1767networking.wireless.enable = true;
1768
1769# This &quot;fixes&quot; the keyboard layout. Put the one you use.
1770i18n = {
1771consoleKeyMap = &quot;es&quot;;
1772}
1773
1774# Timezones are tricky so let's get this right.
1775time.timeZone = &quot;Europe/Madrid&quot;;
1776
1777# We *really* want some base packages installed, such as
1778# wpa_supplicant, or we won't have a way to connect to the
1779# network once we install...
1780environment.systemPackages = with pkgs; [
1781wpa_supplicant wget curl vim neovim cmus mpv firefox git tdesktop
1782];
1783
1784# Printing is useful, sure, enable CUPS
1785services.printing.enable = true;
1786
1787# We have speakers, let's make use of them.
1788sound.enable = true;
1789hardware.pulseaudio.enable = true;
1790
1791# We want the X11 windowing system enabled, in Spanish.
1792services.xserver.enable = true;
1793services.xserver.layout = &quot;es&quot;;
1794
1795# I want a desktop manager in my laptop.
1796# I personally prefer XFCE, but the manual shows plenty
1797# of other options, such as Plasma, i3 WM, or whatever.
1798services.xserver.desktopManager.xfce.enable = true;
1799services.xserver.desktopManager.default = &quot;xfce&quot;;
1800
1801# Touchpad is useful (although sometimes annoying) in a laptop
1802services.xserver.libinput.enable = true;
1803
1804# We don't want to do everything as root!
1805users.users.lonami = {
1806isNormalUser = true;
1807uid = 1000;
1808home = &quot;/home/lonami&quot;;
1809extraGroups = [ &quot;wheel&quot; &quot;networkmanager&quot; &quot;audio&quot; ];
1810};
1811</code></pre>
1812<p><em>(Fun fact, I overlooked the configuration file until I wrote this and hadn't noticed sound/pulseaudio was there. It wasn't hard to find online how to enable it though!)</em></p>
1813<p>Now, let's modify <code>hardware-configuration.nix</code>. But if you have <code>/home</code> in a separate partition like me, you should run <code>blkid</code> to figure out its UUID. To avoid typing it out myself, I just ran <code>blkid &gt;&gt; /mnt/etc/nixos/hardware-configuration.nix</code> so that I could easily move it around with <code>vim</code>:</p>
1814<pre><code># (stuff...)
1815
1816fileSystems.&quot;/home&quot; =
1817{ device = &quot;/dev/disk/by-uuid/d344c686-cae7-4dd3-840e-308eddf86608&quot;;
1818fsType = &quot;ext4&quot;;
1819};
1820
1821# (more stuff...)
1822</code></pre>
1823<p>Note that, obviously, you should put your own partition's UUID there. Modifying the configuration is where I think the current NixOS' manual should have made more emphasis, at this step of the installation. They do detail it below, but that was already too late in my first attempt. Anyway, you can boot from the USB and run <code>nixos-install</code> as many times as you need until you get it working!</p>
1824<p>But before installing, we need to configure the network since there are plenty of things to download. If you want to work from WiFi, you should first figure out the name of your network card with <code>ip link show</code>. In my case it's called <code>wlp3s0</code>. So with that knowledge we can run <code>wpa_supplicant -B -i wlp3s0 -c &lt;(wpa_passphrase SSID key)</code>. Be sure to replace both <code>SSID</code> and <code>key</code> with the name of your network and password key, respectively. If they have spaces, surround them in quotes.</p>
1825<p>Another funny pitfall was typing <code>wpa_supplicant</code> in the command above twice (instead of <code>wpa_passphrase</code>). That sure spit out a few funny errors! Once you have ran that, wait a few seconds and <code>ping 1.1.1.1</code> to make sure that you can reach the internet. If you do, <code>^C</code> and let's install NixOS!</p>
1826<pre><code>nixos-install
1827</code></pre>
1828<p>Well, that was pretty painless. You can now <code>reboot</code> and enjoy your new, functional system.</p>
1829<h2 id="afterword">Afterword</h2>
1830<p>The process of installing NixOS was really painless once you have made sense out of what things mean. I was far more pleased this time than in my previous attempt, despite the four attempts I needed to have it up and running.</p>
1831<p>However not all is so good. I'm not sure where I went wrong, but the first time I tried with <code>i3</code> instead of <code>xfce</code>, all I was welcome with was a white, small terminal in the top left corner. I even generated a configuration file with <code>i3-config-wizard</code> to make sure it could detect my Mod1/Mod4 keys (which, it did), but even after rebooting, my commands weren't responding. For example, I couldn't manage to open another terminal with <code>Mod1+Enter</code>. I'm not even sure that I was in <code>i3</code>…</p>
1832<p>In my very first attempt, I pressed <code>Alt+F8</code> as suggested in the welcome message. This took me an offline copy of the manual, which is really nicely done. Funny enough, though, I couldn't exit <code>w3m</code>. Both <code>Q</code> and <code>B</code> to quit and take me back wouldn't work. Somehow, it kept throwing me back into <code>w3m</code>, so I had to forcibly shutdown.</p>
1833<p>In my second attempt, I also forgot to configure network, so I had no way to download <code>wpa_supplicant</code> without having <code>wpa_supplicant</code> itself to connect my laptop to the network! So, it was important to do that through the USB before installing it (which comes with the program preinstalled), just by making sure to add it in the configuration file.</p>
1834<p>Some other notes, if you can't reach the internet, don't add any DNS in <code>/etc/resolv.conf</code>. This should be done declaratively in <code>configuration.nix</code>.</p>
1835<p>In the end, I spent the entire afternoon playing around with it, taking breaks and what-not. I still haven't figured out why <code>nvim</code> was printing the literal escape character when going from normal to insert mode in the <code>xfce4-terminal</code> (and other actions also made it print this &quot;garbage&quot; to the console), why sometimes the network can reach the internet (and only some sites!) and sometimes not, and how to setup dualboot.</p>
1836<p>But despite all of this, I think it was a worth installing it again. One sure sees things from a different perspective, and gets the chance to write another blog post!</p>
1837<p>If there's something I overlooked or that could be done better, or maybe you can explain it differently, please be sure to <a href="https://lonami.dev/contact">contact me</a> to let me know!</p>
1838<h2 id="update">Update</h2>
1839<p>Well, that was surprisingly fast feedback. Thank you very much <a href="https://bb010g.keybase.pub/">@bb010g</a> for it! As they rightfully pointed out, one can avoid adding <code>/home</code> manually to <code>hardware-configuration.nix</code> if you mount it before generating the configuration files. However, the installation process doesn't need <code>/home</code> mounted, so I didn't do it.</p>
1840<p>The second weird issue with <code>w3m</code> is actually a funny one. <code>Alt+F8</code> <em>switches to another TTY</em>! That's why quitting the program wouldn't do anything. You'd still be in a different TTY! Normally, this is <code>Ctrl+Alt+FX</code>, so I hadn't even thought that this is what could be happening. Anyway, the solution is not quitting the program, but rather going back to the main TTY with <code>Alt+F1</code>. You can switch back and forth all you need to consult the manual.</p>
1841<p>More suggestions are having <a href="https://github.com/rycee/home-manager"><code>home-manager</code></a> manage the graphical sessions, since it should be easier to deal with than the alternatives.</p>
1842<p>Despite having followed the guide and having read it over and over several times, it seems like my thoughts in this blog post may be a bit messy. So I recommend you also reading through the guide to have two versions of all this, just in case.</p>
1843<p>Regarding network issues, they use <code>connman</code> so that may be worth checking out.</p>
1844<p>Regarding terminal issues with <code>nvim</code> printing the literal escape character, I was told off for not having checked what my <code>$TERM</code> was. I hadn't really looked into it much myself, just complained about it here, so sorry for being annoying about that. A quick search in the <code>nixpkgs</code> repository lets us find <a href="https://github.com/NixOS/nixpkgs/blob/release-18.09/pkgs/applications/editors/neovim/default.nix">neovim/default.nix</a>, with version 0.3.1. Looking at <a href="https://github.com/neovim/neovim">Neovim's main repository</a> we can see that this is a bit outdated, but that is fine.</p>
1845<p>If only I had bothered to look at <a href="https://github.com/neovim/neovim/wiki/FAQ#nvim-shows-weird-symbols-2-q-when-changing-modes">Neovim's wiki</a>, (which they found through <a href="https://github.com/neovim/neovim/issues/7749">Neovim's GitHub issues</a>) I would've seen that some terminals just don't support the program properly. The solution is, of course, to use a different terminal emulator with better support or to disable the <code>guicursor</code> in Neovim's config.</p>
1846<p>This is a pretty good life lesson. 30 seconds of searching, maybe two minutes and a half for also checking XFCE issues, are often more than enough to troubleshoot your issues. The internet is a big place and more people have surely came across the problem before, so make sure to look online first. In my defense I'll say that it didn't bother me so much so I didn't bother looking for that soon either.</p>
1847</content>
1848 </entry>
1849 <entry xml:lang="en">
1850 <title>Breaking Risk of Rain</title>
1851 <published>2019-01-12T00:00:00+00:00</published>
1852 <updated>2019-01-12T00:00:00+00:00</updated>
1853 <link href="https://lonami.dev/blog/breaking-ror/" type="text/html"/>
1854 <id>https://lonami.dev/blog/breaking-ror/</id>
1855 <content type="html"><p><a href="https://riskofraingame.com/">Risk of Rain</a> is a fun little game you can spend a lot of hours on. It's incredibly challenging for new players, and fun once you have learnt the basics. This blog will go through what I've learnt and how to play the game correctly.</p>
1856<h2 id="getting-started">Getting Started</h2>
1857<p>If you're new to the game, you may find it frustrating. You must learn very well to dodge.</p>
1858<p>Your first <a href="http://riskofrain.wikia.com/wiki/Category:Characters">character</a> will be <a href="http://riskofrain.wikia.com/wiki/Commando">Commando</a>. He's actually a very nice character. Use your third skill (dodge) to move faster, pass through large groups of enemies, and negate fall damage.</p>
1859<p>If there are a lot of monsters, remember to <strong>leave</strong> from there! It's really important for survival. Most enemies <strong>don't do body damage</strong>. Not even the body of the <a href="http://riskofrain.wikia.com/wiki/Magma_Worm">Magma Worm</a> or the <a href="http://riskofrain.wikia.com/wiki/Wandering_Vagrant">Wandering Vagrant</a> (just dodge the head and projectiles respectively).</p>
1860<p>The first thing you must do is always <strong>rush for the teleporter</strong>. Completing the levels quick will make the game easier. But make sure to take note of <strong>where the chests are</strong>! When you have time (even when the countdown finishes), go back for them and buy as many as you can. Generally, prefer <a href="http://riskofrain.wikia.com/wiki/Chest">chests</a> over <a href="http://riskofrain.wikia.com/wiki/Shrine">shrines</a> since they may eat all your money.</p>
1861<p>Completing the game on <a href="http://riskofrain.wikia.com/wiki/Difficulty">Drizzle</a> is really easy if you follow these tips.</p>
1862<h2 id="requisites">Requisites</h2>
1863<p>Before breaking the game, you must obtain several <a href="http://riskofrain.wikia.com/wiki/Item#Artifacts">artifacts</a>. We are interested in particular in the following:</p>
1864<ul>
1865<li><a href="http://riskofrain.wikia.com/wiki/Sacrifice">Sacrifice</a>. You really need this one, and may be a bit hard to get. With it, you will be able to farm the first level for 30 minutes and kill the final boss in 30 seconds.</li>
1866<li><a href="http://riskofrain.wikia.com/wiki/Command">Command</a>. You need this unless you want to grind for hours to get enough of the items you really need for the rest of the game. Getting this one is easy.</li>
1867<li><a href="http://riskofrain.wikia.com/wiki/Glass">Glass</a>. Your life will be very small (at the beginning…), but you will be able to one-shot everything easily.</li>
1868<li><a href="http://riskofrain.wikia.com/wiki/Kin">Kin</a> (optional). It makes it easier to obtain a lot of boxes if you restart the first level until you get <a href="http://riskofrain.wikia.com/wiki/Lemurian">lemurians</a> or <a href="http://riskofrain.wikia.com/wiki/Jellyfish">jellyfish</a> as the monster, since they're cheap to spawn.</li>
1869</ul>
1870<p>With those, the game becomes trivial. Playing as <a href="http://riskofrain.wikia.com/wiki/Huntress">Huntress</a> is excellent since she can move at high speed while killing everything on screen.</p>
1871<h2 id="breaking-the-game">Breaking the Game</h2>
1872<p>The rest is easy! With the command artifact you want the following items.</p>
1873<h3 id="common-items"><a href="http://riskofrain.wikia.com/wiki/Category:Common_Items">Common Items</a></h3>
1874<ul>
1875<li><a href="http://riskofrain.wikia.com/wiki/Soldier&#x27;s_Syringe">Soldier's Syringe</a>. <strong>Stack 13</strong> of these and you will triple your attack speed. You can get started with 4 or so.</li>
1876<li><a href="http://riskofrain.wikia.com/wiki/Paul&#x27;s_Goat_Hoof">Paul's Goat Hoof</a>. <strong>Stack +30</strong> of these and your movement speed will be insane. You can get a very good speed with 8 or so.</li>
1877<li><a href="http://riskofrain.wikia.com/wiki/Crowbar">Crowbar</a>. <strong>Stack +20</strong> to guarantee you can one-shot bosses.</li>
1878</ul>
1879<p>If you want to be safer:</p>
1880<ul>
1881<li><a href="http://riskofrain.wikia.com/wiki/Hermit&#x27;s_Scarf">Hermit's Scarf</a>. <strong>Stack 6</strong> of these to dodge 1/3 of the attacks.</li>
1882<li><a href="http://riskofrain.wikia.com/wiki/Monster_Tooth">Monster Tooth</a>. <strong>Stack 9</strong> of these to recover 50 life on kill. This is plenty, since you will be killing <em>a lot</em>.</li>
1883</ul>
1884<p>If you don't have enough and want more fun, get one of these:</p>
1885<ul>
1886<li><a href="http://riskofrain.wikia.com/wiki/Gasoline">Gasoline</a>. Burn the ground on kill, and more will die!</li>
1887<li><a href="http://riskofrain.wikia.com/wiki/Headstompers">Headstompers</a>. They make a pleasing sound on fall, and hurt.</li>
1888<li><a href="http://riskofrain.wikia.com/wiki/Lens-Maker&#x27;s_Glasses">Lens-Maker's Glasses</a>. <strong>Stack 14</strong> and you will always deal a critical strike for double the damage.</li>
1889</ul>
1890<h3 id="uncommon-items"><a href="http://riskofrain.wikia.com/wiki/Category:Uncommon_Items">Uncommon Items</a></h3>
1891<ul>
1892<li><a href="http://riskofrain.wikia.com/wiki/Infusion">Infusion</a>. You only really need one of this. Your life will skyrocket after a while, since this gives you 1HP per kill.</li>
1893<li><a href="http://riskofrain.wikia.com/wiki/Hopoo_Feather">Hopoo Feather</a>. <strong>Stack +10</strong> of these. You will pretty much be able to fly with so many jumps.</li>
1894<li><a href="http://riskofrain.wikia.com/wiki/Guardian&#x27;s_Heart">Guardian's Heart</a>. Not really necessary, but useful for early and late game, since it will absorb infinite damage the first hit.</li>
1895</ul>
1896<p>If, again, you want more fun, get one of these:</p>
1897<ul>
1898<li><a href="http://riskofrain.wikia.com/wiki/Ukulele">Ukelele</a>. Spazz your enemies!</li>
1899<li><a href="http://riskofrain.wikia.com/wiki/Will-o&#x27;-the-wisp">Will-o'-the-wisp</a>. Explode your enemies!</li>
1900<li><a href="http://riskofrain.wikia.com/wiki/Chargefield_Generator">Chargefield Generator</a>. It should cover your entire screen after a bit, hurting all enemies without moving a finger.</li>
1901<li><a href="http://riskofrain.wikia.com/wiki/Golden_Gun">Golden Gun</a>. You will be rich, so this gives you +40% damage.</li>
1902<li><a href="http://riskofrain.wikia.com/wiki/Predatory_Instincts">Predatory Instincts</a>. If you got 14 glasses, you will always be doing critical strikes, and this will give even more attack speed.</li>
1903<li><a href="http://riskofrain.wikia.com/wiki/56_Leaf_Clover">56 Leaf Clover</a>. More drops, in case you didn't have enough.</li>
1904</ul>
1905<h3 id="rare-items"><a href="http://riskofrain.wikia.com/wiki/Category:Rare_Items">Rare Items</a></h3>
1906<ul>
1907<li><a href="http://riskofrain.wikia.com/wiki/Ceremonial_Dagger">Ceremonial Dagger</a>. <strong>Stack +3</strong>, then killing one thing kills another thing and makes a chain reaction.</li>
1908<li><a href="http://riskofrain.wikia.com/wiki/Alien_Head">Alien Head</a>. <strong>Stack 3</strong>, and you will be able to use your abilities more often.</li>
1909</ul>
1910<p>For more fun:</p>
1911<ul>
1912<li><a href="http://riskofrain.wikia.com/wiki/Brilliant_Behemoth">Brilliant Behemoth</a>. Boom boom.</li>
1913</ul>
1914<h2 id="closing-words">Closing Words</h2>
1915<p>You can now beat the game in Monsoon solo with any character. Have fun! And be careful with the sadly common crashes.</p>
1916</content>
1917 </entry>
1918 <entry xml:lang="en">
1919 <title>WorldEdit Commands</title>
1920 <published>2018-07-11T00:00:00+00:00</published>
1921 <updated>2018-07-11T00:00:00+00:00</updated>
1922 <link href="https://lonami.dev/blog/world-edit/" type="text/html"/>
1923 <id>https://lonami.dev/blog/world-edit/</id>
1924 <content type="html"><p><a href="https://dev.bukkit.org/projects/worldedit">WorldEdit</a> is an extremely powerful tool for modifying entire worlds within <a href="https://minecraft.net">Minecraft</a>, which can be used as either a mod for your single-player worlds or as a plugin for your <a href="https://getbukkit.org/">Bukkit</a> servers.</p>
1925<p>This command guide was written for Minecraft 1.12.1, version <a href="https://dev.bukkit.org/projects/worldedit/files/2460562">6.1.7.3</a>, but should work for newer versions too. All WorldEdit commands can be used with a double slash (<code>//</code>) so they don't conlict with built-in commands. This means you can get a list of all commands with <code>//help</code>. Let's explore different categories!</p>
1926<h2 id="movement">Movement</h2>
1927<p>In order to edit a world properly you need to learn how to move in said world properly. There are several straightforward commands that let you move:</p>
1928<ul>
1929<li><code>//ascend</code> goes up one floor.</li>
1930<li><code>//descend</code> goes down one floor.</li>
1931<li><code>//thru</code> let's you pass through walls.</li>
1932<li><code>//jumpto</code> to go wherever you are looking.</li>
1933</ul>
1934<h2 id="information">Information</h2>
1935<p>Knowing your world properly is as important as knowing how to move within it, and will also let you change the information in said world if you need to.</p>
1936<ul>
1937<li><code>//biomelist</code> shows all known biomes.</li>
1938<li><code>//biomeinfo</code> shows the current biome.</li>
1939<li><code>//setbiome</code> lets you change the biome.</li>
1940</ul>
1941<h2 id="blocks">Blocks</h2>
1942<p>You can act over all blocks in a radius around you with quite a few commands. Some won't actually act over the entire range you specify, so 100 is often a good number.</p>
1943<h3 id="filling">Filling</h3>
1944<p>You can fill pools with <code>//fill water 100</code> or caves with <code>//fillr water 100</code>, both of which act below your feet.</p>
1945<h3 id="fixing">Fixing</h3>
1946<p>If the water or lava is buggy use <code>//fixwater 100</code> or <code>//fixlava 100</code> respectively.</p>
1947<p>Some creeper removed the snow or the grass? Fear not, you can use <code>//snow 10</code> or <code>//grass 10</code>.</p>
1948<h3 id="emptying">Emptying</h3>
1949<p>You can empty a pool completely with <code>//drain 100</code>, remove the snow with <code>//thaw 10</code>, and remove fire with <code>//ex 10</code>.</p>
1950<h3 id="removing">Removing</h3>
1951<p>You can remove blocks above and below you in some area with the <code>//removeabove N</code> and <code>//removebelow N</code>. You probably want to set a limit though, or you could fall off the world with <code>//removebelow 1 10</code> for radius and depth. You can also remove near blocks with <code>//removenear block 10</code>.</p>
1952<h3 id="shapes">Shapes</h3>
1953<p>Making a cylinder (or circle) can be done with through <code>//cyl stone 10</code>, a third argument for the height. The radius can be comma-separated to make a ellipses instead, such as <code>//cyl stone 5,10</code>.</p>
1954<p>Spheres are done with <code>//sphere stone 5</code>. This will build one right at your center, so you can raise it to be on your feet with <code>//sphere stone 5 yes</code>. Similar to cylinders, you can comma separate the radius <code>x,y,z</code>.</p>
1955<p>Pyramids can be done with <code>//pyramic stone 5</code>.</p>
1956<p>All these commands can be prefixed with &quot;h&quot; to make them hollow. For instance, <code>//hsphere stone 10</code>.</p>
1957<h2 id="regions">Regions</h2>
1958<h3 id="basics">Basics</h3>
1959<p>Operating over an entire region is really important, and the first thing you need to work comfortably with them is a tool to make selections. The default wooden-axe tool can be obtained with <code>//wand</code>, but you must be near the blocks to select. You can use a different tool, like a golden axe, to use as your &quot;far wand&quot; (wand usable over distance). Once you have one in your hand type <code>//farwand</code> to use it as your &quot;far wand&quot;. You can select the two corners of your region with left and right click. If you have selected the wrong tool, use <code>//none</code> to clear it.</p>
1960<p>If there are no blocks but you want to use your current position as a corner, use <code>//pos1</code> or 2.</p>
1961<p>If you made a region too small, you can enlarge it with <code>//expand 10 up</code>, or <code>//expand vert</code> for the entire vertical range, etc., or make it smaller with <code>//contract 10 up</code> etc., or <code>//inset</code> it to contract in both directions. You can use short-names for the cardinal directions (NSEW).</p>
1962<p>Finally, if you want to move your selection, you can <code>//shift 1 north</code> it to wherever you need.</p>
1963<h3 id="information-1">Information</h3>
1964<p>You can get the <code>//size</code> of the selection or even <code>//count torch</code> in some area. If you want to count all blocks, get their distribution <code>//distr</code>.</p>
1965<h3 id="filling-1">Filling</h3>
1966<p>With a region selected, you can <code>//set</code> it to be any block! For instance, you can use <code>//set air</code> to clear it entirely. You can use more than one block evenly by separting them with a comma <code>//set stone,dirt</code>, or with a custom chance <code>//set 20%stone,80%dirt</code>.</p>
1967<p>You can use <code>//replace from to</code> instead if you don't want to override all blocks in your selection.</p>
1968<p>You can make an hollow set with <code>//faces</code>, and if you just want the walls, use <code>//walls</code>.</p>
1969<h3 id="cleaning">Cleaning</h3>
1970<p>If someone destroyed your wonderful snow landscape, fear not, you can use <code>//overlay snow</code> over it (although for this you actually have <code>//snow N</code> and its opposite <code>//thaw</code>).</p>
1971<p>If you set some rough area, you can always <code>//smooth</code> it, even more than one time with <code>//smooth 3</code>. You can get your dirt and stone back with <code>//naturalize</code> and put some plants with <code>//flora</code> or <code>//forest</code>, both of which support a density or even the type for the trees. If you already have the dirt use <code>//green</code> instead. If you want some pumpkins, with <code>//pumpkins</code>.</p>
1972<h3 id="moving">Moving</h3>
1973<p>You can repeat an entire selection many times by stacking them with <code>//stack N DIR</code>. This is extremely useful to make things like corridors or elevators. For instance, you can make a small section of the corridor, select it entirely, and then repeat it 10 times with <code>//stack 10 north</code>. Or you can make the elevator and then <code>//stack 10 up</code>. If you need to also copy the air use <code>//stackair</code>.</p>
1974<p>Finally, if you don't need to repeat it and simply move it just a bit towards the right direction, you can use <code>//move N</code>. The default direction is &quot;me&quot; (towards where you are facing) but you can set one with <code>//move 1 up</code> for example.</p>
1975<h3 id="selecting">Selecting</h3>
1976<p>You can not only select cuboids. You can also select different shapes, or even just points:</p>
1977<ul>
1978<li><code>//sel cuboid</code> is the default.</li>
1979<li><code>//sel extend</code> expands the default.</li>
1980<li><code>//sel poly</code> first point with left click and right click to add new points.</li>
1981<li><code>//sel ellipsoid</code> first point to select the center and right click to select the different radius.</li>
1982<li><code>//sel sphere</code> first point to select the center and one more right click for the radius.</li>
1983<li><code>//sel cyl</code> for cylinders, first click being the center.</li>
1984<li><code>//sel convex</code> for convex shapes. This one is extremely useful for <code>//curve</code>.</li>
1985</ul>
1986<h2 id="brushes">Brushes</h2>
1987<p>Brushes are a way to paint in 3D without first bothering about making a selection, and there are spherical and cylinder brushes with e.g. <code>//brush sphere stone 2</code>, or the shorter form <code>//br s stone</code>. For cylinder, one must use <code>cyl</code> instead <code>sphere</code>.</p>
1988<p>There also exists a brush to smooth the terrain which can be enabled on the current item with <code>//br smooth</code>, which can be used with right-click like any other brush.</p>
1989<h2 id="clipboard">Clipboard</h2>
1990<p>Finally, you can copy and cut things around like you would do with normal text with <code>//copy</code> and <code>//cut</code>. The copy is issued from wherever you issue the command, so when you use <code>//paste</code>, remember that if you were 4 blocks apart when copying, it will be 4 blocks apart when pasting.</p>
1991<p>The contents of the clipboard can be flipped to wherever you are looking via <code>//flip</code>, and can be rotated via the <code>//rotate 90</code> command (in degrees).</p>
1992<p>To remove the copy use <code>//clearclipboard</code>.</p>
1993</content>
1994 </entry>
1995 <entry xml:lang="en">
1996 <title>An Introduction to Asyncio</title>
1997 <published>2018-06-13T00:00:00+00:00</published>
1998 <updated>2020-10-03T00:00:00+00:00</updated>
1999 <link href="https://lonami.dev/blog/asyncio/" type="text/html"/>
2000 <id>https://lonami.dev/blog/asyncio/</id>
2001 <content type="html"><h2 id="index">Index</h2>
2002<ul>
2003<li><a href="https://lonami.dev/blog/asyncio/#background">Background</a></li>
2004<li><a href="https://lonami.dev/blog/asyncio/#input_output">Input / Output</a></li>
2005<li><a href="https://lonami.dev/blog/asyncio/#diving_in">Diving In</a></li>
2006<li><a href="https://lonami.dev/blog/asyncio/#a_toy_example">A Toy Example</a></li>
2007<li><a href="https://lonami.dev/blog/asyncio/#a_real_example">A Real Example</a></li>
2008<li><a href="https://lonami.dev/blog/asyncio/#extra_material">Extra Material</a></li>
2009</ul>
2010<h2 id="background">Background</h2>
2011<p>After seeing some friends struggle with <code>asyncio</code> I decided that it could be a good idea to write a blog post using my own words to explain how I understand the world of asynchronous IO. I will focus on Python's <code>asyncio</code> module but this post should apply to any other language easily.</p>
2012<p>So what is <code>asyncio</code> and what makes it good? Why don't we just use the old and known threads to run several parts of the code concurrently, at the same time?</p>
2013<p>The first reason is that <code>asyncio</code> makes your code easier to reason about, as opposed to using threads, because the amount of ways in which your code can run grows exponentially. Let's see that with an example. Imagine you have this code:</p>
2014<pre><code class="language-python" data-lang="python">def method():
2015 line 1
2016 line 2
2017 line 3
2018 line 4
2019 line 5
2020</code></pre>
2021<p>And you start two threads to run the method at the same time. What is the order in which the lines of code get executed? The answer is that you can't know! The first thread can run the entire method before the second thread even starts. Or it could be the first thread that runs after the second thread. Perhaps both run the &quot;line 1&quot;, and then the line 2. Maybe the first thread runs lines 1 and 2, and then the second thread only runs the line 1 before the first thread finishes.</p>
2022<p>As you can see, any combination of the order in which the lines run is possible. If the lines modify some global shared state, that will get messy quickly.</p>
2023<p>Second, in Python, threads <em>won't</em> make your code faster most of the time. It will only increase the concurrency of your program (which is okay if it makes many blocking calls), allowing you to run several things at the same time.</p>
2024<p>If you have a lot of CPU work to do though, threads aren't a real advantage. Indeed, your code will probably run slower under the most common Python implementation, CPython, which makes use of a Global Interpreter Lock (GIL) that only lets a thread run at once. The operations won't run in parallel!</p>
2025<h2 id="input-output">Input / Output</h2>
2026<p>Before we go any further, let's first stop to talk about input and output, commonly known as &quot;IO&quot;. There are two main ways to perform IO operations, such as reading or writing from a file or a network socket.</p>
2027<p>The first one is known as &quot;blocking IO&quot;. What this means is that, when you try performing IO, the current application thread is going to <em>block</em> until the Operative System can tell you it's done. Normally, this is not a problem, since disks are pretty fast anyway, but it can soon become a performance bottleneck. And network IO will be much slower than disk IO!</p>
2028<pre><code class="language-python" data-lang="python">import socket
2029
2030# Setup a network socket and a very simple HTTP request.
2031# By default, sockets are open in blocking mode.
2032sock = socket.socket()
2033request = b'''HEAD / HTTP/1.0\r
2034Host: example.com\r
2035\r
2036'''
2037
2038# &quot;connect&quot; will block until a successful TCP connection
2039# is made to the host &quot;example.com&quot; on port 80.
2040sock.connect(('example.com', 80))
2041
2042# &quot;sendall&quot; will repeatedly call &quot;send&quot; until all the data in &quot;request&quot; is
2043# sent to the host we just connected, which blocks until the data is sent.
2044sock.sendall(request)
2045
2046# &quot;recv&quot; will try to receive up to 1024 bytes from the host, and block until
2047# there is any data to receive (or empty if the host closes the connection).
2048response = sock.recv(1024)
2049
2050# After all those blocking calls, we got out data! These are the headers from
2051# making a HTTP request to example.com.
2052print(response.decode())
2053</code></pre>
2054<p>Blocking IO offers timeouts, so that you can get control back in your code if the operation doesn't finish. Imagine that the remote host doesn't want to reply, your code would be stuck for as long as the connection remains alive!</p>
2055<p>But wait, what if we make the timeout small? Very, very small? If we do that, we will never block waiting for an answer. That's how asynchronous IO works, and it's the opposite of blocking IO (you can also call it non-blocking IO if you want to).</p>
2056<p>How does non-blocking IO work if the IO device needs a while to answer with the data? In that case, the operative system responds with &quot;not ready&quot;, and your application gets control back so it can do other stuff while the IO device completes your request. It works a bit like this:</p>
2057<pre><code>&lt;app&gt; Hey, I would like to read 16 bytes from this file
2058&lt;OS&gt; Okay, but the disk hasn't sent me the data yet
2059&lt;app&gt; Alright, I will do something else then
2060(a lot of computer time passes)
2061&lt;app&gt; Do you have my 16 bytes now?
2062&lt;OS&gt; Yes, here they are! &quot;Hello, world !!\n&quot;
2063</code></pre>
2064<p>In reality, you can tell the OS to notify you when the data is ready, as opposed to polling (constantly asking the OS whether the data is ready yet or not), which is more efficient.</p>
2065<p>But either way, that's the difference between blocking and non-blocking IO, and what matters is that your application gets to run more without ever needing to wait for data to arrive, because the data will be there immediately when you ask, and if it's not yet, your app can do more things meanwhile.</p>
2066<h2 id="diving-in">Diving In</h2>
2067<p>Now we've seen what blocking and non-blocking IO is, and how threads make your code harder to reason about, but they give concurrency (yet not more speed). Is there any other way to achieve this concurrency that doesn't involve threads? Yes! The answer is <code>asyncio</code>.</p>
2068<p>So how does <code>asyncio</code> help? First we need to understand a very crucial concept before we can dive any deeper, and I'm talking about the <em>event loop</em>. What is it and why do we need it?</p>
2069<p>You can think of the event loop as a <em>loop</em> that will be responsible for calling your <code>async</code> functions:</p>
2070<p><img src="https://lonami.dev/blog/asyncio/eventloop.svg" alt="The Event Loop" /></p>
2071<p>That's silly you may think. Now not only we run our code but we also have to run some &quot;event loop&quot;. It doesn't sound beneficial at all. What are these events? Well, they are the IO events we talked about before!</p>
2072<p><code>asyncio</code>'s event loop is responsible for handling those IO events, such as file is ready, data arrived, flushing is done, and so on. As we saw before, we can make these events non-blocking by setting their timeout to 0.</p>
2073<p>Let's say you want to read from 10 files at the same time. You will ask the OS to read data from 10 files, and at first none of the reads will be ready. But the event loop will be constantly asking the OS to know which are done, and when they are done, you will get your data.</p>
2074<p>This has some nice advantages. It means that, instead of waiting for a network request to send you a response or some file, instead of blocking there, the event loop can decide to run other code meanwhile. Whenever the contents are ready, they can be read, and your code can continue. Waiting for the contents to be received is done with the <code>await</code> keyword, and it tells the loop that it can run other code meanwhile:</p>
2075<p><img src="https://lonami.dev/blog/asyncio/awaitkwd1.svg" alt="Step 1, await keyword" /></p>
2076<p><img src="https://lonami.dev/blog/asyncio/awaitkwd2.svg" alt="Step 2, await keyword" /></p>
2077<p>Start reading the code of the event loop and follow the arrows. You can see that, in the beginning, there are no events yet, so the loop calls one of your functions. The code runs until it has to <code>await</code> for some IO operation to complete, such as sending a request over the network. The method is &quot;paused&quot; until an event occurs (for example, an &quot;event&quot; occurs when the request has been sent completely).</p>
2078<p>While the first method is busy, the event loop can enter the second method, and run its code until the first <code>await</code>. But it can happen that the event of the second query occurs before the request on the first method, so the event loop can re-enter the second method because it has already sent the query, but the first method isn't done sending the request yet.</p>
2079<p>Then, the second method <code>await</code>'s for an answer, and an event occurs telling the event loop that the request from the first method was sent. The code can be resumed again, until it has to <code>await</code> for a response, and so on. Here's an explanation with pseudo-code for this process if you prefer:</p>
2080<pre><code class="language-python" data-lang="python">async def method(request):
2081 prepare request
2082 await send request
2083
2084 await receive request
2085
2086 process request
2087 return result
2088
2089run in parallel (
2090 method with request 1,
2091 method with request 2,
2092)
2093</code></pre>
2094<p>This is what the event loop will do on the above pseudo-code:</p>
2095<pre><code>no events pending, can advance
2096
2097enter method with request 1
2098 prepare request
2099 await sending request
2100pause method with request 1
2101
2102no events ready, can advance
2103
2104enter method with request 2
2105 prepare request
2106 await sending request
2107pause method with request 2
2108
2109both requests are paused, cannot advance
2110wait for events
2111event for request 2 arrives (sending request completed)
2112
2113enter method with request 2
2114 await receiving response
2115pause method with request 2
2116
2117event for request 1 arrives (sending request completed)
2118
2119enter method with request 1
2120 await receiving response
2121pause method with request 1
2122
2123...and so on
2124</code></pre>
2125<p>You may be wondering &quot;okay, but threads work for me, so why should I change?&quot;. There are some important things to note here. The first is that we only need one thread to be running! The event loop decides when and which methods should run. This results in less pressure for the operating system. The second is that we know when it may run other methods. Those are the <code>await</code> keywords! Whenever there is one of those, we know that the loop is able to run other things until the resource (again, like network) becomes ready (when a event occurs telling us it's ready to be used without blocking or it has completed).</p>
2126<p>So far, we already have two advantages. We are only using a single thread so the cost for switching between methods is low, and we can easily reason about where our program may interleave operations.</p>
2127<p>Another advantage is that, with the event loop, you can easily schedule when a piece of code should run, such as using the method <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.call_at"><code>loop.call_at</code></a>, without the need for spawning another thread at all.</p>
2128<p>To tell the <code>asyncio</code> to run the two methods shown above, we can use <a href="https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future"><code>asyncio.ensure_future</code></a>, which is a way of saying &quot;I want the future of my method to be ensured&quot;. That is, you want to run your method in the future, whenever the loop is free to do so. This method returns a <code>Future</code> object, so if your method returns a value, you can <code>await</code> this future to retrieve its result.</p>
2129<p>What is a <code>Future</code>? This object represents the value of something that will be there in the future, but might not be there yet. Just like you can <code>await</code> your own <code>async def</code> functions, you can <code>await</code> these <code>Future</code>'s.</p>
2130<p>The <code>async def</code> functions are also called &quot;coroutines&quot;, and Python does some magic behind the scenes to turn them into such. The coroutines can be <code>await</code>'ed, and this is what you normally do.</p>
2131<h2 id="a-toy-example">A Toy Example</h2>
2132<p>That's all about <code>asyncio</code>! Let's wrap up with some example code. We will create a server that replies with the text a client sends, but reversed. First, we will show what you could write with normal synchronous code, and then we will port it.</p>
2133<p>Here is the <strong>synchronous version</strong>:</p>
2134<pre><code class="language-python" data-lang="python"># server.py
2135import socket
2136
2137
2138def server_method():
2139 # create a new server socket to listen for connections
2140 server = socket.socket()
2141
2142 # bind to localhost:6789 for new connections
2143 server.bind(('localhost', 6789))
2144
2145 # we will listen for one client at most
2146 server.listen(1)
2147
2148 # *block* waiting for a new client
2149 client, _ = server.accept()
2150
2151 # *block* waiting for some data
2152 data = client.recv(1024)
2153
2154 # reverse the data
2155 data = data[::-1]
2156
2157 # *block* sending the data
2158 client.sendall(data)
2159
2160 # close client and server
2161 server.close()
2162 client.close()
2163
2164
2165if __name__ == '__main__':
2166 # block running the server
2167 server_method()
2168</code></pre>
2169<pre><code class="language-python" data-lang="python"># client.py
2170import socket
2171
2172
2173def client_method():
2174 message = b'Hello Server!\n'
2175 client = socket.socket()
2176
2177 # *block* trying to stabilish a connection
2178 client.connect(('localhost', 6789))
2179
2180 # *block* trying to send the message
2181 print('Sending', message)
2182 client.sendall(message)
2183
2184 # *block* until we receive a response
2185 response = client.recv(1024)
2186 print('Server replied', response)
2187
2188 client.close()
2189
2190
2191if __name__ == '__main__':
2192 client_method()
2193</code></pre>
2194<p>From what we've seen, this code will block on all the lines with a comment above them saying that they will block. This means that for running more than one client or server, or both in the same file, you will need threads. But we can do better, we can rewrite it into <code>asyncio</code>!</p>
2195<p>The first step is to mark all your <code>def</code>initions that may block with <code>async</code>. This marks them as coroutines, which can be <code>await</code>ed on.</p>
2196<p>Second, since we're using low-level sockets, we need to make use of the methods that <code>asyncio</code> provides directly. If this was a third-party library, this would be just like using their <code>async def</code>initions.</p>
2197<p>Here is the <strong>asynchronous version</strong>:</p>
2198<pre><code class="language-python" data-lang="python"># server.py
2199import asyncio
2200import socket
2201
2202# get the default &quot;event loop&quot; that we will run
2203loop = asyncio.get_event_loop()
2204
2205
2206# notice our new &quot;async&quot; before the definition
2207async def server_method():
2208 server = socket.socket()
2209 server.bind(('localhost', 6789))
2210 server.listen(1)
2211
2212 # await for a new client
2213 # the event loop can run other code while we wait here!
2214 client, _ = await loop.sock_accept(server)
2215
2216 # await for some data
2217 data = await loop.sock_recv(client, 1024)
2218 data = data[::-1]
2219
2220 # await for sending the data
2221 await loop.sock_sendall(client, data)
2222
2223 server.close()
2224 client.close()
2225
2226
2227if __name__ == '__main__':
2228 # run the loop until &quot;server method&quot; is complete
2229 loop.run_until_complete(server_method())
2230</code></pre>
2231<pre><code class="language-python" data-lang="python"># client.py
2232import asyncio
2233import socket
2234
2235loop = asyncio.get_event_loop()
2236
2237
2238async def client_method():
2239 message = b'Hello Server!\n'
2240 client = socket.socket()
2241
2242 # await to stabilish a connection
2243 await loop.sock_connect(client, ('localhost', 6789))
2244
2245 # await to send the message
2246 print('Sending', message)
2247 await loop.sock_sendall(client, message)
2248
2249 # await to receive a response
2250 response = await loop.sock_recv(client, 1024)
2251 print('Server replied', response)
2252
2253 client.close()
2254
2255
2256if __name__ == '__main__':
2257 loop.run_until_complete(client_method())
2258</code></pre>
2259<p>That's it! You can place these two files separately and run, first the server, then the client. You should see output in the client.</p>
2260<p>The big difference here is that you can easily modify the code to run more than one server or clients at the same time. Whenever you <code>await</code> the event loop will run other of your code. It seems to &quot;block&quot; on the <code>await</code> parts, but remember it's actually jumping to run more code, and the event loop will get back to you whenever it can.</p>
2261<p>In short, you need an <code>async def</code> to <code>await</code> things, and you run them with the event loop instead of calling them directly. So this…</p>
2262<pre><code class="language-python" data-lang="python">def main():
2263 ... # some code
2264
2265
2266if __name__ == '__main__':
2267 main()
2268</code></pre>
2269<p>…becomes this:</p>
2270<pre><code class="language-python" data-lang="python">import asyncio
2271
2272
2273async def main():
2274 ... # some code
2275
2276
2277if __name__ == '__main__':
2278 asyncio.get_event_loop().run_until_complete(main)
2279</code></pre>
2280<p>This is pretty much how most of your <code>async</code> scripts will start, running the main method until its completion.</p>
2281<h2 id="a-real-example">A Real Example</h2>
2282<p>Let's have some fun with a real library. We'll be using <a href="https://github.com/LonamiWebs/Telethon">Telethon</a> to broadcast a message to our three best friends, all at the same time, thanks to the magic of <code>asyncio</code>. We'll dive right into the code, and then I'll explain our new friend <code>asyncio.wait(...)</code>:</p>
2283<pre><code class="language-python" data-lang="python"># broadcast.py
2284import asyncio
2285import sys
2286
2287from telethon import TelegramClient
2288
2289# (you need your own values here, check Telethon's documentation)
2290api_id = 123
2291api_hash = '123abc'
2292friends = [
2293 '@friend1__username',
2294 '@friend2__username',
2295 '@bestie__username'
2296]
2297
2298# we will have to await things, so we need an async def
2299async def main(message):
2300 # start is a coroutine, so we need to await it to run it
2301 client = await TelegramClient('me', api_id, api_hash).start()
2302
2303 # wait for all three client.send_message to complete
2304 await asyncio.wait([
2305 client.send_message(friend, message)
2306 for friend in friends
2307 ])
2308
2309 # and close our client
2310 await client.disconnect()
2311
2312
2313if __name__ == '__main__':
2314 if len(sys.argv) != 2:
2315 print('You must pass the message to broadcast!')
2316 quit()
2317
2318 message = sys.argv[1]
2319 asyncio.get_event_loop().run_until_complete(main(message))
2320</code></pre>
2321<p>Wait… how did that send a message to all three of
2322my friends? The magic is done here:</p>
2323<pre><code class="language-python" data-lang="python">[
2324 client.send_message(friend, message)
2325 for friend in friends
2326]
2327</code></pre>
2328<p>This list comprehension creates another list with three
2329coroutines, the three <code>client.send_message(...)</code>.
2330Then we just pass that list to <code>asyncio.wait</code>:</p>
2331<pre><code class="language-python" data-lang="python">await asyncio.wait([...])
2332</code></pre>
2333<p>This method, by default, waits for the list of coroutines to run until they've all finished. You can read more on the Python <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.wait">documentation</a>. Truly a good function to know about!</p>
2334<p>Now whenever you have some important news for your friends, you can simply <code>python3 broadcast.py 'I bought a car!'</code> to tell all your friends about your new car! All you need to remember is that you need to <code>await</code> on coroutines, and you will be good. <code>asyncio</code> will warn you when you forget to do so.</p>
2335<h2 id="extra-material">Extra Material</h2>
2336<p>If you want to understand how <code>asyncio</code> works under the hood, I recommend you to watch this hour-long talk <a href="https://youtu.be/M-UcUs7IMIM">Get to grips with asyncio in Python 3</a> by Robert Smallshire. In the video, they will explain the differences between concurrency and parallelism, along with others concepts, and how to implement your own <code>asyncio</code> &quot;scheduler&quot; from scratch.</p>
2337</content>
2338 </entry>
2339 <entry xml:lang="en">
2340 <title>Atemporal Blog Posts</title>
2341 <published>2018-02-03T00:00:00+00:00</published>
2342 <updated>2021-02-19T00:00:00+00:00</updated>
2343 <link href="https://lonami.dev/blog/posts/" type="text/html"/>
2344 <id>https://lonami.dev/blog/posts/</id>
2345 <content type="html"><p>These are some interesting posts and links I've found around the web. I believe they are quite interesting and nice reads, so if you have the time, I encourage you to check some out.</p>
2346<h2 id="algorithms">Algorithms</h2>
2347<ul>
2348<li><a href="http://www.tannerhelland.com/4660/dithering-eleven-algorithms-source-code/">Image Dithering: Eleven Algorithms and Source Code</a>. What does it mean and how to achieve it?</li>
2349<li><a href="https://cristian.io/post/bloom-filters/">Idempotence layer on bloom filters</a>. What are they and how can they help?</li>
2350<li><a href="https://en.wikipedia.org/wiki/Huffman_coding">Huffman coding</a>. This encoding is a simple yet interesting way of compressing information.</li>
2351<li><a href="https://github.com/mxgmn/WaveFunctionCollapse">Wave Function Collapse</a>. Bitmap &amp; tilemap generation from a single example with the help of ideas from quantum mechanics.</li>
2352<li><a href="https://blog.nelhage.com/2015/02/regular-expression-search-with-suffix-arrays/">Regular Expression Search with Suffix Arrays</a>. A way to efficiently search large amounts of text.</li>
2353</ul>
2354<h2 id="culture">Culture</h2>
2355<ul>
2356<li><a href="https://www.wired.com/story/ideas-joi-ito-robot-overlords/">Why Westerners Fear Robots and the Japanese Do Not</a>. Explains some possible reasons for this case.</li>
2357<li><a href="http://catb.org/%7Eesr/faqs/smart-questions.html">How To Ask Questions The Smart Way</a>. Some bits of hacker culture and amazing tips on how to ask a question.</li>
2358<li><a href="http://apenwarr.ca/log/?m=201809#14">XML, blockchains, and the strange shapes of progress</a>. Some of history about XML and blockchain.</li>
2359<li><a href="https://czep.net/17/legion-of-lobotomized-unices.html">Legion of lobotomized unices</a>. A time where computers are treated a lot more nicely.</li>
2360<li><a href="https://eli.thegreenplace.net/2016/the-expression-problem-and-its-solutions/">The Expression Problem and its solutions</a>. What is it and what can we do to solve it?</li>
2361<li><a href="http://allendowney.blogspot.com/2015/08/the-inspection-paradox-is-everywhere.html">The Inspection Paradox is Everywhere</a>. Interesting and very common phenomena.</li>
2362<li><a href="https://github.com/ChrisKnott/Algojammer">An experimental code editor for writing algorithms</a>. Contains several links to different tools for reverse debugging.</li>
2363<li><a href="http://habitatchronicles.com/2017/05/what-are-capabilities/">What Are Capabilities?</a> Good ideas with great security implications.</li>
2364<li><a href="https://blog.aurynn.com/2015/12/16-contempt-culture">Contempt Culture</a>. Or why you should not speak crap about your non-favourite programming languages.</li>
2365<li><a href="https://www.lesswrong.com/posts/tscc3e5eujrsEeFN4/well-kept-gardens-die-by-pacifism">Well-Kept Gardens Die By Pacifism</a>. Risks any online community can run into.</li>
2366<li><a href="https://ncase.me/">It's Nicky Case!</a> They make some cool things worth checking out, I really like &quot;we become what we behold&quot;.</li>
2367</ul>
2368<h2 id="debate">Debate</h2>
2369<ul>
2370<li><a href="https://steemit.com/opensource/@crell/open-source-is-awful">Open Source is awful</a>. Has some points about why is it bad and how it could improve.</li>
2371<li><a href="http://www.mondo2000.com/2018/01/17/pink-lexical-goop-dark-side-autocorrect/">Pink Lexical Goop: The Dark Side of Autocorrect</a>. It can shape how you think.</li>
2372<li><a href="http://blog.ploeh.dk/2015/08/03/idiomatic-or-idiosyncratic/">Idiomatic or idiosyncratic?</a> Can porting code constructs from other languages have a positive effect?</li>
2373<li><a href="https://gamasutra.com/view/news/169296/Indepth_Functional_programming_in_C.php">In-depth: Functional programming in C++</a>. Is it useful to bother with functional concepts in a language like C++?</li>
2374<li><a href="https://vorpus.org/blog/notes-on-structured-concurrency-or-go-statement-considered-harmful/">Notes on structured concurrency, or: Go statement considered harmful</a>.</li>
2375<li><a href="https://queue.acm.org/detail.cfm?id=3212479">C Is Not a Low-level Language</a>. Could there be alternative programming models designed for more specialized CPUs?</li>
2376</ul>
2377<h2 id="food-for-thought">Food for Thought</h2>
2378<ul>
2379<li><a href="https://www.hillelwayne.com/post/divide-by-zero/">1/0 = 0</a>. Explores why it makes sense to redefine mathemathics under some circumstances, and why it is possible to do so.</li>
2380<li><a href="https://jeremykun.com/2018/04/13/for-mathematicians-does-not-mean-equality/">For mathematicians, = does not mean equality</a>. What other definitions does the equal sign have?</li>
2381<li><a href="https://www.lesswrong.com/posts/2MD3NMLBPCqPfnfre/cached-thoughts">Cached Thoughts</a>. How is it possible that our brains work at all?</li>
2382<li><a href="http://tonsky.me/blog/disenchantment/">Software disenchantment</a>. Faster hardware and slower software is a trend.
2383<ul>
2384<li><a href="https://blackhole12.com/blog/software-engineering-is-bad-but-it-s-not-that-bad/">Software Engineering Is Bad, But That's Not Why</a>. This post has some good counterpoints to Software disenchantment.</li>
2385</ul>
2386</li>
2387<li><a href="http://journal.stuffwithstuff.com/2015/02/01/what-color-is-your-function/">What Color is Your Function?</a>. Spoiler: can we approach asynchronous IO better?</li>
2388<li><a href="https://hackernoon.com/im-harvesting-credit-card-numbers-and-passwords-from-your-site-here-s-how-9a8cb347c5b5">I'm harvesting credit card numbers and passwords from your site</a>. A word of warning when mindlessly adding dependencies.</li>
2389<li><a href="https://medium.com/message/everything-is-broken-81e5f33a24e1">Everything Is Broken</a>. Some of the (probable) truths about our world.</li>
2390<li><a href="http://johnsalvatier.org/blog/2017/reality-has-a-surprising-amount-of-detail">Reality has a surprising amount of detail</a>.</li>
2391</ul>
2392<h2 id="funny">Funny</h2>
2393<ul>
2394<li><a href="http://thedailywtf.com/articles/We-Use-BobX">We Use BobX</a>. BobX.</li>
2395<li><a href="http://thedailywtf.com/articles/the-inner-json-effect">The Inner JSON Effect</a>. For some reason, custom languages are in.</li>
2396<li><a href="https://thedailywtf.com/articles/exponential-backup">Exponential Backup</a>. Far better than git.</li>
2397<li><a href="https://thedailywtf.com/articles/ITAPPMONROBOT">ITAPPMONROBOT</a>. Solving software problems with hardware.</li>
2398<li><a href="https://thedailywtf.com/articles/a-tapestry-of-threads">A Tapestry of Threads</a>. More threads must mean faster code, right?</li>
2399<li><a href="https://medium.com/commitlog/a-brief-totally-accurate-history-of-programming-languages-cd93ec806124">A Brief Totally Accurate History Of Programming Languages</a>. Don't take offense for it!</li>
2400</ul>
2401<h2 id="graphics">Graphics</h2>
2402<ul>
2403<li><a href="http://shaunlebron.github.io/visualizing-projections/">Visualizing Projections</a>. Small post about different projection methods.</li>
2404<li><a href="http://www.iquilezles.org/www/index.htm">Inigo Quilez :: fractals, computer graphics, mathematics, shaders, demoscene and more</a> A <em>lot</em> of useful and quality articles regarding computer graphics.</li>
2405</ul>
2406<h2 id="history">History</h2>
2407<ul>
2408<li><a href="https://twobithistory.org/2018/08/18/ada-lovelace-note-g.html">What Did Ada Lovelace's Program Actually Do?</a>. And other characters that took part in the beginning's of programming.</li>
2409<li><a href="https://chrisdown.name/2018/01/02/in-defence-of-swap.html">In defence of swap: common misconceptions</a>. Swap is still an useful concept.</li>
2410<li><a href="https://www.pacifict.com/Story/">The Graphing Calculator Story</a>. A great classic Apple tale.</li>
2411<li><a href="https://twobithistory.org/2018/10/14/lisp.html">How Lisp Became God's Own Programming Language</a>. Lisp as a foundational programming language.</li>
2412</ul>
2413<h2 id="motivational">Motivational</h2>
2414<ul>
2415<li><a href="https://www.joelonsoftware.com/2002/01/06/fire-and-motion/">Fire And Motion</a>. What does actually take to get things done?</li>
2416<li><a href="https://realmensch.org/2017/08/25/the-parable-of-the-two-programmers/">The Parable of the Two Programmers</a>. This tale is about two different types of programmer and their respective endings in a company, illustrating how the one you wouldn't expect to actually ends in a better situation.</li>
2417<li><a href="https://byorgey.wordpress.com/2018/05/06/conversations-with-a-six-year-old-on-functional-programming/">Conversations with a six-year-old on functional programming</a>. Little kids today can be really interested in technological topics.</li>
2418<li><a href="https://bulletproofmusician.com/how-many-hours-a-day-should-you-practice/">How Many Hours a Day Should You Practice?</a>. While the article is about music, it applies to any other areas.</li>
2419<li><a href="http://nathanmarz.com/blog/suffering-oriented-programming.html">Suffering-oriented programming</a>. A possibly new approach on how you could tackle your new projects.</li>
2420<li><a href="https://www.joelonsoftware.com/2000/04/06/things-you-should-never-do-part-i/">Things You Should Never Do, Part I</a>. There is no need to rewrite your code.</li>
2421</ul>
2422<h2 id="optimization">Optimization</h2>
2423<ul>
2424<li><a href="http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html">What Every C Programmer Should Know About Undefined Behavior #1/3</a>. Explains what undefined behaviour is and why it makes sense.</li>
2425<li><a href="http://ridiculousfish.com/blog/posts/labor-of-division-episode-i.html">Labor of Division (Episode I)</a>. Some tricks to divide without division.</li>
2426<li><a href="http://blog.moertel.com/posts/2013-12-14-great-old-timey-game-programming-hack.html">A Great Old-Timey Game-Programming Hack</a>. Abusing instructions to make games playable even on the slowest hardware.</li>
2427<li><a href="https://web.archive.org/web/20191213224640/https://people.eecs.berkeley.edu/%7Esangjin/2012/12/21/epoll-vs-kqueue.html">Scalable Event Multiplexing: epoll vs kqueue</a>. How good OS primitives can really help performance and scability.</li>
2428<li><a href="https://adamdrake.com/command-line-tools-can-be-235x-faster-than-your-hadoop-cluster.html">Command-line Tools can be 235x Faster than your Hadoop Cluster</a>. Or how to use the right tool for the right job.</li>
2429<li><a href="https://nullprogram.com/blog/2018/05/27/">When FFI Function Calls Beat Native C</a>. How lua beat C at it and the explanation behind it.</li>
2430<li><a href="http://igoro.com/archive/gallery-of-processor-cache-effects/">Gallery of Processor Cache Effects</a>. Knowing a few things about the cache can make a big difference.</li>
2431</ul>
2432</content>
2433 </entry>
2434 <entry xml:lang="en">
2435 <title>Graphs</title>
2436 <published>2017-06-02T00:00:00+00:00</published>
2437 <updated>2017-06-02T00:00:00+00:00</updated>
2438 <link href="https://lonami.dev/blog/graphs/" type="text/html"/>
2439 <id>https://lonami.dev/blog/graphs/</id>
2440 <content type="html"><p><noscript>There are a few things which won't render unless you enable
2441JavaScript. No tracking, I promise!</noscript></p>
2442<blockquote>
2443<p>Don't know English? <a href="https://lonami.dev/blog/graphs/spanish.html">Read the Spanish version instead</a>.</p>
2444</blockquote>
2445<p>Let's imagine we have 5 bus stations, which we'll denote by ((s_i)):</p>
2446<div class="matrix">
2447 ' s_1 ' s_2 ' s_3 ' s_4 ' s_5 \\
2448s_1 ' ' V ' ' ' \\
2449s_2 ' V ' ' ' ' V \\
2450s_3 ' ' ' ' V ' \\
2451s_4 ' ' V ' V ' ' \\
2452s_5 ' V ' ' ' V '
2453</div>
2454<p>This is known as a &quot;table of direct interconnections&quot;.
2455The ((V)) represent connected paths. For instance, on the first
2456row starting at ((s_1)), reaching the ((V)),
2457allows us to turn up to get to ((s_2)).</p>
2458<p>We can see the above table represented in a more graphical way:</p>
2459<p><img src="https://lonami.dev/blog/graphs/example1.svg" alt="Table 1 as a Graph" /></p>
2460<p>This type of graph is called, well, a graph, and it's a directed
2461graph (or digraph), since the direction on which the arrows go does
2462matter. It's made up of vertices, joined together by edges (also known as
2463lines or directed arcs).</p>
2464<p>One can walk from a node to another through different paths. For
2465example, ((s_4 $rightarrow s_2 $rightarrow s_5)) is an indirect path of order
2466two, because we must use two edges to go from ((s_4)) to
2467((s_5)).</p>
2468<p>Let's now represent its adjacency matrix called A which represents the
2469same table, but uses 1 instead V to represent
2470a connection:</p>
2471<div class="matrix">
2472 0 ' 1 ' 0 ' 0 ' 0 \\
2473 1 ' 0 ' 0 ' 0 ' 1 \\
2474 0 ' 0 ' 0 ' 1 ' 0 \\
2475 0 ' 1 ' 1 ' 0 ' 0 \\
2476 1 ' 0 ' 0 ' 1 ' 0
2477</div>
2478<p>This way we can see how the ((a_{2,1})) element represents the
2479connection ((s_2 $rightarrow s_1)), and the ((a_{5,1})) element the
2480((s_5 $rightarrow s_1)) connection, etc.</p>
2481<p>In general, ((a_{i,j})) represents a connection from
2482((s_i $rightarrow s_j))as long as ((a_{i,j}$geq 1)).</p>
2483<p>Working with matrices allows us to have a computable representation of
2484any graph, which is very useful.</p>
2485<hr />
2486<p>Graphs have a lot of interesting properties besides being representable
2487by a computer. What would happen if, for instance, we calculated
2488((A^2))? We obtain the following matrix:</p>
2489<div class="matrix">
24901 ' 0 ' 0 ' 0 ' 1 \\
24911 ' 1 ' 0 ' 1 ' 0 \\
24920 ' 1 ' 1 ' 0 ' 0 \\
24931 ' 0 ' 0 ' 1 ' 1 \\
24940 ' 2 ' 1 ' 0 ' 0
2495</div>
2496<p>We can interpret this as the paths of order two.
2497But what does the element ((a_{5,2}=2)) represent? It indicates
2498the amount of possible ways to go from ((s_5 $rightarrow s_i $rightarrow s_2)).</p>
2499<p>One can manually multiply the involved row and column to determine which
2500element is the one we need to pass through, this way we have the row
2501(([1 0 0 1 0])) and the column (([1 0 0 1 0])) (on
2502vertical). The elements ((s_i$geq 1)) are ((s_1)) and
2503((s_4)). This is, we can go from ((s_5)) to
2504((s_2)) via ((s_5 $rightarrow s_1 $rightarrow s_2)) or via
2505((s_5 $rightarrow s_4 $rightarrow s_2)):
2506<img src="example2.svg" /></p>
2507<p>It's important to note that graphs to not consider self-connections, this
2508is, ((s_i $rightarrow s_i)) is not allowed; neither we work with multigraphs
2509here (those which allow multiple connections, for instance, an arbitrary
2510number ((n)) of times).</p>
2511<div class="matrix">
25121 ' 1 ' 0 ' 1 ' 0 \\
25131 ' 2 ' \textbf{1} ' 0 ' 1 \\
25141 ' 0 ' 0 ' 1 ' 1 \\
25151 ' 2 ' 1 ' 1 ' 0 \\
25162 ' 0 ' 0 ' 1 ' 2
2517</div>
2518<p>We can see how the first ((1)) just appeared on the element
2519((a_{2,3})), which means that the shortest path to it is at least
2520of order three.</p>
2521<hr />
2522<p>A graph is said to be strongly connected as long as there is a
2523way to reach all its elements.</p>
2524<p>We can see all the available paths until now by simply adding up all the
2525direct and indirect ways to reach a node, so for now, we can add
2526((A+A^2+A^3)) in such a way that:</p>
2527<div class="matrix">
25282 ' 2 ' 0 ' 1 ' 1 \\
25293 ' 3 ' 1 ' 1 ' 3 \\
25301 ' 1 ' 1 ' 2 ' 1 \\
25312 ' 3 ' 2 ' 2 ' 1 \\
25323 ' 2 ' 1 ' 2 ' 2
2533</div>
2534<p>There isn't a connection between ((s_1)) and ((s_3)) yet.
2535If we were to calculate ((A^4)):</p>
2536<div class="matrix">
25371 ' 2 ' 1 ' ' \\
2538 ' ' ' ' \\
2539 ' ' ' ' \\
2540 ' ' ' ' \\
2541 ' ' ' '
2542</div>
2543<p>We don't need to calculate anymore. We now know that the graph is
2544strongly connected!</p>
2545<hr />
2546<p>Congratulations! You've completed this tiny introduction to graphs.
2547Now you can play around with them and design your own connections.</p>
2548<p>Hold the left mouse button on the above area and drag it down to create
2549a new node, or drag a node to this area to delete it.</p>
2550<p>To create new connections, hold the right mouse button on the node you
2551want to start with, and drag it to the node you want it to be connected to.</p>
2552<p>To delete the connections coming from a specific node, middle click it.</p>
2553<table><tr><td style="width:100%;">
2554 <button onclick="resetConnections()">Reset connections</button>
2555 <button onclick="clearNodes()">Clear all the nodes</button>
2556 <br />
2557 <br />
2558 <label for="matrixOrder">Show matrix of order:</label>
2559 <input id="matrixOrder" type="number" min="1" max="5"
2560 value="1" oninput="updateOrder()">
2561 <br />
2562 <label for="matrixAccum">Show accumulated matrix</label>
2563 <input id="matrixAccum" type="checkbox" onchange="updateOrder()">
2564 <br />
2565 <br />
2566 <div>
2567 <table id="matrixTable"></table>
2568 </div>
2569</td><td>
2570 <canvas id="canvas" width="400" height="400" oncontextmenu="return false;">
2571 Looks like your browser won't let you see this fancy example :(
2572 </canvas>
2573 <br />
2574</td></tr></table>
2575<script src="tinyparser.js"></script>
2576<script src="enhancements.js"></script>
2577<script src="graphs.js"></script>
2578</content>
2579 </entry>
2580 <entry xml:lang="en">
2581 <title>Installing NixOS</title>
2582 <published>2017-05-13T00:00:00+00:00</published>
2583 <updated>2019-02-16T00:00:00+00:00</updated>
2584 <link href="https://lonami.dev/blog/installing-nixos/" type="text/html"/>
2585 <id>https://lonami.dev/blog/installing-nixos/</id>
2586 <content type="html"><h2 id="update">Update</h2>
2587<p><em>Please see <a href="../installing_nixos_2/index.html">my followup post with NixOS</a> for a far better experience with it</em></p>
2588<hr />
2589<p>Today I decided to install <a href="http://nixos.org/">NixOS</a> as a recommendation, a purely functional Linux distribution, since <a href="https://xubuntu.org/">Xubuntu</a> kept crashing. Here's my journey, and how I managed to install it from a terminal for the first time in my life. Steps aren't hard, but they may not seem obvious at first.</p>
2590<ul>
2591<li>
2592<p>Grab the Live CD, burn it on a USB stick and boot. I recommend using <a href="https://etcher.io/">Etcher</a>.</p>
2593</li>
2594<li>
2595<p>Type <code>systemctl start display-manager</code> and wait.<sup class="footnote-reference"><a href="#1">1</a></sup></p>
2596</li>
2597<li>
2598<p>Open both the manual and the <code>konsole</code>.</p>
2599</li>
2600<li>
2601<p>Connect to the network using the GUI.</p>
2602</li>
2603<li>
2604<p>Create the disk partitions by using <code>fdisk</code>.</p>
2605<p>You can list them with <code>fdisk -l</code>, modify a certain drive with <code>fdisk /dev/sdX</code> (for instance, <code>/dev/sda</code>) and follow the instructions.</p>
2606<p>To create the file system, use <code>mkfs.ext4 -L &lt;label&gt; /dev/sdXY</code> and swap with <code>mkswap -L &lt;label&gt; /dev/sdXY</code>.</p>
2607<p>The EFI partition should be done with <code>mkfs.vfat</code>.</p>
2608</li>
2609<li>
2610<p>Mount the target to <code>/mnt</code> e.g. if the label was <code>nixos</code>, <code>mount /dev/disk/by-label/nixos /mnt</code></p>
2611</li>
2612<li>
2613<p><code>mkdir /mnt/boot</code> and then mount your EFI partition to it.</p>
2614</li>
2615<li>
2616<p>Generate a configuration template with <code>nixos-generate-config --root /mnt</code>, and modify it with <code>nano /etc/nixos/configuration.nix</code>.</p>
2617</li>
2618<li>
2619<p>While modifying the configuration, make sure to add <code>boot.loader.grub.device = &quot;/dev/sda&quot;</code></p>
2620</li>
2621<li>
2622<p>More useful configuration things are:</p>
2623<ul>
2624<li>Uncomment the whole <code>i18n</code> block.</li>
2625<li>Add some essential packages like <code>environment.systemPackages = with pkgs; [wget git firefox pulseaudio networkmanagerapplet];</code>.</li>
2626<li>If you want to use XFCE, add <code>services.xserver.desktopManager.xfce.enable = true;</code>, otherwise, you don't need <code>networkmanagerapplet</code> either. Make sure to add <code>networking.networkmanager.enable = true;</code> too.</li>
2627<li>Define some user for yourself (modify <code>guest</code> name) and use a UID greater than 1000. Also, add yourself to <code>extraGroups = [&quot;wheel&quot; &quot;networkmanager&quot;];</code> (the first to be able to <code>sudo</code>, the second to use network related things).</li>
2628</ul>
2629</li>
2630<li>
2631<p>Run <code>nixos-install</code>. If you ever modify that file again, to add more packages for instance (this is how they're installed), run <code>nixos-rebuild switch</code> (or use <code>test</code> to test but don't boot to it, or <code>boot</code> not to switch but to use on next boot.</p>
2632</li>
2633<li>
2634<p><code>reboot</code>.</p>
2635</li>
2636<li>
2637<p>Login as <code>root</code>, and set a password for your user with <code>passwd &lt;user&gt;</code>. Done!</p>
2638</li>
2639</ul>
2640<p>I enjoyed the process of installing it, and it's really cool that it has versioning and is so clean to keep track of which packages you install. But not being able to run arbitrary binaries by default is something very limitting in my opinion, though they've done a good job.</p>
2641<p>I'm now back to Xubuntu, with a fresh install.</p>
2642<h2 id="update-1">Update</h2>
2643<p>It is not true that &quot;they don't allow running arbitrary binaries by default&quot;, as pointed out in their <a href="https://nixos.org/nixpkgs/manual/#sec-fhs-environments">manual, buildFHSUserEnv</a>:</p>
2644<blockquote>
2645<p><code>buildFHSUserEnv</code> provides a way to build and run FHS-compatible lightweight sandboxes. It creates an isolated root with bound <code>/nix/store</code>, so its footprint in terms of disk space needed is quite small. This allows one to run software which is hard or unfeasible to patch for NixOS -- 3rd-party source trees with FHS assumptions, games distributed as tarballs, software with integrity checking and/or external self-updated binaries. It uses Linux namespaces feature to create temporary lightweight environments which are destroyed after all child processes exit, without root user rights requirement.</p>
2646</blockquote>
2647<p>Thanks to <a href="https://github.com/bb010g">@bb010g</a> for pointing this out.</p>
2648<h2 id="notes">Notes</h2>
2649<div class="footnote-definition" id="1"><sup class="footnote-definition-label">1</sup>
2650<p>The keyboard mapping is a bit strange. On my Spanish keyboard, the keys were as follows:</p>
2651</div>
2652<table><thead><tr><th>Keyboard</th><th>Maps to</th><th>Shift</th></tr></thead><tbody>
2653<tr><td>'</td><td>-</td><td>_</td></tr>
2654<tr><td>´</td><td>'</td><td>&quot;</td></tr>
2655<tr><td>`</td><td>[</td><td></td></tr>
2656<tr><td>+</td><td>]</td><td></td></tr>
2657<tr><td>¡</td><td>=</td><td></td></tr>
2658<tr><td>-</td><td>/</td><td></td></tr>
2659<tr><td>ñ</td><td>;</td><td></td></tr>
2660</tbody></table>
2661</content>
2662 </entry>
2663</feed>