Showing posts with label c. Show all posts
Showing posts with label c. Show all posts

Thursday, April 16, 2020

gdb debugging - PART 2

gdb part2

gdb debugging techniques continutaion

This is a continuation from gdb part1 post -
http://naveendavisv.blogspot.com/2020/02/gdb-tips-part1.html

 - Debug an executable:
   gdb executable

 - Attach a process to gdb:
   gdb -p procID

 - Debug with a core file:
   gdb -c core executable

 - Execute given GDB commands upon start:
   gdb -ex "commands" executable

 - Start gdb and pass arguments:
   gdb --args executable argument1 argument2

Saturday, March 14, 2020

How do we make a C program call Rust program

C to Rust.md

Internals of C program call to rust program call

One of the main strength of Rust programming language is that it can easily inter-operate with other programming languages.

But as we know Rust is very very strongly typed language. When you are planning Rust to use some of the C libraries , the C type representation attributes help us .

#[repr( C )]

There are some difference in the type representation for C type corresponding rust type.

We can go-ahead and check what is the size of the below struct
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7392513792a8d390ce4756a6a8a0ed15

use std::mem;
#[repr(C)]
struct FieldStruct {
    first: u8,
    second: u16,
    third: u8
}

// The size of the first field is 1, so add 1 to the size. Size is 1.
// The alignment of the second field is 2, so add 1 to the size for padding. Size is 2.
// The size of the second field is 2, so add 2 to the size. Size is 4.
// The alignment of the third field is 1, so add 0 to the size for padding. Size is 4.
// The size of the third field is 1, so add 1 to the size. Size is 5.
// Finally, the alignment of the struct is 2 (because the largest alignment amongst its
// fields is 2), so add 1 to the size for padding. Size is 6.
assert_eq!(6, mem::size_of::<FieldStruct>());
}

But if you remove #[repr( c )] , the struct size becomes 4.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f1ad5c57ae7e771ca505058784580a1e

#![allow(unused)]
fn main() {
use std::mem;
struct FieldStruct {
    first: u8,
    second: u16,
    third: u8
}
assert_eq!(6, mem::size_of::<FieldStruct>());
}

How to use a Rust function in C program.

I referred the blog for Sergey Potapov for the details.

In this below program, you would see the function print_hello_from_rust defined with extern keyword and [no_mangle] attribute.
[no_mangle] makes the compiler ignores the unknown symbols and it knows this function is going to get called from other languages.
extern keyword makes the function outside of the our library.

std::ffi::CStr. Representation of a borrowed C string. This type represents a borrowed reference to a nul-terminated array of bytes. It can be constructed safely from a &[ u8 ] slice, or unsafely from a raw *const c_char

In this example we are using *const c_char , but what is c_char ?!

c_char is coming from the standard library ‘os’ module and it is Equivalent to C’s char type.C’s char type is completely unlike Rust’s char type; while Rust’s type represents a unicode scalar value, C’s char type is just an ordinary integer. This type will always be either i8 or u8, as the type is defined as being one byte long

reference : c_char

then why *const in front of it ?

*const are called Raw pointers in Rust.Sometimes, when writing certain kinds of libraries, you’ll need to get around Rust’s safety guarantees for some reason. In this case, you can use raw pointers to implement your library, while exposing a safe interface for your users. Ref: Raw pointers

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=40d05db968f82125fb7660e67710ecff

use std::ffi::{CString,CStr};
use std::os::raw::{c_char,c_int};

#[repr(C)]
pub struct Point{
    x: c_int,
    y: c_int,
}

impl Point {

    fn new(x:c_int,y:c_int) -> Point{
//          println!("Creating a Point with x = {},y = {}",x,y);
          Point {x: x,y: y }

    }
}
#[no_mangle]
pub extern fn create_point(x:c_int,y:c_int) -> *mut Point{

        Box::into_raw(Box::new(Point::new(x,y)))
}
#[no_mangle]
pub extern fn print_hello_from_rust(data: *const c_char ){

    unsafe{
          let c_str =       CStr::from_ptr(data);
          println!("hello from rust {:?}",c_str.to_str().unwrap());
    }
}

You can build the rust program with cargo

cargo new whatland -- lib
cd whatland

edit the lib.rs file with above code.

also make sure that your cargo file has

 [lib]
 name = "whatland"
 crate-type = ["staticlib","cdylib"]

