GithubHelp home page GithubHelp logo

fungos / cr Goto Github PK

View Code? Open in Web Editor NEW
1.5K 48.0 99.0 202 KB

cr.h: A Simple C Hot Reload Header-only Library

Home Page: https://fungos.github.io/cr-simple-c-hot-reload/

License: MIT License

CMake 1.27% C++ 97.56% Python 0.81% Batchfile 0.02% Logos 0.35%
gamedev tool hot-reload gamedev-tool live-coding linux osx windows c single-header

cr's Introduction

cr's People

Contributors

clibequilibrium avatar cr545l avatar datgame avatar fungos avatar joaqim avatar jonliu1993 avatar neopallium avatar noahrinehart avatar nslottow avatar pospelove avatar rokups avatar septag avatar skypjack avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cr's Issues

Locked DLL

Hello,

I'm working on MSVC and I am trying to make a really simple 3 files project work, but I have a problem of a locked dll. I've pretty much copy-pasted the basic sample. When I try to regenerate the DLL after modification while my host executable is running, it tells me the DLL can't be overwritten because it is used somewhere. The lib seems to copy the .dll and .pdb properly, but both the original and the copy are used by the executable (I tried to remove them at runtime to make sure they were used). Nobody's complaining about such an issue so I guess I have misunderstood something here.

Crash protection prevents host crashes, causing application to freeze

I encountered a situation where the host crashed, but the cr crash handler caught it, causing the host to simply sit there doing nothing. From the outside, it looked like it had simply frozen.

If I enable trace logging, then I see that the signal handler is called in an infinite loop.

On Ubuntu Linux using Clang 11.0.0-2

Is there a way to avoid this?

Issues with old plugin not unloading correctly. (TLS + Linux)

I found a way to catch panics from Rust guest plugins. But there seems to be a problem when cr does a reload after a rollback. Maybe a segfault happens in the cr reload code and it tries to siglongjmp back to cr_plugin_main()?

Might be useful to have an option to disable the setjmp/exception handling for a plugin.

This is the commit I was using:
Neopallium/cr-sys@8b7853c

With CR_DEBUG defined in src/host.cpp.

Output running under valgrind:
cr-sys-rollback-reload.log

C++ support

If the DLL is written in C++ without exception handling or RTTI, would it work? If not, what would need to implemented? Also, any plans on adding C++ support in the future? Thanks!

Consider C11 only.

C++17 is used to profit from std::filesystem support and reducing the amount of code required to maintain.

I do not consider this an issue in the C++ area, but if for some weird reason pure C is needed too in the host implementation, I may consider downgrading.

How to use this with Visual Studio?

Hello,

I have seen this tip but I have a solution file in Visual Studio and can use the IDE itself or msbuild to compile my project from the command-line. In my solution file I have a project that produces a DLL that cr.h is managing as the "guest application", and the "host" is an executable that is being debugged by Visual Studio. It would be ideal to be able to recompile the DLL while the host program is running in the debugger. I have tried externally invoking msbuild while it runs but it says the PDB file is locked. Apparently this is a common issue with hot reloading. Is this not the intended setup, or is there something I'm missing?

[Tutorial]Windows *.dll only Live Reload

maybe someone find it useful - ido

step-by-stepinstructions

  1. Create a working folder.
  2. Findthe vcvars32.bat (for 32bit) or vcvars64.bat
    and copy+paste it into your working folder.
  3. Create three Windows Batch files with the content listed below.
  4. Download to your working folder.
    cr.h | basic_guest.c | basic_host.cpp
  5. Edit the source of basic_guest.c and basic_host.cpp to:
    #include "cr.h"
  6. Open up windows terminal (cmd.exe)
    and navigate to you working directory.
    for example: CD /D C:\Documents\myWorkingFolder
  7. Execute vcvarsXX.bat in your cmd.
  8. Build the remaining *.bat files.
  • If changes were made to the guest.c source
    Save the fileand Rebuild the source from cmd.
