Skip to content

Commit

Permalink
run pjnath on a console app
Browse files Browse the repository at this point in the history
  • Loading branch information
loki-47-6F-64 committed Feb 5, 2019
1 parent 6debb92 commit 17169d2
Show file tree
Hide file tree
Showing 6 changed files with 208 additions and 54 deletions.
2 changes: 1 addition & 1 deletion console/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ include_directories(
${KITTY_INCLUDE_DIRS}
)

add_executable(tman ${WRAPPER_SOURCES} ${C_SOURCES} ${CPP_SOURCES} pack.cpp pack.h tman.cpp TMan.h)
add_executable(tman ${WRAPPER_SOURCES} ${C_SOURCES} ${CPP_SOURCES} pack.cpp pack.h tman.cpp TMan.h vm.h vm.c)
# Check for missing symbols during linking
#SET_TARGET_PROPERTIES(tman PROPERTIES LINK_FLAGS "-pie -rpath '\\$ORIGIN'"")
###################################################################
Expand Down
116 changes: 68 additions & 48 deletions console/tman.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,12 @@
#include "pool.h"
#include "pack.h"

#include <dlfcn.h>
#include <jni.h>
#include <dlfcn.h>

#include "vm.h"
JavaVM *pj_jni_jvm { nullptr };

typedef int (*JNI_CreateJavaVM_t)(void *, void *, void *);
typedef jint (*registerNatives_t)(JNIEnv* env, jclass clazz);

int distance(const int &l, const int &r) {
return r - l;
}
Expand Down Expand Up @@ -63,46 +61,78 @@ void jvm_destroy(JavaVM *jvm) {
jvm->DestroyJavaVM();
}

