Wednesday, December 15, 2010

Sony VAIO Camera Driver for Ubuntu

After installing Ubuntu and configuring it to look like windows, one thing that was really lacking was the web cam driver, I could not do video call from Gmail. This time with little easy, I found a link which help to install the driver easily.

First check which is your camera, by typing in the command lsusb, which shows something below.
Bus 006 Device 002: ID 045e:00a4 Microsoft Corp. 
Bus 006 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 003 Device 005: ID 044e:3012 Alps Electric Co., Ltd 
Bus 003 Device 004: ID 044e:3013 Alps Electric Co., Ltd 
Bus 003 Device 003: ID 044e:3010 Alps Electric Co., Ltd Bluetooth Adapter
Bus 003 Device 002: ID 044e:3011 Alps Electric Co., Ltd 
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 05ca:1839 Ricoh Co., Ltd Visual Communication Camera VGP-VCC6 [R5U870]
The camera is from Ricoh Co. Ltd, VGP-VCC6[R5U870] 


The packages provided (both source and binary) include only the loader software and do not contain the microcode, whose copyright and license status is unclear. Instead, a simple shell script is provided that can download and install the microcode directly from the upstream repository.

Installation
========
1. sudo add-apt-repository ppa:r5u87x-loader/ppa
2. sudo apt-get update
3. sudo apt-get install r5u87x
4. sudo /usr/share/r5u87x/r5u87x-download-firmware.sh

(Step 1 only works on Ubuntu 9.10 and newer. On 8.04 you will need to add this PPA to your APT sources manually.)

Supported hardware
================
05ca:1803 Flybook V5
05ca:1810 HP Pavilion Webcam
05ca:1835 Sony Camera VGP-VCC5 (used on Sony Vaio SZ laptops)
05ca:1836 Sony Camera VGP-VCC4 (used on Sony Vaio FE laptops)
05ca:1837 Sony Camera VGP-VCC4 (used on Sony Vaio FZ laptops)
05ca:1839 Sony Camera VGP-VCC6 (used on Sony Vaio CR laptops)
05ca:183a Sony Camera VGP-VCC7 (used on Sony Vaio SZ and TZ11 laptops)
05ca:183b Sony Camera VGP-VCC8 (used on Sony Vaio FZ laptops)
05ca:183e Sony Camera VGP-VCC9 (used on Sony Vaio FZ laptops)

Hope this helps !

Monday, December 13, 2010

Make Ubuntu look like Windows 7 (Windows 7 theme for Ubuntu)

Most of my time on my laptop is going to be on Ubuntu-10.10 from now on. But I am a hard core fan of Microsoft and its Windows OS. The best ever OS you can ever have on your personal laptop at this point of time in my opinion for 100s of reasons, but whatever is the case when you want to get into learning mode, things are in favor of Linux, as its open source and you can download, modify, configure and compile your own kernel. and write your own drivers etc. 

