Wednesday, June 23, 2021

Function pointers vs Normal calls

I was looking for mechanism to have zero overhead logging in my personal project. The first approach that struck my brain was creating a dummy function and calling it whenever logging is disabled. However I had many surprises while doing simple experiments. I am writing down here. Hope it helps you too while making decision.

Lets begin with problem. Here is usual way of implementing logging mechanism.

if (debug_flag_enabled & logger_mask)

    //emit my logging function

where logger_mask is represented as set of bits with enabled/disabled logs

There is catch here. Even if the log does not need to be emitted, there is always that "if" condition overhead for every call.

My approach was simple which was to sink the disabled logs to "do-nothing" logger function. The approach I took was to store function pointers in an array mapped to relevant logging function. Whenever the particular log level is disabled, the respective logging function would be mapped to "do-nothing" function which would ultimately be inlined by the compiler optimization (which turned out to be bad assumption).

Assuming that all logger functions are disabled, here is code with "do-nothing" approach

#include <stdio.h>

typedef void (*logging_func)();


#define DEBUG 0

#define INFO 1

#define WARN 2

#define ERR 3

#define CRIT 4

#define MAX (CRIT+1)


void null_logger()

{

    // do nothing

}

logging_func app_loggers[MAX] = {null_logger, null_logger, null_logger, null_logger, null_logger};

int main()

{

    int iteration = 1000;

    for (int i=0; i < iteration; i++)

    {

        app_loggers[DEBUG]();

        app_loggers[INFO]();

        app_loggers[WARN]();

        app_loggers[ERR]();

        app_loggers[CRIT]();

    }

}

Unfortunately, my assumptions were hit back by the surprises. I compared timing of the function pointers with normal calls and the timing results were startling :-D.

Here is code with "if" condition' approach.

int main()

{

    int iteration = 1000;

    for (int i=0; i < iteration; i++)

    {

        if (logger_mask & DEBUG)

            null_logger();


        if (logger_mask & INFO)

            null_logger();


        if (logger_mask & WARN)

            null_logger();


        if (logger_mask & ERR)

            null_logger();


        if (logger_mask & CRIT)

            null_logger();

    }

}

The timing observations for both approaches are as below for 1k iterations. First one is for function pointer approach while second is plain "if" condition approach

For 1k iterations

nanda@heramba:~/experiment/log_c_o1$ gcc -O2 logger_blog.c 

nanda@heramba:~/experiment/log_c_o1$ ./a.out 


===============

START = 2778 - 241274892

END   = 2778 - 241286144


===============


===============

START = 2778 - 241286213

END   = 2778 - 241286283


===============


With function pointer: 11252ns

With direct call: 70ns


For 10k iterations


nanda@heramba:~/experiment/log_c_o1$ gcc -O2 logger_blog.c 

nanda@heramba:~/experiment/log_c_o1$ ./a.out 


===============

START = 2850 - 781701427

END   = 2850 - 781759262


===============


===============

START = 2850 - 781759300

END   = 2850 - 781759326


===============

With function pointer: 57835ns

With direct call: 26ns


Do you see the vast difference of latency provided by function pointers? The one with "if" condition remains relatively constant for 10k iteration also but the assumed O(1) function pointer approach increased the latency :-)

Rather than improving, the situation aggravated. Both of the approach call the same null_logger. One via stored function pointers and other via direct calls with "if" condition. Note also that this code was compiled with "-O2"     

The function pointers apparently introduces lot of overhead in our code. As seen below from assembly, the function pointer has to be dereferenced and then called. Hence we have latency in this procedure. The latency becomes worst if we have multiple iterations of logging

         movq    app_loggers(%rip), %rdx

        movl    $0, %eax

        call    *%rdx

Also because I stored null_logger in array, the compiler did not optimize the null_logger function. When I removed the references of app_loggers[] array, the compiler did wonderful optimization. It was evident from generated assembly code which is stripped for brevity. There is no call to null_logger at all :-)

main:

.LFB24:

        .cfi_startproc

        leaq    time_store(%rip), %rbx

        leaq    64(%rbx), %r12

        call    clock_gettime@PLT

        leaq    48+time_store(%rip), %rsi

        movl    $1, %edi

        call    clock_gettime@PLT

Complete compliable code is in my github page:  https://github.com/nkumar85/experiments/tree/main/fn_ptr_if_direct


There are plenty of things to learn in basics which we fail to experiment. This experiment is one good example. It brings to mind a corollary "does the virtual functions in C++ also have similar overhead?"

Thursday, August 8, 2019

free()ing an invalid pointer

One of my friend asked this question. What happens if you free() an invalid pointer location? i.e. the pointer which was not returned by malloc(). I thought for a while. Few years back when I skimmed through glibc malloc code, I remember it was some kind of lookup based on pointer. After a while, I replied saying it would be a memory leak.

But wait a minute, the free() call returns nothing. While the programmer is happy about his bad code, internally there is something baking bad without his notice. When customer reports a long run memory leak issue, then the furnace erupts and developer is under intense pressure. So there should be something else free() doing. So let's try a sample program

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char ptr = (char)(malloc(100));

    ptr++;

    free(ptr);
}

And the output is...

nanda@nanda-MS-7640:/media/nanda/PERSONAL/c_code/const$ ./a.out 
free(): invalid pointer
Aborted (core dumped)

Yes the ABORT is called by glibc and the actions are performed as per the SIGABRT behaviour of the calling process. This was a fantastic learning. Now let's look at the glibc code.

if you try to free invalid pointer, this is result

if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
      || __builtin_expect (misaligned_chunk (p), 0))
    malloc_printerr ("free(): invalid pointer");

this guy calls abort

malloc_printerr (const char *str)
{
  __libc_message (do_abort, "%s\n", str);
  __builtin_unreachable ();
}

So what's the point here?

Look at the start of free() function : https://code.woboq.org/userspace/glibc/malloc/malloc.c.html#3092

In line 3109 it tries to get the metadata associated with the allocated memory

p = mem2chunk (mem);

In line 3131

ar_ptr = arena_for_chunk (p);
  _int_free (ar_ptr, p, 0);

The _int_free has this comment

/* Little security check which won't hurt performance: the
     allocator never wrapps around at the end of the address space.
     Therefore we can exclude some size values which might appear
     here by accident or by "design" from some intruder.  */

  if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
      || __builtin_expect (misaligned_chunk (p), 0))
    malloc_printerr ("free(): invalid pointer");

Probably in our case, it was misaligned chunk. There is no way ptr in actual code would have wrapped around.


Ending Note:

This is specific to glibc implementation. The man pages do not mandate specific behaviour in such a case. It just says the pointer to free() should be the one returned by malloc.

More deep dive on malloc/free code in subsequent posts.

Sunday, May 19, 2019

How does is_same works?

Sometimes I turn  inquisitive towards the type traits of modern c++. A more dig into glibc unfolds the mystery behind the implementation. So how does is_same work then?

See the below code. I have shamelessly copied libstdc++ code :-) for learning myself.

Find it here: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/type_traits

#include <iostream>

template<typename _Tp, _Tp __v>
struct integral_constant
{
    static constexpr _Tp                  value = __v;
    typedef _Tp                           value_type;
    typedef integral_constant<_Tp, __v>   type;
    constexpr operator value_type() const noexcept { return value; }
};

/// The type used as a compile-time boolean with true value.
typedef integral_constant<bool, true>     true_type;

/// The type used as a compile-time boolean with false value.
typedef integral_constant<bool, false>    false_type;

/// is_same
template<typename, typename>
    struct is_same
    : public false_type {
        is_same() { std::cout << "False Type" << std::endl;}
    };

template<typename _Tp>
    struct is_same<_Tp, _Tp>
    : public true_type
{
        is_same() { std::cout << "True Type" << std::endl;}
};

int main()
{
        is_same<int,int> test1;
        is_same<int,unsigned char> test2;
        std::cout << is_same<int,int>::value << std::endl;
        std::cout << is_same<int,unsigned char>::value << std::endl;
}


The fact is that, is_same works on template specialization! Hurray! It has O(1) complexity. So how is that being achieved?

consider is_same<int,int>

As you know that modern c++ allows template specialization for particular cases. The same thing works here as well!

is_same<> with same datatype resolves to specialized template

template<typename _Tp>
    struct is_same<_Tp, _Tp>
    : public true_type
{
        is_same() { std::cout << "True Type" << std::endl;}
};

which is inherited from true_type which itself is a struct integral_constant having value true and type bool. Note the static constexpr value which is evaluated in compile time i.e. no runtime overhead is seen. Also the weird template structure contains first argument as typename and second as value. These are somethings which even I did not knew are possible to write in this fashion.

Needless to say, is_same<> evaluating on different types is quite trivial template substitution and tracing on similar basis results in value = false.

I was scratching my head why static is required for the first member of integral_constant. I feel its due to the fact that is_same is structure and its value is constant throughout. static makes that each copy of is_same is referencing to same copy in memory for 'value' member. The other members do not consume memory anyway!

Most importantly, the output of program:

True Type
False Type
1
0

Thursday, October 11, 2018

A trivial note on Vector.erase()

Recently, I encountered a problem with Vector.erase() function. Consider the below code.

#include <vector>
#include <iostream>

struct SpookyStruct
{
    int k = 10;
    std::string blank = "blank";

    void operator=(const SpookyStruct& rhs)
    {
        k = rhs.k;
        blank = blank;
    }
};

std::vector<SpookyStruct> spookyVector =
{
    {1, "This"},
    {2, "is"},
    {3, "Disaster"},
    {4, "You"},
    {5, "Know"}
};

int main(int argc, char** argv)
{
    for (auto entry = spookyVector.begin(); entry != spookyVector.end(); ++entry)
    {
        std::cout << "Address of iterator before deletion : " << &(*entry) << std::endl;
    }

    for (auto entry = spookyVector.begin(); entry != spookyVector.end();)
    {
        if (entry->k % 2)
        {
            ++entry;
            continue;
        }

        entry = spookyVector.erase(entry);
    }

    for (auto entry = spookyVector.begin(); entry != spookyVector.end(); ++entry)
    {
        std::cout << "Address of iterator after deletion : " << &(*entry) << std::endl;
    }

    for (const auto& oddOnly : spookyVector)
    {
        std::cout << oddOnly.k << std::endl;
        std::cout << oddOnly.blank << std::endl;
        std::cout << std::endl;
    }

    std::cout << spookyVector.capacity() << std::endl;
}

What should be expected output? Let's run the program

nanda@nanda-MS-7640:/media/nanda/PERSONAL/c14_code/vec_erase$ g++ -std=c++14 SpookyVector.cpp 
nanda@nanda-MS-7640:/media/nanda/PERSONAL/c14_code/vec_erase$ ./a.out 

1
This

3
is

5
Disaster

Yes, the result is a disaster. This is not the output we are expecting. So what's wrong with the code?

void operator=(const SpookyStruct& rhs)
 {
    k = rhs.k;
    blank = blank;
}

Yes! It is a trivial bug but sometimes hard to debug if you don't know what is happening inside erase function.

What is happening during erase?

You know that one of the overloaded erase deletes the data at the given position and returns the next valid location in vector. Basically the data is not deleted but invalidated! The vector.erase invalidates the current entry and copies the following entries to the top. In the process, the object's assignment overloaded operator invoked if present. Here is catch, we must be careful to write the accurate assignment overload. Or else, the results could be absurd and hard to debug fast. Our assignment implementation is partially tainted!

Lets look at the iterator address before and after deletion.

Address of iterator before deletion : 0x55586894be70
Address of iterator before deletion : 0x55586894be98
Address of iterator before deletion : 0x55586894bec0
Address of iterator before deletion : 0x55586894bee8
Address of iterator before deletion : 0x55586894bf10

Address of iterator after deletion : 0x55586894be70
Address of iterator after deletion : 0x55586894be98
Address of iterator after deletion : 0x55586894bec0

Yes it remains same because, the trailing elements are copied to one level up. This should be simple as

copyElements(deletedElemPtr, nextElemPtr, nextElemPtr + numofElementsFromNextElementPtr);
In process of copy, the assignment operator is invoked and our assignment operator has buggy logic. So it copies the "blank" from invalidated entry than the actual entry.
The Details!
Here 2nd element is deleted and 3rd element takes second position. Hence the string value of 3rd element overridden as "is". Similarly 4th element takes 3rd position whose string becomes "Disaster" while 5th becomes fourth with string value as "You". In next iteration, 3rd element is deleted and hence 4th moves to 3rd in which case, string value becomes "Disaster" again [both the output and for coder :-) ]

What's the capacity of vector at the end of exercise?

5

Yes, its still 5. The memory is not deleted assuming that space would be filled soon! This is optimization strategy employed by the library writers.

After correcting the assignment operator, we come to end of disaster and its time to recoup!

void operator=(const SpookyStruct& rhs)
{
    k = rhs.k;
    blank = rhs.blank;
}