cdylib helps - A dynamic system library creation. This is used when compiling a dynamic library to be loaded from another language. This output type will create *.so files on Linux, *.dylib files on macOS, and *.dll files on Windows.

cargo build --release

C program would need to compile with linking the .so file generated.

I am not detailing the C program compilation, but it detailed in the blogpost: https://www.greyblake.com/blog/2017-08-10-exposing-rust-library-to-c/

You would need to use,

gcc -o ./examples/hello ./examples/hello.c -Isrc  -L. -l:target/release/libwhatlang.so

Passing String parameter from C to Rust function.

We can use the trick of accepting the string as a Raw pointer using *const c_char
In order to print that bytes into a valid string slice in Rust, first we need to convert that to CStr - Representation of a borrowed C string.

then we can convert that to Str ( rust string slice) using c_str.to_str().unwrap()

How to use a C struct in Rust program

I believe , Its always recommended to use #[repr©] when working with C structs, enums because it makes alignment https://doc.rust-lang.org/reference/type-layout.html#the-c-representation

#[repr(C)]
pub struct Point{
   x: c_int,
   y: c_int,
  
  //    x:u8, -- if you are using u8, compilier throws error,
  //    y:u8,    stating "expected `u8`, found `i32'"
  }

We implemented a method new in the rust program so that we can use in the Point struct instance creation.

impl Point {

  fn new(x:c_int,y:c_int) -> Point{

 Point {x: x,y: y }
 }
}

Next in this example we have a export function which will be called from C program to creating Point Struct. For creating any object, we need to memory. In Rust we know that we can allocate heap memory through Box::new.

But we need to return a raw pointer to the C program, which can be done through Box::into_raw which Consumes the Box, returning a wrapped raw pointer.

 23 #[no_mangle]
 24 pub extern fn create_point(x:c_int,y:c_int) -> *mut Point{
 25 
 26         Box::into_raw(Box::new(Point::new(x,y)))
 27 }

C program can now just call the Rust function to create struct.

We need to have our C program included with struct and create function declaration.
header file whatland.h

  1 void print_hello_from_rust();
  2 
  3 typedef struct Point{
  4             int x,y;
  5 }Point;
  6 
  7 Point* create_point(int x, int y);
  

Now we can just call it in our main function in C

 11  Point* p1 = create_point(10,20);
 12     printf("Point={%d},{%d}",p1 -> x,p1 -> y);

Thursday, February 20, 2020

gdb tips - PART1

gdb

Some gdb ( GNU debugger) tips

It is very important to understand the debugging tools and their different functionalities to hack the system level programs easily.

How to compile a program to debug in gdb.

  1. compile your C program with -g option

    $cc -g helloworld.c

  2. Open the executable in gdb
    $gdb a.out

  3. Run the program using below commands in gdb prompt using simply ‘r’.
    (gdb)run or (gdb)r

  4. Continue run from breakpoint using ‘c’
    (gdb)c

Setting Breakpoint in gdb.

1.Setting up breakpoint in a line number
$b 10
2. breakpoint setting up in an address
$b *0x7c00

(gdb) b *0x7c00
Breakpoint 1 at 0x7c00
(gdb) c
Continuing.
Thread 1 hit Breakpoint 1, 0x00007c00 in ?? ()

3.Setting up breakpoint in a function
$b main

Switch to tui mode using ctrl+x 2

you can switch to tui ( text gui mode) mode using ctrl+x 2
to view the source file in the same screen.
tui mode

you can ctrl+x 1 to see registers values

ctrl+x n to come back to gdb prompt.

stepping through line and instruction

$si \ steps through instruction
$s \ source level step through next line

Next step over through line

$n
$next

gdb_steps_through_source

Printing variables

$p foo//print the value of foo
$p car // print the value of car variable

$p/x addr //printing hexa decimal values

information about frames and registers

Current function stack frame details can be displayed using the command ‘f’ or ‘frame’
$f
$frame

enter image description here

The registers details or values can be seen using the command ’ info r’

info r
enter image description here

backtrace of call stacks

How can we backtrace all call stacks in gdb?!. This would be very useful command especially when you are debugging big projects source codes.

$bt
shows the backtrace of all call stacks so far.

enter image description here

You can switch to different frames using below command

$f 1
to switch to the first frame
f 5 switch to 5th frame etc

Some of the helpful commands when you are in a function

$info locals
shows the local variable in a function

