<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gnana Ganesh on Medium]]></title>
        <description><![CDATA[Stories by Gnana Ganesh on Medium]]></description>
        <link>https://medium.com/@gnanaganesh?source=rss-b4a345f259af------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*efAznVRPPRD0EW84</url>
            <title>Stories by Gnana Ganesh on Medium</title>
            <link>https://medium.com/@gnanaganesh?source=rss-b4a345f259af------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:36:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gnanaganesh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Integrating existing C++ with Rust using autocxx]]></title>
            <link>https://medium.com/codex/integrating-existing-c-with-rust-using-autocxx-a1e4d41b8586?source=rss-b4a345f259af------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1e4d41b8586</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[interoperability]]></category>
            <category><![CDATA[autocxx]]></category>
            <category><![CDATA[binding]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Gnana Ganesh]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 02:17:54 GMT</pubDate>
            <atom:updated>2024-06-20T11:01:10.401Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Thanks <a href="https://medium.com/u/ad8be536a975">Atri Sarkar</a> for collaborating and helping to put this together</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TcEN8ml6myFOrS-A" /></figure><h3>Context:</h3><p>Rust and C++ are the two major programming languages in the system programming landscape. C++ has established itself as a ruler of this territory for more than 4 decades. But the recent shift in the security problems due to memory vulnerabilities which are more common in C++, is more like shooting yourself in your foot. This gave scope for new languages to get to this landscape. Rust, being a relatively new language (yet to complete its first decade in the industry), has a lot of great features to offer compelling even the experienced C++ developers to take a look at it. In this article we will be exploring how to use Rust project with existing C++ source code.</p><h3>Existing methods for integrating C++ with Rust</h3><p>In this article we will explore 3 different ways using which Rust and C++ can be integrated.</p><ol><li>Bindgen</li><li>Cxx</li><li>AutoCxx</li></ol><h4>Bindgen</h4><p>Bindgen can be used to automatically generate rust bindings to C and C++ code, although it is mostly used with C. Bindgen can be used both as a cli tool and as part of a build.rs script.</p><p>Bindgen needs to be passed a set of C header files from which it generates the rust ffi bindings.</p><p>It is as simple as:</p><pre>bindgen input.h -o bindings.rs</pre><p>While bindgen works well with C, support for C++ isn’t that great and the generated bindings are often not ergonomic to work with.</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ix6bgCSVjb0_6iAO" /></figure><p>The C++ version of this function returns a std::shared_ptr which gets translated to a std_shared_ptr in Rust. But here std_shared_ptr is an opaque type, so there’s no easy way to interact with it from Rust. We can’t even clone it!</p><p>This is also the case for all of the common C++ container types such as std::vector and std::map. This is where Cxx can be of help as it can share data between Rust and C++.</p><h4>Cxx</h4><p>Cxx is a library that helps to communicate between C++ and Rust. It helps in calling Rust functions from C++ and C++ functions from Rust. Also it helps in sharing data structures between Rust and C++ (For structs declared in Rust). It creates an intermediate hidden C ABI to communicate between Rust and C++.</p><p>This tutorial explains about how you can call a C++ function from Rust, Rust function from C++ and shared data structures</p><h3>Sample C++ project</h3><p>Let’s take a simple example, consider the following .cpp file</p><pre>#include &lt;iostream&gt;<br>#include &quot;shapes.hpp&quot;<br><br>void hello() {<br>  std::cout &lt;&lt; &quot;Hello, World!&quot; &lt;&lt; std::endl;<br>}<br><br>Square::Square(int s) : side(s) {}<br><br>std::unique_ptr&lt;Square&gt; create_square(int s) {<br>  return std::make_unique&lt;Square&gt;(s);<br>}<br><br>int Square::area() const {<br>  return side * side;<br>}<br><br>int Square::perimeter() const {<br>  return 4 * side;<br>}</pre><p>And its corresponding header file</p><pre>#pragma once<br>#include &lt;memory&gt;<br><br>void hello();<br><br>class Square {<br>  public:<br>    int side;<br>    Square(int s);<br>    int area() const;<br>    int perimeter() const;<br>};<br>std::unique_ptr&lt;Square&gt; create_square(int s);</pre><p>to create a Rust bindings using cxx, the main.rs might look like this.</p><pre>use cxx::UniquePtr;<br><br>#[cxx::bridge]<br>mod ffi {<br>    extern &quot;C++&quot; {<br>        include!(&quot;shapes.hpp&quot;);<br><br>        fn hello();<br><br>        type Square;<br><br>        fn create_square(s: i32) -&gt; UniquePtr&lt;Square&gt;;<br><br>        unsafe fn square_area(s: &amp;Square) -&gt; i32;<br>        unsafe fn square_perimeter(s: &amp;Square) -&gt; i32;<br>    }<br>}<br><br>fn main() {<br>    ffi::hello();<br><br>    let square = ffi::create_square(5);<br>    unsafe {<br>        println!(&quot;Square area: {}&quot;, ffi::square_area(&amp;square));<br>        println!(&quot;Square perimeter: {}&quot;, ffi::square_perimeter(&amp;square));<br>    }<br>}</pre><p>With cxx you have to define a bridge module which needs to be marked with the #[cxx::bridge] attribute, inside this module you need to whitelist types and methods that you want cxx to generate wrappers for using its custom DSL. Every type in the cpp has to be manually added to the ffi module, this might soon become tedious if the cpp project is fairly complex.</p><p>Cxx is the best choice if you want to freely modify the C++ codebase or if you have a small number of types/methods that needs to be used in Rust.</p><p>For more info about cxx, you can look into the <a href="https://cxx.rs/">documentation</a>.</p><h4>AutoCxx</h4><p>This tool comes in handy when you want to write bindings for existing C++ projects. This crate internally uses CXX to create the bindings but gives a much simplified way to create bindings. This is our main focus in this article.</p><h3>Creating a new Rust project</h3><p>To begin with we need a Rust project, you can create a new Rust project using the following command</p><pre>cargo new - bin shape-rs</pre><p>You can move the previous cpp files into the src directory of the newly created project.</p><blockquote>Note: The actual location of the cpp files can vary but make sure to denote the right path in the build script.</blockquote><h3>Add autocxx dependency</h3><p>To use autocxx in your Rust project, add autocxx and cxx to your Cargo.toml dependencies:</p><pre>[dependencies]<br>cxx = &quot;1.0&quot;<br>autocxx = &quot;0.7&quot;<br><br>[build-dependencies]<br>autocxx-build = &quot;0.26.0&quot;</pre><h3>Create a build script</h3><p>Build script is required to compile the cpp project before compiling the Rust project. Since we are using wrappers for the cpp project, it needs to be compiled first.</p><p>Let’s create a new file in the Rust project, build.rs with the following content</p><pre>fn main() {<br>  let mut build = autocxx_build::Builder::new(&quot;src/main.rs&quot;, &amp;[&quot;src&quot;])<br>    .build().unwrap();<br><br>  build.file(&quot;src/shapes.cpp&quot;)<br>  .std(&quot;c++14&quot;)<br>  .compile(&quot;shapes-rs&quot;);<br><br>  println!(&quot;cargo:rerun-if-changed=src/main.rs&quot;);<br>  println!(&quot;cargo:rerun-if-changed=src/shapes.hpp&quot;);<br>}</pre><p>In the above file, we are using the autocxx builder to compile the cpp file. The <em>println!</em> in the end is used to tell the compiler to rebuild only if there is a change in the main.rs or <em>shapes.hpp</em>.</p><h3>Starting with Rust Wrapper</h3><p>In the main.rs add the following</p><pre>use autocxx::prelude::*;<br><br>autocxx::include_cpp! {<br>  #include &quot;shapes.hpp&quot;<br>  safety!(unsafe)<br>  generate!(&quot;Square&quot;)<br>  generate!(&quot;create_square&quot;)<br>}<br><br>fn main() {<br>  let square = ffi::create_square(c_int(5));<br>  println!(&quot;Area: {} units&quot;, square.area().0);<br>  println!(&quot;Perimeter: {} units&quot;, square.perimeter().0);<br>}</pre><p>The crate autocxx has a set of preludes that are being imported, then we are using the include_cpp macro to let the autocxx know what are the files we are interested in. In this case we are creating a wrapper for Square in the file <em>shape.hpp</em> so we include only the shape.hpp.</p><p>Next, we are using the generate macro to denote the types or methods in the header file, since we have a type named Square in the header file, we can mention that, next we are passing the standalone function create_square to the generate macro.</p><p>That’s all you have to write, <em>autocxx</em> will let the magic happen.</p><p>In the main function, we are calling the module as you would call any Rust module and then using the types and its associated methods like area and perimeter. This shows how powerful <em>autocxx</em> can be.</p><h3>Conclusion</h3><p>While Rust’s memory safety and other benefits are compelling, migrating entire C++ codebases can be a daunting task. The <em>autocxx</em> empowers developers to embrace Rust’s strengths while leveraging existing C++ code, accelerating development. As Rust continues to gain momentum, tools like autocxx will play a crucial role in enabling seamless integration and unlocking the full potential of both languages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1e4d41b8586" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/integrating-existing-c-with-rust-using-autocxx-a1e4d41b8586">Integrating existing C++ with Rust using autocxx</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust Code Coverage Internals: What happens under the hood when you compile your Rust code for…]]></title>
            <link>https://medium.com/@gnanaganesh/rust-code-coverage-internals-what-happens-under-the-hood-when-you-compile-your-rust-code-for-c8fe5c38b237?source=rss-b4a345f259af------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8fe5c38b237</guid>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[llvm]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[code-coverage]]></category>
            <category><![CDATA[rustlang]]></category>
            <dc:creator><![CDATA[Gnana Ganesh]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 03:26:14 GMT</pubDate>
            <atom:updated>2024-06-05T03:26:14.461Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rust Code Coverage Internals: What happens under the hood when you compile your Rust code for coverage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-hqJZAQS5ji6ug6YuGxtgQ.jpeg" /></figure><h3>Context:</h3><p>Rust is a compiled language. It creates an executable or a library depending on the nature of the application. The Rust compiler has several stages which compiles the code to a lower level as it passes through each stage. In this article, let’s explore how Rust compiler adds metadata to the compiled binary and how this data is later used by profiler runtime which generates the code coverage data.</p><h3>Flags:</h3><p>First, to let the Rust compiler know that it needs to add metadata for coverage to the compiled binary, we need to pass additional flags to the compiler. Rust compiler provides 2 different flags that can be used to get the coverage data. Each flag is completely different from the other due to the fact that they use a different compiler backend.</p><ol><li>-z profile: This flag is GCC-compatible</li><li>-C instrumentCoverage: This flag used the LLVM intrinsics to generate the coverage data</li></ol><p>&gt; **Note:** Intrinsics are special functions recognized by the compiler that often map directly to underlying hardware instructions, allowing for low-level code generation and optimization.</p><h3>LLVM Based Code Coverage</h3><p>This article will focus on the `-C instrument-coverage` flag as it’s the preferred method for generating coverage data in Rust. Let’s delve into how this flag influences the compilation process.</p><h4>What is a Counter?</h4><p>At its core, code coverage relies on counting the executions of specific code segments. The compiler achieves this by inserting “counters” at strategic locations within the compiled binary. These counters are essentially variables that increment each time the associated code segment is executed.</p><h4>What Happens at Different Stages of a Compilation?</h4><p>When the `-C instrument-coverage` flag is used, the compiler performs the following actions during the compilation process:</p><ol><li><strong>Instrumentation:</strong> During the intermediate representation (IR) generation stage, the compiler identifies basic blocks within the code. A basic block is a sequence of instructions with a single entry point and a single exit point. The compiler then inserts calls to LLVM intrinsic functions that increment counters at the beginning of each basic block.</li></ol><p><strong>Example: Original Rust code</strong></p><pre>fn foo(x: i32) -&gt; i32 {<br>  if x &gt; 0 {<br>    x + 1<br>  } else {<br>  x - 1<br>  }<br>}</pre><p><strong>Example: LLVM IR with instrumentation (simplified)</strong></p><pre>define i32 @foo(i32 %x) {<br>entry:<br>%cmp = icmp sgt i32 %x, 0<br>br i1 %cmp, label %if.then, label %if.else<br>if.then: ; preds = %entry<br>call void @llvm.instrprof.increment(…) // Increment counter for &quot;if.then&quot;<br>%addtmp = add i32 %x, 1<br>br label %if.end<br>if.else: ; preds = %entry<br>call void @llvm.instrprof.increment(…) // Increment counter for &quot;if.else&quot;<br>%subtmp = sub i32 %x, 1<br>br label %if.end<br>if.end: ; preds = %if.else, %if.then<br>%result = phi i32 [ %addtmp, %if.then ], [ %subtmp, %if.else ]<br>ret i32 %result</pre><p>2. <strong>Counter Generation</strong>: The compiler creates global variables to represent the counters. Each counter is associated with a specific basic block.</p><p>3. <strong>Metadata Embedding</strong>: The compiler embeds metadata within the compiled binary. This metadata contains information about the counters, their locations, and the associated source code.</p><h4>What is a Profile Runtime?</h4><p>The “profile runtime” is a library linked with the instrumented binary. It’s responsible for managing the counters and providing the infrastructure for generating coverage data. The Rust standard library includes this runtime.</p><h4>How the Profile Runtime is Used</h4><p>The profile runtime performs the following actions:</p><p>1. <strong>Counter Initialization</strong>: At program startup, the runtime initializes all counters to zero.</p><p>2. <strong>Counter Incrementing:</strong> As the program executes, the runtime’s intrinsic function calls increment the relevant counters whenever a basic block is entered.</p><p>3. <strong>Data Collection:</strong> Upon program termination or through specific API calls, the runtime gathers the values of all counters.</p><h3>Generating Profraw Files</h3><p>The collected counter data is written to a file, typically named “default.profraw.” This file contains raw profiling information in a format specific to LLVM.</p><h4>What Does a Profraw File Contain?</h4><p>A profraw file stores:</p><p>1. <strong>Function Information:</strong> The names and addresses of all instrumented functions.</p><p>2. <strong>Counter Data:</strong> The values of all counters, representing the number of times each basic block was executed.</p><p>3. <strong>Mapping Information:</strong> Data that maps counters to their corresponding source code locations.</p><h3>Generating Reports From the Profraw Files</h3><p>Specialized tools, such as `llvm-profdata` and `llvm-cov`, are used to process the profraw files and generate human-readable code coverage reports. These tools utilize the mapping information within the profraw file to associate execution counts with specific lines of code.</p><h3>Conclusion</h3><p>The `-C instrument-coverage` flag empowers the Rust compiler to embed coverage instrumentation directly into the compiled binary using LLVM intrinsics. This, in conjunction with the profile runtime, enables the collection of detailed code coverage information during program execution. Utilizing tools like `llvm-profdata` and `llvm-cov`, developers can translate the raw profiling data into comprehensive reports, providing valuable insights into the effectiveness of their test suites and the overall coverage of their codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8fe5c38b237" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using SOME/IP to communicate between two EC2 instances]]></title>
            <link>https://medium.com/@gnanaganesh/using-vsomeip-to-communicate-between-two-ec2-instances-3c90140e9065?source=rss-b4a345f259af------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c90140e9065</guid>
            <category><![CDATA[someip]]></category>
            <category><![CDATA[automotive]]></category>
            <category><![CDATA[thoughtworks]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Gnana Ganesh]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 16:04:37 GMT</pubDate>
            <atom:updated>2024-04-17T04:52:59.357Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Thanks <a href="https://medium.com/u/300fca852">Randheer Ramesh</a> and <a href="https://medium.com/u/ad8be536a975">Atri Sarkar</a> <em>for helping to put this together!</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LatttJhVIZd1JyiHm4okTw.jpeg" /></figure><h4>Context:</h4><p>In this article , we will explore running SOME/IP application on a AWS EC2 instance. The application in itself is fairly simple. It is a client server application, where the client will send “World” and the server replies with “Hello, World!”. Along the way we will cover, setting up the EC2 with the vsomeip (an implementation of SOME/IP), enabling multicast in the AWS using VPC (you can skip this section if you are not using AWS EC2).</p><h3>SOME/IP:</h3><p>SOME/IP is a service oriented architecture, it is an application layer protocol. It can use both TCP and UDP for the transport layer. As you might have guessed, it runs on top of the IP. We will be using the C++ implementation of the protocol called vsomeip. Vsomeip is an open source implementation of SOME/IP by COVESA.</p><h3>Spin up EC2 instance</h3><p>Setup the EC2 instances in AWS following the <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html">official documentation</a></p><h3>Install vsomeip</h3><p>First, Clone the vsomeip repository using the below command,</p><pre>git clone git@github.com:COVESA/vsomeip.git</pre><p>Next, execute the following command to build the project and store the build artefacts</p><pre>cd vsomeip &amp;&amp; \<br>mkdir build &amp;&amp; \<br>cd build &amp;&amp; \<br>cmake . &amp;&amp; \<br>make &amp;&amp; \<br>make install</pre><blockquote>Note: You might have to run the code using sudo make install as it is installing the vsomeip library in the system folder.</blockquote><h3>Allow multicasting in the AWS:</h3><p>Multicast communication is not supported in AWS VPC. And in order to enable multicast communication between instances you need to create AWS Transit Gateway Multicast.</p><p>Steps to enable Multicast communication between instances.</p><ol><li><strong>Create Transit Gateway</strong></li></ol><p><em>a. Open VPC Console in AWS</em></p><p><em>b. Open Transit gateway from the left pane</em></p><p><em>c. Create a Transit Gateway with multicast support</em></p><p><strong>2. Create Transit Gateway Multicast Domain</strong></p><p><em>a. Open the Transit Gateway Multicast Domain from the VPC Console</em></p><p><em>b. Create a new Transit Gateway Multicast Domain</em></p><p><em>c. Choose the Transit Gateway created earlier in step 1.</em></p><p><em>d. Also enable IGMPV2 Support</em></p><p><strong>3. Create Transit Gateway Attachments</strong></p><p><em>a. Open the Transit Gateway Attachments from the VPC Console</em></p><p><em>b. Create a new Transit Gateway Attachment</em></p><p><em>c. Choose the transit gateway from step1</em></p><p><em>d. In the attachment type, select VPC</em></p><p><em>e. And select the VPC id in which the instances are running.</em></p><p><em>f. Choose the subnet IDs from the VPC for attachment.</em></p><p><strong>4. Create Transit Gateway Multicast Domain Associations</strong></p><p><em>a. Open the Transit Gateway Multicast Domain from the VPC Console</em></p><p><em>b. Select the multicast Domain.</em></p><p><em>c. Then Create new Subnet Associations by clicking on the create association button</em></p><p><em>d. Select the subnets to associate.</em></p><p><strong>5. Add Group Members in the Multicast Domain</strong></p><p><em>a. Open the Multicast Domain from the VPC Console</em></p><p><em>b. Click on Actions</em></p><p><em>c. Give the Group IP(Multicast Address) and Select the network interfaces of EC2 instances from the list.</em></p><p><em>d. And click the Add Group Members</em></p><h3>Setting up the sample application</h3><p>We will be building a simple server application that uses a UDP protocol and runs on the port 30509. This application will listen for requests from other SOME/IP services and responses back by appending “Hello, {request}“. It can be cloned from the git repository</p><pre>git clone git@github.com:gnana-ganesh-tw/vsomeip-sample.git</pre><p>This project contains the following folders</p><blockquote>client</blockquote><blockquote>server</blockquote><p>Build the <strong>client</strong> using the following command,</p><pre>cd vsomeip-sample/client &amp;&amp; \<br>mkdir build &amp;&amp; \<br>cd build &amp;&amp; \<br>cmake .. &amp;&amp; \<br>make</pre><p>Build the <strong>server</strong> application using the following command</p><pre>cd vsomeip-sample/server &amp;&amp; \<br>mkdir build &amp;&amp; \<br>cd build &amp;&amp; \<br>cmake .. &amp;&amp; \<br>make</pre><p>In the client folder all the code related to the <em>client</em> application is present, the interesting part here is the config file, lets go over it one by one,</p><pre>{<br>  &quot;unicast&quot; : &quot;&lt;your-client-IP&gt;&quot;,<br>  &quot;netmask&quot;: &quot;&lt;your-netmask-IP&gt;&quot;,<br>  &quot;logging&quot; :<br>  {<br>    &quot;level&quot; : &quot;debug&quot;,<br>    &quot;console&quot; : &quot;true&quot;,<br>    &quot;file&quot; : { &quot;enable&quot; : &quot;false&quot;, &quot;path&quot; : &quot;/var/log/vsomeip.log&quot; },<br>    &quot;dlt&quot; : &quot;false&quot;<br>  },<br>   &quot;applications&quot; : [<br>    {<br>      &quot;name&quot; : &quot;hello_world_client&quot;,<br>      &quot;id&quot; : &quot;0x1313&quot;<br>    }<br>  ],<br>  &quot;routing&quot; : &quot;hello_world_client&quot;,<br>  &quot;service-discovery&quot; : {<br>    &quot;enable&quot; : &quot;true&quot;,<br>    &quot;multicast&quot; : &quot;224.224.224.245&quot;,<br>    &quot;port&quot; : &quot;30490&quot;,<br>    &quot;protocol&quot; : &quot;udp&quot;,<br>    &quot;initial_delay_min&quot; : &quot;10&quot;,<br>    &quot;initial_delay_max&quot; : &quot;100&quot;,<br>    &quot;repetitions_base_delay&quot; : &quot;200&quot;,<br>    &quot;repetitions_max&quot; : &quot;3&quot;,<br>    &quot;ttl&quot; : &quot;3&quot;,<br>    &quot;cyclic_offer_delay&quot; : &quot;2000&quot;,<br>    &quot;request_response_delay&quot; : &quot;1500&quot;<br>  }<br>}</pre><ul><li><strong>unicast</strong> : This is the IP of the client application, you might have to change your client IP</li><li><strong>netmask</strong>: This the net-mask address of your machine</li><li><strong>logging</strong>: This specifies the log level of the application. Currently it is set to debug</li><li><strong>applications</strong>: This specifies the application ID and name of the client application</li><li><strong>routing</strong>: This is the routing service in your client application</li><li><strong>service-discovery:</strong> This is the parameters used by the SOME/IP-SD protocol</li></ul><blockquote>Note: You can find the netmask address using the ifconfig command.</blockquote><p>Similarly the configuration file of the <em>server</em> looks something like this</p><pre>{<br>  &quot;unicast&quot; : &quot;&lt;your-server-IP&gt;&quot;,<br>  &quot;netmask&quot;: &quot;&lt;your-netmask-IP&gt;&quot;,<br>  &quot;logging&quot; : {<br>    &quot;level&quot; : &quot;debug&quot;,<br>    &quot;console&quot; : &quot;true&quot;,<br>    &quot;file&quot; : { &quot;enable&quot; : &quot;false&quot;, &quot;path&quot; : &quot;/tmp/vsomeip.log&quot; },<br>    &quot;dlt&quot; : &quot;false&quot;<br>  },<br>  &quot;applications&quot; : [<br>    {<br>      &quot;name&quot; : &quot;hello_world_service&quot;,<br>      &quot;id&quot; : &quot;0x1212&quot;<br>    }<br>  ],<br>  &quot;services&quot; : [<br>    {<br>      &quot;service&quot; : &quot;0x1111&quot;,<br>      &quot;instance&quot; : &quot;0x2222&quot;,<br>      &quot;unreliable&quot; : &quot;30509&quot;<br>    }<br>  ],<br>    &quot;routing&quot; : &quot;hello_world_service&quot;,<br>  &quot;service-discovery&quot; : {<br>    &quot;enable&quot; : &quot;true&quot;,<br>    &quot;multicast&quot; : &quot;224.224.224.245&quot;,<br>    &quot;port&quot; : &quot;30490&quot;,<br>    &quot;protocol&quot; : &quot;udp&quot;,<br>    &quot;initial_delay_min&quot; : &quot;10&quot;,<br>    &quot;initial_delay_max&quot; : &quot;100&quot;,<br>    &quot;repetitions_base_delay&quot; : &quot;200&quot;,<br>    &quot;repetitions_max&quot; : &quot;3&quot;,<br>    &quot;ttl&quot; : &quot;3&quot;,<br>    &quot;cyclic_offer_delay&quot; : &quot;2000&quot;,<br>    &quot;request_response_delay&quot; : &quot;1500&quot;<br>  }<br>}</pre><ul><li><strong>services</strong>: Services is the configuration related to your services, this contains the port “30509” and it uses UDP as it mentioned “unreliable”\</li></ul><h3>Running the application:</h3><p><strong>Host:1</strong></p><p>To run the server application, run the following command,</p><pre>cd ~/vsomeip-sample/server/build &amp;&amp; \<br>VSOMEIP_CONFIGURATION=&lt;path-to-the-config&gt; VSOMEIP_APPLICATION_NAME=hello_world_service LD_LIBRARY_PATH=/usr/local/lib ./hello_world_service</pre><blockquote>Note: You have to specify the LD_LIBRARY_PATH to link vsomeip functions at runtime</blockquote><p><strong>Host: 2</strong></p><p>To run the client application, run the following command,</p><pre>cd ~/vsomeip-sample/client/build &amp;&amp; \<br>VSOMEIP_CONFIGURATION=&lt;path-to-the-config&gt; VSOMEIP_APPLICATION_NAME=hello_world_client LD_LIBRARY_PATH=/usr/local/lib ./hello_world_client</pre><p>You might be able to see the Client has received the response “Hello, World”</p><h3>Conclusion</h3><p>That brings us to the end of this blog, this shows the communication between two devices running on a EC2 machine communicating with each other using the SOME/IP.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c90140e9065" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Robust Rust: How Code Coverage Powers Rust Software Quality]]></title>
            <link>https://medium.com/@gnanaganesh/robust-rust-how-code-coverage-powers-rust-software-quality-417ef3ac2360?source=rss-b4a345f259af------2</link>
            <guid isPermaLink="false">https://medium.com/p/417ef3ac2360</guid>
            <category><![CDATA[code-coverage-tools]]></category>
            <category><![CDATA[mcdc]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[code-coverage]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Gnana Ganesh]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 09:01:00 GMT</pubDate>
            <atom:updated>2024-02-14T05:46:22.173Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Thanks to <a href="https://medium.com/u/2ca442fa51f6">Amit Dharmapurikar</a> and <a href="https://medium.com/u/ad8be536a975">Atri Sarkar</a> for helping to put this together!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cW_gly6vhog-pGqWRj3K4w.jpeg" /></figure><h3>Introduction</h3><p>Code coverage is a crucial metric which can provide a good insight about the software quality. Code coverage is typically expressed in percentage and provides information about how much of your software and which parts of your code have been tested by a set of unit tests or a test suite. Imagine it as a text highlighting tool which shows which parts of code are tested and which parts of the code can be considered for further testing in order to improve the quality of your code.</p><p>Higher code coverage increases confidence in your code&#39;s functionality and reduces the risk of bugs. Most of the code coverage tools can be integrated in a CI pipeline so that code coverage is continuously improved as your code grows. In several projects, code coverage requirements are included in merge policies to ensure software quality. As code coverage tools also report the areas of code which are not tested by the test suite, it helps to identify the focus areas for testing. In certain regulated domains like automotive, aerospace and healthcare where safety is crucial, code coverage requirements are part of the qualification and certification process.</p><p>There are various methods available for estimating the code coverage by a test suite as discussed briefly below.</p><ol><li><strong>Statement coverage</strong>: Although a more popular term is line coverage, in many languages, there could be multiple statements in a line, therefore purists prefer to use statement coverage. If a statement is executed at least once when you run the test suite, it is considered to be covered.</li><li><strong>Region coverage</strong>: It is the percentage of code regions that have been executed. A code region may span multiple lines consisting of multiple statements, such as a function body.</li><li><strong>Branch coverage:</strong> Branch coverage is a metric used in software testing to assess how many branches or decision points in a program&#39;s control flow have been executed by a set of test cases. In the context of code coverage analysis, a &quot;branch&quot; typically refers to a decision point in the code where the program can take different paths based on a condition (e.g., an if statement or a switch statement).</li><li><strong>MC/DC coverage:</strong> Modified Condition/Decision Coverage (MC/DC) is a rigorous software testing technique used in safety-critical systems. It ensures that every decision in the code has been tested under all possible outcomes, and each condition within a decision can independently affect the decision’s outcome.The strength of MC/DC lies in its efficiency. It provides high fault-detection while requiring fewer test cases than full condition coverage</li></ol><p>In this blog, we will discuss how we can generate code coverage information for Rust applications. We will also discuss the current state and features we can expect in the future versions of Rust compiler related to the code coverage support. Rust uses LLVM as the compilation backend. Accordingly, Rust compiler leverages some of the instrumentation coverage features provided by LLVM. The code coverage support features in Rust are expected to grow as corresponding features are added in LLVM. We will briefly discuss the Rust compiler dependencies on LLVM’s code coverage features.</p><h3>Enabling code coverage in Rust</h3><p>Code coverage data in Rust can be collected with two methods as follows:</p><ol><li><em>Using -Z profile command flag:</em></li></ol><p>This uses the gcc-compatible gcov based coverage implementation. In simple terms, it helps you collect coverage data based on DebugInfo. This is super handy when you want to see which parts of your code are being executed and which aren’t. It’s like having a roadmap of your code execution.</p><p>2.<em> Using -C instrument-coverage command flag:</em></p><p>This flag enables LLVM’s native coverage instrumentation, which is known for its efficiency and precision. It provides highly accurate coverage data, which checks for the exact parts of code that is being executed. This can be very useful for identifying areas of your code that aren’t being tested. So, when you’re looking to improve the robustness of your tests with highly accurate data, you can go for -C instrument-coverage based coverage tools.</p><p>In this blog, we will discuss the -C instrument-coverage flag in detail which is more widely used for source-based code coverage.</p><p>Following simple example shows how this works.</p><pre>pub fn is_even(n: u32) -&gt; bool {<br><br>    if n % 2 == 0 {<br><br>        true<br><br>    } else {<br><br>        false<br><br>    }<br><br>}</pre><p>and its corresponding test:</p><pre>#[test]<br>pub fn test_even() {<br>	assert_eq!(is_even(2), true);<br>}</pre><p>To enable code coverage, we pass the -C instrument-coverage flag while compiling the program with the Rust compiler.</p><p>If we are using Cargo for building the program, we can enable this flag by setting the RUSTFLAGS environment variable as shown below.</p><pre>RUSTFLAGS=&quot;-Cinstrument-coverage&quot; cargo test</pre><p>This will produce something called an “instrumented” binary/executable, which has extra code injected into it to count lines, regions and branches.</p><p>Effectively what happens is that the compiler injects counter increments like shown below to keep track of the counts:</p><pre>pub fn is_even(n: u32) -&gt; bool {<br><br>    is_even_counter += 1;<br><br>    if n % 2 == 0 {<br><br>        is_even_true_branch_counter += 1;<br><br>        true<br><br>    } else {<br><br>        is_even_false_branch_counter += 1;<br><br>        false<br><br>    }<br><br>}</pre><p>So whenever a specific function/region or branch is entered, an associated counter is incremented. All of these counters are stored in a specific location in the program’s memory.</p><p>Apart from this an extra runtime is also injected into the binary which initialises and manages these counters throughout the life of the program (called the LLVM profiler runtime).</p><pre>//Implicit main of test binary<br><br>pub fn main() {<br><br>    __initialize_counters();<br><br>    test_even(); <br><br>    //Other tests….<br><br>    __write_counter_data_to_file();<br><br>}</pre><p>When the program exits, the raw data from these counters is written to a “profraw” file which can be used to create a coverage report.</p><blockquote>Note: This is an oversimplification for explanation purposes. The compiler doesn&#39;t actually inject counters at the source code level. In reality, during compilation the source code is successively converted into a series of lower level representations (called lowering), and in one such representation, the <a href="https://rustc-dev-guide.rust-lang.org/mir/index.html">MIR</a>, is where the actual counter injection happens.</blockquote><h3>Code coverage tools in Rust</h3><p>These are some of the popular coverage tools in Rust</p><ol><li>Tarpaulin: Tarpaulin is a free Rust library providing source code line coverage functionalities. It’s still in an early stage of development, but it’s already proving a good choice for testing Rust applications.</li><li>grcov: grcov is a free library that collects and aggregates code coverage information for all the Rust files in your project.This internally uses the llvm-cov to create the reports.</li><li>cargo-llvm-cov: This is another popular tool for Rust code coverage.</li></ol><h4>Using cargo-tarpaulin</h4><p>Cargo-tarpaulin is a popular tool in the Rust ecosystem for collecting code coverage data. It&#39;s designed to be used with the cargo build system. Here&#39;s a simple example of how you might use cargo-tarpaulin</p><pre># Install cargo-tarpaulin<br><br>cargo install cargo-tarpaulin<br><br># Run cargo-tarpaulin to collect coverage data<br><br>cargo tarpaulin<br><br># cargo-tarpaulin will automatically generate a report in the console</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*my5Iz9XEvv7gNAX_WWKfRQ.png" /></figure><p>In this example, we first installed cargo-tarpaulin and then, we ran cargo-tarpaulin. This will run your tests and collect coverage data, printing a report to the console when it’s done. For more detailed reports, cargo-tarpaulin supports several output formats like Json, Xml, and Html.</p><h4>Using grcov</h4><p>Grcov is a Rust tool that collects and aggregates code coverage data from test suites. It&#39;s particularly useful when you want to integrate code coverage reporting into your continuous integration pipeline. Here&#39;s a simple example of how you might use grcov with a Rust project:</p><pre># Install grcov<br><br>cargo install grcov<br><br># Run your tests<br><br>RUSTFLAGS=&quot;-Cinstrument-coverage&quot; cargo test<br><br># Generate a coverage report<br><br>grcov . -s . --binary-path ./target/debug/ -t html --ignore tests/  -o ./target/debug/coverage/<br><br># Now you can view the report by opening an HTML file in your browser<br><br>open target/debug/coverage/index.html</pre><p>In this example, we first installed grcov and then we ran our tests with coverage instrumentation enabled. The RUSTFLAGS and LLVM_PROFILE_FILE environment variables are set to enable coverage collection. Finally, we use grcov to generate a coverage report, specifying the source directory, binary path, output type (HTML), and output directory. The generated report can be viewed in a web browser.</p><p>Following image shows a sample coverage report. We can find the coverage information for each Rust module in the project such as - line coverage, function coverage and branch coverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Khyo1JrBBxv7m9pGXJh5-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aFpcuLeLcL-ywSmAyxSc4Q.png" /></figure><h4>Using cargo-llvm-cov</h4><p>Cargo-llvm-cov is a Rust tool that leverages LLVM&#39;s source-based code coverage to generate detailed coverage reports. Here&#39;s a simple example of how you might use cargo-llvm-cov with a Rust project:</p><pre># Install cargo-llvm-cov<br><br>cargo install cargo-llvm-cov<br><br># Run your tests with coverage<br><br>cargo llvm-cov<br><br># This will generate a detailed coverage report in the console</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRqVB5QGxPfUhm6NI4BqYQ.png" /></figure><p>In this example, we first install cargo-llvm-cov using cargo install cargo-llvm-cov. Then, we run our tests with coverage using cargo llvm-cov --workspace --all-features -- tests. This command will run your tests and collect coverage data, printing a detailed report to the console when it’s done. For more advanced usage, cargo-llvm-cov supports several command-line options to customize the coverage collection and reporting process.</p><h3>Conclusion</h3><p>As we discussed, code coverage provides highly useful information for assessing and improving the quality of your source code. Rust already provides good support for features such as line coverage, function coverage etc. However, some features are still yet to be added. Though LLVM supports branch coverage and MC/DC coverage, there is still some work which is under progress for Rust. If it makes you curious, you can see the discussion on these features <a href="https://github.com/rust-lang/rust/issues/79649">here</a> in the community. Thus, code coverage for Rust applications is an evolving topic and we can expect these features to be available as they get added to the Rust compiler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=417ef3ac2360" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>