build_basic_guest.bat
cl /c basic_guest.c
link basic_guest.obj /DLL
build_basic_host.bat
cl /DCR_DEPLOY_PATH=\"./\" /EHsc basic_host.cpp
cleanup.bat
DEL *.dll *.obj *.lib *.exp *.exe

Further consideration: currently the naming convention of the *.dll files increments with every build. Fortunately its easy to change this behaivor and use only two states of guest *.dll (old and new, a and b or 0 and 1 ) and switch between the edited content with every new build.

Rollback is unsafe in complex applications

cr is built around a notion that plugin may crash only when executing cr_main(). Thing is any complex system with plugin does not work that way.

For example imagine we have a GUI application where plugin provides some GUI controls. When plugin is loaded it would somehow register itself with the system in place, then system runs it's main loop and calls into plugin code all without need of cr_main(CR_STEP) step. This works good so far.

Problem arises when plugin code crashes. Crash handler will try to jump to context saved by last plugin's cr_main(CR_STEP) invocation. This is not correct and environment may be no longer valid (ctx may be gone for example).

This somehow needs to be addressed. In my own fork i added CR_ROLLBACK macro which set to 0 simply disables rollback mechanism and allows application to crash. This is quick and dirty solution. I am interested if this can be solved proper. Any ideas?

Different behaviour in linux and win

I've noticed a different behaviour in windows and linux versions. in windows the normal static vars (ones without CR_STATE) are not restored after plugin reload. But in linux, all variables are restored and doesn't actually care about CR_STATE
I guess this would be from restoring .bss section. And also other question is, if we backup and restore all static vars, what is the point of CR_STATE ?

Improve CI and range of compilers to test

Reorganize project structure, move fips into a folder to keep the root cleaner.
Add github actions with different compilers and a simplified compilation test to keep the code clear of warnings.

Pdb still locks

Hi,
I was testing out your library and noticed that on visual studio 2015 (update 3) it still locks the original pdb.
I have checked cr_pdb_replace function to see if the pdb name is replaced and it does, but after cr_so_load, the original pdb is locked instead of versioned one.
does visual studio gets it's pdb path from somewhere else instead of binary ?

Add macOS support

A missing wanted feature is support to macOS, at the current moment I don't have access to a Mac, but will try to get this done one way or another.

Starting a DLL

Hello!

I have some questions regarding the usage of cr, it might be that these are unsupported use cases or I'm just doing something wrong :)

I have a DLL that gets started by a server and from a client I'd like to monitor that DLL and reload it with changes. The first problem is the first call to cr_plugin_update sees that the dll has changed and loads it because the timestamp is not initialised during cr_plugin_load. This triggers a call to DllMain which causes problems because the dll is only supposed to be started from the server.

The second problem I see is doing a GetCurrentDirectory from DLLMain shows the directory of the client but the current workspace for that DLL should be the directory where it is in. This is after the first problem.

Lastly, building the changes from inside Visual Studio gives an error because the pdb is being used by another process and the changed dll will not be produced.

The code I'm using is basically the same as the example provided in the README. Any ideas on what I might be doing wrong would be greatly appreciated.

Thanks!

[Feature] Call any Function

I don't know if this is goes against the philosophy of the library or not, but I created a fork where you can call any function. With an extra syntax for C++.

My first try is here: xunilrj@c1638e8

I created some flags that makes this feature totally opt-in.

#define CR_HOST
#define CR_ANYFUNCTION
#define CR_CPP
#include "cr.h"
...
cr_plugin_load(plugin, "c:/game.dll");
cr_plugin_load_functions(plugin, "f1,f2,f3");
...

The C version:

auto f1 = (double(*)(double))cr_plugin_get_function(plugin, 0);
auto r1 = f(1.0f);
auto f2 = (double(*)(double,double))cr_plugin_get_function(plugin, 1);
auto r2 = f(1.0f, 2.0f);

The C++ version:

auto r1 = cr_plugin_call<double>(plugin, 0, 1.0f);
auto r2 = cr_plugin_call<double>(plugin, 1, 1.0f, 2.0f);

[Linux] Crash on reload

