Aug 21

Stupid C++ Threads and Lambdas

For a unit test that I’m writing for some code at the moment, I need to create a thread that doesn’t do anything. Well, the easiest way to do this is to do a lambda function. And since we don’t need to capture anything, and the thread doesn’t need to do anything, I have written the following line of code:

std::thread thr = std::thread( [](){} );

Just look at it in its simplicity. In case you missed it:

[](){}

I actually started laughing after I had written that, it’s just so stupid that it’s funny!

Jun 27

Fixing a Gamecube Disk read error

I recently wanted to play my Gamecube again, so I turned it on for the first time in a while. Unfortunately, it would no longer read any of the disks that I had. Upon some internet searching, it seemed like this is a well-known problem with Gamecubes, in that they will eventually stop reading disks. Fortunately, the fix is pretty simple: you need to adjust a variable resistor on the board in order to get the disks to read again.

I’d like to first say that the information that I got on how to adjust the laser was mostly from this very informative Youtube video, so I would recommend watching that video first. In terms of tools to open the Gamecube, I have the ifixit Moray set of screw bits, which has the special bit required to open the Gamecube.

In my particular case, I have a DOL-001 model of Gamecube. According to the information that I have found online, the value of VR-401 should be between 200-500 ohms for this model(other sources say it should be between 450-600 ohms). Upon opening up my Gamecube however, I noticed that it was below what the minimum level should be(I think it was about 195 ohms). I then spent quite a while adjusting the pot to try and get it to a good value, and was unsuccessful. I was tweaking it in very small increments(~5 ohm), putting it back in, and trying it out. Having finally gotten very frustrated with it, I turned it down to 152 ohms, and all of a sudden it started working! It didn’t work 100% of the time(it seems to need to warm up first), but it started working again.

Upon some further adjustment(after I discovered that it wasn’t super reliable), I eventually got it to reliably read disks at 100 ohms! This is much lower than I would have expected based on the model number and expected range of values for this resistor.

Hints when doing this:
* Make sure to take down the original value of VR-401 before you start.
* Try to go in very small increments. At least in my case, there is a very narrow band that VR-401 needs to be in for the disk to be read reliably
* Had I gone down in my adjustments first, I probably wouldn’t have wasted much time adjusting. I was confused because the original value that I got for VR-401 was so much lower than was was to be expected. My guess is that if you need to adjust the value of VR-401, the new value will probably be near the old value.
* Write down the values that you have done. I have probably adjusted VR-401 a hundred times at this point, so knowing where you have gone is good!
* Once you have a good value, write it on the housing inside of the Gamecube near the laser so that if you need to adjust it again, you know what worked!

May 10

C++ pimpl thoughts

Recently, I’ve been writing some C++ code that I would like to be ABI compliant. Because of that, I’ve been writing the code that uses a private class that holds all of the private data members. This results in code that looks something like the following:

// myclass.h

#include <memory>

class MyClass{
public:
	MyClass();
	~MyClass();

	int foo() const;
	void setFoo( int val );

private:
	class priv;

	std::unique_ptr<priv> m_priv;
};

// myclass.cpp
#include "myclass.h"

class MyClass::priv {
public:
	priv() :
	m_foo( 5 )
	{}

	int m_foo;
};

MyClass::MyClass(){
	m_priv = std::make_unique<priv>();
}

MyClass::~MyClass(){
}

int MyClass::foo() const {
	return m_priv->m_foo;
}

void MyClass::setFoo( int foo ){
	m_priv->m_foo = foo;
}

However, after some further reading I realized that this creates a new problem with const methods: mainly that you can’t ensure const correctness! That is, if we change MyClass::foo to be the following, it’s perfectly legal:

int MyClass::foo() const {
	m_priv->m_foo += 10;
	return m_priv->m_foo;
}

Obviously, this particular design results in code that may look const-correct, but actually is not. You can get around that with having an actual pointer to the implementation and not just the private data members, but this seems like a lot of overhead and is really just a lot of boilerplate in my mind.

