c,gcc,assembly,getchar , getchar() in assembly language

getchar() in assembly language


Tag: c,gcc,assembly,getchar

This is a simple C program:

#include <stdio.h>

int main(){
    return 0;

and this is the output of gcc command "gcc prog.c -S":

    .file   "prog.c"
    .globl  main
    .type   main, @function
    pushl   %ebp
    .cfi_def_cfa_offset 8
    .cfi_offset 5, -8
    movl    %esp, %ebp
    .cfi_def_cfa_register 5
    andl    $-16, %esp
    call getchar
    movl    $0, %eax
    .cfi_restore 5
    .cfi_def_cfa 4, 4
    .size   main, .-main
    .ident  "GCC: (Debian 4.8.2-1) 4.8.2"
    .section    .note.GNU-stack,"",@progbits

In "main" there is a call to "getchar" function. Is possible to see the code (in assembly, of course) of this function?

In particular I would understand the mechanism of keyboard interrupt behind the "getchar()".


If you want an ASM output you can simply ask gdb to load your C program and disassemble getchar for you. This would give something like this (on my system) :

$ gdb /bin/cat
(gdb) run
Starting program: /bin/cat 
Program received signal SIGINT, Interrupt.
0x00007ffff7b0c5c0 in __read_nocancel () at ../sysdeps/unix/syscall-template.S:81
(gdb) disas getchar 
Dump of assembler code for function getchar:
   0x00007ffff7aa4b30 <+0>:     push   %rbx
   0x00007ffff7aa4b31 <+1>:     mov    0x332be0(%rip),%rbx        # 0x7ffff7dd7718 <stdin>
   0x00007ffff7aa4b38 <+8>:     mov    (%rbx),%eax
   0x00007ffff7aa4b3a <+10>:    mov    %rbx,%rdi
   0x00007ffff7aa4b3d <+13>:    and    $0x8000,%eax
   0x00007ffff7aa4b42 <+18>:    jne    0x7ffff7aa4b9e <getchar+110>
   0x00007ffff7aa4b44 <+20>:    mov    0x88(%rbx),%rdx
   0x00007ffff7aa4b4b <+27>:    mov    %fs:0x10,%r8
   0x00007ffff7aa4b54 <+36>:    cmp    0x8(%rdx),%r8
   0x00007ffff7aa4b58 <+40>:    je     0x7ffff7aa4bf0 <getchar+192>
   0x00007ffff7aa4b5e <+46>:    mov    $0x1,%esi
   0x00007ffff7aa4b63 <+51>:    cmpl   $0x0,0x336c6a(%rip)        # 0x7ffff7ddb7d4 <__libc_multiple_threads>
   0x00007ffff7aa4b6a <+58>:    je     0x7ffff7aa4b78 <getchar+72>
   0x00007ffff7aa4b6c <+60>:    lock cmpxchg %esi,(%rdx)
   0x00007ffff7aa4b70 <+64>:    jne    0x7ffff7aa4c41 <_L_lock_30>
   0x00007ffff7aa4b76 <+70>:    jmp    0x7ffff7aa4b81 <getchar+81>
   0x00007ffff7aa4b78 <+72>:    cmpxchg %esi,(%rdx)
   0x00007ffff7aa4b7b <+75>:    jne    0x7ffff7aa4c41 <_L_lock_30>
   0x00007ffff7aa4b81 <+81>:    mov    0x88(%rbx),%rax
   0x00007ffff7aa4b88 <+88>:    mov    0x88(%rbx),%rdx
   0x00007ffff7aa4b8f <+95>:    mov    0x332b82(%rip),%rdi        # 0x7ffff7dd7718 <stdin>
   0x00007ffff7aa4b96 <+102>:   mov    %r8,0x8(%rax)
   0x00007ffff7aa4b9a <+106>:   addl   $0x1,0x4(%rdx)
   0x00007ffff7aa4b9e <+110>:   mov    0x8(%rdi),%rax
   0x00007ffff7aa4ba2 <+114>:   cmp    0x10(%rdi),%rax
   0x00007ffff7aa4ba6 <+118>:   jae    0x7ffff7aa4bf5 <getchar+197>
   0x00007ffff7aa4ba8 <+120>:   lea    0x1(%rax),%rdx
   0x00007ffff7aa4bac <+124>:   mov    %rdx,0x8(%rdi)
   0x00007ffff7aa4bb0 <+128>:   movzbl (%rax),%edx
   0x00007ffff7aa4bb3 <+131>:   testl  $0x8000,(%rbx)
   0x00007ffff7aa4bb9 <+137>:   jne    0x7ffff7aa4be4 <getchar+180>
   0x00007ffff7aa4bbb <+139>:   mov    0x88(%rbx),%rsi
   0x00007ffff7aa4bc2 <+146>:   subl   $0x1,0x4(%rsi)
   0x00007ffff7aa4bc6 <+150>:   jne    0x7ffff7aa4be4 <getchar+180>
   0x00007ffff7aa4bc8 <+152>:   movq   $0x0,0x8(%rsi)
   0x00007ffff7aa4bd0 <+160>:   cmpl   $0x0,0x336bfd(%rip)        # 0x7ffff7ddb7d4 <__libc_multiple_threads>
   0x00007ffff7aa4bd7 <+167>:   je     0x7ffff7aa4be0 <getchar+176>
   0x00007ffff7aa4bd9 <+169>:   lock decl (%rsi)
   0x00007ffff7aa4bdc <+172>:   jne    0x7ffff7aa4c5c <_L_unlock_79>
   0x00007ffff7aa4bde <+174>:   jmp    0x7ffff7aa4be4 <getchar+180>
   0x00007ffff7aa4be0 <+176>:   decl   (%rsi)
   0x00007ffff7aa4be2 <+178>:   jne    0x7ffff7aa4c5c <_L_unlock_79>
   0x00007ffff7aa4be4 <+180>:   mov    %edx,%eax
   0x00007ffff7aa4be6 <+182>:   pop    %rbx
   0x00007ffff7aa4be7 <+183>:   retq   
   0x00007ffff7aa4be8 <+184>:   nopl   0x0(%rax,%rax,1)
   0x00007ffff7aa4bf0 <+192>:   mov    %rbx,%rdi
   0x00007ffff7aa4bf3 <+195>:   jmp    0x7ffff7aa4b9a <getchar+106>
   0x00007ffff7aa4bf5 <+197>:   callq  0x7ffff7aa9060 <__GI___uflow>
   0x00007ffff7aa4bfa <+202>:   mov    %eax,%edx
   0x00007ffff7aa4bfc <+204>:   jmp    0x7ffff7aa4bb3 <getchar+131>
   0x00007ffff7aa4bfe <+206>:   testl  $0x8000,(%rbx)
   0x00007ffff7aa4c04 <+212>:   mov    %rax,%rsi
   0x00007ffff7aa4c07 <+215>:   jne    0x7ffff7aa4c39 <getchar+265>
   0x00007ffff7aa4c09 <+217>:   mov    0x88(%rbx),%rdx
   0x00007ffff7aa4c10 <+224>:   mov    0x4(%rdx),%eax
   0x00007ffff7aa4c13 <+227>:   lea    -0x1(%rax),%ecx
   0x00007ffff7aa4c16 <+230>:   test   %ecx,%ecx
   0x00007ffff7aa4c18 <+232>:   mov    %ecx,0x4(%rdx)
   0x00007ffff7aa4c1b <+235>:   jne    0x7ffff7aa4c39 <getchar+265>
   0x00007ffff7aa4c1d <+237>:   movq   $0x0,0x8(%rdx)
   0x00007ffff7aa4c25 <+245>:   cmpl   $0x0,0x336ba8(%rip)        # 0x7ffff7ddb7d4 <__libc_multiple_threads>
   0x00007ffff7aa4c2c <+252>:   je     0x7ffff7aa4c35 <getchar+261>
   0x00007ffff7aa4c2e <+254>:   lock decl (%rdx)
   0x00007ffff7aa4c31 <+257>:   jne    0x7ffff7aa4c77 <_L_unlock_150>
   0x00007ffff7aa4c33 <+259>:   jmp    0x7ffff7aa4c39 <getchar+265>
   0x00007ffff7aa4c35 <+261>:   decl   (%rdx)
   0x00007ffff7aa4c37 <+263>:   jne    0x7ffff7aa4c77 <_L_unlock_150>
   0x00007ffff7aa4c39 <+265>:   mov    %rsi,%rdi
   0x00007ffff7aa4c3c <+268>:   callq  0x7ffff7a54d50 <_Unwind_Resume>
End of assembler dump.

You could also look directly at the source of your libc to see how getchar is implemented, however this will give you (perhaps sometimes cryptic) C code.


C binary tree sort - extending it

I need some help in C Help me to extend the binary tree sort on C. I need to return a sorted array in sort function. here it is: #include <stdio.h> #include <stdlib.h> struct btreenode { struct btreenode *leftchild ; int data ; struct btreenode *rightchild ; } ; void...

getchar() not working in c

getchar() is not working in the below program, can anyone help me to solve this out. I tried scanf() function in place of getchar() then also it is not working. I am not able to figure out the root cause of the issue, can anyone please help me. #include<stdio.h> int...

How to read string until two consecutive spaces?

A well known function of the scanf() functions is that you can pass a format to scan input according to this format. For my case, I cannot seem to find a solution searching this and this documentation. I have a string (sInput) as the following: #something VAR1 this is a...

ARM assembly cannot use immediate values and ADDS/ADCS together

I am currently trying to speed up some of my C functions on a Cortex-M0 (Freescale KL25Z) using assembly. I get a problem with this minimal test program: @.syntax unified .cpu cortex-m0 .text .global test .code 16 test: mov r0, #0 adds r0, r0, #1 bx lr When I try...

Is there Predefined-Macros define about byte order in armcc

Is there Predefined-Macros define about byte order in armcc. I am a novice on the armcc.and sorry for my English. In gcc these are macros: __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ __ORDER_BIG_ENDIAN__ __ORDER_PDP_ENDIAN__ ... Now I have to use armcc, Is there same like these with armcc? Thank a lot. by the way,the armcc...

OpenGL glTexImage2D memory issue

I'm loading a cubemap to create a skybox, everything is fine and the skybox renders properly with a correct texture application. However, I decided to check my program safety with valgrind, Valgrind gives this error: http://pastebin.com/seqmXjyx The line 53 in sky.c is: glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, texture.width, texture.height, 0,...

Segmentation Fault if I don't say int i=0

void removeVowels(char* array){ int i,j,v; i=0; char vowel[]={'a','e','i','o','u'}; while(array[i]!='\0') { for(v=0;v<5;v++) { if (array[i]==vowel[v]) { j=i; while(array[j]!='\0') { array[j]=array[j+1]; j++; } i--; break; } } i++; } } in function removeVowels() if I don't include i=0; and just say int i; why does it give segmentation fault? Isn't it automatically...

free causing different results from malloc

Below is a C program i have written to print different combination of characters in a string. This is not an efficient way as this algorithm creats a lot of extra strings. However my question is NOT about how to solve this problem more efficiently. The program works(inefficiently though) and...

Disadvantages of calling realloc in a loop

I'm trying to implement some math algorithms in C on Windows 7, and I need to repeatedly increase size of my array. Sometimes it fails because realloc can't allocate memory. But if I allocate a lot of memory at once in the beginning it works fine. Is it a problem...

execl() works on one of my code, but doesn't work on another

I already used execl() in code, and it worked well. But this time, I really have no idea why it doesn't work. So here's the code that do not work #include <unistd.h> #include <stdio.h> int main() { int i = 896; printf("please\n"); execl("home/ubuntu/server/LC/admin/admin", (char*)i, NULL); printf("i have no idea why\n");...

CallXXXMethod undefined using JNI in C

So I've tried to use the JNI interface to call Java methods from C. Calling static methods is no problem, but I get stuck when I want to call a method on an object. The code is as follows: #include <stdio.h> #include <string.h> #include <jni.h> int main() { JavaVMOption options[1];...

Reverse ^ operator for decryption

I'm trying to reverse the following code in order to provide a function which takes the buffer and decrypts it. void crypt_buffer(unsigned char *buffer, size_t size, char *key) { size_t i; int j; j = 0; for(i = 0; i < size; i++) { if(j >= KEY_SIZE) j = 0;...

Is there any way of protecting a variable for being modified at runtime in C?

I was wondering if there is any way of protecting a variable for being modified once initialized (something like "constantize" a variable at runtime ). For example: #include <stdio.h> #include <stdlib.h> int main(void) { int v, op; scanf( "%d", &op ); if( op == 0 ) v = 1; else...

CGO converting Xlib XEvent struct to byte array?

I am creating a simple window manager (code based of the c code in tinywm) in Golang. To use Xlib, I am using cgo, so my header is: // #cgo LDFLAGS: -lX11 // #include <X11/Xlib.h> And I have a variable declaration, like: event := C.XEvent{} And then, I use this...

How convert unsigned int to unsigned char array

I just need to extract those bytes using bitwise & operator. 0xFF is a hexadecimal mask to extract one byte. For 2 bytes, this code is working correctly: #include <stdio.h> int main() { unsigned int i = 0x7ee; unsigned char c[2]; c[0] = i & 0xFF; c[1] = (i>>8) &...

Passing int using char pointer in C

I'm trying to figure out how to pass an int using a char pointer. It fails once the int value is too large for the char. This is what I'm trying to figure out: char *args[5]; int i = 20; /*some other code/assignments*/ args[2] = (char *)&i; execv(path, args); How...

Multiple definition and file management

I'm writing a program for vocabulary training, for myself. And the program itself should be available in different languages, atm in German and English. What I want is to have a Main File which manage all and two separate files for the functions in the right language. I compile all...

How does this code print odd and even?

#define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ } int main(void) { int num; printf("Enter a number: "); scanf("%d", &num); if (num & 1) { MACRO(num, "Odd"); } else { MACRO(num, "Even"); } return 0; } Please explain the above code (if/else condition and how...

Array breaking in Pebble C

I'm trying to create a simple dice-rolling application in Pebble using C on CloudPebble. I have an array of different die sizes you can scroll through using Up/Down, and you roll (currently just generate a random number, it'll get fancier later) using the middle button. There's also a label at...