Here is desired output:

1
This

3
Disaster

5
Know


Hope you learned something today!

PS:

Yeah, if you have copy assignment, you need to have copy constructor as well. That's bug in standard. But its not bug here. I just left it out for brevity.

Wednesday, September 19, 2018

The delete operator rant

I have seen many instances using below code (assuming older standard before nullptr).

if (myAllocatedObject != NULL)
{
    delete  myAllocatedObject;
}

This is absolutely ridiculous. C++ standard guarantees that delete on NULL pointer is harmless and has no effect. Of-course, this is true only if object was allocated using new. It would be bad coding too if you try to deallocate memory using delete which was not constructed by new. This in fact applies to every allocator/deallocator combination.

Suppose if you use your own allocator, then the deallocator also needs to be supplied. It will be absurd if you restrict only to allocator.

Conclusively, the redundant NULL check is worthless. Also the code looks downright ugly.

How does libstdc++ behave?

While peeking  source tree, you get from del_op.cc

_GLIBCXX_WEAK_DEFINITION void
operator delete(void* ptr) _GLIBCXX_USE_NOEXCEPT
{
     std::free(ptr);
}

And std::free leads to cstdlib.h which in turn includes glibc stdlib.h and then to

void
__libc_free (void *mem)


if (mem == 0)                              /* free(0) has no effect */
    return; 

Phew! We landed and also freed safely :-)

PS: I heard few static analyzers also complain if you don't wrap the delete with NULL check. I cannot vouch for this statement as of now since there was never an instance stumbled upon.

Saturday, April 14, 2018

C++ : Tampering with the private class variables

I have lot things to write in C++/OS/Network arena. I don't feel the urge to write unless clarity is gained over the subject. Thanks for waiting! Hopefully, the mute period will be broken and more technical topics in coming days.
From past 3 weeks, I have been intensely pondering on rvalue/lvalue semantics. To large extent I could comprehend as well. In the process of learning, I accidentally wrote below code. Hey! you cannot modify private in C++ but we can trick via pointers. If you argue that C++ have references, take a look at the below code.


#include <iostream>
#include <string>

class PrivateTest
{
    public:
        PrivateTest() = default;
        std::string& getMessage() { return message; }

    private:
        std::string message = "Nanda";
};

int main()
{
    PrivateTest test;

    std::cout << test.getMessage() << std::endl;
    std::string& corrupted = test.getMessage();
    corrupted = "gotcha";
    std::cout << test.getMessage() << std::endl;
}


Let's compile and execute!

nandakumar@heramba ~ $ g++ -std=c++14 PrivateTest.cpp
nandakumar@heramba ~ $ ./a.out
Nanda
gotcha


The private is exposed :-). Perhaps, this is an example of bad/vulnerable C++ class design. The encapsulation needs to be stronger so that private access violations are not broken. The code somewhat similar to pointer version replaced with reference. Ultimately, the assembly boils down to logical address. The jargon of pointers & references only fall under compiler paradigms and has less significance at assembly level.

This is not something new, but revelation to few coders happens slower ;-)

Monday, October 10, 2016

A strange note on bash aliases

Today I encountered a strange scenario (rather common for most of programmers) while adding function in my .bashrc file. For confidentiality purpose, I have slightly modified the use-case to present the scenario. Here is what I did

First, I added alias. But it did not suite my needs wherein I wanted to append folder name to the complete path.

alias my_func="echo /home/nandakumar/funny/"

What I achieved with this alias was

nandakumar@heramba:~$ source ~/.bashrc
nandakumar@heramba:~$ my_func nanda
/home/nandakumar/funny/ nanda


My expectation was to print /home/nandakumar/funny/nanda i.e. without added space. However, aliases do not have such capability.

After scouting the digital knowledge book (aka internet), I realized my use case needed function

So I transformed alias to bash function as below

And the output:

nandakumar@heramba:~$ source ~/.bashrc
nandakumar@heramba:~$ my_func nanda
/home/nandakumar/funny/ nanda


Strange!! Output Unchanged!!! I almost pondered 20 mins wondering what went wrong. I checked syntax, the commands umpteen times. Alas! No luck :-(. Eventually I closed and re-opened shell and to my surprise, here was output

nandakumar@heramba:~$ my_func nanda
/home/nandakumar/funny/nanda


The output is clean now 8-).

Later when I re-did the experiment, alias entry was still present in bash despite wiping out from .bashrc file

nandakumar@heramba:~$ alias my_func
alias my_func='echo /home/nandakumar/funny/'

I stumbled upon one of stack-overflow query later in day and figured out that this is expected. A quote states as below from: http://stackoverflow.com/questions/7131670/make-bash-alias-that-takes-parameter

"If you are changing an alias to a function, sourceing your .bashrc will add the function but it won't unalias the old alias. Since aliases are higher precedent than functions, it will try to use the alias. You need to either close and reopen your shell, or else call unalias <name>. Perhaps I'll save someone the 5 minutes I just wasted."

Ha!! HA LOL :D. All I needed was explicit unalias to achieve what I wished for. One more important lesson learned. Hope you also gained some insight.

This may look familiar to many, but for me it's new learning.

Tuesday, April 19, 2016

Exploring Linux Kernel with Virtualbox - Part 2 - Compiling kernel and install guest additions

Continued from Part 1


I am back!

This post primarily concentrates on following aspects.

(i) Kernel compilation
(ii) Installation of guest additions
(iii) Sharing folders for kernel installation
(iv) Tips

Before starting with mainline topics, I have one more Machine Settings for boot order. Not sure, how much improvisation apparently it yields, but worth the try.

Goto Machine Settings-->System-->Motherboard-->(Uncheck Floppy option)

The irrelevance of Floppy drives in contemporary technology, inspired me to un-check such an option. However, it might be useful if you want to pamper with older systems like DOS.

Also move up Hard disk boot order above all and Optical drive as next priority.



Kernel Compilation

Once the source tar ball is extracted. You need to install libcurses to open up menuconfig.

sudo apt-get install libcurses-ocaml-dev

Once done with installation, enter the below command in extracted source directory to configure kernel.

make menuconfig

Following configurations are required for debugging kernel.

Note: * represents the option is enabled. Press Spacebar to toggle option.

Enter the Kernel Hacking sub-option and enable following. There are umpteen options for debugging but as of now these two enough for basic exploration.



(i) Enable Kernel Debugging: By default this option is enabled, if not make sure to enable


(ii) Enable Stack backrace support: This is required to dump stack trace at required code points