So while I am inside Linux, I don't want to miss the familiar look of Windows 7, So I spent some time to set my Ubuntu look like Windows 7, and there is lot more you can do, but I want to keep it to the minimum and internally it should have the Linux touch to it. So here is the list of things I did, and if I add any more I will update in the Updates section.
  1. Install emerald theme manager, and download Windows 7 theme for it.
    goto synaptic theme manager, and search for emerald and install it and all dependencies. Download the theme for windows 7 from here. Open emerald theme manager and import the downloaded theme. Alt+f2 -> type in command emerald --replace
  2. Move the task bar down, and delete the other bar, which is having minimum buttons, (don't worry, you are not going to loose it forever, its configurable)
  3. Add emerald to start up when Ubuntu starts, same command as above.
  4. Goto Themes, customize, change Icons to Windows 7 set of icons, which are already present by now in the Appearance settings.
  5. Set a bright windows 7 wall paper.
  6. Press Alt + F2 -> type in gconf-editor, goto apps->nautilus->Desktop, and look for the trash_icon_visible and check the box beside, you can also add other icons to desktop like computer etc, I don't like My computer icon on my desktop !
  7. Download the task bar background image from here, and change the task bar settings to put this image as the background image.
  8. Download the Show Desktop background image, and add code for it. The code looks something like this,  You may have to install wmctl package for this.
  9. #!/bin/sh
    if wmctrl -m | grep "mode: ON"; then
    exec wmctrl -k off
    else
    exec wmctrl -k on
    fi
  10. You can change the three menu task bar with single icon start button type task bar, but removing that panel (right click - remove) then add to panel Main Menu. 
  11. You download the Windows 7 icons set from this link, and apply it by drag and dropping on the change themes dialog box.

You are done !, now your desktop should look something like this, its more of windows 7,  with a touch of Linux for the menus. I have referred to these two sites for this make over, and some more from Google! Other things explained on these blogs, I found unnecessary for me at least.


Comments are welcome !

Disable Syntax Error Check in Eclipse

Eclipse underlines when your code does not match the syntax rules, which is done in the CDT parser, for lot of reasons you end up highlighting most of your code as syntax error and its a pain to see the code in between these high lights, I wanted to disable it for god's sake! and could not find an easy menu option to do tat. After Google-ing a bit, I found it can be by un-checking these options shown in the below pictures.


Goto Windows->Preferences->General->Editors->Text Editors->Annotations->C/C++ Occurrences, and uncheck all the boxes on the right side and apply ! Hope this helps !

Sunday, December 12, 2010

Compile Device Driver for Linux in Eclipse

There is an easy way to compile device driver in Linux using eclipse, once its been setup life becomes much easy, as you don't have to switch between the editor and the command shell every time you need to change something,

Here is the screen shot of my project, Look at it carefully, all you need to add to the project are main.c and a makefile. rest are the result of compilation. makefile will only contain one line obj-m := main.o


Most of the things remain same for the simple C project as mentioned in the previous post, after creating the project, you need to change the command to build the project as,

make -C /usr/src/linux-headers-2.6.35-22-generic M=$(PWD) modules

The path given above is my linux kernel header file path, change to yours accordingly. After this, you set the build directory to the directory of your source code for device drivers. And in the behavior tab, remove the all from build command line, other wise it will crib saying could not find rule to build all !! 

Thats it, you are ready to use the Eclipse IDE for device driver development, all the best !


Compiling Linux Kernel in eclipse, and debugging using QEMU

After I have started working with this eclipse IDE, I came across an article in a blog, and found it very interesting. The fact that compiling Linux kernel is fairly easy on the terminal does not need it to be compiled somewhere else, but then the fact that once configured, if you are using eclipse as an IDE for modifying and browsing the source code, it would be beneficial if you can directly build from there.

The procedure is very simple in fact !

Download the latest version of kernel from kernel.org website (ftp) and extract it to where ever you want to. The latest version now is (2.6.36.2), so download the linux-2.6.36.2.tar.gz file from ftp, and copy it to you home directory (in my case prasad)

tar xzvf linux-2.6.36.2.tar.gz

Now build the kernel, after configuring, and make sure it builds fine when built from the command prompt. Now its easy to integrate this environment into eclipse, this is almost same my previous post of building a make file based c project to build in eclipse. But it just looks complicated because its kernel.

Create a new make file based C project ans select the kernel source directory to be your project directory and select other tool chain option for tool chain. Click finish, I hope you have disabled indexing and auto build. 

Now, go to project properties and update the build directory path, and build command as needed, if you are building kernel in the same directory as the source code, you don't have to change anything here, but in case out put directory is different then just update the command as make O=/build/linux-2.6-xxx and build directory to /build/linux-2.6-xxx.

If you were building for a different target other than x86, update the Makefile of linux kernel with the CROSS_COMPILE and ARCH, or you can as well give them in the make command also.

Now click build all, you can see that eclipse IDE runs the commands set and outputs of the compilations are seen on eclipse console. if there is any error, you can just double click and the corresponding source code is highlighted (this is the best part of using an IDE)

Now you are ready to connect to QEMU for debugging the kernel, locate you bzImage/zImage, (kernel binary), run the kernel in QEMU, refer to qemu manual for how to do that (!?)

for your reference, in case of x86 kernel to be run on the QEMU type in this command (I assume qemu is compiled and installed)

qemu -hda /dev/zero -kernel ~/linux-2.6.32.2/arch/i386/boot/bzImage -s -S

-s -S options make the qemu wait on the TCP connection at port 1234 for the gdb debugger to connect. 

Now in the eclipse IDE, go to Run->Debug Configurations, double click on C/C++ application, a new configuration will be created. Browse the project, and in C/C++ application field browse the vmlinux for your kernel, and set the path for it. In the debugger tab, select the gdb-server, and set the stop point to be start_kernel. In the connections tab, set it to TCP and 1234 port number, and you are ready for debugging. 

The whole thing is explained in detail in the blog post here, Thanks for the wonderful information, it was really helpful for me. I myself debugged kernel using this approach in eclipse, if anybody faced problem let me know, I am glad to help you out.

Saturday, December 11, 2010

Compile C/C++ code in eclipse using makefiles

In Linux, usually compilation is done using makefiles, run in command shell. I use to work on Linux kernel, and in such cases, I use to setup a Samba server for editing and source code browsing was done in windows. But then now I am using only one PC, which is a dual boot for windows and Ubuntu Linux, so I cannot have samba server. I was looking for a IDE in Linux, and found eclipse to be very useful.

I wasn't very familiar with the eclipse IDE and I was trying to setup the compilation using makefiles, initially I had some hiccups but could later configure it easily after generating an example C project from it and following similar methods to write the makefiles.

Here is the method to do it, so it might come handy to you in case if you are trying to use eclipse IDE for compiling C/C++ project using make files.

First create a empty C/C++ project, makefile project, and select the --other tool chain--. keep the project settings to default, as shown in the below figure. Click finish.


Once project is created, as a C file, and a 'makefile'. The makefile tells the make program about how the project should be built, I am giving here the sample make file for the simple HelloWorld.c, which you can further extend as per your use.

Wednesday, December 8, 2010

Setting up Dual boot for Windows 7 and Ubuntu 10.10

Recently I have updated to windows 7 and so, I have dumped my ubuntu (8.04), and did not install until I actually needed one for some programming purpose. Now it was time for installation. It was very straight forward last time when I did it, so did not bother to check any how to do it online, and more over installing operating system wasn't a new topic for me, and have done dual booting many time before also. 

But this time the purpose was different, I wanted to make it install on an USB with persistence, I got some link to do that, it was very promising, but when I ran from that, ubuntu was crashing very often, most of the programs were not working as expected, so then I thought of installing it on hard disk after confirming that the iso image I downloaded is good by booting it on a virtual machine.

When started with installation, there was surprise for me, the disk utility was very confusing, it was asking too many questions as to whether the partition should be from beginning or at end etc, and also where the grub boot loader should be installed etc. So I was a bit confused and installed the boot loader on the same partition on which windows boot driver was installed, and it was a mistake, and things did not work, and windows also did not boot, I could only boot ubuntu. But then I was sure that the windows installation is intact, so I put the windows disc and then repaired it, and it worked for me. But because of some updates I started getting error on windows saying that "you are victim of software counterfeit.

I gone through web pages now to find out what needs to be done for making a dual boot with Windows 7 and Ubuntu 10.0, and found that Windows 7 messes up with the grub boot loaded when windows is updated, so we need to make sure that boot loader should be installed on the same drive as boot partition of ubuntu, and then, using EasyBCD program in windows we can configure windows boot loader to boot Linux from the ubuntu installed partition.

I had problem partitioning 4 partitions for linux using their disk tool, so I did that from windows disk management tool, and then during installation selected them, and it worked fine for me. The partitions you need are boot (500mb, primary, ext4, /boot), root (3gb+, logical, ext4, /), swap (1gb), home (remaining, how much ever you wish, ext4, logical). You are done.

EasyBCD is a free software and easy to use also, download, install and configure using the easy to use user interface. Hope it helps. I have not put any screen shots as this much details seems to be enough, and if needed refer to LinuxBSDos for a detailed explanation. If you face any problem let me know. 

Run Chrome OS on your Laptop from USB

Recently I have run android on laptop, and it was meant for mobile. Google is dedicatedly developing a operating system for netbooks/notebooks. It is Chromium OS or Chrome OS. If most of the time you are spending on internet, and most used program on your PC is a browser, and you want to get online as early as possible from the time you pressed the power button then this is something you need to check it out.

You need to have a spare USB stick, with minimum of 4GB space, and a laptop which can boot from USB. People have developed the image of Chrome OS for usb and uploaded in torrent, you can download it from the torrent.


There is small utility tool provided along with the image, it is called Windows Image Writer, its free and open source, used to write data into USB. What it does it it creates partitions in your usb disk, and then writes the data on the USB, so once written you will see that 3GB space is missing from your USB stick, dont get panic, you can restore it, refer to my blog about deleting oem partition, follow similar procedure, and with the help of windows disk management tool available in computer management section of control panel you will be able to recover it.

It worked for me very well, infact the booting was not that fast, it might be little faster than the ubuntu version 8.04 which I was running, but then we can expect it to be faster once the full version is released. The best part is you can login with your gmail id, if connected to network, otherwise use chronos and password to login. You can see that wifi can be setup, it was working for me, browsing is same as on a chrome browser in linux, and nothing more, only browser in the whole operating system. Have fun trying it out !

Tuesday, December 7, 2010

How to install Android (x86) on Laptop

Everyone is talking about android, the mobile OS from the internet giant Google. It is an open operating system for mobile phones, not meant for laptops. But already people have started porting the code to x86 machine and succeeded in booting laptops. 

Keeping in mind that, it is not a full fledged porting, depending on your laptop many things may work, and it may also turn out that it may not boot as well, so the call is yours, but nothing harm in trying out. Because the method I am going to explain you is using an USB thumb drive, so in case if it does not, just format the disk.

You need to go to Andorid x86 project website and download the latest stable release iso image. You need UNetBootin software to download this install this ISO image on your thumb drive, you can download it from here.

You need to select the ISO option and give path to the .iso image you have downloaded, and make sure you select the correct device for USB, otherwise your data on hard disk will be wiped off. The example screen shot is as shown below.


Once the OK, is clicked, download will start, after the downloading to USB is complete, change the boot setting in BIOS to boot from USB and you are ready to boot Android x86, have fun. In my case, I was able to access my wifi router on my android, and it was fun browsing in Andorid. Unlike on virtual machine, the speed is really good on a laptop.


This is the screen shot of what I ran on my laptop, It's the mobile desktop scaled up. Still its a fun !

Tuesday, October 19, 2010

How to delete OEM Recovery Partition

I had Sony Vaio, installed with windows vista, and since these days the laptops dont come with the Operating system and device driver CD, they usually give a backup facility, for which they reserve a partion, and hence that space cannot be utilized.

Recently I have upgraded to Windows 7, and I dont need this partition anymore, so I wanted to remove the partition, I could have done it easily while installing windows 7, but once its installed, it cannot be directly removed from with the windows using the Computer Management program in windows. We need to used the command prompt version of Disk Partition utility.

Here is a guide to do the same,

Open the Diskpart application by either typing in "Diskpart" (without the quotation marks) into the search, or type "Diskpart.exe" into Run by pressing the Windows key + R.

Now with Diskpart open, you must enter the following command lines:
  • Type "list disk" without the quotation marks and press enter.
  • Type in "select disk 0" and press enter.
  • Then type in "list partition" and press enter.
  • Then type in "select partition x" x=the recovery partition you wish to delete, replace x with the recovery partition number and press enter.
  • Then finally type in "delete partition override" and press enter.
That should do the trick.

Monday, October 18, 2010

Windows 7, With All Drivers on Sony VAIO CR313H

Recently I have upgraded from the so called the slower version of windows (Windows Vista) to windows 7, the latest and the faster one. Everything looked nice, until I realize that my webcam is not working when I try to use Google talk on Gmail for video call. I was bit worried, thought it is not so difficult to fix it, as I knew camera driver is missing, and I did some google-ing and found that it’s not so easy to get your camera working on the laptop, mostly because it is a 2 year old laptop and Sony Vaio’s official site does not give any drivers and nowhere else also the exact drivers are available.
 
Now I did worry a bit more, but without losing hope I did some more research on the internet and found that there is driver for the web camera which many people have claimed to work on VAIO laptops. I did give a try, and amazing! It’s working!! Here is a link to download the same if you are having similar problems.
 
I was wondering, if other things on my laptops are working fine, I found that the display and the graphics drivers are missing, and Bluetooth and WLAN switch setting is missing, SD Card Reader is not working, None of the function keys are working, especially the brightness control keys, and Fn+F7 (Dual Mode + Monitor Extension). This is now a serious problem, I thought I must fix this. I called up one of my friend who works for Sony; he was on his way back to native for his sister’s engagement, so wasn’t so useful.
 
I did more search on the internet to find the display driver for my Intel graphics accelerator x3100, and after installing that the graphics did flicker few times, but worked wonders and I could see all the options I was able to see when Vista was there, I was happy, this was the first success. Here is a link if you want to download the same driver for your CR313H laptop, or with the same Intel graphics accelerator.
 
Later for the others, I started searching to make function keys working, and while searching, I found a forum on windows 7, where things which are solved are marked as SOLVED, which helped find the thread easily, and I found memory card driver, you can download it here.
 
I also got a thread, where someone had installed all the utilities needed for the functions keys to work properly. You have to download and Install the following Utilities from the SONY VAIO ftp link ftp://ftp.vaio-link.com/PUB/VAIO/ORIGINAL/ . And Note that all the below needs to be installed in the same order for it to work properly. Download the LATEST version available for each of them and install.
  1. Sony Firmware Extension Parser (SFEP) Driver
  2. Sony Shared Library
  3. Setting Utility Series
  4. Vaio Control Center (if you want it)
  5. Vaio event service
This makes all the features on my SONY VAIO laptop work. If you have any problems, feel free to write to me.

Monday, September 20, 2010

Single Linked List Example - Add/Delete

Here is the sample program, I have written to explain the singly linked list. This has three functions, one to insert to the list at the head, which is pretty easy by making the new item as the head, and other one to remove from the list when the data is found, 3rd one to insert to the tail of the list, in this case you need to traverse till the end of the list and then insert the item there.

#include <stdio.h>
#include <malloc.h>

typedef struct node_type {
    int data;
    struct node_type *next;
} node;

node *list_head = NULL;

void insert_list(node **plist_head, int data)
{
    node *item = (node *)malloc(sizeof(node));
    item->data = data;
    item->next = *plist_head;
    *plist_head = item;
}

void insert_list_tail(node **plist_head, int data)
{
    node **list_ptr = plist_head;
    node *item = (node *)malloc(sizeof(node));
    item->data = data;
    item->next = NULL;

    while(*list_ptr) 
        list_ptr = &(*list_ptr)->next;

    *list_ptr = item;
}

void show_list(node **list_head)
{
    node **list_ptr = list_head;
    while(*list_ptr)
    {    
        printf("%d\t", (*list_ptr)->data);
        list_ptr = &(*list_ptr)->next;
    } 
    printf("\n");
}

void remove_list(node **plist_head, int data)
{
    node **list_ptr = plist_head;
    while(*list_ptr)
    {
        if((*list_ptr)->data == data)
        {
            node *tmp = *list_ptr;
            *list_ptr = (*list_ptr)->next;
            free(tmp);
            break;
        }
        list_ptr = &(*list_ptr)->next;
    }
}

main()
{
    show_list(&list_head);
    insert_list(&list_head, 2);
    show_list(&list_head);
    insert_list(&list_head, 5);
    show_list(&list_head);
    insert_list(&list_head, 9);
    show_list(&list_head);
    insert_list(&list_head, 1);
    show_list(&list_head);
    remove_list(&list_head, 9);
    show_list(&list_head);
    remove_list(&list_head, 2);
    show_list(&list_head);
    insert_list_tail(&list_head, 8);
    insert_list_tail(&list_head, 12);
    show_list(&list_head);
}

Hope this will help someone who just has just started learning Linked list in C, let me know if something is not clear.

Thursday, September 16, 2010

Where is ZERO size array is used?

If you normally try to declare a zero size array, you would end of getting array, but if the same is used as the last element of a structure then it does not give any error. Infact its method or trick to use variable size array for the last element, this can be achived as shown in the below program.

#include <stdio.h>
#include <malloc.h>
#include <string.h>

typedef struct 
{
    int d;
    char name[0];
}s;

int main(void)
{
    char str[] = "prasad";
    int len;
    s *s1;
    len = strlen(str);
    s1 = (s *)malloc(sizeof(*s1) + len + 1);
    strcpy(s1->name, str);
    s1->d = 12345678;
    printf("d : %d  name : %s", s1->d, s1->name);
}

This kind of trick is normally not required, and you can program most of the things in this world with out using this, but still some people want to show that they can do something special than everybody, so they can do this trick, but when you do this you must be extra careful as you need to allocate right amount of memory for the variable size array, else you would end of corrupting others memory.

Tuesday, September 14, 2010

How to setup SDL-Library for Visual Studio Compiler

  1. On the SDL download page, get the latest version of the Windows-VC development libraries.
  2. If you want to use the SDL_mixer library (for sound and music), download the Windows-VC development libraries for SDL_mixer.
  3. Uncompress the SDL and SDL_mixer libraries to your local drive.
  4. Consolidate the SDL includes and libraries with the SDL_mixer includes and libraries, so that they're all in a single set of \include and \lib folders. It's easier this way!
  5. Launch Visual Studio .NET, but do not open a project or solution.
  6. From the Tools menu, select Options...
  7. In the tree view, click on Projects and then select VC++ Directories.
  8. In the Show directories for box, select Include files.
  9. Click the new-folder icon, and browse to the \include directory where you consolidated your SDL and SDL_mixer header files.
  10. In the Show directories for box, you now need to select Library files.
  11. Click the new-folder icon, and browse to the \lib directory where you consolidated your SDL and SDL_mixer library files.
  12. Click OK.
Your build environment is now set up, and VC++.NET will now know where to find the SDL and SDL_mixer headers and libraries. To create an SDL project, perform the following steps.
  1. Launch Visual Studio .NET and from the File menu, select New and then Project...
  2. In the tree view, expand Visual C++ Projects and select Win32.
  3. If you don't want a console window to appear when your program is executed, select Win32 Project. Otherwise, select Win32 Console Project. Give your project a name and location, then click OK.
  4. From the Project menu, select Properties... at the bottom of the menu.
  5. In the tree view, expand C/C++ and select Code Generation.
  6. Set the Runtime Library value to Multi-threaded DLL or Multi-threaded Debug DLL.
  7. We're still in the Properties dialog. In the tree view, now expand Linker and select Command Line.
  8. In the Additional Options field, enter SDL.lib SDLmain.lib and if you are using SDL_mixer, also add SDL_mixer.lib.
  9. VC++ is now set up. You may add your SDL source code to the project, and proceed as normal.
NOTES:
  • The SDL Windows FAQ states that this step is necessary because, "SDL is dynamically linked with the multi-threaded version of the Microsoft Visual C runtime."
  • If you plan on running the VC++ debugger with SDL you will have to pass the value SDL_INIT_NOPARACHUTE to SDL_Init in order for debugging to succeed!
  • When you compile your executable, you will need to copy the SDL.dll and SDL_mixer.dll files into the same folder as the EXE. If these DLLs are missing, when the program is executed you will be given an error message regarding the needed DLLs.

Monday, September 13, 2010

How to use Pointers for 2D Arrays

This is when, you want to have a two dimentional array and whos column size of fixed, but how many number of rows you need, you want to decide run time, in that case you may want to allocate memory for the whole 2D array dynamically. But the access to that array should be as simple as accessing it normally when declared using the standard syntax, i.e by using row and column numbers.

Remember that you cannot use, int **p for this purpose, or even int *p[4] for this purpose.

#include <stdio.h>
#include <malloc.h>

main()
{
    int i, j;
    int a[3][4];
    int (*p)[4];

    int size = 3;
    p = (int (*)[4])malloc(12*4);
    for(i=0; i<3; i++)
        for(j=0; j<4; j++)
        {
            p[i][j] = i+j;
            a[i][j] = p[i][j];
        }

    for(i=0; i<3; i++)
    {
        for(j=0; j<4; j++)
            printf("%d ", a[i][j]);
        printf("\n");
    }
}

Have a nice time, and enjoy programming.!

Saturday, August 28, 2010

An Overview of C++

1) What is a structured language?

