Registering a custom CodeInsight manager to C++Builder without initialization/finalization sections - delphi

I'm trying to register a custom CodeInsight manager into C++Builder 10.1.2 Berlin.
Because there's nothing like Objects Pascal's initialization and finalization sections in C++, e.g.
var
codeManagerIndex: Integer;
{...}
initialization
codeManagerIndex := (BorlandIDEServices as IOTACodeInsightServices).AddCodeInsightManager(TMyCodeInsightManager.Create);
finalization
(borlandIDEServices as IOTACodeInsightServices).RemoveCodeInsightManager(codeManagerIndex);
end.
I tried reproducing their behavior with a custom runner class with constructor/destructor:
class Runner
{
public:
int FCodeManagerIndex;
_di_IOTACodeInsightServices CIS;
Runner() {
if (BorlandIDEServices->Supports(CIS))
FCodeManagerIndex = CIS->AddCodeInsightManager(new TMyCodeInsightManager);
}
~Runner() {
if (BorlandIDEServices->Supports(CIS))
CIS->RemoveCodeInsightManager(FCodeManagerIndex);
}
};
#pragma argsused
extern "C" int _libmain(unsigned long reason)
{
Runner Run;
return 1;
}
I can compile my simple implementation but when I try to install the package the following things are happening:
1st try: Error message: Can't load package ... mypackage.bpl - A dynamic link library (DLL) initialization routine failed.
2nd try: An exception (C0000005) occured during DllEntryPoint or DllMain in module: ... mypackage.bpl ... then the IDE crashes.
Is this a wrong way to register?
What am I doing wrong here?
P.S. I get a [TLIB Warning] Warning: library was too large for page size, rebuilt with page size 32 warning when compiling, but I'm quite sure that this can't be the reason for my errors. (?)

there's nothing like Objects Pascal's initialization and finalization sections in C++
Actually, there is. In C++Builder, you can use #pragma startup and #pragma exit to execute user-defined functions:
static int FCodeManagerIndex = -1;
void DoRegister() {
_di_IOTACodeInsightServices CIS;
if (BorlandIDEServices->Supports(CIS)) {
FCodeManagerIndex = CIS->AddCodeInsightManager(new TMyCodeInsightManager);
}
}
#pragma startup DoRegister
void DoUnregister() {
_di_IOTACodeInsightServices CIS;
if ((FCodeManagerIndex != -1) && BorlandIDEServices->Supports(CIS)) {
CIS->RemoveCodeInsightManager(FCodeManagerIndex);
}
}
#pragma exit DoUnregister
#pragma argsused
extern "C" int _libmain(unsigned long reason)
{
return 1;
}
Alternatively, since you ready declared a class to handle your registration, you can simply move your class variable into global static memory so its constructor runs at startup and destructor runs at shutdown:
class Runner
{
public:
int FCodeManagerIndex;
Runner() : FCodeManagerIndex(-1) {
_di_IOTACodeInsightServices CIS;
if (BorlandIDEServices->Supports(CIS)) {
FCodeManagerIndex = CIS->AddCodeInsightManager(new TMyCodeInsightManager);
}
}
~Runner() {
_di_IOTACodeInsightServices CIS;
if ((FCodeManagerIndex != -1) && BorlandIDEServices->Supports(CIS)) {
CIS->RemoveCodeInsightManager(FCodeManagerIndex);
}
}
};
static Runner Run;
#pragma argsused
extern "C" int _libmain(unsigned long reason)
{
return 1;
}
Declaring the class variable inside of _libmain() is useless since the destructor will be called when the variable goes out of scope when _libmain() exits, thus unregistering the manager immediately after registering it. So the variable has to survive for as long as the package is loaded in memory.

Related

store a lambda that captures this

