8000 fiji/fiji.c at master · glehmann/fiji · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
3286 lines (2872 loc) · 82.7 KB

fiji.c

File metadata and controls

3286 lines (2872 loc) · 82.7 KB
/*
* This is the Fiji launcher, a small native program to handle the
* startup of Java and Fiji.
*
* Copyright 2007-2011 Johannes Schindelin, Mark Longair, Albert Cardona
* Benjamin Schmid, Erwin Frise and Gregory Jefferis
*
* The source is distributed under the GPLv2 or later.
*
* Clarification: the license of the Fiji launcher has no effect on
* the Java Runtime, ImageJ or any plugins, since they are not derivatives.
*/
#define _BSD_SOURCE
#include <stdlib.h>
#include "jni.h"
#include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#ifdef __GNUC__
#define MAYBE_UNUSED __attribute__ ((unused))
#else
#define MAYBE_UNUSED
#endif
#ifdef MACOSX
#include <stdlib.h>
#include <pthread.h>
#include <CoreFoundation/CoreFoundation.h>
#include <ApplicationServices/ApplicationServices.h>
struct string;
static void append_icon_path(struct string *str);
static void set_path_to_JVM(void);
static int get_fiji_bundle_variable(const char *key, struct string *value);
#endif
static const char *get_platform(void)
{
#ifdef MACOSX
return "macosx";
#endif
#ifdef WIN32
return sizeof(void *) < 8 ? "win32" : "win64";
#endif
#ifdef __linux__
return sizeof(void *) < 8 ? "linux32" : "linux64";
#endif
return NULL;
}
#ifdef WIN32
#include <io.h>
#include <process.h>
#define PATH_SEP ";"
static void open_win_console();
/* TODO: use dup2() and freopen() and a thread to handle the output */
#else
#define PATH_SEP ":"
#ifndef O_BINARY
#define O_BINARY 0
#endif
#endif
#ifdef __linux__
#include "glibc-compat.h"
#endif
static void error(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
}
__attribute__((__noreturn__))
__attribute__((format (printf, 1, 2)))
static void die(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
exit(1);
}
static void *xmalloc(size_t size)
{
void *result = malloc(size);
if (!result)
die("Out of memory");
return result;
}
static void *xcalloc(size_t size, size_t nmemb)
{
void *result = calloc(size, nmemb);
if (!result)
die("Out of memory");
return result;
}
static void *xrealloc(void *p, size_t size)
{
void *result = realloc(p, size);
if (!result)
die("Out of memory");
return result;
}
static char *xstrdup(const char *buffer)
{
char *result = strdup(buffer);
if (!result)
die("Out of memory");
return result;
}
static char *xstrndup(const char *buffer, size_t max_length)
{
char *eos = memchr(buffer, '\0', max_length - 1);
int len = eos ? eos - buffer : max_length;
char *result = xmalloc(len + 1);
if (!result)
die("Out of memory");
memcpy(result, buffer, len);
result[len] = '\0';
return result;
}
struct string {
int alloc, length;
char *buffer;
};
static void string_ensure_alloc(struct string *string, int length)
{
if (string->alloc <= length) {
char *new_buffer = xrealloc(string->buffer, length + 1);
string->buffer = new_buffer;
string->alloc = length;
}
}
static void string_set_length(struct string *string, int length)
{
if (length > string->length)
die("Cannot enlarge strings");
string->length = length;
string->buffer[length] = '\0';
}
static void string_set(struct string *string, const char *buffer)
{
free(string->buffer);
string->buffer = xstrdup(buffer);
string->alloc = string->length = strlen(buffer);
}
static struct string *string_init(int length)
{
struct string *string = xcalloc(sizeof(struct string), 1);
string_ensure_alloc(string, length);
string->buffer[0] = '\0';
return string;
}
static struct string *string_copy(const char *string)
{
int len = strlen(string);
struct string *result = string_init(len);
memcpy(result->buffer, string, len + 1);
result->length = len;
return result;
}
static void string_release(struct string *string)
{
if (string) {
free(string->buffer);
free(string);
}
}
static void string_add_char(struct string *string, char c)
{
if (string->alloc == string->length)
string_ensure_alloc(string, 3 * (string->alloc + 16) / 2);
string->buffer[string->length++] = c;
string->buffer[string->length] = '\0';
}
static void string_append(struct string *string, const char *append)
{
int len = strlen(append);
string_ensure_alloc(string, string->length + len);
memcpy(string->buffer + string->length, append, len + 1);
string->length += len;
}
static int path_list_contains(const char *list, const char *path)
{
size_t len = strlen(path);
const char *p = list;
while (p && *p) {
if (!strncmp(p, path, len) &&
(p[len] == PATH_SEP[0] || !p[len]))
return 1;
p = strchr(p, PATH_SEP[0]);
if (!p)
break;
p++;
}
return 0;
}
static void string_append_path_list(struct string *string, const char *append)
{
if (!append || path_list_contains(string->buffer, append))
return;
if (string->length)
string_append(string, PATH_SEP);
string_append(string, append);
}
static void string_append_at_most(struct string *string, const char *append, int length)
{
int len = strlen(append);
if (len > length)
len = length;
string_ensure_alloc(string, string->length + len);
memcpy(string->buffer + string->length, append, len + 1);
string->length += len;
string->buffer[string->length] = '\0';
}
static int number_length(unsigned long number, long base)
{
int length = 1;
while (number >= base) {
number /= base;
length++;
}
return length;
}
static inline int is_digit(char c)
{
return c >= '0' && c <= '9';
}
static void string_vaddf(struct string *string, const char *fmt, va_list ap)
{
while (*fmt) {
char fill = '\0';
int size = -1, max_size = -1;
char *p = (char *)fmt;
if (*p != '%' || *(++p) == '%') {
string_add_char(string, *p++);
fmt = p;
continue;
}
if (*p == ' ' || *p == '0')
fill = *p++;
if (is_digit(*p))
size = (int)strtol(p, &p, 10);
else if (p[0] == '.' && p[1] == '*') {
max_size = va_arg(ap, int);
p += 2;
}
switch (*p) {
case 's': {
const char *s = va_arg(ap, const char *);
if (fill) {
int len = size - strlen(s);
while (len-- > 0)
string_add_char(string, fill);
}
while (*s && max_size--)
string_add_char(string, *s++);
break;
}
case 'c':
string_add_char(string, va_arg(ap, int));
break;
case 'u':
case 'i':
case 'l':
case 'd':
case 'o':
case 'x':
case 'X': {
int base = *p == 'x' || *p == 'X' ? 16 :
*p == 'o' ? 8 : 10;
int negative = 0, len;
unsigned long number, power;
if (*p == 'u')
number = va_arg(ap, unsigned int);
else {
long signed_number;
if (*p == 'l')
signed_number = va_arg(ap, long);
else
signed_number = va_arg(ap, int);
if (signed_number < 0) {
negative = 1;
number = -signed_number;
} else
number = signed_number;
}
/* pad */
len = number_length(number, base);
while (size-- > len + negative)
string_add_char(string, fill ? fill : ' ');
if (negative)
string_add_char(string, '-');
/* output number */
power = 1;
while (len-- > 1)
power *= base;
while (power) {
int digit = number / power;
string_add_char(string, digit < 10 ? '0' + digit
: *p + 'A' - 'X' + digit - 10);
number -= digit * power;
power /= base;
}
break;
}
default:
/* unknown / invalid format: copy verbatim */
string_append_at_most(string, fmt, p - fmt + 1);
}
fmt = p + (*p != '\0');
}
}
__attribute__((format (printf, 2, 3)))
static void string_addf(struct string *string, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
string_vaddf(string, fmt, ap);
va_end(ap);
}
__attribute__((format (printf, 2, 3)))
static void string_addf_path_list(struct string *string, const char *fmt, ...)
{
va_list ap;
if (string->length)
string_append(string, PATH_SEP);
va_start(ap, fmt);
string_vaddf(string, fmt, ap);
va_end(ap);
}
__attribute__((format (printf, 2, 3)))
static void string_setf(struct string *string, const char *fmt, ...)
{
va_list ap;
string_ensure_alloc(string, strlen(fmt) + 64);
string->length = 0;
string->buffer[0] = '\0';
va_start(ap, fmt);
string_vaddf(string, fmt, ap);
va_end(ap);
}
__attribute__((format (printf, 1, 2)))
static struct string *string_initf(const char *fmt, ...)
{
struct string *string = string_init(strlen(fmt) + 64);
va_list ap;
va_start(ap, fmt);
string_vaddf(string, fmt, ap);
va_end(ap);
return string;
}
static void string_replace(struct string *string, char from, char to)
{
int j;
for (j = 0; j < string->length; j++)
if (string->buffer[j] == from)
string->buffer[j] = to;
}
__attribute__((unused))
static int string_read_file(struct string *string, const char *path) {
FILE *file = fopen(path, "rb");
char buffer[1024];
int result = 0;
if (!file) {
error("Could not open %s", path);
return -1;
}
for (;;) {
size_t count = fread(buffer, 1, sizeof(buffer), file);
string_ensure_alloc(string, string->length + count);
memcpy(string->buffer + string->length, buffer, count);
string->length += count;
if (count < sizeof(buffer))
break;
}
if (ferror(file) < 0)
result = -1;
fclose(file);
return result;
}
/*
* If set, overrides the environment variable JAVA_HOME, which in turn
* overrides relative_java_home.
*/
static const char *absolute_java_home;
static const char *relative_java_home = JAVA_HOME;
static const char *library_path = JAVA_LIB_PATH;
static const char *default_main_class = "fiji.Main";
static int is_default_main_class(const char *name)
{
return !strcmp(name, default_main_class) || !strcmp(name, "ij.ImageJ");
}
/* Dynamic library loading stuff */
#ifdef WIN32
#include <windows.h>
#define RTLD_LAZY 0
static char *dlerror_value;
static char *get_win_error(void)
{
DWORD error_code = GetLastError();
LPSTR buffer;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&buffer,
0, NULL);
return buffer;
}
static void *dlopen(const char *name, int flags)
{
void *result = LoadLibrary(name);
dlerror_value = get_win_error();
return result;
}
static char *dlerror(void)
{
/* We need to reset the error */
char *result = dlerror_value;
dlerror_value = NULL;
return result;
}
static void *dlsym(void *handle, const char *name)
{
void *result = (void *)GetProcAddress((HMODULE)handle, name);
dlerror_value = result ? NULL : (char *)"function not found";
return result;
}
static void sleep(int seconds)
{
Sleep(seconds * 1000);
}
// There is no setenv on Windows, so it should be safe for us to
// define this compatible version
static int setenv(const char *name, const char *value, int overwrite)
{
struct string *string;
if (!overwrite && getenv(name))
return 0;
if ((!name) || (!value))
return 0;
string = string_initf("%s=%s", name, value);
return putenv(string->buffer);
}
// Similarly we can do the same for unsetenv:
static int unsetenv(const char *name)
{
struct string *string = string_initf("%s=", name);
return putenv(string->buffer);
}
#else
#include <dlfcn.h>
#endif
// A wrapper for setenv that exits on error
void setenv_or_exit(const char *name, const char *value, int overwrite)
{
int result;
if (!value) {
#ifdef MACOSX
unsetenv(name);
#else
result = unsetenv(name);
if (result)
die("Unsetting environment variable %s failed", name);
#endif
return;
}
result = setenv(name, value, overwrite);
if (result)
die("Setting environment variable %s to %s failed", name, value);
}
/* Determining heap size */
#ifdef MACOSX
#include <mach/mach_init.h>
#include <mach/mach_host.h>
size_t get_memory_size(int available_only)
{
host_priv_t host = mach_host_self();
vm_size_t page_size;
vm_statistics_data_t host_info;
mach_msg_type_number_t host_count =
sizeof(host_info) / sizeof(integer_t);
host_page_size(host, &page_size);
return host_statistics(host, HOST_VM_INFO,
(host_info_t)&host_info, &host_count) ?
0 : ((size_t)(available_only ? host_info.free_count :
host_info.active_count +
host_info.inactive_count +
host_info.wire_count) * (size_t)page_size);
}
#elif defined(linux)
static size_t get_kB(struct string *string, const char *key)
{
const char *p = strstr(string->buffer, key);
if (!p)
return 0;
while (*p && *p != ' ')
p++;
return (size_t)strtoul(p, NULL, 10);
}
size_t get_memory_size(int available_only)
{
ssize_t page_size, available_pages;
/* Avoid overallocation */
if (!available_only) {
struct string *string = string_init(32);
if (!string_read_file(string, "/proc/meminfo"))
return 1024 * (get_kB(string, "MemFree:")
+ get_kB(string, "Buffers:")
+ get_kB(string, "Cached:"));
}
page_size = sysconf(_SC_PAGESIZE);
available_pages = sysconf(available_only ?
_SC_AVPHYS_PAGES : _SC_PHYS_PAGES);
return page_size < 0 || available_pages < 0 ?
0 : (size_t)page_size * (size_t)available_pages;
}
#elif defined(WIN32)
#include <windows.h>
size_t get_memory_size(int available_only)
{
MEMORYSTATUS status;
GlobalMemoryStatus(&status);
return available_only ? status.dwAvailPhys : status.dwTotalPhys;
}
#else
size_t get_memory_size(int available_only)
{
fprintf(stderr, "Unsupported\n");
return 0;
}
#endif
static long long parse_memory(const char *amount)
{
char *endp;
long long result = strtoll(amount, &endp, 0);
if (endp)
switch (*endp) {
case 't': case 'T':
result <<= 10;
/* fall through */
case 'g': case 'G':
result <<= 10;
/* fall through */
case 'm': case 'M':
result <<= 10;
/* fall through */
case 'k': case 'K':
result <<= 10;
break;
case '\0':
/* fall back to megabyte */
if (result < 1024)
result <<= 20;
}
return result;
}
__attribute__((unused))
static int parse_bool(const char *value)
{
return strcmp(value, "0") && strcmp(value, "false") &&
strcmp(value, "False") && strcmp(value, "FALSE");
}
/* work around a SuSE IPv6 setup bug */
#ifdef IPV6_MAYBE_BROKEN
#include <netinet/ip6.h>
#include <fcntl.h>
#endif
static int is_ipv6_broken(void)
{
#ifndef IPV6_MAYBE_BROKEN
return 0;
#else
int sock = socket(AF_INET6, SOCK_STREAM, 0);
static const struct in6_addr in6addr_loopback = {
{ { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } }
};
struct sockaddr_in6 address = {
AF_INET6, 57294 + 7, 0, in6addr_loopback, 0
};
long flags;
if (sock < 0)
return 1;
flags = fcntl(sock, F_GETFL, NULL);
if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) < 0) {
close(sock);
return 1;
}
int result = 0;
if (connect(sock, (struct sockaddr *)&address, sizeof(address)) < 0) {
if (errno == EINPROGRESS) {
struct timeval tv;
fd_set fdset;
tv.tv_sec = 0;
tv.tv_usec = 50000;
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
if (select(sock + 1, NULL, &fdset, NULL, &tv) > 0) {
int error;
socklen_t length = sizeof(int);
if (getsockopt(sock, SOL_SOCKET, SO_ERROR,
(void*)&error, &length) < 0)
result = 1;
else
result = (error == EACCES) |
(error == EPERM) |
(error == EAFNOSUPPORT) |
(error == EINPROGRESS);
} else
result = 1;
} else
result = (errno == EACCES) | (errno == EPERM) |
(errno == EAFNOSUPPORT);
}
close(sock);
return result;
#endif
}
/* Java stuff */
#ifndef JNI_CREATEVM
#define JNI_CREATEVM "JNI_CreateJavaVM"
#endif
static int is_slash(char c)
{
#ifdef WIN32
if (c == '\\')
return 1;
#endif
return c == '/';
}
const char *fiji_dir;
static const char *fiji_path(const char *relative_path)
{
static struct string *string[3];
static int counter;
counter = ((counter + 1) % (sizeof(string) / sizeof(string[0])));
if (!string[counter])
string[counter] = string_initf("%s%s%s", fiji_dir,
is_slash(*relative_path) ? "" : "/", relative_path);
else
string_setf(string[counter], "%s%s%s", fiji_dir,
is_slash(*relative_path) ? "" : "/", relative_path);
return string[counter]->buffer;
}
char *main_argv0;
char **main_argv, **main_argv_backup;
int main_argc, main_argc_backup;
const char *main_class;
int run_precompiled = 0;
static int dir_exists(const char *directory);
static int is_native_library(const char *path);
static int file_exists(const char *path);
__attribute__((unused))
static const char *get_java_home_env(void)
{
const char *env = getenv("JAVA_HOME");
if (env) {
if (dir_exists(env)) {
struct string* libjvm =
string_initf("%s/%s", env, library_path);
if (!file_exists(libjvm->buffer)) {
string_set_length(libjvm, 0);
string_addf(libjvm, "%s/jre/%s", env, library_path);
}
if (file_exists(libjvm->buffer) &&
!is_native_library(libjvm->buffer)) {
error("Ignoring JAVA_HOME (wrong arch): %s",
env);
env = NULL;
}
string_release(libjvm);
if (env)
return env;
}
else
error("Ignoring invalid JAVA_HOME: %s", env);
unsetenv("JAVA_HOME");
}
return NULL;
}
static const char *get_java_home(void)
{
if (absolute_java_home)
return absolute_java_home;
return fiji_path(relative_java_home);
}
static const char *get_jre_home(void)
{
const char *result = get_java_home();
int len = strlen(result);
static struct string *jre;
if (jre)
return jre->buffer;
if (len > 4 && !strcmp(result + len - 4, "/jre"))
return result;
jre = string_initf("%s/jre", result);
if (dir_exists(jre->buffer))
return jre->buffer;
string_setf(jre, "%s", result);
return D8DB result;
}
static size_t mystrlcpy(char *dest, const char *src, size_t size)
{
size_t ret = strlen(src);
if (size) {
size_t len = (ret >= size) ? size - 1 : ret;
memcpy(dest, src, len);
dest[len] = '\0';
}
return ret;
}
const char *last_slash(const char *path)
{
const char *slash = strrchr(path, '/');
#ifdef WIN32
const char *backslash = strrchr(path, '\\');
if (backslash && slash < backslash)
slash = backslash;
#endif
return slash;
}
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
static const char *make_absolute_path(const char *path)
{
static char bufs[2][PATH_MAX + 1], *buf = bufs[0];
char cwd[PATH_MAX] = "";
#ifndef WIN32
static char *next_buf = bufs[1];
int buf_index = 1, len;
#endif
int depth = 20;
char *last_elem = NULL;
struct stat st;
if (mystrlcpy(buf, path, PATH_MAX) >= PATH_MAX)
die("Too long path: %s", path);
while (depth--) {
if (stat(buf, &st) || !S_ISDIR(st.st_mode)) {
const char *slash = last_slash(buf);
if (slash) {
buf[slash-buf] = '\0';
last_elem = xstrdup(slash + 1);
} else {
last_elem = xstrdup(buf);
*buf = '\0';
}
}
if (*buf) {
if (!*cwd && !getcwd(cwd, sizeof(cwd)))
die("Could not get current working dir");
if (chdir(buf))
die("Could not switch to %s", buf);
}
if (!getcwd(buf, PATH_MAX))
die("Could not get current working directory");
if (last_elem) {
int len = strlen(buf);
if (len + strlen(last_elem) + 2 > PATH_MAX)
die("Too long path name: %s/%s", buf, last_elem);
buf[len] = '/';
strcpy(buf + len + 1, last_elem);
free(last_elem);
last_elem = NULL;
}
#ifndef WIN32
if (!lstat(buf, &st) && S_ISLNK(st.st_mode)) {
len = readlink(buf, next_buf, PATH_MAX);
if (len < 0)
die("Invalid symlink: %s", buf);
next_buf[len] = '\0';
buf = next_buf;
buf_index = 1 - buf_index;
next_buf = bufs[buf_index];
} else
#endif
break;
}
if (*cwd && chdir(cwd))
die("Could not change back to %s", cwd);
return buf;
}
static int is_absolute_path(const char *path)
{
#ifdef WIN32
if (((path[0] >= 'A' && path[0] <= 'Z') ||
(path[0] >= 'a' && path[0] <= 'z')) && path[1] == ':')
return 1;
#endif
return path[0] == '/';
}
static int file_exists(const char *path)
{
return !access(path, R_OK);
}
static inline int prefixcmp(const char *string, const char *prefix)
{
return strncmp(string, prefix, strlen(prefix));
}
static inline int suffixcmp(const char *string, int len, const char *suffix)
{
int suffix_len = strlen(suffix);
if (len < suffix_len)
return -1;
return strncmp(string + len - suffix_len, suffix, suffix_len);
}
static const char *find_in_path(const char *path)
{
const char *p = getenv("PATH");
struct string *buffer;
#ifdef WIN32
int len = strlen(path);
struct string *path_with_suffix = NULL;
const char *in_cwd;
if (suffixcmp(path, len, ".exe") && suffixcmp(path, len, ".EXE")) {
path_with_suffix = string_initf("%s.exe", path);
path = path_with_suffix->buffer;
}
in_cwd = make_absolute_path(path);
if (file_exists(in_cwd)) {
string_release(path_with_suffix);
return in_cwd;
}
#endif
if (!p)
die("Could not get PATH");
buffer = string_init(32);
for (;;) {
const char *colon = strchr(p, PATH_SEP[0]), *orig_p = p;
int len = colon ? colon - p : strlen(p);
struct stat st;
if (!len)
die("Could not find %s in PATH", path);
p += len + !!colon;
if (!is_absolute_path(orig_p))
continue;
string_setf(buffer, "%.*s/%s", len, orig_p, path);
#ifdef WIN32
#define S_IX S_IXUSR
#else
#define S_IX (S_IXUSR | S_IXGRP | S_IXOTH)
#endif
if (!stat(buffer->buffer, &st) && S_ISREG(st.st_mode) &&
(st.st_mode & S_IX)) {
const char *result = make_absolute_path(buffer->buffer);
string_release(buffer);
#ifdef WIN32
string_release(path_with_suffix);
#endif
return result;
}
0