This leads me to some thoughts on what would make this nicer. The main problem seems to be this facet of C++:

Size and Layout: The calling code must know the size and layout of the class, including private data members.

https://herbsutter.com/gotw/_100/

Since the calling code needs to know the size and layout, any change to this causes ABI breakage, which is certainly not ideal, thus needing the pimpl pattern. What would be nice is if we didn’t have to do this. Thus, I bring my very simple 5-minute solution that hasn’t been thought out fully.

Add a new keyword! Called ‘privdata’.

Example usage:

// myclass.h

#include <memory>

class MyClass{
public:
	MyClass();
	~MyClass();

	int foo() const;
	void setFoo( int val );

private:
	privdata int m_foo;
};

// myclass.cpp
#include "myclass.h"

MyClass::MyClass() : m_foo( 5 ){
}

MyClass::~MyClass(){
}

int MyClass::foo() const {
	return m_foo;
}

void MyClass::setFoo( int foo ){
	m_foo = foo;
}

The idea behind this is that just by declaring a private variable with ‘privdata’ effectively turns the code into what I posted before with the unique_ptr, so that no matter how many private variables you add(with the ‘privdata’ keyword) the class will stay the same size.

Advantages:

  • One keyword to add
  • Very easily make a class ABI compatible.
  • No need to worry about a layer of indirection – the compiler takes care of this for you.
  • Most tools(e.g. IDEs) will still work correctly. One problem with how I’ve been implementing is that Qt Creator doesn’t have nice auto completion for m_priv->…. That’s not the end of the world, but it would be nice!
  • The compiler could still check for const correctness and only allow access in const methods and editing in non-const methods.

Disadvantages:

  • I’ve spent longer writing this post than thinking about this, so I’m certainly missing something.
  • Compilation speedups may not be possible at this point(assuming that you’re using make), since changing something in the header would cause all dependent files to be rebuilt. Maybe we need a new version of make that can parse code to know when things change and only rebuild when something important changes?
  • This requires a lot of compiler changes. New standards require compiler changes anyway, but this probably can’t be implemented without compiler changes.

I did also start looking at some more recent posts from Herb Sutter, and I found this interesting post on making a clonable class. This makes me wonder if this would be possible to do using just standard C++ and some sort of reflection library…


If you want to learn more about the pimpl patter, check out the cppreference page, which also leads to Herb Sutter’s GotW page on pimpl. Herb Sutter’s page was useful for me in terms of learning about the alternatives and how they work.


ADDENDUM NEXT DAY: It turns out, this is possible using some experimental features(std::propagate_const). See this post on Stack Overflow for more information, or on cppreference!

May 02

SSH Key Length Error

I wanted to SSH into a server of mine earlier today, but I was met with this error when I tried to SSH in using the key:

$ ssh -i private-key username@host
Load key "private-key": Invalid key length
username@host's password:

There is some information on this about the exact SSH version that I was using, but one thing that was not clear was if this was a server error or a client error.

As it turns out, this is a client error, the server itself is still fine. There’s a lot of information on the internet, but suffice to say that as of OpenSSH 7.9, you need a key at least 2048 bits long. So to solve this issue, you just need to use an older version of ssh.

If you don’t have an older version of the SSH client available, you could probably get around the issue by installing a virtual machine with an older version of the SSH client. Debian 9(stretch) comes with a version of openssh-client that will work.

Jan 05

Signing VMWare Drivers for UEFI

Earlier today, I had to install VMWare on a Linux host that had UEFI. Fortunately, there is a guide to how to do this on the VMWare KB, however at the end, the part “Reboot your machine. Follow the instructions to complete the enrollment from the UEFI console” is not clear on what exactly you need to do.