The languages such as C and PASCAL are structure languages, which are characterized by their support for stand-alone subroutines, local variables, rich control constructs and their lack of reliance upon the GOTO statements.

2) What is the basic difference between the object oriented programming language and the structured pro-gramming language?

In structured programming language, the program is organized around the code, means, program is struc-tures into subroutines or functions which act on data, on the other hand the object oriented programming you define the data type, which will define how can access that data, in the sense the program is organized around data.

3) What are the characteristics of C++ or object oriented programming language?

The three main characteristics of an object oriented programming language is Encapsulation, Polymorphism and Inheritance. The class definitions explains encapsulation, the function and operator overloading explains polymorphism and the

4) What is Encapsulation in Object oriented programming language?

Encapsulation is a mechanism that binds together the code and the data it manipulates, and keep both safe from outside interference and misuse, the private data or code is accessible only within that object or class and public data or code can be accessed from outside, which gives an interface to the outside world to access the inside code and data of object.

5) What is polymorphism and what kind of polymorphisms are supported in C++?

One interface, multiple methods, in simple terms it is an attribute that allows one interface to control access to a general class of actions, the specific action selected is determined by the exact nature of the situation. Compiler will select the method appropriate for a particular situation, and programmers don’t need do it manually.

C++ supports both run time and compile time polymorphism. Compile time using function overloading and operator overloading. Run time using virtual functions.

6) What is inheritance in object oriented programming languages?

This is a concept of classification, where an objects property can be derived from another object, and it only needs to define those qualities that make it unique within its class. Example the Apple belongs to the class fruits and fruits belongs to class food etc.
7) How does bool data type is defined in C++?

There is standard Boolean data type in C++, which takes value true or false, true being 1 and false being zero automatic conversion to integer is supported, all non-zero value is treated as true and zero as false.

