Wednesday, February 12, 2020
Going to back OS/system related computer courses
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.

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()

Sunday, December 1, 2019
Sunday, November 17, 2019
Saturday, November 16, 2019
Thursday, September 19, 2019
A bit research on String type in Rust
How did the String Type in Rust define?
There are two type of string types in Rust. Once is &str and other one is “String”.
String is heap allocated, grow able and not null termiated type.
&str is a slice(&[u8] ) that always points to a UTF8 valid sequence.
learn more about type usage here String types
But we are trying to focus on “String” type and how do we search Rust source code to see how this type is implemented.
String type - Heap allocation
Heap allocated memory implies that there will be pointer behind the definition of this type.
Let’s see,
We can get the rust source from below link.
https://doc.rust-lang.org/std/string/struct.String.html
click on the src button, as highlighted in the link.
it will directly take you to the surprising fact that String is simply a vector ( vec ).
String is a Vec<u8>
We know that Vec is also a heap allocated memory. In order to find how “vec” is defined in the source ,we need to search keyword “Vec” in the source code.
click on “src”
Interestingly, you will see the code.
pub struct Vec<T> {
buf: RawVec<T>,
len: usize,
}
I haven’t heard about RawVec earlier, but this is coming from : crate::raw_vec::RawVec;
raw-vec is implemeted for handling contiguous heap allocations.
Rawvec is implemented as below using a Unique pointer.
As guessed , we come to know that String type is actually using a pointer.
But what is unique pointer?
It comes from use core::ptr::Unique;
Unique is wapper around a raw non nullable ‘*mut T’.
interesting …
NonZero is wrapper type for raw pointers and integers that never becomes zero or null .
Tuesday, August 27, 2019
FFI tricks in Rust programming Language
How to do a trick on your Rust compiler to allow external (Foreign Language - FFI) functions
Rust is cool programming language which you can easily plugin to other languages ( Foreign Languages) .
Some of the FFI (Foreign language Interface) methods to call rust programs from C programming and Python programming languages are explained here.
Rust - Two things you should know for allowing Foreign language to call
#[no_mangle]
You might see lot of libraries using #[no_mangle] procedural macro.
The #[no_mangle] inform the Rust compiler that this is foreign language function and not to do anything weird with the symbols of this function when compiled because this will called from from other languages. This is needed if you plan on doing any FFI. Not doing so means you won’t be able to reference it in other languages.
extern
The extern keyword is used in two places in Rust. One is in conjunction with the crate keyword to make your Rust code aware of other Rust crates in your project, i.e. extern crate lazy static. The other use is in foreign function interfaces (FFI).
read more extern
how to create a shared object ie .so file from your Rust program ?
We can create a library in Rust using command below command
We are required to update the Cargo.toml
[dependencies]
[lib]
name = "callc"
crate-type = ["staticlib", "cdylib"]
cdylib is important crate type to specifiy in the Cargo.toml.
--crate-type=cdylib
, #[crate_type = "cdylib"]
- A dynamic system library will be produced. 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.
Read more on this here linkage
Cargo new callc
//lib.rs
#[no_mangle]
pub extern fn hello(){
println!("hello world inside rust ");
}
as we discussed earlier , since we use #[no_mangle], we can directly go ahead and compile it.
cargo build --release
How to check the generate .so file ?
A file with extension “.so” will generated in you target->release library.
run the below command to verify the function in the shared object.
$nm -D ‘filename.so’ | grep ‘function_name’
Our external function name is available in the shared object file created.
Create a C program for calling the shared object ( .so file)
create C program to call the hello function in your ‘src’ folder.
hello.c
#include<stdio.h>
#include "hello.h" /*header file to be included
/* the main C program to call the hello function
/* hello function is resides in the .so ( shared object) file
int main(void){
hello();
}
Below header file needs to be created in your ‘src’ folder
hello.h
/*the header include file should have the function declaration.
void hello();
We should link the .so file while compiling the c program. The below command will link and compile the program.
While compiling the C program, link the .so file the ‘release’ folder.
gcc -o hello hello.c -L. -Isrc /home/naveen/rustprojects/callc/target/release/libcallc.so
Your C program should get compiled and 'hello’e executable should be generated.
How do you call a Rust program from Python.
We are going to use the crate pyo3 for creating python modules.
create the projectfolder using cargo
cargo projectname --lib
Your Cargo.toml file should be updated as below in library and dependency sections.
[lib]
name = "string_sum"
crate_type = ["cdylib"]
[dependencies.pyo3]
version = "0.7.0"
features = ["extension-module"]
update the lib.rs with the below code:
use pyo3::prelude::*;
use pyo3::wrap_pyfunction;
#[pyfunction]
///format the 2 numbers as string
fn sum_as_string(x:usize,y:usize) -> PyResult<String>{
Ok((x+y).to_string())
}
#[pymodule]
fn string_sum(py:Python,m:&PyModule) -> PyResult<()>{
m.add_wrapped(wrap_pyfunction!(sum_as_string))?;
Ok(())
}
You can build the Rust program using Cargo build --release
This will create .so object in your cargo release folder. You might need to rename the file libstring_sum.so to string_sum.so
Now you can start import the module to the python interpreter and starting using the function string_sum
You might need to use python3 or 3+ interpreters for pyo3 to work.
As screenshot shows below , you can import the functions defined in the Rust module and use them in python.
Tuesday, August 20, 2019
One of powerful usage of Enum in Rust - Part1
Rust programming - Enum inside Struct
You might have come across this scenario in programming where you want to restrict a field type to restricted custom types.
Especially when you are working with APIs, the some of the field types can be one of the multiple custom types. You don’t want to accept the types other than defined custom types. enum can help you in these scenarios.
,eg event types can be ‘pullevent’, 'pushevent", ‘keypress’,‘mouseevvent’ etc
Example progarm
#[derive(Debug)]
///enum defined for vechicle type field
enum Oneoftwo{
Car(String),
Bus(String),
}
///struct defined for vehicle.
///Here we are using the defined enum as a type for a field in the struct
struct Vehicle{
type1:Oneoftwo,
price:i32,
}
///implementation for the vechile to create new instances
impl Vehicle {
fn new(type1:Oneoftwo,price:i32) -> Vehicle{
Vehicle{
type1,
price,
}
}
}
///main program to demostrate how to use enum inside a struct
fn main() {
///creating instances of the struct object
let honda = Vehicle::new(Oneoftwo::Car("honda".to_string()),4000);
let tata = Vehicle::new(Oneoftwo::Bus("Tata".to_string()),10000);
println!("{:?},{:?}",honda.type1,honda.price);
println!("{:?},{:?}",tata.type1,tata.price);
}
output:
Car("honda"),4000
Bus("Tata"),10000
Sunday, August 11, 2019
Learn Python ,RUST and C - blog post 2
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.
**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 |

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 |
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"""

It possible to access the characters in a string using their index in python.

nam1[0] prints the character 'n'
Saturday, August 10, 2019
Learn Python ,Rust and C - blog post 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")
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");
}
or You can create a rust programs using Cargo.
The link will help you to install cargo - Cargo
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 .
#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 |
Tuesday, May 28, 2019
Rust Closure - PART2
Closure Rust - Cont…
FnMut Trait
This is a continuation of the previous post ( https://naveendavisv.blogspot.com/2019/05/what-is-closures-how-can-it-be-used-in.html) on closures in rust.Last post we defined the closures as Fn(i32) -> i32 when we want to pass the closure to a function.
Fn trait borrows values from the environment immutably.
But now we will see what is FnMut? .
FnMut can change the environment because it mutably borrows values.
fn double(mut db1:T)
where T:FnMut() -> i32 {
println!("{:?}",db1());
}
fn main() {
let mut x = 10;
let db = || { x*=2; x};
double(db);
println!("{:?}",x);
}
The above example, the ‘x’ value will recalculated when we call the closure inside the function ( double)If we want to change a value in the environment that closure is enclosing, the FnMut trait can be used to define the closure.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5102dff068bc256a59bc9c8c9bf3f92f
Cacher struct with closure.
We will try to build a Cacher Structure as explained in the rust book - https://doc.rust-lang.org/book/ch13-01-closures.htmlThe need for Cacher structure is explained in the book.
Final part of Cacher structure chapter , the author ask us to create the struct with HaspMap to store the calculated value
I will try to explain the Code wrote in Rust here.
How nice would it be if we can cache the computation intensive function and store it's calculated values in a struct !!
A data structure with a 'Closure' and 'Hashmap' will serve the purpose very nicely.
How do we define Cacher Structure with HashMap ?
We can call data structure as Cacher as it cache/store the result values.Normally we don’t define the parameter type or return type of a Closure in Rust. But it is must to explicitly declare the field types of a Struct , so we need to explicitly define the 'T' where T is type of the Closure .Rust Compiler needs to understand all the field types of structures in order to allocate memory
resultMap field is Box (A pointer type for heap allocation - https://doc.rust-lang.org/std/boxed/struct.Box.html) reference to Hashmap.
If you don’t know how much memory you are going to use, one option would be “Box” type. Here we defined the field resultMao as Box reference to a HaspMap .
struct Cacher
where T:Fn(u32) -> u32
{
square:T,
resultMap:Box>,
}
How do we implement the Cacher Struct ?
We defined the Cacher Struct , the next step would be we need to implement the Struct with methods.one method that we would require is “new” . This method creates Objects of the Struct. Another one would be “value” - to get the value from the resultMap. As resultMap is reference to a HashMap , we can use “insert” method to add key and value pairs to the hashmap.
Also we can use “get” method to get a value for a key from the haspmap.
impl Cacher
where T:Fn(u32) -> u32{
fn new(square:T,mut resultMap: HashMap) -> Cacher{
Cacher{
square,
resultMap:Box::new(resultMap),
}
}
fn value(&mut self,x:u32) -> u32 {
match self.resultMap.get(&x){
Some(v) => *v,
None => {
let v = (self.square)(x);
self.resultMap.insert(x,v);
v
},
}
}
}
Tuesday, May 21, 2019
What is a Closure ? How can it be used in Rust programming ? - PART1
Closures in Rust
Closure is record storing a function along with it environment variables. You can read about closures in wiki
Difference between Closure and a function.
function definition:
Note: we have to explicitly pass the type and variable.
fn add (x:u32) -> u32 { x +1 }
Closure definition in Rust:
Note: We can follow any one of the following syntax to define a Closure
//explicitly defining types
let add = |x:u32| -> u32 { x +1 }
or
//the compiler dynamically type the Closure variables
let add = |x| -> {x+1}
or
//ignoring curly braces if you have only one statement
let add = |x| -> x+1
We will go through some example for Closure and discuss its features
Example#1 - passing Closure to a function
Below example shows the closure is defined with parameter ’ x ’ passed from environment where it is called. Closure is enclosed in a variable called square_x here.
We can see that value of the variable x is 2 . In the main program, first we define the Closure and then it is called from square_x(x) in println! statement.
square_x is the Closure.
When Closure looks for it's required variable's 'x' value for calculation, Closure its self will be enclosed with its required variables and understand that 'x' is parameter and it need to get its value from lexical environment which is 2 . And it perform the calculation: x*x - square of 2 which is 4.
The second print statement execute inside the function square . When we call the square(square_x) function, Closure invoked and looks for its lexical environment and find the value for parameter ‘x’ variable.The ‘x’ variable value is 3 over there, so the Closure calculate the square of 3 which is 9 .
fn square<T>(sq:T)
where T:Fn(i32) -> i32
{
let x = 3;
println!("square called from insidefn value = {}",sq(x));
}
fn main() {
let mut x = 2;
let square_x = |x| x*x;
println!("square of x = {}",square_x(x));
square(square_x);
}
From what we learned , Closure doesn’t need to specify it’s Parameters type or Return type. But in the (square) function definition, we explicitly defined ‘T’ as Fn(i32) -> i32.
Because for a function, it is necessary to define it's parameters type.
run in Rust Playground -
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c7dafb2aa3b7f7f83fc7490be6f30925
Example 2 # What will happen if we are not passing variable
This example we remove the passing parameter, to make the Closure as no-parameters.
let sq = || x*x;
But Closure has the property to get all its variables from its lexical environment . When you pass it to a function, it actually pass the Closure and along with variables enclosed.
fn square<T>(sq:T)
where T:Fn() -> i32
{
let x = 3;
println!("square called from insidefn value = {}",sq());
}
fn main() {
let x = 2;
let square_x = || x*x;
println!("square of x = {}",square_x());
square(square_x);
}
Example 3- What will happen if you pass different variable to Closure in the above example
fn square<T>(sq:T)
where T:Fn(i32) -> i32
{
let x = 3;
println!("square called from insidefn value = {}",sq(x));
}
fn main() {
let x = 2;
let square_x = |y| x*x;
square(square_x);
println!("square of x = {}",square_x(x));
}
Can you guess the output ?Hint : Closure is record which stores function along with its environment variables.
run the example above and check out the output.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7763c76893f87426f975db3eafab5e0f
https://doc.rust-lang.org/book/ch13-00-functional-features.html
Friday, April 12, 2019
Concurrency in Rust programming language- PART1
Concurrency in Rust - PART 1
As per Rust documentation, concurrency in Rust is Fearless concurrency. Handling concurrency in a safe and efficient way is one of the Rust goal. The Ownership is the back bone of rust concurrency.
Concurrency means multiple computations at the same time.
- In fact, concurrency is essential part of modern programming
eg > websites should handle multiple users at the same time
Graphical user interface need to do some background work when users are not interrupting the screens.
Multiple applications needs to run on the cloud (server)
Travel reservation system
Many algorithms can be broken down to concurrent parts -
merge sort
quick sort
summing a list by summing fragments in parallel
Concurrency can be achieved in Hardware level and software level. Here we will be talking about software concurrency and what makes Rust an efficient programming language to handle this.
Hardware examples:
- A single processor can have multiple execution pipelines (but only one set of registers)
- A processor can have multiple cores (multicore)
- A computer can have multiple processors
- A network can have multiple computers (Grid computing happens on these)
- An internet has multiple networks
- All combinations of the above
Software examples:
- Multiprogramming, or running a lot of programs concurrently (the O.S. has to multiplex their execution on available processors). For example:
- downloading a file
- listening to streaming audio
- having a clock running
- chatting
- analyzing data from some weird experiment
- streaming a movie
Two Models for Concurrent Programming
- Shared Memory - In this case, the same memory will be shared amount the processors /threads or programs.
A and B programs can be trying to use the same object .
A and B threads can be using the same file system that they can read and write. etc… - Message passing -
There will be a transmitter and a receiver in this model. They communicate each other through a communication channel. Modules sends the messages and the incoming messages will be queued up for modules.
A web browser and web server communication is an example. Web browser client request for a connection and web page, the server sends the data back to browser.
Jumping directly into Rust concurrency
Process. A process is an instance of a running program that is isolated from other processes on the same machine. In particular, it has its own private section of the machine’s memory.
Thread. A thread is a locus of control inside a running program. Think of it as a place in the program that is being run, plus the stack of method calls that led to that place to which it will be necessary to return through.
Threads are automatically ready for shared memory, because threads share all the memory in the process. It needs special effort to get “thread-local” memory that’s private to a single thread. It’s also necessary to set up message-passing explicitly, by creating and using queue data structures.
use::std::thread;
fn main() {
// spawning a new thread
let handle = thread::spawn(||{
loop {
println!("thread1");
}
});
//looping the main thread
loop{
println!("thread2");
}
}
thread::spawn function creates the new thread and returns a handle to it. The parameter would be a closure . Here it is an infinite loop that prints thread1.
You will see thread1 and thread2 printing in the screen. Unfortunately I could not get thread2 in the screenshot!
For listing the threads running under the process, you can use below command in linux
get the process id using command
ps -e
then use top -H -p processid
The memory and CPU usage for each threads can be listed using above command.
Run the below code and see the output …
The program just print “hello world”. It will not wait for the inner thread to complete and print the vector.
use::std::thread;
fn main() {
let v = vec![1,2,3];
let handle = thread::spawn(||{
println!("{:?}",v);
});
// handle.join().unwrap();
println!("Hello, world!");
}
Now remove comments (//) from handle.join().unwrap(); and run the program. You would assume the main thread wait for the inner thread to print the vector values as handle.join() makes main thread to wait/join with inner thread.
But,
We do get a compile time error . The error says the variable vector “v” does not live long enough. If the main thread complete without waiting for inner thread to complete (as we are seen above). The borrowed vector points to wrong memory when its tries to execute. Here Rust help us.
Rust compiler caught that scenario and threw an error .
Compiling concurrent-proj2 v0.1.0 (/home/naveen/rustprojects/concurrent-proj2)
error[E0597]: `v` does not live long enough
--> src/main.rs:11:19
|
10 | let handle = thread::spawn(||{
| -- value captured here
11 | println!("{:?}",v);
| ^ borrowed value does not live long enough
...
16 | }
| - `v` dropped here while still borrowed
We can use the move keyword to transfer the ownership of the variables that we are going to use in the inner thread from the environment.
Below program prints both vector values and helloworld.
use::std::thread;
fn main() {
let v = vec![1,2,3];
let handle = thread::spawn(move ||{
println!("{:?}",v);
});
handle.join().unwrap();
println!("Hello, world!");
}