Hello!
I am experimenting with your library and i bumped into odd issue. Basically i have my libAwesomeGame.so which exports cr_main and does the proper thing. Library is loaded and executed fine. However if i trigger reload by say doing touch libAwesomeGame.so i get crash at this line. Both p->data[sec][0].data and p->data[sec][0].size are null. Any idea why that could be happening?

Figured you might find game library useful so here it is: libAwesomeGame.tar.gz

cr_main isn't invoked with operation CR_LOAD and the context passed to cr_plugin_load

I'm not sure if this is the intended behavior and I haven't found anything in the doc nor the old issues.
I'm using this library on a debian sid, clang 9 for development, the resulting code is meant to be deployed and tested on all the supported platforms.

This is an hypothetical header shared by the main executable and the plugin:

struct foo { int value{0}; };
struct bar { int value{0}; };

Consider the following snippet for main.cpp:

foo load{};
bar update{};

cr_plugin ctx;

ctx.userdata = &load;
cr_plugin_load(ctx, PLUGIN);

ctx.userdata = &update;
cr_plugin_update(ctx);

This is instead the code for the plugin:

CR_EXPORT int cr_main(cr_plugin *ctx, cr_op operation) {
    switch (operation) {
    case CR_LOAD:
        static_cast<foo *>(ctx->userdata)->value = 42;
        break;
    case CR_STEP:
        static_cast<baro *>(ctx->userdata)->value = 42;
        break;
    case CR_UNLOAD:
    case CR_CLOSE:
        // nothing to do here, this is only a test.
        break;
    }

    return 0;
}

I thought that it was possible to pass a given context during the load and a different one during the update.
However, it seems that the call to cr_main is delayed until I invoke cr_plugin_update. At this point, cr_main is invoked two times with the same context (the one containing a pointer to update) and with different operation (CR_LOAD, then CR_STEP).

It's not a big problem. I introduced a wrapper that has two data members for the given types and made it work. However, this is unexpected and somehow counterintuitive.
Is this the case and is there any way I can pass a different pointer through userdata to the different phases?

Unable to rollback crash in first load of plugin

If the first load of a plugin (version number 1) crashes (e.g. segfault), rollback attempts to load a nonexistent version zero and appears to enter a feedback loop of constant crashing / signal handler / crashing / etc.

Assert protection?

Hey, I hope this message finds you well.

Is there a possibility to add assert protection? I was looking at cr_signal_to_failure and sigsetjmp

For instance when imgui throws something like
Assertion failed: (g.WithinEndChild) && "Must call EndChild() and not End()!", file imgui.cpp, line 7162 currently my .dll just crashes and isn't rolling back as it's not considering it as a seg fault or anything like that .

I am on windows, gcc + mingw32

Multi-process support

My application spawns several worker sub-processes of itself. These instances need plugins loaded as well. Situation here gets hairy. Each subprocess insists on renaming original plugin file and each subprocess is counting from 0. Collisions happen between subprocesses and between subprocess and main process.

Would it be possible to somehow handle this situation?

Few things come to my mind:

Include host process id in renamed plugin name. This is probably not a good idea due to name becoming too long and interfering with patching pdb path on windows.

Create a directory with host process id in it's name, put renamed plugins there. This is probably better, common directory prefix could allow easy cleanup of these directories.

But i do not particularly like either suggestion. Maybe someone has a better idea?

Unknown pragmas

Currently, both clang and g++ trigger a warning for an unknown lambda due to this line:

#pragma section(".state", read, write)

Not sure what the purpose of this line is (it's... well, Christmas, I haven't looked into the code today) but apparently both the compilers just ignore it.

clang compile warnings

#if CR_EXPAND(CR_HOST) == 1337
    ^
cr.h:526:22: note: expanded from macro 'CR_EXPAND'
#define CR_EXPAND(x) CR_DO_EXPAND(x)
                     ^
cr.h:525:25: note: expanded from macro 'CR_DO_EXPAND'
#define CR_DO_EXPAND(x) x##1337
                        ^
<scratch space>:560:1: note: expanded from here
CR_UNSAFE1337