Using C++ 17, I'm looking for a way to store a lambda that captures the this pointer, without using std::function<>. The reason to not using std::function<> is that I need the guaranty that no dynamic memory allocations are used. The purpose of this, is to be able to define some asynchronous program flow. Example:
class foo {
public:
void start() {
timer(1ms, [this](){
set_pin(1,2);
timer(1ms, [this](){
set_pin(2,1);
}
}
}
private:
template < class Timeout, class Callback >
void timer( Timeout to, Callback&& cb ) {
cb_ = cb;
// setup timer and call cb_ one timeout reached
...
}
??? cb_;
};
Edit: Maybe it's not really clear: std::function<void()> would do the job, but I need / like to have the guaranty, that no dynamic allocations happens as the project is in the embedded field. In practice std::function<void()> seems to not require dynamic memory allocation, if the lambda just captures this. I guess this is due to some small object optimizations, but I would like to not rely on that.
You can write your own function_lite to store the lambda, then you can use static_assert to check the size and alignment requirements are satisfied:
#include <cstddef>
#include <new>
#include <type_traits>
class function_lite {
static constexpr unsigned buffer_size = 16;
using trampoline_type = void (function_lite::*)() const;
trampoline_type trampoline;
trampoline_type cleanup;
alignas(std::max_align_t) char buffer[buffer_size];
template <typename T>
void trampoline_func() const {
auto const obj =
std::launder(static_cast<const T*>(static_cast<const void*>(buffer)));
(*obj)();
}
template <typename T>
void cleanup_func() const {
auto const obj =
std::launder(static_cast<const T*>(static_cast<const void*>(buffer)));
obj->~T();
}
public:
template <typename T>
function_lite(T t)
: trampoline(&function_lite::trampoline_func<T>),
cleanup(&function_lite::cleanup_func<T>) {
static_assert(sizeof(T) <= buffer_size);
static_assert(alignof(T) <= alignof(std::max_align_t));
new (static_cast<void*>(buffer)) T(t);
}
~function_lite() { (this->*cleanup)(); }
function_lite(function_lite const&) = delete;
function_lite& operator=(function_lite const&) = delete;
void operator()() const { (this->*trampoline)(); }
};
int main() {
int x = 0;
function_lite f([x] {});
}
Note: this is not copyable; to add copy or move semantics you will need to add new members like trampoline and cleanup which can properly copy the stored object.
There is no drop in replacement in the language or the standard library.
Every lambda is a unique type in the typesystem. Technically you may have a lambda as a member, but then its type is fixed. You may not assign other lambdas to it.
If you really want to have an owning function wrapper like std::function, you need to write your own. Actually you want a std::function with a big enough small-buffer-optimization buffer.
Another approach would be to omit the this capture and pass it to the function when doing the call. So you have a captureless lambda, which is convertible to a function pointer which you can easily store. I would take this route and adapter complexer ways if really nessessary.
it would look like this (i trimmed down the code a bit):
class foo
{
public:
void start()
{
timer(1, [](foo* instance)
{
instance->set_pin(1,2);
});
}
private:
template < class Timeout, class Callback >
void timer( Timeout to, Callback&& cb )
{
cb_ = cb;
cb_(this); // call the callback like this
}
void set_pin(int, int)
{
std::cout << "pin set\n";
}
void(*cb_)(foo*);
};

How to implement the Delphi protected member access trick in C++ builder?

I need access to TControlItem.InternalSetLocation which is protected. I Delphi you would do
type
THackControlItem = class(TControlItem);
How do you do this in C++ Builder?
As in Delphi, you need to inherit the class but also override and make public the protected function. However, I wouldn't recommend to use it in production code.
class THackControlItem : public TControlItem
{
public:
void __fastcall InternalSetLocation(int AColumn, int ARow, bool APushed, bool MoveExisting)
{
TControlItem::InternalSetLocation(AColumn, ARow, APushed, MoveExisting);
}
};
In the program
TControlItem* ci = ...;
static_cast<THackControlItem*>(ci)->InternalSetLocation(...);
This is a nice trick I think Remy Lebeau showed me but can not find the QA anymore...
//---------------------------------------------------------------------------
#ifndef _TDirectMemoryStream
#define _TDirectMemoryStream
class TDirectMemoryStream:TMemoryStream // just for accessing protected SetPointer
{
public:
void SetMemory(BYTE *ptr,DWORD siz) { SetPointer(ptr,siz); Position=0; };
};
#endif
//---------------------------------------------------------------------------
You simply create new class that is descendant of the class you want to access. Now just add get/set functions for the protected members ...
Now usage:
TMemoryStream *mem=new TMemoryStream(); // original class instance you want to access
// overtype to our new class and access/use you get/set ...
((TDirectMemoryStream*)(mem))->SetMemory(hdr->lpData,hdr->dwBytesUsed);
delete mem; // release if not needed anymore
I am using it btw to feed a memory stream with custom memory data hdr coming from vfw camera so I can properly decode it using TJPEGImage class instead of writing the data into file and loading it back each frame ...
Here another example:
class A
{
protected:
int x;
public:
int getx(){ return x; }
};
class hack_A:A
{
public:
void setx(int _x){ x=_x; }
};
void test()
{
A a;
hack_A *ha=(hack_A*)&a;
ha->setx(10);
a.getx(); // print the x somwhere
}
However this will not work for private members ... In such case its doable too but requires access to A source code:
class A
{
protected:
int x;
private:
int y;
public:
int getx(){ return x; }
int gety(){ return y; }
friend class hack_A; // but this one requires access to A soourcecode
};
class hack_A:A
{
public:
void setx(int _x){ x=_x; }
void sety(int _y){ y=_y; }
};
void test()
{
A a;
hack_A *ha=(hack_A*)&a;
ha->setx(10);
ha->sety(20);
a.getx(); // print the x somwhere
a.gety(); // print the x somwhere
}

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

How to discover lock declaration instruction in llvm?

I'm new to llvm , and was trying to find lock declaration statement and then do some instrumention work,the code like this:
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int share = 42;
mutex m;
void f()
{
m.lock();
--share;
cout << "function f -> share: " << share << '\n';
m.unlock();
}
int main()
{
thread thf{f};
thf.join();
return 0;
}
I want to find the lock declaration instruction eg:
mutex m;
the llvm instrumention pass like this:
struct SkeletonPass : public FunctionPass {
static char ID;
SkeletonPass() : FunctionPass(ID) {}
virtual bool runOnFunction(Function &F) {
// Get the function to call from our runtime library.
LLVMContext &Ctx = F.getContext();
Constant *logFunc = F.getParent()->getOrInsertFunction(
"logop", Type::getVoidTy(Ctx), Type::getInt32Ty(Ctx), NULL
);
for (auto &B : F) {
for (auto &I : B) {
***if ((&I) is lock declaration instruction)*** {
// Insert something *after* `op`.
IRBuilder<> builder(op);
builder.SetInsertPoint(&B, ++builder.GetInsertPoint());
// Insert a call to function.
builder.CreateCall(logFunc, ConstantInt::get(Type::getInt32Ty(Ctx), 2));
return true;
}
}
}
In short, could you please tell me how to discover lock declaration instruction, thanks!
The declaration would appear as a global, so you should write a module pass to find it, not a function pass. It should appear as something like:
#m = global %mutex zeroinitializer
In fact, using the demo at http://ellcc.org/demo/index.cgi to try this, you can indeed see that:
...
%"class.std::__1::mutex" = type { %struct.pthread_mutex_t }
%struct.pthread_mutex_t = type { %union.anon }
%union.anon = type { [5 x i8*] }
...
#m = global %"class.std::__1::mutex" zeroinitializer, align 8
You can use LLVM's CppBackend to compile your code. This would produce a C++ code that makes up the source. You can then easily find out how mutex m; definition is constructed via LLVM API.
Run clang -march=cpp foo.cpp to use CppBackend. Alternatively, you can use this demo page to compile your code online.

why I can't hook my private function with fishhook

These days, I found that hook in an iOS application is hard, and found that there is a tool called "fishhook", created by facebook. I import the tool in my personal project, but it doesn't work. Am I wrong? Here are the source code:
#import <dlfcn.h>
#import <Foundation/Foundation.h>
#import "fishhook.h"
static void (*orig_testABC)(void);
void testABC()
{
NSLog(#"This is main log...");
}
void my_testABC()
{
NSLog(#"This is other log, not main log...");
}
void save_original_symbols()
{
// void *handle = dlopen("/Users/bianyiji/Library/Developer/Xcode/DerivedData/HookTest-ghlgmahvsgfbqeekbrouzdyoxgdw/Build/Intermediates/HookTest.build/Debug/HookTest.build/Objects-normal/x86_64/main.o", RTLD_LAZY);
// printf("%s\n", handle);
orig_testABC = dlsym(RTLD_DEFAULT, "testABC");
}
int main(int argc, const char * argv[]) {
#autoreleasepool {
// save_original_symbols();
int rebind_int = rebind_symbols((struct rebinding[1]){"testABC", my_testABC}, 1);
printf("%d\n", rebind_int);
}
testABC();
return 0;
}
Although I called the function "testABC()", but I use "rebind_symbols" before, why I can't get my expected result...
fishhook isn't meant to hook into private functions, because fishhook works by rebinding symbols that are present in the symbol table.
for hooking private functions you need read-write access in the executable memory pages of your running app, and this is obviously not possible for security reasons.
however, in jailbroken iOS, the kernel has a patch that allows this, so you can hook private functions with frameworks such as CydiaSubstrate or substitute. But fishhook does not support this and probably never will, also if it did would never be AppStore-friendly.
Source: our open-source SSL pinning library TrustKit uses fishhook and we introduced it at BlackHat 2015 elaborating an all these topics.

Resources