Text justification C language

I have to solve a problem that involves left justification string length and leading zeros. I have the following table : BEGIN CLOSE CONCATENATE DELETE END INITIALIZE PRINT WRITE This is produced by a simple program. My problem is to find out how to convert it like that : It...

How to control C Macro Precedence

#define VAL1CHK 20 #define NUM 1 #define JOIN(A,B,C) A##B##C int x = JOIN(VAL,NUM,CHK); With above code my expectation was int x = 20; But i get compilation error as macro expands to int x = VALNUMCHK; // Which is undefined How to make it so that NUM is replaced first...

Does realloc() invalidate all pointers?

Note, this question is not asking if realloc() invalidates pointers within the original block, but if it invalidates all the other pointers. I'm new to C, and am a bit confused about the nature of realloc(), specifically if it moves any other memory. For example: void* ptr1 = malloc(2); void*...

Counting bytes received by posix read()

I get confused with one line of code: temp_uart_count = read(VCOM, temp_uart_data, 4096); I found more about read function at http://linux.die.net/man/3/read, but if everything is okay it returns 0, so how we can get num of bytes received from that? temp_uart_count is used to count how much bytes we received...

Is i=i+1 an undefined behaviour?

I'm using codeblocks and it is giving a different output to other compilers and I can't find a solution to it.What's the undefined behaviour in this program and is there any solution to avoid it? This is the code to print the nth number in a number system with only...