In order to get this to work on my Acer Aspire, I did the following(note: I’m not sure what exactly is required, as I was messing around with several settings).

  1. Reboot your system and add a password in the BIOS. Smash F2 when the system boots. Alternatively, GRUB should have an option to go to the BIOS. (this step may not be required)
  2. Generate the keys as shown in the VMWare KB article.
  3. Copy the .der file to /boot/efi/EFI/debian
  4. Reboot the system.
  5. You should get a screen that says ‘Perform MOK Management’. Enroll your key from here. See this site for more details.

And that should be it. It’s not hard to do, but it is not clear and may be different for each manufacturer.

Oct 11

London vs Washington DC

A few weeks ago, I took a trip to London and saw some very cool things! While I was there, I took the Underground most of the time and figured that I would make a quick list for anybody who ever wants to visit Washington, DC and is familiar with London.

First things first: some terminology. In London, the system is the Underground. In DC, the system is Metro. The long name of the system is WMATA, or Washington Metropolitan Area Transit Authority. Nobody actually calls it WMATA though, Metro would be the proper term.

Metro and Bus

Like the London Oyster card, the DC Metro uses a contactless card called Smartrip. Put it close to the reader, and the gates will open, allowing you to enter the system. Paper farecards were accepted until 2016, and were largely replaced because the maintenance of the machines to process the paper farecards became prohibitively expensive. Fares are based off of time(rush-hour or non-rush) and distance traveled.

Metro buses also accept the Smartrip card, making it easy to pay for the buses and trains. The convenient part about using a Smartrip card on the bus is that you get free two-hour transfers between buses, which can be useful if you need to travel on more than one bus.

A number of other local jurisdictions also have their own bus services. This includes Arlington Transit, Fairfax Connector, Alexandria Dash, Ride On, and DC Circulator. As far as I am aware, all of the other local bus services also take Smartrip cards as payment.

If you’re comfortable taking a bus, it is definitely a plausible way to travel around, but may be slow and not always direct.

You can pick up a Smartrip card at any Metro station(go to the fare machines). Cards can also be topped up there, or if you’re on a bus you can use the card reader on the bus to add more money to the card. If you need to do this, you probably want to wait until everybody else has boarded the bus. Press the button to add more money(left side of reader), tap Smartrip, insert money, and tap Smartrip again to have the fare loaded.

Other Metro Thoughts

The DC Metro is not as dense or have trains as often as the Underground, but it does have a few advantages. Like London, the trains display the last line on the route that they are going to. For example, the Silver line has two endpoints: Largo Town Center and Wiehle-Reston East. You need to know which direction you are going in order to get on the correct train. On the new 7000-series cars, the announcer on the train is a computerized voice; the earlier cars have the engineer making the announcements, which can be notoriously unclear.

Like London, each platform has an LED board showing the next train coming into the station. This board shows the line that the train is for(Green/Yellow/Blue/Orange/Silver/Red), the station it is going to, and how many cars the train has. There is a push to hopefully have all 8-car trains, however there are still many 6-car trains on the Metro, so those trains will be a little shorter. Since the Metro makes large use of having multiple lines share the same physical tracks, depending on where you are going you may not need to get on the same color train. For example, to get between Rosslyn and Smithsonian stations, you can take either the Orange line going to New Carrolton, the Blue line to Largo Town Center, or the Silver line to Largo Town Center.

The DC Metro is nicer than London in at least two respects: the accessibility of the stations, and the transfer from one line to another. On the accessibility side, all of the Metro trains are on straight platforms and have no steps up(or down!) into the cars. This also makes it very easy to use if you are disabled. If you need an elevator though, if the elevator at the station you are going to is broken you can get a bus transfer from another station; listen for station announcements or check the Metro website. Transferring from one line to another is also very easy, since the trains go to the same station, and at most you have one escalator to go up(or down). Why the Underground stations are very cramped and have a ton of stairs and turns between the stations is a mystery to me.

Walking Around

