Monday, 10 October 2011

PYTHON BYTECODE

                                                        In this blog post we are going to look at the internal representation of the python byte code.When we try to execute a python script there a some common steps which will happen.
1. compile the code and transform the code script to an intermediate representation called byte code .
2. The byte code will be executed by a virtual machine.
By doing this python will become platform independent as the python byte code is not interpreted by the real hardware.

    Internals of python bytecode

Now let us dig into the internals of a python bytecode . The python bytecode is divided into 3 parts mainly
1. first four byte magic number.
The starting of four bytes of a python byte code will be a magic number . The magic number will unique for a version python .
2. second four byte time stamp.
The time stamp field will modified each time the script file is modified . If the script file is modified the python script should be recompiled
and a new byte code should be produced .
3. rest of the code will be the marshelling code .
Thre rest of the code is the marshelling code . Means python byte code instructions along with its operands will be sequencially encoded in this
region.

    Manually compiling a python script.

To manually compile a python code you can use py_compile module.
for example make a python script .

$vim test.py
i = 1


now to compile test.py you can use this script given below.
import sys,py_compile

def main():
  py_compile.compile(argv[1])

if __name__ == '__main__':
  main(sys.argv)
let us call the above script file as compile.py
$python compile.py test.py
This will produce a file named test.pyc in the directory where you have executed the above script .

if you want to see what is inside the test.pyc you can do it by using the linux command.
$od -tx1 test.pyc
0000000 d1 f2 0d 0a fb 73 8e 4e 63 00 00 00 00 00 00 00
0000020 00 01 00 00 00 40 00 00 00 73 0a 00 00 00 64 00
0000040 00 5a 00 00 64 01 00 53 28 02 00 00 00 69 01 00
0000060 00 00 4e 28 01 00 00 00 74 01 00 00 00 69 28 00 
0000100 00 00 00 28 00 00 00 00 28 00 00 00 00 73 07 00
0000120 00 00 74 65 73 74 2e 70 79 74 08 00 00 00 3c 6d
0000140 6f 64 75 6c 65 3e 01 00 00 00 73 00 00 00 00
0000157
The above thing is the hex dump of my test.pyc file . as you can see the first 4 bytes.
is the magic number.
is the time stamp.

to understand the rest of the part we need to see the python byte_code instructions opcode. you can see all the python byte code and its opcode
hear


    Disassembling the python bytecodes

To dis assemble the python code you can use dis module.
$python -m dis test.py

0 LOAD_CONST 0 (1)
3 STORE_NAME 0 (i)
6 LOAD_CONST 1 (None)
9 RETURN_VALUE
this is the internal representaion of the code i = 1 in python byte code
if you wan tot see the full dis assembly of the bytecode test.pyc you can use the script which is given below.

import sys,dis

def main(argv):
  fp = open(argv[1],'r')
  byte_code_string = fp.read()
  dis.dis(byte_code_string)

if __name__ == '__main__':
  if len(sys.argv) < 2:
    print 'usage: python pydis.py '
  else:
    main(sys.argv)
    Writing your own dis assembler

Now with the above details given if you are interested try to make a dis assembler . you can also check this code
https://github.com/tonylijo/python-byte-code-disassembler

Wednesday, 21 September 2011

Linux kernel module programming

                                                           A kernel module is a piece of code which can be dynamically loaded or unloaded from the system to extend its functionality . There is no need to compile the whole kernel source code for adding a single functionality. also you need not reboot the system after adding the module . This is one of the features of the micro kernel architecture.
so let us write our conventional starting code .
Hello world module.
#include
int int_module(void)
{
   printk(" Hello, world \n");
   return 0;
}

void cleanup_module(void)
{
   printk(" bye bye world \n");
}
as you can see in the code above there are two functions
1) init_module .
2) cleanup_module
init_moudule is some what like the main fuction in the usual code this is where the kernel module starts working .It is called immidiately after insmod command is executed.
The cleanup_module is the exit function it is called immidiately after the rmmod comman is executed.
As given in the code above , we are using printk function instead of printf function .Heare our module is going to run in kernel space not as a user program so we don't use the user library functions so we need the kernels own printf and that is our printk function .



Compiling the kernel module
for compiling the kernel module you need to compile the kernel module. For this you need to create a make file

Makefile:
obj-m: hello-world.o


now you need to execute the command
make -C /usr/src/linux-3.0/ M=`pwd` modules
After executing the above command do an ls in the current directory you can see that there will be a file named hello-world.ko

Loading the kernel module to the running kernel.

To load the kernel to the currently running kernel we need to use some commands

commands for loading

1)insmod
2)modprob

command for unloading the module

1)rmmod

now use the command
insmod hello-world.ko
if you didnot see a print

Wednesday, 31 August 2011