Few tips to fasten up kernel compilation. I will update, if I spot anymore.
  1. Disable container and namespace support: I prefer to enable it for future purpose.
  2. Disable unnecessary file system support: This can save lot of time. You do only need basic filesystem support and others required only if you wish to know the filesystem structure. Since the linux follows VFS, the flow is identical from User space except for lower layer implementation.
  3. Disable excess driver support: This requires careful attention. Many drivers such as apple device support etc.. can be easily omitted. Make sure you do not disable basic drivers such as Mouse, Keypad, USB etc..
Once done, keep pressing Exit till it returns to main menu. Then press Save to save configuration. Let the default name be retained.


The below picture confirms the saved configuration.



Now we are ready to compile! Execute below command to start compilation

make && make modules

It will require 3-4 hrs depending on hardware configuration and kernel configuration to complete the process. Sit back and listen to few uplifting music, sip a coffee, eat churmuri or watch a movie even [Kung Fu Panda 3 preferred :)].

Once completed you will get success message.


Now we have the kernel image and ready to explore.

Install the new kernel image with following commands.

sudo make modules_install (To install modules)

sudo make install (To install the new kernel bzimage)

Note: Make sure to install the modules first and then kernel image


Reboot the machine!

After reboot check if the kernel version is what you compiled.

vmguest1@heramba:~$ uname -a
Linux heramba 4.2.8-ckt3 #4 SMP Sat Apr 9 11:02:58 IST 2016 i686 athlon i686 GNU/Linux
vmguest1@heramba:~$ date
Sat Apr  9 11:24:45 IST 2016
vmguest1@heramba:~$





Hurray!! It is done.

Installing Guest Additions:

In my previous post, I preferred to defer installation of guest additions. The reason is, installation of guest additions involves compilation of kernel modules. Hence if we had done installation with vanilla build, it would have required recompilation of guest additions (since we installed our own compiled kernel). In order to mitigate the time involved, it is better to install guest additions after kernel is compiled.

Once ubuntu is booted, click on Devices --> Insert Guest Additions CD Image



You will get prompt as below and click on Run



The process involves compilation of guest modules with installed kernel and later installation.




Once done, reboot the guest OS and you will recognize the change in display rendering of guest OS. Now the guest OS display fits into your native display.

Please note that in my case guest additions were pre-installed and hence one does not see the default display rendering of VM

The guest additions are required for following purposes. This is non-exhaustive list of guest additions' usage.
  1. Native display support
  2. File sharing between guest and host OSes
  3. Clipboard data sharing
Next part will explain few tips and short debug session.

Friday, April 8, 2016

Exploring Linux Kernel with Virtualbox - Part 1 - The environment setup


Finally few experiments is about to fire with Linux Kernel. I am sharing those learning curve with a blog-post to invite readers for feedback. I have setup virtualbox to debug linux kernel and it has been fun so far. I want to make it more interesting by debugging/exploring major functionalities of linux kernel. Here is my initial start to this festival and I hope it will last long!

For all the demotivators, stop right here and read:

There are humongous online references and in form of printed text. So why is this juggling required ?

You know! experiences ingrain to brain more than reading theory. When you dont have such related work in your office, you buy those experiences by motivating yourself!


It's just beginning with exploration towards networking aspect of kernel. Hope I will come up with various other parts of linux not limited to networking.

The initial few sessions concentrate on bringing up setup and a tiny debug session.

My setup

Host: Ubuntu x86_64
Guest 1: Ubuntu i686
Guest 2: Ubuntu i686 (As of now not much in use. Primarily used to simulate network forwarding)

What you need in Host OS?

a) VirtualBox
b) VirtualboxGuestAdditions
c) Ubuntu i686 ISO (from Ubuntu site)

Install above utils with

sudo apt-get install virtualbox virtualbox-guest-additions-iso

Once installed, it is time to create virtual machine. I am not elaborating the process involved since lots of tutorials point at this procedure. Here are the steps leading to installation of guest OS.

Creating a virtual network

Create a Host only adapter Network interface under File-->Preferences-->Network.

Here I have added vboxnet1 as well but it is not required as of now.

Edit the settings (as shown in figure below) of added interface and disable the DHCP server and assign a manual address of your choice.




Choosing RAM size

I have healthy 16GB of RAM and hence chose 2GB for my VM. You can choose appropriate size that fits to your actual physical memory or choose size recommended by virtualbox.




Choosing disk space

Make sure to give at-least 24GB of disk space to accommodate guest OS. I prefer fixed size since we will not do much installation other than linux kernel. VDI image was chosen for storing VM disk. I have not experimented with other formats. If you wish to inter operate with other VMs, you can chose other formats.


  



Networking between host & guest

After VM is created, click on created VM and click on Machine Settings in Toolbar.

Note: There are two types of settings

(i) Global Settings which is applicable to all VMs
(ii) Per VM settings which refers to VM specific settings.

When I refer as "Machine Settings" it means VM specific settings.



Enable Adapter1 as NAT for connecting towards Internet.

Note: If Internet requires proxy, the proxy has to be set inside guest OS.




Enable another Host-only adapter interface and choose already created interface in Creating Virtuan Network section



Enable clipboard sharing

This is very important if you need to work with clipboard data between host & guest (copy & paste)

Goto Machine Settings-->General-->Advanced, choose "Bidirectional" for both parameters as shown below.



Enable file sharing

This enables you to share files between host & guest. To make use of this functionality, Goto Machine Settings-->Shared Folders and add a folder of your choice.



Installing OS

Boot the machine and it will guide you do browse for virtual boot disk. At that time, point to ISO file downloaded for installation. Make sure to disable downloading updates from internet.




The installation is like any other linux OS. The only recommendation from me is to have custom partitions as below.

(i) Dedicated /home partition for kernel compilation (about 14GB)
(ii) Dedicated / partition for installing new kernel (about 8GB)
(iii) Rest 2GB can be for swap

Note: The below picture is just an illustration and does not conform to the above mentioned parameters




Installing Guest Additions

Once installation is completed, first step is to Install guest additions on guest OS. But I prefer to defer this step for the moment. Why? Soon the secret will be unfolded ;).

Once the guest OS is booted, first and foremost, download the kernel source.

sudo apt-get install linux-source

This will be place /usr/src directory as compressed bz2 file.

Create a directory in /home/<user>/ say name "kernel" and copy the bz2 file to that directory. Once done extract the kernel source. Below file name is just for illustration. It could be something else in your native system.

tar -xf linux-source-4.2.0.tar.bz2


Now the system is ready for kernel game and we are ready to cheer! The sequel will be explained in subsequent blog post.