int main(int argc, char* argv[]) {
auto libandroid_runtime_dso = dlopen("libandroid_runtime.so", RTLD_NOW);
auto libart = dlopen("libart.so", RTLD_NOW);
class except_t {
public:
std::string_view name;
std::string_view message;

if(!(libandroid_runtime_dso && libart)) {
std::cerr << "cannot load [libandroid_runtime_dso] || [libart.so]" << std::endl;
except_t() = default;

return 120;
except_t(const std::string_view &name, const std::string_view &message, const std::tuple<JNIEnv*, jstring, jstring> &env) :
name(name), message(message), _env(env) {}

except_t(except_t &&other) {
_env = other._env;
other._env = {nullptr, nullptr, nullptr};
}


auto JNI_CreateJavaVM = (JNI_CreateJavaVM_t) dlsym(libart, "JNI_CreateJavaVM");

except_t &operator=(except_t &&other) {
std::swap(_env, other._env);
std::swap(name, other.name);
std::swap(message, other.message);

std::cout << "hello world!" << std::endl;
JNIEnv *env { nullptr };
return *this;
}

JavaVMInitArgs vm_args;
JavaVMOption jvmopt[4];
jvmopt[0].optionString = "-Djava.class.path=/data/local/tmp/target-app.apk";
jvmopt[1].optionString = "-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y";
jvmopt[2].optionString = "-Djava.library.path=/data/local/tmp";
jvmopt[3].optionString = "-verbose:jni"; // may want to remove this, it's noisy

//JNI_GetDefaultJavaVMInitArgs(&vm_args);
vm_args.nOptions = 4;
vm_args.ignoreUnrecognized = JNI_FALSE;
vm_args.version = JNI_VERSION_1_6;
vm_args.options = jvmopt;
~except_t() {
if(std::get<0>(_env)) {
std::get<0>(_env)->ReleaseStringUTFChars(std::get<1>(_env), name.data());
std::get<0>(_env)->ReleaseStringUTFChars(std::get<2>(_env), message.data());
}
}

private:
std::tuple<JNIEnv*, jstring, jstring> _env = {nullptr, nullptr, nullptr};
};

std::cout << "hello world!" << std::endl;
except_t get_message(JNIEnv *env, jthrowable except) {
env->ExceptionClear();

auto except_class = env->GetObjectClass(except);
auto class_ = env->FindClass("java/lang/Class");

JNI_CreateJavaVM(&pj_jni_jvm, &env, &vm_args);
auto get_name = env->GetMethodID(class_, "getName", "()Ljava/lang/String;");
auto get_message = env->GetMethodID(except_class, "getMessage", "()Ljava/lang/String;");

std::cout << "hello world!" << std::endl;
auto jname = (jstring)env->CallObjectMethod(except_class, get_name);
auto jmessage = (jstring)env->CallObjectMethod(except, get_message);

util::safe_ptr<JavaVM, jvm_destroy> jvm(pj_jni_jvm);

auto message = env->GetStringUTFChars(jmessage, 0);
auto name = env->GetStringUTFChars(jname, 0);

return {
{name},
{message},
{env,jname,jmessage}
};
}

void handle_exception(JNIEnv *jni_env) {
if(auto exception = jni_env->ExceptionOccurred()) {
auto ex = get_message(jni_env, exception);
}
else {
print(error, "no exception :|");
}
}

int main(int argc, char* argv[]) {
JNIEnv *jni_env { nullptr };
util::safe_ptr<JavaVM, jvm_destroy> jvm {
init_jvm(&pj_jni_jvm, &jni_env)
};

pj::init(nullptr);

Expand All @@ -117,6 +147,7 @@ int main(int argc, char* argv[]) {
auto thread_ptr = pj::register_thread();

auto_run.run([&pool]() {

std::chrono::milliseconds max_tm { 500 };
std::chrono::milliseconds milli { 0 };

Expand All @@ -127,28 +158,30 @@ int main(int argc, char* argv[]) {
auto c = pool.io_queue().poll(milli);
if(c < 0) {
std::cerr << __FILE__ "::" << pj::err(pj::get_netos_err());

std::abort();
}
});
});

auto ice_trans = pool.ice_trans(on_data, on_ice_compl, on_call_connect);

std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
ice_trans.init_ice();



auto json = pack({ ice_trans.credentials(), ice_trans.get_candidates() });
auto str = json->dump();

auto client = file::connect("localhost", "2345");
auto client = file::connect("192.168.0.115", "2345");

if(!client.is_open()) {
print(error, "Could not connect to localhost:2345 :: ", err::current());
print(error, "Could not connect to 192.168.0.115:2345 :: ", err::current());

return 7;
}

print(info, "Connected to 192.168.0.115:2345");
util::append_struct(client.get_write_cache(), util::endian::little((std::uint16_t)str.size()));
_print(client, str);

Expand Down Expand Up @@ -250,16 +283,3 @@ int main() {
return 0;
}
*/

// linker flags needed :: -Wl,--export-dynamic
// Include all of the Android's libsigchain symbols
// libsigchain calls abort()
extern "C" {
JNIEXPORT void InitializeSignalChain() {}
JNIEXPORT void ClaimSignalChain() {}
JNIEXPORT void UnclaimSignalChain() {}
JNIEXPORT void InvokeUserSignalHandler() {}
JNIEXPORT void EnsureFrontOfChain() {}
JNIEXPORT void AddSpecialSignalHandlerFn() {}
JNIEXPORT void RemoveSpecialSignalHandlerFn() {}
}
88 changes: 88 additions & 0 deletions console/vm.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#include "vm.h"

/**
Copyright 2015 Tim 'diff' Strazzere <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
* COPIED from -- https://github.com/rednaga/native-shim
*/

JavaVM *init_jvm(JavaVM **p_vm, JNIEnv **p_env) {
//https://android.googlesource.com/platform/frameworks/native/+/ce3a0a5/services/surfaceflinger/DdmConnection.cpp
JavaVMOption opt[4];
opt[0].optionString = "-Djava.class.path=/data/local/tmp/target-app.apk";
opt[1].optionString = "-agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y";
opt[2].optionString = "-Djava.library.path=/data/local/tmp:/system/lib";
opt[3].optionString = "-verbose:jni"; // may want to remove this, it's noisy

// Add this option if you're hacking stuff and need it, not normally required
// opt[4].optionString = "-Xno-sig-chain"; // may not be require prior to ART vm, may even cause issues for DVM

JavaVMInitArgs args;
args.version = JNI_VERSION_1_6;
args.options = opt;
args.nOptions = 4; // Uptick this to 5, it will pass in the no-sig-chain option
args.ignoreUnrecognized = JNI_FALSE;

void *libdvm_dso = dlopen("libdvm.so", RTLD_NOW);
void *libandroid_runtime_dso = dlopen("libandroid_runtime.so", RTLD_NOW);

if (!libdvm_dso) {
libdvm_dso = dlopen("libart.so", RTLD_NOW);
}

if (!libdvm_dso || !libandroid_runtime_dso) {
return NULL;
}

JNI_CreateJavaVM_t JNI_CreateJavaVM;
JNI_CreateJavaVM = (JNI_CreateJavaVM_t) dlsym(libdvm_dso, "JNI_CreateJavaVM");
if (!JNI_CreateJavaVM) {
return NULL;
}

registerNatives_t registerNatives;
registerNatives = (registerNatives_t) dlsym(libandroid_runtime_dso, "Java_com_android_internal_util_WithFramework_registerNatives");
if (!registerNatives) {
// Attempt non-legacy version
registerNatives = (registerNatives_t) dlsym(libandroid_runtime_dso, "registerFrameworkNatives");
if(!registerNatives) {
return NULL;
}
}

if (JNI_CreateJavaVM(&(*p_vm), &(*p_env), &args)) {
return NULL;
}

if (registerNatives(*p_env, 0)) {
return NULL;
}

return *p_vm;
}

// linker flags needed :: -Wl,--export-dynamic
// Include all of the Android's libsigchain symbols
// libsigchain calls abort()
JNIEXPORT void InitializeSignalChain() {}
JNIEXPORT void ClaimSignalChain() {}
JNIEXPORT void UnclaimSignalChain() {}
JNIEXPORT void InvokeUserSignalHandler() {}
JNIEXPORT void EnsureFrontOfChain() {}
JNIEXPORT void AddSpecialSignalHandlerFn() {}
JNIEXPORT void RemoveSpecialSignalHandlerFn() {}
19 changes: 19 additions & 0 deletions console/vm.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#ifndef VM_H
#define VM_H

#include <jni.h>
#include <dlfcn.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef int(*JNI_CreateJavaVM_t)(JavaVM **p_vm, JNIEnv **p_env, void *vm_args);
typedef jint(*registerNatives_t)(JNIEnv *env, jclass clazz);

JavaVM *init_jvm(JavaVM **p_vm, JNIEnv **p_env);

#ifdef __cplusplus
}
#endif
#endif
2 changes: 1 addition & 1 deletion wrappers/pjsip/ice_trans.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ creds_t ICETrans::credentials() {

std::vector<ice_sess_cand_t> ICETrans::get_candidates(unsigned int comp_cnt) {
ice_sess_cand_t cand[ICE_MAX_CAND];
unsigned count;
unsigned count = ICE_MAX_CAND;

pj_ice_strans_enum_cands(_ice_trans.get(), comp_cnt +1, &count, cand);

Expand Down
35 changes: 31 additions & 4 deletions wrappers/pjsip/nath.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include "pool.h"

#include <kitty/util/optional.h>
#include <kitty/log/log.h>

namespace pj {

Expand All @@ -17,17 +18,43 @@ Pool pool;


// log callback to write to file
// TODO: define log_func
//static void log_func(int level, const char *data, int len) {
//
//}
static void log_func(int level, const char *data, int len) {
std::string_view str { data, (std::size_t)len };

if(str.back() == '\n') {
str.remove_suffix(1);
}

switch (level) {
case 0:
print(error, "FATAL --> aborting... ", str);
std::abort();
case 1:
print(info, str);
break;
case 2:
print(info, str);
break;
case 3:
print(info, str);
break;
case 4:
print(info, str);
break;
case 5:
print(debug, str);
break;
}
}

status_t init(util::Optional<std::string_view> logFile) {
pj_log_set_level(5);
if(logFile) {
pj_log_set_log_func(&pj_log_write);
}

pj_log_set_log_func(&log_func);

if(auto status = pj_init()) {
return status;
}
Expand Down

0 comments on commit 17169d2

Please sign in to comment.