How to make a block-based instrumentation for C code? - parsing

I am trying to instrument a piece of C code for code coverage. I am trying to achieve the block-based code coverage as mentioned here. And for a simple program as below:
int f()
{
if (a)
{
printf("aaaaa");
}
else if (b)
{
printf("bbbbb");
}
return 1;
}
I can make some simple instrumentation with ANTLR4 like this:
int f()
{/* probe here! */
if (a)
{/* probe here! */
printf("aaaaa");
}
else if (b)
{/* probe here! */
printf("bbbbb");
}
/* ????? */
return 1;
}
But according to the link above, I missed the probe at /* ????? */.
I guess the solution lies in the parse-tree manipulation algorithm. But I am no expert at parsing yet. Anyone could shed some light? Thanks.
I am using the ANTLR4 C grammar.
The parse tree I obtained for above code snippet is like this:
ADD 1
To ensure the instrumentation not jeopardize anything from the original source code, I have to keep all the original tokens, such as formatting tokens like NEWLINE and WHITESPACE. So that when I output the rewritten/instrumented source code, the format can remain. Luckily ANTLR's lexer provides multiple channels for different type of tokens. But be careful with the ANTLR token channel specification issue.
ADD 2 -- 9:44 AM 3/13/2018
Some progress so far. The ternary operator ? is not handled yet. I am wondering if there's a complete C code sample file that I can test with.
int f()
{/* compound statement */
if (a)
{/* compound statement */
printf("aaaaa");/* after function call */
}
else if (b)
{/* compound statement */
printf("bbbbb");/* after function call */
if (c)
{/* compound statement */
if(d)
{/* selection non-compound statement child */return 0;}
/* statment */printf("ccccc") ;/* after function call */
printf("ddddd");/* after function call */
if(d2)
{/* compound statement */
a1++;
a2++;
a3++;
return 1;
}
/* statment */switch (e)
{
case f:/* case */
f1++;
f2++;
f3++;
func("fffff");/* after function call */
f4++;
f5++;
break;
case g:/* case */
printf("ggggg");/* after function call */
break;
case i:/* case */
x() ;/* after function call */
if(x)
{/* compound statement */
x1();/* after function call */
if(y)
{/* selection non-compound statement child */abc();/* after function call */}
/* statment */x2();/* after function call */
}
case h:/* case */
default:/* default */
do {/* compound statement */
x();/* after function call */
if(a)
{/* selection non-compound statement child */return 1;}
/* statment */y();/* after function call */
z();/* after function call */
}while(abc);
/* statment */break;
}
}
/* statment */while(a)
{/* compound statement */
x();/* after function call */
}
g();/* after function call */
}
/* statment */xxx?yyy:zzz;
}

Related

Variadic Dispatch Function

I have an interface wherein the types of the parameters mostly encode their own meanings. I have a function that takes one of these parameters. I'm trying to make a function that takes a set of these parameters and performs the function on each one in order.
#include <iostream>
#include <vector>
enum param_type{typeA,typeB};
template <param_type PT> struct Container{
int value;
Container(int v):value(v){}
};
int f(Container<typeA> param){
std::cout<<"Got typeA with value "<<param.value<<std::endl;
return param.value;
}
int f(Container<typeB> param){
std::cout<<"Got typeB with value "<<param.value<<std::endl;
return param.value;
}
My current solution uses a recursive variadic template to delegate the work.
void g(){}
template <typename T,typename...R>
void g(T param,R...rest){
f(param);
g(rest...);
}
I would like to use a packed parameter expansion, but I can't seem to get that to work without also using the return values. (In my particular case the functions are void.)
template <typename...T> // TODO: Use concepts once they exist.
void h(T... params){
// f(params);...
// f(params)...; // Fail to compile.
// {f(params)...};
std::vector<int> v={f(params)...}; // Works
}
Example usage
int main(){
auto a=Container<typeA>(5);
auto b=Container<typeB>(10);
g(a,b);
h(a,b);
return 0;
}
Is there an elegant syntax for this expansion in C++?
In C++17: use a fold expression with the comma operator.
template <typename... Args>
void g(Args... args)
{
((void)f(args), ...);
}
Before C++17: comma with 0 and then expand into the braced initializer list of an int array. The extra 0 is there to ensure that a zero-sized array is not created.
template <typename... Args>
void g(Args... args)
{
int arr[] {0, ((void)f(args), 0)...};
(void)arr; // suppress unused variable warning
}
In both cases, the function call expression is cast to void to avoid accidentally invoking a user-defined operator,.

