Skip to content

Commit a921f27

Browse files
committed
add plain java target
1 parent e0f5769 commit a921f27

14 files changed

+464
-51
lines changed

bind/genjava.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1713,7 +1713,6 @@ import go.Seq;
17131713
//
17141714
// autogenerated by gobind %[1]s %[2]s
17151715
1716-
#include <android/log.h>
17171716
#include <stdint.h>
17181717
#include "seq.h"
17191718
#include "_cgo_export.h"

bind/java/NativeUtils.java

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
/*
2+
* Class NativeUtils is published under the The MIT License:
3+
*
4+
* Copyright (c) 2012 Adam Heinrich <[email protected]>
5+
*
6+
* Permission is hereby granted, free of charge, to any person obtaining a copy
7+
* of this software and associated documentation files (the "Software"), to deal
8+
* in the Software without restriction, including without limitation the rights
9+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
* copies of the Software, and to permit persons to whom the Software is
11+
* furnished to do so, subject to the following conditions:
12+
*
13+
* The above copyright notice and this permission notice shall be included in all
14+
* copies or substantial portions of the Software.
15+
*
16+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
* SOFTWARE.
23+
*/
24+
package go;
25+
26+
import java.io.*;
27+
import java.nio.file.FileSystemNotFoundException;
28+
import java.nio.file.FileSystems;
29+
import java.nio.file.Files;
30+
import java.nio.file.ProviderNotFoundException;
31+
import java.nio.file.StandardCopyOption;
32+
33+
/**
34+
* A simple library class which helps with loading dynamic libraries stored in the
35+
* JAR archive. These libraries usually contain implementation of some methods in
36+
* native code (using JNI - Java Native Interface).
37+
*
38+
* @see <a href="http://adamheinrich.com/blog/2012/how-to-load-native-jni-library-from-jar">http://adamheinrich.com/blog/2012/how-to-load-native-jni-library-from-jar</a>
39+
* @see <a href="https://github.com/adamheinrich/native-utils">https://github.com/adamheinrich/native-utils</a>
40+
*
41+
*/
42+
public class NativeUtils {
43+
44+
/**
45+
* The minimum length a prefix for a file has to have according to {@link File#createTempFile(String, String)}}.
46+
*/
47+
private static final int MIN_PREFIX_LENGTH = 3;
48+
public static final String NATIVE_FOLDER_PATH_PREFIX = "nativeutils";
49+
50+
/**
51+
* Temporary directory which will contain the DLLs.
52+
*/
53+
private static File temporaryDir;
54+
55+
/**
56+
* Private constructor - this class will never be instanced
57+
*/
58+
private NativeUtils() {
59+
}
60+
61+
/**
62+
* Loads library from current JAR archive
63+
*
64+
* The file from JAR is copied into system temporary directory and then loaded. The temporary file is deleted after
65+
* exiting.
66+
* Method uses String as filename because the pathname is "abstract", not system-dependent.
67+
*
68+
* @param path The path of file inside JAR as absolute path (beginning with '/'), e.g. /package/File.ext
69+
* @throws IOException If temporary file creation or read/write operation fails
70+
* @throws IllegalArgumentException If source file (param path) does not exist
71+
* @throws IllegalArgumentException If the path is not absolute or if the filename is shorter than three characters
72+
* (restriction of {@link File#createTempFile(java.lang.String, java.lang.String)}).
73+
* @throws FileNotFoundException If the file could not be found inside the JAR.
74+
*/
75+
public static void loadLibraryFromJar(String path) throws IOException {
76+
77+
if (null == path || !path.startsWith("/")) {
78+
throw new IllegalArgumentException("The path has to be absolute (start with '/').");
79+
}
80+
81+
// Obtain filename from path
82+
String[] parts = path.split("/");
83+
String filename = (parts.length > 1) ? parts[parts.length - 1] : null;
84+
85+
// Check if the filename is okay
86+
if (filename == null || filename.length() < MIN_PREFIX_LENGTH) {
87+
throw new IllegalArgumentException("The filename has to be at least 3 characters long.");
88+
}
89+
90+
// Prepare temporary file
91+
if (temporaryDir == null) {
92+
temporaryDir = createTempDirectory(NATIVE_FOLDER_PATH_PREFIX);
93+
temporaryDir.deleteOnExit();
94+
}
95+
96+
File temp = new File(temporaryDir, filename);
97+
98+
try (InputStream is = NativeUtils.class.getResourceAsStream(path)) {
99+
Files.copy(is, temp.toPath(), StandardCopyOption.REPLACE_EXISTING);
100+
} catch (IOException e) {
101+
temp.delete();
102+
throw e;
103+
} catch (NullPointerException e) {
104+
temp.delete();
105+
throw new FileNotFoundException("File " + path + " was not found inside JAR.");
106+
}
107+
108+
try {
109+
System.load(temp.getAbsolutePath());
110+
} finally {
111+
if (isPosixCompliant()) {
112+
// Assume POSIX compliant file system, can be deleted after loading
113+
temp.delete();
114+
} else {
115+
// Assume non-POSIX, and don't delete until last file descriptor closed
116+
temp.deleteOnExit();
117+
}
118+
}
119+
}
120+
121+
private static boolean isPosixCompliant() {
122+
try {
123+
return FileSystems.getDefault()
124+
.supportedFileAttributeViews()
125+
.contains("posix");
126+
} catch (FileSystemNotFoundException
127+
| ProviderNotFoundException
128+
| SecurityException e) {
129+
return false;
130+
}
131+
}
132+
133+
private static File createTempDirectory(String prefix) throws IOException {
134+
String tempDir = System.getProperty("java.io.tmpdir");
135+
File generatedDir = new File(tempDir, prefix + System.nanoTime());
136+
137+
if (!generatedDir.mkdir())
138+
throw new IOException("Failed to create temp directory " + generatedDir.getName());
139+
140+
return generatedDir;
141+
}
142+
}