Configuring UML kernel For Linux Kernel Development.

It is always a good idea to create a simulated environment while doing kernel programming, because playing with kernel may lead to data corruption, system hang-ups and all such nasty things. This post may help you to configure User Mode Linux . User Mode Linux is just like an operating system which is running in user space. So you can do all your experiments on this user space kernel with a less probability of serious damages.


Installing/downloading The appropriate Packages.
You should download / install the following packages.
1)Linux kernel Source 2.6.xx
2)UML Utilities
You can download a latest kernel from www.kernel.org
Extract the kernel to a directory and change your current working directory to that directory.
In my case I have installed the kernel from the Debian's package manager
host# apt-get install kernel-source
host# apt-get install uml-utilities
host# cd /usr/src/
host# bunzip2 linux-source-2.6.32.tar.bz
host# tar -xvf linux-source-2.6.32.tar
host# cd linux-source-2.6.32/

Compiling The UML Kernel
Now you have to compile your linux kernel source for uml architecture . The compilation is similar to the usual compilation.
host# make mrproper
host# make mrproper ARCH=um
host# make defconfig ARCH=um
if you have to compile with a customized config file you can use make menuconfig or make xconfig and customize the config file.
host# make Linux ARCH=um
The above command will create an executable kernel file called Linux.
host# make modules ARCH=um
The above command will create the loadable modules

Creating the Filesystem
Now lets create a root filesystem for our uml kernel.
host# dd if=/dev/zero of=root_fs bs=4k count=1M
this will create a file named root_fs of size around 4G, after this we can write a filesystem onto this root_fs file
host# mkfs.ext3 root_fs
now you have an ext3 file system in the file root_fs. so you can mount that file to a directory .
host# mkdir rootdir/
host# mount -o loop root_fs rootdir/
now you need all the root directory tree should be place on to this directory in our case say rootdir.For this we can use debootstrap command.
host# debootstrap squeeze rootdir/ file:/media/cdrom0/
I created a root file system for the squeeze release from the installation dvd of Debian Squeeze.if you don't have a installation DVD you retrieve the files form the Debian squeeze remote repository. for this you can read the man page of debootstrap.After completion of debootstraping if you go to that directory<rootdir> you can see the complete root directory structure in that directory. now you have a complete directory structure so you can now install the modules to the existing directory structure.
host# make modules_install INSTALL_MOD_PATH=rootdir/ ARCH=um
now your compiled loadable module files will the copied to rootdir/lib/modules/ . now you have to set the password for the root in the filesystem.
host# cd rootdir
host# chroot .
by executing the above command your root of the filesystem tree of the host will be changed to the current working directory . now by executing the passwd command you can update the passward .
host# passwd
set the passward .
host# exit
now you have to create a swap filesystem.
host# dd if=/dev/zero of=swap_file bs=4k count=50k
host# mkswap swap_file

now we should edit some of the configuration files of our newly created filesytem .
1.etc/inittab
2.etc/fstab
3.etc/udev/links.conf

edit file etc/inittab keep the line given below and  delete all such similar lines.

1:2345:respawn:/sbin/getty 38400 tty1


edit file etc/fstab as

/dev/ubd0    /    ext3    defaults 0    0
/dev/ubd1    none    swap    sw     0    0
proc        /proc     proc    defaults 0     0


edit file etc/udev/links.conf

M ubd0    b 98 0
M ubd1    b 98 16
M ubd2    b 98 32
M ubd3    b 98 48
M ubd4    b 98 64
M ubd5    b 98 80
M ubd6    b 98 96

#host umount rootdir/
Networking
To configure networking in uml machine we will use the tuntap methord.
<to--do > write what is tuntap</to--do>
you can create a tap0 interface using the tunctl coammdn
#host tunctl -t tap0
#host ifconfig tap0 192.168.2.33 up
now you are redy to run the code uml kernel
#host ./linux ubd0=root_fs ubd1=swap_file mem=256M eth0=tuntap,tap0
after executing the above command you will get a console on which you can login with the password that you have set using the passwd command
now in the virtual machine you have to set up the the ip of eth0
#host ifconfig eth0 192.168.2.2
#host route add default gw 192.168.2.33

now you have to write some rules for iptable if we want to connect to some public network.
host# echo 1 > /proc/sys/net/ipv4/ip_forward
host# iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
host# iptables -A FORWARD -i eth1 -o tap0 -m state --state RELATED,ESTABLISHED -j ACCEPT
host# iptables -A FORWARD -i tap0 -o eth1 -j ACCEPT
now to start the virtual machine
host# ifup tap0
host# ./linux ubd0=root_fs ubd1=swap_file mem=256M eth0=tuntap,tap0
now you will get a login window if all the above things works fine.To check the whether the connection is ok you can ping to the host machine
virtual-machine# ping 192.168.2.33
virtual-machine# ping 192.168.1.7
virtual-machine# ping google.com