Is there a way in CppUtest that can call mock and real function at runtime in the same test file?

For example:
Production.cpp
int func1()
{
return 7;
}
void func2()
{
printf("func2");
}
void productionCode()
{
int x = func1();
if(x==7) func2();
}
TestProduction.cpp
int func1()
{
return mock().actualCall("func1").
returnIntValue();
}
void setExpFunc1(int x)
{
mock().expectOneCall("func1")
andReturnValue(x);
}
TEST(testGroupSample, testMockFunc1)
{
setExpFunc1(8);
// this will call mock func1()
productionCode();
}
TEST(testGroupSample, testRealFunc2)
{
// this will call real func1()
productionCode();
}
From my understanding, when func1() was mocked, there's no way to test the actual function.
Below sample code is just an idea on what I'm trying to do.
Because I have to test many functions that calls many functions inside.
Sometimes, I don't care on the actual result of those other function so I mocked it, but when I want to test the behavior of the real function when calling inside a function that I'm testing, I cannot do it since that function is already mocked.
Also I hope I can do this without modifying the production code, only the tests code.
No. You mocked using the linker, so, for the whole file context, the real functions do not exist.
You may achieve this by using function pointers (or std::function, …) to set the implementation used by productionCode() at runtime.
Pseudocode
int func1() { /* Production }
int func1_mock() { /* Mock */ }
std::function<int()> impl; // Use a function ptr for C
void productionCode()
{
int x = impl(); // Call current implementation
// ...
}
TEST(...)
{
impl = func1; // Use production code
productionCode();
impl = func1_mock; // Use mock instead
productionCode();
}

What are the prototypes for these flex functions in a re-entrant parser?

