Long time no see!

It’s been almost three years since I last posted here. Three years! That’s a really long time. A LOT has changed in my life since then.

My dad passed away.

My dad said goodbye to this world on June 2012. I miss him every single day. See you on the Last Day, dad!

Dad and I

I got married!

In October 2012, I married the most beautiful and amazing woman on Earth, Liana Lutz.

Liana and I

I became a stepdad!

Along with Liana came Sabrina, who’s just turned 6.


I moved to the US and now work at Microsoft

In February 2012 I interviewed with Microsoft at their office in São Paulo. I got an offer on the same day, after four rounds of interviews. Almost a year later, in January 2013 I landed in Seattle and now call this place home. A life dream come true!


I am working as a Software Engineer on Microsoft Dynamics AX, a highly customizable ERP product. I was initially supposed to work as a Software Development Engineer in Test (SDET), but before my start date the organization switched to what they call Unified Engineering, where every engineer became a Software Engineer (i.e. there’s no longer a distinction between SDEs and SDETs).

Overall, it’s been great

These past few years have been incredibly enriching for me. I feel that I’ve matured enormously after getting married and becoming a stepdad. I now have a much deeper appreciation for life. And then coming to the US has taught me a lot about standing on my own feet and figuring out my way in a completely new and unknown place. It was very challenging at some points in the beginning, but now we’re pretty much settled, which is great.

No promises, but…

I’ll try not to stay so long without writing anything here. It’s hard to find time to write down a decent post, but lately I’ve decided that I really should work on my writing skills. Let’s see what comes next.

propertypp: Objective-C-like properties for C++ classes

The short version: propertypp on GitHub

The long version:

A co-worker recently told me he had made some member variables in a C++ class public, because a getter and setter for them would just do exactly the same thing as reading and writing those member variables directly. I told him that was bad design, and he told me he was aware of it but that in that particular case making those member variables public would hardly have any negative impact on the system, because it was a small piece of code with a very limited and controlled scope. I told him he should still consider making those member variables private and writing getters and setters, but then he admitted he found the get*() and set*() syntax too cumbersome.

I agree with him on that last point. Calling getters and setters makes code so ugly when you could be using dot notation. Objective-C and other languages have this nice little feature called properties, which allow you to use dot notation for accessing member variables of a class, but having getters and setters getting called behind the scenes.

I began wondering if it would be possible to implement properties in C++ and soon realized it is, indeed, possible. You can declare public member variables of wrapper classes that overload cast and assignment operators and read and write private member variables containing property values. If that explanation wasn’t enough to help you picture the solution, here are some example implementations:



Those aren’t the only C++ property implementations available out there, but I found that all implementations required too much code to be used.

I set out to write a generic C++ property library that required as little effort to be used by the programmer as possible. propertypp is the result of that. I wont’t go into detail here on how to use it and what code that uses it looks like, because it’s all there on the README on GitHub.

Notice how I’ve managed to have the name of the class containing the properties to be informed only on getter and setter synthetization. If you read the code on propertypp.h, you’ll see there was no way out of that. Another nice thing is that it doesn’t have any dependencies on third-party libraries: it’s just plain C++ and STL. My initial, unpublished implementation used Boost.Function to wrap the function objects for getters and setters, but I didn’t want to impose that dependency on every project that shall use propertypp.

propertypp is far from finished. At present, it only works with fundamental data types and pointers. That prevents having a struct or object as a property, unless it’s a pointer to that struct or object. I also want to support read-only properties.

I have to admit I’m quite proud of my work on propertypp. So far, the people I’ve shown it to thought it nice. However, criticism will be appreciated if anyone has any :)

Drawing scalable pixels in the Qt Graphics View framework

Say you have a custom QGraphicsItem that you would like to draw pixel by pixel, and want it to appear pixelated when that item is scaled (or the QGraphicsView it is being displayed on, or whatever). At first, you might try drawing your pixels with QPainter::drawPoint():

void MyItem::paint(
    QPainter* painter,
    const QStyleOptionGraphicsItem* option,
    QWidget* widget)
    painter->drawPoint(x, y);

