How to insert print for each function of C language for debugging? - c

I am studying and debugging one software. There are thousands of functions in this software. I plan to add printf() at the entry and exit point of each function. It will take a lot of time.
Is there one tool/script to do this?
I may use '__cyg_profile_func_enter'. But it can only get address. But I have to run another script to get function name. I also hope to get value of input parameters of this function too.

You should give a try to AOP : Aspect Oriented Programming. Personnaly I've only tried with Java and Spring AOP but there's an API for C too : AspectC (https://sites.google.com/a/gapp.msrg.utoronto.ca/aspectc/home). From what I've seen, it's not the only one.
From what I've red about this library, you can add an pointcut before compiling with AspectC :
// before means it's a before function aspect
// call means it's processed when a function is called
// args(...) means it applies to any function with any arguments
// this->funcName is the name of the function handled by AspectC
before(): call(args(...)) {
printf("Entering %s\n", this->funcName);
}
(not tried by myself but extracted from the reference page https://sites.google.com/a/gapp.msrg.utoronto.ca/aspectc/tutorial)
This is only a basic overview of what can be done and you still have to deal with the compilation (documented in the page linked before) but it looks like it could possibly help you. Give a try with a simple POC maybe.

Related

How to create FMU slave and initialise FMU in C using Modelica's fmi headers

I'm creating a simple FMI demo system to try out FMI where I have 1 simulator connected to an FMU which computes the state of the system (represented as a number calculated from a closed-form equation) and another FMU that controls the system via a parameter in the closed-form equation. So the system looks something like
FMU-system <--> Simulator <--> FMU-control
In every iteration, I'm updating the system state based on 1 equation, and passing it to the control, which returns a parameter to be passed to the system.
I'm using FMI 2.0.3, and have read the specification. Right now I have 3 files, 1 to act as a simulator and 2 to act as the FMUs. But I'm having difficulties with the implementation of the FMUs and the initialisation of the simulator.
To initialise the FMU, my understanding is I need to call fmi2Instantiate which has this signature.
fmi2Component fmi2Instantiate(fmi2String instanceName, fmi2Type fmuType, fmi2String fmuGUID, fmi2String fmuResourceLocation, const fmi2CallbackFunctions* functions, fmi2Boolean visible, fmi2Boolean loggingOn);
But I don't know what to pass in the function for the GUID, resource location and callback function. How should I implement the callback function and initialisation?
Then to implement the FMU, my understanding is I need to implement fmi2SetReal, fmi2GetReal and fmi2DoStep, but I can't figure out how to implement them in terms of code. These are the signatures
fmi2Status setReal(fmi2Component c, fmi2ValueReference vr[], size_t nvr, fmi2Real value[])
fmi2Status getReal(fmi2Component c, fmi2ValueReference vr[], size_t nvr, fmi2Real value[])
fmi2Status doStep(fmi2Component c, fmi2Real currentCommunicationPoint, fmi2Real communicationStepSize, fmi2Boolean noSetFMUStatePriorToCurrentPoint)
But I can't figure out how to implement these functions. Is fmi2Component c meaningless here? And I suppose I have to do the system state computation for the FMU-system in doStep. How should I update the state and pass the code here?
Sorry if this is too many questions but I was trying to look for a tutorial too and I couldn't find any.
https://github.com/traversaro/awesome-fmi
This is a curated list of Functional Mock-up Interface (FMI) libraries, tools and resources.
There are non commercial tools available. Check them out, you will get idea to implement these functions for your application.
A good starting point to implement FMI support are the open source Reference FMUs (which recently also got a simple FMU simulator) and fmpy:
https://github.com/CATIA-Systems/FMPy
https://github.com/modelica/Reference-FMUs/tree/main/fmusim

LLVM Loop Simplify Pass

I am probably misunderstanding some basic concept how LLVM & passes work, anyhow here is my question:
I am currently working on a pass where I extend the runOnModule (https://llvm.org/doxygen/classllvm_1_1ModulePass.html) function. I would like to run LoopSimplify first on the IR, but I do not seem to understand how to do that. There is a run(Function &F, FunctionAnalysisManager &AM) function as described on https://llvm.org/doxygen/classllvm_1_1LoopSimplifyPass.html and as far as I understand it I can call it on every function in my module. But for that I need a member of that class (LoopSimplify) to call it on which I do not know where to get from and also some FunctionAnalysisManager. What are they for and how do they need to look like? It is not like I can just feed it some empty constructs right?
I want to do this for the following guarantee:
"Loop pre-header insertion guarantees that there is a single, non-critical
entry edge from outside of the loop to the loop header. This simplifies a
number of analyses and transformations, such as LICM." as described in https://llvm.org/doxygen/LoopSimplify_8h_source.html.
While I support the directions to integrate your pass into using the pass manager, nonetheless, there is a way to force LoopSimplify to run by making your pass require it. This is also used in many of the LLVM provided passes, such as Scalar/LoopVersioningLICM.cpp
// This header includes LoopSimplifyID as an extern
#include "llvm/Transforms/Utils.h"
...
void YourPass::getAnalysisUsage(AnalysisUsage& AU) const {
AU.addRequiredID(LoopSimplifyID);
}
Doing so will force the pass to be run prior to your pass, no need to invoke it. However, if you need interface with this or another pass, you can request its analysis:
getAnalysis<LoopSimplifyPass>(F); // Where F is a function&

Track C variable doxygen

New to Doxygen and wondering can it be used to draw a graph showing what functions use a given global variable. I have been able to get call/caller graphs working for functions and want to do something similar for a hand full of variables.
REFERENCED_BY_RELATION = YES: In a Variable description it documents all functions which have used the variable and generates a hyperlink to these functions in the code. In the function documentation, this documents all functions being used in that particular function and also generates a hyperlink to the actual code.
REFERENCES_RELATION = YES: In a function documentation, this documents all functions that have called the function being described and also generates a hyperlink tot he code.
Although this is not a graphical solution (which would be way better), this is something one can definitely work with.

How can I parametrize a callback function that I submit to an external library

Say I have an external library that computes the optima, say minima, of a given function. Say its headers give me a function
double[] minimizer(ObjFun f)
where the headers define
typedef double (*ObjFun)(double x[])
and "minimizer" returns the minima of the function f of, say, a two dimensional vector x.
Now, I want to use this to minimize a parameterized function. I don't know how to express this in code exactly, but say if I am minimizing quadratic forms (just a silly example, I know these have closed form minima)
double quadraticForm(double x[]) {
return x[0]*x[0]*q11 + 2*x[0]*x[1]*q12 + x[1]*x[1]*q22
}
which is parameterized by the constants (q11, q12, q22). I want to write code where the user can input (q11, q12, q22) at runtime, I can generate a function to give to the library as a callback, and return the optima.
What is the recommended way to do this in C?
I am rusty with C, so asking about both feasibility and best practices. Really I am trying to solve this using C/Cython code. I was using python bindings to the library so far and using "inner functions" it was really obvious how to do this in python:
def getFunction(q11, q12, q22):
def f(x):
return x[0]*x[0]*q11 + 2*x[0]*x[1]*q12 + x[1]*x[1]*q22
return f
// now submit getFunction(/*user params*/) to the library
I am trying to figure out the C construct so that I can be better informed in creating a Cython equivalent.
The header defines the prototype of a function which can be used as a callback. I am assuming that you can't/won't change that header.
If your function has more parameters, they cannot be filled by the call.
Your function therefor cannot be called as callback, to avoid undefined behaviour or bogus values in parameters.
The function therefor cannot be given as callback; not with additional parameters.
Above means you need to drop the idea of "parameterizing" your function.
Your actual goal is to somehow allow the constants/coefficients to be changed during runtime.
Find a different way of doing that. Think of "dynamic configuration" instead of "parameterizing".
I.e. the function does not always expect those values at each call. It just has access to them.
(This suggests the configuration values are less often changed than the function is called, but does not require it.)
How:
I only can think of one simple way and it is pretty ugly and vulnerable (e.g. due to racing conditions, concurrent access, reentrance; you name it, it will hurt you ...):
Introduce a set of global variables, or better one struct-variable, for readability. (See recommendation below for "file-global" instead of "global".)
Set them at runtime to the desired values, using a separate function.
Initialise them to meaningful defaults, in case they never get written.
Read them at the start of the minimizing callback function.
Recommendation: Have everything (the minimizing function, the configuration variable and the function which sets the configuration at runtime) in one code file and make the configuration variable(s) static (i.e. restricts access to it this code file).
Note:
The answer is only the analysis that and why you should not try paraemeters.
The proposed method is not considered part of the answer; it is more simple than good.
I invite more holistic answers, which propose safer implementation.

Ruby C Extension using Singleton

I only wanted to allow one instance of my C extension class to be made, so I wanted to include the singleton module.
void Init_mousetest() {
VALUE mouseclass = rb_define_class("MyMouse",rb_cObject);
rb_require("singleton");
VALUE singletonmodule = rb_const_get(rb_cObject,rb_intern("Singleton"));
rb_include_module(mouseclass,singletonmodule);
rb_funcall(singletonmodule,rb_intern("included"),1,mouseclass);
### ^ Why do I need this line here?
rb_define_method(mouseclass,"run",method_run,0);
rb_define_method(mouseclass,"spawn",method_spawn,0);
rb_define_method(mouseclass,"stop",method_stop,0);
}
As I understand it, what that line does is the same as Singleton.included(MyMouse), but if I try to invoke that, I get
irb(main):006:0> Singleton.included(MyMouse)
NoMethodError: private method `included' called for Singleton:Module
from (irb):6
from C:/Ruby19/bin/irb:12:in `<main>'
Why does rb_include_module behave differently than I would expect it to? Also any tangential discussions/explanations or related articles are appreciated. Ruby beginner here.
Also it seems like I could have just kept my extension as simple as possible and just hack some kind of interface later on to ensure I only allow one instance. Or just put my mouse related methods into a module... Any of that make sense?
according to http://www.groupsrv.com/computers/about105620.html the rb_include_module() is actually just Module#append_features.
Apparently Module#include calls Module#append_features and Module#included. So in our C code we must also call included. Since clearly something important happens there.

Resources