8) What is a class in C++

Class is a means to define an objects outline using data and code and access permissions, this is the inheri-tance is achieved in C++.

9) What is function overloading?

When you have similar tasks to be performed then you can declare functions with same name, keeping the number of parameters and /or their type different. Then the compiler will select the right function depending on the situation. This process is called function overloading. It is not only enough to keep the return type different. This is a polymorphism feature of C++. The other polymorphism feature available in C++ is operator overloading. There is run time polymorphism also using virtual functions using inheritance and derived class.

10) What are constructor and destructors?

It is very often that we need to initialize the class before we can use them, so C++ provides a way to auto-matically do it using constructor and then de-allocate any resources in the destructor. The constructor has same name as that of the class and it does not have any return type, because constructor cannot return anything. It should also be public member function of the class, because objects of that class needs to be defined in public scope. The same rules apply to the destructors also, destructors names has additional ~ at the beginning. The constructors are called when the declaration statements are executed, and destructors are called when the objects are destroyed

Wednesday, August 11, 2010

Dynamic Memory Management

1) What are the approaches for dynamic memory management?

Explicit: Explicit memory allocation and de-allocation using malloc() and free() by the programmer, this can be very efficient, but its error prone, when a programmer forgets to free the allocated memory.

Automatic: In this approach the programmer allocates the memory but the run time system takes care of claiming the un-used memory (garbage collection). This kind of method is used in languages such as Java, this can be very simple for the programmer but it can lead to slow performance, since run time system needs to decide which memory to be reclaimed.

2) How does malloc work?

Before calling main(), C runtime system asks OS for large chunk of memory. This will serve as the heap for that program. Malloc() carves out a piece of the heap records the fact that it is allocated, so subsequent calls to malloc will not use this storage. When free() is called, records the fact that piece of heap is no longer allocated, subsequent calls to malloc can use it.

3) How does malloc manage the Heap?
  • Free data is arranged in a linked list (free list)
  • Next pointer embedded in free data itself (rather than building a separate “list” structure as shown in figure
  • Each chunk is “tagged” with size (prefix or auxiliary table)
  • When malloc called,
  • Scan list for sufficiently large chunk, Chunk may need to be split
  • Returned chunk also “tagged” with size
  • When Free is called,
  • Adds chunk of data back onto the free list (at head)
  • Size available in “tag”

 
4) What are the problems associated with Malloc() and Free()

a. What if wrong address is freed?
- Consider the following code example,
p = malloc(x);
p++;
free(p);
In this case the size info will be wrong!, and hence the program will likely (later) fail in mysterious ways

b. What if same chunk is freed twice?
- Often results in free-list cycle

5) More Problems

a) Fragmentation
 • After a while, we end up with lots of small chunks
 • May have enough memory for some request, but not contiguous
 • Solutions
1) Allow heap to grow (ask OS for more memory)
2) Choose chunks wisely: best fit v. first fit
b) Slow allocation
 • Must traverse long list to find suitable chunk of memory
 • Solutions
1) Sort free list (now free is slower)
2) Multiple free lists (e.g., one for large chunks, one for small, etc.)
c) Bugs
 • Wild writes can corrupt size or next pointers
 • Solution?
1) Use auxiliary structure to record size (doesn’t actually solve problem)
2) Valgrind (provides its own implementation of malloc)

Initrd and initramfs

Initrd Creation

To create an (initially empty) initrd use the following steps:
Note: Change count to your required filesystem size. E.g. with count=8192 you will get a 8MB ramdisk.

host > dd if=/dev/zero of=/dev/ram0 bs=1k count=<count>
host > mke2fs -vm0 /dev/ram0 <count>
host > tune2fs -c 0 /dev/ram0
host > dd if=/dev/ram0 bs=1k count=<count>  | gzip -v9 > ramdisk.gz

Now, we have a (empty) gzipped ramdisk image with (extracted) size of <count>.

Filling

To fill empty ramdisk created above with all files needed for ramdisk, mount the image and fill it. Content would be e.g. BusyBox and/or other applications and/or libraries.

host > mkdir mnt
host > gunzip ramdisk.gz
host > mount -o loop ramdisk mnt/
host > ... copy stuff you want to have in ramdisk to mnt...
host > umount mnt
host > gzip -v9 ramdisk

The resulting ramdisk.gz is now ready for usage. Note its size is smaller than <count> cause of compression.

Note: Don't forget to create/copy some basic /dev/xxx nodes to ramdisk.

Note: If BusyBox or applications in ramdisk are linked dynamically, don't forget to copy dynamic libraries (*.so) to ramdisk (to correct directory) as well.

Kernel options

To make initrd work, you have to configure kernel properly:

#
# General setup
#
...
CONFIG_BLK_DEV_INITRD=y
CONFIG_INITRAMFS_SOURCE=""
...
#
# UBI - Unsorted block images
#
...
CONFIG_BLK_DEV_RAM=y
CONFIG_BLK_DEV_RAM_COUNT=1
CONFIG_BLK_DEV_RAM_SIZE=8192
CONFIG_BLK_DEV_RAM_BLOCKSIZE=1024
...
Note: The ramdisk size e.g. 8192 above has to be configured for your individual setup.

Installation

Now, you can install the ramdisk via u-boot e.g. in NOR flash. For this copy filled ramdisk created above to your tftpboot directory on host (e.g. /tftpboot/ramdisk.gz). Then start target and copy the data into RAM and flash:

UBOOT # tftp 0x87000000 ramdisk.gz
UBOOT # erase 0x2200000 +0x<filesize>
UBOOT # cp.b 0x87000000 0x2200000 0x<filesize>

Note: Replace filesize above by the value the tftp download command gives you as Bytes transferred.
Now, last step is to update kernel boot parameters and save them

UBOOT # setenv bootargs ... root=/dev/ram0 rw initrd=0x87000000,8M
UBOOT # setenv bootcmd cp.b 0x2200000 0x87000000 0x<filesize>; bootm
UBOOT # saveenv

Note: In example above with "8M" we assume that your ramdisk is 8MBytes. Adapt this to your needs.
Note: Your ramdisk filled above should have a /dev/ram0 node to make this work properly.

brw-rw---- 1 root disk 1, 0 Sep 11 1999 /dev/ram0

Now you should be able to start your kernel and it should find and mount the initrd:

Linux version 2.6.23-davinci1 ...
...
checking if image is initramfs...it isn't (no cpio magic); looks like an initrd
Freeing initrd memory: 8192K
...
RAMDISK driver initialized: 1 RAM disks of 8192K size 1024 blocksize
...
RAMDISK: Compressed image found at block 0
VFS: Mounted root (ext2 filesystem).
Freeing init memory: ...
...

Initramfs

To use initramfs a cpio archive is embedded directly into the kernel. I.e. you don't create an additional (ramdisk) image. Instead, the initial file system is directly incorporated into the kernel. With this, the kernel size increases by the file system size. It's like you embed above ramdisk directly into the kernel.

Creation

Cause initramfs is directly embedded in the the kernel, its creation is simpler. No dd & mount & gzip stuff like with ramdisk above. You simply have to fill a directory on your host with the target filesystem you like and then pass the path to this directory to the kernel build process.

Create target file system

host > mkdir target_fs
host > ... copy stuff you want to have in initramfs to target_fs...

Note: cpio system used for initramfs can't handle hard links. If you e.g. created your BusyBox using hard links, you will get a quite large initramfs cause each command is taken with its size and not as hard link. In cpio initramfs use symbolic/soft links instead.

Note: To be able to detect initramfs by kernel properly, the top level directory has to contain a program called init. This can be done by e.g. using a soft link from top level init to /bin/busybox

/init -> /bin/busybox

if you use BusyBox in your initramfs.

Kernel options

The only difference from creating an initrd is to give the kernel the path to the target file system you like to embed:

#
# General setup
#
...
CONFIG_BLK_DEV_INITRD=y
CONFIG_INITRAMFS_SOURCE="<path_to>/target_fs>"
...
#
# UBI - Unsorted block images
#
...
CONFIG_BLK_DEV_RAM=y
CONFIG_BLK_DEV_RAM_COUNT=1
CONFIG_BLK_DEV_RAM_SIZE=8192
CONFIG_BLK_DEV_RAM_BLOCKSIZE=1024
...

Then, if you compile the kernel, e.g. by make uImage, the cpio archive is generated and embedded into the kernel:

...
CHK include/linux/compile.h
GEN usr/initramfs_data.cpio.gz
AS usr/initramfs_data.o
LD usr/built-in.o
...

Installation

No special installation like above with initrd is necessary. The initramfs is already in the kernel. If you start the kernel, the initramfs is already there. Therefore, there is no root=/dev/ram0 rw initrd=0x87000000,8M bootargs option necessary. Remove this if you still have it!