If you don’t mess with the width of the QPainter’s QPen, that won’t work. Your pixels will always be the size of 1 display pixel, no matter the item’s or the view’s scaling factor. That happens because the default pen width is 0, which guarantees points, outlines, etc. are drawn 1 pixel thick, no matter the scale. Notice the single pixel drawn on the following image, which shows a scaled 16×16 QGraphicsItem:

QPainter::drawPoint will always draw 1-pixel points no matter the scale, if the pen width is set to 0.

But guess what? Setting the pen width to 1 won’t do it either, at least not without a little extra effort. Things will start to look weird. A look into QGraphicsItem’s documentation reveals that QPainter will draw things half outside the pen’s outline, and half inside.

There are two options here:

  1. Set the pen width to 1 and compensate for the way QPainter draws things with its QPen; or
  2. Find another way to draw single pixel-sized… pixels.

The first option can be achieved like this:

QPen pen;
painter->drawPoint(QPointF(x + 0.5,y + 0.5));

But the results aren’t the best. Take a look at the following screenshot. It shows a QGraphicsView with its background QBrush set to black. There is a single 16×16 QGraphicsItem that draws a 16×16 white rectangle and a single red point at it’s bottom right corner. Notice that the red point is off the rectangle’s right border by one pixel. I’m not sure about this, but I think it might be due to floating-point error.

Drawing single pixels in QGraphicsItem::paint with a pen width of 1 does not yield the best possible results.

It seems that the most appropriate way to achieve the desired result is to draw a filled 1×1 rectangle, as in:

painter->fillRect(x, y, 1, 1, Qt::red);

Notice that you should leave/set the pen width to 0. As you can see below, there is no error like in the previous approach:

A better way to draw single pixels in QGraphicsItem::paint is by drawing 1x1 filled rectangles width the pen width set to 0.

In conclusion, you should draw single pixels by drawing filled 1×1 rectangles with a pen width of 0, instead of drawings points with a pen width of 1.

Fond Memories

When I was 9 years old, I used to go to my mom’s workplace to talk to some IT guys who were working there. Eventually, one of them started teaching me BASIC, getting me started into programming and fulfilling my desire to understand how people made “stuff appear on the screen”.

Nowadays I know how bad a language BASIC is, but I eventually get nostalgic. I still sometimes feel like opening an MS-DOS prompt on Microsoft Windows 95 and firing up QBasic 1.0, just to have hours of fun printing things on the screen and making the computer produce all sorts of beeps. Those were really nice days.

My trip to Seattle for the Amazon.com SDE interview

I was in Seattle from June 16 to 18. Amazon flew me there for a set of on-site interviews for a Software Design Engineer (SDE) position. The trip was amazing, despite the incident while returning to Brazil (read Day 5 below). I loved my time there and I loved Amazon.

What follows is a day-by-day summary of the trip. The pictures are not really high-quality, since they were taken with an iPod Touch.

Day 1 – June 15

I flew from Porto Alegre to Brasilia and then from Brasilia to Atlanta in a night flight. Everything was alright, except that Gol had some trouble finding my flight information and I had to wait about an hour to check-in in Porto Alegre. Thankfully, I had arrived much earlier than I was supposed to.

Day 2 – June 16

I got through immigration in Atlanta (quite intimidating!) and then flew to Seattle. The plane landed in Seattle at around 11 AM. I think by 12 PM I had already checked in at the Grand Hyatt. Even though I was excited to be in America for the first time and wanted to go out on the streets, I HAD to get some sleep, so I think I slept for about 2 hours.

I contacted my parents and some friends to tell them I was already in Seattle and that everything was fine. Then I contacted the Amazon.com recruiter I have been in contact with since the interview process started and she emailed me my interview schedule and some other important things. My interviews were to start at 9:45 AM the next morning.

Some time later I took a cab and went to the Best Buy store in Northgate Way. I bought myself a 32GB 4th generation iPod and also some other stuff my friends had asked for. What was particularly funny about the store is that it didn’t have an entrance for humans. A great deal of the time I was there was spent outside looking for some kind of entrance. I didn’t manage to find one, so I had to get inside through the parking garage and figuring out my way in there until I found an elevator that got me inside the store.

The cab driver was a really nice Ethiopian guy. He said it would be hard for me to find a cab back to the hotel in that area, and he waited for me while I was at Best Buy. I thought it very cool of him not to charge me for the wait, although I don’t know whether that’s usual or not. We talked a lot about our countries and he told me a number of interesting things about America.

