Wednesday 24 October 2012

Mount/link remote directory via ssh



ami@ami:~/Downloads/ram$ sudo sshfs jonna@172.16.99.67:/jonnasdd/android  /mnt/
The authenticity of host '172.16.99.67 (172.16.99.67)' can't be established.
ECDSA key fingerprint is a3:b3:4b:10:21:0b:76:19:62:b1:d6:f1:3f:a7:40:72.
Are you sure you want to continue connecting (yes/no)? yes
jonna@172.16.99.67's password:
ami@ami:~/Downloads/ram$

so the remote directory has been mounted.

Tuesday 11 September 2012

Embedding GDB breakpoints in C source code

Have you ever wanted to embed GDB breakpoints in C source code?
int main() {
    printf("Hello,\n");
    EMBED_BREAKPOINT;
    printf("world!\n");
    EMBED_BREAKPOINT;
    return 0;
}
One way is to directly insert your CPU's breakpoint instruction. On x86:
#define EMBED_BREAKPOINT  asm volatile ("int3;")
There are at least two problems with this approach:
  • They aren't real GDB breakpoints. You can't disable them, count how many times they've been hit, etc.
  • If you run the program outside GDB, the breakpoint instruction will crash your process.
Here is a small hack which solves both problems:
#define EMBED_BREAKPOINT \
    asm("0:"                              \
        ".pushsection embed-breakpoints;" \
        ".quad 0b;"                       \
        ".popsection;")
We place a local label into the instruction stream, and then save its address in the embed-breakpoints linker section.
Then we need to convert these addresses into GDB breakpoint commands. I wrote a tool that does this, as a wrapper for the gdb command. Here's how it works, on our initial example:
$ gcc -g -o example example.c$ ./gdb-with-breakpoints ./example
Reading symbols from example...done.
Breakpoint 1 at 0x4004f2: file example.c, line 8.
Breakpoint 2 at 0x4004fc: file example.c, line 10.
(gdb) run
Starting program: example 
Hello,

Breakpoint 1, main () at example.c:8
8           printf("world!\n");
(gdb) info breakpoints
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x00000000004004f2 in main at example.c:8
        breakpoint already hit 1 time
2       breakpoint     keep y   0x00000000004004fc in main at example.c:10
If we run the program normally, or in GDB without the wrapper, the EMBED_BREAKPOINT statements do nothing. The breakpoint addresses aren't even loaded into memory, because the embed-breakpoints section is not marked as allocatable.
You can find all of the code on GitHub under a BSD license. I've done only minimal testing, but I hope it will be a useful debugging tool for someone. Let me know if you find any bugs or improvements. You can comment here, or find my email address on GitHub.
I'm not sure about the decision to write the GDB wrapper in C using BFD. I also considered Haskell and elf, or Python and the new pyelftools. One can probably do something nicer using the GDB Python API, which was added a few years ago.
This code depends on a GNU toolchain: it uses GNU C extensions, GNU assembler syntax, and BFD. The GDB wrapper uses the Linux proc filesystem, so that it can pass to GDB a temporary file which has already been unlinked. You could port it to other UNIX systems by changing the tempfile handling. It should work on a variety of CPU architectures, but I've only tested it on 32- and 64-bit x86.

Sunday 9 September 2012

How to Create Dynamic Library in Linux

Step1: implement the library source. Let us assume there are two files namely one.c and two.c each implementing one function as follows
$ vim one.c
#include<stdio.h>
void fun1(){
printf("This is function 1\n");
}
 
$ vim two.c
#include<stdio.h>
void fun2(){
printf("This is function 2\n");
}
 
Step2: compile the sources to generate relocatables. Relocatable binary is created in two forms
position dependent : in this relocated code is bound to offset
position independent : in this relocated code is not bound to offset, because of which sharing of libraries among multiple applications becomes easy.
Preferably we compile them to get position independent relocatables because of some advantages (will cover latter on).
Note: ‘.so’ is the extension for dynamic libraries.

$ gcc -c -fpic one.c 
        ( to create a relocatable one.o )
$ gcc -c -fpic two.c 
       ( to create a relocatable two.o ) 
$ gcc -shared -o libmyown.so one.o two.o
        ( libmyown.so is the name of the dynamic library to be created )
         - shared flag used to create a shared library 
$ gcc -I ./ test.c -o testdynamic ./libmyown.so 
         - I option to let the compiler to check for "mylib.h" in current working directory
         
$ ./testdynamic
This is test to create own library
This is function 1
This is function 2

How to create a static library in linux


: Step 1: implement the library source. Let us assume there are two files namely one.c and two.c each implementing one function as follows
$ vim one.c
#include<stdio.h>
void fun1(){
printf("This is function 1\n");
}
~
$ vim two.c
#include<stdio.h>
void fun2(){
printf("This is function 2\n");
}
~


Step2: compile the sources (one.c, two.c) to generate relocatables
$ gcc -c one.c
$ gcc -c two.c
ls -l
total 16
-rw-r--r-- 1 ramchandra ramchandra 66 2011-01-23 14:59 one.c
-rw-r--r-- 1 ramchandra ramchandra 844 2011-01-23 15:01 one.o
-rw-r--r-- 1 ramchandra ramchandra 66 2011-01-23 14:58 two.c
-rw-r--r-- 1 ramchandra ramchandra 844 2011-01-23 15:01 two.o
$

Note: “.a “ is the extension for the static libraries.

Using the archive tool ar we create a static library.

$ ar rcs libmyown.a one.o two.o
- libmyown.a is the own static library to be created. According to the general naming conventions a library should start with “lib” .
- rcs are the options (replace, create, symbol) for more details refer to man pages as follows.
- one.o and two.o are the list of sources to be packed into archive.

The above created static library is position dependent.

