Month: October 2015

Home / Month: October 2015

Understanding ASCII

October 19, 2015 | Article | 4 Comments

What is ASCII?

ASCII is American Standard Code for Information Exchange. What does it mean? And why we use it?

Well, computer only knows number that we call binary number. Therefore, to instruct machine we have to use proper machine language which is binary coded form. Can you instruct machine, write sequence of 0 and 1 bits that make computer do something? It can but would be hard. Since computer only know 0 and 1, they also can’t understand our character. To make computer understand, our character will be mapped / encode to binary. That’s ASCII work for. It represent our character, from ‘A’ to ‘Z’, ‘0’ to ‘9’ and many more characters. This is standard that used in computer. As we say standard, the symbols on ASCII are well-known symbol or mutually agreed by many vendor.This guarantee that computer of different vendor / platform can still communicate and we also can use machine in more human-way.

Character in ASCII code are around 256 symbols numbered from 0 to 255 (in early era there are only 128 characters. The other 128 characters are extended to old standard). Why 0? Because our number system use 0 as lowest value for each digit. If you want to know further about number system, you can read my other article Number System or Decimal Number.

Now, I present to you list of ASCII code in simple table. Click the image to view full version of image.

ASCII Table 0~127

ASCII Table 127-255 (EXTENDED)

Now, what can we do with ASCII? Is it used? There are lot of things ASCII did. If ASCII was not present, we can’t read human character like we did now. So, must we read this article or blog with sequence of 0’s or 1’s? Must we remember and use machine language? If that’s the situation, you can imagine how many 0 and 1 you will see if there is a sentence “Satria is handsome and so cool”. (FYI: one character consist of eight number that can be 0 or 1).

Wow @@

ASCII inside program

Like I said before, computer only knows binary number. In the program, we use characters of ASCII to print or read something. ASCII characters are symbolized by character data type in programming language (character in Pascal or char in C).

This snippet is written in C++ language and will print character of ASCII from 0 to 127 (means: 128 character would appear). Don’t be surprised if some characters are not printable.

#include <iostream>
using namespace std;

int main() {
   int i;

   for(i=0; i< 128; i++) {
      cout<<(char) i<<endl;
   }

   return 0;
}

ASCII is not only a character

ASCII is the way of life! No, that’s only joking. But when I say ASCII is not only a character I mean, yes that’s true.

ASCII are not only characters we often meet everyday like a,b,c,d,.., z or 0,1,…,9 or symbols like [email protected]#$%^&*(). If you compile and execute snippet above and look carefully, you will see weird symbol in some lines. Yes, that’s also part of ASCII.

ASCII characters are also known by computer. Let’s take example of 8’th character in ASCII which is a backspace. This is a symbol used to represents backspace key on keyboard. Not only that, there is also character used for transmission like 2nd symbol which is STX or Start of Text. This character is used by program as beginning of text.

Now, we can conclude that ASCII is a universal code used for general purpose.

A Little Advice in Making C Header File

October 19, 2015 | Article | No Comments

As we know, C and C++ programming language are supporting modular programming. It means that we can break our long code into several separate modules. For this we need a file named header file that mostly are set of function prototypes. Later the functions will be implemented on another source file. Now, what are things we should (or should not) put in header file? When we should create a header file?

This article will give little advice about what we should include in our header file. This list is based on personal experience, so you can agree or reject it.

[DO] Always Create “guard” Macro for Each Header

What is “guard” that I mean? They are 3 line of code that protect your header files from multiple inclusion. This is essentially important as we can include our header as many as we like but compiler only read it once. Therefore, we can guarantee that our declarations are only once. The “guard” are composed by macro #ifndef, #define, #endif. You must check a unique macro name that acts as you unique header identifier. If not exist, we declare our code. Otherwise, the compiler will ignore the declaration. Our code will be between #define and #endif code respectively.

[DO] Create One Header File for Each “Module” of the System

Yes, for each. A module may comprise one or more compilation units. But it should implement just one aspect of the system. Examples of well-chosen modules are:

  • device driver for A/D converter
  • communication protocol
  • alarm manager that is responsible for logging error conditions and alerting the user.

Every module must be create on one header file.

[DO] Include All of the Function Prototypes for Public Interface of Module

For example, a header file lcd.h might contain function prototype for lcd_init(), lcd_write(), and lcd_clear(). But private implementation or helper functions that only known or used by those functions must be remain hidden.

[DON’T] Include Any executable Lines of Code in a Header file, Including Variable Declarations.

It’s not so effective. Another reason is there would be a chance of fatal error by multiple declaration. Especially if you are not providing “guard” for header files. But it is necessary to make an exception for the bodies of some inline functions.