when doing

#define CR_HOST CR_UNSAFE
#include "cr.h" 

i think also that CR_STATE is not working for me, (never tried before), because ASAN (clang++ -fsanitize=address) complains upon reload.
i tried adding these to the globals in stb_image.h

#include "cr.h"
static const char CR_STATE *stbi__g_failure_reason;

but ASAN still complains. not sure if that's correct in this matter or not, but i think so.

not sure if these 2 are related or not.
nor what to do about them

that was on linux.

trying to build the same on windows now, i get:

cr.h(455): warning C4109: unexpected identifier '_read'
stb_image.h(845): error C2341: '.state': segment must be defined using #pragma data_seg, code_seg or section prior to use

Bug: Elf relocation

On linux (elf), when we define a new .section add assign some variables to it, the .state section data gets mangled.
I couldn't solve it yet, because I don't have enough knowledge on elf format and how the code accesses section data pointers.
But I suspect that there must a bug within cr_elf_validate_sections where we fetch the pointer to section's data.
For example, if we define a new variable:

__attribute__((section(".test"))) int test;

the .state data seems to be overwritten with zeros by 4 bytes
I may do more investigations and keep you posted

CR_LOAD called on first update, contrary to what the documentation states. Is this correct?

Hi,

In the documentation for CR_LOAD, it says:

This does not happen when a plugin is loaded for the first time as there is no state to restore;

However, I'm observing that it gets called on initial call to cr_plugin_update. Is this the expected behaviour (and the documentation is wrong)?

My test code:

// main.cpp
#define CR_HOST
#include <cr.h>

int main (int argc, char* argv[])
{
    cr_plugin ctx;
    cr_plugin_open(ctx, "./test.so");
    cr_plugin_update(ctx);
    cr_plugin_close(ctx);
    return 0;
}
// test.cpp
#include <cr.h>
#include <iostream>

CR_EXPORT int cr_main(cr_plugin* ctx, cr_op operation)
{
    switch (operation) {
        case CR_STEP:
        {
            std::cout << "STEP\n";
            break;
        }
        case CR_CLOSE:
        {
            std::cout << "CLOSE\n";
            break;
        }
        case CR_LOAD:
        {
            std::cout << "LOAD\n";
            break;
        }
        case CR_UNLOAD:
        {
            std::cout << "UNLOAD\n";
            break;
        }
    }
    return 0;
}

Compiled with:

clang++ -fPIC -Icr -c test.cpp -o test.o
clang++ -shared test.o -o test.so
clang++ -Icr -c main.cpp -o main.o
clang++ -ldl main.o -o main

Running ./main gives the output:

LOAD
STEP
CLOSE

AddressSanitizer reports an error when calling cr_plugin_close

When running my codebase with ASan, I noticed that it complained about CR. So I reran the code from #60 and the same thing happens. The code is unchanged from what I posted in #60, the only change is I compiled like this:

clang++ -fPIC -Icr -fsanitize=address -c test.cpp -o test.o
clang++ -shared -fsanitize=address test.o -o test.so
clang++ -Icr -fsanitize=address -c main.cpp -o main.o
clang++ -ldl -fsanitize=address main.o -o main

I'm unsure if its a false positive due to how CR messes with setjmp/longjmp and crash protection or if there's a real bug.

The ASan report is below:

=================================================================
==2496617==ERROR: AddressSanitizer: global-buffer-overflow on address 0x7f123c9e61e1 at pc 0x000000496967 bp 0x7ffe9df6e3e0 sp 0x7ffe9df6dba8
READ of size 96 at 0x7f123c9e61e1 thread T0
    #0 0x496966 in __asan_memcpy (/home/dan/code/cr_test/main+0x496966)
    #1 0x4ceaa7 in cr_plugin_sections_store(cr_plugin&) (/home/dan/code/cr_test/main+0x4ceaa7)
    #2 0x4cb20c in cr_plugin_unload(cr_plugin&, bool, bool) (/home/dan/code/cr_test/main+0x4cb20c)
    #3 0x4cae0e in cr_plugin_close (/home/dan/code/cr_test/main+0x4cae0e)
    #4 0x4cbacb in main (/home/dan/code/cr_test/main+0x4cbacb)
    #5 0x7f123f57ccb1 in __libc_start_main csu/../csu/libc-start.c:314:16
    #6 0x41d49d in _start (/home/dan/code/cr_test/main+0x41d49d)