$info args
shows arguments of the function

getting help on gdb

(gdb) help

List of classes of commands:

aliases – Aliases of other commands
breakpoints – Making program stop at certain points
data – Examining data
files – Specifying and examining files
internals – Maintenance commands
obscure – Obscure features
running – Running the program

(gdb)h breakpoints //provide help on breakpoints

PART 2 -
https://naveendavisv.blogspot.com/2020/04/gdb-debugging-part-2.html

Tuesday, February 18, 2020

Have you ever tried Ctrl+x 2 in GDB ?

I got amazed when I tried Ctrl+x  2 in gdb and step through code. I never thought GDB had an option to do this.





again press ctrl+x 2  .. you will see another magic.

Wednesday, February 12, 2020

Going to back OS/system related computer courses

I tried to read linux kernel and dropped it long back around the year of 2007 or 2008. Whenever I start touching system level code, programming languages becomes alien language for me. I thought of watching again the OS/computer architecture video courses. Luckily come across xv6 (https://en.wikipedia.org/wiki/Xv6)  operating system. This makes/motivating me to give one more attempt to learn the kernel and system level programming.

This one also helps me a lot.
  https://github.com/Babtsov/jos/tree/master/lab1

Wednesday, January 8, 2020

Emscripten - C programs to browser

--- ---

C programs and libraries to Browser

How nice it would be if I can call my own created C programs especially the computational intensive C programs from my Mozilla or Google Browser ( :-) in fact I don’t have anything that much computational intensive), But still . I would also be amazed if I can port some of the C libraries or C++ Games to browser.

Emscripten and Webassembly(wasm) together make this happen

I was following web-assembly and Rust for a few months now. Since Rust has lot of safety features, I did not think of exploring more on porting C or C++ programs to browser.

Emscripten is an Open Source LLVM to JavaScript compiler. Using Emscripten you can:
Compile C and C++ code into JavaScript
Compile any other code that can be translated into LLVM bitcode into JavaScript.
Compile the C/C++ runtimes of other languages into JavaScript, and then run code in those other languages in an indirect way (this has been done for Python and Lua)!

WebAssembly (often shortened to Wasm) is an open standard that defines a portable binary code format for executable programs, and a corresponding textual assembly language, as well as interfaces for facilitating interactions between such programs and their host environment.



Emscripten Installation


Emcripten is not that complex to install,there is good documentation in the site - Emscripten
You might need to install python2.7 and cmake etc as a prior requisite.We just need to follow the instructions. My Linux machine helped me to install everything with apt-get insall command.
You might come across some installation errors, but just search those errors in google, there will be solution to fix it.


C program to wasm


I wrote a simple C program called emccwasm.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>
int main(){
        int a = 1;
        printf("%d",a);
        //string function to put a space in the screen
        puts(" ");
        printf("First C program compiled to browser. a=%d",a);
        return 1;
}

In command line, you might need to use below command to compile if you are using Linux machine.
emcc -s NO_EXIT_RUNTIME=1 -s FORCE_FILESYSTEM=1 -s EXPORTED_FUNCTIONS=[’_main’] -o emccwasm.html emccwasm.c
Emscripten FAQ might help you understand these options and resolve the errors you might encounter quickly.
The above command generated 3 files for me , they are emccwasm.html , emccwasm.js and emccwasm.wasm


Emscripten generated Files.


Emcripten created a compiled webassembly file which is emccwasm.wasm as mentioned earlier.Filename will be same as the C program file name. To know more about webassembly , following documentation link helps - https://webassembly.org/
In a nutshell “WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server application
The .js and .html files are glue files created for web. The html file can be rendered to the browser and Javascript file initialize webassembly and rest of the glue work


http server


You might need to install http server to void below error . The following documentation can be used for installation -
https://github.com/thecoshman/http
Note: if you have installed Cargo in your machine, the server installation will be very easy.
"**Failed to execute ‘compile’ on ‘WebAssembly’: Incorrect response MIME type. Expected ‘application/wasm’.
**
We can run the server simply by below command:


http

Emscripten files in localhost


Once the http server is up, the files will be served in the browser in the link: http://localhost:8000/emccwasm.html
Note: the port might vary .
If everything goes well, you should be getting a screen similar to below.

enter image description here


Accessing exported functions.


When we compiled the C program we used EXPORT_FUNCTIONS option with _main. That means the _main function should be available in Module.
ie , we can invoke main function by Module._main()
enter image description here