Sunday, January 17, 2016

Welcome back Ubuntu!

My prolonged tryst with Linux Mint is finally over. It has been a splendid relation with Mint but had to be discontinued due to valid reasons. The transition has been smooth too! The only thing that held me back from using Ubuntu was its Mac Look & Feel. Consequently, this time too I had installed Mint 17.3 Rosa but was disappointed with its performance. Being descendant of Ubuntu, I am not sure why it does not match up-to vanilla Ubuntu editions. The primary reason for ditching is that newer mint releases are planned with older stable releases of Ubuntu which is major hindrance to upgrading latest softwares. Newer versions of utilities I use (Darktable, KDENLIVE etc..) cannot be installed with newer Mint releases or requires lot of juggling with source repositories. One more point of highlight is that I felt Mint is not leveraging the hardware potential rightly. This was more profound after installing 17.3 which was sluggish in processing power. All these point tempted me to try ubuntu again.

The initial hurdle of installing ubuntu was undoubtedly its OSX LAF :(. I was heavily annoyed to see its desktop environment. But there is a way to get around. After installing "gnome-session-flashback" and making few settings, my desktop environment is back to legacy look. Also "unsettings" app made sure I have required icons on the desktop. The other bottleneck there is no "Hibernate" alongside other power options. User needs to manually test hibernate functionality using "pm-hibernate" and configure if the hibernation is successful. There are articles which help you to get around hibernate. One more tweak required is that we need to create templates in "Templates" directory for showing up some options in nautilus context menu. Eventually, I have faster running ubuntu with desired OS & UI settings. Hope this relation stays for a while. Not sure when will I reconcile with Mint again! Here is my new mate in picture :). It is faster, smoother and glossy too :D

Tuesday, September 1, 2015

A note on pushd and popd commands

Users of Linux shell are familiar with pushd & popd commands. But wait a minute, how does it work? How does it remember the directories which it traversed. Just a stack functionality right?
As you are aware, bash does fork+exec on the commands it runs and hence it is impossible for pushd & popd to store the directory list if spawned afresh. The solution is none other than the method used by bash for 'cd' command. Yes, the commands 'popd' & 'popd' too nestle within the bash executable ;). Of-course the concept of shared memory can pitch-in but why complicate when there is simpler solution ;)

The experiment as mentioned in my 'cd' post

heramba@heramba-MS-7640 ~ $ which pushd
heramba@heramba-MS-7640 ~ $ which ls
/bin/ls
heramba@heramba-MS-7640 ~ $ which popd

Saturday, April 18, 2015

A NULL pointer trivia

Off-late, I have been pondering on the NULL checks in 'C'. As I skimmed through programming forums, one aspect that arose was the checking of NULLness of pointer.

For ex:

char *k = NULL;

if (!k)
{
}
else
{
}

What do you think? Will it ever fall through the else block? Some say, Yes! It is possible to have NULL as a pointer which is reserved for systemic purpose (not even kernel). So the ideal way would be

if (k == NULL)
{
    //bail out
}

Moving a step ahead, we nowadays have grandeur of VMAs which means expression "!k" is always comparing with VMA rather than physical address. However, NULL is constant expression defined by compilers rather than OS by itself which means first example may sometimes mislead.

So what do you say, the first one is not right way? May not be! The C standard says NULL is integer constant expression with a value zero, and resolving to generic pointer expression. This means the first block is always safe provided the compilers follow the standards. Also note that first is quite optimized version since assembly requires to check JNZ instruction while the other (k==NULL) requires copying the address to register and comparing!

What is your opinion?

Monday, September 15, 2014

A simple read-write lock implementation - Problem 2

This is the continued analysis of simple read-write lock implementation problem. This time it is starvation of writer locks.

Let me modify the thread routines and remove the sleep() after unlock, which means that readers or writers are assumed to have no pause in between. Here are modified thread routines.

void*
thread_routine1 (void *arg)
{
    for (;;) {
        my_rwlock_read_lock(&g_rw_lock);
        printf("Grabbed read-lock -- 1\n");
        sleep(10);
        my_rwlock_read_unlock(&g_rw_lock);
    }
}

void*
thread_routine2 (void *arg)
{
    for (;;) {
        my_rwlock_read_lock(&g_rw_lock);
        printf("Grabbed read-lock -- 2\n");
        sleep(10);
        my_rwlock_read_unlock(&g_rw_lock);
    }
}


void*
thread_routine3 (void *arg)
{
    for (;;) {
        my_rwlock_write_lock(&g_rw_lock);
        printf("Grabbed write-lock -- 1\n");
        sleep(5);
        my_rwlock_write_unlock(&g_rw_lock);
    }
}

void*
thread_routine4 (void *arg)
{
    for (;;) {
        my_rwlock_write_lock(&g_rw_lock);
        printf("Grabbed write-lock -- 2\n");
        sleep(5);
        my_rwlock_write_unlock(&g_rw_lock);
    }
}


What is the output?

Grabbed read-lock -- 1
Grabbed read-lock -- 2
Grabbed read-lock -- 2
Grabbed read-lock -- 1
Grabbed read-lock -- 2
Grabbed read-lock -- 1
Grabbed read-lock -- 1
Grabbed read-lock -- 2


:). As you see the writers are severely starved! As of now, I am not still have zero thoughts to fix this issue. If you find any suitable approach please let me know in the comment box.

Wednesday, September 3, 2014

Filesplitter source in github now!

Today, I am glad to announce the availability of FileSplitter source code in github. This was lying in sourceforge for quite sometime and now I wish to enhance my github profile and uploaded the same to github :). This was written way back in 2007 (IIRC) and is written in Java. The UI design matches with that of chainsaw file splitter (check here). The UI is written using Java Swing APIs. Unfortunately, this works only with windows i.e. final output is batch file and cannot be used in Linux :(. I have enhancement plans for the same and willing to improve it in future releases. There are lots of known bugs and I wish someone could pull up more bugs to make it robust. Also the code is little bit cluttered and want to cleanse the same. For everything, I need to find sufficient time to move ahead. The second good news is that the code is available under GNU GPL license and you are free to enhance it and play with it.

Jump to the github page now!: https://github.com/nkumar85/filesplitter_java

Features
--------------
Can handle files above 4GB and split sizes above 4GB (need confirmation)
Checksum validation tool available to check if the merged file is in tact.

Planned enhancements
-------------------------------
Shell script support for Linux
Tool to merge the split files manually
cleanse cluttered code

Bugs
---------
long strings are not taken care for creating batch files
Lot more bugs which I have not documented [There are no show stoppers though ;)]