When I got back to the hotel, I looked up the Amazon HQ’s address in Google Maps. It was close to the hotel, so I decided I would go there on foot the next morning. To make sure I knew the way, I went out later and walked to Amazon. I had no problem getting there after a 15-minute walk.

I spent the rest of the day studying for the interview and chatting online. I had a Pizza Margherita for dinner, along with 7 Up and then for dessert I had a kind of ice cream brownie with warm chocolate cover (I can’t remember what it was called).

Pizza Margherita @ Grand Hyatt Seattle7 Up @ Grand Hyatt SeattleChocolate dessert (can't remember the name!) @ Grand Hyatt Seattle

Oh, and I loved seeing a still-blueish sky at 10 PM!

Blueish sky at 10 PM in Seattle

Day 3 – June 17

My interviews were to start at 9:45 AM and I was told to get there at least 15 minutes early. I planned to leave the hotel at 9 AM, so I would get there half an hour before the interviews started.

I set up the alarm on my iPod to 7 AM, but I was fully awake a little after 5 AM. I think that was due to jet lag (Seattle is 4 hours behind Porto Alegre), or maybe because I was a little nervous, or maybe both.

I had pancakes with maple syrup and some hot apple stuff for breakfast, and also a glass of orange juice.

Pancakes with maple syrup, some apple stuff and orange juice @ Grand Hyatt Seattle

After breakfast, I went to the Amazon.com headquarters. When I got there, I had to show my passport to ID myself, and I had to sign an NDA. I had a total of 6 interviews, some of them pretty hard. Even lunch was an interview. All the Amazonians that interviewed me were awesome people. They were all incredibly nice, and it was really cool talking and discussing with them. The interview experience was amazing, no matter if I get the job or not.

The interviews involved a number of questions about algorithm design, OO design and also about the way I work. Besides being asked to write code on the whiteboard, I was also proposed some work situations and had to answer what I would do when facing them. I was also asked about the way I look at my job, about how I perceive it, and why I would like to work at Amazon.

My interviews ended around 3:30 PM. It was a beautiful day outside and I still had the whole afternoon left, so I decided to visit the Space Needle. I looked up how to get there on Google Maps, and it was also quite easy. I already knew it wasn’t too far, because I could see the Space Needle quite close from the Amazon building I was at.

I took some pictures on the way to the Space Needle. Seattle is a very beautiful city. Everything is clean and the street layout is clearly well planned. Drivers are very respectful towards pedestrians. There are many crosswalks and it was really easy to find my way around.

On the way to the Space Needle in SeattleSeattleCrosswalk in SeattleSeattleSeattle

I met a homeless guy on the way to the Space Needle. He was quite funny and told some jokes. He said he had been in Rio once during Carnival, and that he thought it was much better than Mardi Gras in Lousiana, where he said he was from. I don’t know how much of it was true, but he also told me he had survived two shipwrecks while working in Alaska and that he had been in the army, but had to retired after he got shot. He said it was funny he survived all those deadly experiences, but got really screwed up due to a divorce. After a while, each of us took different directions.

The Space Needle was a half an hour walk from the hotel. I had to pay $18 to go up there, but it was worth it. The view is quite nice.

Space Needle in SeattleDowntown Seattle seen from the Space NeedleSeattle seen from the Space NeedleSeattle seen from the Space Needle

There is a park around the Space Needle. I took a short walk around it and took some more pictures.

Park around the Space Needle in SeattleMonument in park around the Space Needle in SeattlePark around the Space Needle in SeattlePark around the Space Needle in Seattle

At night, I ate something for dinner which I forgot to take a picture of, but I think it was a hamburguer or something like that.

Around 11:30 PM I looked down to the street and noticed there were people walking around. I had heard Seattle was a very safe city, so at midnight I went out for a walk around the block.

Downtown Seattle at nightDowntown Seattle at night

Day 4 – June 18

Saturday was my last day in Seattle and I was kind of sad I had to leave. I had had an awesome time there and wished I could stay more.

My flight to Atlanta was scheduled to 11:40 AM, so I had breakfast and left. My last breakfast there was an “English Club Sandwich”, or something like that. I also had two cups of Seattle’s Best Coffee (a local brand of coffee).

June 18 Breakfast @ Grand Hyatt Seattle

The flight from Seattle to Atlanta was very bumpy, especially when we got closer to Atlanta. The weather was pretty bad there.

While waiting at the airport for my flight to Brasilia, I met a group of 5 people from there. I overheard their conversation and turned towards them, and then one of them asked if I was Brazilian and when I said I was, he invited me to join them. Their names were Andre, Andreya, Cicero, Daniel and Vivian. They were really nice people and being with them was a blessing in the events that followed (I’ll soon get into that). All of them were from Brasilia, but they had met each other there at the airport too (except Andre and Andreya, who are engaged to each other). They had missed the flight to Brasilia the night before and couldn’t wait to get back home.

It was an Amazing coincidence when we boarded the airplane and found out we were all sitting in the same row!

Day 5 – June 19

The trip back to Brazil had an unexpected diversion.

The flight to Brasilia was also very bumpy. As in really bumpy. We were all quite scared. It was most likely unrealted to the turbulence, but 3 or 4 hours after we had taken off, the cabin lights suddenly went on and we heard the captain announce that the aircraft’s right engine had failed and that we were doing an emergency landing in Venezuela in 50 minutes. Even though I knew a plane like the Boeing 757 can fly with only one engine, I was frightened. Well, everyone was. Fortunately there was no panic at all. We all got very apprehensive, but the flight attendants talked to us and told us everything was alright and under control.

When we finally landed at the Simon Bolivar International Airport in Maiquetia, Venezuela, there were a number of ambulances and fire trucks on the ground waiting for us. That was just standard procedure, though; their services were not really required.

The Delta Airlines 757 that had a right-engine failure on the way back to Brasilia

We had to wait around 15 hours in Venezuela until another plane from Delta Airlines got there to fly us home. Some people were really angry and/or sad, but I was cool, as well as most of the other people I was with. I spent most of the time with the people from Brasilia I had met in Atlanta, but I also got to talk with a lady from Recife and some guys from Manaus. The wait was very boring and tiresome, but I knew it was coming to an end, so there was no need to despair.

When the other plane finally arrived at around 4:30 PM, we were all happy and excited. The flight back home was smooth most of the time, with just some regular bumps along the way. I was a little apprehensive though, because I knew we were flying over the Amazon Rainforest.

We landed in Brasilia after 1 AM. Delta Airlines had rescheduled all connecting flights to the next morning, and we were taken to a hotel to spend the night. I met a nice girl from Manaus called Tatiane on the way to the hotel. She was coming back after spending 1 year studying and teaching in Chicago. We didn’t have much time to talk, though. We were all extremely tired and needed to get some sleep. I remember going to bed at almost 3 AM. I got up at 8 AM and headed back to the airport. The vans were taking a long time to pick everyone up, so I shared a cab to the airport with Tatiane. I got to see some of Brasilia, and it seems like a beautiful city. I must go there some day!

Day 6 – June 20

Not much to say about this day. I flew back to Porto Alegre and called my dad when I got home. Then I slept a little and then went to my godmother’s. It was nice seeing a beloved person after such a trip! I took a shower (the shower at my apartment was broken and a cold shower in winter after that trip wasn’t really appealing), had dinner and spent the night there.

So that was the end of a very exciting, but also very long trip. To those who might ask, I am not really afraid of flying again. I wouldn’t mind getting into a plane right now. But I think visiting Venezuela might not be on my most immediate plans ;)

