Search This Blog

Monday, March 18, 2013

Eclipse - Ctrl+Space does it all!!! :D

I am a huge Eclipse IDE fan. It reduces development time by a huge factor. If you are well-versed with the keyboard shortcuts, writing a java program in eclipse takes few minutes once your logic is in place. Browsing through other related projects, adding jars to your project, building and testing, it makes it so much simpler!!!! Whoever came up with this IDE funda - wow :) I remember writing programs on my notepad!! Of course, you realize how dependent you have become on IDE's during Coding Interviews..lol... imagin pressing Ctrl+Space on collabedit so it would suggest functions for the String class... :P.

Anyway, getting a hang of project set ups in Eclipse can sometimes be a pain and might make you not like Eclipse, which I dont wannnttt :) So to increase the fan following for eclipse, I'll share a few project setups specific to the development projects that one might use.


Setting up web development environment in eclipse



1. Make sure you have java - jre1.6.0_07 and jre6
2. Set environment variables for the same

CLASSPATH = C:\Program Files\Java\jre1.6.0_07\lib\ext\QTJava.zip;%CATALINA_HOME%\common\lib;%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar

JAVA_HOME = C:\Program Files\Java\jre1.6.0_07

JRE_HOME = C:\Program Files\Java\jre1.6.0_07

PATH = C:\oracle\product\10.2.0\client_1\bin;C:\FileNet\IDM;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\system32\WBEM;C:\Program Files\QuickTime\QTSystem\;C:\Program Files\Microsoft SQL Server\80\Tools\Binn\;C:\Program Files\Microsoft SQL Server\90\Tools\binn\;C:\Program Files\Microsoft SQL Server\90\DTS\Binn\;C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Program Files\Tealeaf;%CATALINA_HOME%\bin;C:\Program Files\Java\jre1.6.0_07\bin


3. Create your dynamic web project
4. Go to project->Properties->Server
Add server
Download and install Tomcat Apache 7 through eclipse

5. Set up the server properties as follows


6. Set environ variable for catalina
CATALINA_HOME = C:\apache-tomcat-7.0.29

7. Change port number in the server.xml file of Tomcat if needed…only 8080-8081

8. Create jsps in WEB-INF

9. Create servlets in Java Resources

10. Make sure to do servlet mapping in web.xml

11. This is how the hierarchy/ folder structure will look like.





 Hope it helps!! I will come back with maven set up in Eclipse :)
Cheers :)

Friday, July 15, 2011

Have you ever wondered this about C?

I came across a wonderful post which commented on some puzzling and amazing things about C language. I am re-posting the same here.

  1. Can you guess why there is no distinct format specifier for ‘double’ in the printf/scanf format string, although it is one of the four basic data types? (Remember we use %lf for printing the double value in printf/scanf; %d is for integers).
  2. Why is some of the precedence of operators in C wrong? For example, equality operators (==, !=, etc) have higher precedence than logical operators (&&, ||).
  3. In the original C library, has all operations done in double precision, i.e., long float or double (and not single precision, i.e., float). Why?
  4. Why is the output file of the C compiler called a.out?
Answers to these questions are really interesting:

Answers:

  1. 1 In older versions of C, there was no ‘double’—it was just ‘long float’ type—and that is the reason why it has the format specifier ‘%lf’ (‘%d’ was already in use to indicate signed decimal values). Later, double type was added to indicate that the floating point type might be of ‘double precision’ (IEEE format, 64-bit value). So a format specifier for long float and double was kept the same.
  2. The confusion in the precedence of the logical and equality operators is the source of numerous bugs in C. For example, in (a && b == c && d), == has higher precedence than &&. So it is interpreted as,(a && (b == c) && d), which is not intuitive.
    There is a historical background for this wrong operator precedence. Here is the explanation given by Dennis Ritchie [1]: “Early C had no separate operators for & and && or | and ||. Instead it used the notion (inherited from B and BCPL) of ‘truth-value context’: where a Boolean value was expected, after ‘if’ and ‘while’ and so forth; the & and | operators were interpreted as && and || are now; in ordinary expressions, the bit-wise interpretations were used. It worked out pretty well, but was hard to explain. (There was the notion of ‘top-level operators’ in a truth-value context.)
    “The precedence of & and | were as they are now. Primarily at the urging of Alan Snyder, the && and ||operators were added. This successfully separated the concepts of bit-wise operations and short-circuit Boolean evaluation. However, I had cold feet about the precedence problems. For example, there were lots of programs with things like: if (a==b & c==d) ...
    “In retrospect it would have been better to go ahead and change the precedence of & to higher than ==, but it seemed safer just to split & and && without moving & past an existing operator.”
  3. Since C was originally designed for writing UNIX (system programming), the nature of its application reduced the necessity for floating point operations. Moreover, in the hardware of the original and initial implementations of C (PDP-11) floating point arithmetic was done in double precision (long float or double type) only. Writing library functions seemed to be easy if only one type was handled. For these reasons, the library functions involving mathematics () were done for double types, and all the floating point calculations were promoted and were done in double precision only. For the same reason, when we use a floating point literal, such as 10.0, it is treated as double precision and not single precision.
  4. The a.out stands for ‘assembler.output’ file [2]. The original UNIX was written using an assembler for the PDP-7 machine. The output of the assembler was a fixed file name, which was a.out to indicate that it was the output file from the assembler. No assembly needs to be done in modern compilers; instead, linking and loading of object files is done. However, this tradition continues and the output of ccis by default a.out!
Reference:
http://www.linuxforu.com/teach-me/%EF%BB%BFsome-puzzling-things-about-c-language/

Wednesday, October 7, 2009

DLL Injection

DLL Injection is a method by which some code is run within the address space of any process by forcing it to load a dynamic-link library.

Library interposition is a useful technique for tuning performance, collecting runtime statistics, or debugging applications. With dynamic linking, you can intercept any function call an application makes to any shared library. Once you intercept it, you can do whatever you want in that function, as well as call the real function the application originally intended to call.

However this feature may also be exploited for some malicious use.

In Linux, the environment variable LD_PRELOAD allows specified libraries to be loaded before any other code.

This variable if set to some code which has a function in it with the constructor attribute, then the control will always go the library code first and then to any other code.

lets look at an example,
The code which will be loaded dynamically :


//demo.c

void __attribute__((constructor)) init() {
printf("How did it come to me??? ;) ;) ");
}

//End of file demo.c

$ gcc -shared demo.c -o demo.so -fPIC
$ export LD_PRELOAD=$PWD/demo.so true

Now execute any command :

$ ls
How did it come to me??? ;) ;) a aj.c a.out arr.s demo.so demo.c

$ gcc a.c
How did it come to me??? ;) ;) How did it come to me??? ;) ;) How did it come to me??? ;) ;) How did it come to me??? ;) ;) How did it come to me??? ;) ;)

$ ps
How did it come to me??? ;) ;) PID TTY TIME CMD
24126 pts/61 00:00:00 ps
28996 pts/61 00:00:00 bash



It doesnt end here...There is something more to it.
As the man page for LD_PRELOAD states "This can be used to selectively override functions in other shared libraries."

see this :

// --- demo.c ---

int printf(char *s, ...) {
fprintf(stdout, "Where is ur printf??? ;) ;) ");
}

// End of demo.c

// --- a.c ----

int main()
{
printf("Hello world");
}

// End of a.c

$ gcc a.c
$ ./a.out
Where is ur printf??? ;) ;)



One way out is.... using static-linking.....
eg :
For the above printf wala code

$ gcc -static a.c
$ ./a.out
Hello



This is because if static linking is done, the control never goes to the dynamic linker as u see below :

$ readelf -d a.out

There is no dynamic segment in this file.

Sunday, October 4, 2009

Allocating memory on heap and stack

The very famous "malloc" allocates space on the heap and returns a pointer to the allocated space.

But there also exists a function which can allocate space on stack frame.

The "alloca" function allocates size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca returns to its caller.

The alloca function returns a pointer to the beginning of the allocated space. However, if the allocation causes stack overflow, program behaviour is undefined.

Allocation on the stack is more convenient and cheaper, but the maximum stack size is limited. It may cause stack overflow if your program allocates large memory on the stack. In addition, allocating large arrays on the stack may fool valgrind . Usually, large arrays should be allocated on the heap.


example :
With malloc :

#include

int main()
{
char *str = (char *)malloc(sizeof(char) * 10);
printf("%p\n",str);
printf("PID = %d\n",getpid());
getchar();
}