0x7f123c9e61e1 is located 0 bytes to the right of global variable 'std::__ioinit' defined in '/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/iostream:74:25' (0x7f123c9e61e0) of size 1
  'std::__ioinit' is ascii string ''
SUMMARY: AddressSanitizer: global-buffer-overflow (/home/dan/code/cr_test/main+0x496966) in __asan_memcpy
Shadow bytes around the buggy address:
  0x0fe2c7934be0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0fe2c7934bf0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0fe2c7934c00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 f9 f9
  0x0fe2c7934c10: f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9
  0x0fe2c7934c20: f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9 f9
=>0x0fe2c7934c30: f9 f9 f9 f9 f9 f9 00 00 00 00 00 00[01]f9 f9 f9
  0x0fe2c7934c40: f9 f9 f9 f9 00 00 00 00 00 00 00 00 00 00 00 00
  0x0fe2c7934c50: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0fe2c7934c60: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0fe2c7934c70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x0fe2c7934c80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
  Shadow gap:              cc
==2496617==ABORTING

Incremental versioning could be incorrect

While reading the code I think I found an issue, but I am not sure, apologize in advance in that case :)

It could happen that you loaded new version, failed, rollback happened. Later you again update the plugin, version increments and it will start to load on the same version as was already tried once. But since dll was once loaded VS will lock .dll/.pdb files and you won't be able to overwrite them. So it looks like it would be better to always try newer version (the one which was never ever loaded with LoadLibrary).

No error when cr_main is missing

I am fairly confident this is a bug, but wanted to double-check.

In case loadable module does not have cr_main exported cr_plugin_update() does not report an error. What happens is host is trying to load guest over and over spamming console with errors and doing nothing. Shouldnt cr_plugin_update() return an error in this case?

Can't load plugins on linux

Hello, i was using this library on macos and it worked just fine with my setup and project.
I switch to the linux and i compiled it but the cr_plugin_update() function returns -2.
According to the cr.h file
// -2 to differentiate from crash handling code path, meaning the crash
// happened probably during load or unload and not update
I didn't understand why this happened, so i tried to run the samples with fips. It worked
but i use shell scripts for compiling for my projects and i tried to compile the basic_guest and basic_host files like this
clang -shared basic_guest.c -fPIC -o basic_guest.so
clang++ -std=c++17 basic_host.cpp -ldl -o basic_host

and again, the cr_plugin_update() function gives me -2
I am 100% sure i am putting the exact path to the plugin.
From what i understand it is a compiler thing. I also tried using optimizations(and without it), with gcc, looked at auto generated fips files and used the flags that fips used still not working

Print errors outside of debug mode

As far as I can tell, zero info is printed if CR_DEBUG isn't defined, not even errors. I personally don't think the define should have to be added to get basic info like "Couldn't load plugin: ./libSIMPLE-Sokol1.so: undefined symbol: get_delta".

If you disagree, feel free to close this issue, this is just a personal opinion.

I am more than willing to make the changes myself and submit a PR, but I'd rather get your input on whether it's a change you'd accept anyways before putting in that work.

multiple definition issue

Hi. Thank you for this project, it's exactly what I was looking for, however I'm stuck with the linker errors:

multiple definition of cr_plugin_open; CMakeFiles/hrust_sop.dir/plugin_manager.cpp.o
.... same for all other cr_plugin_* symbols

What I can figure out is how cr.h is getting into all of my compilation units.

I should say that I include cr.h into my header, which is then gets included in a few other places (with guards).
I suspect cr.h can not be included into headers, but instead should be only used in a cpp file?

I will appreciate any help,

Alex