[DON’T] Expose Any Variable in Header File

Again! If you want to make a variable public or known by another module, it’s not wise to put them on header file. Use extern in header file while the actual declaration would be in source code file (.c file).

[DON’T] Expose Internal Format of Any Module-Specific Data Structure Passed to or Returned from One or More of the Module’s Interface Functions

No declaration of structure in header file. Implicitly, no “struct { … } foo;” like code in any header file. If you do have a type that you need to pass in and out of your module so client can create instance of it, simply use “typedef struct moduleb_type” in header type. Outside that module should never know the internal format of the struct.

Maybe this is strict, but I hope this advice will give a better and readable C programming practice. More advice would be added later.

C volatile keywords

October 19, 2015 | Article | No Comments

In C/C++ programming language, volatile keyword is a type qualifier used to declare an object that can be modified in the program by something such as operating system, the hardware, or a concurrently executing thread.

In reality, the C’s volatile keyword is poorly understood by many programmers and used not properly. It’s not surprising as most book covering C language only explain it in one or two sentence. This article will covering about a proper way to use volatile. This article is categorized as little advanced so I hope you have understand C\C++.

Mostly, people experience these while programming C\C++ for embedded code (check for yourself):

  • Code works fine until compiler optimizations enabled
  • Code works fine until interrupts enabled
  • Flaky hardware drivers
  • RTOS tasks that work fine in isolation until other task is spawned.

If you ever experience any of above, most likely you didn’t use the C keyword volatile.

C’s volatile keyword is a qualifier that is applied to a variable when declared and tells the compiler that the value of the variable may change at any time without any action being taken by the code that compiler finds nearby. This is quite serious.

There are some declaration that may have different meaning. Let’s inspect further.

To declare a variable volatile, include the keyword volatile before or after the data type in variable declaration. Both have same meaning:

volatile int xathrya;
int volatile xathrya;

Those are very common declaration. Now, there is another way of declaring pointer. Both of these declaration will declare a pointer to a volatile unsigned integer:

volatile unsigned int * xathrya;
unsigned int * xathrya;

Next, we can have volatile pointers to non-volatile data. But this is very uncommon:

int* volatile xathrya;

You may think that we can have a volatile pointer to volatile variable, and yes this is possible:

int volatile * volatile xathrya;

If you apply volatile to a struct, union, or a class, the entire contents of struct/union/class would be volatile too. If you don’t want this, apply volatile to individual members of struct/union/class.

Now speaking about proper use of volatile. When we declare volatile? Whenever a variable’s value could change unexpectedly. In practice there are only three types of variable could changes:

  1. Memory-mapped peripheral registers
  2. Global variables modified by an interrupt service routine
  3. Global variables accessed by multiple tasks within a multi-threaded application

Let’s discuss each case!

Peripheral registers

Embedded systems contain real hardware, usually with sophisticated peripherals. These peripherals contain registers whose values may change asynchronously to the program flow. As a very simple example, consider an 8-bit status register that is memory mapped at address 0x1234. It is required that you poll the status register until it becomes non-zero. The naive and incorrect implementation is as follows:

uint8_t* pReg = (uint8t *) 0x1234;
// wait for register to become non-zero

while(*pReg == 0) {  } // do something else

This will almost certainly fail as soon as you turn compiler optimization on, since the compiler will generate assembly language that looks something like this:

mov ptr, 0x1234
mov a, ptr
loop:
bz loop

The rationale of the optimizer is quite simple: having already read the variable’s value into the accumulator (on the second line of assembly), there is no need to reread it, since the value will always be the same. Thus, in the third line, we end up with an infinite loop. To force the compiler to do what we want, we modify the declaration to:

uint8_t volatile* pReg = (uint8_t volatile *) 0x1234;

Thus the assembly language would looks like:

mov ptr, 0x1234
loop:
mov a, ptr
bz loop

The desired behavior is achieved.

Subtler problems tend to arise with registers that have special properties. For instance, a lot of peripherals contain registers that are cleared simply by reading them. Extra (or fewer) reads than you are intending can cause quite unexpected results in these cases.

Interrupt Service Routines

Interrupt service routines often set variables that are tested in mainline code. For example, a serial port interrupt may test each received character to see if it is an ETX character (presumably signifying the end of a message). If the character is an ETX, the ISR might set a global flag. An incorrect implementation of this might be:

int etx_rcvd = FALSE;

void main() {
...

   while(!ext_rcvd) {

      // wait
   }

...

}

interrupt void rx_isr(void) {

...

   if(ETX == rx_char) {
      etx_rcvd = TRUE;
   }

...

}