I'm converting a working flex/bison parser to run re-entrantly. The parser has the ability to accept include command-file.txt directives, which was implemented on the flex side of things like this:
^include { BEGIN INCL; }
<INCL>{ws}+ { /* Ignore */ }
<INCL>[^ \t\n\r\f]+ { /* Swallow everything up to whitespace or an EOL character.
* When state returns to initial, the whitepsace
* and/or EOL will be taken care of. */
yyin = fopen ( yytext, "r" );
if (! yyin) {
char filename[1024];
sprintf(filename,"/home/scripts/%s",yytext);
yyin = fopen( filename, "r");
if ( ! yyin) {
char buf[256];
sprintf(buf,"Couldn't open ""%s"".",yytext);
yyerror(buf);
}
}
yypush_buffer_state(yy_create_buffer(yyin, YY_BUF_SIZE));
BEGIN 0;
}
<<EOF>> {
yypop_buffer_state();
if (!YY_CURRENT_BUFFER) {
yyterminate();
}
}
This works nicely. Now that I've added %option reentrant and %option bison-bridge, I get these errors:
lexer.l:119: error: too few arguments to function `yy_create_buffer'
lexer.l:119: error: too few arguments to function `yypush_buffer_state'
lexer.l:123: error: too few arguments to function `yypop_buffer_state'
What are the proper ways to invoke these functions/macros in a re-entrant parser?
The reentrant interfaces are documented (briefly) in the flex manual.
All interfaces have one extra argument of type yyscan_t which comes at the end of the argument list. Examples (pulled from a flex-generated file):
YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner );
void yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
void yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner );
void yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner );
void yypop_buffer_state (yyscan_t yyscanner );
yylex follows the same pattern, so you can use yyscanner inside an action to refer to the argument provided to yylex

Porting javascript to dart

I'd like to port this javascript code to dart.
function Beagle() {
this.argv_ = null;
this.io = null;
};
Beagle.prototype.run = function() {
this.io = this.argv_.io.push();
};
runCommandClass(Beagle);
the probleme is
How to create object Beagle
How to create prototype object Beagle.prototype.run
This kind of Js code (function definition and prototype changes) can be ported to a Dart class. You can follow these main rules :
function Xxxx(){/* js code to init */} (pseudo Js class) translates to :
class Xxxx {
/// constructor
Xxxx() {
/* Dart code to init */
}
}
when you have contructor parameters like in function Xxxx(param1, param2){/* js code to init */} you have to create an other constructor with those parameters :
class Xxxx {
/// constructor with parameters
Xxxx(param1, param2) {
/* Dart code to init with param1, param2 */
}
}
Xxxx.prototype.method1 = function(p1, p2, p3){/* js code for method */} are like methods that have to be translated to :
class Xxxx {
// .... other code
/// method
method1(p1, p2, p3) {
/* Dart code */
}
}
To make your code more clear you can also add type annotations on methods and constructors. This is recommanded by the Dart Style Guide.
Type annotations are important documentation for how a library should be used. Annotating the parameter and return types of public methods and functions helps users understand what the API expects and what it provides.
For instance :
class Xxxx {
/// constructor
Xxxx(String param1, int param2) {
/* Dart code to init with param1, param2 */
}
/// method
void method1(num p1, String p2, DateTime p3) {
/* Dart code */
}
}
class Beagle { //
Map argv_;
int io;
Map portInfo;
// could make sense to make this a constructor, that depends how the Terminal class uses it (didn't look)
void run(this.argv_) {
this.portInfo_ = JSON.parse(this.argv_['argString']); // not tested
io = argv_['io'].length;
}
void sendString_(String s) { // no idea what the underlines at the end of argv_, sendString_, ... are for
// ...
}
void onRead_(String s) {}
void onTerminalResize_(int width, int height) {}
void exit(code) {
// ...
}
void close() {
// ...
}
}
var b = new Beagle(); // not translated from the JS source - just added to show how to create a new object from the Beagle class
b.run(argvFromSomewhere);
This includes a some guessing about what the intention of the JavaScript code might be.
I prefer using specific types when porting from JavaScript. It helped me a lot finding bugs and understanding the intention. When I guessed the wrong type I get an exception at runtime, then I can reason about why I got an unexpected type and which of my assumptions were wrong.

How to bind JavaScript callback in stable 1.1.1 Dart and bind Dart callback in JavaScript (Dart2Js2Dart)?

I want to write some Dart function "oKey" which calls JavaScript function "jsOnKey" (with success or exception too since cannot predict).
Next I want that JavaScript function "onKey" will call Dart function "callbackFromJs" to return control to Dart again (with success or exception).
Can you help me with this full flow - please assume SUCCESS or EXCEPTION on each border - I can not rely on 3rd party code - DART 2 JS 2 DART?
To make more context to this general question I put example code.
import 'dart:html';
void onKey(Event event) {
// I want to call something in javascript
// function callbackFromDart () {
// /* something */;
// /* call callbackJs in Dart - return control to dart */
// }
}
void callbackFromJs() {
// It should be called from JavaScript
}
void main() {
InputElement nameElement = querySelector('input[name=name]');
nameElement..placeholder = 'Enter text'
..onKeyUp.listen(onKey);
InputElement descriptionElement = querySelector('input[name=description]');
descriptionElement..placeholder = 'Enter text'
..onKeyUp.listen(onKey);
}
First have a look at Using JavaScript from Dart.
For your case you can simply pass callbacks to handle what you call Js 2 Dart :
import 'dart:js' as js;
void onKey(Event event) {
onSuccess() {
// Dart callback called from Js
}
onError() {
// Dart callback called from Js
}
// assuming your js function takes 2 callbacks as parameters
try {
// in JS : function a() { throw "throw from js"; }
js.context.callMethod('myTopLevelFunction', [onSuccess, onError]);
}
catch (e) {
print('js error catch on Dart side : $e');
}
}
The Dart exceptions can be catch with the same kind of code on Js side.

Resources