Mittwoch, 13. Mai 2015

C/C++: data alignment in structs

What does alignment of data in structs mean? Consider the following struct:
 struct myStruct {  
      char aChar;  
      double aDouble;  
      uint32_t a32BitUInt;  
      bool aBool;  
 };  
What would you think the size of that struct is?

The C standard forbids the reordering of this struct like mentioned here and here.

Alignment means that the address of a variable starts at a memory location which is divisible by the size of the variable. So if you take a32BitUInt for example which is of type uint32_t this variable can be located at addresses which are equal to n * 4 because the size of the variable is 4 bytes.

Now what will happen in our case? The compiler will look at the variables in the struct and determine the largest size used which will be aDouble in this case. The compiler will put the struct at a memory location which is aligned to the size of the largest variable (address = n * 8, because sizeof(myStruct.aDouble) = 8).

The compiler isn't allowed to change the order of the variables in memory so aChar will have the lowest address. Lets assume the address for aChar was 0. The next possible address would be 1 but this is not aligned for double numbers so aDouble will be stored at address 8 because this address is divisable by sizeof(myStruct.aDouble) = 8.

a32BitUInt has a size of 4 bytes and the next possible address is 16 so this is an aligned address. 20 would be the next possible address and this is also aligned for bool which has a size of 1.

The size of the struct has to be a multiple of the largest variable size. So taking our example the current size would be 21 (addresses 0 .. 20). 21 (current size of struct) divided by 8 (size of aDouble) = 2,625. This would result in the compiler to add some padding so that the size would be ceil(2,625) * 8 bytes = 3 * 8 bytes = 24 bytes.

So here it is what it would look like in memory:

If printing out the values:
      myStruct myStructVar;  
      cout << "Size of char: " << sizeof(myStructVar.aChar) << endl;  
      cout << "Size of double: " << sizeof(myStructVar.aDouble) << endl;  
      cout << "Size of uint32_t: " << sizeof(myStructVar.a32BitUInt) << endl;  
      cout << "Size of bool: " << sizeof(myStructVar.aBool) << endl;  
      cout << "Size of struct: " << sizeof(myStructVar) << endl;  
      cout << "Start address of struct: " << &myStructVar << endl;  
it would look like this:
 Size of char: 1  
 Size of double: 8  
 Size of uint32_t: 4  
 Size of bool: 1  
 Size of struct: 24  
 Start address of struct: 0x7ffd147cedb0  

Dienstag, 12. Mai 2015

Qt: Setting dbus-properties and calling dbus-mehtods using QtDBus

The following examples on this page will set the "Powered" property for bluez to true for the first bluetooth adapter (hci0) found.

All examples use the following defines:
 #define BLUEZ_DBUS_SERVICE "org.bluez"  
 #define BLUEZ_DBUS_PATH "/org/bluez/hci0"  
 #define BLUEZ_DBUS_IF "org.bluez.Adapter1"  


Set a dbus property using QtDBus

   QDBusInterface ifc(  
         BLUEZ_DBUS_SERVICE,  
         BLUEZ_DBUS_PATH,  
         BLUEZ_DBUS_IF,  
         QDBusConnection::systemBus());  
   if ( ifc.isValid() ) {  
     ifc.setProperty("Powered", true);  
   }  

Calling methods with QtDBus

Example 1:
   QDBusConnection bus = QDBusConnection::systemBus();  
   if (!bus.isConnected())  
   {  
     qFatal("Cannot connect to the D-Bus session bus.");  
     return;  
   }  
   QDBusInterface dbus_iface(BLUEZ_DBUS_SERVICE,  
                BLUEZ_DBUS_PATH,  
                "org.freedesktop.DBus.Properties",  
                bus);  
   if ( dbus_iface.isValid() ) {  
     QDBusPendingReply<QVariantMap> reply = dbus_iface.asyncCall("Set",  
                                   BLUEZ_DBUS_IF,  
                                   "Powered",  
                                   QVariant::fromValue(QDBusVariant(true)));  
     reply.waitForFinished();  
   }  

Example 2:
   QDBusConnection bus = QDBusConnection::systemBus();  
   if (!bus.isConnected())  
   {  
     qFatal("Cannot connect to the D-Bus session bus.");  
     return;  
   }  
   QDBusMessage message = QDBusMessage::createMethodCall(BLUEZ_DBUS_SERVICE,  
                              BLUEZ_DBUS_PATH,  
                              "org.freedesktop.DBus.Properties",  
                              "Set");  
   QList<QVariant> arguments;  
   arguments << BLUEZ_DBUS_IF
        << "Powered"
        << QVariant::fromValue(QDBusVariant(true));  
   message.setArguments(arguments);  
   QDBusPendingReply<QVariantMap> reply = bus.asyncCall(message);  
   reply.waitForFinished();  

In case there is something not working the reply message can provide some usefull hints:
    qDebug() << reply.error().message();   

qdbusviewer

A really nice tool is the qdbusviewer which you can use to browse the dbus hierarchy:
For methods this tool will also show you types of the parameters.

Footnote

If the rfkill block bits are set for  the bluetooth devices you still have to unblock the bluetooth devices first:
$ rfkill unblock bluetooth  
At least on my system this has the side effect that the Powered property will be set to true. With the code above you can set the property to false without affecting the rfkill setting.

Donnerstag, 7. Mai 2015

Qt: Poweroff System

I'm currently working on an embedded project and wanted to have an option to poweroff the system with a keyboard shortcut. The system is using systemd as init-system.

The following two functions show how you can call the poweroff function:
 void MainWindow::poweroff()  
 {  
   QDBusConnection system = QDBusConnection::systemBus();  
   if (!system.isConnected())  
   {  
     qFatal("Cannot connect to the D-Bus session bus.");  
     return;  
   }  
   QDBusMessage message = QDBusMessage::createMethodCall("org.freedesktop.systemd1",  
                          "/org/freedesktop/systemd1",  
                          "org.freedesktop.systemd1.Manager",  
                          "PowerOff");  
   QDBusConnection::systemBus().asyncCall(message);  
 }  
 void MainWindow::poweroff_2()  
 {  
   QProcess *process = new QProcess(this);  
   QString program = "systemctl";  
   QStringList arguments("poweroff");  
   process->start(program, arguments);  
 }  
The first function will send a dbus message to systemd to poweroff the system while the second function will execute the systemctl command with poweroff as argument.

$ gdbus introspect --system --dest org.freedesktop.systemd1 --object-path /org/freedesktop/systemd1 will give you a nice overview of the available interface and methods available for systemd.

To assign a shortcut you can use the following functions (I'm calling these two functions in the constructor of my MainWindow class):
   new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_F4), this, SLOT(poweroff()));  
   new QShortcut(QKeySequence(Qt::ALT + Qt::Key_F4), this, SLOT(poweroff_2()));