RFC: Re-loadable plugin callbacks and nested plugins.

I have started a branch symbols in my repos:
https://github.com/Neopallium/cr/tree/symbols

It has added support for:

  1. Re-loadable custom plugin symbols cr_symbol. It is an opaque structure that holds a pointer to a symbol from the plugin. When the plugin reloads, all re-loadable symbols are updated.
  2. Support for safely calling plugin callbacks. cr_closure
  3. Nested setjmp protected calls (Allows nesting of plugins). This is only needed on linux/macOS, windows uses __try/__except which doesn't use a global and "should" be nesting safe?

Limits:

  1. Don't call into the same plugin more then once in a call chain (i.e. Plugin A -> Plugin B -> Plugin A "crash", would cause Plugin A to possible reload while it is still on the call stack.)

TODOS:

  • Doesn't free cr_symbol or cr_closure. I plan to add reference counting of cr_symbol
  • Always creates a new cr_symbol, should check if one already exists for the requested symbol.
  • Tests
  • Untested on windows/macOS.
  • Add cr_closure_free to release allocated cr_closure and release reference to cr_symbol
  • Add cr_closure_init to allow embedding cr_closure inside the callback's userdata object.
  • Try adding a "protected call" counter to cr_plugin to prevent reload/rollback while a protected call is active for that plugin. Or try to longjmp/throw back to the first protected call.

New public API:

struct cr_symbol *cr_plugin_get_symbol(struct cr_plugin *ctx, const char *name)

Returns a reference to a re-loadable plugin symbol.

struct cr_closure *cr_plugin_new_closure(struct cr_symbol *symbol, void *userdata)

Used to wrap the plugin's callback and userdata, so it can be safely unwrapped and called from host-side "trampoline" function.

Example (See working example in repos: samples/fake_gui.*, samples/cb_host.*, samples/cb_guest.c):

  • Fake GUI event callback API
typedef int (*cb_mouse_event_func)(void *userdata, int x, int y, int buttons);
int fake_register_mouse_events(cb_mouse_event_func cb, void *userdata);
int fake_send_mouse_event(int x, int y, int buttons);
  • Host-side support
// We need a "trampoline" function that will never be unloaded/reloaded.
// Only need one for each kind of callback function (typedef)
// This can be defined in a small common shared library that is dynamically linked into the host and plugins.
int host_trampoline_mouse_events(void *userdata, int x, int y, int buttons) {
  CR_CLOSURE_CALL_START(cb_mouse_event_func, userdata, true)
  if (cb_func) {
    return cb_func(closure->userdata, x, y, buttons);
  } else {
    fprintf(stdout, "No plugin callback.  Can happen when the plugin is closed `cr_plugin_close`\n");
  }
  CR_CLOSURE_CALL_END

  return 0;
}

///// Normal host-side code follows.....
  • Guest plugin callback
static struct cr_symbol * CR_STATE g_plugin_mouse_cb = NULL;
static void register_mouse_events(struct cr_plugin *ctx, void *userdata) {
  if (!g_plugin_mouse_cb) {
    // Only need to initialize `g_plugin_mouse_cb` on the first `CR_LOAD`
    g_plugin_mouse_cb = cr_plugin_get_symbol(ctx, "plugin_mouse_events");

    // We can create any number of `cr_closure` as needed and re-use `cr_symbol`
    struct cr_closure *closure = cr_symbol_new_closure(g_plugin_mouse_cb, userdata);
    fake_register_mouse_events(host_trampoline_mouse_events, closure);
  }
}

// Plugin callback for mouse events.
CR_EXPORT int plugin_mouse_events(void *userdata, int x, int y, int buttons) {
  struct cr_plugin *ctx = (struct cr_plugin *)userdata;
  fprintf(stdout, "Guest: mouse event: (%d, %d, 0x%x): ver=%d\n", x, y, buttons);
  return 0;
}

