Category: My Article

Writing OS and compiler independent code

My experience in programming was mixed between Linux and Windows. There are lot of standards like POSIX to standardize the api’s and there behavior across different OS and compiler environment. Here in this article I’m going to provide few tips which will be helpful for you to write OS and compiler independent code. Send me mail(yogi@yogindar.com) or add comment if you want any specific tips to be included in this section which you believe it is commonly encountered.

Few principles to be kept in mind before writing a code is

1. Reusable code
Never assume your code will be used only in Linux or Windows or for the same reason the code is written. There will be cross compiled projects which may have the same requirement. E.g:- An embedded Linux project adding a new encryption algorithm which is reused in windows based application.

2. Use standards
Use standards like ANSII C, POSIX where ever applicable as the compilers C compilation and C library will be supporting those standards by default. There will be other standards which will support more identifiers and compiler specific macros and I suggest you should be avoiding those.

3. Avoid compiler supported macros and keywords.
Most of the time you may have to compile your code based on the best compiler suited for that OS environment. You might be tempted to use those short cuts. Unless and until it is extremely important avoid those keywords and macros.

4. OS specific includes
All OS/compiler specific includes, #defines should be defined in OS specific files. This way while porting you may have to only touch this source file and not any other source files. Include platform.h in all your source code. Obviously Makefile differs.
E.g:-
Have a file named platform.h
Inside platform.h have the following code.
#ifdef WINDOWS
#include "windowsdef.h"
#endif
#ifdef LINUX
#include "linuxdef.h"
#endif

Now you will think what you will define within windowsdef.h and linuxdef.h. Next few points covers the same.

5. Segregating the includes
Identify all the #includes you need for your code. Include your OS specific #includes accordingly.
E.g:- a specific type may be defined in two different header files/path between windows and Linux.

6. Typedefining
There will be OS specific types which needs to be manually added in the other OS specific header file.
E.g:- uint16_t in Linux GCC.
I suggest a better approach for the same. Have a platform independent Typedef.
E.g:-
In windows
typedef unsigned short UINT16
In Linux
typedef uint16_t UINT16
Ones you have made the type independent start using the type independent code only.

7. Library codes
Similar to types and includes you may find differences in system and C library calls. I suggest you should add a separate platform specific library to handle the scenario. In windows have a seperate code for oswin.lib/oswin.dll where you define OS/compiler specific library calls for windows. Similarly you can do the same for Linux too with a liboslinux.a/liboslinus.so.

8. C library calls.
There will be lot of C library calls with the following behavior.
a. Same between both the OS. Until and unless you have to port to a new OS/compiler/different C library, you dont have to worry. If you encounter the same situation just add the specific prototype in #include os(newos).h and define the C library call in os(newos).lib/os(newos).so.
b. Minimal difference. May be the parameters used are swapped. Use #define in your one of the OS specific include file(oswin.h/oslinux.h) and there by call the corresponding C library call for that OS. Avoid rewriting the same C library code. If you have the code why do you want to rewrite. our time is valuable for lot of other things so never reinvent.
c. Completely different. As mentioned din point a where a new OS does not have the code understand the api parameters, return codes well and also the behaviour and rewrite the same with your OS specific library(oswin.lib/oslinux.a)

9. System calls
I suggest the same C library points applies here. So copied the same and also added a specific section more.
a. Same between both the OS. Until and unless you have to port to a new OS/compiler/different system call, you dont have to worry. If you encounter the same situation just add the specific prototype in #include os(newos).h and define the C library call in os(newos).lib/os(newos).so.
b. Minimal difference. May be the parameters used are swapped. Use #define in your one of the OS specific include file(oswin.h/oslinux.h) and there by call the corresponding C library call for that OS. Avoid rewriting the same C library system call code. If you have the code why do you want to rewrite. our time is valuable for lot of other things so never reinvent.
c. Completely different. As mentioned din point a where a new OS does not have the code understand the api parameters, return codes well and also the behaviour and rewrite the same with your OS specific library(oswin.lib/oslinux.a)
d. Very OS specific system calls. E.g:- fork(). There is no equivalent system call in windows. I suggest write wrappers and make use of the application of fork() rather than its oS specific behavior. Use it for creating a child process but with wrappers.