$ man ar (this gives description about the usage of ar)
$ info ar (this gives information like an ebook)

To list what all files have gone into archive type use option‘t’ of ar.
$ ar -t libmyown.a
one.o
two.o

you can even view the list of file that are packed into libc.a standard library as follows. To see where libc.a located in your machine use whereis as follows, which gives the path for libc.a
$ whereis libc.a
libc: /usr/lib/libc.so /usr/lib/libc.a /usr/share/man/man7/libc.7.gz

$ ar -t /usr/lib/libc.a init-first.o |more
libc-start.o
sysdep.o
version.o
check_fds.o
libc-tls.o
elf-init.o
dso_handle.o
errno.o
 
Now we can ship our library to costumer, along with this we even need to ship the header file to give the function prototypes. Create a header file mylib.h as follows.

$ vim mylib.h
void fun1();
void fun2();

to make use of the library above created write a test application as follows.
$ vim test.c
#include<stdio.h>
#include<mylib.h>
main(){
printf("This is test to create own library\n");
fun1();/*call to function */
fun2();/*call to function */
}

Now compile the source file as follows.

$ gcc test.c -o test (gives an error)
test.c:2:18: error: mylib.h: No such file or directory

to figure out where the error occurred use the following option
$ gcc -v test.c -o test
v option with gcc, stands for verbose.
the error is because the header files included are searched at the following locations.
/usr/local/include
         /usr/lib/gcc/i486-linux-gnu/4.4.3/include
           /usr/lib/gcc/i486-linux-gnu/4.4.3/include-fixed
           /usr/include
