Linux load dll с
Здравствуйте, Alexey_VL, Вы писали:
>Пытась найти ответ на winehq.org, но пока безуспешно.
Сам сейчас поэксперементировал, получилось вот что.
Нашел в интернете готовую Windows DLL — из руководства, как делать DLL в Windows (http://www.flipcode.com/archives/Creating_And_Using_DLLs.shtml).
Взял оттуда код, который загружает DLL и выполняет из неё функции, немного подрихтовал и получил вот что:
Собирать при помощи вот такой команды:
На выходе будет файл с названием dllrun.exe, запускать его.
| От: | Alexey_VL |
Дата: | 19.10.09 09:58 | |
Оценка: |
| От: | Sheridan |
Дата: | 19.10.09 10:35 | |
Оценка: |
Приветствую, Alexey_VL, вы писали:
Можно озвучить — для чего? Что в той длл такого?
| От: | Alexey_VL |
Дата: | 19.10.09 11:07 | |
Оценка: |
S>Можно озвучить — для чего? Что в той длл такого?
В DLL драйвер под Виндос для устройства на СОМ-порте, который можно самостоятельно написать и под Linux, но это потребует времени. Задача как можно быстрее начать работать с устройством для демонстрации оного. В дальнейшем уже можно будет сделать нормально, написав драйвер под Linux. Ну и вообще для общего развития интересно — неужели нет проги-эмулятора, позволяющей работать с виндовскими длл-ками в Линуксе, с учетом существования WINE
| От: | rising_edge |
Дата: | 19.10.09 11:13 | |
Оценка: |
Здравствуйте, Alexey_VL, Вы писали:
S>>Можно озвучить — для чего? Что в той длл такого?
A_V>В DLL драйвер под Виндос для устройства на СОМ-порте
А оная DLL небось через драйвер COM-порта работает? И как вы собираетесь виндовой DLL лазить в устройство через линуксовый драйвер COM-порта?
| От: | Sheridan |
Дата: | 19.10.09 11:17 | |
Оценка: |
| От: | LuciferSaratov |
Дата: | 19.10.09 11:24 | |
Оценка: |
Здравствуйте, Alexey_VL, Вы писали:
A_V>Я так понимаю, что мне winelib не подойдет, потому что у меня Linux-приложение, которое я не могу скомпилировать как виндовское с помощью Winelib. Исходников dll-ки у меня тоже нет.
Насколько я понимаю, вот эти самые winegcc и wineg++ никоим образом не запрещают использовать обычные линуксовые библиотеки и системные вызовы. Т.е. если собирать программу при помощи winegcc, то можно использовать как WinAPI, так и линуксовые API.
Код, необходимый для инициализации WINE, winegcc генерирует сам.
| От: | Alexey_VL |
Дата: | 19.10.09 11:32 | |
Оценка: |
_>А оная DLL небось через драйвер COM-порта работает? И как вы собираетесь виндовой DLL лазить в устройство через линуксовый драйвер COM-порта?
Хм, а собственно почему виндовой? Я так понимаю WINE подменяет вызовы виндос длл-ок на свои реализации. Думаю kernel32 входит в число длл-ок вызовы которых заменили.
| От: | Alexey_VL |
Дата: | 19.10.09 11:41 | |
Оценка: |
S>А демонстрацию лучше на виндах демонстрируйте, раз уж там готовое есть.
Суть в том, что продемонстрировать надо работу Linux-программы. Так что виндос тут не подходит.
AVL>>Ну и вообще для общего развития интересно — неужели нет проги-эмулятора, позволяющей работать с виндовскими длл-ками в Линуксе, с учетом существования WINE
S>А оно надо? Оно ненадо. Да и вредно.
Хм, ну мне вот сейчас например надо. И судя по количеству аналогичных вопросов в нете, не только мне. Это может и не здорово для использования как архитектурное решение, но в плане временно поставить стороннюю длл-ку в свое Линукс приложение при портировании очень даже неплохо — можно сразу смотреть что получается.
| От: | Alexey_VL |
Дата: | 19.10.09 11:47 | |
Оценка: |
LS>Насколько я понимаю, вот эти самые winegcc и wineg++ никоим образом не запрещают использовать обычные линуксовые библиотеки и системные вызовы. Т.е. если собирать программу при помощи winegcc, то можно использовать как WinAPI, так и линуксовые API.
LS>Код, необходимый для инициализации WINE, winegcc генерирует сам.
Угу, дочитал Wine-wiki до ответа на свой вопрос. А если у меня только часть исходников Linux-проги, которая используются для собирания so библиотек — никаких подводных камней не возникнет при стыковке с основной частью приложения, которая собрана обычным gcc?
| От: | LuciferSaratov |
Дата: | 19.10.09 12:05 | |
Оценка: |
Здравствуйте, Alexey_VL, Вы писали:
A_V>Угу, дочитал Wine-wiki до ответа на свой вопрос. А если у меня только часть исходников Linux-проги, которая используются для собирания so библиотек — никаких подводных камней не возникнет при стыковке с основной частью приложения, которая собрана обычным gcc?
Я думаю, чтобы проблем не было, нужно итоговый исполняемый файл линковать при помощи winegcc/wineg++ — чтобы были прилинкованы все нужные библиотеки.
| От: | Alexey_VL |
Дата: | 19.10.09 14:00 | |
Оценка: |
LS>Я думаю, чтобы проблем не было, нужно итоговый исполняемый файл линковать при помощи winegcc/wineg++ — чтобы были прилинкованы все нужные библиотеки.
В итоге нашел все ответы на свои вопросы в Wine-wiki. Спасиб за ссылку Вот похоже наиболее оптимальный подход для решения задачи по использованию длл-ки в Линукс приложении (из Wine-wiki):
A programmer asked Jun 2007 Wine devel]: [How can I write a shared library that uses Wine and can be called from a non-winelib app?]
S. Dossinger: your plugin, that loads the dll, needs to run in Wine’s environment in order to be able to load the dll. So you have to write a winelib dll. If the plugin is loaded as a library in your host app, the whole host app would have to be a winelib app. Not good So you can split your plugin into two parts, one is the plugin that runs in the host app, the other one is a seperate winelib application that runs in a seperate process and loads the win32 dll. That way the dll gets the virtual memory setup it needs. The two parts of your plugin can use any Unix IPC techniques you feel like using — sockets, pipes, shared memory, semaphores, whatever. You could forward function calls using pipes, transport bigger blobs using shared memory, and synchronise everything using semaphores(and implicit pipe synchronisation).
Источник
Linux load dll с
Porting Windows Dynamic Link Libraries to Linux
This repository contains a library that allows native Linux programs to load and call functions from a Windows DLL.
As a demonstration, I’ve ported Windows Defender to Linux.
How does it work?
The peloader directory contains a custom PE/COFF loader derived from ndiswrapper. The library will process the relocations and imports, then provide a dlopen -like API. The code supports debugging with gdb (including symbols), basic block coverage collection, and runtime hooking and patching.
The intention is to allow scalable and efficient fuzzing of self-contained Windows libraries on Linux. Good candidates might be video codecs, decompression libraries, virus scanners, image decoders, and so on.
- C++ exception dispatch and unwinding.
- Loading additional symbols from IDA.
- Debugging with gdb (including symbols), breakpoints, stack traces, etc.
- Runtime hooking and patching.
- Support for ASAN and Valgrind to detect subtle memory corruption bugs.
If you need to add support for any external imports, writing stubs is usually quick and easy.
Distributed, scalable fuzzing on Windows can be challenging and inefficient. This is especially true for endpoint security products, which use complex interconnected components that span across kernel and user space. This often requires spinning up an entire virtualized Windows environment to fuzz them or collect coverage data.
This is less of a problem on Linux, and I’ve found that porting components of Windows Antivirus products to Linux is often possible. This allows me to run the code I’m testing in minimal containers with very little overhead, and easily scale up testing.
This is just personal opinion, but I also think Linux has better tools. ¯\_(ツ)_/¯
MsMpEng is the Malware Protection service that is enabled by default on Windows 8, 8.1, 10, Windows Server 2016, and so on. Additionally, Microsoft Security Essentials, System Centre Endpoint Protection and various other Microsoft security products share the same core engine.
The core component of MsMpEng responsible for scanning and analysis is called mpengine. Mpengine is a vast and complex attack surface, comprising of handlers for dozens of esoteric archive formats, executable packers, full system emulators for various architectures and interpreters for various languages. All of this code is accessible to remote attackers.
To build the test client, simply type make .
Note that the .i686 or :i386 suffixes are important, we need the 32bit libraries to use the 32bit dll.
Fedora / RedHat | Ubuntu / Debian | Comment |
---|---|---|
glibc-devel.i686 | libc6-dev:i386 / libc6-dev-i386 | Name varies with version. |
libgcc.i686 | gcc-multilib | |
readline-devel.i686 | libreadline-dev:i386 | Optional, used in mpscript. |
cabextract | cabextract | Used to extract definitions. |
You will need to download the 32-bit antimalware update file from this page:
This should be a direct link to the right file:
This will download a file called mpam-fe.exe , which is a cabinet file that can be extracted with cabextract . Extract the files into the engine directory:
If you want to know which version you got, try this:
The main mpengine loader is called mpclient , it accepts filenames to scan as a parameter.
There are some other sample tools, mpstreamfuzz and mpscript .
If you want to debug a crash, single step through a routine or set breakpoints, follow these examples. First, you need a map file from IDA.
Microsoft doesn’t release public symbols for every build, and sometimes the symbols lag behind for a few months after release. Make sure you’re using an mpengine version with public symbols available.
Use the following sample commandline to generate map and idb files.
If you generate the map files on Windows, you’ll get CRLF line terminators, fix them like this:
When you run mpclient under gdb, it will detect a debugger and print the commands you need to enter to teach gdb about the symbols:
If you enter the commands it shows into gdb, you will have symbols available.
Note that genmapsym.sh assumes you’re using GNU awk.
Then you can continue, and it will run as normal.
Breakpoints, watchpoints and backtraces all work as normal, although it may be more reliable to use hardware breakpoints than software breakpoints.
To use hardware breakpoints in gdb, you just use hb or hbreak instead of break . Note that you only get a limited number of hardware breakpoints.
What about Wine and Winelib?
This project does not replace Wine or Winelib.
Winelib is used to port Windows C++ projects to Linux, and Wine is intended to run full Windows applications. This project is intended to allow native Linux code to load simple Windows DLLs.
The closest analogy would be ndiswrapper but for userspace.
Источник