Code injection - Solaris & Linux - linux

I have an executable module created by third party. I would like to "inject" my code (kind of watchdog running in separate thread) into this process.
So far there are two possible ways - one is to run my code as executable and dynamically load a proess on top of it (seems to be very hard and tricky) or to make my code a shared object, load it via LD_PRELOAD and initialize from some static variable constructor.
Are there more convenient ways to do this ?
My OS are Linux x86 and Solaris-SPARC.
Update: If possible, I'd like not to patch the process, but load my code dynamicaly.

Sounds like you're looking for InjectSo. There's a Powerpoint presentation that explains how it works. I haven't gotten around to trying it out yet.

Hotpatch should do this for you. It is more capable than injectso.

Rob Kennedy told you about InjectSo - that's probably what you need.
Beware that the introduction of a thread into a non-threaded process would be fraught with synchronization issues. The problems are less serious if the application is already threaded, but even so, the application may object to a thread that it doesn't know about.

I have not used the mentioned InjectSo but it is a noteworthy information.
If you are looking for alternatives here is a simple way to inject your code:
#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>
int main()
{
struct passwd* pswd = getpwuid(1000);
if(pswd)
printf("%s\n", pswd->pw_name);
return 0;
}
gcc test.c -o test
#define _GNU_SOURCE
#include <dlfcn.h>
#include <sys/types.h>
#include <pwd.h>
#include <stdlib.h>
#include <stdio.h>
static char* hocus = "hocus pocus";
struct passwd *getpwuid(uid_t uid)
{
static struct passwd *(*orig_getpwuid)(uid_t uid);
if(!orig_getpwuid) {
orig_getpwuid = (struct passwd* (*)(uid_t))dlsym(RTLD_NEXT, "getpwuid");
}
struct passwd* original_passwd = (*orig_getpwuid)(uid);
if(original_passwd) {
original_passwd->pw_name = hocus;
}
// your code here
return original_passwd;
}
gcc inject.c -shared -o libinject.so
run with LD_LIBRARY_PATH=. LD_PRELOAD=libinject.so ./test
Should say hocus pocus. You can override arbitrary libc functions, like printf, snprintf - just find what is that module using.
In the "your code here" you can start arbitrary threads, watchdogs etc.

Related

MSVC compiler error for external variables and OpenMP's threadprivate

I am trying to compile a c++ application using MSVC (Compiler Version 19.32.31329 for x86). The author of the application has complied it successfully using GCC 8.3, 9.3, and 10.3.
I run into an error when I enable OpenMP for parallel computing - in particular in the random.h and random.cpp files. I have found a small code snippet that throws the same compile error on MSVC but has no issues when compiled with GCC according to the author.
#include<omp.h>
#include<iostream>
struct point2d
{
int x;
int y;
#ifndef DECLARE_AS_POD_TYPE
point2d() {}
#endif
};
int main(int argc, char* argv[])
{
using namespace std;
extern point2d myPoint;
#pragma omp threadprivate(myPoint)
//point2d myPoint;
myPoint.x = omp_get_thread_num();
cout << myPoint.x << endl;
}
The MSVC error I get is error C3053: 'myPoint': 'threadprivate' is only valid for global or static data items
I am pretty new to OpenMP but have done a fair amount of googling. I am not the first person to have this issue but I have not found a solution that works for me. In particular, I have looked at:
Using threadprivate directive in Visual Studio
Threadprivate directive after external declaration of global variables
OpenMP threadprivate directive is not working.
I am using this application as a bit of a learning exercise so I am happy to make changes to the code but I have tried quite a few permutations and I am not able to make progress.
Any suggestions are welcome.

Adding a new system call Linux 5-9.8 and make it appear on boot screen

I'm trying to add a new system call to linux -5.9.8 for this I've been following this tutorial from a prev question and this one and this from a guide they are both really similar and everything does work as intended BUT to get the system call to show with dmesg we get to compile the following code after boot up:
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#define __NR_identity 440
long identity_syscall(void)
{
return syscall(__NR_identity);
}
int main(int argc, char *argv[])
{
long activity;
activity = identity_syscall();
if(activity < 0)
{
perror("Sorry. Your system call appears to have failed.");
}
else
{
printf("Congratulations! Your system call is functional. Run the command dmesg in the terminal and find out!\n");
}
return 0;
}
This code does in fact add the message to dmesg but it does it after boot up and I need to run the code everytime, how should I go to actually make my system call appear on the boot up screen and not later, what file should I edit to make it happen?
If the goal is to merely display some sort of message at system startup time, you don't need a system call but rather a kernel module statically linked or dynamically loaded.
In the file where you define the system call, you can add an "init" routine which will be called by the kernel at startup. To make it, the kernel build chain uses "__init" section identifier to gather all the initialization entry points into a dedicated section. Then, in the boot procedure, all the functions from this section are called. You can try something like the following from your example (I didn't tried it !):
#include <linux/kernel.h>
#include <linux/syscalls.h>
SYSCALL_DEFINE0(identity)
{
printk("I am Jihan Jasper Al-rashid.\n");
return 0;
}
void __init identity_entry(void)
{
printk("Boot message from identity\n");
}

How to rotate a Qt5 application using the linux framebuffer?

I have an embedded linux application running directly on the linux framebuffer (no x-Windows). We now have to physically rotate the display 180 degrees. How do I get my Qt application to rotate so it doesn't appear upside down? I saw reference to using the following option:
-platform linuxfb:fb=/dev/fb0:rotation:180
However, the rotation option seems to be ignored.
Using Qt 5.9.2 on Ubuntu server 16.04.6
You could handle it on application level. With QML thats easy, but with QWidgets the best I could come up with is to render the Widget on a QGraphicsScene and rotate it like this:
#include "mainwindow.h"
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
QGraphicsScene *scene = new QGraphicsScene();
QGraphicsView *view = new QGraphicsView();
view->setGeometry(w.geometry());
view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
scene->addWidget(&w);
view->setScene(scene);
view->show();
view->rotate(180);
//w.show();
return a.exec();
}
It seems a bit glitchy, but you could give it a try.
Also I think the correct syntax is -platform linuxfb:fb=/dev/fb0:rotation=180 note the = instead of :
Edit: but that did not make a difference for me either.