Sunday, August 11, 2019

Learn Python ,RUST and C - blog post 2

Data Types in Python,Rust and C - PART 1

Understanding Data Types in Python,Rust and C progamming languages.

I am not sure whether I can cover all data types comparison in one blog post. So I might be doing it in multiple blog posts.
Standard Data Types:*
  • Numbers.
  • String.
  • List.
  • Tuple.
  • Dictionary.
Numbers Datatypes
**Python programming **
Type format description
int a = 10 signed integer
long 356L Long integers
float a = 12.34 floating point values
complex a = 3.14J (J) Contains integer in the range 0 to 255
enter image description here
The variable types are dynamically typed in python.So when you assign a value to a variable, python compiler determines the type of the variable.
But once the type is defined , the defined operations can only be performed for that particular type.
but you can change the type of the variable by assigning a different value. So in python it is the developer responsibility to maintain and make sure type of the variable intact through out the program.
For example,
>a = 10;
>a = "naveen" //allowed
>a = a + 1 // not allowed
>a = 11  //allowed
>a = a +1 // now this is allowed
**Rust programming **:
Length signed unsigned
8bit i8 u8
16bit i16 u16
32bit i32 u32
64bit i64 u64
128 bit i128 u128
arch isize usize
signed and unsigned means whether a number can be -ve or +ve.
Each signed variant can store numbers from -(2n -1) to 2n-1
unsigned variants can vary from 0 to 2n-1
eg: u8 means 0 to 28-1 = 128
signed means -28-1 to 28-1
Rust’s floating-point types are f32 and f64, which are 32 bits and 64 bits in size, respectively.
In the below example we assigned a value 129 to varialble ‘b’ which is of ‘i8’ ,so the program won’t get compiled.
fn main(){
   let a:i8 = 127;
   let b:i8= 129;  //this will cause overflow.
   let c:f32=123.32;
   let d:i8 = -127;
   let e:u8 = 127;

  println!("{}.{},{},{},{}",a,d,c,e,b);
}

when you compile the program,

error: literal out of range for `i8`
 --> datatype.rs:3:13
  |
3 |   let b:i8= 129;
  |             ^^^
  |
  = note: #[deny(overflowing_literals)] on by default


String:
Strings in python can be denoted by single quotes(’), double quotes("), triple quotes(""").
name1    = 'naveen'
name2    = "davis"
fullname = """naveen davis
                       vallooran"""
python3
It possible to access the characters in a string using their index in python.
python-string2
nam1[0] prints the character 'n'

Saturday, August 10, 2019

Learn Python ,Rust and C - blog post 1

Learn Python ,Rust and C - session 1

Learning Python ,Rust , C programming together

I have seen in different forums that people ask following questions " Why should I learn multiple programming language ?" or “Should I learn C or Python or JavaScript ?”.
My opinion would be , you can concentrate on one language and learn it deep. But as a developer some point of time it is important that to learn multiple programming languages and understand the difference and know where these languages are strong. This would helps you take decision on which language to use for your application.

Python Hello world : you can run this program from a python interpreter or save the program in in file and run with python.
install python - python

//python programming 
print("hello world")

enter image description here

Rust Hello world
The below Rust program needs to be saved in filename.rs and compiled with Rust compiler.t
Please follow the link for Rust installation How to install rust

///Rust programming 
fn main(){
 println!("hello world");
}

enter image description here

or You can create a rust programs using Cargo.
The link will help you to install cargo - Cargo
enter image description here

C Hello world
You preferred to have GCC compiler to generate C program executable.
installation -
Ubuntu GCC installation
Windows GCC

The program can be saved in a helloworld.c and compile and execute as below .

enter image description here

#include<stdio.h>
int main(){
    printf("hello world\n");
}

Python Rust C
Interpreting language compiled language compiled language
platform independent cross platform
individual building or compilation for each platform that it supports,
platform dependent
Strongly typed
dynamically typed
strongly typed and dynamically typed weekly typed and statically typed
objected oriented Object-Oriented Programming is a way of modeling programs that originated with Simula in the 1960s and became popular with C++ in the 1990s. There are many competing definitions for what counts as OOP, and under some definitions, Rust is object-oriented; under other definitions, it is not. structural language
inbuilt garbage collector no separate garbage collector,but memory management is done automatically in compile time manual memory management