initrd vs. initramfs
  1. Using initrd, kernel and initial file system are splitted. Making changes to kernel or filesystem doesn't touch the other one. The download size (e.g. while development) of one component is smaller.
  2. Creating and modifying an initramfs is easier than with initrd (unzip & mount & unmount & zip)
  3. Having one big image (kernel & initramfs) is easier to handle (e.g. download or flashing) than having two splitted images.

Tuesday, August 10, 2010

Mixed-Language Programming and External Linkage

The C++ standard provides a mechanism called linkage specification for mixing code that was written in different programming languages and was compiled by the respective compilers, in the same program. Linkage specification refers to the protocol for linking functions or procedures written in different languages. Linkage is the term used by the C++ standard to describe the accessibility of objects from one file to another or even within the same file. Three types of linkage exist:
  1. No linkage
  2. Internal linkage
  3. External linkage
Something internal to a function, in regard to its arguments, variables, and so on, always has no linkage and hence can be accessed only within the function.

Sometimes it is necessary to declare functions and other objects within a single file in a way that allows them to reference each other, but not to be accessible from outside that file. This can be done through internal linkage. Symbols with internal linkage only refer to the same object within a single source file. Prefixing the declarations with the keyword static changes the linkage of external objects from external linkage to internal linkage.

Objects that have external linkage are all considered to be located at the outermost level of the program. This is the default linkage for functions and anything declared outside of a function. All instances of a particular name with external linkage refer to the same object in the program. If two or more declarations of the same symbol have external linkage, but with incompatible types (for example, mismatch of declaration and definition), then the program may either crash or show abnormal behaviour. The rest of the article discusses one of the issues with mixed code and provides a recommended solution with external linkage.

In the real world, it is very common to use the functionality of code written in one programming language from code written in another. A trivial example is a C++ programmer relying on a standard C library (libc) for sorting a series of integers with the "quick sort" technique. It works because the C implementation takes care of the language linkage for us. But we need to take additional care if we use our own libraries written in C, from a C++ program. Otherwise the compilation may fail with link errors caused by unresolved symbols. Consider the following example:

Assume that we're writing C++ code and wish to call a C function from C++ code. Here's the code for the callee, for example, C routine:

%cat greet.h
extern char *greet();

%cat greet.c
#include "greet.h"

char *greet() {
           return ((char *) "Hello!");
}

%cc -G -o libgreet.so greet.c

Note: The extern keyword declares a variable or function and specifies that it has external linkage, i.e., its name is visible from files other than the one in which it's defined.
Let's try to call the C function greet() from a C++ program

%cat mixedcode.cpp
#include <iostream.h>
#include "greet.h"

int main() {
        char *greeting = greet();
    cout << greeting << "\n";
        return (0);
}

 
%CC -lgreet mixedcode.cpp
Undefined                       first referenced
 symbol                            in file
char*greet()                    mixedcode.o
ld: fatal: Symbol referencing errors. No output written to a.out

Though the C++ code is linked with the dynamic library that holds the implementation for greet(), libgreet.so, the linking failed with undefined symbol error. What went wrong?

The reason for the link error is that a typical C++ compiler mangles (encodes) function names to support function overloading. So, the symbol greet is changed to something else depending on the algorithm implemented in the compiler during the name mangling process. Hence the object file does not have the symbol greet anywhere in the symbol table. The symbol table of mixedcode.o confirms this. Let's have a look at the symbol tables of both libgreet.so and mixedcode.o:

%elfdump1 -s libgreet.so

Symbol Table Section:  .symtab
index    value       size     type bind oth ver shndx       name
...
[1]  0x00000000 0x00000000  FILE LOCL  D    0 ABS         libgreet.so
...
[37]  0x00000268 0x00000004  OBJT GLOB  D    0 .rodata     _lib_version
[38]  0x000102f3 0x00000000  OBJT GLOB  D    0 .data1      _edata
[39]  0x00000228 0x00000028  FUNC GLOB  D    0 .text       greet
[40]  0x0001026c 0x00000000  OBJT GLOB  D    0 .dynamic    _DYNAMIC

%elfdump -s mixedcode.o

Symbol Table Section:  .symtab
index    value       size     type bind oth ver shndx       name
[0]  0x00000000 0x00000000  NOTY LOCL  D    0 UNDEF
[1]  0x00000000 0x00000000  FILE LOCL  D    0 ABS         mixedcode.cpp
[2]  0x00000000 0x00000000  SECT LOCL  D    0 .rodata
[3]  0x00000000 0x00000000  FUNC GLOB  D    0 UNDEF     
    __1cDstd2l6Frn0ANbasic_ostream4Ccn0ALchar_traits4Cc____pkc_2_
[4]  0x00000000 0x00000000  FUNC GLOB  D    0 UNDEF       __1cFgreet6F_pc_
[5]  0x00000000 0x00000000  NOTY GLOB  D    0 UNDEF       __1cDstdEcout_
[6]  0x00000010 0x00000050  FUNC GLOB  D    0 .text       main
[7]  0x00000000 0x00000000  NOTY GLOB  D    0 ABS         __fsr_init_value

%dem2 __1cFgreet6F_pc_

__1cFgreet6F_pc_ == char*greet()

char*greet() has been mangled to __1cFgreet6F_pc_ by the C++ compiler. That's the reason why the static linker (ld) couldn't match the symbol in the object file.
Note that a C compiler that complies with the C99 standard may mangle some names. For example, on systems in which linkers cannot accept extended characters, a C compiler may encode the universal character name in forming valid external identifiers.
 
How to solve this problem?
 
The C++ standard provides a mechanism called linkage specification to enables smooth compilation of mixed code. Linkage between C++ and non-C++ code fragments is called language linkage. All function types, function names, and variable names have a default C++ language linkage. Language linkage can be achieved using the following linkage specification
 
The string-literal specifies the linkage associated with a particular function, for example, C and C++. Every C++ implementation provides for linkage to functions written in C language ("C") and linkage to C++ ("C++").
The solution to the problem under discussion is to ask the C++ compiler to use C mangling for the external functions to be called, so we can use the functionality of external C functions from C++ code, without any issues. We can accomplish this using the linkage to C. The following declaration of greet() in greet.h should resolve the problem:

extern "C" char *greet();

Because we were calling C code from a C++ program, C linkage was used for the routine greet(). The linkage directive extern "C" tells the compiler to change from C++ mangling to C mangling for the function, and to use C calling conventions while sending external information to the linker. In other words, the C linkage specification forces the C++ compiler to adopt C conventions, which are not the same as C++ conventions.

So, let's modify the header greet.h, and recompile:

%cat greet.h
#if defined __cplusplus
        extern "C" {
#endif

        char *greet();

#if defined __cplusplus
    }
#endif

%cc -G -o libgreet.so greet.c
%CC -lgreet mixedcode.cpp
%./a.out
Hello!

It works! Since the header greet.h was used in both C and C++ files, it is necessary to guard extern "C" with the C++ compiler's predefined macro _cplusplus. This is because the C compiler doesn't recognize the "C" portion of extern "C", and throws an error message for the same.
Let's have a look at the symbol table of mixedcode.o one more time
 
%CC -c -lgreet mixedcode.cpp
%elfdump -s mixedcode.o

Symbol Table Section:  .symtab
index    value       size     type bind oth ver shndx       name
[0]  0x00000000 0x00000000  NOTY LOCL  D    0 UNDEF
[1]  0x00000000 0x00000000  FILE LOCL  D    0 ABS         mixedcode.cpp
[2]  0x00000000 0x00000000  SECT LOCL  D    0 .rodata
[3]  0x00000000 0x00000000  FUNC GLOB  D    0 UNDEF     
    __1cDstd2l6Frn0ANbasic_ostream4Ccn0ALchar_traits4Cc____pkc_2_
[4]  0x00000000 0x00000000  FUNC GLOB  D    0 UNDEF       greet
[5]  0x00000000 0x00000000  NOTY GLOB  D    0 UNDEF       __1cDstdEcout_
[6]  0x00000010 0x00000050  FUNC GLOB  D    0 .text       main
[7]  0x00000000 0x00000000  NOTY GLOB  D    0 ABS         __fsr_init_value

 The function name greet was not mangled by the C++ compiler, and hence the linker could find the symbol in the object file and was able to build the executable.

Friday, August 6, 2010

Name Mangling in C++

When C++ compilers compile a C++ program, it encodes all function names and certain other identifiers to include type and scoping information. This encoding process is called name mangling. Linker uses these mangled names to ensure type-safe linkage. These mangled names appear in the object files and final executable file.

What's a symbol?

In every C++ program/library/object file, all non-static functions are represented in the binary file as symbols. These symbols are special text strings that uniquely identify a function in the program, library or object file

The Need for Name Mangling:

C language programs does not use name mangling, because in C no two non-static functions can have the same name. i.e., the symbol name is the same as the function name: the symbol of myfunc will be myfunc
Because C++ allows overloading (different functions with the same name but different number of arguments) and has many features C does not, like classes, member functions, exception specifications — it is not possible to simply use the function name as the symbol name. To solve that, C++ uses name mangling, which encodes the function name and all the necessary information (like the number and size of the arguments) into some special string which only the compiler knows about

eg.,
bpte4500s001:/sunbuild1/giri/testcases/% nm hide.o

hide.o:

[Index]   Value      Size    Type  Bind  Other Shndx   Name
[3]     |        16|      56|FUNC |GLOB |3    |2      |__1cKCRectangleKset_values6Mii_v_
[4]     |         0|       0|NOTY |GLOB |0    |ABS    |__fsr_init_value
[1]     |         0|       0|FILE |LOCL |0    |ABS    |hide.cpp
[2]     |        88|      32|FUNC |GLOB |2    |2      |main
"__1cKCRectangleKset_values6Mii_v_" is the mangled name

But this kind of scheme is undesirable for the developers because the names are difficult to read & debug

Two utilities are available with Sun Studio C/C++ compiler collection to convert the mangled names to their original source code names:
1) c++filt &
2) dem

C++filt is a filter that demangles (decodes) mangled names.
bpte4500s001% echo __1cKCRectangleKset_values6Mii_v_ | c++filt
void CRectangle::set_values(int,int)

"dem" is another utility to demangle C++ names
bpte4500s001% dem __1cKCRectangleKset_values6Mii_v_
__1cKCRectangleKset_values6Mii_v_ == void CRectangle::set_values(int,int)

Note:
C++ standard does not define how names have to be mangled; thus every compiler mangles names in its own way. Some compilers even change their name mangling algorithm between different versions. This could be a problem if the developers hack & rely on how compiler mangles the C++ symbols, as the same algorithm may not work with the next version of C++ compiler

Thursday, August 5, 2010

Interview qeustions on C/C++

1. What is the size of the structure, assume int to be 4 bytes and float to be 4 bytes.

struct {
    enum  {
        integer,
        floating
    } type;
    union {
        int a;
        float b;
    };
} t1;

Answer: The enum would take one integer (4) and other union together will take one more space of larget between two (4), so total 8 bytes.

suppose the structure delcaration is changes as below, then what would be the size?

struct {
    enum type {
        integer,
        floating
    } ;
    union {
        int a;
        float b;
    };
} t1;

Answer: This would result in compilation error, as there is no member of 'type'

2. What doe the following function do? can it be given a better name?

DT* func(DT* a, const DT* b)
{
    DT *c = a;
    while(*a++ = *b++);
    return c;
}

Answer: Assuming that DT is an integer or char, the function would copy data from b to a, untill a zero in b is obtained, zero is also copied, so it can be renamed as string copy function.

3. Is the out put of line one and two inside the loop same, or different?

int a[100][100];
for(int i = 0; i<100; i++) {
    for(int j = 0; j<100; j++) {
        printf("%d", a[i][j]);
        printf("%d", a[j][i]);
    }
}

Answer: The output would be different as they refer to different row and colum, but at the end they out put all the data in the two dimentional array.

If one needs to be prefered over the other, which one will you prefer? and why?

Answer: The first one will be faster as it has less cache miss in case of a cache enabled system compared to the second one, so in a practical system the using first line would be faster, and so it should be prefered. Theoretically if memory access does not use cache, then both will be same in terms of time taken.

4. What is function overloading? how does compiler will know which function to call?

class{ 
    void func(int a);
    void func(int a, int b);
}

Answer: Having many function definitions for the same functions with different number of arguments is called function overloading, and the compiler will decide about the functions by seeing the type and number of params passed to the function call, and decide on which function to call at compile time.

Suppose if the function is defined below with a default argument and when calling if it is not passed then how would compiler decide about function?

class{ 
    void func(int a);
    void func(int a, int b = 0);
}

Answer: Then the compiler wont be able to decide, and it will throw a compile time error.

Wednesday, August 4, 2010

First bit set in an Integer

Write a C code which returns the position of the first bit set.fot eg. for number 104(1101000) output will be 4.

You need to right shift the number untill the number becomes zero and count the number of times right shifted, then you subtract it from the size of an interger (32 bit on a 32 bit machine), you will get the answer. Here is the code for your reference.

int fbs(unsigned int num)
{
    int pos = -1;
    while(num!=0)
    {
        num <<= 1;
        pos++;
    }
    return 32 - pos;
}

Mod 16 without using arithmatic

Write a function which takes an integer value as an argument and return its mod 16 value without using these (%,+,_,/) arithmetic operations

int mod16(int a)
{
    return a>>4;
}

The 4 bits left shift will give mod 16.

what is the difference between dynamic and static linking? which is better?

A dynamic-link library (DLL) is an executable file that acts as a shared library of functions. Dynamic linking provides a way for a process to call a function that is not part of its executable code. The executable code for the function is located in a DLL, which contains one or more functions that are compiled, linked, and stored separately from the processes that use them. DLLs also facilitate the sharing of data and resources. Multiple applications can simultaneously access the contents of a single copy of a DLL in memory.

Dynamic linking differs from static linking in that it allows an executable module (either a .dll or .exe file) to include only the information needed at run time to locate the executable code for a DLL function. In static linking, the linker gets all of the referenced functions from the static link library and places it with your code into your executable.

Using dynamic linking instead of static linking offers several advantages. DLLs save memory, reduce swapping, save disk space, upgrade easier, provide after-market support, provide a mechanism to extend the MFC library classes, support multilanguage programs, and ease the creation of international versions.

In case of free software licenses also, there are provisions with LGPL, using which you dont have to share the code which are linked dynamically.

Thursday, July 15, 2010

Wipro C/C++ Interview Questions

1. What is the main difference between the C++ class and the C structure?


Answer : Both in C++ class and C structure you can have member functions and member variables, but in C++ the member functions are inside the memory allocated for the object, but in C structures they will reside out the memory allocated for the structure.  C++ the member functions are passed with 'this' pointer which pointer to the objects and rest of the things are taken care by compiler with the help of 'this' pointer. This is done by compiler during compile time, and this remains the main difference and helps in achieving the object oriented nature of C++.

2. What is the difference between the two declarations below using volatile keyword.
volatile struct reg_map {
          int reg_r1;
          int reg_r2;
};

struct reg_map {
        volatile int reg_r1;
        volatile int reg_r2;
};

Answer : In the first case it is up to the compiler to make all the variables as volatile, but in second case the compiler will always make the members as volatile, so that the purpose is served. In first case we need to check if the compiler really makes all members volatile or not, and if it does not, then it does not serve the purpose.

3. I have a union declared as below    union  ex_union {
    int a;
    short int ar[2];
   }
 
if I assign the value 0x112233 to a, what would be the values of elements ar[0] and ar[1]

Answer: Considering it to be little endian machine, the value would be, 0x2233 and 0x0011 respectively, Because in Little endian end byte will be in little address and first byte will be in high address.

4. Assume you have a function with two params a and b, and you need to return an int after processing like below.

   int compare(int a, int b)
   {
       if a>b return 1
       if b>a return -1
       if a = b, return 0
   }
you need to write this function without using if else, switch and ternary operators, how do you do it?
Answer: The purpose of this question is, to reduce the pipe line flush during branch, since here there is 50% chance of branch, we need to avoid any branch instructions.
int compare(int a, int b)
{
    int x, m, s;
    x = a - b;             // find the difference
    m = x || 1;            // if magnitude not zero make it 1
    s = (x & (1 << 31));   // get the sign
    __asm sar s, 31        // extend the sign to make it -1
    return s | m;          // or sign and magnitude
}

This can also be written like below, but it will introduce branch in the generated x86 code, check it in visual studio.
int compare (int a, int b)
{
   int x  = 0;
   (a>b) && (x = 1) || (a<b) && (x = -1);
   return x;
}

Update:
In both the above cases, the compiler will generate the the branch instruction, which is same as the if, else and thus defeating the purpose, I have an solution for it, after the subtraction find the sign of the result using below function (code) and it wont generate the branch instruction.

int IntSign(int num)
{
    int sign = (num !=0) | -(int)((unsigned int)num >> (sizeof(int)*8 - 1));
    return sign;
}


The assembly code generate for the calculation is as below (visual studio for x86)

    int sign = (num !=0) | -(int)((unsigned int)num >> (sizeof(int)*8 - 1));
0041140E  xor         eax,eax 
00411410  cmp         dword ptr [num],0 
00411414  setne       al   
00411417  mov         ecx,dword ptr [num] 
0041141A  shr         ecx,1Fh 
0041141D  neg         ecx  
0041141F  or          eax,ecx 
00411421  mov         dword ptr [sign],eax 
    return sign;