Loop through database table and compare user input

I am trying to loop through the rows in a MySql table and compare the data in a certain column to some user input using C. Currently my code looks like this: MYSQL *cxn = mysql_init(NULL); MYSQL_RES *result; unsigned int num_fields; unsigned int num_rows; char *query_string; MYSQL_ROW *row; if (mysql_real_connect(cxn,...

Unexpected result when calculating a percentage - even when factoring in integer division rules

I am trying to express a battery voltage as a percentage. My battery level is a (global) uint16 in mV. I have a 16-bit CPU. Here is my code: static uint8 convertBattery(void){ uint16 const fullBattery = 3000; /* 3V = 3000mV */ uint8 charge; charge = ((battery*100)/fullBattery); return charge; }...

__cplusplus < 201402L return true in gcc even when I specified -std=c++14

The directive: #ifndef __cplusplus #error C++ is required #elif __cplusplus < 201402L #error C++14 is required #endif The command-line: g++ -Wall -Wextra -std=c++14 -c -o header.o header.hpp My g++ version: g++ (tdm-1) 4.9.2 The error C++14 is required is generated even when I added -std=c++14, I don't know why. Please...

Is it safe to read and write on an array of 32 bit data byte by byte?

So I have a void * data of 32 bit unsigned integers which represents the pixels. Is it okay for me to access one of the pixels with a char * and modify the values directly? Or is it better to store my new pixel in a temporary uint32_t variable...

Is post-increment operator guaranteed to run instantly?

Let's say I have the following code: int i = 0; func(i++, i++); The increment is happening right after returning the value? Is it guaranteed that the first argument will be 0, and the second argument will be 1?...

C programming - Confusion regarding curly braces

The following code is for replacing multiple consecutive spaces into 1 space. Although I manage to do it, I am confused in the use of curly braces. This one is actually running fine: #include <stdio.h> #include <stdlib.h> int main() { int ch, lastch; lastch = 'a'; while((ch = getchar())!= EOF)...

On entry to NIT parameter number 9 had an illegal value

I go this ex1.c file from Intel 11. However, when I execute it, it fails: [email protected]:~/konstantis$ ../mpich-install/bin/mpicc -o test ex1.c -I../intel/mkl/include ../intel/mkl/lib/intel64/libmkl_scalapack_ilp64.a -Wl,--start-group ../intel/mkl/lib/intel64/libmkl_intel_ilp64.a ../intel/mkl/lib/intel64/libmkl_core.a ../intel/mkl/lib/intel64/libmkl_sequential.a -Wl,--end-group ../intel/mkl/lib/intel64/libmkl_blacs_intelmpi_ilp64.a -lpthread -lm -ldl gsamar[email protected]:~/konstantis$ mpiexec -n 4 ./test { 0, 0}: On entry to DESCI{...

VS2012 Identifer not found when part of static lib

Using VS2012 C/C++: I created and linked a static lib called "libtools" to my project. Calls to functions in the libtools lib worked as expected. I created and linked a second static lib called "shunt" to my project. But when I incorporate a call to a function in shunt, I...

Set precision dynamically using sprintf

Using sprintf and the general syntax "%A.B" I can do this: double a = 0.0000005l; char myNumber[50]; sprintf(myNumber,"%.2lf",a); Can I set A and B dynamically in the format string?...

C language, vector of struct, miss something?

This is a part of my program that I want to create a vector of struct typedef struct { char nome[501]; int qtd; int linha; int coluna; } tPeca; tPeca* criarPecas(FILE *pFile, int tam) { int i; tPeca *pecaJogo = (tPeca*)malloc(tam*sizeof(tPeca)); if (pecaJogo == NULL) return NULL; for (i =...

C++ / C #define macro calculation

Suppose I have #define DETUNE1 sqrt(7)-sqrt(5) #define DETUNE2 sqrt(11)-sqrt(7) And I call these multiple times in my program. Are DETUNE1 and DETUNE2 calculated every time it is called? Thanks. Please don't downvote this, I really want to know and a search didn't turn up anything definite. ...

How can I convert an int to a string in C++11 without using to_string or stoi?

I know it sounds stupid, but I'm using MinGW32 on Windows7, and "to_string was not declared in this scope." It's an actual GCC Bug, and I've followed these instructions and they did not work. So, how can I convert an int to a string in C++11 without using to_string or...

fread(), solaris to unix portability and use of uninitialised values

Valgrind found the following error and I, after reading the documentation, the code and other questions in here couldn't figure it out why. Valgrind: first warning ~$ valgrind --vgdb=yes --vgdb-error=0 --read-var-info=yes --leak-check=yes --track-origins=yes debitadmin* debitadmin ==20720== Conditional jump or move depends on uninitialised value(s) ==20720== at 0x4013BC6: initialise (dbg.c:199) ==20720==...

Django MySQLClient pip compile failure on Linux

Django documentation as of v1.8 recommends using mysqlclient connector for the framework. I'm attempting to pip install the package on Ubuntu 14.04 with Python 3.4 and running into a GCC error that I'm unable to find reference to. I'm not an expert on compiling software, so was hoping somebody can...

scanf get multiple values at once

I need to get in one single shot different inputs from one single line. In particular I need to get a single char and then, depending on which char value I just read, it can be a string and an int or a string, an int and another string and...

How can I align stack to the end of SRAM?

I have a STM32F103VCT6 microcontroller with 48kb of SRAM, and recently i've got a memory collision: I have some static variable (lets call it A) located in heap with size of 0x7000 and I wrote some simple function to get info about stack and heap: void check(int depth) { char...

What all local variables goto Data/BSS segment?

The man page of nm here: MAN NM says that The symbol type. At least the following types are used; others are, as well, depending on the object file format. If lowercase, the symbol is usually local; if uppercase, the symbol is global (external) And underneath it has "b" and...

How to increment the value of an unsigned char * (C)

I have a value stored as an unsigned char * (in C). This holds the SHA1 hash of a string. My goal is to cover the SHA1 key space. Since I'm using <openssl/evp.h> to generate the hashes, I end up with an unsigned char* holding the SHA1 value. Now I...

Efficient comparison of small integer vectors

I have small vectors. Each of them is made of 10 integers which are between 0 and 15. This means that every element in a vector can be written using 4 bits. Hence I can concatenate my vector elements and store the whole vector in a single long type (in...

How does ((a++,b)) work? [duplicate]

This question already has an answer here: What does the comma operator `,` do in C? 8 answers In the below block of code, I am trying to understand how the line return reverse((i++, i)) is working. #include <stdio.h> void reverse(int i); int main() { reverse(1); } void reverse(int...

What does `strcpy(x+1, SEQX)` do?

I'm wondering what this syntax of strcpy() does in line 65 and 66: 24 #define SEQX "TTCATA" 25 #define SEQY "TGCTCGTA" 61 M = strlen(SEQX); 62 N = strlen(SEQY); 63 x = malloc(sizeof(char) * (M+2)); /* +2: leading blank, and trailing \0 */ 64 y = malloc(sizeof(char) * (N+2)); 65...

Galois LFSR - how to specify the output bit number

I am trying to understand how change the galois LFSR code to be able to specify the output bit number as a parameter for the function mentioned below. I mean I need to return not the last bit of LFSR as output bit, but any bit of the LFSR (...

Segmentation fault with generating an RSA and saving in ASN.1/DER?

#include <string.h> #include <openssl/aes.h> #include <openssl/rand.h> #include <openssl/bio.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/pem.h> #define RSA_LEN 2048 #define RSA_FACTOR 65537 int genRSA2048(unsigned char **pub,unsigned int *pub_l,unsigned char **priv,unsigned int *priv_l){ RSA *pRSA = NULL; pRSA = RSA_generate_key(RSA_LEN,RSA_FACTOR,NULL,NULL); if (pRSA){ pub_l = malloc(sizeof(pub_l)); *pub_l = i2d_RSAPublicKey(pRSA,pub); priv_l = malloc(sizeof(priv_l));...

Does strlen() always correctly report the number of char's in a pointer initialized string?

As long as I use the char and not some wchar_t type to declare a string will strlen() correctly report the number of chars in the string or are there some very specific cases I need to be aware of? Here is an example: char *something = "Report all my...

Program to reverse a string in C without declaring a char[]

I need to reverse a given string and display it without using the value At[index] notation , I tried the below program using pointers,but it does not print anything for the reverse string, Please help! int main() { char* name=malloc(256); printf("\nEnter string\n"); scanf("%s",name); printf("\nYou entered%s",name); int i,count; count=0; //find the...

Infinite loop with fread

I'm trying to allocate an array 64 bytes in size and then loop over the array indexes to put a read a byte each from the inputfile. but when I don't malloc() the array indexes, the loop stays in index0 (so each time it loops it replaces the content in...