10. Threads, IPC and sockets
Most of them are written based on POSIX and windows and Linux will have the same implementation with same api name, different api name, different library support etc. Find out those differences and apply the above mentioned logic.

11. Wrappers/Stubs
Try using wrappers and stubs. This will help the code easy for porting and maintenance.
Wrapper is an api defined by us over the C library call(system call). Like typedef we are trying to consolidate same names for functions also there by we know what are C library calls we use and we can quickly know what are api’s to be defined by us.
Stubs is just a dummy api. Sometimes we may need those stubs because of the implementation of library calls.
E.g:- In windows socket calls are defined in a separate library and in Linux they are system calls and part of GNU C library. To use the socket libraries we need to use WSAInit() in windows for which we can define an equivalent stub in Linux and a wrapper in windows named socketinit().

12. Coding styles
I don’t have a strong opinion on using Hungarian notation or Linux kernel coding style. Use one of them but don’t mix and match.

13. Avoid using architecture specific code. One example is using asm keyword. Between 320-bit windows itself there is a difference in using assembly code inline.

14. Other common tips which is not OS specific.
a. Ensure your structures are padded correctly.
b. Take care of endianism if you are sending/receiving data to a different device/computer.
c. Avoid architecture specific code. If architecture suggests the local variables are initialized to 0 by default never rely on the same. Initialize all the local variables.
d. Use common indentation style. 1 tab = 4 spaces.
e. Avoid mix and match of new line characters. In windows it is \r\n, Linux editors it is \n and in apple editors it is \r. Use always one environment for the same. Preferably windows.
f. Use the source code management system property to take care of new lines correctly.

I believe I almost covered all the points required to write a OS/compiler independent code. Keep it as a practice and even if you have to work over a project which already has written OS/compiler dependent code try using the methodology I have given. Im sure your code will be reused by somebody with less effort if you implement the same coding methodology.

Printing the gcc predefined macros to stdout

Any time you wanted to know the list of gcc used macros and their values. Here is the command details

touch foo.h; gcc -dM -E foo.h

will list all the macros used.

The option

-dM will generate the list of all #defines used by the pre-processor during execution, this also includes pre-defined macros.

-E will stop the compiler after pre-processing stage. Will not enter to the compiling stage. The output will be in the preprocessed form and will be sent to the stdout.

Find a pattern and then do search and replace of a word.

I was having a file with format as below.
1. Different fields with a field seperator.
2. Multiple lines.
3. There were multiple lines with same strings to be replaced but there are few lines to match a pattern string to execute find and replace.

Used the following vi editor command.
:%g/^.*pattern*.$/s/find/replace/g
where,
%g for using regular expression command in vi.
^.*pattern*.$ for searching and selecting lines containing the (semi-)word pattern.
s/find/replace/g for string find words with value “find” and replace them with string “replace”.

/Gs (Control Stack Checking Calls) (C++)

Usually you might have faced the following issue while compiling on Visual Studio .NET 2005.

error LNK2019: unresolved external symbol __chkstk referenced in function…

This is caused by stack probes. Either you can increase the size of the stack to what ever maximum your function uses using Gs option (Default for x64 is /Gs8192) or using heap.

Gs option is an advanced feature to control stack probes. A stack probe is a sequence of code the compiler inserts into every function call.

Read more on MSDN

Blogged with the Flock Browser

ACPI States

Introduction
    The Advanced Configuration and Power Interface (ACPI) is an open industry standard developed by HP, Intel, Microsoft, Phoenix, and Toshiba) defines common interfaces for hardware recognition, motherboard and device configuration and power management.

