lcov how to cover static initialization and destruction function - gcov

In this page:
https://servernl1.sveena.com/lcov3987/c/s/c/port/lin/lindow.cpp.func-sort-c.html
there is this function
__static_initialization_and_destruction_0(int, int)
that is not covered.
What is this function? It is not in the source.
How do I cover it or exclude it?

For each translation unit that has a static global object which has to be constructed, gcc will generate a __static_initialization_and_destruction_0 function. The language mandates that all global objects are initialized before the first call to a function in the same translation unit.
Technically, I would assume that it is reached once you call a function from that translation unit, but maybe the coverage instrumentation does not generate code for it.
As it is an compiler-internal function, I would recommend to ignore it. I am not aware that lcov allows to define exclusions for indiviual functions.

Related

LLVM module-level inliner `ModuleInlinerWrapperPass` usage

From reading the source code of LLVM in lib/Transforms/IPO/Inliner.cpp I found that LLVM designed the actual inliner pass as a CGSCC pass, and then there is ModuleInlinerWrapperPass that wraps around the CGSCC pass to do per-module inlining.
Peeking inside PassBuilder.cpp, I found the module-level inliner wrapper pass is typically run at the PGO-instrumentation stage (as part of the addPGOInstrPipeline pipeline), as well as the LTO stage.
I was interested in the differences between the CGSCC pass and the module-level pass and which one is scheduled earlier, so I added some LLVM_DEBUG statements to print from the initializer of the module-level pass. seems like by default opt -O2 does not run the module-level inliner; instead, it runs the CGSCC pass quite early in the optimization pipeline.
My question is: When is the module-level inliner pass run in the optimization pipeline (if ever), and what is its relationship with the CGSCC inliner pass?
This question boils down to the difference between the new PassManager and old PassManager in LLVM.
Essentially, there are two ways to write a pass: either we can use the new PassManager (with pass classes extending PassInfoMixin<...>) or use the legacy PassManager (with pass classes extending ModulePass/CGSCCPass/FunctionPass...).
The new PassManager uses the PassBuilder class to schedule passes into pipelines and then run the pipeline in the sequence it is scheduled. The ModuleInlinerWrapperPass is essentially a module-level wrapper pass in order for the new PassManager to schedule inliner into its existing module-level optimization pipeline.

A more standard __attribute__((warning("msg"))

In my C++ library I have a function that is still there, 1) for debugging 2) for small operations.
The function is basically a very slow fallback of more efficient versions.
(think of a loop of individual assigments vs memcpy for example)>
For this reason I would like to emit a warning as soon the function is invoked instantiated directly or indirectly. Without a warning it is not easy to test if the function is being invoked instantiated, because the function might be called instantiated trough several layers of template code.
I found that GCC's __attribute__((warning("slow function!"))) does the job quite well.
template<class T>
__attribute__((warning("careful this fun is very slow, redesign your algorithm")))
void slow_function(T){...}
However it is not standard or compatible with clang.
Is there a better alternative for this kind of compile time warning?
It looks like there is a standard [[deprecated("msg")]] attribute that also does the job, the problem is that it is confusing because there is nothing deprecated about this function, it is there for convenience.
There is also, I found recently a #pragma poison that might be applicable here, but I don't understand how it is used, besides the function is actually a member function of a template class, the examples do not consider this case. https://www.fluentcpp.com/2018/09/04/function-poisoning-in-cpp/

Dynamically modify symbol table at runtime (in C)