Why does gtkmm automatically create a second thread sometimes?

If I compile and run the code as-is, the process will run with 1 thread. If I uncomment the commented out section and then compile and run it, it runs with 2 threads.
I am compiling the code with this command:
g++ pkg-config gtkmm-2.4 --cflags --libs test.cpp
When the program is running I can check how many threads are created with:
ps -mC a.out
If I look at the second thread in ddd, I can see that it is running g_main_loop_run. This confuses me:
What is the purpose of this thread?
Why does adding a toolbar button create a new thread?
I thought g_main_loop_run() should only ever run in one thread (unless you use the GDK_THREADS_ENTER/GDK_THREADS_LEAVE macros). Since I am running Gtk::Main::Run() in my main thread am breaking the rules?
Thanks in advance for any help. It's driving me crazy.
#include <gtkmm.h>
bool OnDeleteEvent(GdkEventAny* PtrGdkEventAny)
{
Gtk::Main::quit();
return(true);
}
void OnExecuteButtonClicked()
{
}
int main(int argc, char *argv[])
{
new Gtk::Main(0, NULL);
Gtk::Window *ptrWindow = new Gtk::Window;
ptrWindow->signal_delete_event().connect(sigc::ptr_fun(&OnDeleteEvent));
/*
Gtk::Toolbar *ptrToolBar = manage(new Gtk::Toolbar);
Gtk::ToolButton *ptrToolButton;
ptrToolButton = manage( new Gtk::ToolButton(Gtk::Stock::EXECUTE));
ptrToolBar->append(*ptrToolButton, sigc::ptr_fun(&OnExecuteButtonClicked));
ptrWindow->add(*ptrToolBar);
*/
ptrWindow->show_all();
Gtk::Main::run();
return (0);
}
Sometimes GThreads are created when you use functions that rely on async behaviour. These usually create a GTask internally (with g_task_run_in_thread and friends) and run the synchronous version in a seperate thread (except for those being nativly async or async-able, those usually won't spawn another thread). Usually this is IO (i.e. GtkBuilder), Socket and IPC (dbus) related - so mostly glib stuff.
There might also be occasions which I am not aware of, that will spawn additional threads, the mainloop itself is strictly single threaded.
So in your case I can only think of two thing that could trigger this: The Stock image that is loaded from your local disk or the styling information of your theme.

Module Programming in linux

here is the simple module program code.
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/init.h> /* Needed for the macros */
static int hello3_data __initdata = 3;
static int __init hello_3_init(void)
{
printk(KERN_INFO "Hello, world %d\n", hello3_data);
return 0;
}
static void __exit hello_3_exit(void)
{
printk(KERN_INFO "Goodbye, world %d\n",hello3_data);
}
module_init(hello_3_init);
module_exit(hello_3_exit);
I've initialized a variable with __initdata macro and a function with __init. when I did insmod the module was inserted and i was able to see the log message(/var/log/messages). But, when I did rmmod it was unable to remove it, and it says Resource busy.
My question is does the `modules_init` function cleans the memory of `hello3_data`??
or it is done by `module_exit`??.
Someone please explain.
Please when declaring the varialble hello3_data you're using the __initdata modifier which specifies that the variable shall be used in only the __init function.
Try recompile your kernel module with options like make CONFIG_DEBUG_SECTION_MISMATCH=y and you shall see warnings like this:
WARNING: /home/pengyu/temp/yusen/test_mod.o(.exit.text+0x3): Section mismatch in reference from the function cleanup_module() to the variable .init.data:hello3_data
The function __exit cleanup_module() references
a variable __initdata hello3_data.
This is often seen when error handling in the exit function
uses functionality in the init path.
The fix is often to remove the __initdata annotation of
hello3_data so it may be used outside an init section.
You could simply remove __initdata and try again.
EDITED:
Here I'm trying to provide further explanations. The kernel module itself is in the format of ELF (Executable and Linkable Format) (with some kernel-module-specific sections). Feature of the .init and .fini sections is supported by the linkers and loaders including insmod.
In this case the attribute #define __initdata __section(.init.data) works like __attribute__((section(".init.data"))) which explicitly specifies which section the data/function shall be put in.
As a kernel module the section of .init is not guaranteed to be kept after module initialization, and anything inside that section is not supposed to be referenced outside the initialization function. See page 31 of Linux Device Drivers, Third Edition:
The _init token in the definition may look a little strange; it is a hint to the kernel that the given function is used only at initialization time. The module loader drops the initialization function after the module is loaded, making its memory available for other uses. There is a similar tag (_initdata)for data used only during initialization. Use of __init and __initdata is optional, but it is worth the trouble. Just be sure not to use them for any function (or data structure)you will be using after initialization completes

Resources