If you’re visiting DC as a tourist, you’re probably planning on going to the museums. The good news is that for the most part, all of the museums are situated around the national mall. This means that they are walkable, although you may walk a lot! Some places you probably want to want to take the Metro to so that you’re not walking a large distance. Unlike London, where the crosswalk is a separate stage in the light cycle, for the most part US traffic light cycles have you crossing with traffic at the same time. This makes it difficult for traffic to turn left or right, and so sometimes the cycle will allow pedestrians or traffic to go first. The indicators for if you can walk are also nice and clear, with either a walking man or a hand telling you to stop. When the hand comes up, nearly all of the walking indicators also have a separate display counting down the seconds that you have left until the light will change. This is very useful so that you can see how long you have until you need to clear the intersection, and is one thing that I missed when I was in London.

Conclusion

I don’t really have a conclusion, this is just some information for people who may be interested. There’s much more information that I could put here, but this post is long enough as-is. Have fun!

Aug 19

C++17 and Fold Expressions

So I’ve just come across this very cool feature in C++17 that I plan on using called ‘fold expressions’. This is basically a way of expanding a bunch of operations. It is also very hard for me to wrap my head around, so we’re going to go through a (very simple) example here, since people don’t seem to explain what exactly happens.

This simple example prints out everything that is passed into the method to stdout:

template <typename... argn>
void fold_test_types( argn... params ){
    (std::cout << ... << params);
}

int main(){
    fold_test_types( 3, 4, "hi", 8);
}

The output is 34hi8, because we forgot to add any newlines or spaces, but that’s fine for this example.

Now what really tripped me up here is the fact that in the fold expression, we’re using the << operator to distinguish things, and it makes it very confusing as to what is actually happening. With fold expressions, the data between the parentheses is expanded, kinda like a template. Let’s look at the rules real quick:

( pack op ... ) (1)
( ... op pack ) (2)
( pack op ... op init ) (3)
( init op ... op pack ) (4)


1) unary right fold
2) unary left fold
3) binary right fold
4) binary left fold


op – any of the following 32 binary operators: + – * / % ^ & | = < > << >> += -= *= /= %= ^= &= |= <<= >>= == != <= >= && || , .* ->*. In a binary fold, both ops must be the same.
pack – an expression that contains an unexpanded parameter pack and does not contain an operator with precedence lower than cast at the top level (formally, a cast-expression)
init – an expression that does not contain an unexpanded parameter pack and does not contain an operator with precedence lower than cast at the top level (formally, a cast-expression)
Note that the open and closing parentheses are part of the fold expression.

https://en.cppreference.com/w/cpp/language/fold

This is a bit hard to understand, but the … is basically a keyword when it is in the parentheses like this. ‘pack’ is the name of the parameters, e.g. in our example it is ‘params’.

Looking at these rules, the rule that we are following in this example is #4, the binary left fold. Let’s look at the fold expression again, with some comments:

(std::cout << ... << params);
|    |      |  |   |    |  ^----ending paren
|    |      |  |   |    ^---- pack(params) - see definition above
|    |      |  |   ^---- operator(<<)
|    |      |  ^---- ...(keyword?)
|    |      ^---- operator(<<)
|    ^--- init(std::cout) - see definition above
^----Starting paren   

With these broken out, it should now be clear why this is #4, the binary left hold. The rules on how it folds are as follows:

1) Unary right fold (E op …) becomes (E1 op (… op (EN-1 op EN)))
2) Unary left fold (… op E) becomes (((E1 op E2) op …) op EN)
3) Binary right fold (E op … op I) becomes (E1 op (… op (EN−1 op (EN op I))))
4) Binary left fold (I op … op E) becomes ((((I op E1) op E2) op …) op EN)

https://en.cppreference.com/w/cpp/language/fold

Since we are using #4, apply the rule for #4. When the compiler runs, the code effectively becomes the following with the template substitution and the fold expression expansion:

void fold_test_types( int arg1, int arg2, std::string arg3, int arg4 ){
    ((((std::cout << arg1) << arg2) << arg3) << arg4);
}

int main(){
    fold_test_types( 3, 4, "hi", 8);
}