C smart pointer library

hacker_compDeveloper Franklin Mathieu is working on a new library that implements smart pointers in C. His primary aim is to bring the following constructs to C:

  • unique_ptr, shared_ptr macros, and smart type attribute
  • Destructor support for cleanup
  • Custom variable metadata on allocation

Here’s an example to demonstrate how smart pointers are to be used:

#include <stdio.h>
#include <csptr/smart_ptr.h>

int main(void) {
    smart int *some_int = unique_ptr(int);
    *some_int = 1;

    printf("%p = %d\n", some_int, *some_int);

    // some_int is destroyed here
    return 0;
}

It’s possible to add a destructor or any other function while allocating a variable or an array. For example:

#include <stdio.h>
#include <csptr/smart_ptr.h>
#include <csptr/array.h>

void print_int(void *ptr, void *meta) {
    (void) meta;
    // ptr points to the current element
    // meta points to the array metadata (global to the array), if any.
     printf("%d\n", *(int*) ptr);
}

int main(void) {
    // Destructors for array types are run on every 
    // element of the array before destruction.
    smart int *ints = unique_ptr(int[10], print_int);

    // Smart arrays are length-aware
        for (size_t i = 0; i < array_length(ints); ++i) {
        ints[i] = i;
    }

    // Not initializing the array before getting out of scope
    // is undefined behavior: beware !
    return 0;
}

The library also allows you to use a different memory allocator than the usual malloc() / free(), supports automatic cleanup in case of errors, destructor macro helper etc.

The library is open source. In addition, the author has written an article to explain the techniques used.

Compilation

Run the following commands to compile the library on your system:

$ git clone https://github.com/Snaipe/c-smart-pointers.git
$ cd c-smart-pointers
$ ./autogen.sh && ./configure && make && sudo make install

On GitHub: C smart pointers

cpip: informative C/C++ pre-processing

cpip is a C/C++ pre-processor that gives you every detail of the pre-processing phase. Let’s take an example: you want to detect if there is any cyclic header file inclusion. cpip shows you a tree view of header file inclusion and you can easily detect the cycles from it. cpip is powerful and matured enough to pre-process Linux kernel source code. Features include:

  • Show as original source or translation unit
  • Include graphs
  • Conditional compilation graphs
  • Macros
  • Token count
  • Files included and count
  • Detailed graphical views

Steps to pre-process a file using cpip

  • Download the latest source from SourceForge or using Hg
    $ mkdir cpip_dir
    $ cd cpip_dir
    $ hg clone http://hg.code.sf.net/p/cpip/code .
  • Add the current directory to $PYTHONPATH
    $ export PYTHONPATH=$PWD:$PYTHONPATH
  • Make sure cpip can be imported from $PYTHONPATH
    $ python3
    Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
    [GCC 4.8.2] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import cpip
    >>> dir(cpip)
    ['CPIP_VERSION', 'ExceptionCpip', 'RELEASE_NOTES', '__all__', '__author__', '__builtins__', '__cached__', '__date__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__rights__', '__version__']
    >>> cpip.CPIP_VERSION
    (0, 9, 1)
    >>>
  • Now pre-process a file
    $ python3 CPIPMain.py /path_to_file/myfile.c
  • The output files should be generated in the following directory:
    cpip_dir/out

Webpage: cpip

pentium-builder: generate optimized code for i3/i5/i7

gcc_compGCC 4.6 has added an option to generate i3/i5/i7 processor specific machine code. The option is corei7 and it generates optimized machine code for these cores with 64-bit extensions, MMX, SSE, SSE2, SSE3, SSSE3, SSE4.1 and SSE4.2 instruction set support. Before going into the details of how to use this option with pentium-builder we will explain 3 GCC switches relevant in this context:

  • -march=cpu-type
    generate instructions for this cpu-type. Implies -mtune=cpu-type (see next). Enables all instruction subsets supported by cpu-type and the generated code might not be compatible with other CPUs.
  • -mtune=cpu-type
    Tune to cpu-type everything applicable about the generated code, except for the ABI and the set of available instructions.  While picking a specific cpu-type schedules things appropriately for that particular chip, the compiler does not generate any code that cannot run on the default machine type.
  • -mcpu=cpu-type
    Deprecated. Same as -mtune.