CR_EXPORT int cr_main(struct cr_plugin *ctx, enum cr_op operation) {
  if (operation == CR_LOAD) {
    // Reload/rollback unsafe register of mouse events callback
    //fake_register_mouse_events(plugin_mouse_events, ctx);
    // Reload/rollback safe.
    register_mouse_events(ctx, ctx);  // We are just using `ctx` as our plugin userdata.
  }
  return 0;
}

A function to test plugin file validity

Do you think it would be useful to have a function to test plugin file validity before it is actually loaded? Im thinking it would be very useful in cases where plugin files and there names are not known at a build time and there is no distinction between plugin files and other libraries (like special plugin folder or something). I know we can try to load library and look up cr_main, however this may cause execution of code and depending on library it may even lead to crashes or some other nasty side effects.

What i am proposing is to have cr_is_valid_plugin(file_path). This function should read dynamic library file, parse it's headers and look for cr_main export. If export is found then we can be reasonably sure it is a plugin.

Good thing about this is that i already have implementation for linux and windows here. So just MacOS bit is missing.

OSX: fails to find imageFile

OSX implementation: in cr_plugin_validate_sections function. right here inside the loop:

        if (strcasecmp(name, imagefile.c_str())) {
            // match loaded image filename
            continue;
        }

It doesn't find a match if I submit the relative path to cr_plugin_load, because the imageFile is absolute path.
I can submit a pull request, but I'm not sure is this a real bug or I'm not complying with the API or something..
does the API assume that the plugin path is always absolute ?

Extra callbacks and pointer fixing

I've been thinking about couple of improvements for Cr :

  1. Crash callback: when initializing plugins we could pass an optional crash handler callback to report plugin crashes to the host app

  2. We could have a reload plugin callback that notifies the host whether a plugin is reloaded, so host can do some extra stuff like pointer fixing (see below)

  3. There is a problem where we have to assign some callbacks that reside in the plugin to the host. for example gameplay events or coroutines , etc.. when plugin reloads, the callbacks may become invalid. So we can define another CR_STATE (for example CR_POINTER) like variable section that instead of reloading the section data, it keeps the data, but reports them to the host app, so the host could fix and replace those pointers. in order to not break the api compatibility, we can add a new cr_plugin_load function with these callbacks as arguments.

  4. There is also a need for event dispatching to plugins that is somewhat custom and cannot be handled by cr_main. For example you want to post mouse movements to all the plugins. so besides cr_main we could also have cr_events with a void* argument, that we can call a function like cr_dispatch_event from the host app to be called on every plugin. it's also optional. the plugin can also choose to implement it or not

If you are interested I can make a PR for them. Any suggestions ?

cr_pdb_process has unused arguments

The function in the object is defined as:

bool static cr_pdb_process(const std::string &source,
                           const std::string &desination) {
    std::string folder, fname, ext, orig_pdb;
    cr_split_path(desination, folder, fname, ext);
    bool result = cr_pdb_replace(desination, fname + ".pdb", orig_pdb);
    result &= cr_copy(orig_pdb, cr_replace_extension(desination, ".pdb"));
    return result;
}

As you can see, source isn't used at all. This triggers a lot of warnings when including cr.
Is it possible to suppress them by removing the unused argument from the function definition?
I can also open a PR for that, just let me know if it makes sense to you to update this function.

Thanks.

help needed

Hi,
live reloading isn't working for me on linux, here the facts I've debugged so far:

  • your repository with the imgui-sample reloading in linux works!
  • my project on windows reloading works
  • my project on linux 64bit does NOT work!

So the issue is clearly from my project setup, your sample is working. I've tried to debug this and found out:

  • library is copied successfully
  • new library is loaded (lsof -p shows the new library and debug logs also indicate that the new so is loaded). Old library is marked as "DEL"
  • I've checked md5 sums of the files and for the reloaded library and they're different (original vs runtime-modified library)
  • my project works, but code-changes done are compiled (shared library size changes, md5sum changes), are loaded (checked via lsof) but still old code is executed

any ideas how to find out what is going on and why it doesn't work? I'm not sure if I can trust qtcreator-debugger when I step through the source code, but on assembly level it looks like the old function (old debugging info also might happen). Or any sanity-checks I can do?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.