00411424  mov         eax,dword ptr [sign] 

Friday, July 9, 2010

Embedded Systems Questions for Interview

Embedded Systems Questions for Interview
 
1) What is a 'volatile' variable?
 
Volatile is a keyword to specify the compiler that this variable value can change any time, so compiler should always read its value from it's address, and not to use temporary registers to store its value and use in later part of the code.
 
 
This is specially important to handle the memory mapped registers which are mapped as some variables or structures in embedded systems, such as hardward status registers etc, whose value can be changed anytime, depending on the hardware state.
 
Examples of volatile variables are,
 
  • Hardware registers in peripherals (for example, status registers)
  • Non-automatic variables referenced within an interrupt service routine
  • Variables shared by multiple tasks in a multi-threaded application
 
Can a volatile be constant? like
volatile const a;
 
Yes it can be, it means that, it can be changes by hardware state chage, but its read only register in hardware, so code should not try to modify it.
 
Can a pointer be volatile ? Explain.
Yes, although this is not very common. An example is when an interrupt service routine modifies a pointer to a buffer
 
What's wrong with the following function?
 
int square(volatile int *ptr)
{
    return *ptr * *ptr;
}
 
This one is wicked. The intent of the code is to return the square of the value pointed to by *ptr . However, since *ptr points to a volatile parameter, the compiler will generate code that looks something like this:
 
int square(volatile int *ptr)
{
    int a,b;
    a = *ptr;
    b = *ptr;
    return a * b;
}
Because it's possible for the value of *ptr to change unexpectedly, it is possible for a and b to be different. Consequently, this code could return a number that is not a square! The correct way to code this is:
 
long square(volatile int *ptr)
{
    int a;
    a = *ptr;
    return a * a;
}
 
2) What is a 'const' variable?
 
In simple terms 'const' means 'read only'. Its value is not changed by any part of the code executed. So compiler can optimize by taking this info, and also it will give warning when user try to change the value of this variable by mistake.
 
If the candidate gets the answer correct, I'll ask him these supplemental questions:
What do the following declarations mean?
 
const int a;
int const a;
const int *a;
int * const a;
int const * a const;
 
The first two mean the same thing, namely a is a const (read-only) integer. The third means a is a pointer to a const integer (that is, the integer isn't modifiable, but the pointer is). The fourth declares a to be a const pointer to an integer (that is, the integer pointed to by a is modifiable, but the pointer is not). The final declaration declares a to be a const pointer to a const integer (that is, neither the integer pointed to by a, nor the pointer itself may be modified). If the candidate correctly answers these questions, I'll be impressed.
 
Even thouugh any program can be written without this keyword, it's good to use this, since it will help the one who is reading the program to understand the code easily by the information that the variable's value wont get changed. So using const keyword will help reducing the bugs in the code.
 
 
3) Which is the best way to write Loops?
The best way is to write count down loops and compiler can generate better machine code for it than the count up loops. In count down at loop termination, it needs to generate one instructions (SUBS), which subtracts as well as check the zero flag, but in count up case it has to add and compare with a constant, which takes two instructions.
 
 
4) What is loop unrolling? 
 
Small loops can be unrolled for higher performance, with the disadvantage of increased codesize. When a loop is unrolled, a loop counter needs to be updated less often and fewer branches are executed. If the loop iterates only a few times, it can be fully unrolled, so that the loop overhead completely disappears.
 
int CountBitOne(uint n)
{     
  int bits = 0;
    while (n != 0)
    {
        if (n & 1) bits++;
        n >> = 1;
    }
  return bits;
}
 
int CountBitOne(uint n)
{
   int bits = 0;
    while (n != 0)
    {
    if (n & 1) bits++;
    if (n & 2) bits++;
    if (n & 4) bits++;
    if (n & 8) bits++;
    n >> = 4;
    }
  return bits;
}
5) How are local and Global variables are allocated by compiler.
 
Normally, cpu registers are allocated for local variables, but if the address of that local variable is used by some code, then it wont allocate register but access from memory, thus result in un-optimized code. Gobal variables always use memory, so access is slower, so always use global only when it is absolutely neccessary.
 
6) Which is better a char, short or int type for optimization?
 
Where possible, it is best to avoid using char and short as local variables. For the types char and short the compiler needs to reduce the size of the local variable to 8 or 16 bits after each assignment. This is called sign-extending for signed variables and zeroextending for unsigned variables. It is implemented by shifting the register left by 24 or 16 bits, followed by a signed or unsigned shift right by the same amount, taking two instructions (zero-extension of an unsigned char takes one instruction).
 
These shifts can be avoided by using int and unsigned int for local variables. This is particularly important for calculations which first load data into local variables and then process the data inside the local variables. Even if data is input and output as 8- or 16-bit quantities, it is worth considering processing them as 32bit quantities
 
7) How to reduce function call overhead in ARM based systems
 
  • Try to ensure that small functions take four or fewer arguments. These will not use the stack for argument passing. It will copied into registers.
 
  • If a function needs more than four arguments, try to ensure that it does a significant amount of work, so that the cost of passing the stacked arguments is outweighed.
 
  • Pass pointers to structures instead of passing the structure itself.
 
  • Put related arguments in a structure, and pass a pointer to the structure to functions. This will reduce the number of parameters and increase readability.
 
  • Minimize the number of long long parameters, as these take two argument words. This also applies to doubles if software floating-point is enabled.
 
  • Avoid functions with a parameter that is passed partially in a register and partially on the stack (split-argument). This is not handled efficiently by the current compilers: all register arguments are pushed on the stack.
 
  • Avoid functions with a variable number of parameters. Varargs functions 
 
8) What is a pure function in ARM terminology?
 
 
Pure functions are those which return a result which depends only on their arguments. They can be thought of as mathematical functions: they always return the same result if the arguments are the same. To tell the compiler that a function is pure, use the special declaration keyword __pure.

__pure int square(int x)
{
    return x * x;
}
9) What are inline functions?
 
The ARM compilers support inline functions with the keyword __inline. This results in each call to an inline function being substituted by its body, instead of a normal call. This results in faster code, but it adversely affects code size, particularly if the inline function is large and used often.
 
Preprocessor
 
10) Using the #define statement, how would you declare a manifest constant that returns the number of seconds in a year? Disregard leap years in your answer.
  
#define SECONDS_PER_YEAR
(60 * 60 * 24 * 365)UL
 
The purpose of this question is to test the following:
 
  1. Basic knowledge of the #define syntax (for example, no semi-colon at the end, the need to parenthesize, and so on)
     
  2. An understanding that the pre-processor will evaluate constant expressions for you. Thus, it is clearer, and penalty-free, to spell out how you are calculating the number of seconds in a year, rather than actually doing the calculation yourself
     
  3. A realization that the expression will overflow an integer argument on a 16-bit machinehence the need for the L, telling the compiler to treat the variable as a Long
     
  4. As a bonus, if you modified the expression with a UL (indicating unsigned long), then you are off to a great start. And remember, first impressions count!
 
11) Write the "standard" MIN macro-that is, a macro that takes two arguments and returns the smaller of the two arguments.
 
#define MIN(a,b) ((a)<(b)?(a):(b))
 
The purpose of this question is to test the following:
 
  1. Basic knowledge of the #define directive as used in macros. This is important because until the inline operator becomes part of standard C, macros are the only portable way of generating inline code. Inline code is often necessary in embedded systems in order to achieve the required performance level
     
  2. Knowledge of the ternary conditional operator. This operator exists in C because it allows the compiler to produce more optimal code than an if-then-else sequence. Given that performance is normally an issue in embedded systems, knowledge and use of this construct is important 
      
  3. Understanding of the need to very carefully parenthesize arguments to macros
 
I also use this question to start a discussion on the side effects of macros, for example,

what happens when you write code such as:

least = MIN(*p++, b);
 
In this case, the expression is replaced by,
 
 *ptr is compared with b, then ptr is incremented to point to next integer, suppose *ptr is small, then *ptr is assigned to least, and ptr is incremented again. 
 
So the result will be integer at (ptr + sizeof(int)). 
 
 
12) What is the purpose of the preprocessor directive #error?   
 
Answer to this question does not need to be known, this is normally explained in the appendices, only nerds normally look into the appendices to see the answers for such questions. Normal folks dont be knowing the answer to this unless they happend to see this somewhere else while doing some project.
 
13) Infinite loops often arise in embedded systems. How does you code an infinite loop in C?
 
There are several solutions to this question. One is,
while(1)
{
Other is using for loop, but here things are not pretty clear as to what is going on.
for(;;)
{
}
Even though both serve the same perpose, its always better to know why you are using the first or second. So when you are asked about such questions you must answer with confidence that both are right, and just matter which way you wish to code it, anyways finally compiler would optimize and generate the same code for it. So dont ever say, I was taught to do it this way, and so never thought about the other ways.
 
There is another way of doing it, i.e. by using goto statement, goto is very basic keyword, which is more like an assembly jump instruction, if one finds more confortable with goto then possibly he works closely with assembly language, or with FORATN.
 
loop:
 ...
 ...
goto loop;
 
 
14) Data declarations
 