Note
--------
The code is provided under GNU GPL License and does not contain any proprietary code/materials in it. Please do not sell the tool for money. Feel free to distribute amongst anyone for free of charge. Any modifications to code has to be informed to me (email details are provided in the About dialog of filesplitter)

Enjoy using the filesplitter :)

Tuesday, August 26, 2014

Set or Unset a particular bit in an integer - A short program

Many times we need a method to set and unset a bit without having condition construct. It is easy to execute with 'if' construct. Just for fun, is it possible without having a conditional construct? Here is program I wrote

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

uint32_t
set_unset_bit (uint32_t src, uint32_t pos, bool set)
{
    return ((src & ~((uint32_t)1 << (pos-1))) | (!!set << (pos-1)));
}

int main (int argc, char **argv)
{
    uint32_t test1 = 0;
    uint32_t test2 = 0xFFFFFFFF;

    printf("%x\n", set_unset_bit(test1, 10, 1));
    printf("%x\n", set_unset_bit(test2, 11, 0));
}


This works for uint32_t types and as expected.  What was the approach? Basically you need to set the bit of interest to zero and OR with whatever option user requested for (set or unset i.e. 1 or 0). The first part "(src & ~((uint32_t)1 << (pos-1)))" forcibly sets bit of requested position 'pos' to zero while the next construct "| (!!set << (pos-1))" sets or unsets based on the requirement. Hope you enjoy the small code snippet.

Why do you think '!!set' required? Read my previous article here

Output:

nandakumar@heramba ~/setbit $ ./a.out
200
fffffbff

Final note: This works only for uint32_t however can be expanded to other types too! For uint64_t, make sure to cast '1' to uint64_t!

Sunday, August 24, 2014

A simple read-write lock implementation - Problem 1

Here I implemented a very basic read-write lock based on pthread libraries. You may be wondering as how this below code works?

void
my_rwlock_write_lock (my_rwlock_t *rw_lock)
{
    if (!rw_lock) {
        return;
    }

    pthread_mutex_lock(&rw_lock->rw_mutex);
    if (rw_lock->num_readers) {
        pthread_cond_wait(&rw_lock->rw_cond, &rw_lock->rw_mutex);
    }
}

Hell, where is the unlock? Does it not cause permanent deadlock?

If you look at the manpage of pthread_cond_wait(), the function atomically unlocks the mutex and waits on condition variable. So there is no need to worry!

Now coming to the problem. As you are aware, the previous implementation was running on continuous loop and hence readers and writers were grabbing their time-slices properly (even though not fair). Now, let me remove for-loops from all the thread routines and examine the output.

nandakumar@heramba ~/rwlock $ ./a.out
Grabbed read-lock -- 1
Grabbed read-lock -- 2
Grabbed write-lock -- 1


Voila, only one write lock gets woken up while the other is permanently waiting. What is the reason? There is no one to wake him up! pthread_cond_signal() wakes up only one thread and hence only one of the writer thread gets woken up. How to get around this problem? Simple, wake up all writer threads waiting on the lock. In that case, the writer threads will be scheduled as per scheduling policy but none of them will be blocked on condition.

The modified part of read_unlock is below.

void
my_rwlock_read_unlock (my_rwlock_t *rw_lock)
{
    if (!rw_lock) {
        return;
    }

    pthread_mutex_lock(&rw_lock->rw_mutex);
    if (rw_lock->num_readers) {
        rw_lock->num_readers--;
        if (!rw_lock->num_readers) {
            pthread_cond_broadcast(&rw_lock->rw_cond);
        }
    }
    pthread_mutex_unlock(&rw_lock->rw_mutex);
}


And here is output:

nandakumar@heramba ~/rwlock $ ./a.out
Grabbed read-lock -- 1
Grabbed read-lock -- 2
Grabbed write-lock -- 1
Grabbed write-lock -- 2


Works as expected! Another way is to signal the thread waiting on condition variable when write lock is unlocked. Here is the modifed code snippet and output. Note that conditional signal is required while unlocking final reader lock

void
my_rwlock_write_unlock (my_rwlock_t *rw_lock)
{
    if (!rw_lock) {
        return;
    }

    pthread_cond_broadcast(&rw_lock->rw_cond);
    pthread_mutex_unlock(&rw_lock->rw_mutex);
}


Output:

nandakumar@heramba ~/rwlock $ gcc my_rwlock.c -lpthread
nandakumar@heramba ~/rwlock $ ./a.out
Grabbed read-lock -- 2
Grabbed read-lock -- 1
Grabbed write-lock -- 2
Grabbed write-lock -- 1


I still feel #1 is better solution since it is reader's responsibility to wake up writing threads.

Finally here is comparison between the initial implementation and one with pthread_cond_broadcast in read_unlock()

Output with pthread_cond_signal:

Grabbed read-lock -- 1
Grabbed read-lock -- 2
Grabbed write-lock -- 1
Grabbed read-lock -- 1
Grabbed read-lock -- 2
Grabbed write-lock -- 2
Grabbed read-lock -- 1
Grabbed read-lock -- 2
Grabbed write-lock -- 1
Grabbed read-lock -- 1
Grabbed read-lock -- 2


Output with pthread_cond_broadcast:

Grabbed read-lock -- 1
Grabbed read-lock -- 2
Grabbed write-lock -- 1
Grabbed read-lock -- 2
Grabbed write-lock -- 2
Grabbed read-lock -- 1
Grabbed write-lock -- 2
Grabbed read-lock -- 2
Grabbed write-lock -- 1
Grabbed read-lock -- 1
Grabbed write-lock -- 2
Grabbed write-lock -- 1
Grabbed read-lock -- 2
Grabbed read-lock -- 1


As you see, the initial implementation does not guarantee fair chance. Also I mentioned about inherent problem above. For second, even though not in order, all of them get fair chance to access shared resource. Also second implementation confirms that no regression is introduced by change!

There may be far better solutions to circumvent the problem. The comment box is always in your service to help me :)

Hope you enjoyed the sequel. By the way, there are still more problems. Stay tuned for further analysis!

Thursday, August 21, 2014

A simple read-write lock implementation

Here is a simple read-write lock I implemented in quick succession as just to understand how pthred_rwlocks would have been implemented. I have not dug deep into the pthread code yet but believe would be having some similar mechanism. This implementation functions as per definition of read-write locks. Note that this is just very basic implementation I coded to satisfy my inquisitiveness. There are problems though with this implementation which I will be documenting further.

How does it work?