where in our header file exists in the current working directory, and is not in above of the paths, so we have to explicitly say this by using the option I.
$ gcc -I ./ test.c -o test (gives error)
/tmp/ccFPPIsN.o: In function `main':
test.c:(.text+0x16): undefined reference to `fun1'
test.c:(.text+0x1b): undefined reference to `fun2'
collect2: ld returned 1 exit status
$
Still we end up with the following errors.
$ gcc -I ./ test.c -o teststatic ./libmyown.a
$ ./test
This is test to create own library
This is function 1
This is function 2
$

Here important thing to note is what ever the executable (teststatic) we generated is not complete static, it is dynamically linked, this can be know by the tool file.
$ file teststatic
teststatic: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, not stripped
$
Therefore to obtain a complete static executable use the -static flag with the above command and check out the type of file as above.
$ gcc -static -I ./ test.c -o test_complete_static ./libmyown.a
$ file test_complete_static
test_complete_static: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, for GNU/Linux 2.6.15, not stripped
$
One more thing to discuss is, in the above output there is something like “not stripped”. Which means there is some extra information like metadata in the executable. That extra unnecessary information can be removed using the tool strip. After stripping the file check out the earlier and current file sizes.
$ ls -l test_complete_static
-rwxr-xr-x 1 ramchandra ramchandra 578100 2011-01-23 17:14 test_complete_static

$ strip test_complete_static
$ ls -l test_complete_static
-rwxr-xr-x 1 ramchandra ramchandra 515108 2011-01-23 17:15 test_complete_static

Friday 31 August 2012

example of char device driver

--------------------
 char_dev.c
--------------------

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h> // required for various structures related to files liked fops.
#include <asm/uaccess.h> // required for copy_from and copy_to user functions
#include <linux/semaphore.h>
#include <linux/cdev.h>
static int Major;
dev_t dev_no,dev;
struct device
{
char array[100];
struct semaphore sem;
}char_dev;

int open(struct inode *inode, struct file *filp)
 {
        printk(KERN_INFO "Inside open \n");
        if(down_interruptible(&char_dev.sem)) {
        printk(KERN_INFO " could not hold semaphore");
        return -1;
  }
 return 0;
}

int release(struct inode *inode, struct file *filp)
 {
        printk (KERN_INFO "Inside close \n");
        printk(KERN_INFO "Releasing semaphore");
        up(&char_dev.sem);
        return 0;
}

ssize_t read(struct file *filp, char *buff, size_t count, loff_t *offp)
{
       unsigned long ret;
       printk("Inside read \n");
       ret = copy_to_user(buff, char_dev.array, count);
       return ret;
}

ssize_t write(struct file *filp, const char *buff, size_t count, loff_t *offp)
{
       unsigned long ret;
       printk(KERN_INFO "Inside write \n");
       ret = copy_from_user(char_dev.array, buff, count);
       return count;
}

struct file_operations fops = {
 read:  read,
 write:  write,
 open:   open,
 release: release
};

struct cdev *kernel_cdev;

int char_dev_init (void)
{
      int ret;
      kernel_cdev = cdev_alloc();
      kernel_cdev->ops = &fops;
      kernel_cdev->owner = THIS_MODULE;
      printk (" Inside init module\n");
      ret = alloc_chrdev_region( &dev_no , 0, 1,"chr_arr_dev");
      if (ret < 0) {
      printk("Major number allocation is failed\n");
      return ret;
 }

Major = MAJOR(dev_no);
dev = MKDEV(Major,0);
sema_init(&char_dev.sem,1);
printk (" The major number for your device is %d\n", Major);
ret = cdev_add( kernel_cdev,dev,1);
if(ret < 0 )
{
     printk(KERN_INFO "Unable to allocate cdev");
     return ret;
}
     return 0;
}

void char_dev_cleanup(void)
{
     printk(KERN_INFO " Inside cleanup_module\n");
     cdev_del(kernel_cdev);
     unregister_chrdev_region(Major, 1);
}

MODULE_LICENSE("GPL");
module_init(char_dev_init);
module_exit(char_dev_cleanup);
-------------
Makefile :
-------------

ifneq ($(KERNELRELEASE),)
   obj-m := char_dev.o
else
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default:
        $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
endif

----------------
creating a node:
----------------
mknod /dev/char_dev c 250 0



User Application :-
-------------------
main.c
------------------

#include <stdio.h>
#include <fcntl.h>

main ( )
 {
        int i,fd;
        char ch, write_buf[100], read_buf[100];
        fd = open("/dev/char_dev", O_RDWR);
        if (fd == -1)
        {
                printf("Error in opening file \n");
                exit(-1);
        }
        printf ("Press r to read from device or w to write the device ");
        scanf ("%c", &ch);

        switch (ch) {
                case 'w':
                       printf (" Enter the data to be written into device");
                        scanf (" %[^\n]", write_buf);
                        write(fd, write_buf, sizeof(write_buf));
                        break;
                case 'r':
                        read(fd, read_buf, sizeof(read_buf));
                        printf ("The data in the device is %s\n", read_buf);
                        break;
                default:
                        printf("Wrong choice \n");
                        break;
        }
        close(fd);
}
------------------------------
Compiling User Application :
------------------------------
$gcc -o main main.c

#./main
Press r to read from device or w to write the device : w
Enter the data to be written into device  : American Megatrends Inc.

#./main
Press r to read from device or w to write the device : r
The data in the device is : American Megatrends Inc.

Thursday 30 August 2012

Forgot Root Password


I think this must be a common problem to a lot of users, forgetting the root password of their system or in the case of New ubuntu like systems that do not have a root log in, if you forget the password for the only user in your system then you are stuck with no way of logging in. Well there is simple work around for situations like this.
Follow the following steps to reset your root password. [Please see below for ubuntu systems]

1. While your system boots go the GRUB menu by pressing "esc".
2. Highlight the OS you want to boot using the arrow keys.
3. Press "e"
4. You will see three options ( generally), move to the line that starts with "kernel".
5. press "e" again
6. You will see a line of text, move to the end of it.
7. Add "single" or "1" to the end of the line.
8. Hit Enter and press "b".

Your system should boot into a text mode, with a shell prompt.

typer  "passwd" and hit enter.
You will be prompted for a new password. enter the password , you will be asked for confirmation enter the password again.

enter the command "reboot" and hit enter.

The system should boot back to your normal log in screen, you can use the new password that you just set for the root log in.

In case of Ubuntu systems this method does not work very well so there is slightly different way of making it work.
in step 7: instead of adding "1"  add the text "/dev/sda=rw"  assuming sda is the partition on which you have your Linux installed.

Hope you are able to log into your system again :-)

User is not in the sudoers file. This incident will be reported

On using the sudo command if we see the error message:
 
"User is not in the sudoers file. This incident will be reported."

This means that the user as whom we have logged in and are trying to run the command "sudo" does not have the permission to do so.
Only the users listed in /etc/sudoers have the permission to use the command "sudo".
To give the sudo permission to a user we need to add the user to the file /etc/sudoers file.
Open the file /etc/sudoers as root.
 
$sudo vim /etc/sudoers

Add the line
 
username ALL = (ALL) ALL

under the User privilege specification section.
Save the file and exit, now the sudo command should work for the user which was added in the file.

How to get Motherboard details



We can find out all the details about the motherboard in our system using the command lshw.
#lshw -class bus |grep -A 6 Motherboard
       description: Motherboard
       product: DH55TC
       vendor: Intel Corporation
       physical id: 0
       version: AAE70932-302
       serial: BTTC10900DL8
       slot: To be filled by O.E.M.

Inter Process Communication using shared memory


Processes can communicate between each other in various ways, one of the techniques is by using shared memory, i.e. the processes share a memory region between each other which both can read from. Processes can read and write from this memory what ever that has to be shared.

To create or get access to an already created shared memory we use the function shmget (shared memory get).

int shmget(key_t key, size_t size , int shmflg);

Arguments: key : The key used by the process to identify the shared memory, it is assigned by the process and the other processes which want to communicate with this shared memory need to know this key.

size: The size of the shared memory that is allocated.

flag: If the shared memory is being created then we can use the flag IPC_CREAT as the flag. If we are trying the get access to a shared memory already created then we can pass the mode flag specifying the rights for owner,group and the world in the same format as followed by "chmod".

Return : An identifier to the shared memory which is used along with the "key" to identify the memory segment for communication.

Once the share memory is allocated to start the communication we need forts attach this shard memory with the memory of the process to this we use the function shmat (shared memory attach)


void * shmat(int shmid,const void *shmaddr , int shmflg);

Arguments:

shmid: The identifier returned by shmget

shmaddr: The address where the segment should get attached, if left NULL the system automatically chooses a suitable location for the attach.

shmflg: Used in the specific case when mapping of the segment should replace any existing mapping in the range starting at shmaddr , can be left NULL otherwise.

Return: The address of the shared memory that was attached to the process.

Once the memory segment is attached data can be read from and written to the shared memory using the address returned by shmat and the the functions sscanf and sprintf respectively.

Example:

The following program creates a shared memory in the default mode and then writes a message in the shard memory.

Note the used of IPC_CREAT flag with the shmget call.

write_shm.c
------------------------------------------------------------------------------------------------------------
#include <sys/ipc.h>
#include<sys/shm.h>
#include <stdio.h>
main()
{
key_t key=12345;
int shm_id;
void *shm;
char *message="hello";
shm_id =shmget(key,10*sizeof(char),IPC_CREAT);
shm = shmat(shm_id,NULL,NULL);
sprintf(shm,"%s",message);
}
------------------------------------------------------------------------------------------------------------


The following code tries access the shared memory created by the above code and read the data written in it. Note that the value of key used by both the codes are same, failing which the shmget will be unable to identify the shared memory.


 read_shm.c
------------------------------------------------------------------------------------------------------------
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
main()
{
key_t key=12345;
int shm_id;
void *shm;
char *message;
message=malloc(10*sizeof(char));
shm_id=shmget(key,10*sizeof(char),NULL);
shm=shmat(shm_id,NULL,NULL);
if(shm == NULL)
{
printf("error");
}
sscanf(shm,"%s",message);
printf("\nmessage=%s\n",message);
}
------------------------------------------------------------------------------------------------------------


Compile the above programs
Compile the above programs

$gcc write_shm.c -o write_shm
$gcc read_shm.c -o read_shm

execute them

$./write_shm
$./read_shm
Message = hello

You should see the message written by the first process displayed by the second process thus achieving the required communication between the processes.

Wednesday 25 July 2012

COLINUX:


Running Linux under Windows Using  Cooperative Linux

coLinux
coLinux is a port of the standard Linux kernel. In other words, coLinux is the Linux kernel that's modified to run cooperatively with another operating system. The host operating system (Windows or Linux) maintains control of the physical resources of the operating system, while the guest operating system (coLinux) is provided with a virtual abstraction of the hardware. The host operating system must provide the means to execute a driver in the privileged ring (ring 0) and export the means to allocate memory (see Figure 3).

Figure 1. coLinux executes as a process of the host operating system
coLinux executes as a process           of the host operating system
The root file system for coLinux is a regular file within the host operating system. To Windows it's just a regular file, but to coLinux it's an ext3 file system that can be read and written to.
Other features needed by the Linux kernel, such as networking or video access, are proxied externally. Networking is made accessible to coLinux through a TUN/TAP driver (which is covered in "Networking," below). In short, this driver provides user-space access to the Ethernet device so that packets can be transmitted and received. Access to the display is also proxied. Recall that X Window System is a protocol by which video output can be sent from one host to another. Therefore, by using an X Window System server on the host operating system, video output can be redirected to the available X server.
Now on to the installation of coLinux and configuration for both networking and video display.
Installing coLinux
Installing coLinux is surprisingly simple. There are a few steps involved, depending upon what you intend to do, but they're straightforward and worked on my Windows XP box without a single problem. This section explores installing coLinux and enabling services such as networking.
The first step is to download a coLinux distribution. Go to http://www.colinux.org and select Downloads from the left sidebar. If your browser doesn't take you to SourceForge, select the link to go there directly. Near the middle of the page is the coLinux-stable package. Download the coLinux executable file (at the time of this writing, the latest is coLinux-0.6.4.exe). The 0.6.4 release of coLinux is the 2.6.11 Linux kernel. When it has finished downloading, double-click the file to install.
After the usual license acceptance, you'll be asked for the components that you'd like to install. Leave these as is (all should be selected), including downloading a root file system image. To make things easier later on, change the destination folder for the coLinux install to c:\colinux\ because colinux is the standard install subdirectory from the perspective of configuration files.

When the installation program asks for a root file system image, select the Debian distribution because it's the smallest and extracts to only 1GB. Select Install to perform the install and root file system download.
When the install completes, you're not quite done yet. The next step is to open a folder to the install subdirectory to decompress the root file system.
The coLinux README file includes lots of additional information about other install options. This is available in the install subdirectory (c:\colinux). There will be an oddly named file that ends in .bz2. Rename this file to root_fs (this is the default root file system file in the configuration).
At this point, installation of coLinux is basically done. You can then start the coLinux daemon to run with Windows XP as follows (invoking through a Command Prompt window):
$ colinux-daemon.exe -c default.colinux.xml
            

After invoking the colinux-daemon, the boot window is displayed (see Figure 4). This provides the same boot information that you find in the traditional Linux boot. Notice that coLinux boots extremely fast.

Figure 2. The coLinux boot window
The coLinux boot window
A console window is also produced (see Figure 3) that attaches to the colinux-daemon. From this window, you can log in to coLinux to interact with the shell. The default username and password is root/root.

Figure 3. The coLinux virtual console (shell)
The coLinux virtual console           (shell)
From Figure 3, you can see that the coLinux console is made up of two sections: the traditional console and the virtual console that provides information about the monitor.
Networking
Networking support for coLinux is done from the Linux perspective when the install is complete. Recall that the TAP driver is loaded during the install. The TAP driver is a user-space tap onto the Ethernet device managed by the host operating system. The TAP driver allows the guest operating system to read or write raw Ethernet frames to a virtual Ethernet device (extended to user space). The virtual Ethernet device in user space then moves Ethernet frames to and from the real Ethernet device in the host operating system. Note that the TAP driver moves Ethernet frames, while the TUN driver is used for Internet Protocol (IP) frames.
For the TAP driver to work, the host operating system must share the available Ethernet device. To enable sharing within Windows XP, open the Network Connections panel from the Control Panel. Select the active local area connection, and then open the properties. Select the Advanced tab, and then select the check box for allowing other network users to connect through this computer's Internet connection (see Figure 6).

Figure 4. Local area connection properties for enabling network device sharing
Local area connection           properties for enabling network device sharing
After the network is shared, you can start coLinux and use the network as you would normally. This is shown in Figure 7 with the ping command.

Figure 5. Using the shared network device is transparent with coLinux through the TAP driver
Using the shared network           device is transparent with coLinux through the TAP driver
With little effort and configuration, coLinux provides networking out of the box.

X Window System
A console window is fine, but a graphical window manager would be ideal. With an open source X server, such as Xming, you can create xterms or use other graphical applications with coLinux. There are numerous documented options, such as Virtual Network Computing (VNC), but I'll show you how using Xming.
The first step is to download Xming from SourceForge. After installing, there's one file, called X0.hosts, that you need to update in the install subdirectory. It contains the remote hosts that are permitted access to the X server. Simply add the IP address of the machine that hosts the coLinux process. Start the Xming X server and coLinux, and then perform the following commands in coLinux:
colinux:~# export DISPLAY=192.168.1.3:0.0
colinux:~# xterm &
            

Note that the IP address specified here is the IP address of the coLinux host. After you execute the xterm command, a new xterm window is presented, as shown in Figure 6.

Figure 6. The xterm created with Xming
The xterm created with Xming
Extending coLinux
Whichever root file system you download, it may not include everything that you'd like. But you can easily extend the root file system. For example, with Debian GNU/Linux, you can use the Advanced Packaging Tool (APT), a package management system, to install new packages or update existing ones. The first step is to update the APT metadata, which maintains management information about the installed packages (including newly available packages and where to get them):
$ apt-get update
            

Now you can update your root file system with other packages that you need. For example, if you want to add the wonderful Ruby language to your root file system, you invoke the following command:
$ apt-get install ruby
            

In this way, you can use an existing root file system and tailor it to your specific needs. You can also rebuild coLinux from the sources if it lacks something that you need.
Advantages of coLinux
coLinux is a great way to use and experiment with Linux. Like Cygwin, it allows you to develop and execute Linux applications on the Windows operating system (through coLinux). You can also maintain the Linux operating system by installing, upgrading, or removing applications with apt-get.
Unlike Cygwin, you can execute Linux applications on coLinux without rebuilding. In this respect, coLinux is a real Linux operating system that runs (or cooperates) with the Windows operating system.
Another interesting advantage of coLinux is its portability. You can have a coLinux distribution with a custom set of applications on a given Windows host (within the root file system). You can move the root file system to another host, and then restart it. This allows for a mobile development platform where the compressed root file system fits on a standard Universal Serial Bus (USB) memory stick.
Finally, coLinux is fast because it's essentially running on the native hardware.
Problems with coLinux
The primary disadvantage of coLinux is that it has the ability to crash the entire machine (all cooperating operating systems) because the guest operating system runs in a privileged mode in the host kernel. It also has some dependencies on external software for normal operation (windows and networking support). Outside of this, it's quite easy to install and configure. In the many hours that I've used it, I've never seen a crash.

Thursday 17 May 2012

Basic SVN Commands

Here I'm gonna show you some basic SVN commands with some examples.

Checking out
svn co http://[hostname]/trunk

Checking in
svn ci

Viewing SVN information
This will display information, such SVN URL, revision number, etc.
svn info

Viewing SVN status
This will display information, such as files modified, added, deleted, etc.
svn status

Updating the local SVN repository
svn up

Viewing the diff
svn diff

Viewing SVN logs
svn log

Adding a file into SVN
svn add new_file.txt

Moving/Renaming a file from one place to another place
svn move old_file.txt new_file.txt

Deleting a file from SVN
svn del junk_file.txt

Reverting local changes in a file
svn revert whatever_file.txt

Reverting local changes recursively
svn revert -R *

Creating a branch/tag
svn copy http://[hostname]/trunk http://[hostname]/branches/1.0
svn copy http://[hostname]/trunk http://[hostname]/tags/1.0

De-commiting changes in the trunk
This will first do a diff between HEAD and rev 123 in the trunk and then do a dry-run before performing an actual merge.
svn diff -r HEAD:1234 http:/[hostname]/trunk
svn merge -r --dry-run HEAD:1234 http:/[hostname]/trunk
svn merge -r HEAD:1234 http:/[hostname]/trunk
svn ci

Merging changes from the branch to the trunk
Assume that the current directory is where the trunk code was checked out.
svn diff -r 1234:HEAD http://[hostname]branches/1.0
svn merge -r 1234:HEAD --dry-run http://[hostname]/branches/1.0
svn merge -r 1234:HEAD http://[hostname]/branches/1.0
svn ci

Merging changes from the trunk to the branch
Assume that the current directory is where the branch code was checked out.
svn diff -r 1234:HEAD http://[hostname]/trunk
svn merge -r 1234:HEAD --dry-run http://[hostname]/trunk
svn merge -r 1234:HEAD http://[hostname]/trunk
svn ci

Viewing SVN externals
svn propset svn:externals .

Editing SVN externals
svn propedit svn:externals .

Viewing who modified the file
svn blame whosefault.txt

Getting Started with GDB

GDB is a very powerful debugging tool for C/C++ and many other languages. Here I'm gonna show you how to get started with GDB.

testgdb.cpp
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;
  
string globalmsg = "Hello World";
  
void half(int& a) {
    a /= 2;
}
  
int whatever() {
    int i = 5;
    i *= 3;
    return i;
}
  
int main() {
    int a = 10;
    half(a);
    cout << a << endl;
    cout << whatever() << endl;
    return 0;
}

1. Compile the code
g++ -c -g -Wall -O0 testgdb.cpp
The -O0 flag is useful for debugging information because the compiler may do its own optimization that can eliminate some debugging information, such as -O2 flag for example.
2. Link it
g++ -o testgdb testgdb.o
3. Run it
gdb ./testgdb
After running this statement, there will be gdb prompt.
4. Set the breakpoint in line 18 and 19
break testgdb.cpp:18
break testgdb.cpp:19
5. See the list of breakpoints
info break
6. Remove the second breakpoint
delete 2
7. Run the program
run
8. See the current line
list
9. Step over to the next line
next
10. See the current line again
list
11. Step in to the half() function
step
12. Print the arguments
info args
13. Go to the next line
next
14. Print the value a now
print a
The new value should be 5.
15. Step out from half() function
finish
16. Print all the local variables
info locals
17. Set another breakpoint in line 13
break testgdb.cpp:13
18. Jump to that newly-set breakpoint
continue
19. Step over
next
20. Print the new value of i
print i
The value of i should be 15
21. Step out from the whatever() function
finish
22. Get the length of globalmessage string
print globalmessage.size()
23. Quit gdb
quit

I hope this brief introduction is useful. For more information, type
help <command>

Tuesday 3 April 2012

HowToUbootScriptcmd

U-boot is a very versatile universal opensource bootloader, a customized version of which is used in VT8500 and WM8505-based devices. It has a built-in mini-shell with some handy commands that can be accessed through a [[serial console]]. Alternatively, required command sequences to e.g. redefine boot parameters and load a custom OS (like the Linux kernel) can be put into a so-called scriptcmd file. This is basically just a plain text script for the U-boot’s shell with just some binary header added to it.
The useful fact is that by default VT8500/WM8505 versions of U-boot will happily execute a scriptcmd file put into a script/ folder on the first partition (FAT) of an SD card, which allows for a simple and non-destructive redefinition of the boot sequence.
Below are the simple steps to take to create your own scriptcmd file (assuming that you have the mkimage program from U-boot tools package installed already).
  • Create a plain text file with the commands you need and call it, for example, script.txt. In the simplest case its contents may be something like this:
setenv bootargs rootwait root=/dev/sda1
fatload mmc 0 0 /script/uImage
bootm 0
The first statement redefines the kernel command line to allow the first partition on a USB drive (/dev/sda1) to be used as a root filesystem. The second one loads /script/uImage from the first partition of the SD card to a memory address 0. The third one executes the Linux kernel uImage that we've just loaded into memory.
  • Generate the final scriptcmd file (the one with a binary header) by issuing a command like this:
mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n “My scriptcmd” -d script.txt scriptcmd
  • Put the scriptcmd file together with your kernel uImage to a script/ folder on the first (FAT) partition on an SD card and turn your device on with this card inserted. If everything is OK, your kernel should boot up.

Pthread Example


Set up Ubuntu to use static ip address

 had bit problem when using tftp server to boot NGW100, every time DHCP tend to find a different ip address for my PC, which is not what I wanted;I don’t want to change NGW100 boot args everytime to use different TFTP server or NFS server.
Here is what I do:
If Your Ubuntu System has set to use DHCP, you will want to change it to a static IP address here is simple tip
open the /etc/network/interfaces file.
sudo vi /etc/network/interfaces
If you are using DHCP for your primary network card which is usually eth0, you will see the following lines
auto eth0
iface eth0 inet dhcp
As you can see, it’s using DHCP right now. We are going to change dhcp to static, and then there are a number of options that should add and here is the example and you can change these settings according to your network settings.
auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway 192.168.1.1
Restart the neworking service using the following command
sudo /etc/init.d/networking restart
My interfaces file like this:
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
        address 192.168.1.59
        netmask 255.255.255.0
        broadcast 192.168.1.255
        network 192.168.1.0
        gateway 192.168.1.2

PThread example
    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    void *print_message_function( void *ptr );
    main()
    {
         pthread_t thread1, thread2;
         char *message1 = “Thread 1″;
         char *message2 = “Thread 2″;
         int  iret1, iret2;
        /* Create independent threads each of which will execute function */
         iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
         iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
         /* Wait till threads are complete before main continues. Unless we  */
         /* wait we run the risk of executing an exit which will terminate   */
         /* the process and all threads before the threads have completed.   */
         pthread_join( thread1, NULL);
         pthread_join( thread2, NULL);
         printf(“Thread 1 returns: %d “,iret1);
         printf(“Thread 2 returns: %d “,iret2);
         exit(0);
    }
    void *print_message_function( void *ptr )
    {
         char *message;
         message = (char *) ptr;
         printf(“%s “, message);
    }

Thursday 9 February 2012

How To Compile GTK Application For Arm


1. add the following lines to your /etc/apt/sources.list at the bottom

deb http://scratchbox.org/debian/ apophis main
deb http://scratchbox.org/debian/ hathor main


2.

$ sudo apt-get update
$ sudo apt-get install scratchbox-core scratchbox-libs scratchbox-devkit-qemu scratchbox-devkit-debian scratchbox-devkit-doctools scratchbox-devkit-perl scratchbox-toolchain-host-gcc scratchbox-toolchain-cs2007q3-glibc2.5-arm7 scratchbox-toolchain-cs2007q3-glibc2.5-i486  scratchbox-devkit-svn scratchbox-devkit-git scratchbox-devkit-apt-https


3.
run
$ sudo /scratchbox/sbin/sbox_adduser $USER

4.
$/scratchbox/login

5.
after login
$ /scratchbox/login

Welcome to Scratchbox, the cross-compilation toolkit!

Use 'sb-menu' to change your compilation target.

See /scratchbox/doc/ for documentation.

[sbox-FREMANTLE_X86: ~]>

6.
[sbox-FREMANTLE_X86: ~]> sb_menu





a)You will enter the main menu:
Select the Setup option.
b)First it will ask if you want to create a new target or change the configuration of a previously created target:
Select the NEW option.

c)Since we're creating a new target we need to specify a name:

We use "MYTARGET" as the target name in this example.

d)Next, the setup will ask which toolchain should be used to compile programs:
We selected gcc 3.3 that creates binaries for the ARM architecture and links them against glibc 2.3.

e)We can select optional development tools:
At this point we don't need any. Just select the DONE option to proceed.

f)After development kit selection the CPU-transparency method is chosen:
The QEMU emulator is sufficient for our example target, so select 'qemu-arm'.

g)Now the setup is done, but sb-menu asks if we want to extract a rootstrap and/or install system files on the target. Answer no to the rootstrap question but choose to install files.

h)You can install the C-library (and related binaries) provided by the toolchain, some standard config files in /etc, config files required by the selected devkits (we have not selected any) and some target-specific binaries:

i)The default selection is fine, so you can just press enter to install them.

Everything is now ready and we can activate the target by answering yes to the last question.



7.
Now we need to compile gtk packages for building our gtk application



GTK+, or the GIMP Toolkit, is a multi-platform toolkit for creating graphical user interfaces. Offering a complete set of widgets. GTK+ is suitable for projects ranging from small one-off tools to complete application suites.

I have download the below softwares to start with.
atk-1.30.0: http://ftp.gnome.org/pub/GNOME/sources/atk/1.30/atk-1.30.0.tar.bz2

cairo-1.8.10: http://cairographics.org/releases/cairo-1.8.10.tar.gz

DirectFB-1.4.3: http://directfb.org/downloads/Core/DirectFB-1.4/DirectFB-1.4.3.tar.gz

expat-2.0.1: http://sourceforge.net/projects/expat/

fontconfig-2.8.0: http://fontconfig.org/release/fontconfig-2.8.0.tar.gz

freetype-2.3.12: http://sourceforge.net/projects/freetype/files/

glib-2.24.0: http://ftp.gnome.org/pub/gnome/sources/glib/2.24/glib-2.24.0.tar.bz2

gtk+-2.20.1: http://ftp.gnome.org/pub/gnome/sources/gtk+/2.20/gtk+-2.20.1.tar.bz2

jpeg-8b: http://www.ijg.org/files/jpegsrc.v8b.tar.gz

tslib: http://www.zelow.no/floppyfw/download/Development/src/

libpng-1.2.39: http://sourceforge.net/projects/libpng/files/

libxml2-2.7.7: ftp://gd.tuwien.ac.at/pub/libxml/libxml2-2.7.7.tar.gz

pango-1.28.1: http://ftp.gnome.org/pub/gnome/sources/pango/1.28/pango-1.28.1.tar.bz2

pixman-0.18.2: http://cairographics.org/releases/pixman-0.18.2.tar.gz










tiff-3.9.2: http://download.osgeo.org/libtiff/tiff-3.9.2.tar.gz

zlib-1.2.5: http://zlib.net/zlib-1.2.5.tar.gz


With scratchbox and qemu on the host machine cross compiling was straightforward.

Cross compiling order

1) tslib
sb2 ./configure --prefix=/opt/ram
sb2 make install

2) zlib
since glib require zlib
sb2 ./configure --prefix=/opt/ram --shared
sb2 make install

3) glib
LDFLAGS=-L/opt/ram/lib CPPFLAGS=-I/opt/ram/include/ sb2 ./configure --prefix=/opt/ram --disable-static --with-html-dir=/tmp/dump
sb2 make install

4) atk
export PKG_CONFIG_PATH=/opt/ram/lib/pkgconfig
LDFLAGS=-L/opt/ram/lib CPPFLAGS=-I/opt/ram/include/ sb2 ./configure --prefix=/opt/ram --disable-glibtest
sb2 make install

5) jpeg-8b
sb2 ./configure --prefix=/opt/ram --enable-shared --enable-static
sb2 make install


6) libpng
LDFLAGS=-L/opt/ram/lib CPPFLAGS=-I/opt/ram/include/ sb2 ./configure --prefix=/opt/ram
sb2 make install

7) expat-2.0
sb2 ./configure --prefix=/opt/ram
sb2 make install

8) freetype
sb2 ./configure --prefix=/opt/ram
sb2 make install

9)libxml
LDFLAGS=-L/opt/ram/lib CPPFLAGS=-I/opt/ram/include/ sb2 ./configure --prefix=/opt/ram --without-python
sb2 make install

10)freetype-2.3.12
LDFLAGS=-L/opt/ram/lib CPPFLAGS=-I/opt/ram/include/ sb2 ./configure --prefix=/opt/ram --with-freetype-config=/opt/ram/bin/freetype-config

11) tiff -- not used gcc 4.3.2
LDFLAGS=-L/opt/arm/gst/lib CPPFLAGS=-I/opt/arm/gst/include/ sb2 ./configure --prefix=/opt/ram --enable-shared
sb2 make install

12) DirectFB
LDFLAGS=-L/opt/arm/gst/lib CPPFLAGS=-I/opt/arm/gst/include/ sb2 ./configure --prefix=/opt/ram --with-gfxdrivers=none --with-inputdrivers=all --enable-png --enable-jpeg --enable-tiff=no --enable-zlib --enable-sdl=no --enable-gif=no --disable-x11
sb2 make install

13) pixman-0.18.2
LDFLAGS=-L/opt/arm/gst/lib CPPFLAGS=-I/opt/arm/gst/include/ sb2 ./configure --prefix=/opt/ram --disable-gtk

14) cairo
LDFLAGS=-L/opt/ram/lib CPPFLAGS=-I/opt/ram/include/ sb2 ./configure --prefix=/opt/ram --without-x --disable-xlib --disable-xlib-xrender --enable-directfb --enable-freetype --disable-win32 --enable-pdf --enable-ps --enable-svg --enable-png

15) Pango
LDFLAGS=-L/opt/ram/lib CPPFLAGS=-I/opt/ram/include/ sb2 ./configure --prefix=/opt/ram --without-x

16 gtk
LDFLAGS=-L/opt/ram/lib CPPFLAGS=-I/opt/ram/include/ sb2 ./configure --prefix=/opt/ram --with-gdktarget=directfb --without-x --without-libtiff --disable-glibtest --disable-cups

Now to compile a simple helloworld.c pro-gramme with these libraries.

export PKG_CONFIG_PATH=/opt/ram/lib/pkgconfig

[arm-linux~]>arm-linux-gcc -Wall -g helloworld.c -o helloworld `pkg-config --cflags gtk+-2.0` `pkg-config --libs gtk+-2.0` -Wl,-O1 -Wl,-rpath,/opt/ram/lib

Tuesday 10 January 2012

Linux Directory Structure (File System Structure) Explained with Examples


Have you wondered why certain programs are located under /bin, or /sbin, or /usr/bin, or /usr/sbin?
For example, less command is located under /usr/bin directory. Why not /bin, or /sbin, or /usr/sbin? What is the different between all these directories?
In this article, let us review the Linux filesystem structures and understand the meaning of individual high-level directories.


1. / – Root

  • Every single file and directory starts from the root directory.
  • Only root user has write privilege under this directory.
  • Please note that /root is root user’s home directory, which is not same as /.

2. /bin – User Binaries

  • Contains binary executables.
  • Common linux commands you need to use in single-user modes are located under this directory.
  • Commands used by all the users of the system are located here.
  • For example: ps, ls, ping, grep, cp.

3. /sbin – System Binaries

  • Just like /bin, /sbin also contains binary executables.
  • But, the linux commands located under this directory are used typically by system aministrator, for system maintenance purpose.
  • For example: iptables, reboot, fdisk, ifconfig, swapon

4. /etc – Configuration Files

  • Contains configuration files required by all programs.
  • This also contains startup and shutdown shell scripts used to start/stop individual programs.
  • For example: /etc/resolv.conf, /etc/logrotate.conf

5. /dev – Device Files

  • Contains device files.
  • These include terminal devices, usb, or any device attached to the system.
  • For example: /dev/tty1, /dev/usbmon0

6. /proc – Process Information

  • Contains information about system process.
  • This is a pseudo filesystem contains information about running process. For example: /proc/{pid} directory contains information about the process with that particular pid.
  • This is a virtual filesystem with text information about system resources. For example: /proc/uptime

7. /var – Variable Files

  • var stands for variable files.
  • Content of the files that are expected to grow can be found under this directory.
  • This includes — system log files (/var/log); packages and database files (/var/lib); emails (/var/mail); print queues (/var/spool); lock files (/var/lock); temp files needed across reboots (/var/tmp);

8. /tmp – Temporary Files

  • Directory that contains temporary files created by system and users.
  • Files under this directory are deleted when system is rebooted.

9. /usr – User Programs

  • Contains binaries, libraries, documentation, and source-code for second level programs.
  • /usr/bin contains binary files for user programs. If you can’t find a user binary under /bin, look under /usr/bin. For example: at, awk, cc, less, scp
  • /usr/sbin contains binary files for system administrators. If you can’t find a system binary under /sbin, look under /usr/sbin. For example: atd, cron, sshd, useradd, userdel
  • /usr/lib contains libraries for /usr/bin and /usr/sbin
  • /usr/local contains users programs that you install from source. For example, when you install apache from source, it goes under /usr/local/apache2

10. /home – Home Directories

  • Home directories for all users to store their personal files.
  • For example: /home/john, /home/nikita

11. /boot – Boot Loader Files

  • Contains boot loader related files.
  • Kernel initrd, vmlinux, grub files are located under /boot
  • For example: initrd.img-2.6.32-24-generic, vmlinuz-2.6.32-24-generic

12. /lib – System Libraries

  • Contains library files that supports the binaries located under /bin and /sbin
  • Library filenames are either ld* or lib*.so.*
  • For example: ld-2.11.1.so, libncurses.so.5.7

13. /opt – Optional add-on Applications

  • opt stands for optional.
  • Contains add-on applications from individual vendors.
  • add-on applications should be installed under either /opt/ or /opt/ sub-directory.

14. /mnt – Mount Directory

  • Temporary mount directory where sysadmins can mount filesystems.

15. /media – Removable Media Devices

  • Temporary mount directory for removable devices.
  • For examples, /media/cdrom for CD-ROM; /media/floppy for floppy drives; /media/cdrecorder for CD writer

16. /srv – Service Data

  • srv stands for service.
  • Contains server specific services related data.
  • For example, /srv/cvs contains CVS related data.

Monday 9 January 2012

How to Run a C program/Shell script with root privilege

This method for creating a script that runs as root automatically.
  1. Open a text editor, and type up your script:
    #!/bin/sh
    program1
    program2
    ...
  2. Save the file as something.sh.
  3. Open a terminal, and enter the following commands:
    $ su
    [enter password]
    chown root:root something.sh
    chmod 4755 something.sh
    exit
    
  4. Then, finally run it with ./something.sh, and it'll have root access!
...or not. Most likely, you'll get the same error messages that you did before you ran those commands. If your script does actually work,
Take the down part for executing it.

The problem The instructions are fairly straightforward. Create the shell script that you want to execute, and change the owner and group to root (chown root:root). Now comes the command that's supposed to do the magic:
chmod 4755

Except it doesn't. Well, the truth is actually that the setuid bit is disabled on a lot of *nix implementations due the massive security holes it incurs. If the method originally mentioned doesn't work for you, chances are that your Linux distribution has disabled setuid for shell scripts.

The solution(s) One way of solving this problem is to call the shell script from a program that can use the setuid bit. For example, here is how you would accomplish this in a C program:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
   setuid( 0 );
   system( "/path/to/script.sh" );

   return 0;
}

chown root:root runscript
chmod 4755 runscript

Now, you should be able to run it, and you'll see your script being executed with root permissions.
Conclusion With all that said, running shell scripts with setuid isn't very safe, and the distro designers had a pretty good idea of what they were doing when many of them disabled it. If you're running a multiuser Unix environment and security is an asset for you, make sure that your scripts are secure. A single slip can result in the compromising of an entire network. Only use them when absolutely necessary, and make sure you know exactly what you're doing if you do decide to use them.