a) int a; 
An integer
 
b) int *a; 
A pointer to an integer
 
c) int **a; 
A pointer to a pointer to an integer
 
d) int a[10]; 
An array of 10 integers
 
e) int *a[10]; 
An array of 10 pointers to integers
 
f) int (*a)[10]; 
A pointer to an array of 10 integers
 
g) int (*a)(int); 
A pointer to a function a that takes an integer argument and returns an integer
 
h) int (*a[10])(int); 
An array of 10 pointers to functions that take an integer argument and return an integer
 
People often claim that a couple of these are the sorts of thing that one looks up in textbooks and I agree. While writing this article, I consulted textbooks to ensure the syntax was correct. However, I expect to be asked this question (or something close to it) when I'm being interviewed. Consequently, I make sure I know the answers, at least for the few hours of the interview. Candidates who don't know all the answers (or at least most of them) are simply unprepared for the interview. If they can't be prepared for the interview, what will they be prepared for? 
 
 
15) What are the uses of the keyword static?
 
This simple question is rarely answered completely. Static has three distinct uses in C:
 
  • A variable declared static within the body of a function maintains its value between function invocations

  • A variable declared static within a module, (but outside the body of a function) is accessible by all functions within that module. It is not accessible by functions within any other module. That is, it is a localized global.
      
  • Functions declared static within a module may only be called by other functions within that module. That is, the scope of the function is localized to the module within which it is declared
 
Most candidates get the first part correct. A reasonable number get the second part correct, while a pitiful number understand the third answer. This is a serious weakness in a candidate, since he obviously doesn't understand the importance and benefits of localizing the scope of both data and code.
 
 
16) Bit manipulation : Embedded systems always require the user to manipulate bits in registers or variables. Given an integer variable a, write two code fragments. The first should set bit 3 of a. The second should clear bit 3 of a. In both cases, the remaining bits should be unmodified.
 
These are the three basic responses to this question:
 
  1. No idea. The interviewee cannot have done any embedded systems work
     
  2. Use bit fields. Bit fields are right up there with trigraphs as the most brain-dead portion of C. Bit fields are inherently non-portable across compilers, and as such guarantee that your code is not reusable. The moral: never let a non-embedded person anywhere near a real piece of hardware
     
  3. Use #defines and bit masks. This is a highly portable method and is the one that should be used.
     
My optimal solution to this problem would be:
 
 
#define BIT3 (0x1 << 3)
static int a;
 
void set_bit3(void) {
    a |= BIT3;
}
 
void clear_bit3(void) {
    a &= ~BIT3;
}
 
Some people prefer to define a mask together with manifest constants for the set and clear values. This is also acceptable. The element that I'm looking for is the use of manifest constants, together with the |= and &= ~ constructs 
 
17) Accessing fixed memory locations
 
Embedded systems are often characterized by requiring the programmer to access a specific memory location. On a certain project it is required to set an integer variable at the absolute address 0x67a9 to the value 0xaa55. The compiler is a pure ANSI compiler. Write code to accomplish this task.
 
This problem tests whether you know that it is legal to typecast an integer to a pointer in order to access an absolute location. The exact syntax varies depending upon one's style. However, I would typically be looking for something like this:
 
int *ptr;
ptr = (int *)0x67a9;
*ptr = 0xaa55;
 
A more obscure approach is:
*(int * const)(0x67a9) = 0xaa55;
 
Even if your taste runs more to the second solution, I suggest the first solution when you are in an interview situation.
 
 
18) Interrupts and ISR
Interrupts are an important part of embedded systems. Consequently, many compiler vendors offer an extension to standard C to support interrupts. Typically, this new keyword is __interrupt. The following code uses __interrupt to define an interrupt service routine (ISR). Comment on the code.
 
__interrupt double compute_area (double radius)
{
    double area = PI * radius * radius;
    printf("\nArea = %f", area);
    return area;
}
 
This function has so much wrong with it, it's hard to know where to start:
 
  1. ISRs cannot return a value. If you don't understand this, you aren't hired
  2. ISRs cannot be passed parameters. See the first item for your employment prospects if you missed this
  3. On many processors/compilers, floating-point operations are not necessarily re-entrant. In some cases one needs to stack additional registers. In other cases, one simply cannot do floating point in an ISR. Furthermore, given that a general rule of thumb is that ISRs should be short and sweet, one wonders about the wisdom of doing floating-point math here
  4. In a vein similar to the third point, printf() often has problems with reentrancy and performance.
 
If you missed points three and four, I wouldn't be too hard on you. Needless to say, if you got these last two points, your employment prospects are looking better and better.
 
Code examples
19) What does the following code output and why?

void foo(void)
{
    unsigned int a = 6;
    int b = -20;
    (a+b > 6) ? puts("> 6") :puts("<= 6");
}

This question tests whether you understand the integer promotion rules in C-an area that I find is very poorly understood by many developers. Anyway, the answer is that this outputs "> 6." The reason for this is that expressions involving signed and unsigned types have all operands promoted to unsigned types. Thus comes a very large positive integer and the expression evaluates to greater than 6. This is a very important point in embedded systems where unsigned data types should be used frequently. If you get this one wrong, you are perilously close to not getting the job. 
 
 
20) Comment on the following code fragment.
unsigned int zero = 0;
unsigned int compzero = 0xFFFF;
/*1's complement of zero */

On machines where an int is not 16 bits, this will be incorrect.
 
It should be coded: unsigned int compzero = ~0;
 
This question really gets to whether the candidate understands the importance of word length on a computer. In my experience, good embedded programmers are critically aware of the underlying hardware and its limitations, whereas computer programmers tend to dismiss the hardware as a necessary annoyance.

By this stage, candidates are either completely demoralized-or they're on a roll and having a good time. If it's obvious that the candidate isn't very good, then the test is terminated at this point. However, if the candidate is doing well, then I throw in these supplemental questions.
These questions are hard, and I expect that only the very best candidates will do well on them. In posing these questions, I'm looking more at the way the candidate tackles the problems, rather than the answers. Anyway, have fun...
 

Dynamic memory allocation

21) Although not as common as in non-embedded computers, embedded systems do still dynamically allocate memory from the heap. What are the problems with dynamic memory allocation in embedded systems?
Here, I expect the user to mention memory fragmentation, problems with garbage collection, variable execution time, and so on. This topic has been covered extensively in ESP , mainly by P.J. Plauger. His explanations are far more insightful than anything I could offer here, so go and read those back issues! Having lulled the candidate into a sense of false security, I then offer up
this tidbit:
What does the following code fragment output and why?

char *ptr;
if ((ptr = (char *)malloc(0)) == NULL)
    puts("Got a valid pointer");
else
    puts("Got a null pointer");

This is a fun question. I stumbled across this only recently when a colleague of mine advertently passed a value of 0 to malloc and got back a valid pointer! That is, the above code will output "Got a valid pointer." I use this to start a discussion on whether the interviewee thinks this is the correct thing for the library routine to do. Getting the right answer here is not nearly as important as the way you approach the problem and the rationale for your decision.
 
 
22. Typedef is frequently used in C to declare synonyms for pre-existing data types. It is also possible to use the preprocessor to do something similar. For instance, consider the following code fragment:
#define dPS struct s *
typedef struct s * tPS;


The intent in both cases is to define dPS and tPS to be pointers to structure s. Which method, if any, is preferred and why?
 
This is a very subtle question, and anyone who gets it right (for the right reason) is to be congratulated or condemned ("get a life" springs to mind). The answer is the typedef is preferred. Consider the declarations:
dPS p1,p2;
tPS p3,p4;
The first expands to:
struct s * p1, p2;

which defines p1 to be a pointer to the structure and p2 to be an actual structure, which is probably not what you wanted. The second example correctly defines p3 and p4 to be pointers.

 
Obscure syntax
23. C allows some appalling constructs. Is this construct legal, and if so what does this code do?

int a = 5, b = 7, c;
c = a+++b;
This question is intended to be a lighthearted end to the quiz, as, believe it or not, this is perfectly legal syntax. The question is how does the compiler treat it? Those poor compiler writers actually debated this issue, and came up with the "maximum munch" rule, which stipulates that the compiler should bite off as big (and legal) a chunk as it can. Hence, this code is treated as:
c = a++ + b;
Thus, after this code is executed, a = 6, b = 7, and c = 12.
If you knew the answer, or guessed correctly, well done. If you didn't know the answer then I wouldn't consider this to be a problem. I find the greatest benefit of this question is that it is good for stimulating questions on coding styles, the value of code reviews, and the benefits of using lint.