With compiler optimization turned off, this code might work. However, any half decent optimizer will “break” the code. The problem is that the compiler has no idea that etx_rcvd can be changed within an ISR. As far as the compiler is concerned, the expression !ext_rcvd is always true, and, therefore, you can never exit the while loop. Consequently, all the code after the while loop may simply be removed by the optimizer. If you are lucky, your compiler will warn you about this. If you are unlucky (or you haven’t yet learned to take compiler warnings seriously), your code will fail miserably. Naturally, the blame will be placed on a “lousy optimizer.”.

The solution is to declare the variable etx_rcvd to be volatile. Then all of your problems (well, some of them anyway) will disappear.

Multi-threaded applications

Despite the presence of queues, pipes, and other scheduler-aware communications mechanisms in real-time operating systems, it is still fairly common for two tasks to exchange information via a shared memory location (that is, a global). Even as you add a preemptive scheduler to your code, your compiler has no idea what a context switch is or when one might occur. Thus, another task modifying a shared global is conceptually identical to the problem of interrupt service routines discussed previously. So all shared global variables should be declared volatile. For example, this is asking for trouble:

int cntr;

void task1(void) {
   cntr = 0;
   while(cntr == 0) {
      sleep(1);
   }

...

}

void task2(void) {

...

   cntr++;
   sleep(10);

...

}

With a simple observation, we will know that this code will likely fail once the compiler’s optimizer is enabled. Declaring cntr to be volatile is the proper way to solve it.

Some compilers allow you to implicitly declare all variable as volatile. But, resist this temptation since it is essentially a substitute for thought. It also leads to potentially less efficient code. Use volatile if you must.

AVR Microcontroller Programming in Linux

October 19, 2015 | Article | 2 Comments

AVR or Alf & Vegard RISC, is a single chip microcontroller developed by Atmel. AVR is a modified Harvard architecture 8-bit RISC (Reduced Instruction Set Computer) which is a famous microcontroller.

AVR microcontrollers has many categories or we will say family. Family basically a group or category based on similiar characteristic and properties. There are six family and fortunately, AVR microcontrollers have same architecture. Thus programming in one family can be guaranteed work on other family. It is only limited to physical limitation such as different amount of flash storage, etc. AVR’s merit is about ease of porting.

As one of widely used microcontroller, there are lot of communities in internet. We can easily find various options can while developing microcontroller project.

This article will be covering preparation and setting up environment in Linux to develop AVR program.

What you will need:

  1. GNU/Linux
  2. avrdude
  3. avr-gcc
  4. avr-binutils
  5. A programmer (will be described later)
  6. AVR Microcontroller, with it’s development board if any, in this case I use AVR ATMega32

Program in Microcontroller

Before I start, let’s talk about program. What is program? A program is simply set of instructions written using machine language so it can be executed by machine. It is also called “binary” which mean to be not human-readable file (but can be understood by machine). For microcontrollers, binary files have type .hex (Intel Hex Format). You can imagine it as .exe in windows application. There are other forms, but in this article we will focus on .hex.

AVR has a small amount of memory in it. It is a storage where program is actually saved. And yes it is small compared by computer. Just some Kilobytes. When the chip starts up, microcontroller will start running whatever program written in flash.

Compiler and Cross Compiling

Compilation for microcontroller is basically similar to compiling program for PC. However, the difference between those two is in term of product of compilation. Compiler for AVR is run in our PC (developer machine), compile source code, and then produce machine language which is specific for the microcontroller (not our PC). This process is called cross compiling.

There are many cross compiler for AVR. I use AVR-GCC for this purpose (in this article and other similar articles, unless told otherwise).

Other tools we need are collectively known as avr-binutils. The binutils packages provide all the low-level utilities needed in building and manipulating object files. In this package, we have AVR assembler (avr-as), linker (avr-ld), and librarian (avr-ar and avr-ranlib). In addition, we get tools which extract data from object files (avr-objcopy), dissassemble object file information (avr-objdump), and strip information from object files (avr-strip).

The last thing to mention is the libc or standard c library. This is library designed for AVR microcontroller, or in other word it is different with our library used for PC programing.

Check your package management for avr-gcc and avr-binutils and install them.

For Debian and Ubuntu based:

sudo apt-get install gcc-avr
sudo apt-get install binutils-avr
sudo apt-get install gdb-avr
sudo apt-get install avr-libc

For Red Hat and Fedora based:

yum install avr-gcc
yum install avr-binutils
yum install avr-libc
yum install avr-gdb

Now invoke these to test the tools:

avr-gcc
avr-objcopy

Download / Burn the Program to the Chip

To program microcontroller we need a downloader.  It is a special chip that can connect your microcontroller with our computer and write our program into our chip. Every AVR has a set of pins that are programming pins. You have to verify you chip pins and connect the programmer to those pins in the right order.

So what programmer can be used? In this article I used USBasp. Of course you can have other programmers, but I will only talk about this programmer. For information about USBasp, you can visit this link http://www.fischl.de/usbasp/

Now we have know our programmer (I mean USBasp) but then, how to write our program to microcontroller? Relax! We will cover now.

We will use avrdude, a small application to do that. Install it if you have not install.

For Debian and Ubuntu based:

sudo apt-get install avrdude

For Red Hat and Fedora based:

yum install avrdude

Let’s take a peek of avrdude by give this command on our terminal:

avrdude

Let’s see what we have got. You will get something like this:

Usage: avrdude [options]
Options:
-p <partno>                Required. Specify AVR device.
-b <baudrate>              Override RS-232 baud rate.
-B <bitclock>              Specify JTAG/STK500v2 bit clock period (us).
-C <config-file>           Specify location of configuration file.
<strong>-c <programmer>            Specify programmer type.</strong>
-D                         Disable auto erase for flash memory
-i <delay>                 ISP Clock Delay [in microseconds]
-P <port>                  Specify connection port.
-F                         Override invalid signature check.
-e                         Perform a chip erase.
-O                         Perform RC oscillator calibration (see AVR053).
-U <memtype>:r|w|v:<filename>[:format]
 Memory operation specification.
 Multiple -U options are allowed, each request
 is performed in the order specified.
-n                         Do not write anything to the device.
-V                         Do not verify.
-u                         Disable safemode, default when running from a script.
-s                         Silent safemode operation, will not ask you if
fuses should be changed back.
-t                         Enter terminal mode.
-E <exitspec>[,<exitspec>] List programmer exit specifications.
-x <extended_param>        Pass <extended_param> to programmer.
-y                         Count # erase cycles in EEPROM.
-Y <number>                Initialize erase cycle # in EEPROM.
-v                         Verbose output. -v -v for more.
-q                         Quell progress output. -q -q for less.
-?                         Display this usage.

avrdude version 5.10, URL: <http://savannah.nongnu.org/projects/avrdude/>

Woah, that’s too much. But our interest is only in few options. I’ve bold the text which will get our attention. We only interests in -p, -U, and -c options as this is a minimum command we need to invoke along with avrdude.

  • -c : We specify the programmer we type. We are using usbasp so can be replaced with usbasp. Of course if you are using other programmer you must specify. For a complete list about supported programmer, invoke command: avrdude -c asdf. Because asdf is not a valid programmer, avrdude would complaint and print out list of supported programmer to you. Read it and verify your programmer is supported.
  • -U :r|w|v:[:format]: This is the most important command. is either flash or eeprom which is destination where our program will be stored. Next is r (read), w (write), or v (verify) option that you must choose one (only one). Next is which you have to replace with your program path and name. Next is optional format flag [:format] that specify our program format.
  • -p : Specify microcontroller series. Or simply what microcontroller we willl program. For example I will use ATMega32 so i will replace with atmega32.

With these three, we can program in minimal. In this case when I want to program ATMega32 using USBasp with filename avr_leds.hex, the command I use will be:

avrdude -c usbasp -U flash:w:avr_leds.hex -p atmega32

Wait until process is finish and then you can see you microcontroller is programmed now.

Next time I will write some actual writing program for AVR.

Android Operating System is one of popular operating system for mobile device beside Windows Phone, Apple iOS, etc. The popularity comes from the fact that Android is open source, used by various vendor. You have a freedom to modify and do anything to your Android, though you will void your warranty.

This article main focus would be concentrated on installation of development tools, which is Eclipse IDE, Android SDK, and Android Developer Tool.

Why Eclipse? Eclipse is an open source Integrated Development Environment and has full support for Android. It’s also quite simple.

In the time i write this article, I use GNU/Linux Ubuntu 10.10. Of course you can use other linux distribution if you like, especially Debian or Ubuntu derivative distribution. I might encourage you to use later version if possible. You must also have active internet connection to do installation and fetching required packages.

Table of Content

  1. Installation
    1. Eclipse IDE
    2. Oracle Java JDK
    3. Android Developer Tool Plugin
    4. SDK and SDK Platform
  2. Create Android Virtual Device

Installation

[x] Installing Eclipse IDE