ACPI Power Management States

  • Global system states
  • Sleeping states
  • Device Power states
  • CPU Power states
  • CPU / Device Performance states
  • CPU Thermal Monitor states

Global System States (G-States)

  • Global system states apply to the entire system and it is user-visible.
  • Divided into 4 states – G0, G1, G2, G3

G0 Working State

  • This is the power state where computer is able to run applications.
  • Power consumption is the highest among all G states.

G1 Sleeping State

  • The computer appears “turned off” to the user.
  • Most of the system context will be saved in memory – either RAM or the hard drive.
  • Example : Switching the computer into “Standby” or “Hibernate” mode in Windows XP.

G2 Soft Off

  • The whole is system is turned off, with the exception of the main switch of the power supply unit.
  • Some debug and machine check registers still retain their error codes, if there are any.
  • Power consumption is almost zero.
  • The operating system needs a reboot, and the wake up latency is long.
  • Example : Choose “Shut Down Computer” in Windows XP, but the main power switch is not turned off.

G3 Mechanical Off

The computer is completely turned off by cutting the main power into power supply unit.
Power consumption is zero.

G Power Consumption
G0 > G1 > G2 > G3

Sleeping States (S-States)

  • Sleeping states define the computer’s ‘sleeping methods’ in the G1 (sleeping) state. In all the sleeping states (except S0 and S5),
  • Divided into 5 states – S1, S2, S3, S4, S5
  • The CPU executes no instructions. It is having a good sleep!
  • User applications will not run (duh… the CPU is sleeping!)
  • When the system is ‘awakened’, it will continue working from the point before it slept.

S0 State

  • Same as G0

S1 State

  • The hardware maintains all its system context.
  • The CPU input clock will be stopped, and its caches will be invalidated.
  • The system memory goes into its self-refreshing mode.
  • All system clocks are turned off, except the real time clock.
  • Wake up latency is low. It takes about 2 seconds to go back to the G0 working state. The hardware will be responsible for restarting the system clocks.
  • Example : “Stand-by” mode in Windows XP, if the S3 state isn’t supported.

S2 State

  • The CPU and its caches are powered down, instead of just gating the clock input and invalidating the caches.

S3 State

  • The S3 state powers down the CPU, cache, chipset and peripherals, except RAM.
  • RAM goes into a low-power, self-refreshing mode.
  • The wake-up latency is about 5-6 seconds.
  • Example : “Stand-by” mode in Windows XP if the S3 state is supported by hardware.

S4 State

  • All devices including system RAM are powered down.
  • Only platform settings are maintained, while other settings are stored in a special partition in the hard drive.
  • The power consumption is very low (< 3W), as almost everything has turned off.
  • We need to go through the BIOS boot sequence again when the computer is awakened.
  • The OS reboot is not required. It will automatically return to where you last left it.
  • Example : “Hibernate” mode in Windows XP

S5 State

  • Same as G2

S Power Consumption

  • S0(G0) > S1 > S2 > S3 > S4 > S5(G2)

Device States (D-States)

  • Device states occur in the global system G0 working state.
  • Defined to enable device vendors to design ACPI-compliant products, so that operating system that support ACPI, like Windows XP, can manage the devices.
  • Divided into 4 states – D0, D1, D2, and D3.

D0 State

  • In this state, the device is operating at its full power.
  • Example : A HDD in active use.

D1 State

  • The device can choose to discard its context.
  • However, the bus connected to this device should not do anything to cause the context loss in the device.
  • Power consumption is lower than the D0 state, as some working units in the device will shut down.
  • Example : After idling for some time, the laser in the DVD-ROM drive will automatically turn off, but the drive controller will still be active.

D2 State

  • It is similar to D1, but the bus is free to some power management, like lower the current and voltage.

D3 State

  • The device in this state can be completely turned off.
  • Maximum power saving is achieved.