Laptops with i3/i5/i7 CPU are very common nowadays. If you want to optimize your local applications (or even your locally compiled kernel) you can use the corei7 option. The utility that can help you do this without tinkering with the installed gcc on your system or editing a lot of Makefiles is pentium-builder. It creates wrappers to the default installed gcc, g++ etc. To install on Ubuntu, run:

$ sudo apt-get install pentium-builder

By default gcc, g++… will behave as usual even with pentium-builder installed. To add the optimization option export the following before you start a compilation:

$ export DEBIAN_BUILDARCH=corei7

If you want to use this option always, add it to your .bashrc. It’s easy to add new switches with pentium-builder. Open and edit /usr/bin/gcc which is now a link to /usr/bin/builder-cc installed by pentium-builder. The line of interest is

"-mcpu=$ENV{DEBIAN_BUILDARCH}", "-march=$ENV{DEBIAN_BUILDARCH}"

You can add new switches to it.

CppDroid: GCC on Android

android_compThe latest Android devices are powerful enough to run a compiler. While some commercial apps available already, CppDroid is a brand new (released on Google Play today) free compiler that runs on Android to compile and execute C/C++ programs. Yes, it’s GCC on Android! CppDroid is fresh-baked, but it already has powerful features:

  • a collection of programs for newbies to start tinkering around with
  • terminal emulation to run your compiled programs
  • code complete
  • real-time diagnostics (warnings and errors) and fixes
  • file and tutorial navigator (variables, methods, etc)
  • smart syntax highlighting
  • portrait/landscape UI
  • auto indentation and auto pairing (configurable)
  • configurable code syntax highlighting (themes)
  • compile C/C++ code (no root required)
  • works offline (no internet connection required)
  • great C/C++ code examples included
  • detailed C++ tutorial and learn guide included
  • add-ons manager and auto updates
  • Dropbox support

CppDroid blog
On Google Play: CppDroid

[Courtesy: Anton Smirnov, the author of CppDroid]

Useful GCC preprocessor features

gcc_compThis might become a big list if we consider all the important features the GCC preprocessor provides, so I will just settle with the ones which I use frequently and are handy:

  • #if 0 : This is highly useful when you want to comment out huge chunks of code in a go. While the textbook recommendation prefers /* */ style comments, you can’t really make mistakes to understand where a new line starts and where it ends. However you can miss a hidden /* or */ anytime. Don’t forget to end it with a #endif.
  • #error : A 5 year old code often gets burdened with #ifdef -s. How do you figure out quickly (during compilation) whether your code is really getting compiled? Spill a #error in the modified area. If the preprocessor reaches it, it will throw an error.
  • Predefined Macros : When you enable debug logs you need information. Some of the predefined macros provide you quite handy information:
    __LINE__ : the line number of the log
    __FILE__ : name of the file where this log is
    __FUNCTION__ : the function which logged this
    __DATE__ : date of logging
    __TIME__ : time of logging
    You can use some of these in your default debug log format and it will be much easier to figure out where the code ran into or how long a lengthy algorithm took to complete.

Linux binaries, objdump, readelf

hacker_compA collection of interesting tutorials and articles to learn Linux binaries, objdump, readelf and reverse engineering.

Understanding Assembly

How to make faster

tux_compThe make tool can run jobs (commands) simultaneously instead to running them one by one. Works best on multiprocessor systems. To enable it, run:

$ make -j n

where n is the number of parallel jobs to execute. As per this analysis, the results are best when n = number of processors in the system.

This speeds up the compilation of large source code like that of the Linux kernel. As Bob has mentioned in his comment below, not all Makefiles are “job safe” and the jobs may be completed in any order. So be cautious when using the -j option.