$ ./a.out
0x804a008
PID = 16637



$ cat /proc/16637/maps
08048000-08049000 r-xp 00000000 00:15 18172215 /home/fshaikh/trial/a.out
08049000-0804a000 rwxp 00000000 00:15 18172215 /home/fshaikh/trial/a.out
0804a000-0806b000 rwxp 0804a000 00:00 0 [heap]
f7e3d000-f7e3e000 rwxp f7e3d000 00:00 0
f7e3e000-f7f68000 r-xp 00000000 fe:00 1509438 /lib/tls/libc-2.3.2.so
f7f68000-f7f71000 rwxp 00129000 fe:00 1509438 /lib/tls/libc-2.3.2.so
f7f71000-f7f73000 rwxp f7f71000 00:00 0
f7f79000-f7f7c000 rwxp f7f79000 00:00 0
f7f7c000-f7f92000 r-xp 00000000 fe:00 1474565 /lib/ld-2.3.2.so
f7f92000-f7f93000 rwxp 00015000 fe:00 1474565 /lib/ld-2.3.2.so
ffb03000-ffb05000 rw-p ffb03000 00:00 0 [stack]
ffffe000-fffff000 r-xp ffffe000 00:00 0 [vdso]



With alloca :

#include

int main()
{
char *str = (char *)alloca(sizeof(char) * 10);
printf("%p\n",str);
printf("PID = %d\n",getpid());
getchar();
}

$ ./a.out
0xfff26c08
PID = 1324

$ cat /proc/1324/maps
08048000-08049000 r-xp 00000000 00:15 18172215 /home/fshaikh/trial/a.out
08049000-0804a000 rwxp 00000000 00:15 18172215 /home/fshaikh/trial/a.out
f7df0000-f7df1000 rwxp f7df0000 00:00 0
f7df1000-f7f1b000 r-xp 00000000 fe:00 1509438 /lib/tls/libc-2.3.2.so
f7f1b000-f7f24000 rwxp 00129000 fe:00 1509438 /lib/tls/libc-2.3.2.so
f7f24000-f7f26000 rwxp f7f24000 00:00 0
f7f2c000-f7f2f000 rwxp f7f2c000 00:00 0
f7f2f000-f7f45000 r-xp 00000000 fe:00 1474565 /lib/ld-2.3.2.so
f7f45000-f7f46000 rwxp 00015000 fe:00 1474565 /lib/ld-2.3.2.so
fff26000-fff28000 rw-p fff26000 00:00 0 [stack]
ffffe000-fffff000 r-xp ffffe000 00:00 0 [vdso]


Wednesday, September 30, 2009

Sleep-ing in pthread

Using any variant of sleep for pthreads, the behaviour is not guaranteed. All the threads can also sleep since the kernel is not aware of the different threads. Hence a solution is required which the pthread library can handle rather than the kernel.

A safer and cleaner solution to use is the pthread_cond_timedwait...


pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER;

void mywait(int timeInSec)
{
struct timespec timeToWait;
struct timeval now;
int rt;

gettimeofday(&now,NULL);

timeToWait.tv_sec = now.tv_sec + timeInSec;
timeToWait.tv_nsec = now.tv_usec*1000;

pthread_mutex_lock(&fakeMutex);
rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait);
pthread_mutex_unlock(&fakeMutex);
printf("\nDone\n");
}

void* fun(void* arg)
{
printf("\nIn thread\n");
mywait(5);
}

int main()
{
pthread_t thread;
void *ret;

pthread_create(&thread, NULL, fun, NULL);
pthread_join(thread,&ret);
}

For pthread_cond_timedwait , you need to specify how much time to wait from current time.

Now by the use of the function mywait() only the thread calling it will sleep and not the other pthreads.

Note : I have not checked the return values of the functions for error. Please do the same.

Thursday, September 17, 2009

Default Path for #include

This is what i got when i googled about "how to check the default path for include"

echo | gcc -v -x c -E -