bind/java/Seq.java

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
package go;
66

7-
import android.content.Context;
7+
// import android.content.Context;
88

99
import java.lang.ref.PhantomReference;
1010
import java.lang.ref.Reference;
@@ -34,15 +34,29 @@ public class Seq {
3434
private static final GoRefQueue goRefQueue = new GoRefQueue();
3535

3636
static {
37-
System.loadLibrary("gojni");
37+
if ("The Android Project".equals(System.getProperty("java.vendor"))) {
38+
System.loadLibrary("gojni");
39+
} else {
40+
String arch = System.getProperty("os.arch");
41+
if ("aarch64".equals(arch)) {
42+
arch = "arm64";
43+
} else if ("x86_64".equals(arch)) {
44+
arch = "amd64";
45+
}
46+
try {
47+
NativeUtils.loadLibraryFromJar("/jniLibs/" + arch + "/libgojni.so");
48+
} catch (Exception e) {
49+
throw new RuntimeException(e);
50+
}
51+
}
3852
init();
3953
Universe.touch();
4054
}
4155

4256
// setContext sets the context in the go-library to be used in RunOnJvm.
43-
public static void setContext(Context context) {
44-
setContext((java.lang.Object)context);
45-
}
57+
// public static void setContext(Context context) {
58+
// setContext((java.lang.Object)context);
59+
// }
4660

4761
private static native void init();
4862

bind/java/context_android.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
// license that can be found in the LICENSE file.
44

55
#include <jni.h>
6-
#include "seq_android.h"
6+
#include "seq_java.h"
77
#include "_cgo_export.h"
88

99
JNIEXPORT void JNICALL

bind/java/seq_android.c.support

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
// generated gomobile_bind package and compiled along with the
77
// generated binding files.
88

9-
#include <android/log.h>
109
#include <errno.h>
1110
#include <jni.h>
1211
#include <stdint.h>
@@ -19,6 +18,12 @@
1918

2019
#define NULL_REFNUM 41
2120

21+
#ifndef __GOBIND_ANDROID__
22+
#define ACT_ENV_CAST (void**)
23+
#else
24+
#define ACT_ENV_CAST
25+
#endif
26+
2227
// initClasses are only exported from Go if reverse bindings are used.
2328
// If they're not, weakly define a no-op function.
2429
__attribute__((weak)) void initClasses(void) { }
@@ -55,7 +60,7 @@ static JNIEnv *go_seq_get_thread_env(void) {
5560
if (ret != JNI_EDETACHED) {
5661
LOG_FATAL("failed to get thread env");
5762
}
58-
if ((*jvm)->AttachCurrentThread(jvm, &env, NULL) != JNI_OK) {
63+
if ((*jvm)->AttachCurrentThread(jvm, ACT_ENV_CAST &env, NULL) != JNI_OK) {
5964
LOG_FATAL("failed to attach current thread");
6065
}
6166
pthread_setspecific(jnienvs, env);

bind/java/seq_android.go.support

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@ package main
99
// files.
1010

1111
//#cgo CFLAGS: -Werror
12-
//#cgo LDFLAGS: -llog
12+
//#cgo android LDFLAGS: -llog
1313
//#include <jni.h>
1414
//#include <stdint.h>
1515
//#include <stdlib.h>
16-
//#include "seq_android.h"
16+
//#include "seq_java.h"
1717
import "C"
1818
import (
1919
"unsafe"

bind/java/seq_android.h

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,18 +6,32 @@
66
#define __GO_SEQ_ANDROID_HDR__
77

88
#include <stdint.h>
9-
#include <android/log.h>
109
// For abort()
1110
#include <stdlib.h>
1211
#include <jni.h>
1312

13+
#ifdef __GOBIND_ANDROID__
14+
15+
#include <android/log.h>
16+
1417
#define LOG_INFO(...) __android_log_print(ANDROID_LOG_INFO, "go/Seq", __VA_ARGS__)
1518
#define LOG_FATAL(...) \
1619
{ \
1720
__android_log_print(ANDROID_LOG_FATAL, "go/Seq", __VA_ARGS__); \
1821
abort(); \
1922
}
2023

24+
#else
25+
26+
#define LOG_INFO(...) printf(__VA_ARGS__)
27+
#define LOG_FATAL(...) \
28+
{ \
29+
fprintf(stderr, __VA_ARGS__); \
30+
abort(); \
31+
}
32+
33+
#endif
34+
2135
// Platform specific types
2236
typedef struct nstring {
2337
// UTF16 or UTF8 Encoded string. When converting from Java string to Go

bind/seq.go.support

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ package main
99
// with the bindings.
1010

1111
// #cgo android CFLAGS: -D__GOBIND_ANDROID__
12+
// #cgo java CFLAGS: -D__GOBIND_JAVA__
1213
// #cgo darwin CFLAGS: -D__GOBIND_DARWIN__
1314
// #include <stdlib.h>
1415
// #include "seq.h"

0 commit comments

Comments
 (0)