i)  The structure consists of mutex, codition variable and reader count.
ii) As soon as reader grabs the lock, the reader count is atomically incremented.
iii) Note that the lock is common for both reader and writer.
iv) If a thread wants to acquire write lock, then it first atomically checks if reader count is zero. If yes, it safely can acquire the lock
v) If there are readers pending, the write lock blocks on condition variable
vi) Once all readers are done with reading, the condition variable woken up signalling the waiting writer thread

Bugs:

If readers take same amount as writers, then writers are severely starved and may not even get a chance to hold the lock. I will simulate this in next write.


For brevity, error checks are offloaded to readers and users!

Here is the code then. Execute, test and enjoy! You are open to provide comments on improvements.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>

typedef struct my_rwlock {
    pthread_cond_t   rw_cond;
    pthread_mutex_t  rw_mutex;
    int              num_readers;
} my_rwlock_t;

#define MY_RWLOCK_INITIALIZER {PTHREAD_COND_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, 0}

my_rwlock_t g_rw_lock = MY_RWLOCK_INITIALIZER;

void
my_rwlock_init (my_rwlock_t *rw_lock)
{
    if (!rw_lock) {
        return;
    }

    memset(rw_lock, 0, sizeof(my_rwlock_t));
}

void
my_rwlock_read_lock (my_rwlock_t *rw_lock)
{
    if (!rw_lock) {
        return;
    }

    pthread_mutex_lock(&rw_lock->rw_mutex);
    rw_lock->num_readers++;
    pthread_mutex_unlock(&rw_lock->rw_mutex);
}

void
my_rwlock_read_unlock (my_rwlock_t *rw_lock)
{
    if (!rw_lock) {
        return;
    }

    pthread_mutex_lock(&rw_lock->rw_mutex);
    if (rw_lock->num_readers) {
        rw_lock->num_readers--;
        if (!rw_lock->num_readers) {
            pthread_cond_signal(&rw_lock->rw_cond);
        }
    }
    pthread_mutex_unlock(&rw_lock->rw_mutex);
}

void
my_rwlock_write_lock (my_rwlock_t *rw_lock)
{
    if (!rw_lock) {
        return;
    }

    pthread_mutex_lock(&rw_lock->rw_mutex);
    if (rw_lock->num_readers) {
        pthread_cond_wait(&rw_lock->rw_cond, &rw_lock->rw_mutex);
    }
}

void
my_rwlock_write_unlock (my_rwlock_t *rw_lock)
{
    if (!rw_lock) {
        return;
    }

    pthread_mutex_unlock(&rw_lock->rw_mutex);
}

void*
thread_routine1 (void *arg)
{
    for (;;) {
        my_rwlock_read_lock(&g_rw_lock);
        printf("Grabbed read-lock -- 1\n");
        sleep(5);
        my_rwlock_read_unlock(&g_rw_lock);
        sleep(5);
    }
}

void*
thread_routine2 (void *arg)
{
    for (;;) {
        my_rwlock_read_lock(&g_rw_lock);
        printf("Grabbed read-lock -- 2\n");
        sleep(8);
        my_rwlock_read_unlock(&g_rw_lock);
        sleep(5);
    }
}

void*
thread_routine3 (void *arg)
{
    for (;;) {
        my_rwlock_write_lock(&g_rw_lock);
        printf("Grabbed write-lock -- 1\n");
        sleep(5);
        my_rwlock_write_unlock(&g_rw_lock);
        sleep(5);
    }
}

void*
thread_routine4 (void *arg)
{
    for (;;) {
        my_rwlock_write_lock(&g_rw_lock);
        printf("Grabbed write-lock -- 2\n");
        sleep(8);
        my_rwlock_write_unlock(&g_rw_lock);
        sleep(5);
    }
}

int
main (int argc, char *argv[])
{
    pthread_t tid[4];

    pthread_create(&tid[0], NULL, thread_routine1, NULL);
    pthread_create(&tid[1], NULL, thread_routine2, NULL);
    pthread_create(&tid[2], NULL, thread_routine3, NULL);
    pthread_create(&tid[3], NULL, thread_routine4, NULL);

    for (;;) {
        sleep(10);
    }
}

Monday, August 18, 2014

The msgbuf structure in SysV message queue

Most of you who are familiar with SysV message queue must be aware of the formatting the message to following weird structure. The weirdest part is none other than the char mtext[1]. What is this unusual stuff? It is nothing but plays the role of expandable structure.

struct msgbuf {
    long mtype;       /* message type, must be > 0 */
    char mtext[1];    /* message data */
};


For example:

If you wish to send a message of 40 bytes, then one needs to create a structure with following size.

sizeof(long)+40;

Of-course, first element should be of type 'long' which represents message type.

Now, why is this weird mtext[1]. It could have been mtext[0]? Simple, SysV IPCs were introduced way long back. There was no C standard of having zero length arrays in structure. That is the sole reason behind mtext[1]. I used to scratch my head for a very long time and it has been eventually settled [hope even louses are out]. If any other reason, please leave comment in the box.

Saturday, May 3, 2014

Glibc malloc in linux

How does glibc implement malloc? I guess as many of you know, in traditional nix systems, it is implemented using brk() and sbrk() system calls. Basically these system calls adjust the heap pointer of process (or rather break pointer) to new location as per desired size. However in linux, glibc employs a different methodology in implementing malloc functions. For "x" number of bytes, the glibc allocates via brk()/sbrk() system calls while anything equal or above "x", mmap system call is used. Currently this threshold is 128k. Now what is mmap(). In the case of mmap(), the process address space is not adjusted rather the kernel allocates memory from its page cache and attaches the Virtual Memory Address to the process address space. Hence the heap segment is untouched and stack can grow freely upwards teasing heap :D.

Alright, can we have plausible example? Here it is :-). The first one is with 127k and latter is 128k. Follow the explanations after example code. Both of the code have sleep() function to be in wait state for some time. This enables me to see process maps. To see how malloc() behaves, one needs to run system call trace tool (strace) to understand the flow for different sizes.

1) 127k

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

#define BUF_SIZE (127 * 1024)

int main()
{
    char *temp = NULL;

    temp = (char*)(malloc(BUF_SIZE));
    strcpy(temp, "LINUX-TUX :-)");
    sleep(100);
}


compile with gcc and run the resulting executable with strace
>>strace ./a.out

I have stripped most of the portions especially the memory mappings of shared libraries. The actual snippet looks like