Reading specs from /usr/lib/gcc-lib/i486-linux/3.3.5/specs
Configured with: ../src/configure -v --enable-languages=c,c++,java,f77,pascal,objc,ada,treelang --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-gxx-include-dir=/usr/include/c++/3.3 --enable-shared --enable-__cxa_atexit --with-system-zlib --enable-nls --without-included-gettext --enable-clocale=gnu --enable-debug --enable-java-gc=boehm --enable-java-awt=xlib --enable-objc-gc i486-linux
Thread model: posix
gcc version 3.3.5 (Debian 1:3.3.5-13)
/usr/lib/gcc-lib/i486-linux/3.3.5/cc1 -E -quiet -v -D__GNUC__=3 -D__GNUC_MINOR__=3 -D__GNUC_PATCHLEVEL__=5 -
ignoring nonexistent directory "/usr/i486-linux/include"
#include "..." search starts here:
#include <...> search starts here:
/usr/local/include
/usr/lib/gcc-lib/i486-linux/3.3.5/include
/usr/include
End of search list.
...
...
...


Tuesday, September 15, 2009

Boot Loader

In the simplest of terms, a boot loader is something which loads the OS.

It basically performs the following tasks :

- decide what to load
- load the kernel and additional data such as initrd or parameters for the kernel
- set up an execution environment suitable for the kernel
- run the kernel

Types of boot loaders :

There are different types of boot-loaders depending upon how they interact with the underlying system.

a) Specialized loaders

They are typically aware of only one storage device. eg : flash memory or floppy disk on which a small number of kernels is stored in some format specific to the boot-loader.
eg: SYSLINUX, LinuxBIOS

b) General loaders running under other operating system

They normally use the services provided by the host operating system for reading the kernel image and additional data. Disadvantages of this approach are (i) slow loading and (ii) problem of overwriting the host OS while loading the other OS.
eg: LOADLIN

c) File-system aware general loaders running on firmware

They are little operating systems by themselves. They know the structure of one or more filesystems. They access the devices via the services provided by the firmware and sometimes they may have their own drivers to access hardware directly.
eg: GRUB


d) File-system unaware general loaders running on firmware

They rely on third-party to map the on-disk data structures to a more general and convenient representation.
eg:LILO


Lets have a look at the GRUB MBR :)

MBR is a 512-byte sector located in the first sector of the disk i.e. sector 1 of cylinder 0, head 0.
GRUB usually replaces the MBR when linux is installed. But it maintains the same structure as the MBR.
i.e. 446 bytes - Executable code and error messages
64 bytes - Partition table
2 bytes - Magic number (0xAA55)

To take a hexdump of the GRUB MBR code ,
# dd if=/dev/sda of=mbr.bin bs=512 count=1

# hexdump -Cv mbr.bin | less

00000000 eb 48 90 00 00 00 00 00 00 00 00 00 00 00 00 00 |ëH..............|
00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
00000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03 02 |................|
00000040 ff 00 00 20 01 00 00 00 00

The first three bytes specify a Jmp instruction. so the execution jumps over 71 bytes which is also called the BIOS Parameter Block(BPB) and is marked in blue.




00000160 00 eb 0e be 84 7d e8 38 00 eb 06 be 8e 7d e8 30 |.ë.¾.}è8.ë.¾.}è0|
00000170 00 be 93 7d e8 2a 00 eb fe 47 52 55 42 20 00 47 |.¾.}è*.ëþGRUB .G|
00000180 65 6f 6d 00 48 61 72 64 20 44 69 73 6b 00 52 65 |eom.Hard Disk.Re|
00000190 61 64 00 20 45 72 72 6f 72 00 bb 01 00 b4 0e cd |ad. Error.»..´.Í|
000001a0 10 ac 3c 00 75 f4 c3 00 00 00 00 00 00 00 00 00 |.¬<.uôÃ.........|

At offset 179h , we find the zero-terminated string GRUB followed by some error messages.



000001b0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 |................|
000001c0 01 00 83 fe ff ff 3f 00 00 00 5b 01 5c 08 00 fe |...þÿÿ?...[.\..þ|
000001d0 ff ff 82 fe ff ff 9a 01 5c 08 42 8e 2f 00 00 00 |ÿÿ.þÿÿ..\.B./...|
000001e0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
000001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 aa |..............Uª|

And finally the MBR ends with the magic number AA55h. (seen in reverse because of little-endianness ;))




Reference :
1) Almesberger, Werner; "Booting Linux: The History and the Future"
http://www.almesberger.net/cv/papers/ols2k-9.ps.gz

2) http://mirror.href.com/thestarman/asm/mbr/GRUB.htm