views:

381

answers:

5

Hi,

This was an onsite interview question and I was baffled.

I was asked to write a Hello world program for linux.. That too without using any libraries in the system. I think I have to use system calls or something.. The code should run using -nostdlib and -nostartfiles option..

It would be great if someone could help..

+9  A: 

Have a look at example 4 (won't win a prize for portability):

#include <syscall.h>

void syscall1(int num, int arg1)
{
  asm("int\t$0x80\n\t":
      /* output */    :
      /* input  */    "a"(num), "b"(arg1)
      /* clobbered */ );
}

void syscall3(int num, int arg1, int arg2, int arg3)
{
  asm("int\t$0x80\n\t" :
      /* output */     :
      /* input  */    "a"(num), "b"(arg1), "c"(arg2), "d"(arg3) 
      /* clobbered */ );
}

char str[] = "Hello, world!\n";

int _start()
{
  syscall3(SYS_write, 0, (int) str, sizeof(str)-1);
  syscall1(SYS_exit,  0);
}

Edit: as pointed out by Zan Lynx below, the first argument to sys_write is the file descriptor. Thus this code does the uncommon thing of writing "Hello, world!\n" to stdin (fd 0) instead of stdout (fd 1).

Stephan202
I think you want file descriptor 1 in your write syscall.
Zan Lynx
Hey, you're right. I see that in nearly all examples on that linked page he writes to stdin instead of stdout.
Stephan202
A: 

You'd have to talk to the OS directly. You could write to file descriptor 1, (stdout), by doing:

#include <unistd.h>

int main()
{
    write(1, "Hello World\n", 12);
}
Charles Salvia
And where do you believe "write" comes from?
Employed Russian
A: 

What about a shell script? I didn't see any programming language requirement in the question.

echo "Hello World!"
phasetwenty
Even if `echo(1)` _doesn't_ use the C standard library at all, I'm pretty sure there's an implicit "C" language here (or at least a compiled language).
Chris Lutz
The OP specified gcc compiler flags, which pretty much indicates that they had C in mind here
Charles Salvia
+2  A: 

How about writing it in pure assembly as in the example presented in the following link?

http://blog.var.cc/blog/archive/2004/11/10/hello_world_in_x86_assembly__programming_workshop.html

John Scipione
+15  A: 
$ cat > hwa.S
write = 0x04
exit  = 0xfc
.text
_start:
        movl    $1, %ebx
        lea     str, %ecx
        movl    $len, %edx
        movl    $write, %eax
        int     $0x80
        xorl    %ebx, %ebx
        movl    $exit, %eax
        int     $0x80
.data
str:    .ascii "Hello, world!\n"
len = . -str
.globl  _start
$ as -o hwa.o hwa.S
$ ld hwa.o
$ ./a.out
Hello, world!
DigitalRoss
Writes device drivers off the top of his head using only cat...
Don
could you give an "assembly for dummies" explanation of the code?
Amro
@Amro: sure, I've pasted a commented version to: http://pastie.org/688375
DigitalRoss
I have no idea if this would work, but if it does, it gets +1 for awesomeness, and if it doesn't, it gets +1 for chutzpah.
Bob Murphy