<<snip>>
brk(0)                                  = 0xb1d000
brk(0xb5d000)                           = 0xb5d000
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigaction(SIGCHLD, NULL, {SIG_DFL, [], 0}, 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
<<snip>>


As you can see malloc() implementation uses brk() system calls to increase the data segment width. Initially it passes 0 to find current data segment location and later adds 127k to inform the OS to adjust data segment to new location.

How to verify? Most unix systems list memory mapings in /proc/<pid>/maps. Lets do the same for our case. As I mentioned earlier, the sleep serves the purpose of grabbing memory map or else the proc entry of the process gets flushed out.

In one more terminal, obtain process-id of a.out

>>pgrep a.out
14565

>>cat /proc/14565/maps
00400000-00401000 r-xp 00000000 08:0a 1708078                            /home/nandakumar/a.out
00600000-00601000 r--p 00000000 08:0a 1708078                            /home/nandakumar/a.out
00601000-00602000 rw-p 00001000 08:0a 1708078                            /home/nandakumar/a.out
00b1d000-00b5d000 rw-p 00000000 00:00 0                                  [heap]
7f5fe1ca0000-7f5fe1e5d000 r-xp 00000000 08:0a 658188                     /lib/x86_64-linux-gnu/libc-2.17.so
7f5fe1e5d000-7f5fe205d000 ---p 001bd000 08:0a 658188                     /lib/x86_64-linux-gnu/libc-2.17.so
7f5fe205d000-7f5fe2061000 r--p 001bd000 08:0a 658188                     /lib/x86_64-linux-gnu/libc-2.17.so
7f5fe2061000-7f5fe2063000 rw-p 001c1000 08:0a 658188                     /lib/x86_64-linux-gnu/libc-2.17.so
7f5fe2063000-7f5fe2068000 rw-p 00000000 00:00 0
7f5fe2068000-7f5fe208b000 r-xp 00000000 08:0a 658164                     /lib/x86_64-linux-gnu/ld-2.17.so
7f5fe2268000-7f5fe226b000 rw-p 00000000 00:00 0
7f5fe2288000-7f5fe228a000 rw-p 00000000 00:00 0
7f5fe228a000-7f5fe228b000 r--p 00022000 08:0a 658164                     /lib/x86_64-linux-gnu/ld-2.17.so
7f5fe228b000-7f5fe228d000 rw-p 00023000 08:0a 658164                     /lib/x86_64-linux-gnu/ld-2.17.so
7ffffa977000-7ffffa998000 rw-p 00000000 00:00 0                          [stack]
7ffffa99d000-7ffffa99f000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]


Here we go :D. The new break pointer obtained from system call matches with proc entry [and obviously should match ;-)]. The length if you have calculate is [00b1d000-00b5d000]= 256K

Wait a minute! How come so much? That's how malloc does. It allocates more than what is required and manages later requests internally. This avoids frequent system call overheads and also fragmentation to certain extent

If you are curious to know the logic behind the calculation, please dissect sysmalloc() function in glibc/malloc/malloc.c {Home work :-)}

2) 128k (mmap). Here is next example!

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

#define BUF_SIZE (128 * 1024)

int main()
{
    char *temp = NULL;

    temp = (char*)(malloc(BUF_SIZE));
    strcpy(temp, "LINUX-TUX :-)");
    sleep(100);
}

Snipping unnecessary parts:

<<snip>>
mmap(NULL, 135168, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fbd51e67000
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigaction(SIGCHLD, NULL, {SIG_DFL, [], 0}, 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
<<snip>>


Now lets look into maps

>>pgrep a.out
15060

>>cat /proc/15060/maps
00400000-00401000 r-xp 00000000 08:0a 1708078                            /home/nandakumar/a.out
00600000-00601000 r--p 00000000 08:0a 1708078                            /home/nandakumar/a.out
00601000-00602000 rw-p 00001000 08:0a 1708078                            /home/nandakumar/a.out
7fbd518c0000-7fbd51a7d000 r-xp 00000000 08:0a 658188                     /lib/x86_64-linux-gnu/libc-2.17.so
7fbd51a7d000-7fbd51c7d000 ---p 001bd000 08:0a 658188                     /lib/x86_64-linux-gnu/libc-2.17.so
7fbd51c7d000-7fbd51c81000 r--p 001bd000 08:0a 658188                     /lib/x86_64-linux-gnu/libc-2.17.so
7fbd51c81000-7fbd51c83000 rw-p 001c1000 08:0a 658188                     /lib/x86_64-linux-gnu/libc-2.17.so
7fbd51c83000-7fbd51c88000 rw-p 00000000 00:00 0
7fbd51c88000-7fbd51cab000 r-xp 00000000 08:0a 658164                     /lib/x86_64-linux-gnu/ld-2.17.so
7fbd51e67000-7fbd51e8b000 rw-p 00000000 00:00 0
7fbd51ea8000-7fbd51eaa000 rw-p 00000000 00:00 0
7fbd51eaa000-7fbd51eab000 r--p 00022000 08:0a 658164                     /lib/x86_64-linux-gnu/ld-2.17.so
7fbd51eab000-7fbd51ead000 rw-p 00023000 08:0a 658164                     /lib/x86_64-linux-gnu/ld-2.17.so
7fff48a97000-7fff48ab8000 rw-p 00000000 00:00 0                          [stack]
7fff48bfe000-7fff48c00000 r-xp 00000000 00:00 0                          [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]


If you glance at the process maps, the address returned by mmap() 0x7fbd51e67000 is attached to process address space with size of 7fbd51e67000-7fbd51e8b000 which is 144k. The kernel for mmap returns memory which is aligned by pagesize. If you look at mmap system call, the number supplied by glibc is 128k+4k. As said earlier, it may be for some house keeping stuffs. Later kernel allocates with multiples of pagesize. The extra memory returned by kernel is zeroed out and useless which means even if you write at that location, it will be still zero (citation required). Also note that there is no heap segment now!

The memory allocation is complex matter and one needs to dwell into glibc code if you wish to know more. The mmap() system call is quite complex implementation in linux kernel :-). If you wish to know why malloc follows this mechanism, please read Linux System Programming by Robert Love which provides excellent insight on this topic.

As mentioned, memory topics are quite confusing and complicated. If you have feedback or corrections, please feel free to leave a comment. It also helps me to improve.

References:


1) Linux system programming by Robert Love

2) glibc malloc code (just peeped into)

3) If you wish, you can check linux kernel mmap code [mm/mmap.c -- SYSCALL_DEFINE6(mmap_pgoff, ...)]. To give some heads-up, the code is quite complicated and requires to have good knowledge of Linux Kernel MM subsystem