Is it possible to dynamically modify symbol table at runtime in C (in elf format on Linux)?
My eventual goal is the following:
Inside certain function say foo, I want to override malloc function to my custom handler my_malloc. But outside foo, any malloc should still call to malloc as in glibc.
Note: this is different from LD_PRELOAD which would override malloc during the entire program execution.
Is it possible to dynamically modify symbol table at runtime in C (in elf format on Linux)?
In theory this is possible, but in practice it's too hard to do.
Inside certain function say foo, I want to override malloc function to my custom handler my_malloc. But outside foo, any malloc should still call to malloc as in glibc.
Modifying symbol table (even if it were possible) would not get you to your desired goal.
All calls from anywhere inside your ELF binary (let's assume foo is in the main executable), resolve to the same PLT import slot malloc#plt. That slot is resolved to glibc malloc on the first call (from anywhere in your program, assuming you are not using LD_BIND_NOW=1 or similar). After that slot has been resolved, any further modification to the symbol table will have no effect.
You didn't say how much control over foo you have.
If you can recompile it, the problem becomes trivial:
#define malloc my_malloc
int foo() {
// same code as before
}
#undef malloc
If you are handed a precompiled foo.o, you are linking it with my_malloc.o, and you want to redirect all calls from inside foo.o from malloc to my_malloc, that's actually quite simple to do at the object level (i.e. before final link).
All you have to do is go through foo.o relocation records, and change the ones that say "put address of external malloc here" to "put address of external my_malloc here".
If foo.o contains additional functions besides foo, it's quite simple to limit the relocation rewrite to just the relocations inside foo.
Is it possible to dynamically modify symbol table at runtime in C (in elf format on Linux)?
Yes, it is not easy, but the functionality can be packaged into a library, so at the end of the day, it can be made practical.
Typemock Isolator++
(https://www.typemock.com/isolatorpp-product-page/isolate-pp/)
This is free-to-use, but closed source solution. The usage example from documentation should be instructive
TEST_F(IsolatorPPTests, IsExpired_YearIs2018_ReturnTrue) {
Product product;
// Prepare a future time construct
tm* fakeTime = new tm();
fakeTime->tm_year = 2018;
// Fake the localtime method
FAKE_GLOBAL(localtime);
// Replace the returned value when the method is called
// with the fake value.
WHEN_CALLED(localtime(_)).Return(fakeTime);
ASSERT_TRUE(product.IsExpired());
}
Other libraries of this kind
Mimick, from Q: Function mocking in C?
cpp-stub, from Q: Creating stub functionality in C++
Elfspy, for C++, but sometimes it's OK to test C code from C++ unittests, from Q: C++ mock framework capable of mocking non-virtual methods and C functions
HippoMocks, from Q: Mocking C functions in MSVC (Visual Studio)
the subprojects in https://github.com/coolxv/cpp-stub/tree/master/other
... there is still more, feel free to append ...
Alternate approaches
ld's --wrap option and linker scripts, https://gitlab.com/hedayat/powerfake
various approaches described in answers for Q: Advice on Mocking System Calls
and in answers to Q: How to mock library calls?
Rewrite code to make it testable
This is easier in other languages than C, but still doable even in C. Structure code into small functions without side-effects that can be unit-tested without resorting to trickery, and so on. I like this blog Modularity. Details. Pick One. about the tradeoffs this brings. Personally, I guturally dislike the "sea of small functions and tons of dependency injection" style of code, but I realize that that's the easiest to work with, all things considered.
Excursion to other languages
What you are asking for is trivial to do in Python, with the unittest.mock.patch, or possibly by just assigning the mock into the original function directly, and undoing that at the end of the test.
In Java, there is Mockito/PowerMock, which can be used to replace static methods for the duration of a test. Static methods in Java approximately correspond to regular functions in C.
In Go, there is Mockey, which works similarly to what needs to be done in C. It has similar limitations in that inlining can break this kind of runtime mocking. I am not sure if in C you can hit the issue that very short methods are unmockable because there is not enough space to inject the redirection code; I think more likely not, if all calls go through the Procedure Linkage Table.

Adding methods to records type from Delphi in DWScript

After I've created a TRecordSymbol, how do I add a constructor and methods to it? I've tried using TMethodSymbol with little success, as I can't find a way to define the execution of the method.
Method symbols (like all TFuncSymbol) defer the execution to an interface (defined through the Executable property) for "normal" execution (ie. with a stack frame and parameters evaluated and pushed on the stack). "Magic" function symbols on the other hand require a dedicated expression class, and they take over the whole function call (so less overhead, but you've got to guard yourself against everything).
For samples, you can look at what the dwsMathComplex & 3d units do, they introduce records with custom methods.

Can Luabind property getters and setters yield?

Is it possible to create a Luabind property with getters and setters that yield while they wait for the query to be performed in a different thread? The following syntax compiles but doesn't seem to work:
luabind::class_<Foo>("Foo")
.property("bar", &Foo::getBar, &Foo::setBar, luabind::yield)
Wrapping the object on the Lua side and adding property wrappers around regular functions is not a good option, as I need to define these properties on base classes and this would require much duplication of wrapper code for each derived class.
The following syntax compiles but doesn't seem to work:
Of course it doesn't work; luabind::yield solves a different problem. yield tells the system to yield after the function completes, not before, and certainly not in the middle of it.
You can't yield in the middle of C/C++ functions. Lua 5.2 adds the ability to set a "resume" function, but even then, there is significant danger in yielding within C++ code, since Lua generally won't clean up the stack.
What you want to do is yield before calling the function. It would be the equivalent of this Lua code:
function myGet(...)
local tester = StartAsyncAction(...);
while(~tester:IsFinished()) do
coroutine.yield();
end
return tester:Get(...);
end
You cannot really mimic that in C/C++; not with Lua 5.2. And Luabind doesn't fully support the new 5.2 features.

Resources