CPU Power States (C-States)

  • CPU (Sleep state)C-states occur in the global system G0 state.
  • Divided into 7 states – C0, C1, C2, C3, C4, C5 and C6.

C0 State (Active)

  • This is the CPU’s maximum working state, where it is actively accepting instructions and processing data.
  • Power saving is virtually zero.

C1 State (Halt)

  • It is simply done by executing the assembly instruction “HLT” (Halt).
  • This will stop the instruction pipeline within the CPU from executing any instructions.
  • Wake-up time is ultra fast (only about 10 nano seconds).
  • The CPU is able to save up to 70% of its maximum power consumption.
  • All modern processors must support this power state.

C2 State (Stop Grant)

  • The processor core clock and platform I/O buffers are gated.
  • The transition time from C2 to C0 is 10 times more (~100 nano seconds).

C3 State (Deep Sleep)

  • The bus clock and PLLs are gated.
  • In a multi-processor system, the processors no longer handle FSB snoops to maintain cache coherency. Cache contents are invalidated.
  • In a single-processor system, memory transactions are prohibited but cache contents are not invalidated.
  • CPU still saves around 70% power, but the platform power will be reduced even more than C2.
  • Wake up time is 500 times longer than C2 (about 50 micro seconds).

C4 State (Deeper Sleep)

  • It is similar to the C3 state, but with two main differences.
  • First, the core voltage is reduced to a very low level (less than 1.0V) to decrease current leakage.
  • Second, data stored in the L2 cache will be reduced bit by bit over time.
  • The CPU can save around 98% of its maximum power.

C5 State

  • When the data in the L2 cache is reduced to zero.
  • Wake-up time is more than 200 micro seconds.

C6 State

  • New power management feature in Penryn.
  • When the L2 cache contents are shrunk to zero, the CPU will go into an even lower core voltage.
  • CPU context is no longer preserved.
  • Power consumption is virtually near zero.

C-States In Multi-Core Processors

  • In a multi-core processor, there can be multiple C-states in each core, but only one processor C-state is enabled at one time.
  • The processor C-state is equal to the highest C-state of any processing core.
  • Cx = max (Cx1, Cx2, Cx3, …… , CCxn)

CPU / Device Performance States (P-States)

  • P-states define the power management state while the CPU / device is within its executing state, C0 for CPU and D0 for device.
  • Usually clock speed and voltage varies depend on workload.
  • The amount of P-state is CPU / Device specific
    •     P0 : Minimum p-state, highest power consumption.
    •     P1, P2, P3…. : P1 > P2 > P3 and so on, in terms of power consumption.
    •     Pn : Maximum p-state with the lowest power consumption.
  • P-state power management can be seen in modern CPUs and GPUs.
  • It allows them to control their active power according to the load at any particular moment.
  • The number of P-states is implementation-specific.
  • Wake-up time is slower, but still much lower than 1 second (~160 micro seconds).

CPU Thermal Monitor

  • The main purpose of the thermal monitor is to decrease the processor power consumption when it is running too hot.

Thermal Monitor 1
(TM1)

  • When the thermal treshold is exceeded, TM1 changes the clock duty cycle to lower down the CPU power consumption. Users will feel choppiness in their applications when TM1 is applied.
  • The throttling can be done on a per-core basis (only CPU TM1). This means Core 1 may do TM1 but Core 2 can still run normally.

Thermal Monitor 2
(TM2)

  • When the thermal treshold is exceeded, TM2 changes the clock speed and core voltage to reduce the CPU power consumption. All cores will activate TM2 simultaneously as there is no per-core support. Users will not feel the choppiness as the transition between P-states are very smooth. TM2 is only supported by the CPU.

Extended Thermal Monitor
(ETTM)

  • When the thermal condition is very bad, TM1 is activated on top of TM2 to aggressively reduce the CPU power consumption.

 

Blogged with the Flock Browser