Aligning text in QGraphicsTextItem

The Qt Graphics View Framework provides a rich set of resources to create applications with interactive graphics scenes that display arbitrary shapes, text and even Qt widgets. While the framework provides almost everything you need regarding interactivity, scene hierarchy management and graphics display, allowing you to concentrate on your application-specific code, some things require doing some extra work.

One of those things is setting the text alignment on QGraphicsTextItem items. Even though the class doesn’t provide a setAlignment() method, you have access to the underlying QTextDocument and QTextCursor objects that manage all the text processing and layout for the item. However, simply setting the text alignment on those objects also doesn’t get the job done.

The text in a QGraphicsTextItem is only displayed with any set alignment if the text width for the item is set. The text width determines the maximum width the text displayed by the item might have. If the text is actually larger than that width, automatic line breaks are inserted so that the text doesn’t extend past it. The text width property is also used by the framework to calculate the text position when the alignment is set to something other than left.

So how can the text width of a QGraphicsTextItem be set so that no automatic line breaks are inserted by the framework, and so that the text alignment can be set and be made to work? The answer is quite simple: just set it to the width of the item’s bounding rectangle:


Now, to align the text to the right, for example, you can use the item’s QTextCursor to merge it with a QTextBlockFormat with the alignment set to Qt::AlignRight:

QTextBlockFormat format;
QTextCursor cursor = item->textCursor();

Notice that before setting the alignment, the entire text under the cursor i.e. the text in the QGraphicsTextItem object must be selected, and aftwerwards the selection should be cleared so that the text is not displayed as selected. Failing to select all the text might result in having only part of the text aligned in the desired way.

Here’s a screenshot of a QGraphicsView displaying a scene with a right-aligned QGraphicsTextItem:

Right-aligned QGraphicsTextItem

So that was easy. Now let’s improve this.

The preceding approach is limited if you are not setting the QGraphicsTextItem’s text and alignment only once in your application. It requires you to set the text width and the text alignment every time the text content changes.

In the remainder of this post I will demonstrate how to create a subclass of QGraphicsTextItem with a setAlignment() method for setting the text alignment and that automatically updates the text width of the item whenever a change in its contents occurs. Also, this subclass will have the interesting characteristic of growing or shriking to the left when the text is right-aligned, thus anchoring it to its top-right corner, which might make sense in some applications.

Let’s start out by the class definition. We must use the Q_OBJECT macro since QGraphicsTextItem is a subclass of QObject (QGraphicsTextItem -> QGraphicsObject -> QObject) and we’re going to define a slot on the new class.

#include <QGraphicsTextItem>
class TextItem : public QGraphicsTextItem
    enum { Type = UserType + 1 };
    TextItem(QGraphicsItem* parent = 0);
    TextItem(const QString& text, QGraphicsItem* parent = 0);
    void setAlignment(Qt::Alignment alignment);
    virtual int type() const;
public slots:
    void updateGeometry(int, int, int);
    void updateGeometry();
    void init();

The constructors are quite simple: they just initialize the base object and the alignment_ attribute and invoke the private method init() to do the rest of the initialization:

TextItem::TextItem(QGraphicsItem* parent)
    : QGraphicsTextItem(parent),
TextItem::TextItem(const QString& text, QGraphicsItem* parent)
    : QGraphicsTextItem(text, parent),

The init() method is responsible for properly initializing the object. It calls updateGeometry() (which will soon be explained) to set the initial item’s text width. It also connects the QTextDocument::contentsChange() signal to the updateGeometry() slot so that the text width is recomputed after any change to the text, thus preventing automatic line breaks:

void TextItem::init()
    connect(document(), SIGNAL(contentsChange(int, int, int)),
            this, SLOT(updateGeometry(int, int, int)));

Note that the updateGeometry() slot has two different signatures: one which receives no arguments and one which receives the three int arguments from the QTextDocument::contentsChange() signal. As will be shown later, the one with three int arguments just calls the one that doesn’t take any arguments. QTextDocument has another signal called contentsChanged() that carries no arguments, but unfortunatelt is cannot be used here. This will be explained after the code to updateGeometry() is presented.

The setAlignment() method contains the code for setting the text alignment that was shown at the beginning of this post. It also stores the last set alignment in the alignment_ attribute so that the object “remembers” its last alignment:

void TextItem::setAlignment(Qt::Alignment alignment)
    alignment_ = alignment;
    QTextBlockFormat format;
    QTextCursor cursor = textCursor();

The updateGeometry() method is responsible for setting the item’s text width to a size that removes any automatic line breaks that might have been inserted after a change to the item’s contents:

void TextItem::updateGeometry(int, int, int)
void TextItem::updateGeometry()

Note that the text width is first set to -1, then to the item’s bounding rectangle’s width. Setting the item’s text width to -1 “resets” the text width, changing the item’s size so that the text is displayed without any automatic line breaks that might have been inserted to the limit imposed by the previous text width. This effectively recomputes the item’s bounding rectangle, allowing its new width to be used again to set the item’s text width.

