djkaty / Il2CppInspector

Powerful automated tool for reverse engineering Unity IL2CPP binaries
http://www.djkaty.com
GNU Affero General Public License v3.0
2.62k stars 433 forks source link

Boxing a value causes game crashing #173

Closed robertnisipeanu closed 3 years ago

robertnisipeanu commented 3 years ago

I'm trying to convert a normal value to a boxed one (Scene to Scene__Boxed), however I can't seem to understand how to correctly do that nor find any documentation on how to do it.

main.cpp:

// Generated C++ file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty
// Custom injected code entry point

#include "pch-il2cpp.h"

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <iostream>
#include "il2cpp-appdata.h"
#include "helpers.h"

// Set the name of your log file here
extern const LPCWSTR LOG_FILE = L"il2cpp-log.txt";

// Custom injected code entry point
void Run()
{
    // Initialize thread data - DO NOT REMOVE
    il2cpp_thread_attach(il2cpp_domain_get());

    // If you would like to output to a new console window, use il2cppi_new_console() to open one and redirect stdout
    il2cppi_new_console();

    auto sceneNumber = app::SceneManager_get_sceneCount(nullptr);
    std::cout << "Scene count: " << sceneNumber << std::endl;

    auto activeScene = app::SceneManager_GetActiveScene(nullptr);
    auto activeSceneBoxed = (app::Scene__Boxed*) il2cpp_value_box((Il2CppClass*)*app::Scene__TypeInfo, &activeScene); // IT CRASHSES HERE

    auto sceneName = app::Scene_get_name(activeSceneBoxed, nullptr);
    auto sceneNameCpp = il2cppi_to_string(sceneName);

    std::cout << "Current scene: " << sceneNameCpp.c_str() << std::endl;
}

Game crashes when calling il2cpp_value_box and trying to convert the Scene object into a Scene__Boxed pointer. What is the proper way to get a boxed pointer from a non-boxed variable?

femanzo commented 3 years ago

I was having the same problem, then I tried SceneInstance instead, it worked. Try this:

if (il2cppi_is_initialized(SceneInstance__TypeInfo)) {
    auto activeScene = app::SceneManager_GetActiveScene(nullptr);
    std::cout << "\nActive Scene pointer: " << activeScene.m_Handle << std::endl;
    auto activeSceneBoxed = (SceneInstance__Boxed*)il2cpp_value_box((Il2CppClass*)*app::SceneInstance__TypeInfo, &activeScene);
    auto activeSceneBoxedNew = (Scene__Boxed*)il2cpp_value_box((Il2CppClass*)*app::SceneInstance__TypeInfo, &activeSceneBoxed->fields.m_Scene); 

    auto sceneName = app::Scene_get_name(activeSceneBoxedNew, nullptr);
    auto sceneNameCpp = il2cppi_to_string(sceneName);
    std::cout << "Current scene: " << sceneNameCpp.c_str() << std::endl;
}
robertnisipeanu commented 3 years ago

@femanso thanks for the answer. Unfortunately, I didn't have time (and I still don't) to set up everything so I can check your solution, but I'll assume this was it.

I'll close the issue now