Monday, 21 March 2011

Foss cell gec sreekrishnapuram

Foss cell has been setup in our college by a group of Linux enthusists , This is a group of  Open Source Software Enthusiasts from Govt. Engineering College, sreekrishnapuram . The main objective is to bring together students and users to explore, discuss and share knowledge on usage of open source software  .  As part of first activity of FOSS cell GEC Sreekrishnapuram , a class on linux installation was conducted by me, syamkrishnan and najeeb sir.This was made possible due to the immense support extended to us by our HOD and lab staff.The class started with the indroduction session on linux and unix ,its ethics,GPL license etc on 14th march 2011 . The next two sessions on 16th and 17th march were workshops on 'How to install linux successfully' . Installation CDs ware given to groups of 8 students each . 95% of the students succeeded in their first attempt itself.Linux commands were also taught in the second and third workshop.The response from students was really great.The students of all semesters participated in this . The class was very effective and many students described it as highly resourcefull .I saw many students installing linux on their laptops many number of times and were trying out different distributions of linux.So I assume that the students were highly motivated by these classes.The number of students has increased since then .We look upon it as a positive response. We welcome any kind of feedback on the classes ,it's pros and cons and how students would like us to improve upon it,

Thank you!

Wednesday, 8 September 2010

python

Python is simple real programming language. It's use comes mainly for automation purpuses as shell and pearl is being used. python is applicable to larger problem domain than in shell or pearl with the help of its build in flexible data structures.
python gives more structural support for large programs than bash and pearl.
python offers much more error checking than c.
python has more flexible data structures like flexible arrays and dictionaries.
python allows to split the program into several modules and these modules can be reused.
python has a collection of build in modules
python allows the programs to be written in a more readable form.
python saves the software development time as it is having the following features.
1)The high level data structure and the map-reduce operations allows you to do complex jobs in single lines.
2)Statement grouping is done by indentation instead of braces , this will make code more readable and saves a considerable amount of time when writing large programs.
3)No variable declaration is required as the type of the variable is found while its first assignment.
python is extensible(ie, if you known c coding you can write codes for new build in functions and modules.)
So what do you think , isn't python awesome .
To learn more you should read the online python tutorial and also write small programs along with it.

Monday, 15 March 2010

Connect to internet via bluetooth

Connect to internet via bluetooth

----------------------------------

From linux systems you can connect to internet from

your phone through bluetooth. For this you need to edit

the configuration file



edit /etc/wvdial.conf as follows





***************************************************



[Dialer bluetooth]

Modem = /dev/rfcomm0



[Dialer usb]

Modem = /dev/ttyACM0

Modem Type = USB Modem



[Dialer Defaults]

Modem = /dev/ttyACM0

Init1 = ATZ

Init2 = ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0

Stupid Mode = yes

Modem Type = USB Modem

Phone = *99#

New PPPD = yes

nit6 = AT+CGDCONT=1,"IP","internet"

ISDN = 0

Username = b

Password = a

Baud = 460800

*****************************************************

now you need to type some commands in the teminal



i will demonstrate it in some steps





step1:

>hcitool scan

this command will give you Bluetooth device's address

for example the output looks like this

Scanning ...

00:1B:AF:F2:DE:1C Tòñý£íjøjôßë

00:1E:7D:4F:97:71 nibas





step2:

>rfcomm connect 0 00:1B:AF:F2:DE:1C

replace the bluetooth device address given above by yours

now pair the device



step3:

>wvdial bluetooth



now you will be connected





to check the connectivity try

>ping google.com

Tuesday, 28 July 2009

compile linux kernel yourself

Download a kernel source code ,if it is a compressed source code decompress it and then enter the directory.
To configure your kernel according to your needs you can type any of the following commands
* make menuconfig (ncurses based )
* make config (text based)
* make Xconfig (X11 based)
* make gconfig (gui based).
After configuring the kernel u can type makedep (if u r using kernel source less than or equal to 2.4 else this step is not needed),
then type the command makebzImage (if u r using kernel source less than or equal to 2.4 else this step is not needed)then type make modules (if u r using kernel source less than or equal to 2.4 else this step is not needed) if you r using 2.6 kernel then you can avoid steps after make menuconfig
and just type make -j2 or j4 according to the no of processors
after this step just type the command make modules_install then make install
Now a kernel image will be formed in the /boot directory
if no initrdimg if formed for the new kernel just make it manualy by the command mkinitramfs /tmp/initrd[version].img [version]
now type cp /tmp/initrd[version].img /boot
Now we shall edit the grub as
title name of the kernel
root (hd0,X)#where x is the partition no of your root filesystem minus 1
kernel vmlinuz[version]
initrd intrd[version].img