Also note that setAlignment() is called after the new text width is set. When the text width is set to -1, any alignment that might have been set before is lost, because a text width value of -1 indicates the item has no text width value. As explained before, the text width value is required by the framework to align the text to any position other than left. Since the alignment was lost, setAlignment() is called to restore the item’s last set alignment.

Remember I said that the QTextDocument::contentsChanged() signal could not be used to directly connect it to updateGeometry()? The problem is that QTextDocument::contentsChanged() is not emitted exactly like contentsChange(). The contentsChanged() signal is also emitted when the text alignment is changed, so that would start an infinite recursion (and eventually a stack overflow would happen) in updateGeometry() because of the call to setAlignment(). It is not actually necessary to have two different signatures for updateGeometry(), but since the int arguments from the QTextDocument::contentsChange() signal are ignored, having an updateGeometry() signature which takes no arguments provides a cleaner interface for TextItem.

The Type constant and the type() method are required by the framework if item type information is necessary. That is not really relevant in the present discussion, but here’s the code for type():

int TextItem::type() const
    return Type;

Obviously, Type might be set to any other value allowed by Qt.

What about making the item grow or shrink to the left when the text is right-aligned? This requires a slight modification to updateGeometry(). The trick is to save the item’s top right position before recomputing it’s text width and then displacing its position by the difference between the new top right position and the saved one:

void TextItem::updateGeometry()
    QPointF topRightPrev = boundingRect().topRight();
    QPointF topRight = boundingRect().topRight();
    if (alignment_ & Qt::AlignRight)
        setPos(pos() + (topRightPrev - topRight));

Another change is necessary for TextItem to work properly. If it is editable i.e. its text interaction flags are set to something like Qt::TextEditorInteraction, the cursor position must be saved and restored whenever the alignment is set:

void TextItem::setAlignment(Qt::Alignment alignment)
    alignment_ = alignment;
    QTextBlockFormat format;
    QTextCursor cursor = textCursor();      // save cursor position
    int position = textCursor().position();
    cursor.setPosition(position);           // restore cursor position

This is necessary because the cursor position is moved to the end of the text when the cursor selects all the text in the item. Failing to save and restore the cursor position completely breaks the interaction when the item is editable, since setAlignment() is called on every key stroke (because QTextDocument::contentsChange() is emitted due to the change in content caused by the keystroke).

Unfortunately, I don’t know if there is a way to detect a font change on a QGraphicsTextItem. So TextItem works neatly when the text itself is changed, but if the font is changed to a larger size, automatic line breaks will be inserted by the framework because updateGeometry() will not get called in that case. Of course, you can work around that by calling updateGeometry() manually on a TextItem whenever its font is changed by the application. Another strategy would be to override setFont(), but then polymorphism will not work because setFont() is not virtual. Also, a different method like changeFont() could be added to TextItem that calls setFont() and then updateGeometry(), but that defines an interface different from QGraphicsTextItem. If you know how to make the item update itself when a font change occurs, please leave a comment!

Run time machine code generation and execution

Some Common Lisp implementations (and I believe other languages’ also, but I don’t know of any) are incremental compilers, which means they are able to read Lisp code during program execution, compile it and make it immediately available for execution, without requiring the program to be restarted.

I find that quite amazing, so I decided to try it out for myself. The following code contains a function that generates an array of opcodes for a function that returns an integer passed as the first function’s argument. After calling the function, it is possible to convert the returned pointer to a function pointer and call it.

#include <stdio.h>
#include <stdlib.h>
char* makefunction(int ret)
    char* opcodes = malloc(6);
    opcodes[0] = 0xb8;
    *((int*)(opcodes + 1)) = ret;
    opcodes[5] = 0xc3;
    return opcodes;
int main()
    char* code = makefunction(20);
    int (*f)() = (int(*)()) code;
    int a = f();
    printf("%d\n", a);
    return 0;

That should print “20” to the console.

What’s happening here? Here’s a function that returns 2 when called:

int f(void)
    return 2;

This is the output of objdump -d after compiling it:

f.o:     file format elf32-i386

Disassembly of section .text:

00000000 :
   0:	55                   	push   %ebp
   1:	89 e5                	mov    %esp,%ebp
   3:	b8 02 00 00 00       	mov    $0x2,%eax
   8:	5d                   	pop    %ebp
   9:	c3                   	ret  

The first two instructions, as well as the fourth (push, mov and pop), are stack-related code the compiler generates for all functions. So what really accomplishes the task of returning 2 is the following opcode sequence:

b8 02 00 00 00 c3

By checking this reference, I verified that b8 moves a value to the EAX register, which is commonly used to store function return values. The other 4 bytes correspond to the value that should be stored in that register. c3 is the opcode for ret, which returns from a function call (Captain Obvious, 2010).

Now let’s see what makefunction does:

  1. Allocates memory for 6 opcodes:
    char* opcodes = malloc(6);
  2. Writes the opcode for moving a value into the EAX register into the array:
    opcodes[0] = 0xb8;
  3. Writes the actual value that should be moved into EAX
  4. *((int*)(opcodes + 1)) = ret;
  5. Writes the opcode for the ret instruction
    opcodes[5] = 0xc3;
  6. Returns the array of opcodes:
    return opcodes;

Back in main, The pointer to the opcode array is converted to a function pointer of the appropriate type:

int (*f)() = (int(*)()) code;

And then called as any other function:

int a = f();

This generates a call instruction, which causes the current value of the IP register to be saved and the execution to jump to the specified address. In this case, that address corresponds to the opcode array’s address, which contains valid instructions that will be executed by the processor.

The difference here in relation to regular function call code is that the code is being fetched and executed from the data section of the program, instead of the code section. I’m almost sure that will crash on processors with the NX bit enabled, but I haven’t checked it. Anyways, that’s an extremely simple example of how it is possible to generate machine code during run time and execute it right away.

Nerd Girls

Disclaimer: this post contains my personal view on a given matter. Don’t ask me for statistical data that supports what’s written here, because I don’t have it. These are simply my own perceptions and conclusions, which might be completely mistaken.

There’s this movement called Nerd Girls, and reading their website just made me laugh.

So, they want to encourage girls to enter the “science, technology, math and engineering” fields so that they can “change their world”. That’s actually a very nice initiative, and I would be willing to support it.

But there’s a problem.

The science and engineering fields are traditionally dominated by men. I believe that might be alredy intimidating for women. However, I believe the real issue is that many men in these fields act just like the character sitting on the chair in this xkcd comic.

What’s the problem with Nerd Girls? Check out the Profiles section on their website. It does a really lousy job at trying to get women to be respected in science and engineering. The Nerd Girls website doesn’t look like one which is trying to promote the inclusion of women in specific academic/market fields. Pictures like Casey‘s bottommost one will only encourage men in science and engineering (I mean, men who have such an attitude) to continue having an idiotic attitude towards women in their fields, thus keeping them away.

So please, Nerd Girls, get serious.

Propositional logic symbols in LaTeX

Found this while doing some backups. Might be useful to someone.


Solving linker errors OpenThreads/Atomic on OSG projects on Mac OS X 10.6

I’ve just spent two days trying to figure out what was wrong with an OSG application I was not being able to build on Mac OS X 10.6. After importing all necessary OSG frameworks, I kept constantly getting linker errors saying the symbols OpenThreads::Atomic::operator--() and OpenThreads::Atomic::operator--() couldn’t be found.

It turns out it was a binary compatilbility issue. I built the 32-bit Debug Carbon configuration of OSG 2.8.3 from the Xcode project files that come in the source distribution (not the ones generated by CMake). The problem is that the Deployment Target is set to Mac OS X 10.4 in that project:


As far as I know, there’s no binary compatibility with libraries targeted at Mac OS X 10.4 or older starting with SDK 10.5. So, I was trying to build an application using the 10.6 SDK, but linking it to libraries built for Mac OS X 10.4.

Therefore, the solution was very simple (took me 2 days to find it, however). I just had to change the Deployment Target in the OSG Xcode project settings to 10.5 and rebuild it:


I first changed the Deployment Target to 10.6, but I wasn’t able to build OSG then. So I changed it to 10.5. I didn’t take the time to figure out what was wrong when targeting at 10.6, though.