libwg-go: more efficient and safer string passing

It was unclear when the Go string was actually freed.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Jason A. Donenfeld 2018-06-05 02:17:50 +02:00
parent 40a30d997d
commit dea60e13c0
2 changed files with 7 additions and 10 deletions

View File

@ -161,8 +161,8 @@ func wgGetSocketV6(tunnelHandle int32) int32 {
} }
//export wgVersion //export wgVersion
func wgVersion() string { func wgVersion() *C.char {
return WireGuardGoVersion return C.CString(WireGuardGoVersion)
} }
func main() {} func main() {}

View File

@ -12,7 +12,7 @@ extern int wgTurnOn(struct go_string ifname, int tun_fd, struct go_string settin
extern void wgTurnOff(int handle); extern void wgTurnOff(int handle);
extern int wgGetSocketV4(int handle); extern int wgGetSocketV4(int handle);
extern int wgGetSocketV6(int handle); extern int wgGetSocketV6(int handle);
extern struct go_string wgVersion(); extern char *wgVersion();
JNIEXPORT jint JNICALL Java_com_wireguard_android_backend_GoBackend_wgTurnOn(JNIEnv *env, jclass c, jstring ifname, jint tun_fd, jstring settings) JNIEXPORT jint JNICALL Java_com_wireguard_android_backend_GoBackend_wgTurnOn(JNIEnv *env, jclass c, jstring ifname, jint tun_fd, jstring settings)
{ {
@ -50,13 +50,10 @@ JNIEXPORT jint JNICALL Java_com_wireguard_android_backend_GoBackend_wgGetSocketV
JNIEXPORT jstring JNICALL Java_com_wireguard_android_backend_GoBackend_wgVersion(JNIEnv *env, jclass c) JNIEXPORT jstring JNICALL Java_com_wireguard_android_backend_GoBackend_wgVersion(JNIEnv *env, jclass c)
{ {
jstring ret; jstring ret;
struct go_string s = wgVersion(); char *version = wgVersion();
char *cstr = malloc(s.n + 1); if (!version)
if (!cstr)
return NULL; return NULL;
memcpy(cstr, s.str, s.n); ret = (*env)->NewStringUTF(env, version);
cstr[s.n] = '\0'; free(version);
ret = (*env)->NewStringUTF(env, cstr);
free(cstr);
return ret; return ret;
} }