First, installing Eclipse. In this article I will use latest Eclipse (per September 6th, 2012) version. It’s Eclipse 4.2 Juno for Linux 32 bit. You can download it at this link.

I pick eclipse-SDK-4.2-linux-gtk.tar.gz, it is a ready to use version means no installation required. Download it and then extract the file.

tar xvzf eclipse-SDK-4.2-linux-gtk.tar.gz

We will have a new extracted directory named eclipse. Move this directory to /opt. This is a good practice for FHS (Filesystem Hierarchy Standard) as an optional software installed to this. In my case I extracted eclipse in /home/xathrya/Downloads. I will invoke following command and remember the command need privileges as /opt is usually owned by root:

mv /home/xathrya/Downloads/eclipse  /opt

Create symbolic link to eclipse in /usr/bin (use root privilege):

ln -s /opt/eclipse/eclipse /usr/bin/eclipse

[x] Installing Oracle Java (Replace OpenJDK)

You can use OpenJDK and skip this. However if you want

Next you must have a running JAVA Runtime Environment. We need to install Oracle Java. Ubuntu has come with a default OpenJDK Environment so we will replace it.

In Ubuntu, the JAVA is located on repository partner which indicated it is a proprietary repository. To install JAVA first we have to add the repository. In this case I use maverick meerkat (Ubuntu 10.10 distribution), if you have other distribution, you can replace maverick with your Ubuntu codename (ex: lucid for lucid lynx, natty for natty narwhal)

sudo add-apt-repository "deb http://archive.canonical.com/ maverick partner"
sudo apt-get update

After that you can install JAVA JRE

sudo apt-get install sun-java6-jre galternatives

last we need to change the default java environment for OpenJDK to Sun JRE 6

sudo galternatives

Select java in left panel and select java-6-sun as shown by image below:

Now, verify your java installation. Invoke this command:

java -version

This should gives you message like this:

java version "1.6.0.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04)
Java HotSpot(TM) Client VM (build 17.1-b03, moxed mode,sharing)

[x] Android Developer Tool Plugin

Now let’s moving to installation of Androit Developer Tool (ADT). It is a special Eclipse plugin contains integrated android environment for building Android application using eclipse. Reminder: my eclipse version is 4.2 (Juno)

Start eclipse. Now navigate to:

Help - Install New Software - Add

enter the following information:

Name: ADT Plugin
Location: https://dl-ssl.google.com/android/eclipse/

Click on OK. Now select “Developer Tools” and/or “NDK Plugins”. Click Next to begin installation. Wait for installation to finish its work. With my connection around 50KB/s the installation done in 30 minutes.

[x] Install the SDK and SDK Platform

Next we will install Android SDK. Downlad Android SDK starter pack from this link

Download the latest SDK. By the time I write this article, the latest version is 20.0.3. You can download linux version directly in this link:

Extract the content of Android SDK pack:

tar xvzf android-sdk_r20.0.3-linux.tgz

In my case I will leave the SDK on /home/xathrya/android-sdk.

Now we need to install platforms and optional additional plugins or sample codes. Start SDK manager:

/home/xathrya/android-sdk/tools/android

Seleck SDK Platforms you want. I choose Android 2.3.3 API 10 as my smartphone Sony Xperia U use this one. When you have selected all packages you want, click Install Selected. You will be prompted to Accept License. Click Accept All and then Install.

Create Android Virtual Device

Now we have to join Eclipse IDE with Android SDK and create and Android Virtual Device (AVD). Android Virtual Device is an emulator to run your application on top of your computer.

In Eclipse, navigate to: Window -> Preferences -> Android

Enter location of your Android SDK installation. In my case it is in /home/xathrya/android-sdk/. Press OK.

Now navigate to Window -> AVD Manager -> New

Insert following information into:

Name: AndroidVirtualDevice
Target: [chose any desired Android version and API level available]

Click Create AVD. The new Android Virtual Device will be created in the directory:

~/.android/avd

We are done!

New World, New NEST!

October 13, 2015 | News | No Comments

Hello, Internet!

I’m Xathrya and this is my new NEST.

If you ever know my old NEST (https://blog.xathrya.id) and got here because of that, thank you! This new NEST will serve as continuation of old NEST. I will fix some things and make the content back here. Recreating is not easy but I will do my best.

I would be pleased if you can help me by suggesting contents or help me spread the fame.

Outside of writing articles, I also studying reverse engineering and playing some CTFs. If you ever know Dago Cybernesha or Sabertooth Ganesha, please say hi. You can also recruit me for CTF if you want 😀

 

Last, thanks for all of my friends who keep me doing my best (and push me to back in action).

Social media & sharing icons powered by UltimatelySocial