I wrote next program:
#include <iostream>
#include <dlfcn.h>
int main(int argc, char** argv)
{
typedef void* (*fptr)();
fptr func;
void *handle = dlopen(0, RTLD_NOW);
std::cout << dlerror() << std::endl;
*(void **)(&func) = dlsym(handle, "__libc_start_main");
std::cout << dlerror() << std::endl;
std::cout << handle << " " << func << "\n";
dlclose(handle);
return 0;
}
and try to compile in next way:
g++ -rdynamic main.cpp -ldl -o test
When I run this program I don’t see any message. Why?
Thank U for attention.
Your process is faulting because dlerror() is only valid to call in an error condition, which you never validated actually happened prior to invocation.
From the Linux docs:
The function dlerror() returns a human readable string describing the
most recent error that occurred from dlopen(), dlsym() or dlclose()
since the last call to dlerror(). It returns NULL if no errors have
occurred since initialization or since it was last called.
In other words, your dlopen succeeded, so NULL is returned from dlerror(). That NULL is then sent as a char * to std::cout, and kerboom.
Bottom line: check your error conditions before invoking dlerror(). Try this instead:
#include <iostream>
#include <dlfcn.h>
int main(int argc, char** argv)
{
typedef void* (*fptr)();
fptr func;
void *handle = dlopen(0, RTLD_NOW);
if (handle == nullptr)
{
std::cout << dlerror() << std::endl;
exit(EXIT_FAILURE);
}
func = (fptr)dlsym(handle, "__libc_start_main");
if (!func)
{
std::cout << dlerror() << std::endl;
exit(EXIT_FAILURE);
}
std::cout << handle << " " << func << "\n";
dlclose(handle);
return 0;
}
This is (likely) undefined behavior:
std::cout << dlerror() << std::endl;
...unless dlerror is actually non-null (which it probably isn't). It should be:
char* error = dlerror();
if (error != 0)
std::cout << error << std::endl;
...or:
void *handle = dlopen(0, RTLD_NOW);
if (handle == 0)
std::cout << dlerror() << std::endl;
Also, you probably should abort if dlerror is non-null (or handle is null), because calling dlsym on an null handle is also undefined behavior.
See Why does std::cout output disappear completely after NULL is sent to it.
Related
I might be missing something very easy but still i confronted this problem that i couldnt solve. I create a dll with these functions,
extern "C"{
__declspec(dllexport) void some();
__declspec(dllexport) void printer();
}
void printer()
{
printf("printing...\n");
}
i compile it using cmake
cmake .. -G "Visual Studio 15 2017" -A x64 -DBUILD_SHARED_LIBS=TRUE
cmake --build . --config Release
the i load it from my dllloader.cpp
int main() {
HINSTANCE hGetProcIDDLL = LoadLibrary("mydll.dll");
if (hGetProcIDDLL == NULL) {
std::cout << "cannot locate the .dll file" << std::endl;
} else {
std::cout << "it has been called" << std::endl;
}
if(GetProcAddress(hGetProcIDDLL, "printer") == NULL){
}else{
std::cout <<"not null" << std::endl;
}
std::cout << GetLastError() << " err" << std::endl;
getchar();
return 0;
}
So GetLastError returns 0 but nothing is printed, in the original file it is pretty much the same, the function is more that just a printf() call but the function gets loaded, how do we run it ? I know i might be missing something, just function does not execute. Any help is appreciated
typedef void(*my_dll_print)(); // function pointer to print method of dll
int main()
{
HINSTANCE hGetProcIDDLL = LoadLibrary("mydll.dll");
if (hGetProcIDDLL == nullptr)
std::cout << "cannot locate the .dll file" << std::endl;
else
std::cout << "it has been called" << std::endl;
my_dll_print print_method = reinterpret_cast<my_dll_print>(GetProcAddress(hGetProcIDDLL, "printer")); // Extract method address and create pointer
if (print_method == nullptr)
std::cout << "is null" << std::endl;
else
print_method(); // Call dll method
std::cout << GetLastError() << " err" << std::endl;
getchar();
return 0;
}
Try to use nullptr instead NULL to check pointer.
GetProcAdrress retrieves the address of an exported function or variable from the specified dynamic-link library! and makes no function call. You must first assign to function pointer then make call to pointed function!
My problem is that is access the kinect with the following code:
#include "libfreenect.hpp"
#include <iostream>
freenect_context* ctx;
freenect_device* dev;
void freenect_threadfunc(freenect_device* dev, void* v_depth, uint32_t timestamp){
short* d = (short*) v_depth;
std::cout << d[0] << std::endl;
}
int main(int argc, char const *argv[])
{
if(freenect_init(&ctx, NULL) < 0){
std::cout << "freenect_init() failed!" << std::endl;
}
if (freenect_open_device(ctx, &dev, 0) < 0){
std::cout << "No device found!" << std::endl;
freenect_shutdown(ctx);
}
freenect_set_depth_callback(dev, freenect_threadfunc);
freenect_set_depth_mode(dev, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_11BIT));
freenect_start_depth(dev);
while (true) {
}
return 0;
}
But for some reason i don't know, the callback function ´freenect_threadfunc´ doesn't execute. When executing freenect-glview which is a example provided by Openkinect, everything works fine.
Thank you for your help.
I am on my way to learn C++. Im now trying to link a Library on Runtime. Im getting a segmentation fault error. I dont know why it happens.
Here is the cpp file where the error happens:
#include "CreateShape.h"
#include <dlfcn.h>
#include <iostream>
#include <sstream>
#include "Shape.h"
namespace six
{
typedef six::Shape* (*GET_OBJECT);
Shape* create_shape(const char* name)
{
Shape* shape = nullptr;
std::stringstream libName;
libName << "./lib" << name << ".so";
void* handle = dlopen(libName.str().c_str(), RTLD_LAZY);
if(handle == nullptr)
{
std::cout << "Could not open the library" << std::endl;
std::cout << "dlerror: "<< std::endl << dlerror() << std::endl;
exit(EXIT_FAILURE);
}
GET_OBJECT createShape = reinterpret_cast<GET_OBJECT>(dlsym(handle, "getNewShape"));
if(createShape == nullptr)
{
std::cout << "Could not find symbol getNewShape" << std::endl;
std::cout << "dlerror=" << dlerror() << std::endl;
dlclose(handle);
exit(EXIT_FAILURE);
}
return create_shape(name);
}
}
A stripped down version of your function is
Shape* create_shape(const char* name)
{
if(some_condition)
{
exit(EXIT_FAILURE);
}
if(some_other_condition)
{
exit(EXIT_FAILURE);
}
return create_shape(name);
}
Probably you wanted to return shape or some Shape that you created inside that function. What you do instead is calling the function recursively. The only way to stop recursion is when you hit one of the conditions and then call exit.
Though, i have to admit, why the symptom is a segfault I do not really understand.
You are not using the dl-calls the proper way. From the linux dlopen(3) man page
dlsym()
[...]Since the value of the symbol could actually be NULL (so that a NULL return from dlsym() need not indicate an error), the correct way to test for an error is to call dlerror() to clear any old error conditions, then call dlsym(), and then call dlerror() again, saving its return value into a variable, and check whether this saved value is not NULL.
I am trying to use clang+llvm 3.6 to JIT compile several C functions (each can eventually be very large).
Unfortunately I the function pointer that LLVM provides makes the program SEGFAULT.
So far I have following code:
#include <iostream>
#include <clang/CodeGen/CodeGenAction.h>
#include <clang/Basic/DiagnosticOptions.h>
#include <clang/Basic/TargetInfo.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/CompilerInvocation.h>
#include <clang/Frontend/FrontendDiagnostic.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <clang/Frontend/Utils.h>
#include <clang/Parse/ParseAST.h>
#include <clang/Lex/Preprocessor.h>
#include <llvm/Analysis/Passes.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/IR/Verifier.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/Support/ManagedStatic.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_os_ostream.h>
#include <llvm/Linker/Linker.h>
int main(int argc, char *argv[]) {
using namespace llvm;
using namespace clang;
static const char* clangArgv [] = {"program", "-x", "c", "string-input"};
static const int clangArgc = sizeof (clangArgv) / sizeof (clangArgv[0]);
// C functions to be compiled (they could eventually be extremely large)
std::map<std::string, std::string> func2Source;
func2Source["getOne"] = "int getOne() {return 1;}";
func2Source["getTwo"] = "int getTwo() {return 2;}";
llvm::InitializeAllTargets();
llvm::InitializeAllAsmPrinters();
std::unique_ptr<llvm::Linker> linker;
std::unique_ptr<llvm::LLVMContext> context(new llvm::LLVMContext());
std::unique_ptr<llvm::Module> module;
/**
* add each C function to the same module
*/
for (const auto& p : func2Source) {
const std::string& source = p.second;
IntrusiveRefCntPtr<DiagnosticOptions> diagOpts = new DiagnosticOptions();
TextDiagnosticPrinter *diagClient = new TextDiagnosticPrinter(llvm::errs(), &*diagOpts); // will be owned by diags
IntrusiveRefCntPtr<DiagnosticIDs> diagID(new DiagnosticIDs());
IntrusiveRefCntPtr<DiagnosticsEngine> diags(new DiagnosticsEngine(diagID, &*diagOpts, diagClient));
ArrayRef<const char *> args(clangArgv + 1, // skip program name
clangArgc - 1);
std::unique_ptr<CompilerInvocation> invocation(createInvocationFromCommandLine(args, diags));
if (invocation.get() == nullptr) {
std::cerr << "Failed to create compiler invocation" << std::endl;
exit(1);
}
CompilerInvocation::setLangDefaults(*invocation->getLangOpts(), IK_C,
LangStandard::lang_unspecified);
invocation->getFrontendOpts().DisableFree = false; // make sure we free memory (by default it does not)
// Create a compiler instance to handle the actual work.
CompilerInstance compiler;
compiler.setInvocation(invocation.release());
// Create the compilers actual diagnostics engine.
compiler.createDiagnostics(); //compiler.createDiagnostics(argc, const_cast<char**> (argv));
if (!compiler.hasDiagnostics()) {
std::cerr << "No diagnostics" << std::endl;
exit(1);
}
// Create memory buffer with source text
std::unique_ptr<llvm::MemoryBuffer> buffer = llvm::MemoryBuffer::getMemBufferCopy(source, "SIMPLE_BUFFER");
if (buffer.get() == nullptr) {
std::cerr << "Failed to create memory buffer" << std::endl;
exit(1);
}
// Remap auxiliary name "string-input" to memory buffer
PreprocessorOptions& po = compiler.getInvocation().getPreprocessorOpts();
po.addRemappedFile("string-input", buffer.release());
// Create and execute the frontend to generate an LLVM bitcode module.
clang::EmitLLVMOnlyAction action(context.get());
if (!compiler.ExecuteAction(action)) {
std::cerr << "Failed to emit LLVM bitcode" << std::endl;
exit(1);
}
std::unique_ptr<llvm::Module> module1 = action.takeModule();
if (module1.get() == nullptr) {
std::cerr << "No module" << std::endl;
exit(1);
}
if (linker.get() == nullptr) {
module.reset(module1.release());
linker.reset(new llvm::Linker(module.get()));
} else {
if (linker->linkInModule(module1.release())) {
std::cerr << "LLVM failed to link module" << std::endl;
exit(1);
}
}
}
llvm::InitializeNativeTarget();
llvm::Module* m = module.get();
std::string errStr;
std::unique_ptr<llvm::ExecutionEngine> executionEngine(EngineBuilder(std::move(module))
.setErrorStr(&errStr)
.setEngineKind(EngineKind::JIT)
.setMCJITMemoryManager(std::unique_ptr<SectionMemoryManager>(new SectionMemoryManager()))
.setVerifyModules(true)
.create());
if (!executionEngine.get()) {
std::cerr << "Could not create ExecutionEngine: " + errStr << std::endl;
exit(1);
}
executionEngine->finalizeObject();
/**
* Lets try to use each function
*/
for (const auto& p : func2Source) {
const std::string& funcName = p.first;
llvm::Function* func = m->getFunction(funcName);
if (func == nullptr) {
std::cerr << "Unable to find function '" << funcName << "' in LLVM module" << std::endl;
exit(1);
}
// Validate the generated code, checking for consistency.
llvm::raw_os_ostream os(std::cerr);
bool failed = llvm::verifyFunction(*func, &os);
if (failed) {
std::cerr << "Failed to verify function '" << funcName << "' in LLVM module" << std::endl;
exit(1);
}
#if 1
func->dump(); // Dump the function for exposition purposes.
// JIT the function, returning a function pointer.
void *fPtr = executionEngine->getPointerToFunction(func); ///// BAD function pointer!!!!
// Cast it to the right type (takes no arguments, returns a double) so we
// can call it as a native function.
int (*funcPtr)();
*(int **) (&funcPtr) = *(int **) fPtr;
int v = (*funcPtr)();
std::cout << "return: " << v << std::endl;
#else // THIS DOES NOT WORK EITHER:
// JIT the function, returning a function pointer.
uint64_t fPtr = executionEngine->getFunctionAddress(funcName); ///// BAD function pointer!!!!
if (fPtr == 0) {
std::cerr << "Unable to find function '" << funcName << "' in LLVM module" << std::endl;
exit(1);
}
int (*funcPtr)();
*(int **) (&funcPtr) = *(int **) fPtr;
int v = (*funcPtr)();
std::cout << "return: " << v << std::endl;
#endif
}
}
Can anyone help me pin-point the problem?
(I'm running this in linux-ubuntu 15.04)
This assignment is incredibly messed up:
*(int **) (&funcPtr) = *(int **) fPtr;
Not only does it violate strict-aliasing to write an int* and then use it as a function pointer on the next line, but a data pointer is often not large enough to hold an entire code pointer.
The safe approach is either
memcpy(funcPtr, fPtr, sizeof funcPtr);
or
funcPtr = reinterpret_cast<decltype(funcPtr)>(fPtr);
I am having a really hard time with some API calls to the Wininet dll. I am trying to read cookies client side set by IE 9. Here's the code.
#include "stdafx.h"
#include <Windows.h>
#include <WinInet.h>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
LPTSTR lpData = NULL;
DWORD dwSz = 500;
std::cout << "Hello Chris" << std::endl;
lpData = new TCHAR[dwSz];
std::wcout << "Arg 0: " << argv[1] << std::endl;
bool val = InternetGetCookieEx(argv[1], argv[2], lpData, &dwSz, INTERNET_COOKIE_THIRD_PARTY | INTERNET_FLAG_RESTRICTED_ZONE, NULL);
if (!val)
{
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
std::cout << "Insufficent Buffer size" << std::endl;
lpData = new TCHAR[dwSz];
val = InternetGetCookieEx(argv[1], argv[2], lpData, &dwSz, INTERNET_COOKIE_THIRD_PARTY | INTERNET_FLAG_RESTRICTED_ZONE, NULL);
if (val)
{
std::cout << "Cookie Data: " << lpData << std::endl;
}
else
{
std::cout << "ERROR Code: " << GetLastError() << std::endl;
}
}
else
{
int err = GetLastError();
std::cout << "ERROR Code: " << err << std::endl;
}
}
else
{
std::cout << "Cookie Data: " << lpData << std::endl;
}
//}
return 0;
}
The problem that I am having is that when I call InternetGetCookeEx I always return false and get an error code of 259, which means no more data available. When you consult the API essentially what that means is that it couldn't find my cookie.
Because I am using IE 9 the names for files that the cookie is being stored in are obviously mangled , which is why I am trying to read my cookie data that way.
I have removed the company name to protect the company. Essentially what I am trying to do is. Find the lUsrCtxPersist cookie value. Therefore I am calling the code as such CookieReader.ext http://[CompanyDomain].com lUsrCtxPersist.
However I always get a false and an error code of 259. Any light you might be able to shed on this would be greatly appreciated.
http://msdn.microsoft.com/en-us/library/ms537312%28v=vs.85%29.aspx
Try to use IEGetProtectedModeCookie
Assuming the cookie name is correct, then try removing the INTERNET_COOKIE_THIRD_PARTY and/or INTERNET_FLAG_RESTRICTED_ZONE flags and see what happens. Or try calling InternetGetCookie() instead, which has no such flags available.
On a separate note, when InternetGetCookieEx() returns ERROR_INSUFFICIENT_BUFFER, you are leaking memory. You need to delete[] your existing buffer before then calling new[] to allocate a new buffer.