Unverified Commit c978ced7 authored by ganyao114's avatar ganyao114 Committed by GitHub

Merge pull request #17 from ganyao114/new_xpcompat

New xpcompat
parents 8f7d1d20 d77a98bd
...@@ -38,7 +38,7 @@ cant hook if lined ...@@ -38,7 +38,7 @@ cant hook if lined
# how to use # how to use
```gradle ```gradle
implementation 'com.swift.sandhook:hooklib:3.1.0' implementation 'com.swift.sandhook:hooklib:4.0.0'
``` ```
## Annotation API ## Annotation API
...@@ -115,7 +115,7 @@ SanHook.public static boolean hook(Member target, Method hook, Method backup) {} ...@@ -115,7 +115,7 @@ SanHook.public static boolean hook(Member target, Method hook, Method backup) {}
if hookers is in plugin(like xposed): if hookers is in plugin(like xposed):
```groovy ```groovy
provided 'com.swift.sandhook:hookannotation:3.1.0' provided 'com.swift.sandhook:hookannotation:4.0.0'
``` ```
in your plugin in your plugin
...@@ -127,18 +127,30 @@ backup method can call itself to avoid be inlining ...@@ -127,18 +127,30 @@ backup method can call itself to avoid be inlining
-------------------------------------------------------------------- --------------------------------------------------------------------
Now you can use Xposed api: Now you can use Xposed api:
We have two different implements:
```groovy ```groovy
implementation 'com.swift.sandhook:xposedcompat:3.1.0' //stable
implementation 'com.swift.sandhook:xposedcompat:4.0.0'
//or
//hook fast first time
implementation 'com.swift.sandhook:xposedcompat_new:4.0.0'
``` ```
```java ```java
//setup for xposed //setup for xposed
//for xposed compat only(no need xposed comapt new)
XposedCompat.cacheDir = getCacheDir(); XposedCompat.cacheDir = getCacheDir();
//for load xp module(sandvxp)
XposedCompat.context = this; XposedCompat.context = this;
XposedCompat.classLoader = getClassLoader(); XposedCompat.classLoader = getClassLoader();
XposedCompat.isFirstApplication= true; XposedCompat.isFirstApplication= true;
//do hook //do hook
XposedHelpers.findAndHookMethod(Activity.class, "onResume", new XC_MethodHook() { XposedHelpers.findAndHookMethod(Activity.class, "onResume", new XC_MethodHook() {
@Override @Override
......
...@@ -27,6 +27,7 @@ dependencies { ...@@ -27,6 +27,7 @@ dependencies {
androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation project(':hooklib') implementation project(':hooklib')
implementation project(':nativehook') //implementation project(':nativehook')
implementation project(':xposedcompat') implementation project(':xposedcompat')
//implementation project(':xposedcompat_new')
} }
...@@ -5,7 +5,6 @@ import android.app.Application; ...@@ -5,7 +5,6 @@ import android.app.Application;
import android.os.Build; import android.os.Build;
import android.util.Log; import android.util.Log;
import com.swift.sandhook.nativehook.NativeHook;
import com.swift.sandhook.test.TestClass; import com.swift.sandhook.test.TestClass;
import com.swift.sandhook.testHookers.ActivityHooker; import com.swift.sandhook.testHookers.ActivityHooker;
import com.swift.sandhook.testHookers.CtrHook; import com.swift.sandhook.testHookers.CtrHook;
...@@ -30,7 +29,6 @@ public class MyApp extends Application { ...@@ -30,7 +29,6 @@ public class MyApp extends Application {
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
NativeHook.test();
SandHookConfig.DEBUG = BuildConfig.DEBUG; SandHookConfig.DEBUG = BuildConfig.DEBUG;
...@@ -58,8 +56,11 @@ public class MyApp extends Application { ...@@ -58,8 +56,11 @@ public class MyApp extends Application {
e.printStackTrace(); e.printStackTrace();
} }
//setup for xposed //for xposed compat(no need xposed comapt new)
XposedCompat.cacheDir = getCacheDir(); XposedCompat.cacheDir = getCacheDir();
//for load xp module(sandvxp)
XposedCompat.context = this; XposedCompat.context = this;
XposedCompat.classLoader = getClassLoader(); XposedCompat.classLoader = getClassLoader();
XposedCompat.isFirstApplication= true; XposedCompat.isFirstApplication= true;
......
...@@ -30,7 +30,7 @@ ext { ...@@ -30,7 +30,7 @@ ext {
userOrg = 'ganyao114' userOrg = 'ganyao114'
groupId = 'com.swift.sandhook' groupId = 'com.swift.sandhook'
repoName = 'SandHook' repoName = 'SandHook'
publishVersion = '3.4.6' publishVersion = '4.0.0'
desc = 'android art hook' desc = 'android art hook'
website = 'https://github.com/ganyao114/SandHook' website = 'https://github.com/ganyao114/SandHook'
licences = ['Apache-2.0'] licences = ['Apache-2.0']
......
...@@ -106,7 +106,7 @@ void* ArtMethod::getQuickCodeEntry() { ...@@ -106,7 +106,7 @@ void* ArtMethod::getQuickCodeEntry() {
} }
void* ArtMethod::getInterpreterCodeEntry() { void* ArtMethod::getInterpreterCodeEntry() {
return CastArtMethod::entryPointFormInterpreter->get(this); return CastArtMethod::entryPointFromInterpreter->get(this);
} }
GCRoot ArtMethod::getDeclaringClass() { GCRoot ArtMethod::getDeclaringClass() {
...@@ -122,10 +122,11 @@ void ArtMethod::setQuickCodeEntry(void *entry) { ...@@ -122,10 +122,11 @@ void ArtMethod::setQuickCodeEntry(void *entry) {
} }
void ArtMethod::setJniCodeEntry(void *entry) { void ArtMethod::setJniCodeEntry(void *entry) {
CastArtMethod::entryPointFromJNI->set(this, entry);
} }
void ArtMethod::setInterpreterCodeEntry(void *entry) { void ArtMethod::setInterpreterCodeEntry(void *entry) {
CastArtMethod::entryPointFormInterpreter->set(this, entry); CastArtMethod::entryPointFromInterpreter->set(this, entry);
} }
void ArtMethod::setDexCacheResolveList(void *list) { void ArtMethod::setDexCacheResolveList(void *list) {
......
...@@ -4,6 +4,7 @@ ...@@ -4,6 +4,7 @@
#include "../includes/cast_art_method.h" #include "../includes/cast_art_method.h"
#include "../includes/utils.h" #include "../includes/utils.h"
#include "../includes/never_call.h"
extern int SDK_INT; extern int SDK_INT;
...@@ -90,6 +91,11 @@ namespace SandHook { ...@@ -90,6 +91,11 @@ namespace SandHook {
class CastEntryPointFromJni : public IMember<art::mirror::ArtMethod, void *> { class CastEntryPointFromJni : public IMember<art::mirror::ArtMethod, void *> {
protected: protected:
Size calOffset(JNIEnv *jniEnv, art::mirror::ArtMethod *p) override { Size calOffset(JNIEnv *jniEnv, art::mirror::ArtMethod *p) override {
Size jniAddr = reinterpret_cast<Size>(Java_com_swift_sandhook_ClassNeverCall_neverCallNative);
int offset = findOffset(p, getParentSize(), 2, jniAddr);
if (offset >= 0) {
return static_cast<Size>(offset);
}
if (SDK_INT >= ANDROID_L2 && SDK_INT <= ANDROID_N) { if (SDK_INT >= ANDROID_L2 && SDK_INT <= ANDROID_N) {
return getParentSize() - 2 * BYTE_POINT; return getParentSize() - 2 * BYTE_POINT;
} else { } else {
...@@ -189,8 +195,8 @@ namespace SandHook { ...@@ -189,8 +195,8 @@ namespace SandHook {
accessFlag = new CastAccessFlag(); accessFlag = new CastAccessFlag();
accessFlag->init(env, m1, size); accessFlag->init(env, m1, size);
entryPointFormInterpreter = new CastEntryPointFormInterpreter(); entryPointFromInterpreter = new CastEntryPointFormInterpreter();
entryPointFormInterpreter->init(env, m1, size); entryPointFromInterpreter->init(env, m1, size);
dexCacheResolvedMethods = new CastDexCacheResolvedMethods(); dexCacheResolvedMethods = new CastDexCacheResolvedMethods();
dexCacheResolvedMethods->init(env, m1, size); dexCacheResolvedMethods->init(env, m1, size);
...@@ -240,6 +246,9 @@ namespace SandHook { ...@@ -240,6 +246,9 @@ namespace SandHook {
genericJniStub = entryPointQuickCompiled->get(neverCallNative); genericJniStub = entryPointQuickCompiled->get(neverCallNative);
} }
entryPointFromJNI = new CastEntryPointFromJni();
entryPointFromJNI->init(env, neverCallNative, size);
art::mirror::ArtMethod *neverCallStatic = reinterpret_cast<art::mirror::ArtMethod *>(env->GetStaticMethodID( art::mirror::ArtMethod *neverCallStatic = reinterpret_cast<art::mirror::ArtMethod *>(env->GetStaticMethodID(
neverCallTestClass, "neverCallStatic", "()V")); neverCallTestClass, "neverCallStatic", "()V"));
staticResolveStub = entryPointQuickCompiled->get(neverCallStatic); staticResolveStub = entryPointQuickCompiled->get(neverCallStatic);
...@@ -252,7 +261,8 @@ namespace SandHook { ...@@ -252,7 +261,8 @@ namespace SandHook {
Size CastArtMethod::size = 0; Size CastArtMethod::size = 0;
IMember<art::mirror::ArtMethod, void *> *CastArtMethod::entryPointQuickCompiled = nullptr; IMember<art::mirror::ArtMethod, void *> *CastArtMethod::entryPointQuickCompiled = nullptr;
IMember<art::mirror::ArtMethod, void *> *CastArtMethod::entryPointFormInterpreter = nullptr; IMember<art::mirror::ArtMethod, void *> *CastArtMethod::entryPointFromInterpreter = nullptr;
IMember<art::mirror::ArtMethod, void *> *CastArtMethod::entryPointFromJNI = nullptr;
ArrayMember<art::mirror::ArtMethod, void *> *CastArtMethod::dexCacheResolvedMethods = nullptr; ArrayMember<art::mirror::ArtMethod, void *> *CastArtMethod::dexCacheResolvedMethods = nullptr;
IMember<art::mirror::ArtMethod, uint32_t> *CastArtMethod::dexMethodIndex = nullptr; IMember<art::mirror::ArtMethod, uint32_t> *CastArtMethod::dexMethodIndex = nullptr;
IMember<art::mirror::ArtMethod, uint32_t> *CastArtMethod::accessFlag = nullptr; IMember<art::mirror::ArtMethod, uint32_t> *CastArtMethod::accessFlag = nullptr;
......
...@@ -14,7 +14,8 @@ namespace SandHook { ...@@ -14,7 +14,8 @@ namespace SandHook {
public: public:
static Size size; static Size size;
static IMember<art::mirror::ArtMethod, void*>* entryPointQuickCompiled; static IMember<art::mirror::ArtMethod, void*>* entryPointQuickCompiled;
static IMember<art::mirror::ArtMethod, void*>* entryPointFormInterpreter; static IMember<art::mirror::ArtMethod, void*>* entryPointFromInterpreter;
static IMember<art::mirror::ArtMethod, void*>* entryPointFromJNI;
static ArrayMember<art::mirror::ArtMethod,void*>* dexCacheResolvedMethods; static ArrayMember<art::mirror::ArtMethod,void*>* dexCacheResolvedMethods;
static IMember<art::mirror::ArtMethod, uint32_t>* dexMethodIndex; static IMember<art::mirror::ArtMethod, uint32_t>* dexMethodIndex;
static IMember<art::mirror::ArtMethod, uint32_t>* accessFlag; static IMember<art::mirror::ArtMethod, uint32_t>* accessFlag;
......
//
// Created by swift on 2019/6/3.
//
#ifndef SANDHOOK_NEVER_CALL_H
#define SANDHOOK_NEVER_CALL_H
#include <jni.h>
extern "C"
JNIEXPORT void JNICALL
Java_com_swift_sandhook_ClassNeverCall_neverCallNative(JNIEnv *env, jobject instance);
#endif //SANDHOOK_NEVER_CALL_H
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
#include "includes/log.h" #include "includes/log.h"
#include "includes/native_hook.h" #include "includes/native_hook.h"
#include "includes/elf_util.h" #include "includes/elf_util.h"
#include "includes/never_call.h"
#include <jni.h> #include <jni.h>
SandHook::TrampolineManager trampolineManager; SandHook::TrampolineManager trampolineManager;
...@@ -345,6 +345,22 @@ Java_com_swift_sandhook_SandHook_disableDex2oatInline(JNIEnv *env, jclass type, ...@@ -345,6 +345,22 @@ Java_com_swift_sandhook_SandHook_disableDex2oatInline(JNIEnv *env, jclass type,
return static_cast<jboolean>(SandHook::NativeHook::hookDex2oat(disableDex2oat)); return static_cast<jboolean>(SandHook::NativeHook::hookDex2oat(disableDex2oat));
} }
extern "C"
JNIEXPORT jboolean JNICALL
Java_com_swift_sandhook_SandHook_setNativeEntry(JNIEnv *env, jclass type, jobject origin, jobject hook, jlong jniTrampoline) {
if (origin == nullptr || hook == NULL)
return JNI_FALSE;
art::mirror::ArtMethod* hookMethod = reinterpret_cast<art::mirror::ArtMethod *>(env->FromReflectedMethod(hook));
art::mirror::ArtMethod* originMethod = reinterpret_cast<art::mirror::ArtMethod *>(env->FromReflectedMethod(origin));
originMethod->backup(hookMethod);
hookMethod->setNative();
hookMethod->setQuickCodeEntry(SandHook::CastArtMethod::genericJniStub);
hookMethod->setJniCodeEntry(reinterpret_cast<void *>(jniTrampoline));
hookMethod->disableCompilable();
hookMethod->flushCache();
return JNI_TRUE;
}
extern "C" extern "C"
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_swift_sandhook_ClassNeverCall_neverCallNative(JNIEnv *env, jobject instance) { Java_com_swift_sandhook_ClassNeverCall_neverCallNative(JNIEnv *env, jobject instance) {
...@@ -456,6 +472,11 @@ static JNINativeMethod jniSandHook[] = { ...@@ -456,6 +472,11 @@ static JNINativeMethod jniSandHook[] = {
"disableDex2oatInline", "disableDex2oatInline",
"(Z)Z", "(Z)Z",
(void *) Java_com_swift_sandhook_SandHook_disableDex2oatInline (void *) Java_com_swift_sandhook_SandHook_disableDex2oatInline
},
{
"setNativeEntry",
"(Ljava/lang/reflect/Member;Ljava/lang/reflect/Member;J)Z",
(void *) Java_com_swift_sandhook_SandHook_setNativeEntry
} }
}; };
......
...@@ -365,6 +365,8 @@ public class SandHook { ...@@ -365,6 +365,8 @@ public class SandHook {
public static native boolean disableDex2oatInline(boolean disableDex2oat); public static native boolean disableDex2oatInline(boolean disableDex2oat);
public static native boolean setNativeEntry(Member origin, Member hook, long nativeEntry);
@FunctionalInterface @FunctionalInterface
public interface HookModeCallBack { public interface HookModeCallBack {
int hookMode(Member originMethod); int hookMode(Member originMethod);
......
...@@ -68,7 +68,7 @@ public class HookWrapper { ...@@ -68,7 +68,7 @@ public class HookWrapper {
if (TextUtils.equals(hookEntity.isCtor() ? "<init>" : hookEntity.target.getName(), hookMethodBackup.value()) && samePars(classLoader, field, hookEntity.pars)) { if (TextUtils.equals(hookEntity.isCtor() ? "<init>" : hookEntity.target.getName(), hookMethodBackup.value()) && samePars(classLoader, field, hookEntity.pars)) {
field.setAccessible(true); field.setAccessible(true);
if (hookEntity.backup == null) { if (hookEntity.backup == null) {
hookEntity.backup = BackupMethodStubs.getStubMethod(); hookEntity.backup = StubMethodsFactory.getStubMethod();
hookEntity.hookIsStub = true; hookEntity.hookIsStub = true;
hookEntity.resolveDexCache = false; hookEntity.resolveDexCache = false;
} }
......
package com.swift.sandhook.wrapper; package com.swift.sandhook.wrapper;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class BackupMethodStubs { public class StubMethodsFactory {
final static int maxStub = 300; final static int maxStub = 300;
private static volatile int curStub = 0; private static volatile int curStub = 0;
private static Method proxyGenClass;
static {
try {
proxyGenClass = Proxy.class.getDeclaredMethod("generateProxy",String.class,Class[].class,ClassLoader.class,Method[].class,Class[][].class);
proxyGenClass.setAccessible(true);
} catch (Throwable e) {
e.printStackTrace();
}
}
public static synchronized Method getStubMethod() { public static synchronized Method getStubMethod() {
while (curStub <= maxStub) { while (curStub <= maxStub) {
try { try {
return BackupMethodStubs.class.getDeclaredMethod("stub" + curStub++); return StubMethodsFactory.class.getDeclaredMethod("stub" + curStub++);
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
} }
} }
return null; try {
curStub++;
Class proxyClass = (Class)proxyGenClass.invoke(null,"SandHookerStubClass_" + curStub, null, StubMethodsFactory.class.getClassLoader(), new Method[]{proxyGenClass}, null);
return proxyClass.getDeclaredMethods()[0];
} catch (Throwable e) {
e.printStackTrace();
return null;
}
} }
public void stub0() {} public void stub0() {}
......
...@@ -39,9 +39,4 @@ android { ...@@ -39,9 +39,4 @@ android {
dependencies { dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar']) implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
} }
package com.swift.sandhook.nativehook;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.swift.sandhook.nativehook.test", appContext.getPackageName());
}
}
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
#ifndef SANDHOOK_SANDHOOK_NATIVE_H #ifndef SANDHOOK_SANDHOOK_NATIVE_H
#define SANDHOOK_SANDHOOK_NATIVE_H #define SANDHOOK_SANDHOOK_NATIVE_H
#include "hook.h" typedef size_t REG;
#define EXPORT __attribute__ ((visibility ("default"))) #define EXPORT __attribute__ ((visibility ("default")))
......
package com.swift.sandhook.nativehook;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
\ No newline at end of file
include ':app', ':hooklib', ':hookers', ':annotation', ':xposedcompat', ':nativehook' include ':app', ':hooklib', ':hookers', ':annotation', ':xposedcompat', ':nativehook', ':xposedcompat_new'
...@@ -5,7 +5,7 @@ import android.util.Log; ...@@ -5,7 +5,7 @@ import android.util.Log;
import com.swift.sandhook.SandHook; import com.swift.sandhook.SandHook;
import com.swift.sandhook.SandHookMethodResolver; import com.swift.sandhook.SandHookMethodResolver;
import com.swift.sandhook.utils.ParamWrapper; import com.swift.sandhook.utils.ParamWrapper;
import com.swift.sandhook.wrapper.BackupMethodStubs; import com.swift.sandhook.wrapper.StubMethodsFactory;
import com.swift.sandhook.xposedcompat.XposedCompat; import com.swift.sandhook.xposedcompat.XposedCompat;
import com.swift.sandhook.xposedcompat.utils.DexLog; import com.swift.sandhook.xposedcompat.utils.DexLog;
...@@ -167,13 +167,13 @@ public class HookStubManager { ...@@ -167,13 +167,13 @@ public class HookStubManager {
try { try {
if (is64Bit) { if (is64Bit) {
Method hook = MethodHookerStubs64.class.getDeclaredMethod(getHookMethodName(curUseStubIndex), pars); Method hook = MethodHookerStubs64.class.getDeclaredMethod(getHookMethodName(curUseStubIndex), pars);
Method backup = hasStubBackup ? MethodHookerStubs64.class.getDeclaredMethod(getBackupMethodName(curUseStubIndex), pars) : BackupMethodStubs.getStubMethod(); Method backup = hasStubBackup ? MethodHookerStubs64.class.getDeclaredMethod(getBackupMethodName(curUseStubIndex), pars) : StubMethodsFactory.getStubMethod();
if (hook == null || backup == null) if (hook == null || backup == null)
return null; return null;
return new StubMethodsInfo(stubArgs, curUseStubIndex, hook, backup); return new StubMethodsInfo(stubArgs, curUseStubIndex, hook, backup);
} else { } else {
Method hook = MethodHookerStubs32.class.getDeclaredMethod(getHookMethodName(curUseStubIndex), pars); Method hook = MethodHookerStubs32.class.getDeclaredMethod(getHookMethodName(curUseStubIndex), pars);
Method backup = hasStubBackup ? MethodHookerStubs32.class.getDeclaredMethod(getBackupMethodName(curUseStubIndex), pars) : BackupMethodStubs.getStubMethod(); Method backup = hasStubBackup ? MethodHookerStubs32.class.getDeclaredMethod(getBackupMethodName(curUseStubIndex), pars) : StubMethodsFactory.getStubMethod();
if (hook == null || backup == null) if (hook == null || backup == null)
return null; return null;
return new StubMethodsInfo(stubArgs, curUseStubIndex, hook, backup); return new StubMethodsInfo(stubArgs, curUseStubIndex, hook, backup);
......
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html
# Sets the minimum version of CMake required to build the native library.
cmake_minimum_required(VERSION 3.4.1)
set(CMAKE_CXX_STANDARD 14)
enable_language(ASM)
SET(CMAKE_ASM_FLAGS "${CFLAGS} -x assembler-with-cpp")
# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
if(${CMAKE_ANDROID_ARCH_ABI} STREQUAL "arm64-v8a")
set(OS_DEPENDENDED_SRC
src/main/cpp/libffi/aarch64/ffi_arm64.c
src/main/cpp/libffi/aarch64/sysv_arm64.S)
elseif (${CMAKE_ANDROID_ARCH_ABI} STREQUAL "armeabi-v7a")
set(OS_DEPENDENDED_SRC
src/main/cpp/libffi/arm/ffi_armv7.c
src/main/cpp/libffi/arm/sysv_armv7.S)
endif()
add_library( # Sets the name of the library.
sandhook-xp
# Sets the library as a shared library.
SHARED
src/main/cpp/art_jni_trampoline.cpp
# Provides a relative path to your source file(s).
src/main/cpp/libffi/closures.c
src/main/cpp/libffi/closures.c
src/main/cpp/libffi/debug.c
src/main/cpp/libffi/dlmalloc.c
src/main/cpp/libffi/java_raw_api.c
src/main/cpp/libffi/prep_cif.c
src/main/cpp/libffi/raw_api.c
src/main/cpp/libffi/types.c
src/main/cpp/libffi/ffi_cxx.cc
${OS_DEPENDENDED_SRC})
include_directories(
src/main/cpp
src/main/cpp/libffi
src/main/cpp/libffi/platform_include
../nativehook/src/main/cpp
)
add_library(sandhook-native
SHARED
IMPORTED)
set_target_properties(sandhook-native
PROPERTIES IMPORTED_LOCATION
${CMAKE_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libsandhook-native.so)
# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.
find_library( # Sets the name of the path variable.
log-lib
# Specifies the name of the NDK library that
# you want CMake to locate.
log)
# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries( # Specifies the target library.
sandhook-xp
sandhook-native
# Links the target library to the log library
# included in the NDK.
${log-lib})
ENABLE_LANGUAGE(ASM)
\ No newline at end of file
apply plugin: 'com.android.library'
android {
compileSdkVersion 28
defaultConfig {
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
arguments '-DBUILD_TESTING=OFF'
cppFlags "-frtti -fexceptions -Wpointer-arith"
abiFilters 'armeabi-v7a', 'arm64-v8a'
}
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
compileOnly project(':hooklib')
}
apply plugin: 'com.novoda.bintray-release'
publish {
userOrg = rootProject.userOrg
groupId = rootProject.groupId
artifactId = 'xposedcompat_new'
publishVersion = rootProject.publishVersion
desc = rootProject.desc
website = rootProject.website
licences = rootProject.licences
}
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.swift.sandhook.xposedcompat" />
//
// Created by swift on 2019/6/3.
//
#include <cstring>
#include <utils/log.h>
#include "art_jni_trampoline.h"
#include "sandhook_native.h"
//bug fix hooks
void* NewGetOatQuickMethodHeader(void* artMethod, uintptr_t pc) {
std::set<void*>::iterator it = hookMethods.find(artMethod);
if (it != hookMethods.end()) {
LOGE("skip GetOatQuickMethodHeader");
return nullptr;
}
return GetOatQuickMethodHeaderBackup(artMethod, pc);
}
//bug fix hooks
#define EXPORT_LANG_ClASS(c) jclass Types::java_lang_##c; jmethodID Types::java_lang_##c##_init; jmethodID Types::java_value_##c;
EXPORT_LANG_ClASS(Integer);
EXPORT_LANG_ClASS(Long);
EXPORT_LANG_ClASS(Float);
EXPORT_LANG_ClASS(Double);
EXPORT_LANG_ClASS(Byte);
EXPORT_LANG_ClASS(Short);
EXPORT_LANG_ClASS(Boolean);
EXPORT_LANG_ClASS(Character);
#undef EXPORT_LANG_ClASS
void Types::Load(JNIEnv *env) {
jclass clazz;
env->PushLocalFrame(16);
#define LOAD_CLASS(c, s) clazz = env->FindClass(s); c = reinterpret_cast<jclass>(env->NewWeakGlobalRef(clazz))
#define LOAD_LANG_CLASS(c, s) LOAD_CLASS(java_lang_##c, "java/lang/" #c); java_lang_##c##_init = env->GetMethodID(java_lang_##c, "<init>", s)
LOAD_LANG_CLASS(Integer, "(I)V");
LOAD_LANG_CLASS(Long, "(J)V");
LOAD_LANG_CLASS(Float, "(F)V");
LOAD_LANG_CLASS(Double, "(D)V");
LOAD_LANG_CLASS(Byte, "(B)V");
LOAD_LANG_CLASS(Short, "(S)V");
LOAD_LANG_CLASS(Boolean, "(Z)V");
LOAD_LANG_CLASS(Character, "(C)V");
#undef LOAD_CLASS
#undef LOAD_LANG_CLASS
#define LOAD_METHOD(k, c, r, s) java_value_##c = env->GetMethodID(k, r "Value", s)
#define LOAD_NUMBER(c, r, s) LOAD_METHOD(java_lang_Number, c, r, s)
jclass java_lang_Number = env->FindClass("java/lang/Number");
LOAD_NUMBER(Integer, "int", "()I");
LOAD_NUMBER(Long, "long", "()J");
LOAD_NUMBER(Float, "float", "()F");
LOAD_NUMBER(Double, "double", "()D");
LOAD_NUMBER(Byte, "byte", "()B");
LOAD_NUMBER(Short, "short", "()S");
LOAD_METHOD(java_lang_Boolean, Boolean, "boolean", "()Z");
LOAD_METHOD(java_lang_Character, Character, "char", "()C");
env->PopLocalFrame(nullptr);
#undef LOAD_METHOD
#undef LOAD_NUMBER
}
#define LANG_BOX(c, t) jobject Types::To##c(JNIEnv *env, t v) { \
return env->NewObject(Types::java_lang_##c, Types::java_lang_##c##_init, v); \
}
#define LANG_UNBOX_V(k, c, t) t Types::From##c(JNIEnv *env, jobject j) { \
return env->Call##k##Method(j, Types::java_value_##c); \
}
#define LANG_UNBOX(c, t) LANG_UNBOX_V(c, c, t)
LANG_BOX(Integer, jint);
LANG_BOX(Long, jlong);
LANG_BOX(Float, jfloat);
LANG_BOX(Double, jdouble);
LANG_BOX(Byte, jbyte);
LANG_BOX(Short, jshort);
LANG_BOX(Boolean, jboolean);
LANG_BOX(Character, jchar);
jobject Types::ToObject(JNIEnv *env, jobject obj) {
return obj;
}
LANG_UNBOX_V(Int, Integer, jint);
LANG_UNBOX(Long, jlong);
LANG_UNBOX(Float, jfloat);
LANG_UNBOX(Double, jdouble);
LANG_UNBOX(Byte, jbyte);
LANG_UNBOX(Short, jshort);
LANG_UNBOX(Boolean, jboolean);
LANG_UNBOX_V(Char, Character, jchar);
jobject Types::FromObject(JNIEnv *env, jobject obj) {
return obj;
}
#undef LANG_BOX
#undef LANG_UNBOX_V
#undef LANG_UNBOX
jobject InvokeHookedMethodBridge(JNIEnv *env, jint slot, jobject receiver,
jobjectArray array) {
return env->CallStaticObjectMethod(bridgeClass, bridgeMethod, slot, receiver, array);
}
template<typename RetType>
static RetType
InvokeJavaBridge(JNIEnv *env, ArtHookParam *param, jobject this_object,
jobjectArray arguments) {
jobject ret = InvokeHookedMethodBridge(
env,
param->slot,
this_object,
arguments
);
jvalue val;
UnBoxValue(env, &val, ret, param->returnShorty);
return ForceCast<RetType>(val);
}
static void InvokeVoidJavaBridge(JNIEnv *env, ArtHookParam *param, jobject this_object,
jobjectArray arguments) {
InvokeHookedMethodBridge(
env,
param->slot,
this_object,
arguments
);
}
FFIType FFIGetJniParameter(char shorty) {
switch (shorty) {
case 'Z':
return FFIType::kFFITypeU1;
case 'B':
return FFIType::kFFITypeS1;
case 'C':
return FFIType::kFFITypeU2;
case 'S':
return FFIType::kFFITypeS2;
case 'I':
return FFIType::kFFITypeS4;
case 'J':
return FFIType::kFFITypeS8;
case 'F':
return FFIType::kFFITypeFloat;
case 'D':
return FFIType::kFFITypeDouble;
case 'L':
return FFIType::kFFITypePointer;
case 'V':
return FFIType::kFFITypeVoid;
default:
return FFIType::kFFITypePointer;
}
}
void FFIJniDispatcher(FFIClosure *closure, void *resp, void **args, void *userdata) {
#define FFI_ARG(name, type) \
builder.Append##name(*reinterpret_cast<type *>(args[i]));
ArtHookParam *param = reinterpret_cast<ArtHookParam *>(userdata);
const char *argument = param->paramsShorty;
unsigned int argument_len = (unsigned int) strlen(argument);
JNIEnv *env = *reinterpret_cast<JNIEnv **>(args[0]);
jobject this_object = nullptr;
if (!param->is_static_) {
this_object = *reinterpret_cast<jobject *>(args[1]);
}
// skip first two arguments
args += 2;
QuickArgumentBuilder builder(env, argument_len);
for (int i = 0; i < argument_len; ++i) {
switch (argument[i]) {
case 'Z':
FFI_ARG(Boolean, jboolean);
break;
case 'B':
FFI_ARG(Byte, jbyte);
break;
case 'C':
FFI_ARG(Character, jchar);
break;
case 'S':
FFI_ARG(Short, jshort);
break;
case 'I':
FFI_ARG(Integer, jint);
break;
case 'J':
FFI_ARG(Long, jlong);
break;
case 'F':
FFI_ARG(Float, jfloat);
break;
case 'D':
FFI_ARG(Double, jdouble);
break;
case 'L':
FFI_ARG(Object, jobject);
break;
default:
FFI_ARG(Object, jobject);
break;
}
}
#define INVOKE(type) \
*reinterpret_cast<type *>(resp) = InvokeJavaBridge<type>(env, param, this_object, \
builder.GetArray());
switch (param->returnShorty) {
case 'Z':
INVOKE(jboolean);
break;
case 'B':
INVOKE(jbyte);
break;
case 'C':
INVOKE(jchar);
break;
case 'S':
INVOKE(jshort);
break;
case 'I':
INVOKE(jint);
break;
case 'J':
INVOKE(jlong);
break;
case 'F':
INVOKE(jfloat);
break;
case 'D':
INVOKE(jdouble);
break;
case 'L':
INVOKE(jobject);
break;
case 'V':
InvokeVoidJavaBridge(env, param, this_object, builder.GetArray());
break;
default:
InvokeVoidJavaBridge(env, param, this_object, builder.GetArray());
break;
}
#undef INVOKE
#undef FFI_ARG
}
FFIClosure* BuildJniClosure(ArtHookParam *param) {
const char *argument = param->paramsShorty;
unsigned int java_argument_len = (unsigned int) strlen(argument);
unsigned int jni_argument_len = java_argument_len + 2;
FFICallInterface *cif = new FFICallInterface(
FFIGetJniParameter(param->returnShorty)
);
cif->Parameter(FFIType::kFFITypePointer); // JNIEnv *
cif->Parameter(FFIType::kFFITypePointer); // jclass or jobject
for (int i = 2; i < jni_argument_len; ++i) {
cif->Parameter(FFIGetJniParameter(argument[i - 2]));
}
cif->FinalizeCif();
return cif->CreateClosure(param, FFIJniDispatcher);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_swift_sandhook_xposedcompat_XposedCompat_init(JNIEnv *env, jclass type, jclass jbridgeClass, jobject jbridgeMethod, jclass jobjClass) {
java_lang_Object = static_cast<jclass>(env->NewGlobalRef(jobjClass));
bridgeClass = static_cast<jclass>(env->NewGlobalRef(jbridgeClass));
bridgeMethod = env->FromReflectedMethod(jbridgeMethod);
env->GetJavaVM(&javaVM);
Types::Load(env);
if (sizeof(size_t) == 8) {
GetOatQuickMethodHeaderBackup = reinterpret_cast<void *(*)(void *,
uintptr_t)>(SandInlineHookSym("/system/lib64/libart.so", "_ZN3art9ArtMethod23GetOatQuickMethodHeaderEm", (void*)NewGetOatQuickMethodHeader));
} else {
GetOatQuickMethodHeaderBackup = reinterpret_cast<void *(*)(void *,
uintptr_t)>(SandInlineHookSym("/system/lib/libart.so", "_ZN3art9ArtMethod23GetOatQuickMethodHeaderEj", (void*)NewGetOatQuickMethodHeader));
}
}
extern "C"
JNIEXPORT jlong JNICALL
Java_com_swift_sandhook_xposedcompat_XposedCompat_getJNITrampoline(JNIEnv *env, jclass type, jint slot, jboolean isStatic, jchar retShorty, jcharArray paramShorty) {
ArtHookParam* artHookParam = new ArtHookParam();
hookParams.push_back(artHookParam);
artHookParam->is_static_ = isStatic;
artHookParam->slot = slot;
artHookParam->returnShorty = static_cast<char>(retShorty);
jchar* jcs = env->GetCharArrayElements(paramShorty, NULL);
char* params = new char[env->GetArrayLength(paramShorty) + 1];
for (int i = 0; i < env->GetArrayLength(paramShorty); ++i) {
params[i] = static_cast<char>(jcs[i]);
}
params[env->GetArrayLength(paramShorty)] = '\0';
artHookParam->paramsShorty = params;
env->ReleaseCharArrayElements(paramShorty, jcs, 0);
FFIClosure* closure = BuildJniClosure(artHookParam);
if (closure != nullptr) {
return reinterpret_cast<jlong>(closure->GetCode());
} else {
return 0;
}
}
extern "C"
JNIEXPORT void JNICALL
Java_com_swift_sandhook_xposedcompat_XposedCompat_addHookMethod(JNIEnv *env, jclass type, jobject hookMethod) {
hookMethods.insert(env->FromReflectedMethod(hookMethod));
}
static JNINativeMethod jniXpCompat[] = {
{
"init",
"(Ljava/lang/Class;Ljava/lang/reflect/Method;Ljava/lang/Class;)V",
(void *) Java_com_swift_sandhook_xposedcompat_XposedCompat_init
},
{
"getJNITrampoline",
"(IZC[C)J",
(void *) Java_com_swift_sandhook_xposedcompat_XposedCompat_getJNITrampoline
},
{
"addHookMethod",
"(Ljava/lang/reflect/Member;)V",
(void *) Java_com_swift_sandhook_xposedcompat_XposedCompat_addHookMethod
}
};
static bool registerNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *jniMethods, int methods) {
jclass clazz = env->FindClass(className);
if (clazz == NULL) {
return false;
}
return env->RegisterNatives(clazz, jniMethods, methods) >= 0;
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
const char* CLASS_XP_COMPAT = "com/swift/sandhook/xposedcompat/XposedCompat";
int jniMethodSize = sizeof(JNINativeMethod);
JNIEnv *env = NULL;
if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
if (!registerNativeMethods(env, CLASS_XP_COMPAT, jniXpCompat, sizeof(jniXpCompat) / jniMethodSize)) {
return -1;
}
LOGW("JNI Loaded");
return JNI_VERSION_1_6;
}
extern "C"
JNIEXPORT bool JNI_Load_Ex(JNIEnv* env, jclass classXpComapt) {
int jniMethodSize = sizeof(JNINativeMethod);
if (env == nullptr || classXpComapt == nullptr)
return false;
if (env->RegisterNatives(classXpComapt, jniXpCompat, sizeof(jniXpCompat) / jniMethodSize) < 0) {
return false;
}
LOGW("JNI Loaded");
return true;
}
//
// Created by swift on 2019/6/3.
//
#ifndef SANDHOOK_ART_JNI_TRAMPOLINE_H
#define SANDHOOK_ART_JNI_TRAMPOLINE_H
#include <cstdint>
#include <jni.h>
#include <list>
#include <set>
#include "ffi_cxx.h"
jclass java_lang_Object;
JavaVM* javaVM;
jclass bridgeClass;
jmethodID bridgeMethod;
void* (*GetOatQuickMethodHeaderBackup)(void*,uintptr_t) = nullptr;
struct ArtHookParam {
jint slot;
bool is_static_;
char returnShorty;
char* paramsShorty;
};
std::list<ArtHookParam*> hookParams = std::list<ArtHookParam*>();
std::set<void*> hookMethods = std::set<void*>();
template<typename U, typename T>
U ForceCast(T *x) {
return (U) (uintptr_t) x;
}
template<typename U, typename T>
U ForceCast(T &x) {
return *(U *) &x;
}
struct Types {
#define LANG_ClASS(c) static jclass java_lang_##c; static jmethodID java_lang_##c##_init; static jmethodID java_value_##c;
LANG_ClASS(Integer);
LANG_ClASS(Long);
LANG_ClASS(Float);
LANG_ClASS(Double);
LANG_ClASS(Byte);
LANG_ClASS(Short);
LANG_ClASS(Boolean);
LANG_ClASS(Character);
#undef LANG_ClASS
static void Load(JNIEnv *env);
#define LANG_BOX_DEF(c, t) static jobject To##c(JNIEnv *env, t v);
#define LANG_UNBOX_V_DEF(k, c, t) static t From##c(JNIEnv *env, jobject j);
#define LANG_UNBOX_DEF(c, t) LANG_UNBOX_V_DEF(c, c, t)
LANG_BOX_DEF(Object, jobject);
LANG_BOX_DEF(Integer, jint);
LANG_BOX_DEF(Long, jlong);
LANG_BOX_DEF(Float, jfloat);
LANG_BOX_DEF(Double, jdouble);
LANG_BOX_DEF(Byte, jbyte);
LANG_BOX_DEF(Short, jshort);
LANG_BOX_DEF(Boolean, jboolean);
LANG_BOX_DEF(Character, jchar);
LANG_UNBOX_V_DEF(Int, Integer, jint);
LANG_UNBOX_DEF(Object, jobject);
LANG_UNBOX_DEF(Long, jlong);
LANG_UNBOX_DEF(Float, jfloat);
LANG_UNBOX_DEF(Double, jdouble);
LANG_UNBOX_DEF(Byte, jbyte);
LANG_UNBOX_DEF(Short, jshort);
LANG_UNBOX_DEF(Boolean, jboolean);
LANG_UNBOX_V_DEF(Char, Character, jchar);
#undef LANG_BOX_DEF
#undef LANG_UNBOX_V_DEF
#undef LANG_UNBOX_DEF
};
static void UnBoxValue(JNIEnv *env, jvalue *jv, jobject obj, char type) {
switch (type) {
case 'I':
jv->i = Types::FromInteger(env, obj);
break;
case 'Z':
jv->z = Types::FromBoolean(env, obj);
break;
case 'J':
jv->j = Types::FromLong(env, obj);
break;
case 'F':
jv->f = Types::FromFloat(env, obj);
break;
case 'B':
jv->b = Types::FromByte(env, obj);
break;
case 'D':
jv->d = Types::FromDouble(env, obj);
break;
case 'S':
jv->s = Types::FromShort(env, obj);
break;
case 'C':
jv->c = Types::FromCharacter(env, obj);
break;
default:
jv->l = obj;
}
}
class QuickArgumentBuilder {
public:
QuickArgumentBuilder(JNIEnv *env, size_t len) : env_(env), index_(0) {
array_ = env->NewObjectArray(
static_cast<jsize>(len),
java_lang_Object,
nullptr
);
}
#define APPEND_DEF(name, type) \
void Append##name(type value) { \
env_->SetObjectArrayElement(array_, index_++, \
Types::To##name(env_, value)); \
} \
APPEND_DEF(Integer, jint)
APPEND_DEF(Boolean, jboolean)
APPEND_DEF(Byte, jbyte)
APPEND_DEF(Character, jchar)
APPEND_DEF(Short, jshort)
APPEND_DEF(Float, jfloat)
APPEND_DEF(Double, jdouble)
APPEND_DEF(Long, jlong)
APPEND_DEF(Object, jobject)
#undef APPEND_DEF
jobjectArray GetArray() {
return array_;
}
private:
JNIEnv *env_;
jobjectArray array_;
int index_;
};
#endif //SANDHOOK_ART_JNI_TRAMPOLINE_H
#if defined(__aarch64__) || defined(__arm64__)
/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <fficonfig.h>
#include <ffi.h>
#include <ffi_common.h>
#include "internal.h"
/* Force FFI_TYPE_LONGDOUBLE to be different than FFI_TYPE_DOUBLE;
all further uses in this file will refer to the 128-bit type. */
#if FFI_TYPE_DOUBLE != FFI_TYPE_LONGDOUBLE
# if FFI_TYPE_LONGDOUBLE != 4
# error FFI_TYPE_LONGDOUBLE out of date
# endif
#else
# undef FFI_TYPE_LONGDOUBLE
# define FFI_TYPE_LONGDOUBLE 4
#endif
union _d
{
UINT64 d;
UINT32 s[2];
};
struct _v
{
union _d d[2] __attribute__((aligned(16)));
};
struct call_context
{
struct _v v[N_V_ARG_REG];
UINT64 x[N_X_ARG_REG];
};
#if FFI_EXEC_TRAMPOLINE_TABLE
#ifdef __MACH__
#include <mach/vm_param.h>
#endif
#else
#if defined (__clang__) && defined (__APPLE__)
extern void sys_icache_invalidate (void *start, size_t len);
#endif
static inline void
ffi_clear_cache (void *start, void *end)
{
#if defined (__clang__) && defined (__APPLE__)
sys_icache_invalidate (start, (char *)end - (char *)start);
#elif defined (__GNUC__)
__builtin___clear_cache (start, end);
#else
#error "Missing builtin to flush instruction cache"
#endif
}
#endif
/* A subroutine of is_vfp_type. Given a structure type, return the type code
of the first non-structure element. Recurse for structure elements.
Return -1 if the structure is in fact empty, i.e. no nested elements. */
static int
is_hfa0 (const ffi_type *ty)
{
ffi_type **elements = ty->elements;
int i, ret = -1;
if (elements != NULL)
for (i = 0; elements[i]; ++i)
{
ret = elements[i]->type;
if (ret == FFI_TYPE_STRUCT || ret == FFI_TYPE_COMPLEX)
{
ret = is_hfa0 (elements[i]);
if (ret < 0)
continue;
}
break;
}
return ret;
}
/* A subroutine of is_vfp_type. Given a structure type, return true if all
of the non-structure elements are the same as CANDIDATE. */
static int
is_hfa1 (const ffi_type *ty, int candidate)
{
ffi_type **elements = ty->elements;
int i;
if (elements != NULL)
for (i = 0; elements[i]; ++i)
{
int t = elements[i]->type;
if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
{
if (!is_hfa1 (elements[i], candidate))
return 0;
}
else if (t != candidate)
return 0;
}
return 1;
}
/* Determine if TY may be allocated to the FP registers. This is both an
fp scalar type as well as an homogenous floating point aggregate (HFA).
That is, a structure consisting of 1 to 4 members of all the same type,
where that type is an fp scalar.
Returns non-zero iff TY is an HFA. The result is the AARCH64_RET_*
constant for the type. */
static int
is_vfp_type (const ffi_type *ty)
{
ffi_type **elements;
int candidate, i;
size_t size, ele_count;
/* Quickest tests first. */
candidate = ty->type;
switch (candidate)
{
default:
return 0;
case FFI_TYPE_FLOAT:
case FFI_TYPE_DOUBLE:
case FFI_TYPE_LONGDOUBLE:
ele_count = 1;
goto done;
case FFI_TYPE_COMPLEX:
candidate = ty->elements[0]->type;
switch (candidate)
{
case FFI_TYPE_FLOAT:
case FFI_TYPE_DOUBLE:
case FFI_TYPE_LONGDOUBLE:
ele_count = 2;
goto done;
}
return 0;
case FFI_TYPE_STRUCT:
break;
}
/* No HFA types are smaller than 4 bytes, or larger than 64 bytes. */
size = ty->size;
if (size < 4 || size > 64)
return 0;
/* Find the type of the first non-structure member. */
elements = ty->elements;
candidate = elements[0]->type;
if (candidate == FFI_TYPE_STRUCT || candidate == FFI_TYPE_COMPLEX)
{
for (i = 0; ; ++i)
{
candidate = is_hfa0 (elements[i]);
if (candidate >= 0)
break;
}
}
/* If the first member is not a floating point type, it's not an HFA.
Also quickly re-check the size of the structure. */
switch (candidate)
{
case FFI_TYPE_FLOAT:
ele_count = size / sizeof(float);
if (size != ele_count * sizeof(float))
return 0;
break;
case FFI_TYPE_DOUBLE:
ele_count = size / sizeof(double);
if (size != ele_count * sizeof(double))
return 0;
break;
case FFI_TYPE_LONGDOUBLE:
ele_count = size / sizeof(long double);
if (size != ele_count * sizeof(long double))
return 0;
break;
default:
return 0;
}
if (ele_count > 4)
return 0;
/* Finally, make sure that all scalar elements are the same type. */
for (i = 0; elements[i]; ++i)
{
int t = elements[i]->type;
if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
{
if (!is_hfa1 (elements[i], candidate))
return 0;
}
else if (t != candidate)
return 0;
}
/* All tests succeeded. Encode the result. */
done:
return candidate * 4 + (4 - (int)ele_count);
}
/* Representation of the procedure call argument marshalling
state.
The terse state variable names match the names used in the AARCH64
PCS. */
struct arg_state
{
unsigned ngrn; /* Next general-purpose register number. */
unsigned nsrn; /* Next vector register number. */
size_t nsaa; /* Next stack offset. */
#if defined (__APPLE__)
unsigned allocating_variadic;
#endif
};
/* Initialize a procedure call argument marshalling state. */
static void
arg_init (struct arg_state *state)
{
state->ngrn = 0;
state->nsrn = 0;
state->nsaa = 0;
#if defined (__APPLE__)
state->allocating_variadic = 0;
#endif
}
/* Allocate an aligned slot on the stack and return a pointer to it. */
static void *
allocate_to_stack (struct arg_state *state, void *stack,
size_t alignment, size_t size)
{
size_t nsaa = state->nsaa;
/* Round up the NSAA to the larger of 8 or the natural
alignment of the argument's type. */
#if defined (__APPLE__)
if (state->allocating_variadic && alignment < 8)
alignment = 8;
#else
if (alignment < 8)
alignment = 8;
#endif
nsaa = FFI_ALIGN (nsaa, alignment);
state->nsaa = nsaa + size;
return (char *)stack + nsaa;
}
static ffi_arg
extend_integer_type (void *source, int type)
{
switch (type)
{
case FFI_TYPE_UINT8:
return *(UINT8 *) source;
case FFI_TYPE_SINT8:
return *(SINT8 *) source;
case FFI_TYPE_UINT16:
return *(UINT16 *) source;
case FFI_TYPE_SINT16:
return *(SINT16 *) source;
case FFI_TYPE_UINT32:
return *(UINT32 *) source;
case FFI_TYPE_INT:
case FFI_TYPE_SINT32:
return *(SINT32 *) source;
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
return *(UINT64 *) source;
break;
case FFI_TYPE_POINTER:
return *(uintptr_t *) source;
default:
abort();
}
}
static void
extend_hfa_type (void *dest, void *src, int h)
{
ssize_t f = h - AARCH64_RET_S4;
void *x0;
asm volatile (
"adr %0, 0f\n"
" add %0, %0, %1\n"
" br %0\n"
"0: ldp s16, s17, [%3]\n" /* S4 */
" ldp s18, s19, [%3, #8]\n"
" b 4f\n"
" ldp s16, s17, [%3]\n" /* S3 */
" ldr s18, [%3, #8]\n"
" b 3f\n"
" ldp s16, s17, [%3]\n" /* S2 */
" b 2f\n"
" nop\n"
" ldr s16, [%3]\n" /* S1 */
" b 1f\n"
" nop\n"
" ldp d16, d17, [%3]\n" /* D4 */
" ldp d18, d19, [%3, #16]\n"
" b 4f\n"
" ldp d16, d17, [%3]\n" /* D3 */
" ldr d18, [%3, #16]\n"
" b 3f\n"
" ldp d16, d17, [%3]\n" /* D2 */
" b 2f\n"
" nop\n"
" ldr d16, [%3]\n" /* D1 */
" b 1f\n"
" nop\n"
" ldp q16, q17, [%3]\n" /* Q4 */
" ldp q18, q19, [%3, #32]\n"
" b 4f\n"
" ldp q16, q17, [%3]\n" /* Q3 */
" ldr q18, [%3, #32]\n"
" b 3f\n"
" ldp q16, q17, [%3]\n" /* Q2 */
" b 2f\n"
" nop\n"
" ldr q16, [%3]\n" /* Q1 */
" b 1f\n"
"4: str q19, [%2, #48]\n"
"3: str q18, [%2, #32]\n"
"2: str q17, [%2, #16]\n"
"1: str q16, [%2]"
: "=&r"(x0)
: "r"(f * 12), "r"(dest), "r"(src)
: "memory", "v16", "v17", "v18", "v19");
}
static void *
compress_hfa_type (void *dest, void *reg, int h)
{
switch (h)
{
case AARCH64_RET_S1:
if (dest == reg)
{
#ifdef __AARCH64EB__
dest += 12;
#endif
}
else
*(float *)dest = *(float *)reg;
break;
case AARCH64_RET_S2:
asm ("ldp q16, q17, [%1]\n\t"
"st2 { v16.s, v17.s }[0], [%0]"
: : "r"(dest), "r"(reg) : "memory", "v16", "v17");
break;
case AARCH64_RET_S3:
asm ("ldp q16, q17, [%1]\n\t"
"ldr q18, [%1, #32]\n\t"
"st3 { v16.s, v17.s, v18.s }[0], [%0]"
: : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18");
break;
case AARCH64_RET_S4:
asm ("ldp q16, q17, [%1]\n\t"
"ldp q18, q19, [%1, #32]\n\t"
"st4 { v16.s, v17.s, v18.s, v19.s }[0], [%0]"
: : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18", "v19");
break;
case AARCH64_RET_D1:
if (dest == reg)
{
#ifdef __AARCH64EB__
dest += 8;
#endif
}
else
*(double *)dest = *(double *)reg;
break;
case AARCH64_RET_D2:
asm ("ldp q16, q17, [%1]\n\t"
"st2 { v16.d, v17.d }[0], [%0]"
: : "r"(dest), "r"(reg) : "memory", "v16", "v17");
break;
case AARCH64_RET_D3:
asm ("ldp q16, q17, [%1]\n\t"
"ldr q18, [%1, #32]\n\t"
"st3 { v16.d, v17.d, v18.d }[0], [%0]"
: : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18");
break;
case AARCH64_RET_D4:
asm ("ldp q16, q17, [%1]\n\t"
"ldp q18, q19, [%1, #32]\n\t"
"st4 { v16.d, v17.d, v18.d, v19.d }[0], [%0]"
: : "r"(dest), "r"(reg) : "memory", "v16", "v17", "v18", "v19");
break;
default:
if (dest != reg)
return memcpy (dest, reg, 16 * (4 - (h & 3)));
break;
}
return dest;
}
/* Either allocate an appropriate register for the argument type, or if
none are available, allocate a stack slot and return a pointer
to the allocated space. */
static void *
allocate_int_to_reg_or_stack (struct call_context *context,
struct arg_state *state,
void *stack, size_t size)
{
if (state->ngrn < N_X_ARG_REG)
return &context->x[state->ngrn++];
state->ngrn = N_X_ARG_REG;
return allocate_to_stack (state, stack, size, size);
}
ffi_status
ffi_prep_cif_machdep (ffi_cif *cif)
{
ffi_type *rtype = cif->rtype;
size_t bytes = cif->bytes;
int flags, i, n;
switch (rtype->type)
{
case FFI_TYPE_VOID:
flags = AARCH64_RET_VOID;
break;
case FFI_TYPE_UINT8:
flags = AARCH64_RET_UINT8;
break;
case FFI_TYPE_UINT16:
flags = AARCH64_RET_UINT16;
break;
case FFI_TYPE_UINT32:
flags = AARCH64_RET_UINT32;
break;
case FFI_TYPE_SINT8:
flags = AARCH64_RET_SINT8;
break;
case FFI_TYPE_SINT16:
flags = AARCH64_RET_SINT16;
break;
case FFI_TYPE_INT:
case FFI_TYPE_SINT32:
flags = AARCH64_RET_SINT32;
break;
case FFI_TYPE_SINT64:
case FFI_TYPE_UINT64:
flags = AARCH64_RET_INT64;
break;
case FFI_TYPE_POINTER:
flags = (sizeof(void *) == 4 ? AARCH64_RET_UINT32 : AARCH64_RET_INT64);
break;
case FFI_TYPE_FLOAT:
case FFI_TYPE_DOUBLE:
case FFI_TYPE_LONGDOUBLE:
case FFI_TYPE_STRUCT:
case FFI_TYPE_COMPLEX:
flags = is_vfp_type (rtype);
if (flags == 0)
{
size_t s = rtype->size;
if (s > 16)
{
flags = AARCH64_RET_VOID | AARCH64_RET_IN_MEM;
bytes += 8;
}
else if (s == 16)
flags = AARCH64_RET_INT128;
else if (s == 8)
flags = AARCH64_RET_INT64;
else
flags = AARCH64_RET_INT128 | AARCH64_RET_NEED_COPY;
}
break;
default:
abort();
}
for (i = 0, n = cif->nargs; i < n; i++)
if (is_vfp_type (cif->arg_types[i]))
{
flags |= AARCH64_FLAG_ARG_V;
break;
}
/* Round the stack up to a multiple of the stack alignment requirement. */
cif->bytes = (unsigned) FFI_ALIGN(bytes, 16);
cif->flags = flags;
#if defined (__APPLE__)
cif->aarch64_nfixedargs = 0;
#endif
return FFI_OK;
}
#if defined (__APPLE__)
/* Perform Apple-specific cif processing for variadic calls */
ffi_status ffi_prep_cif_machdep_var(ffi_cif *cif,
unsigned int nfixedargs,
unsigned int ntotalargs)
{
ffi_status status = ffi_prep_cif_machdep (cif);
cif->aarch64_nfixedargs = nfixedargs;
return status;
}
#endif /* __APPLE__ */
extern void ffi_call_SYSV (struct call_context *context, void *frame,
void (*fn)(void), void *rvalue, int flags,
void *closure) FFI_HIDDEN;
/* Call a function with the provided arguments and capture the return
value. */
static void
ffi_call_int (ffi_cif *cif, void (*fn)(void), void *orig_rvalue,
void **avalue, void *closure)
{
struct call_context *context;
void *stack, *frame, *rvalue;
struct arg_state state;
size_t stack_bytes, rtype_size, rsize;
int i, nargs, flags;
ffi_type *rtype;
flags = cif->flags;
rtype = cif->rtype;
rtype_size = rtype->size;
stack_bytes = cif->bytes;
/* If the target function returns a structure via hidden pointer,
then we cannot allow a null rvalue. Otherwise, mash a null
rvalue to void return type. */
rsize = 0;
if (flags & AARCH64_RET_IN_MEM)
{
if (orig_rvalue == NULL)
rsize = rtype_size;
}
else if (orig_rvalue == NULL)
flags &= AARCH64_FLAG_ARG_V;
else if (flags & AARCH64_RET_NEED_COPY)
rsize = 16;
/* Allocate consectutive stack for everything we'll need. */
context = alloca (sizeof(struct call_context) + stack_bytes + 32 + rsize);
stack = context + 1;
frame = stack + stack_bytes;
rvalue = (rsize ? frame + 32 : orig_rvalue);
arg_init (&state);
for (i = 0, nargs = cif->nargs; i < nargs; i++)
{
ffi_type *ty = cif->arg_types[i];
size_t s = ty->size;
void *a = avalue[i];
int h, t;
t = ty->type;
switch (t)
{
case FFI_TYPE_VOID:
FFI_ASSERT (0);
break;
/* If the argument is a basic type the argument is allocated to an
appropriate register, or if none are available, to the stack. */
case FFI_TYPE_INT:
case FFI_TYPE_UINT8:
case FFI_TYPE_SINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_SINT16:
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT32:
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
case FFI_TYPE_POINTER:
do_pointer:
{
ffi_arg ext = extend_integer_type (a, t);
if (state.ngrn < N_X_ARG_REG)
context->x[state.ngrn++] = ext;
else
{
void *d = allocate_to_stack (&state, stack, ty->alignment, s);
state.ngrn = N_X_ARG_REG;
/* Note that the default abi extends each argument
to a full 64-bit slot, while the iOS abi allocates
only enough space. */
#ifdef __APPLE__
memcpy(d, a, s);
#else
*(ffi_arg *)d = ext;
#endif
}
}
break;
case FFI_TYPE_FLOAT:
case FFI_TYPE_DOUBLE:
case FFI_TYPE_LONGDOUBLE:
case FFI_TYPE_STRUCT:
case FFI_TYPE_COMPLEX:
{
void *dest;
h = is_vfp_type (ty);
if (h)
{
int elems = 4 - (h & 3);
if (state.nsrn + elems <= N_V_ARG_REG)
{
dest = &context->v[state.nsrn];
state.nsrn += elems;
extend_hfa_type (dest, a, h);
break;
}
state.nsrn = N_V_ARG_REG;
dest = allocate_to_stack (&state, stack, ty->alignment, s);
}
else if (s > 16)
{
/* If the argument is a composite type that is larger than 16
bytes, then the argument has been copied to memory, and
the argument is replaced by a pointer to the copy. */
a = &avalue[i];
t = FFI_TYPE_POINTER;
s = sizeof (void *);
goto do_pointer;
}
else
{
size_t n = (s + 7) / 8;
if (state.ngrn + n <= N_X_ARG_REG)
{
/* If the argument is a composite type and the size in
double-words is not more than the number of available
X registers, then the argument is copied into
consecutive X registers. */
dest = &context->x[state.ngrn];
state.ngrn += n;
}
else
{
/* Otherwise, there are insufficient X registers. Further
X register allocations are prevented, the NSAA is
adjusted and the argument is copied to memory at the
adjusted NSAA. */
state.ngrn = N_X_ARG_REG;
dest = allocate_to_stack (&state, stack, ty->alignment, s);
}
}
memcpy (dest, a, s);
}
break;
default:
abort();
}
#if defined (__APPLE__)
if (i + 1 == cif->aarch64_nfixedargs)
{
state.ngrn = N_X_ARG_REG;
state.nsrn = N_V_ARG_REG;
state.allocating_variadic = 1;
}
#endif
}
ffi_call_SYSV (context, frame, fn, rvalue, flags, closure);
if (flags & AARCH64_RET_NEED_COPY)
memcpy (orig_rvalue, rvalue, rtype_size);
}
void
ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue)
{
ffi_call_int (cif, fn, rvalue, avalue, NULL);
}
#ifdef FFI_GO_CLOSURES
void
ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue,
void **avalue, void *closure)
{
ffi_call_int (cif, fn, rvalue, avalue, closure);
}
#endif /* FFI_GO_CLOSURES */
/* Build a trampoline. */
extern void ffi_closure_SYSV (void) FFI_HIDDEN;
extern void ffi_closure_SYSV_V (void) FFI_HIDDEN;
ffi_status
ffi_prep_closure_loc (ffi_closure *closure,
ffi_cif* cif,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data,
void *codeloc)
{
if (cif->abi != FFI_SYSV)
return FFI_BAD_ABI;
void (*start)(void);
if (cif->flags & AARCH64_FLAG_ARG_V)
start = ffi_closure_SYSV_V;
else
start = ffi_closure_SYSV;
#if FFI_EXEC_TRAMPOLINE_TABLE
#ifdef __MACH__
void **config = (void **)((uint8_t *)codeloc - PAGE_MAX_SIZE);
config[0] = closure;
config[1] = start;
#endif
#else
static const unsigned char trampoline[16] = {
0x90, 0x00, 0x00, 0x58, /* ldr x16, tramp+16 */
0xf1, 0xff, 0xff, 0x10, /* adr x17, tramp+0 */
0x00, 0x02, 0x1f, 0xd6 /* br x16 */
};
char *tramp = closure->tramp;
memcpy (tramp, trampoline, sizeof(trampoline));
*(UINT64 *)(tramp + 16) = (uintptr_t)start;
ffi_clear_cache(tramp, tramp + FFI_TRAMPOLINE_SIZE);
#endif
closure->cif = cif;
closure->fun = fun;
closure->user_data = user_data;
return FFI_OK;
}
#ifdef FFI_GO_CLOSURES
extern void ffi_go_closure_SYSV (void) FFI_HIDDEN;
extern void ffi_go_closure_SYSV_V (void) FFI_HIDDEN;
ffi_status
ffi_prep_go_closure (ffi_go_closure *closure, ffi_cif* cif,
void (*fun)(ffi_cif*,void*,void**,void*))
{
void (*start)(void);
if (cif->abi != FFI_SYSV)
return FFI_BAD_ABI;
if (cif->flags & AARCH64_FLAG_ARG_V)
start = ffi_go_closure_SYSV_V;
else
start = ffi_go_closure_SYSV;
closure->tramp = start;
closure->cif = cif;
closure->fun = fun;
return FFI_OK;
}
#endif /* FFI_GO_CLOSURES */
/* Primary handler to setup and invoke a function within a closure.
A closure when invoked enters via the assembler wrapper
ffi_closure_SYSV(). The wrapper allocates a call context on the
stack, saves the interesting registers (from the perspective of
the calling convention) into the context then passes control to
ffi_closure_SYSV_inner() passing the saved context and a pointer to
the stack at the point ffi_closure_SYSV() was invoked.
On the return path the assembler wrapper will reload call context
registers.
ffi_closure_SYSV_inner() marshalls the call context into ffi value
descriptors, invokes the wrapped function, then marshalls the return
value back into the call context. */
int FFI_HIDDEN
ffi_closure_SYSV_inner (ffi_cif *cif,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data,
struct call_context *context,
void *stack, void *rvalue, void *struct_rvalue)
{
void **avalue = (void**) alloca (cif->nargs * sizeof (void*));
int i, h, nargs, flags;
struct arg_state state;
arg_init (&state);
for (i = 0, nargs = cif->nargs; i < nargs; i++)
{
ffi_type *ty = cif->arg_types[i];
int t = ty->type;
size_t n, s = ty->size;
switch (t)
{
case FFI_TYPE_VOID:
FFI_ASSERT (0);
break;
case FFI_TYPE_INT:
case FFI_TYPE_UINT8:
case FFI_TYPE_SINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_SINT16:
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT32:
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
case FFI_TYPE_POINTER:
avalue[i] = allocate_int_to_reg_or_stack (context, &state, stack, s);
break;
case FFI_TYPE_FLOAT:
case FFI_TYPE_DOUBLE:
case FFI_TYPE_LONGDOUBLE:
case FFI_TYPE_STRUCT:
case FFI_TYPE_COMPLEX:
h = is_vfp_type (ty);
if (h)
{
n = 4 - (h & 3);
if (state.nsrn + n <= N_V_ARG_REG)
{
void *reg = &context->v[state.nsrn];
state.nsrn += n;
/* Eeek! We need a pointer to the structure, however the
homogeneous float elements are being passed in individual
registers, therefore for float and double the structure
is not represented as a contiguous sequence of bytes in
our saved register context. We don't need the original
contents of the register storage, so we reformat the
structure into the same memory. */
avalue[i] = compress_hfa_type (reg, reg, h);
}
else
{
state.nsrn = N_V_ARG_REG;
avalue[i] = allocate_to_stack (&state, stack,
ty->alignment, s);
}
}
else if (s > 16)
{
/* Replace Composite type of size greater than 16 with a
pointer. */
avalue[i] = *(void **)
allocate_int_to_reg_or_stack (context, &state, stack,
sizeof (void *));
}
else
{
n = (s + 7) / 8;
if (state.ngrn + n <= N_X_ARG_REG)
{
avalue[i] = &context->x[state.ngrn];
state.ngrn += n;
}
else
{
state.ngrn = N_X_ARG_REG;
avalue[i] = allocate_to_stack (&state, stack,
ty->alignment, s);
}
}
break;
default:
abort();
}
#if defined (__APPLE__)
if (i + 1 == cif->aarch64_nfixedargs)
{
state.ngrn = N_X_ARG_REG;
state.nsrn = N_V_ARG_REG;
state.allocating_variadic = 1;
}
#endif
}
flags = cif->flags;
if (flags & AARCH64_RET_IN_MEM)
rvalue = struct_rvalue;
fun (cif, rvalue, avalue, user_data);
return flags;
}
#endif
\ No newline at end of file
#if defined(__aarch64__) || defined(__arm64__)
/*
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#define AARCH64_RET_VOID 0
#define AARCH64_RET_INT64 1
#define AARCH64_RET_INT128 2
#define AARCH64_RET_UNUSED3 3
#define AARCH64_RET_UNUSED4 4
#define AARCH64_RET_UNUSED5 5
#define AARCH64_RET_UNUSED6 6
#define AARCH64_RET_UNUSED7 7
/* Note that FFI_TYPE_FLOAT == 2, _DOUBLE == 3, _LONGDOUBLE == 4,
so _S4 through _Q1 are layed out as (TYPE * 4) + (4 - COUNT). */
#define AARCH64_RET_S4 8
#define AARCH64_RET_S3 9
#define AARCH64_RET_S2 10
#define AARCH64_RET_S1 11
#define AARCH64_RET_D4 12
#define AARCH64_RET_D3 13
#define AARCH64_RET_D2 14
#define AARCH64_RET_D1 15
#define AARCH64_RET_Q4 16
#define AARCH64_RET_Q3 17
#define AARCH64_RET_Q2 18
#define AARCH64_RET_Q1 19
/* Note that each of the sub-64-bit integers gets two entries. */
#define AARCH64_RET_UINT8 20
#define AARCH64_RET_UINT16 22
#define AARCH64_RET_UINT32 24
#define AARCH64_RET_SINT8 26
#define AARCH64_RET_SINT16 28
#define AARCH64_RET_SINT32 30
#define AARCH64_RET_MASK 31
#define AARCH64_RET_IN_MEM (1 << 5)
#define AARCH64_RET_NEED_COPY (1 << 6)
#define AARCH64_FLAG_ARG_V_BIT 7
#define AARCH64_FLAG_ARG_V (1 << AARCH64_FLAG_ARG_V_BIT)
#define N_X_ARG_REG 8
#define N_V_ARG_REG 8
#define CALL_CONTEXT_SIZE (N_V_ARG_REG * 16 + N_X_ARG_REG * 8)
#endif
\ No newline at end of file
#if defined(__aarch64__)
/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#define LIBFFI_ASM
#include <fficonfig.h>
#include <ffi.h>
#include <ffi_cfi.h>
#include "internal.h"
#ifdef HAVE_MACHINE_ASM_H
#include <machine/asm.h>
#else
#ifdef __USER_LABEL_PREFIX__
#define CONCAT1(a, b) CONCAT2(a, b)
#define CONCAT2(a, b) a ## b
/* Use the right prefix for global labels. */
#define CNAME(x) CONCAT1 (__USER_LABEL_PREFIX__, x)
#else
#define CNAME(x) x
#endif
#endif
#ifdef __AARCH64EB__
# define BE(X) X
#else
# define BE(X) 0
#endif
#ifdef __ILP32__
#define PTR_REG(n) w##n
#else
#define PTR_REG(n) x##n
#endif
#ifdef __ILP32__
#define PTR_SIZE 4
#else
#define PTR_SIZE 8
#endif
.text
.align 4
/* ffi_call_SYSV
extern void ffi_call_SYSV (void *stack, void *frame,
void (*fn)(void), void *rvalue,
int flags, void *closure);
Therefore on entry we have:
x0 stack
x1 frame
x2 fn
x3 rvalue
x4 flags
x5 closure
*/
cfi_startproc
CNAME(ffi_call_SYSV):
/* Use a stack frame allocated by our caller. */
cfi_def_cfa(x1, 32);
stp x29, x30, [x1]
mov x29, x1
mov sp, x0
cfi_def_cfa_register(x29)
cfi_rel_offset (x29, 0)
cfi_rel_offset (x30, 8)
mov x9, x2 /* save fn */
mov x8, x3 /* install structure return */
#ifdef FFI_GO_CLOSURES
mov x18, x5 /* install static chain */
#endif
stp x3, x4, [x29, #16] /* save rvalue and flags */
/* Load the vector argument passing registers, if necessary. */
tbz w4, #AARCH64_FLAG_ARG_V_BIT, 1f
ldp q0, q1, [sp, #0]
ldp q2, q3, [sp, #32]
ldp q4, q5, [sp, #64]
ldp q6, q7, [sp, #96]
1:
/* Load the core argument passing registers, including
the structure return pointer. */
ldp x0, x1, [sp, #16*N_V_ARG_REG + 0]
ldp x2, x3, [sp, #16*N_V_ARG_REG + 16]
ldp x4, x5, [sp, #16*N_V_ARG_REG + 32]
ldp x6, x7, [sp, #16*N_V_ARG_REG + 48]
/* Deallocate the context, leaving the stacked arguments. */
add sp, sp, #CALL_CONTEXT_SIZE
blr x9 /* call fn */
ldp x3, x4, [x29, #16] /* reload rvalue and flags */
/* Partially deconstruct the stack frame. */
mov sp, x29
cfi_def_cfa_register (sp)
ldp x29, x30, [x29]
/* Save the return value as directed. */
adr x5, 0f
and w4, w4, #AARCH64_RET_MASK
add x5, x5, x4, lsl #3
br x5
/* Note that each table entry is 2 insns, and thus 8 bytes.
For integer data, note that we're storing into ffi_arg
and therefore we want to extend to 64 bits; these types
have two consecutive entries allocated for them. */
.align 4
0: ret /* VOID */
nop
1: str x0, [x3] /* INT64 */
ret
2: stp x0, x1, [x3] /* INT128 */
ret
3: brk #1000 /* UNUSED */
ret
4: brk #1000 /* UNUSED */
ret
5: brk #1000 /* UNUSED */
ret
6: brk #1000 /* UNUSED */
ret
7: brk #1000 /* UNUSED */
ret
8: st4 { v0.s, v1.s, v2.s, v3.s }[0], [x3] /* S4 */
ret
9: st3 { v0.s, v1.s, v2.s }[0], [x3] /* S3 */
ret
10: stp s0, s1, [x3] /* S2 */
ret
11: str s0, [x3] /* S1 */
ret
12: st4 { v0.d, v1.d, v2.d, v3.d }[0], [x3] /* D4 */
ret
13: st3 { v0.d, v1.d, v2.d }[0], [x3] /* D3 */
ret
14: stp d0, d1, [x3] /* D2 */
ret
15: str d0, [x3] /* D1 */
ret
16: str q3, [x3, #48] /* Q4 */
nop
17: str q2, [x3, #32] /* Q3 */
nop
18: stp q0, q1, [x3] /* Q2 */
ret
19: str q0, [x3] /* Q1 */
ret
20: uxtb w0, w0 /* UINT8 */
str x0, [x3]
21: ret /* reserved */
nop
22: uxth w0, w0 /* UINT16 */
str x0, [x3]
23: ret /* reserved */
nop
24: mov w0, w0 /* UINT32 */
str x0, [x3]
25: ret /* reserved */
nop
26: sxtb x0, w0 /* SINT8 */
str x0, [x3]
27: ret /* reserved */
nop
28: sxth x0, w0 /* SINT16 */
str x0, [x3]
29: ret /* reserved */
nop
30: sxtw x0, w0 /* SINT32 */
str x0, [x3]
31: ret /* reserved */
nop
cfi_endproc
.globl CNAME(ffi_call_SYSV)
#ifdef __ELF__
.type CNAME(ffi_call_SYSV), #function
.hidden CNAME(ffi_call_SYSV)
.size CNAME(ffi_call_SYSV), .-CNAME(ffi_call_SYSV)
#endif
/* ffi_closure_SYSV
Closure invocation glue. This is the low level code invoked directly by
the closure trampoline to setup and call a closure.
On entry x17 points to a struct ffi_closure, x16 has been clobbered
all other registers are preserved.
We allocate a call context and save the argument passing registers,
then invoked the generic C ffi_closure_SYSV_inner() function to do all
the real work, on return we load the result passing registers back from
the call context.
*/
#define ffi_closure_SYSV_FS (8*2 + CALL_CONTEXT_SIZE + 64)
.align 4
CNAME(ffi_closure_SYSV_V):
cfi_startproc
stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
cfi_rel_offset (x29, 0)
cfi_rel_offset (x30, 8)
/* Save the argument passing vector registers. */
stp q0, q1, [sp, #16 + 0]
stp q2, q3, [sp, #16 + 32]
stp q4, q5, [sp, #16 + 64]
stp q6, q7, [sp, #16 + 96]
b 0f
cfi_endproc
.globl CNAME(ffi_closure_SYSV_V)
#ifdef __ELF__
.type CNAME(ffi_closure_SYSV_V), #function
.hidden CNAME(ffi_closure_SYSV_V)
.size CNAME(ffi_closure_SYSV_V), . - CNAME(ffi_closure_SYSV_V)
#endif
.align 4
cfi_startproc
CNAME(ffi_closure_SYSV):
stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
cfi_rel_offset (x29, 0)
cfi_rel_offset (x30, 8)
0:
mov x29, sp
/* Save the argument passing core registers. */
stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0]
stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16]
stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32]
stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48]
/* Load ffi_closure_inner arguments. */
ldp PTR_REG(0), PTR_REG(1), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET] /* load cif, fn */
ldr PTR_REG(2), [x17, #FFI_TRAMPOLINE_CLOSURE_OFFSET+PTR_SIZE*2] /* load user_data */
.Ldo_closure:
add x3, sp, #16 /* load context */
add x4, sp, #ffi_closure_SYSV_FS /* load stack */
add x5, sp, #16+CALL_CONTEXT_SIZE /* load rvalue */
mov x6, x8 /* load struct_rval */
bl CNAME(ffi_closure_SYSV_inner)
/* Load the return value as directed. */
adr x1, 0f
and w0, w0, #AARCH64_RET_MASK
add x1, x1, x0, lsl #3
add x3, sp, #16+CALL_CONTEXT_SIZE
br x1
/* Note that each table entry is 2 insns, and thus 8 bytes. */
.align 4
0: b 99f /* VOID */
nop
1: ldr x0, [x3] /* INT64 */
b 99f
2: ldp x0, x1, [x3] /* INT128 */
b 99f
3: brk #1000 /* UNUSED */
nop
4: brk #1000 /* UNUSED */
nop
5: brk #1000 /* UNUSED */
nop
6: brk #1000 /* UNUSED */
nop
7: brk #1000 /* UNUSED */
nop
8: ldr s3, [x3, #12] /* S4 */
nop
9: ldr s2, [x3, #8] /* S3 */
nop
10: ldp s0, s1, [x3] /* S2 */
b 99f
11: ldr s0, [x3] /* S1 */
b 99f
12: ldr d3, [x3, #24] /* D4 */
nop
13: ldr d2, [x3, #16] /* D3 */
nop
14: ldp d0, d1, [x3] /* D2 */
b 99f
15: ldr d0, [x3] /* D1 */
b 99f
16: ldr q3, [x3, #48] /* Q4 */
nop
17: ldr q2, [x3, #32] /* Q3 */
nop
18: ldp q0, q1, [x3] /* Q2 */
b 99f
19: ldr q0, [x3] /* Q1 */
b 99f
20: ldrb w0, [x3, #BE(7)] /* UINT8 */
b 99f
21: brk #1000 /* reserved */
nop
22: ldrh w0, [x3, #BE(6)] /* UINT16 */
b 99f
23: brk #1000 /* reserved */
nop
24: ldr w0, [x3, #BE(4)] /* UINT32 */
b 99f
25: brk #1000 /* reserved */
nop
26: ldrsb x0, [x3, #BE(7)] /* SINT8 */
b 99f
27: brk #1000 /* reserved */
nop
28: ldrsh x0, [x3, #BE(6)] /* SINT16 */
b 99f
29: brk #1000 /* reserved */
nop
30: ldrsw x0, [x3, #BE(4)] /* SINT32 */
nop
31: /* reserved */
99: ldp x29, x30, [sp], #ffi_closure_SYSV_FS
cfi_adjust_cfa_offset (-ffi_closure_SYSV_FS)
cfi_restore (x29)
cfi_restore (x30)
ret
cfi_endproc
.globl CNAME(ffi_closure_SYSV)
#ifdef __ELF__
.type CNAME(ffi_closure_SYSV), #function
.hidden CNAME(ffi_closure_SYSV)
.size CNAME(ffi_closure_SYSV), . - CNAME(ffi_closure_SYSV)
#endif
#if FFI_EXEC_TRAMPOLINE_TABLE
#ifdef __MACH__
#include <mach/machine/vm_param.h>
.align PAGE_MAX_SHIFT
CNAME(ffi_closure_trampoline_table_page):
.rept PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE
adr x16, -PAGE_MAX_SIZE
ldp x17, x16, [x16]
br x16
nop /* each entry in the trampoline config page is 2*sizeof(void*) so the trampoline itself cannot be smaller that 16 bytes */
.endr
.globl CNAME(ffi_closure_trampoline_table_page)
#ifdef __ELF__
.type CNAME(ffi_closure_trampoline_table_page), #function
.hidden CNAME(ffi_closure_trampoline_table_page)
.size CNAME(ffi_closure_trampoline_table_page), . - CNAME(ffi_closure_trampoline_table_page)
#endif
#endif
#endif /* FFI_EXEC_TRAMPOLINE_TABLE */
#ifdef FFI_GO_CLOSURES
.align 4
CNAME(ffi_go_closure_SYSV_V):
cfi_startproc
stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
cfi_rel_offset (x29, 0)
cfi_rel_offset (x30, 8)
/* Save the argument passing vector registers. */
stp q0, q1, [sp, #16 + 0]
stp q2, q3, [sp, #16 + 32]
stp q4, q5, [sp, #16 + 64]
stp q6, q7, [sp, #16 + 96]
b 0f
cfi_endproc
.globl CNAME(ffi_go_closure_SYSV_V)
#ifdef __ELF__
.type CNAME(ffi_go_closure_SYSV_V), #function
.hidden CNAME(ffi_go_closure_SYSV_V)
.size CNAME(ffi_go_closure_SYSV_V), . - CNAME(ffi_go_closure_SYSV_V)
#endif
.align 4
cfi_startproc
CNAME(ffi_go_closure_SYSV):
stp x29, x30, [sp, #-ffi_closure_SYSV_FS]!
cfi_adjust_cfa_offset (ffi_closure_SYSV_FS)
cfi_rel_offset (x29, 0)
cfi_rel_offset (x30, 8)
0:
mov x29, sp
/* Save the argument passing core registers. */
stp x0, x1, [sp, #16 + 16*N_V_ARG_REG + 0]
stp x2, x3, [sp, #16 + 16*N_V_ARG_REG + 16]
stp x4, x5, [sp, #16 + 16*N_V_ARG_REG + 32]
stp x6, x7, [sp, #16 + 16*N_V_ARG_REG + 48]
/* Load ffi_closure_inner arguments. */
ldp PTR_REG(0), PTR_REG(1), [x18, #PTR_SIZE]/* load cif, fn */
mov x2, x18 /* load user_data */
b .Ldo_closure
cfi_endproc
.globl CNAME(ffi_go_closure_SYSV)
#ifdef __ELF__
.type CNAME(ffi_go_closure_SYSV), #function
.hidden CNAME(ffi_go_closure_SYSV)
.size CNAME(ffi_go_closure_SYSV), . - CNAME(ffi_go_closure_SYSV)
#endif
#endif /* FFI_GO_CLOSURES */
#if defined __ELF__ && defined __linux__
.section .note.GNU-stack,"",%progbits
#endif
#endif
#ifdef __arm__
/* -----------------------------------------------------------------------
ffi.c - Copyright (c) 2011 Timothy Wall
Copyright (c) 2011 Plausible Labs Cooperative, Inc.
Copyright (c) 2011 Anthony Green
Copyright (c) 2011 Free Software Foundation
Copyright (c) 1998, 2008, 2011 Red Hat, Inc.
ARM Foreign Function Interface
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
#include <fficonfig.h>
#include <ffi.h>
#include <ffi_common.h>
#include <stdint.h>
#include <stdlib.h>
#include "internal.h"
#if FFI_EXEC_TRAMPOLINE_TABLE
#ifdef __MACH__
#include <mach/machine/vm_param.h>
#endif
#else
extern unsigned int ffi_arm_trampoline[2] FFI_HIDDEN;
#endif
/* Forward declares. */
static int vfp_type_p (const ffi_type *);
static void layout_vfp_args (ffi_cif *);
static void *
ffi_align (ffi_type *ty, void *p)
{
/* Align if necessary */
size_t alignment;
#ifdef _WIN32_WCE
alignment = 4;
#else
alignment = ty->alignment;
if (alignment < 4)
alignment = 4;
#endif
return (void *) FFI_ALIGN (p, alignment);
}
static size_t
ffi_put_arg (ffi_type *ty, void *src, void *dst)
{
size_t z = ty->size;
switch (ty->type)
{
case FFI_TYPE_SINT8:
*(UINT32 *)dst = *(SINT8 *)src;
break;
case FFI_TYPE_UINT8:
*(UINT32 *)dst = *(UINT8 *)src;
break;
case FFI_TYPE_SINT16:
*(UINT32 *)dst = *(SINT16 *)src;
break;
case FFI_TYPE_UINT16:
*(UINT32 *)dst = *(UINT16 *)src;
break;
case FFI_TYPE_INT:
case FFI_TYPE_SINT32:
case FFI_TYPE_UINT32:
case FFI_TYPE_POINTER:
case FFI_TYPE_FLOAT:
*(UINT32 *)dst = *(UINT32 *)src;
break;
case FFI_TYPE_SINT64:
case FFI_TYPE_UINT64:
case FFI_TYPE_DOUBLE:
*(UINT64 *)dst = *(UINT64 *)src;
break;
case FFI_TYPE_STRUCT:
case FFI_TYPE_COMPLEX:
memcpy (dst, src, z);
break;
default:
abort();
}
return FFI_ALIGN (z, 4);
}
/* ffi_prep_args is called once stack space has been allocated
for the function's arguments.
The vfp_space parameter is the load area for VFP regs, the return
value is cif->vfp_used (word bitset of VFP regs used for passing
arguments). These are only used for the VFP hard-float ABI.
*/
static void
ffi_prep_args_SYSV (ffi_cif *cif, int flags, void *rvalue,
void **avalue, char *argp)
{
ffi_type **arg_types = cif->arg_types;
int i, n;
if (flags == ARM_TYPE_STRUCT)
{
*(void **) argp = rvalue;
argp += 4;
}
for (i = 0, n = cif->nargs; i < n; i++)
{
ffi_type *ty = arg_types[i];
argp = ffi_align (ty, argp);
argp += ffi_put_arg (ty, avalue[i], argp);
}
}
static void
ffi_prep_args_VFP (ffi_cif *cif, int flags, void *rvalue,
void **avalue, char *stack, char *vfp_space)
{
ffi_type **arg_types = cif->arg_types;
int i, n, vi = 0;
char *argp, *regp, *eo_regp;
char stack_used = 0;
char done_with_regs = 0;
/* The first 4 words on the stack are used for values
passed in core registers. */
regp = stack;
eo_regp = argp = regp + 16;
/* If the function returns an FFI_TYPE_STRUCT in memory,
that address is passed in r0 to the function. */
if (flags == ARM_TYPE_STRUCT)
{
*(void **) regp = rvalue;
regp += 4;
}
for (i = 0, n = cif->nargs; i < n; i++)
{
ffi_type *ty = arg_types[i];
void *a = avalue[i];
int is_vfp_type = vfp_type_p (ty);
/* Allocated in VFP registers. */
if (vi < cif->vfp_nargs && is_vfp_type)
{
char *vfp_slot = vfp_space + cif->vfp_args[vi++] * 4;
ffi_put_arg (ty, a, vfp_slot);
continue;
}
/* Try allocating in core registers. */
else if (!done_with_regs && !is_vfp_type)
{
char *tregp = ffi_align (ty, regp);
size_t size = ty->size;
size = (size < 4) ? 4 : size; // pad
/* Check if there is space left in the aligned register
area to place the argument. */
if (tregp + size <= eo_regp)
{
regp = tregp + ffi_put_arg (ty, a, tregp);
done_with_regs = (regp == argp);
// ensure we did not write into the stack area
FFI_ASSERT (regp <= argp);
continue;
}
/* In case there are no arguments in the stack area yet,
the argument is passed in the remaining core registers
and on the stack. */
else if (!stack_used)
{
stack_used = 1;
done_with_regs = 1;
argp = tregp + ffi_put_arg (ty, a, tregp);
FFI_ASSERT (eo_regp < argp);
continue;
}
}
/* Base case, arguments are passed on the stack */
stack_used = 1;
argp = ffi_align (ty, argp);
argp += ffi_put_arg (ty, a, argp);
}
}
/* Perform machine dependent cif processing */
ffi_status
ffi_prep_cif_machdep (ffi_cif *cif)
{
int flags = 0, cabi = cif->abi;
size_t bytes = cif->bytes;
/* Map out the register placements of VFP register args. The VFP
hard-float calling conventions are slightly more sophisticated
than the base calling conventions, so we do it here instead of
in ffi_prep_args(). */
if (cabi == FFI_VFP)
layout_vfp_args (cif);
/* Set the return type flag */
switch (cif->rtype->type)
{
case FFI_TYPE_VOID:
flags = ARM_TYPE_VOID;
break;
case FFI_TYPE_INT:
case FFI_TYPE_UINT8:
case FFI_TYPE_SINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_SINT16:
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT32:
case FFI_TYPE_POINTER:
flags = ARM_TYPE_INT;
break;
case FFI_TYPE_SINT64:
case FFI_TYPE_UINT64:
flags = ARM_TYPE_INT64;
break;
case FFI_TYPE_FLOAT:
flags = (cabi == FFI_VFP ? ARM_TYPE_VFP_S : ARM_TYPE_INT);
break;
case FFI_TYPE_DOUBLE:
flags = (cabi == FFI_VFP ? ARM_TYPE_VFP_D : ARM_TYPE_INT64);
break;
case FFI_TYPE_STRUCT:
case FFI_TYPE_COMPLEX:
if (cabi == FFI_VFP)
{
int h = vfp_type_p (cif->rtype);
flags = ARM_TYPE_VFP_N;
if (h == 0x100 + FFI_TYPE_FLOAT)
flags = ARM_TYPE_VFP_S;
if (h == 0x100 + FFI_TYPE_DOUBLE)
flags = ARM_TYPE_VFP_D;
if (h != 0)
break;
}
/* A Composite Type not larger than 4 bytes is returned in r0.
A Composite Type larger than 4 bytes, or whose size cannot
be determined statically ... is stored in memory at an
address passed [in r0]. */
if (cif->rtype->size <= 4)
flags = ARM_TYPE_INT;
else
{
flags = ARM_TYPE_STRUCT;
bytes += 4;
}
break;
default:
abort();
}
/* Round the stack up to a multiple of 8 bytes. This isn't needed
everywhere, but it is on some platforms, and it doesn't harm anything
when it isn't needed. */
bytes = FFI_ALIGN (bytes, 8);
/* Minimum stack space is the 4 register arguments that we pop. */
if (bytes < 4*4)
bytes = 4*4;
cif->bytes = bytes;
cif->flags = flags;
return FFI_OK;
}
/* Perform machine dependent cif processing for variadic calls */
ffi_status
ffi_prep_cif_machdep_var (ffi_cif * cif,
unsigned int nfixedargs, unsigned int ntotalargs)
{
/* VFP variadic calls actually use the SYSV ABI */
if (cif->abi == FFI_VFP)
cif->abi = FFI_SYSV;
return ffi_prep_cif_machdep (cif);
}
/* Prototypes for assembly functions, in sysv.S. */
struct call_frame
{
void *fp;
void *lr;
void *rvalue;
int flags;
void *closure;
};
extern void ffi_call_SYSV (void *stack, struct call_frame *,
void (*fn) (void)) FFI_HIDDEN;
extern void ffi_call_VFP (void *vfp_space, struct call_frame *,
void (*fn) (void), unsigned vfp_used) FFI_HIDDEN;
static void
ffi_call_int (ffi_cif * cif, void (*fn) (void), void *rvalue,
void **avalue, void *closure)
{
int flags = cif->flags;
ffi_type *rtype = cif->rtype;
size_t bytes, rsize, vfp_size;
char *stack, *vfp_space, *new_rvalue;
struct call_frame *frame;
rsize = 0;
if (rvalue == NULL)
{
/* If the return value is a struct and we don't have a return
value address then we need to make one. Otherwise the return
value is in registers and we can ignore them. */
if (flags == ARM_TYPE_STRUCT)
rsize = rtype->size;
else
flags = ARM_TYPE_VOID;
}
else if (flags == ARM_TYPE_VFP_N)
{
/* Largest case is double x 4. */
rsize = 32;
}
else if (flags == ARM_TYPE_INT && rtype->type == FFI_TYPE_STRUCT)
rsize = 4;
/* Largest case. */
vfp_size = (cif->abi == FFI_VFP && cif->vfp_used ? 8*8: 0);
bytes = cif->bytes;
stack = alloca (vfp_size + bytes + sizeof(struct call_frame) + rsize);
vfp_space = NULL;
if (vfp_size)
{
vfp_space = stack;
stack += vfp_size;
}
frame = (struct call_frame *)(stack + bytes);
new_rvalue = rvalue;
if (rsize)
new_rvalue = (void *)(frame + 1);
frame->rvalue = new_rvalue;
frame->flags = flags;
frame->closure = closure;
if (vfp_space)
{
ffi_prep_args_VFP (cif, flags, new_rvalue, avalue, stack, vfp_space);
ffi_call_VFP (vfp_space, frame, fn, cif->vfp_used);
}
else
{
ffi_prep_args_SYSV (cif, flags, new_rvalue, avalue, stack);
ffi_call_SYSV (stack, frame, fn);
}
if (rvalue && rvalue != new_rvalue)
memcpy (rvalue, new_rvalue, rtype->size);
}
void
ffi_call (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue)
{
ffi_call_int (cif, fn, rvalue, avalue, NULL);
}
void
ffi_call_go (ffi_cif *cif, void (*fn) (void), void *rvalue,
void **avalue, void *closure)
{
ffi_call_int (cif, fn, rvalue, avalue, closure);
}
static void *
ffi_prep_incoming_args_SYSV (ffi_cif *cif, void *rvalue,
char *argp, void **avalue)
{
ffi_type **arg_types = cif->arg_types;
int i, n;
if (cif->flags == ARM_TYPE_STRUCT)
{
rvalue = *(void **) argp;
argp += 4;
}
else
{
if (cif->rtype->size && cif->rtype->size < 4)
*(uint32_t *) rvalue = 0;
}
for (i = 0, n = cif->nargs; i < n; i++)
{
ffi_type *ty = arg_types[i];
size_t z = ty->size;
argp = ffi_align (ty, argp);
avalue[i] = (void *) argp;
argp += z;
}
return rvalue;
}
static void *
ffi_prep_incoming_args_VFP (ffi_cif *cif, void *rvalue, char *stack,
char *vfp_space, void **avalue)
{
ffi_type **arg_types = cif->arg_types;
int i, n, vi = 0;
char *argp, *regp, *eo_regp;
char done_with_regs = 0;
char stack_used = 0;
regp = stack;
eo_regp = argp = regp + 16;
if (cif->flags == ARM_TYPE_STRUCT)
{
rvalue = *(void **) regp;
regp += 4;
}
for (i = 0, n = cif->nargs; i < n; i++)
{
ffi_type *ty = arg_types[i];
int is_vfp_type = vfp_type_p (ty);
size_t z = ty->size;
if (vi < cif->vfp_nargs && is_vfp_type)
{
avalue[i] = vfp_space + cif->vfp_args[vi++] * 4;
continue;
}
else if (!done_with_regs && !is_vfp_type)
{
char *tregp = ffi_align (ty, regp);
z = (z < 4) ? 4 : z; // pad
/* If the arguments either fits into the registers or uses registers
and stack, while we haven't read other things from the stack */
if (tregp + z <= eo_regp || !stack_used)
{
/* Because we're little endian, this is what it turns into. */
avalue[i] = (void *) tregp;
regp = tregp + z;
/* If we read past the last core register, make sure we
have not read from the stack before and continue
reading after regp. */
if (regp > eo_regp)
{
FFI_ASSERT (!stack_used);
argp = regp;
}
if (regp >= eo_regp)
{
done_with_regs = 1;
stack_used = 1;
}
continue;
}
}
stack_used = 1;
argp = ffi_align (ty, argp);
avalue[i] = (void *) argp;
argp += z;
}
return rvalue;
}
struct closure_frame
{
char vfp_space[8*8] __attribute__((aligned(8)));
char result[8*4];
char argp[];
};
int FFI_HIDDEN
ffi_closure_inner_SYSV (ffi_cif *cif,
void (*fun) (ffi_cif *, void *, void **, void *),
void *user_data,
struct closure_frame *frame)
{
void **avalue = (void **) alloca (cif->nargs * sizeof (void *));
void *rvalue = ffi_prep_incoming_args_SYSV (cif, frame->result,
frame->argp, avalue);
fun (cif, rvalue, avalue, user_data);
return cif->flags;
}
int FFI_HIDDEN
ffi_closure_inner_VFP (ffi_cif *cif,
void (*fun) (ffi_cif *, void *, void **, void *),
void *user_data,
struct closure_frame *frame)
{
void **avalue = (void **) alloca (cif->nargs * sizeof (void *));
void *rvalue = ffi_prep_incoming_args_VFP (cif, frame->result, frame->argp,
frame->vfp_space, avalue);
fun (cif, rvalue, avalue, user_data);
return cif->flags;
}
void ffi_closure_SYSV (void) FFI_HIDDEN;
void ffi_closure_VFP (void) FFI_HIDDEN;
void ffi_go_closure_SYSV (void) FFI_HIDDEN;
void ffi_go_closure_VFP (void) FFI_HIDDEN;
/* the cif must already be prep'ed */
ffi_status
ffi_prep_closure_loc (ffi_closure * closure,
ffi_cif * cif,
void (*fun) (ffi_cif *, void *, void **, void *),
void *user_data, void *codeloc)
{
void (*closure_func) (void) = ffi_closure_SYSV;
if (cif->abi == FFI_VFP)
{
/* We only need take the vfp path if there are vfp arguments. */
if (cif->vfp_used)
closure_func = ffi_closure_VFP;
}
else if (cif->abi != FFI_SYSV)
return FFI_BAD_ABI;
#if FFI_EXEC_TRAMPOLINE_TABLE
void **config = (void **)((uint8_t *)codeloc - PAGE_MAX_SIZE);
config[0] = closure;
config[1] = closure_func;
#else
memcpy (closure->tramp, ffi_arm_trampoline, 8);
#if defined (__QNX__)
msync(closure->tramp, 8, 0x1000000); /* clear data map */
msync(codeloc, 8, 0x1000000); /* clear insn map */
#else
__clear_cache(closure->tramp, closure->tramp + 8); /* clear data map */
__clear_cache(codeloc, codeloc + 8); /* clear insn map */
#endif
*(void (**)(void))(closure->tramp + 8) = closure_func;
#endif
closure->cif = cif;
closure->fun = fun;
closure->user_data = user_data;
return FFI_OK;
}
ffi_status
ffi_prep_go_closure (ffi_go_closure *closure, ffi_cif *cif,
void (*fun) (ffi_cif *, void *, void **, void *))
{
void (*closure_func) (void) = ffi_go_closure_SYSV;
if (cif->abi == FFI_VFP)
{
/* We only need take the vfp path if there are vfp arguments. */
if (cif->vfp_used)
closure_func = ffi_go_closure_VFP;
}
else if (cif->abi != FFI_SYSV)
return FFI_BAD_ABI;
closure->tramp = closure_func;
closure->cif = cif;
closure->fun = fun;
return FFI_OK;
}
/* Below are routines for VFP hard-float support. */
/* A subroutine of vfp_type_p. Given a structure type, return the type code
of the first non-structure element. Recurse for structure elements.
Return -1 if the structure is in fact empty, i.e. no nested elements. */
static int
is_hfa0 (const ffi_type *ty)
{
ffi_type **elements = ty->elements;
int i, ret = -1;
if (elements != NULL)
for (i = 0; elements[i]; ++i)
{
ret = elements[i]->type;
if (ret == FFI_TYPE_STRUCT || ret == FFI_TYPE_COMPLEX)
{
ret = is_hfa0 (elements[i]);
if (ret < 0)
continue;
}
break;
}
return ret;
}
/* A subroutine of vfp_type_p. Given a structure type, return true if all
of the non-structure elements are the same as CANDIDATE. */
static int
is_hfa1 (const ffi_type *ty, int candidate)
{
ffi_type **elements = ty->elements;
int i;
if (elements != NULL)
for (i = 0; elements[i]; ++i)
{
int t = elements[i]->type;
if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
{
if (!is_hfa1 (elements[i], candidate))
return 0;
}
else if (t != candidate)
return 0;
}
return 1;
}
/* Determine if TY is an homogenous floating point aggregate (HFA).
That is, a structure consisting of 1 to 4 members of all the same type,
where that type is a floating point scalar.
Returns non-zero iff TY is an HFA. The result is an encoded value where
bits 0-7 contain the type code, and bits 8-10 contain the element count. */
static int
vfp_type_p (const ffi_type *ty)
{
ffi_type **elements;
int candidate, i;
size_t size, ele_count;
/* Quickest tests first. */
candidate = ty->type;
switch (ty->type)
{
default:
return 0;
case FFI_TYPE_FLOAT:
case FFI_TYPE_DOUBLE:
ele_count = 1;
goto done;
case FFI_TYPE_COMPLEX:
candidate = ty->elements[0]->type;
if (candidate != FFI_TYPE_FLOAT && candidate != FFI_TYPE_DOUBLE)
return 0;
ele_count = 2;
goto done;
case FFI_TYPE_STRUCT:
break;
}
/* No HFA types are smaller than 4 bytes, or larger than 32 bytes. */
size = ty->size;
if (size < 4 || size > 32)
return 0;
/* Find the type of the first non-structure member. */
elements = ty->elements;
candidate = elements[0]->type;
if (candidate == FFI_TYPE_STRUCT || candidate == FFI_TYPE_COMPLEX)
{
for (i = 0; ; ++i)
{
candidate = is_hfa0 (elements[i]);
if (candidate >= 0)
break;
}
}
/* If the first member is not a floating point type, it's not an HFA.
Also quickly re-check the size of the structure. */
switch (candidate)
{
case FFI_TYPE_FLOAT:
ele_count = size / sizeof(float);
if (size != ele_count * sizeof(float))
return 0;
break;
case FFI_TYPE_DOUBLE:
ele_count = size / sizeof(double);
if (size != ele_count * sizeof(double))
return 0;
break;
default:
return 0;
}
if (ele_count > 4)
return 0;
/* Finally, make sure that all scalar elements are the same type. */
for (i = 0; elements[i]; ++i)
{
int t = elements[i]->type;
if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX)
{
if (!is_hfa1 (elements[i], candidate))
return 0;
}
else if (t != candidate)
return 0;
}
/* All tests succeeded. Encode the result. */
done:
return (ele_count << 8) | candidate;
}
static int
place_vfp_arg (ffi_cif *cif, int h)
{
unsigned short reg = cif->vfp_reg_free;
int align = 1, nregs = h >> 8;
if ((h & 0xff) == FFI_TYPE_DOUBLE)
align = 2, nregs *= 2;
/* Align register number. */
if ((reg & 1) && align == 2)
reg++;
while (reg + nregs <= 16)
{
int s, new_used = 0;
for (s = reg; s < reg + nregs; s++)
{
new_used |= (1 << s);
if (cif->vfp_used & (1 << s))
{
reg += align;
goto next_reg;
}
}
/* Found regs to allocate. */
cif->vfp_used |= new_used;
cif->vfp_args[cif->vfp_nargs++] = reg;
/* Update vfp_reg_free. */
if (cif->vfp_used & (1 << cif->vfp_reg_free))
{
reg += nregs;
while (cif->vfp_used & (1 << reg))
reg += 1;
cif->vfp_reg_free = reg;
}
return 0;
next_reg:;
}
// done, mark all regs as used
cif->vfp_reg_free = 16;
cif->vfp_used = 0xFFFF;
return 1;
}
static void
layout_vfp_args (ffi_cif * cif)
{
int i;
/* Init VFP fields */
cif->vfp_used = 0;
cif->vfp_nargs = 0;
cif->vfp_reg_free = 0;
memset (cif->vfp_args, -1, 16); /* Init to -1. */
for (i = 0; i < cif->nargs; i++)
{
int h = vfp_type_p (cif->arg_types[i]);
if (h && place_vfp_arg (cif, h) == 1)
break;
}
}
#endif
\ No newline at end of file
#ifdef __arm__
#define ARM_TYPE_VFP_S 0
#define ARM_TYPE_VFP_D 1
#define ARM_TYPE_VFP_N 2
#define ARM_TYPE_INT64 3
#define ARM_TYPE_INT 4
#define ARM_TYPE_VOID 5
#define ARM_TYPE_STRUCT 6
#endif
\ No newline at end of file
#ifdef __arm__
/* -----------------------------------------------------------------------
sysv.S - Copyright (c) 1998, 2008, 2011 Red Hat, Inc.
Copyright (c) 2011 Plausible Labs Cooperative, Inc.
ARM Foreign Function Interface
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
#define LIBFFI_ASM
#include <fficonfig.h>
#include <ffi.h>
#include <ffi_cfi.h>
#include "internal.h"
/* GCC 4.8 provides __ARM_ARCH; construct it otherwise. */
#ifndef __ARM_ARCH
# if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) \
|| defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) \
|| defined(__ARM_ARCH_7EM__)
# define __ARM_ARCH 7
# elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) \
|| defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) \
|| defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) \
|| defined(__ARM_ARCH_6M__)
# define __ARM_ARCH 6
# elif defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) \
|| defined(__ARM_ARCH_5E__) || defined(__ARM_ARCH_5TE__) \
|| defined(__ARM_ARCH_5TEJ__)
# define __ARM_ARCH 5
# else
# define __ARM_ARCH 4
# endif
#endif
/* Conditionally compile unwinder directives. */
#ifdef __ARM_EABI__
# define UNWIND(...) __VA_ARGS__
#else
# define UNWIND(...)
#endif
#if defined(HAVE_AS_CFI_PSEUDO_OP) && defined(__ARM_EABI__)
.cfi_sections .debug_frame
#endif
#define CONCAT(a, b) CONCAT2(a, b)
#define CONCAT2(a, b) a ## b
#ifdef __USER_LABEL_PREFIX__
# define CNAME(X) CONCAT (__USER_LABEL_PREFIX__, X)
#else
# define CNAME(X) X
#endif
#ifdef __ELF__
# define SIZE(X) .size CNAME(X), . - CNAME(X)
# define TYPE(X, Y) .type CNAME(X), Y
#else
# define SIZE(X)
# define TYPE(X, Y)
#endif
#define ARM_FUNC_START_LOCAL(name) \
.align 3; \
TYPE(CNAME(name), %function); \
CNAME(name):
#define ARM_FUNC_START(name) \
.globl CNAME(name); \
FFI_HIDDEN(CNAME(name)); \
ARM_FUNC_START_LOCAL(name)
#define ARM_FUNC_END(name) \
SIZE(name)
/* Aid in defining a jump table with 8 bytes between entries. */
/* ??? The clang assembler doesn't handle .if with symbolic expressions. */
#ifdef __clang__
# define E(index)
#else
# define E(index) \
.if . - 0b - 8*index; \
.error "type table out of sync"; \
.endif
#endif
.text
.syntax unified
.arm
#ifndef __clang__
/* We require interworking on LDM, which implies ARMv5T,
which implies the existance of BLX. */
.arch armv5t
#endif
/* Note that we use STC and LDC to encode VFP instructions,
so that we do not need ".fpu vfp", nor get that added to
the object file attributes. These will not be executed
unless the FFI_VFP abi is used. */
@ r0: stack
@ r1: frame
@ r2: fn
@ r3: vfp_used
ARM_FUNC_START(ffi_call_VFP)
UNWIND(.fnstart)
cfi_startproc
cmp r3, #3 @ load only d0 if possible
#ifdef __clang__
vldrle d0, [sp]
vldmgt sp, {d0-d7}
#else
ldcle p11, cr0, [r0] @ vldrle d0, [sp]
ldcgt p11, cr0, [r0], {16} @ vldmgt sp, {d0-d7}
#endif
add r0, r0, #64 @ discard the vfp register args
/* FALLTHRU */
ARM_FUNC_END(ffi_call_VFP)
ARM_FUNC_START(ffi_call_SYSV)
stm r1, {fp, lr}
mov fp, r1
@ This is a bit of a lie wrt the origin of the unwind info, but
@ now we've got the usual frame pointer and two saved registers.
UNWIND(.save {fp,lr})
UNWIND(.setfp fp, sp)
cfi_def_cfa(fp, 8)
cfi_rel_offset(fp, 0)
cfi_rel_offset(lr, 4)
mov sp, r0 @ install the stack pointer
mov lr, r2 @ move the fn pointer out of the way
ldr ip, [fp, #16] @ install the static chain
ldmia sp!, {r0-r3} @ move first 4 parameters in registers.
blx lr @ call fn
@ Load r2 with the pointer to storage for the return value
@ Load r3 with the return type code
ldr r2, [fp, #8]
ldr r3, [fp, #12]
@ Deallocate the stack with the arguments.
mov sp, fp
cfi_def_cfa_register(sp)
@ Store values stored in registers.
.align 3
add pc, pc, r3, lsl #3
nop
0:
E(ARM_TYPE_VFP_S)
#ifdef __clang__
vstr s0, [r2]
#else
stc p10, cr0, [r2] @ vstr s0, [r2]
#endif
pop {fp,pc}
E(ARM_TYPE_VFP_D)
#ifdef __clang__
vstr d0, [r2]
#else
stc p11, cr0, [r2] @ vstr d0, [r2]
#endif
pop {fp,pc}
E(ARM_TYPE_VFP_N)
#ifdef __clang__
vstm r2, {d0-d3}
#else
stc p11, cr0, [r2], {8} @ vstm r2, {d0-d3}
#endif
pop {fp,pc}
E(ARM_TYPE_INT64)
str r1, [r2, #4]
nop
E(ARM_TYPE_INT)
str r0, [r2]
pop {fp,pc}
E(ARM_TYPE_VOID)
pop {fp,pc}
nop
E(ARM_TYPE_STRUCT)
pop {fp,pc}
cfi_endproc
UNWIND(.fnend)
ARM_FUNC_END(ffi_call_SYSV)
/*
int ffi_closure_inner_* (cif, fun, user_data, frame)
*/
ARM_FUNC_START(ffi_go_closure_SYSV)
cfi_startproc
stmdb sp!, {r0-r3} @ save argument regs
cfi_adjust_cfa_offset(16)
ldr r0, [ip, #4] @ load cif
ldr r1, [ip, #8] @ load fun
mov r2, ip @ load user_data
b 0f
cfi_endproc
ARM_FUNC_END(ffi_go_closure_SYSV)
ARM_FUNC_START(ffi_closure_SYSV)
UNWIND(.fnstart)
cfi_startproc
stmdb sp!, {r0-r3} @ save argument regs
cfi_adjust_cfa_offset(16)
#if FFI_EXEC_TRAMPOLINE_TABLE
ldr ip, [ip] @ ip points to the config page, dereference to get the ffi_closure*
#endif
ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] @ load cif
ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] @ load fun
ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] @ load user_data
0:
add ip, sp, #16 @ compute entry sp
sub sp, sp, #64+32 @ allocate frame
cfi_adjust_cfa_offset(64+32)
stmdb sp!, {ip,lr}
/* Remember that EABI unwind info only applies at call sites.
We need do nothing except note the save of the stack pointer
and the link registers. */
UNWIND(.save {sp,lr})
cfi_adjust_cfa_offset(8)
cfi_rel_offset(lr, 4)
add r3, sp, #8 @ load frame
bl CNAME(ffi_closure_inner_SYSV)
@ Load values returned in registers.
add r2, sp, #8+64 @ load result
adr r3, CNAME(ffi_closure_ret)
add pc, r3, r0, lsl #3
cfi_endproc
UNWIND(.fnend)
ARM_FUNC_END(ffi_closure_SYSV)
ARM_FUNC_START(ffi_go_closure_VFP)
cfi_startproc
stmdb sp!, {r0-r3} @ save argument regs
cfi_adjust_cfa_offset(16)
ldr r0, [ip, #4] @ load cif
ldr r1, [ip, #8] @ load fun
mov r2, ip @ load user_data
b 0f
cfi_endproc
ARM_FUNC_END(ffi_go_closure_VFP)
ARM_FUNC_START(ffi_closure_VFP)
UNWIND(.fnstart)
cfi_startproc
stmdb sp!, {r0-r3} @ save argument regs
cfi_adjust_cfa_offset(16)
#if FFI_EXEC_TRAMPOLINE_TABLE
ldr ip, [ip] @ ip points to the config page, dereference to get the ffi_closure*
#endif
ldr r0, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET] @ load cif
ldr r1, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+4] @ load fun
ldr r2, [ip, #FFI_TRAMPOLINE_CLOSURE_OFFSET+8] @ load user_data
0:
add ip, sp, #16
sub sp, sp, #64+32 @ allocate frame
cfi_adjust_cfa_offset(64+32)
#ifdef __clang__
vstm sp, {d0-d7}
#else
stc p11, cr0, [sp], {16} @ vstm sp, {d0-d7}
#endif
stmdb sp!, {ip,lr}
/* See above. */
UNWIND(.save {sp,lr})
cfi_adjust_cfa_offset(8)
cfi_rel_offset(lr, 4)
add r3, sp, #8 @ load frame
bl CNAME(ffi_closure_inner_VFP)
@ Load values returned in registers.
add r2, sp, #8+64 @ load result
adr r3, CNAME(ffi_closure_ret)
add pc, r3, r0, lsl #3
cfi_endproc
UNWIND(.fnend)
ARM_FUNC_END(ffi_closure_VFP)
/* Load values returned in registers for both closure entry points.
Note that we use LDM with SP in the register set. This is deprecated
by ARM, but not yet unpredictable. */
ARM_FUNC_START_LOCAL(ffi_closure_ret)
cfi_startproc
cfi_rel_offset(sp, 0)
cfi_rel_offset(lr, 4)
0:
E(ARM_TYPE_VFP_S)
#ifdef __clang__
vldr s0, [r2]
#else
ldc p10, cr0, [r2] @ vldr s0, [r2]
#endif
ldm sp, {sp,pc}
E(ARM_TYPE_VFP_D)
#ifdef __clang__
vldr d0, [r2]
#else
ldc p11, cr0, [r2] @ vldr d0, [r2]
#endif
ldm sp, {sp,pc}
E(ARM_TYPE_VFP_N)
#ifdef __clang__
vldm r2, {d0-d3}
#else
ldc p11, cr0, [r2], {8} @ vldm r2, {d0-d3}
#endif
ldm sp, {sp,pc}
E(ARM_TYPE_INT64)
ldr r1, [r2, #4]
nop
E(ARM_TYPE_INT)
ldr r0, [r2]
ldm sp, {sp,pc}
E(ARM_TYPE_VOID)
ldm sp, {sp,pc}
nop
E(ARM_TYPE_STRUCT)
ldm sp, {sp,pc}
cfi_endproc
ARM_FUNC_END(ffi_closure_ret)
#if FFI_EXEC_TRAMPOLINE_TABLE
#ifdef __MACH__
#include <mach/machine/vm_param.h>
.align PAGE_MAX_SHIFT
ARM_FUNC_START(ffi_closure_trampoline_table_page)
.rept PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE
adr ip, #-PAGE_MAX_SIZE @ the config page is PAGE_MAX_SIZE behind the trampoline page
sub ip, #8 @ account for pc bias
ldr pc, [ip, #4] @ jump to ffi_closure_SYSV or ffi_closure_VFP
.endr
ARM_FUNC_END(ffi_closure_trampoline_table_page)
#endif
#else
ARM_FUNC_START(ffi_arm_trampoline)
0: adr ip, 0b
ldr pc, 1f
1: .long 0
ARM_FUNC_END(ffi_arm_trampoline)
#endif /* FFI_EXEC_TRAMPOLINE_TABLE */
#if defined __ELF__ && defined __linux__
.section .note.GNU-stack,"",%progbits
#endif
#endif
\ No newline at end of file
/* -----------------------------------------------------------------------
closures.c - Copyright (c) 2007, 2009, 2010 Red Hat, Inc.
Copyright (C) 2007, 2009, 2010 Free Software Foundation, Inc
Copyright (c) 2011 Plausible Labs Cooperative, Inc.
Code to allocate and deallocate memory for closures.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
#if defined __linux__ && !defined _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include <fficonfig.h>
#include <ffi.h>
#include <ffi_common.h>
#ifdef __NetBSD__
#include <sys/param.h>
#endif
#if __NetBSD_Version__ - 0 >= 799007200
/* NetBSD with PROT_MPROTECT */
#include <sys/mman.h>
#include <stddef.h>
#include <unistd.h>
static const size_t overhead =
(sizeof(max_align_t) > sizeof(void *) + sizeof(size_t)) ?
sizeof(max_align_t)
: sizeof(void *) + sizeof(size_t);
#define ADD_TO_POINTER(p, d) ((void *)((uintptr_t)(p) + (d)))
void *
ffi_closure_alloc (size_t size, void **code)
{
static size_t page_size;
size_t rounded_size;
void *codeseg, *dataseg;
int prot;
/* Expect that PAX mprotect is active and a separate code mapping is necessary. */
if (!code)
return NULL;
/* Obtain system page size. */
if (!page_size)
page_size = sysconf(_SC_PAGESIZE);
/* Round allocation size up to the next page, keeping in mind the size field and pointer to code map. */
rounded_size = (size + overhead + page_size - 1) & ~(page_size - 1);
/* Primary mapping is RW, but request permission to switch to PROT_EXEC later. */
prot = PROT_READ | PROT_WRITE | PROT_MPROTECT(PROT_EXEC);
dataseg = mmap(NULL, rounded_size, prot, MAP_ANON | MAP_PRIVATE, -1, 0);
if (dataseg == MAP_FAILED)
return NULL;
/* Create secondary mapping and switch it to RX. */
codeseg = mremap(dataseg, rounded_size, NULL, rounded_size, MAP_REMAPDUP);
if (codeseg == MAP_FAILED) {
munmap(dataseg, rounded_size);
return NULL;
}
if (mprotect(codeseg, rounded_size, PROT_READ | PROT_EXEC) == -1) {
munmap(codeseg, rounded_size);
munmap(dataseg, rounded_size);
return NULL;
}
/* Remember allocation size and location of the secondary mapping for ffi_closure_free. */
memcpy(dataseg, &rounded_size, sizeof(rounded_size));
memcpy(ADD_TO_POINTER(dataseg, sizeof(size_t)), &codeseg, sizeof(void *));
*code = ADD_TO_POINTER(codeseg, overhead);
return ADD_TO_POINTER(dataseg, overhead);
}
void
ffi_closure_free (void *ptr)
{
void *codeseg, *dataseg;
size_t rounded_size;
dataseg = ADD_TO_POINTER(ptr, -overhead);
memcpy(&rounded_size, dataseg, sizeof(rounded_size));
memcpy(&codeseg, ADD_TO_POINTER(dataseg, sizeof(size_t)), sizeof(void *));
munmap(dataseg, rounded_size);
munmap(codeseg, rounded_size);
}
#else /* !NetBSD with PROT_MPROTECT */
#if !FFI_MMAP_EXEC_WRIT && !FFI_EXEC_TRAMPOLINE_TABLE
# if __linux__ && !defined(__ANDROID__)
/* This macro indicates it may be forbidden to map anonymous memory
with both write and execute permission. Code compiled when this
option is defined will attempt to map such pages once, but if it
fails, it falls back to creating a temporary file in a writable and
executable filesystem and mapping pages from it into separate
locations in the virtual memory space, one location writable and
another executable. */
# define FFI_MMAP_EXEC_WRIT 1
# define HAVE_MNTENT 1
# endif
# if defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)
/* Windows systems may have Data Execution Protection (DEP) enabled,
which requires the use of VirtualMalloc/VirtualFree to alloc/free
executable memory. */
# define FFI_MMAP_EXEC_WRIT 1
# endif
#endif
#if FFI_MMAP_EXEC_WRIT && !defined FFI_MMAP_EXEC_SELINUX
# if defined(__linux__) && !defined(__ANDROID__)
/* When defined to 1 check for SELinux and if SELinux is active,
don't attempt PROT_EXEC|PROT_WRITE mapping at all, as that
might cause audit messages. */
# define FFI_MMAP_EXEC_SELINUX 1
# endif
#endif
#if FFI_CLOSURES
#if FFI_EXEC_TRAMPOLINE_TABLE
#ifdef __MACH__
#include <mach/mach.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
extern void *ffi_closure_trampoline_table_page;
typedef struct ffi_trampoline_table ffi_trampoline_table;
typedef struct ffi_trampoline_table_entry ffi_trampoline_table_entry;
struct ffi_trampoline_table
{
/* contiguous writable and executable pages */
vm_address_t config_page;
vm_address_t trampoline_page;
/* free list tracking */
uint16_t free_count;
ffi_trampoline_table_entry *free_list;
ffi_trampoline_table_entry *free_list_pool;
ffi_trampoline_table *prev;
ffi_trampoline_table *next;
};
struct ffi_trampoline_table_entry
{
void *(*trampoline) ();
ffi_trampoline_table_entry *next;
};
/* Total number of trampolines that fit in one trampoline table */
#define FFI_TRAMPOLINE_COUNT (PAGE_MAX_SIZE / FFI_TRAMPOLINE_SIZE)
static pthread_mutex_t ffi_trampoline_lock = PTHREAD_MUTEX_INITIALIZER;
static ffi_trampoline_table *ffi_trampoline_tables = NULL;
static ffi_trampoline_table *
ffi_trampoline_table_alloc (void)
{
ffi_trampoline_table *table;
vm_address_t config_page;
vm_address_t trampoline_page;
vm_address_t trampoline_page_template;
vm_prot_t cur_prot;
vm_prot_t max_prot;
kern_return_t kt;
uint16_t i;
/* Allocate two pages -- a config page and a placeholder page */
config_page = 0x0;
kt = vm_allocate (mach_task_self (), &config_page, PAGE_MAX_SIZE * 2,
VM_FLAGS_ANYWHERE);
if (kt != KERN_SUCCESS)
return NULL;
/* Remap the trampoline table on top of the placeholder page */
trampoline_page = config_page + PAGE_MAX_SIZE;
trampoline_page_template = (vm_address_t)&ffi_closure_trampoline_table_page;
#ifdef __arm__
/* ffi_closure_trampoline_table_page can be thumb-biased on some ARM archs */
trampoline_page_template &= ~1UL;
#endif
kt = vm_remap (mach_task_self (), &trampoline_page, PAGE_MAX_SIZE, 0x0,
VM_FLAGS_OVERWRITE, mach_task_self (), trampoline_page_template,
FALSE, &cur_prot, &max_prot, VM_INHERIT_SHARE);
if (kt != KERN_SUCCESS)
{
vm_deallocate (mach_task_self (), config_page, PAGE_MAX_SIZE * 2);
return NULL;
}
/* We have valid trampoline and config pages */
table = calloc (1, sizeof (ffi_trampoline_table));
table->free_count = FFI_TRAMPOLINE_COUNT;
table->config_page = config_page;
table->trampoline_page = trampoline_page;
/* Create and initialize the free list */
table->free_list_pool =
calloc (FFI_TRAMPOLINE_COUNT, sizeof (ffi_trampoline_table_entry));
for (i = 0; i < table->free_count; i++)
{
ffi_trampoline_table_entry *entry = &table->free_list_pool[i];
entry->trampoline =
(void *) (table->trampoline_page + (i * FFI_TRAMPOLINE_SIZE));
if (i < table->free_count - 1)
entry->next = &table->free_list_pool[i + 1];
}
table->free_list = table->free_list_pool;
return table;
}
static void
ffi_trampoline_table_free (ffi_trampoline_table *table)
{
/* Remove from the list */
if (table->prev != NULL)
table->prev->next = table->next;
if (table->next != NULL)
table->next->prev = table->prev;
/* Deallocate pages */
vm_deallocate (mach_task_self (), table->config_page, PAGE_MAX_SIZE * 2);
/* Deallocate free list */
free (table->free_list_pool);
free (table);
}
void *
ffi_closure_alloc (size_t size, void **code)
{
/* Create the closure */
ffi_closure *closure = malloc (size);
if (closure == NULL)
return NULL;
pthread_mutex_lock (&ffi_trampoline_lock);
/* Check for an active trampoline table with available entries. */
ffi_trampoline_table *table = ffi_trampoline_tables;
if (table == NULL || table->free_list == NULL)
{
table = ffi_trampoline_table_alloc ();
if (table == NULL)
{
pthread_mutex_unlock (&ffi_trampoline_lock);
free (closure);
return NULL;
}
/* Insert the new table at the top of the list */
table->next = ffi_trampoline_tables;
if (table->next != NULL)
table->next->prev = table;
ffi_trampoline_tables = table;
}
/* Claim the free entry */
ffi_trampoline_table_entry *entry = ffi_trampoline_tables->free_list;
ffi_trampoline_tables->free_list = entry->next;
ffi_trampoline_tables->free_count--;
entry->next = NULL;
pthread_mutex_unlock (&ffi_trampoline_lock);
/* Initialize the return values */
*code = entry->trampoline;
closure->trampoline_table = table;
closure->trampoline_table_entry = entry;
return closure;
}
void
ffi_closure_free (void *ptr)
{
ffi_closure *closure = ptr;
pthread_mutex_lock (&ffi_trampoline_lock);
/* Fetch the table and entry references */
ffi_trampoline_table *table = closure->trampoline_table;
ffi_trampoline_table_entry *entry = closure->trampoline_table_entry;
/* Return the entry to the free list */
entry->next = table->free_list;
table->free_list = entry;
table->free_count++;
/* If all trampolines within this table are free, and at least one other table exists, deallocate
* the table */
if (table->free_count == FFI_TRAMPOLINE_COUNT
&& ffi_trampoline_tables != table)
{
ffi_trampoline_table_free (table);
}
else if (ffi_trampoline_tables != table)
{
/* Otherwise, bump this table to the top of the list */
table->prev = NULL;
table->next = ffi_trampoline_tables;
if (ffi_trampoline_tables != NULL)
ffi_trampoline_tables->prev = table;
ffi_trampoline_tables = table;
}
pthread_mutex_unlock (&ffi_trampoline_lock);
/* Free the closure */
free (closure);
}
#endif
// Per-target implementation; It's unclear what can reasonable be shared between two OS/architecture implementations.
#elif FFI_MMAP_EXEC_WRIT /* !FFI_EXEC_TRAMPOLINE_TABLE */
#define USE_LOCKS 1
#define USE_DL_PREFIX 1
#ifdef __GNUC__
#ifndef USE_BUILTIN_FFS
#define USE_BUILTIN_FFS 1
#endif
#endif
/* We need to use mmap, not sbrk. */
#define HAVE_MORECORE 0
/* We could, in theory, support mremap, but it wouldn't buy us anything. */
#define HAVE_MREMAP 0
/* We have no use for this, so save some code and data. */
#define NO_MALLINFO 1
/* We need all allocations to be in regular segments, otherwise we
lose track of the corresponding code address. */
#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T
/* Don't allocate more than a page unless needed. */
#define DEFAULT_GRANULARITY ((size_t)malloc_getpagesize)
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <string.h>
#include <stdio.h>
#if !defined(X86_WIN32) && !defined(X86_WIN64)
#ifdef HAVE_MNTENT
#include <mntent.h>
#endif /* HAVE_MNTENT */
#include <sys/param.h>
#include <pthread.h>
/* We don't want sys/mman.h to be included after we redefine mmap and
dlmunmap. */
#include <sys/mman.h>
#define LACKS_SYS_MMAN_H 1
#if FFI_MMAP_EXEC_SELINUX
#include <sys/statfs.h>
#include <stdlib.h>
static int selinux_enabled = -1;
static int
selinux_enabled_check (void)
{
struct statfs sfs;
FILE *f;
char *buf = NULL;
size_t len = 0;
if (statfs ("/selinux", &sfs) >= 0
&& (unsigned int) sfs.f_type == 0xf97cff8cU)
return 1;
f = fopen ("/proc/mounts", "r");
if (f == NULL)
return 0;
while (getline (&buf, &len, f) >= 0)
{
char *p = strchr (buf, ' ');
if (p == NULL)
break;
p = strchr (p + 1, ' ');
if (p == NULL)
break;
if (strncmp (p + 1, "selinuxfs ", 10) == 0)
{
free (buf);
fclose (f);
return 1;
}
}
free (buf);
fclose (f);
return 0;
}
#define is_selinux_enabled() (selinux_enabled >= 0 ? selinux_enabled \
: (selinux_enabled = selinux_enabled_check ()))
#else
#define is_selinux_enabled() 0
#endif /* !FFI_MMAP_EXEC_SELINUX */
/* On PaX enable kernels that have MPROTECT enable we can't use PROT_EXEC. */
#ifdef FFI_MMAP_EXEC_EMUTRAMP_PAX
#include <stdlib.h>
static int emutramp_enabled = -1;
static int
emutramp_enabled_check (void)
{
char *buf = NULL;
size_t len = 0;
FILE *f;
int ret;
f = fopen ("/proc/self/status", "r");
if (f == NULL)
return 0;
ret = 0;
while (getline (&buf, &len, f) != -1)
if (!strncmp (buf, "PaX:", 4))
{
char emutramp;
if (sscanf (buf, "%*s %*c%c", &emutramp) == 1)
ret = (emutramp == 'E');
break;
}
free (buf);
fclose (f);
return ret;
}
#define is_emutramp_enabled() (emutramp_enabled >= 0 ? emutramp_enabled \
: (emutramp_enabled = emutramp_enabled_check ()))
#endif /* FFI_MMAP_EXEC_EMUTRAMP_PAX */
#elif defined (__CYGWIN__) || defined(__INTERIX)
#include <sys/mman.h>
/* Cygwin is Linux-like, but not quite that Linux-like. */
#define is_selinux_enabled() 0
#endif /* !defined(X86_WIN32) && !defined(X86_WIN64) */
#ifndef FFI_MMAP_EXEC_EMUTRAMP_PAX
#define is_emutramp_enabled() 0
#endif /* FFI_MMAP_EXEC_EMUTRAMP_PAX */
/* Declare all functions defined in dlmalloc.c as static. */
static void *dlmalloc(size_t);
static void dlfree(void*);
static void *dlcalloc(size_t, size_t) MAYBE_UNUSED;
static void *dlrealloc(void *, size_t) MAYBE_UNUSED;
static void *dlmemalign(size_t, size_t) MAYBE_UNUSED;
static void *dlvalloc(size_t) MAYBE_UNUSED;
static int dlmallopt(int, int) MAYBE_UNUSED;
static size_t dlmalloc_footprint(void) MAYBE_UNUSED;
static size_t dlmalloc_max_footprint(void) MAYBE_UNUSED;
static void** dlindependent_calloc(size_t, size_t, void**) MAYBE_UNUSED;
static void** dlindependent_comalloc(size_t, size_t*, void**) MAYBE_UNUSED;
static void *dlpvalloc(size_t) MAYBE_UNUSED;
static int dlmalloc_trim(size_t) MAYBE_UNUSED;
static size_t dlmalloc_usable_size(void*) MAYBE_UNUSED;
static void dlmalloc_stats(void) MAYBE_UNUSED;
#if !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX)
/* Use these for mmap and munmap within dlmalloc.c. */
static void *dlmmap(void *, size_t, int, int, int, off_t);
static int dlmunmap(void *, size_t);
#endif /* !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) */
#define mmap dlmmap
#define munmap dlmunmap
#include "dlmalloc.c"
#undef mmap
#undef munmap
#if !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX)
/* A mutex used to synchronize access to *exec* variables in this file. */
static pthread_mutex_t open_temp_exec_file_mutex = PTHREAD_MUTEX_INITIALIZER;
/* A file descriptor of a temporary file from which we'll map
executable pages. */
static int execfd = -1;
/* The amount of space already allocated from the temporary file. */
static size_t execsize = 0;
/* Open a temporary file name, and immediately unlink it. */
static int
open_temp_exec_file_name (char *name, int flags)
{
int fd;
#ifdef HAVE_MKOSTEMP
fd = mkostemp (name, flags);
#else
fd = mkstemp (name);
#endif
if (fd != -1)
unlink (name);
return fd;
}
/* Open a temporary file in the named directory. */
static int
open_temp_exec_file_dir (const char *dir)
{
static const char suffix[] = "/ffiXXXXXX";
int lendir, flags;
char *tempname;
#ifdef O_TMPFILE
int fd;
#endif
#ifdef O_CLOEXEC
flags = O_CLOEXEC;
#else
flags = 0;
#endif
#ifdef O_TMPFILE
fd = open (dir, flags | O_RDWR | O_EXCL | O_TMPFILE, 0700);
/* If the running system does not support the O_TMPFILE flag then retry without it. */
if (fd != -1 || (errno != EINVAL && errno != EISDIR && errno != EOPNOTSUPP)) {
return fd;
} else {
errno = 0;
}
#endif
lendir = (int) strlen (dir);
tempname = __builtin_alloca (lendir + sizeof (suffix));
if (!tempname)
return -1;
memcpy (tempname, dir, lendir);
memcpy (tempname + lendir, suffix, sizeof (suffix));
return open_temp_exec_file_name (tempname, flags);
}
/* Open a temporary file in the directory in the named environment
variable. */
static int
open_temp_exec_file_env (const char *envvar)
{
const char *value = getenv (envvar);
if (!value)
return -1;
return open_temp_exec_file_dir (value);
}
#ifdef HAVE_MNTENT
/* Open a temporary file in an executable and writable mount point
listed in the mounts file. Subsequent calls with the same mounts
keep searching for mount points in the same file. Providing NULL
as the mounts file closes the file. */
static int
open_temp_exec_file_mnt (const char *mounts)
{
static const char *last_mounts;
static FILE *last_mntent;
if (mounts != last_mounts)
{
if (last_mntent)
endmntent (last_mntent);
last_mounts = mounts;
if (mounts)
last_mntent = setmntent (mounts, "r");
else
last_mntent = NULL;
}
if (!last_mntent)
return -1;
for (;;)
{
int fd;
struct mntent mnt;
char buf[MAXPATHLEN * 3];
if (getmntent_r (last_mntent, &mnt, buf, sizeof (buf)) == NULL)
return -1;
if (hasmntopt (&mnt, "ro")
|| hasmntopt (&mnt, "noexec")
|| access (mnt.mnt_dir, W_OK))
continue;
fd = open_temp_exec_file_dir (mnt.mnt_dir);
if (fd != -1)
return fd;
}
}
#endif /* HAVE_MNTENT */
/* Instructions to look for a location to hold a temporary file that
can be mapped in for execution. */
static struct
{
int (*func)(const char *);
const char *arg;
int repeat;
} open_temp_exec_file_opts[] = {
{ open_temp_exec_file_env, "TMPDIR", 0 },
{ open_temp_exec_file_dir, "/tmp", 0 },
{ open_temp_exec_file_dir, "/var/tmp", 0 },
{ open_temp_exec_file_dir, "/dev/shm", 0 },
{ open_temp_exec_file_env, "HOME", 0 },
#ifdef HAVE_MNTENT
{ open_temp_exec_file_mnt, "/etc/mtab", 1 },
{ open_temp_exec_file_mnt, "/proc/mounts", 1 },
#endif /* HAVE_MNTENT */
};
/* Current index into open_temp_exec_file_opts. */
static int open_temp_exec_file_opts_idx = 0;
/* Reset a current multi-call func, then advances to the next entry.
If we're at the last, go back to the first and return nonzero,
otherwise return zero. */
static int
open_temp_exec_file_opts_next (void)
{
if (open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat)
open_temp_exec_file_opts[open_temp_exec_file_opts_idx].func (NULL);
open_temp_exec_file_opts_idx++;
if (open_temp_exec_file_opts_idx
== (sizeof (open_temp_exec_file_opts)
/ sizeof (*open_temp_exec_file_opts)))
{
open_temp_exec_file_opts_idx = 0;
return 1;
}
return 0;
}
/* Return a file descriptor of a temporary zero-sized file in a
writable and executable filesystem. */
static int
open_temp_exec_file (void)
{
int fd;
do
{
fd = open_temp_exec_file_opts[open_temp_exec_file_opts_idx].func
(open_temp_exec_file_opts[open_temp_exec_file_opts_idx].arg);
if (!open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat
|| fd == -1)
{
if (open_temp_exec_file_opts_next ())
break;
}
}
while (fd == -1);
return fd;
}
/* We need to allocate space in a file that will be backing a writable
mapping. Several problems exist with the usual approaches:
- fallocate() is Linux-only
- posix_fallocate() is not available on all platforms
- ftruncate() does not allocate space on filesystems with sparse files
Failure to allocate the space will cause SIGBUS to be thrown when
the mapping is subsequently written to. */
static int
allocate_space (int fd, off_t offset, off_t len)
{
static size_t page_size;
/* Obtain system page size. */
if (!page_size)
page_size = sysconf(_SC_PAGESIZE);
unsigned char buf[page_size];
memset (buf, 0, page_size);
while (len > 0)
{
off_t to_write = (len < page_size) ? len : page_size;
if (write (fd, buf, to_write) < to_write)
return -1;
len -= to_write;
}
return 0;
}
/* Map in a chunk of memory from the temporary exec file into separate
locations in the virtual memory address space, one writable and one
executable. Returns the address of the writable portion, after
storing an offset to the corresponding executable portion at the
last word of the requested chunk. */
static void *
dlmmap_locked (void *start, size_t length, int prot, int flags, off_t offset)
{
void *ptr;
if (execfd == -1)
{
open_temp_exec_file_opts_idx = 0;
retry_open:
execfd = open_temp_exec_file ();
if (execfd == -1)
return MFAIL;
}
offset = execsize;
if (allocate_space (execfd, offset, length))
return MFAIL;
flags &= ~(MAP_PRIVATE | MAP_ANONYMOUS);
flags |= MAP_SHARED;
ptr = mmap (NULL, length, (prot & ~PROT_WRITE) | PROT_EXEC,
flags, execfd, offset);
if (ptr == MFAIL)
{
if (!offset)
{
close (execfd);
goto retry_open;
}
ftruncate (execfd, offset);
return MFAIL;
}
else if (!offset
&& open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat)
open_temp_exec_file_opts_next ();
start = mmap (start, length, prot, flags, execfd, offset);
if (start == MFAIL)
{
munmap (ptr, length);
ftruncate (execfd, offset);
return start;
}
mmap_exec_offset ((char *)start, length) = (char*)ptr - (char*)start;
execsize += length;
return start;
}
/* Map in a writable and executable chunk of memory if possible.
Failing that, fall back to dlmmap_locked. */
static void *
dlmmap (void *start, size_t length, int prot,
int flags, int fd, off_t offset)
{
void *ptr;
assert (start == NULL && length % malloc_getpagesize == 0
&& prot == (PROT_READ | PROT_WRITE)
&& flags == (MAP_PRIVATE | MAP_ANONYMOUS)
&& fd == -1 && offset == 0);
if (execfd == -1 && is_emutramp_enabled ())
{
ptr = mmap (start, length, prot & ~PROT_EXEC, flags, fd, offset);
return ptr;
}
if (execfd == -1 && !is_selinux_enabled ())
{
ptr = mmap (start, length, prot | PROT_EXEC, flags, fd, offset);
if (ptr != MFAIL || (errno != EPERM && errno != EACCES))
/* Cool, no need to mess with separate segments. */
return ptr;
/* If MREMAP_DUP is ever introduced and implemented, try mmap
with ((prot & ~PROT_WRITE) | PROT_EXEC) and mremap with
MREMAP_DUP and prot at this point. */
}
if (execsize == 0 || execfd == -1)
{
pthread_mutex_lock (&open_temp_exec_file_mutex);
ptr = dlmmap_locked (start, length, prot, flags, offset);
pthread_mutex_unlock (&open_temp_exec_file_mutex);
return ptr;
}
return dlmmap_locked (start, length, prot, flags, offset);
}
/* Release memory at the given address, as well as the corresponding
executable page if it's separate. */
static int
dlmunmap (void *start, size_t length)
{
/* We don't bother decreasing execsize or truncating the file, since
we can't quite tell whether we're unmapping the end of the file.
We don't expect frequent deallocation anyway. If we did, we
could locate pages in the file by writing to the pages being
deallocated and checking that the file contents change.
Yuck. */
msegmentptr seg = segment_holding (gm, start);
void *code;
if (seg && (code = add_segment_exec_offset (start, seg)) != start)
{
int ret = munmap (code, length);
if (ret)
return ret;
}
return munmap (start, length);
}
#if FFI_CLOSURE_FREE_CODE
/* Return segment holding given code address. */
static msegmentptr
segment_holding_code (mstate m, char* addr)
{
msegmentptr sp = &m->seg;
for (;;) {
if (addr >= add_segment_exec_offset (sp->base, sp)
&& addr < add_segment_exec_offset (sp->base, sp) + sp->size)
return sp;
if ((sp = sp->next) == 0)
return 0;
}
}
#endif
#endif /* !(defined(X86_WIN32) || defined(X86_WIN64) || defined(__OS2__)) || defined (__CYGWIN__) || defined(__INTERIX) */
/* Allocate a chunk of memory with the given size. Returns a pointer
to the writable address, and sets *CODE to the executable
corresponding virtual address. */
void *
ffi_closure_alloc (size_t size, void **code)
{
void *ptr;
if (!code)
return NULL;
ptr = dlmalloc (size);
if (ptr)
{
msegmentptr seg = segment_holding (gm, ptr);
*code = add_segment_exec_offset (ptr, seg);
}
return ptr;
}
/* Release a chunk of memory allocated with ffi_closure_alloc. If
FFI_CLOSURE_FREE_CODE is nonzero, the given address can be the
writable or the executable address given. Otherwise, only the
writable address can be provided here. */
void
ffi_closure_free (void *ptr)
{
#if FFI_CLOSURE_FREE_CODE
msegmentptr seg = segment_holding_code (gm, ptr);
if (seg)
ptr = sub_segment_exec_offset (ptr, seg);
#endif
dlfree (ptr);
}
# else /* ! FFI_MMAP_EXEC_WRIT */
/* On many systems, memory returned by malloc is writable and
executable, so just use it. */
#include <stdlib.h>
void *
ffi_closure_alloc (size_t size, void **code)
{
if (!code)
return NULL;
return *code = malloc (size);
}
void
ffi_closure_free (void *ptr)
{
free (ptr);
}
# endif /* ! FFI_MMAP_EXEC_WRIT */
#endif /* FFI_CLOSURES */
#endif /* NetBSD with PROT_MPROTECT */
/* -----------------------------------------------------------------------
debug.c - Copyright (c) 1996 Red Hat, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
#include <ffi.h>
#include <ffi_common.h>
#include <stdlib.h>
#include <stdio.h>
/* General debugging routines */
void ffi_stop_here(void)
{
/* This function is only useful for debugging purposes.
Place a breakpoint on ffi_stop_here to be notified of
significant events. */
}
/* This function should only be called via the FFI_ASSERT() macro */
void ffi_assert(char *expr, char *file, int line)
{
fprintf(stderr, "ASSERTION FAILURE: %s at %s:%d\n", expr, file, line);
ffi_stop_here();
abort();
}
/* Perform a sanity check on an ffi_type structure */
void ffi_type_test(ffi_type *a, char *file, int line)
{
FFI_ASSERT_AT(a != NULL, file, line);
FFI_ASSERT_AT(a->type <= FFI_TYPE_LAST, file, line);
FFI_ASSERT_AT(a->type == FFI_TYPE_VOID || a->size > 0, file, line);
FFI_ASSERT_AT(a->type == FFI_TYPE_VOID || a->alignment > 0, file, line);
FFI_ASSERT_AT((a->type != FFI_TYPE_STRUCT && a->type != FFI_TYPE_COMPLEX)
|| a->elements != NULL, file, line);
FFI_ASSERT_AT(a->type != FFI_TYPE_COMPLEX
|| (a->elements != NULL
&& a->elements[0] != NULL && a->elements[1] == NULL),
file, line);
}
This source diff could not be displayed because it is too large. You can view the blob instead.
#ifdef __aarch64__
#include <ffi_arm64.h>
#endif
#ifdef __i386__
#include <ffi_i386.h>
#endif
#ifdef __arm__
#include <ffi_armv7.h>
#endif
#ifdef __x86_64__
#include <ffi_x86_64.h>
#endif
/* -----------------------------------------------------------------------
ffi_cfi.h - Copyright (c) 2014 Red Hat, Inc.
Conditionally assemble cfi directives. Only necessary for building libffi.
----------------------------------------------------------------------- */
#ifndef FFI_CFI_H
#define FFI_CFI_H
#ifdef HAVE_AS_CFI_PSEUDO_OP
# define cfi_startproc .cfi_startproc
# define cfi_endproc .cfi_endproc
# define cfi_def_cfa(reg, off) .cfi_def_cfa reg, off
# define cfi_def_cfa_register(reg) .cfi_def_cfa_register reg
# define cfi_def_cfa_offset(off) .cfi_def_cfa_offset off
# define cfi_adjust_cfa_offset(off) .cfi_adjust_cfa_offset off
# define cfi_offset(reg, off) .cfi_offset reg, off
# define cfi_rel_offset(reg, off) .cfi_rel_offset reg, off
# define cfi_register(r1, r2) .cfi_register r1, r2
# define cfi_return_column(reg) .cfi_return_column reg
# define cfi_restore(reg) .cfi_restore reg
# define cfi_same_value(reg) .cfi_same_value reg
# define cfi_undefined(reg) .cfi_undefined reg
# define cfi_remember_state .cfi_remember_state
# define cfi_restore_state .cfi_restore_state
# define cfi_window_save .cfi_window_save
# define cfi_personality(enc, exp) .cfi_personality enc, exp
# define cfi_lsda(enc, exp) .cfi_lsda enc, exp
# define cfi_escape(...) .cfi_escape __VA_ARGS__
#else
# define cfi_startproc
# define cfi_endproc
# define cfi_def_cfa(reg, off)
# define cfi_def_cfa_register(reg)
# define cfi_def_cfa_offset(off)
# define cfi_adjust_cfa_offset(off)
# define cfi_offset(reg, off)
# define cfi_rel_offset(reg, off)
# define cfi_register(r1, r2)
# define cfi_return_column(reg)
# define cfi_restore(reg)
# define cfi_same_value(reg)
# define cfi_undefined(reg)
# define cfi_remember_state
# define cfi_restore_state
# define cfi_window_save
# define cfi_personality(enc, exp)
# define cfi_lsda(enc, exp)
# define cfi_escape(...)
#endif /* HAVE_AS_CFI_PSEUDO_OP */
#endif /* FFI_CFI_H */
/* -----------------------------------------------------------------------
ffi_common.h - Copyright (C) 2011, 2012, 2013 Anthony Green
Copyright (C) 2007 Free Software Foundation, Inc
Copyright (c) 1996 Red Hat, Inc.
Common internal definitions and macros. Only necessary for building
libffi.
----------------------------------------------------------------------- */
#ifndef FFI_COMMON_H
#define FFI_COMMON_H
#ifdef __cplusplus
extern "C" {
#endif
#include <fficonfig.h>
/* Do not move this. Some versions of AIX are very picky about where
this is positioned. */
#ifdef __GNUC__
# if HAVE_ALLOCA_H
# include <alloca.h>
# else
/* mingw64 defines this already in malloc.h. */
# ifndef alloca
# define alloca __builtin_alloca
# endif
# endif
# define MAYBE_UNUSED __attribute__((__unused__))
#else
# define MAYBE_UNUSED
# if HAVE_ALLOCA_H
# include <alloca.h>
# else
# ifdef _AIX
# pragma alloca
# else
# ifndef alloca /* predefined by HP cc +Olibcalls */
# ifdef _MSC_VER
# define alloca _alloca
# else
char *alloca ();
# endif
# endif
# endif
# endif
#endif
/* Check for the existence of memcpy. */
#if STDC_HEADERS
# include <string.h>
#else
# ifndef HAVE_MEMCPY
# define memcpy(d, s, n) bcopy ((s), (d), (n))
# endif
#endif
#if defined(FFI_DEBUG)
#include <stdio.h>
#endif
#ifdef FFI_DEBUG
void ffi_assert(char *expr, char *file, int line);
void ffi_stop_here(void);
void ffi_type_test(ffi_type *a, char *file, int line);
#define FFI_ASSERT(x) ((x) ? (void)0 : ffi_assert(#x, __FILE__,__LINE__))
#define FFI_ASSERT_AT(x, f, l) ((x) ? 0 : ffi_assert(#x, (f), (l)))
#define FFI_ASSERT_VALID_TYPE(x) ffi_type_test (x, __FILE__, __LINE__)
#else
#define FFI_ASSERT(x)
#define FFI_ASSERT_AT(x, f, l)
#define FFI_ASSERT_VALID_TYPE(x)
#endif
/* v cast to size_t and aligned up to a multiple of a */
#define FFI_ALIGN(v, a) (((((size_t) (v))-1) | ((a)-1))+1)
/* v cast to size_t and aligned down to a multiple of a */
#define FFI_ALIGN_DOWN(v, a) (((size_t) (v)) & -a)
/* Perform machine dependent cif processing */
ffi_status ffi_prep_cif_machdep(ffi_cif *cif);
ffi_status ffi_prep_cif_machdep_var(ffi_cif *cif,
unsigned int nfixedargs, unsigned int ntotalargs);
#if HAVE_LONG_DOUBLE_VARIANT
/* Used to adjust size/alignment of ffi types. */
void ffi_prep_types (ffi_abi abi);
#endif
/* Used internally, but overridden by some architectures */
ffi_status ffi_prep_cif_core(ffi_cif *cif,
ffi_abi abi,
unsigned int isvariadic,
unsigned int nfixedargs,
unsigned int ntotalargs,
ffi_type *rtype,
ffi_type **atypes);
/* Extended cif, used in callback from assembly routine */
typedef struct
{
ffi_cif *cif;
void *rvalue;
void **avalue;
} extended_cif;
/* Terse sized type definitions. */
#if defined(_MSC_VER) || defined(__sgi) || defined(__SUNPRO_C)
typedef unsigned char UINT8;
typedef signed char SINT8;
typedef unsigned short UINT16;
typedef signed short SINT16;
typedef unsigned int UINT32;
typedef signed int SINT32;
# ifdef _MSC_VER
typedef unsigned __int64 UINT64;
typedef signed __int64 SINT64;
# else
# include <inttypes.h>
typedef uint64_t UINT64;
typedef int64_t SINT64;
# endif
#else
typedef unsigned int UINT8 __attribute__((__mode__(__QI__)));
typedef signed int SINT8 __attribute__((__mode__(__QI__)));
typedef unsigned int UINT16 __attribute__((__mode__(__HI__)));
typedef signed int SINT16 __attribute__((__mode__(__HI__)));
typedef unsigned int UINT32 __attribute__((__mode__(__SI__)));
typedef signed int SINT32 __attribute__((__mode__(__SI__)));
typedef unsigned int UINT64 __attribute__((__mode__(__DI__)));
typedef signed int SINT64 __attribute__((__mode__(__DI__)));
#endif
typedef float FLOAT32;
#ifndef __GNUC__
#define __builtin_expect(x, expected_value) (x)
#endif
#define LIKELY(x) __builtin_expect(!!(x),1)
#define UNLIKELY(x) __builtin_expect((x)!=0,0)
#ifdef __cplusplus
}
#endif
#endif
#include "ffi_cxx.h"
FFICallInterface::~FFICallInterface() {
for (FFIClosure *closure : closures_) {
delete closure;
}
delete cif_;
delete types_;
}
void FFIDispatcher(ffi_cif *cif OPTION, void *ret, void **args, void *userdata) {
FFIClosure *closure = reinterpret_cast<FFIClosure *>(userdata);
FFICallback callback = closure->GetCallback();
callback(closure, ret, args, closure->GetUserData());
}
FFIClosure *FFICallInterface::CreateClosure(void *userdata, FFICallback callback) {
std::lock_guard<std::mutex> guard(lock_);
FFIClosure *closure = new FFIClosure(this, userdata, callback);
ffi_prep_closure_loc(closure->closure_, cif_, FFIDispatcher, closure, closure->code_);
closures_.push_back(closure);
return closure;
}
static ffi_type *FFIGetCType(FFIType type) {
switch (type) {
case FFIType::kFFITypeVoid:
return &ffi_type_void;
case FFIType::kFFITypeU1:
return &ffi_type_uint8;
case FFIType::kFFITypeU2:
return &ffi_type_uint16;
case FFIType::kFFITypeU4:
return &ffi_type_uint32;
case FFIType::kFFITypeU8:
return &ffi_type_uint64;
case FFIType::kFFITypeS1:
return &ffi_type_sint8;
case FFIType::kFFITypeS2:
return &ffi_type_sint16;
case FFIType::kFFITypeS4:
return &ffi_type_sint32;
case FFIType::kFFITypeS8:
return &ffi_type_sint64;
case FFIType::kFFITypePointer:
return &ffi_type_pointer;
case FFIType::kFFITypeFloat:
return &ffi_type_float;
case FFIType::kFFITypeDouble:
return &ffi_type_double;
}
}
FFICallInterface *FFICallInterface::FinalizeCif() {
cif_ = new ffi_cif;
types_ = new ffi_type *[parameters_.size()];
int idx = 0;
for (FFIType type : parameters_) {
types_[idx] = FFIGetCType(type);
idx++;
}
ffi_prep_cif(cif_, FFI_DEFAULT_ABI,
(unsigned int) parameters_.size(), FFIGetCType(return_type_), types_);
return this;
}
#ifndef WHALE_FFI_CXX_H_
#define WHALE_FFI_CXX_H_
#include <cstdarg>
#include <list>
#include <mutex>
#include "ffi.h"
#define OPTION __unused
enum class FFIType {
kFFITypeVoid,
kFFITypeU1,
kFFITypeU2,
kFFITypeU4,
kFFITypeU8,
kFFITypeS1,
kFFITypeS2,
kFFITypeS4,
kFFITypeS8,
kFFITypePointer,
kFFITypeFloat,
kFFITypeDouble,
};
class FFICallInterface;
class FFIClosure;
typedef void (*FFICallback)(FFIClosure *closure, void *ret, void **args, void *userdata);
class FFIClosure {
public:
FFIClosure(FFICallInterface *cif, void *userdata, FFICallback callback) : cif_(cif),
userdata_(userdata),
callback_(callback) {
closure_ = reinterpret_cast<ffi_closure *>(ffi_closure_alloc(sizeof(ffi_closure), &code_));
}
~FFIClosure() {
ffi_closure_free(closure_);
}
void *GetCode() {
return code_;
}
void *GetUserData() {
return userdata_;
}
FFICallInterface *GetCif() {
return cif_;
}
FFICallback GetCallback() {
return callback_;
}
private:
friend class FFICallInterface;
FFICallInterface *cif_;
ffi_closure *closure_;
FFICallback callback_;
void *code_;
void *userdata_;
};
class FFICallInterface {
public:
FFICallInterface(const FFIType return_type) : return_type_(return_type) {}
~FFICallInterface();
FFICallInterface *Parameter(const FFIType parameter) {
parameters_.push_back(parameter);
return this;
}
FFICallInterface *Parameters(unsigned int count, ...) {
va_list ap;
va_start(ap, count);
while (count-- > 0) {
Parameter(va_arg(ap, FFIType));
}
va_end(ap);
return this;
}
FFICallInterface *FinalizeCif();
size_t GetParameterCount() {
return parameters_.size();
}
std::list<FFIType> GetParameters() {
return parameters_;
}
FFIClosure *CreateClosure(void *userdata, FFICallback callback);
void RemoveClosure(FFIClosure *closure) {
std::lock_guard<std::mutex> guard(lock_);
closures_.remove(closure);
}
private:
std::mutex lock_;
ffi_cif *cif_;
ffi_type **types_;
std::list<FFIType> parameters_;
const FFIType return_type_;
std::list<FFIClosure *> closures_;
};
#endif //WHALE_FFI_CXX_H_
#if defined(__aarch64__) || defined(__arm64__)
#include <fficonfig_arm64.h>
#endif
#ifdef __i386__
#include <fficonfig_i386.h>
#endif
#ifdef __arm__
#include <fficonfig_armv7.h>
#endif
#ifdef __x86_64__
#include <fficonfig_x86_64.h>
#endif
#ifdef __aarch64__
#include <ffitarget_arm64.h>
#endif
#ifdef __i386__
#include <ffitarget_i386.h>
#endif
#ifdef __arm__
#include <ffitarget_armv7.h>
#endif
#ifdef __x86_64__
#include <ffitarget_x86_64.h>
#endif
/* -----------------------------------------------------------------------
java_raw_api.c - Copyright (c) 1999, 2007, 2008 Red Hat, Inc.
Cloned from raw_api.c
Raw_api.c author: Kresten Krab Thorup <krab@gnu.org>
Java_raw_api.c author: Hans-J. Boehm <hboehm@hpl.hp.com>
$Id $
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
/* This defines a Java- and 64-bit specific variant of the raw API. */
/* It assumes that "raw" argument blocks look like Java stacks on a */
/* 64-bit machine. Arguments that can be stored in a single stack */
/* stack slots (longs, doubles) occupy 128 bits, but only the first */
/* 64 bits are actually used. */
#include <ffi.h>
#include <ffi_common.h>
#include <stdlib.h>
#if !defined(NO_JAVA_RAW_API)
size_t
ffi_java_raw_size (ffi_cif *cif)
{
size_t result = 0;
int i;
ffi_type **at = cif->arg_types;
for (i = cif->nargs-1; i >= 0; i--, at++)
{
switch((*at) -> type) {
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
case FFI_TYPE_DOUBLE:
result += 2 * FFI_SIZEOF_JAVA_RAW;
break;
case FFI_TYPE_STRUCT:
/* No structure parameters in Java. */
abort();
case FFI_TYPE_COMPLEX:
/* Not supported yet. */
abort();
default:
result += FFI_SIZEOF_JAVA_RAW;
}
}
return result;
}
void
ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args)
{
unsigned i;
ffi_type **tp = cif->arg_types;
#if WORDS_BIGENDIAN
for (i = 0; i < cif->nargs; i++, tp++, args++)
{
switch ((*tp)->type)
{
case FFI_TYPE_UINT8:
case FFI_TYPE_SINT8:
*args = (void*) ((char*)(raw++) + 3);
break;
case FFI_TYPE_UINT16:
case FFI_TYPE_SINT16:
*args = (void*) ((char*)(raw++) + 2);
break;
#if FFI_SIZEOF_JAVA_RAW == 8
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
case FFI_TYPE_DOUBLE:
*args = (void *)raw;
raw += 2;
break;
#endif
case FFI_TYPE_POINTER:
*args = (void*) &(raw++)->ptr;
break;
case FFI_TYPE_COMPLEX:
/* Not supported yet. */
abort();
default:
*args = raw;
raw +=
FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw);
}
}
#else /* WORDS_BIGENDIAN */
#if !PDP
/* then assume little endian */
for (i = 0; i < cif->nargs; i++, tp++, args++)
{
#if FFI_SIZEOF_JAVA_RAW == 8
switch((*tp)->type) {
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
case FFI_TYPE_DOUBLE:
*args = (void*) raw;
raw += 2;
break;
case FFI_TYPE_COMPLEX:
/* Not supported yet. */
abort();
default:
*args = (void*) raw++;
}
#else /* FFI_SIZEOF_JAVA_RAW != 8 */
*args = (void*) raw;
raw +=
FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw);
#endif /* FFI_SIZEOF_JAVA_RAW == 8 */
}
#else
#error "pdp endian not supported"
#endif /* ! PDP */
#endif /* WORDS_BIGENDIAN */
}
void
ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw)
{
unsigned i;
ffi_type **tp = cif->arg_types;
for (i = 0; i < cif->nargs; i++, tp++, args++)
{
switch ((*tp)->type)
{
case FFI_TYPE_UINT8:
#if WORDS_BIGENDIAN
*(UINT32*)(raw++) = *(UINT8*) (*args);
#else
(raw++)->uint = *(UINT8*) (*args);
#endif
break;
case FFI_TYPE_SINT8:
#if WORDS_BIGENDIAN
*(SINT32*)(raw++) = *(SINT8*) (*args);
#else
(raw++)->sint = *(SINT8*) (*args);
#endif
break;
case FFI_TYPE_UINT16:
#if WORDS_BIGENDIAN
*(UINT32*)(raw++) = *(UINT16*) (*args);
#else
(raw++)->uint = *(UINT16*) (*args);
#endif
break;
case FFI_TYPE_SINT16:
#if WORDS_BIGENDIAN
*(SINT32*)(raw++) = *(SINT16*) (*args);
#else
(raw++)->sint = *(SINT16*) (*args);
#endif
break;
case FFI_TYPE_UINT32:
#if WORDS_BIGENDIAN
*(UINT32*)(raw++) = *(UINT32*) (*args);
#else
(raw++)->uint = *(UINT32*) (*args);
#endif
break;
case FFI_TYPE_SINT32:
#if WORDS_BIGENDIAN
*(SINT32*)(raw++) = *(SINT32*) (*args);
#else
(raw++)->sint = *(SINT32*) (*args);
#endif
break;
case FFI_TYPE_FLOAT:
(raw++)->flt = *(FLOAT32*) (*args);
break;
#if FFI_SIZEOF_JAVA_RAW == 8
case FFI_TYPE_UINT64:
case FFI_TYPE_SINT64:
case FFI_TYPE_DOUBLE:
raw->uint = *(UINT64*) (*args);
raw += 2;
break;
#endif
case FFI_TYPE_POINTER:
(raw++)->ptr = **(void***) args;
break;
default:
#if FFI_SIZEOF_JAVA_RAW == 8
FFI_ASSERT(0); /* Should have covered all cases */
#else
memcpy ((void*) raw->data, (void*)*args, (*tp)->size);
raw +=
FFI_ALIGN ((*tp)->size, sizeof(ffi_java_raw)) / sizeof(ffi_java_raw);
#endif
}
}
}
#if !FFI_NATIVE_RAW_API
static void
ffi_java_rvalue_to_raw (ffi_cif *cif, void *rvalue)
{
#if WORDS_BIGENDIAN && FFI_SIZEOF_ARG == 8
switch (cif->rtype->type)
{
case FFI_TYPE_UINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_UINT32:
*(UINT64 *)rvalue <<= 32;
break;
case FFI_TYPE_SINT8:
case FFI_TYPE_SINT16:
case FFI_TYPE_SINT32:
case FFI_TYPE_INT:
#if FFI_SIZEOF_JAVA_RAW == 4
case FFI_TYPE_POINTER:
#endif
*(SINT64 *)rvalue <<= 32;
break;
case FFI_TYPE_COMPLEX:
/* Not supported yet. */
abort();
default:
break;
}
#endif
}
static void
ffi_java_raw_to_rvalue (ffi_cif *cif, void *rvalue)
{
#if WORDS_BIGENDIAN && FFI_SIZEOF_ARG == 8
switch (cif->rtype->type)
{
case FFI_TYPE_UINT8:
case FFI_TYPE_UINT16:
case FFI_TYPE_UINT32:
*(UINT64 *)rvalue >>= 32;
break;
case FFI_TYPE_SINT8:
case FFI_TYPE_SINT16:
case FFI_TYPE_SINT32:
case FFI_TYPE_INT:
*(SINT64 *)rvalue >>= 32;
break;
case FFI_TYPE_COMPLEX:
/* Not supported yet. */
abort();
default:
break;
}
#endif
}
/* This is a generic definition of ffi_raw_call, to be used if the
* native system does not provide a machine-specific implementation.
* Having this, allows code to be written for the raw API, without
* the need for system-specific code to handle input in that format;
* these following couple of functions will handle the translation forth
* and back automatically. */
void ffi_java_raw_call (ffi_cif *cif, void (*fn)(void), void *rvalue,
ffi_java_raw *raw)
{
void **avalue = (void**) alloca (cif->nargs * sizeof (void*));
ffi_java_raw_to_ptrarray (cif, raw, avalue);
ffi_call (cif, fn, rvalue, avalue);
ffi_java_rvalue_to_raw (cif, rvalue);
}
#if FFI_CLOSURES /* base system provides closures */
static void
ffi_java_translate_args (ffi_cif *cif, void *rvalue,
void **avalue, void *user_data)
{
ffi_java_raw *raw = (ffi_java_raw*)alloca (ffi_java_raw_size (cif));
ffi_raw_closure *cl = (ffi_raw_closure*)user_data;
ffi_java_ptrarray_to_raw (cif, avalue, raw);
(*cl->fun) (cif, rvalue, (ffi_raw*)raw, cl->user_data);
ffi_java_raw_to_rvalue (cif, rvalue);
}
ffi_status
ffi_prep_java_raw_closure_loc (ffi_java_raw_closure* cl,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
void *user_data,
void *codeloc)
{
ffi_status status;
status = ffi_prep_closure_loc ((ffi_closure*) cl,
cif,
&ffi_java_translate_args,
codeloc,
codeloc);
if (status == FFI_OK)
{
cl->fun = fun;
cl->user_data = user_data;
}
return status;
}
/* Again, here is the generic version of ffi_prep_raw_closure, which
* will install an intermediate "hub" for translation of arguments from
* the pointer-array format, to the raw format */
ffi_status
ffi_prep_java_raw_closure (ffi_java_raw_closure* cl,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
void *user_data)
{
return ffi_prep_java_raw_closure_loc (cl, cif, fun, user_data, cl);
}
#endif /* FFI_CLOSURES */
#endif /* !FFI_NATIVE_RAW_API */
#endif /* !NO_JAVA_RAW_API */
#if defined(__aarch64__) || defined(__arm64__)
/* -----------------------------------------------------------------*-C-*-
libffi 3.3-rc0 - Copyright (c) 2011, 2014 Anthony Green
- Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the ``Software''), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
/* -------------------------------------------------------------------
Most of the API is documented in doc/libffi.texi.
The raw API is designed to bypass some of the argument packing and
unpacking on architectures for which it can be avoided. Routines
are provided to emulate the raw API if the underlying platform
doesn't allow faster implementation.
More details on the raw API can be found in:
http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
and
http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
-------------------------------------------------------------------- */
#ifndef LIBFFI_H
#define LIBFFI_H
#ifdef __cplusplus
extern "C" {
#endif
/* Specify which architecture libffi is configured for. */
#ifndef AARCH64
#define AARCH64
#endif
/* ---- System configuration information --------------------------------- */
#include <ffitarget.h>
#ifndef LIBFFI_ASM
#if defined(_MSC_VER) && !defined(__clang__)
#define __attribute__(X)
#endif
#include <stddef.h>
#include <limits.h>
/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
But we can find it either under the correct ANSI name, or under GNU
C's internal name. */
#define FFI_64_BIT_MAX 9223372036854775807
#ifdef LONG_LONG_MAX
# define FFI_LONG_LONG_MAX LONG_LONG_MAX
#else
# ifdef LLONG_MAX
# define FFI_LONG_LONG_MAX LLONG_MAX
# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
# undef FFI_64_BIT_MAX
# define FFI_64_BIT_MAX 9223372036854775807LL
# endif /* _AIX52 or newer */
# else
# ifdef __GNUC__
# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
# endif
# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
# ifndef __PPC64__
# if defined (__IBMC__) || defined (__IBMCPP__)
# define FFI_LONG_LONG_MAX LONGLONG_MAX
# endif
# endif /* __PPC64__ */
# undef FFI_64_BIT_MAX
# define FFI_64_BIT_MAX 9223372036854775807LL
# endif
# endif
#endif
/* The closure code assumes that this works on pointers, i.e. a size_t
can hold a pointer. */
typedef struct _ffi_type
{
size_t size;
unsigned short alignment;
unsigned short type;
struct _ffi_type **elements;
} ffi_type;
/* Need minimal decorations for DLLs to work on Windows. GCC has
autoimport and autoexport. Always mark externally visible symbols
as dllimport for MSVC clients, even if it means an extra indirection
when using the static version of the library.
Besides, as a workaround, they can define FFI_BUILDING if they
*know* they are going to link with the static library. */
#if defined _MSC_VER
# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
# define FFI_API __declspec(dllexport)
# elif !defined FFI_BUILDING /* Importing libffi.DLL */
# define FFI_API __declspec(dllimport)
# else /* Building/linking static library */
# define FFI_API
# endif
#else
# define FFI_API
#endif
/* The externally visible type declarations also need the MSVC DLL
decorations, or they will not be exported from the object file. */
#if defined LIBFFI_HIDE_BASIC_TYPES
# define FFI_EXTERN FFI_API
#else
# define FFI_EXTERN extern FFI_API
#endif
#ifndef LIBFFI_HIDE_BASIC_TYPES
#if SCHAR_MAX == 127
# define ffi_type_uchar ffi_type_uint8
# define ffi_type_schar ffi_type_sint8
#else
#error "char size not supported"
#endif
#if SHRT_MAX == 32767
# define ffi_type_ushort ffi_type_uint16
# define ffi_type_sshort ffi_type_sint16
#elif SHRT_MAX == 2147483647
# define ffi_type_ushort ffi_type_uint32
# define ffi_type_sshort ffi_type_sint32
#else
#error "short size not supported"
#endif
#if INT_MAX == 32767
# define ffi_type_uint ffi_type_uint16
# define ffi_type_sint ffi_type_sint16
#elif INT_MAX == 2147483647
# define ffi_type_uint ffi_type_uint32
# define ffi_type_sint ffi_type_sint32
#elif INT_MAX == 9223372036854775807
# define ffi_type_uint ffi_type_uint64
# define ffi_type_sint ffi_type_sint64
#else
#error "int size not supported"
#endif
#if LONG_MAX == 2147483647
# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
#error "no 64-bit data type supported"
# endif
#elif LONG_MAX != FFI_64_BIT_MAX
#error "long size not supported"
#endif
#if LONG_MAX == 2147483647
# define ffi_type_ulong ffi_type_uint32
# define ffi_type_slong ffi_type_sint32
#elif LONG_MAX == FFI_64_BIT_MAX
# define ffi_type_ulong ffi_type_uint64
# define ffi_type_slong ffi_type_sint64
#else
#error "long size not supported"
#endif
/* These are defined in types.c. */
FFI_EXTERN ffi_type ffi_type_void;
FFI_EXTERN ffi_type ffi_type_uint8;
FFI_EXTERN ffi_type ffi_type_sint8;
FFI_EXTERN ffi_type ffi_type_uint16;
FFI_EXTERN ffi_type ffi_type_sint16;
FFI_EXTERN ffi_type ffi_type_uint32;
FFI_EXTERN ffi_type ffi_type_sint32;
FFI_EXTERN ffi_type ffi_type_uint64;
FFI_EXTERN ffi_type ffi_type_sint64;
FFI_EXTERN ffi_type ffi_type_float;
FFI_EXTERN ffi_type ffi_type_double;
FFI_EXTERN ffi_type ffi_type_pointer;
#if 1
FFI_EXTERN ffi_type ffi_type_longdouble;
#else
#define ffi_type_longdouble ffi_type_double
#endif
#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
FFI_EXTERN ffi_type ffi_type_complex_float;
FFI_EXTERN ffi_type ffi_type_complex_double;
#if 1
FFI_EXTERN ffi_type ffi_type_complex_longdouble;
#else
#define ffi_type_complex_longdouble ffi_type_complex_double
#endif
#endif
#endif /* LIBFFI_HIDE_BASIC_TYPES */
typedef enum {
FFI_OK = 0,
FFI_BAD_TYPEDEF,
FFI_BAD_ABI
} ffi_status;
typedef struct {
ffi_abi abi;
unsigned nargs;
ffi_type **arg_types;
ffi_type *rtype;
unsigned bytes;
unsigned flags;
#ifdef FFI_EXTRA_CIF_FIELDS
FFI_EXTRA_CIF_FIELDS;
#endif
} ffi_cif;
/* ---- Definitions for the raw API -------------------------------------- */
#ifndef FFI_SIZEOF_ARG
# if LONG_MAX == 2147483647
# define FFI_SIZEOF_ARG 4
# elif LONG_MAX == FFI_64_BIT_MAX
# define FFI_SIZEOF_ARG 8
# endif
#endif
#ifndef FFI_SIZEOF_JAVA_RAW
# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
#endif
typedef union {
ffi_sarg sint;
ffi_arg uint;
float flt;
char data[FFI_SIZEOF_ARG];
void* ptr;
} ffi_raw;
#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
/* This is a special case for mips64/n32 ABI (and perhaps others) where
sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
typedef union {
signed int sint;
unsigned int uint;
float flt;
char data[FFI_SIZEOF_JAVA_RAW];
void* ptr;
} ffi_java_raw;
#else
typedef ffi_raw ffi_java_raw;
#endif
FFI_API
void ffi_raw_call (ffi_cif *cif,
void (*fn)(void),
void *rvalue,
ffi_raw *avalue);
FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
FFI_API size_t ffi_raw_size (ffi_cif *cif);
/* This is analogous to the raw API, except it uses Java parameter
packing, even on 64-bit machines. I.e. on 64-bit machines longs
and doubles are followed by an empty 64-bit word. */
FFI_API
void ffi_java_raw_call (ffi_cif *cif,
void (*fn)(void),
void *rvalue,
ffi_java_raw *avalue);
FFI_API
void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw);
FFI_API
void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args);
FFI_API
size_t ffi_java_raw_size (ffi_cif *cif);
/* ---- Definitions for closures ----------------------------------------- */
#if FFI_CLOSURES
#ifdef _MSC_VER
__declspec(align(8))
#endif
typedef struct {
#if FFI_EXEC_TRAMPOLINE_TABLE
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
void (*fun)(ffi_cif*,void*,void**,void*);
void *user_data;
} ffi_closure
#ifdef __GNUC__
__attribute__((aligned (8)))
#endif
;
#ifndef __GNUC__
# ifdef __sgi
# pragma pack 0
# endif
#endif
FFI_API void *ffi_closure_alloc (size_t size, void **code);
FFI_API void ffi_closure_free (void *);
FFI_API ffi_status
ffi_prep_closure (ffi_closure*,
ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data)
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
__attribute__((deprecated ("use ffi_prep_closure_loc instead")))
#elif defined(__GNUC__) && __GNUC__ >= 3
__attribute__((deprecated))
#endif
;
FFI_API ffi_status
ffi_prep_closure_loc (ffi_closure*,
ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data,
void*codeloc);
#ifdef __sgi
# pragma pack 8
#endif
typedef struct {
#if FFI_EXEC_TRAMPOLINE_TABLE
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
#if !FFI_NATIVE_RAW_API
/* If this is enabled, then a raw closure has the same layout
as a regular closure. We use this to install an intermediate
handler to do the transaltion, void** -> ffi_raw*. */
void (*translate_args)(ffi_cif*,void*,void**,void*);
void *this_closure;
#endif
void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
void *user_data;
} ffi_raw_closure;
typedef struct {
#if FFI_EXEC_TRAMPOLINE_TABLE
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
#if !FFI_NATIVE_RAW_API
/* If this is enabled, then a raw closure has the same layout
as a regular closure. We use this to install an intermediate
handler to do the translation, void** -> ffi_raw*. */
void (*translate_args)(ffi_cif*,void*,void**,void*);
void *this_closure;
#endif
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
void *user_data;
} ffi_java_raw_closure;
FFI_API ffi_status
ffi_prep_raw_closure (ffi_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
void *user_data);
FFI_API ffi_status
ffi_prep_raw_closure_loc (ffi_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
void *user_data,
void *codeloc);
FFI_API ffi_status
ffi_prep_java_raw_closure (ffi_java_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
void *user_data);
FFI_API ffi_status
ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
void *user_data,
void *codeloc);
#endif /* FFI_CLOSURES */
#if FFI_GO_CLOSURES
typedef struct {
void *tramp;
ffi_cif *cif;
void (*fun)(ffi_cif*,void*,void**,void*);
} ffi_go_closure;
FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*));
FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
void **avalue, void *closure);
#endif /* FFI_GO_CLOSURES */
/* ---- Public interface definition -------------------------------------- */
FFI_API
ffi_status ffi_prep_cif(ffi_cif *cif,
ffi_abi abi,
unsigned int nargs,
ffi_type *rtype,
ffi_type **atypes);
FFI_API
ffi_status ffi_prep_cif_var(ffi_cif *cif,
ffi_abi abi,
unsigned int nfixedargs,
unsigned int ntotalargs,
ffi_type *rtype,
ffi_type **atypes);
FFI_API
void ffi_call(ffi_cif *cif,
void (*fn)(void),
void *rvalue,
void **avalue);
FFI_API
ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
size_t *offsets);
/* Useful for eliminating compiler warnings. */
#define FFI_FN(f) ((void (*)(void))f)
/* ---- Definitions shared with assembly code ---------------------------- */
#endif
/* If these change, update src/mips/ffitarget.h. */
#define FFI_TYPE_VOID 0
#define FFI_TYPE_INT 1
#define FFI_TYPE_FLOAT 2
#define FFI_TYPE_DOUBLE 3
#if 1
#define FFI_TYPE_LONGDOUBLE 4
#else
#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
#endif
#define FFI_TYPE_UINT8 5
#define FFI_TYPE_SINT8 6
#define FFI_TYPE_UINT16 7
#define FFI_TYPE_SINT16 8
#define FFI_TYPE_UINT32 9
#define FFI_TYPE_SINT32 10
#define FFI_TYPE_UINT64 11
#define FFI_TYPE_SINT64 12
#define FFI_TYPE_STRUCT 13
#define FFI_TYPE_POINTER 14
#define FFI_TYPE_COMPLEX 15
/* This should always refer to the last type code (for sanity checks). */
#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
#ifdef __cplusplus
}
#endif
#endif
#endif
\ No newline at end of file
#ifdef __arm__
/* -----------------------------------------------------------------*-C-*-
libffi 3.3-rc0 - Copyright (c) 2011, 2014 Anthony Green
- Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the ``Software''), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
/* -------------------------------------------------------------------
Most of the API is documented in doc/libffi.texi.
The raw API is designed to bypass some of the argument packing and
unpacking on architectures for which it can be avoided. Routines
are provided to emulate the raw API if the underlying platform
doesn't allow faster implementation.
More details on the raw API can be found in:
http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
and
http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
-------------------------------------------------------------------- */
#ifndef LIBFFI_H
#define LIBFFI_H
#ifdef __cplusplus
extern "C" {
#endif
/* Specify which architecture libffi is configured for. */
#ifndef ARM
#define ARM
#endif
/* ---- System configuration information --------------------------------- */
#include <ffitarget.h>
#ifndef LIBFFI_ASM
#if defined(_MSC_VER) && !defined(__clang__)
#define __attribute__(X)
#endif
#include <stddef.h>
#include <limits.h>
/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
But we can find it either under the correct ANSI name, or under GNU
C's internal name. */
#define FFI_64_BIT_MAX 9223372036854775807
#ifdef LONG_LONG_MAX
# define FFI_LONG_LONG_MAX LONG_LONG_MAX
#else
# ifdef LLONG_MAX
# define FFI_LONG_LONG_MAX LLONG_MAX
# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
# undef FFI_64_BIT_MAX
# define FFI_64_BIT_MAX 9223372036854775807LL
# endif /* _AIX52 or newer */
# else
# ifdef __GNUC__
# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
# endif
# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
# ifndef __PPC64__
# if defined (__IBMC__) || defined (__IBMCPP__)
# define FFI_LONG_LONG_MAX LONGLONG_MAX
# endif
# endif /* __PPC64__ */
# undef FFI_64_BIT_MAX
# define FFI_64_BIT_MAX 9223372036854775807LL
# endif
# endif
#endif
/* The closure code assumes that this works on pointers, i.e. a size_t
can hold a pointer. */
typedef struct _ffi_type
{
size_t size;
unsigned short alignment;
unsigned short type;
struct _ffi_type **elements;
} ffi_type;
/* Need minimal decorations for DLLs to work on Windows. GCC has
autoimport and autoexport. Always mark externally visible symbols
as dllimport for MSVC clients, even if it means an extra indirection
when using the static version of the library.
Besides, as a workaround, they can define FFI_BUILDING if they
*know* they are going to link with the static library. */
#if defined _MSC_VER
# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
# define FFI_API __declspec(dllexport)
# elif !defined FFI_BUILDING /* Importing libffi.DLL */
# define FFI_API __declspec(dllimport)
# else /* Building/linking static library */
# define FFI_API
# endif
#else
# define FFI_API
#endif
/* The externally visible type declarations also need the MSVC DLL
decorations, or they will not be exported from the object file. */
#if defined LIBFFI_HIDE_BASIC_TYPES
# define FFI_EXTERN FFI_API
#else
# define FFI_EXTERN extern FFI_API
#endif
#ifndef LIBFFI_HIDE_BASIC_TYPES
#if SCHAR_MAX == 127
# define ffi_type_uchar ffi_type_uint8
# define ffi_type_schar ffi_type_sint8
#else
#error "char size not supported"
#endif
#if SHRT_MAX == 32767
# define ffi_type_ushort ffi_type_uint16
# define ffi_type_sshort ffi_type_sint16
#elif SHRT_MAX == 2147483647
# define ffi_type_ushort ffi_type_uint32
# define ffi_type_sshort ffi_type_sint32
#else
#error "short size not supported"
#endif
#if INT_MAX == 32767
# define ffi_type_uint ffi_type_uint16
# define ffi_type_sint ffi_type_sint16
#elif INT_MAX == 2147483647
# define ffi_type_uint ffi_type_uint32
# define ffi_type_sint ffi_type_sint32
#elif INT_MAX == 9223372036854775807
# define ffi_type_uint ffi_type_uint64
# define ffi_type_sint ffi_type_sint64
#else
#error "int size not supported"
#endif
#if LONG_MAX == 2147483647
# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
#error "no 64-bit data type supported"
# endif
#elif LONG_MAX != FFI_64_BIT_MAX
#error "long size not supported"
#endif
#if LONG_MAX == 2147483647
# define ffi_type_ulong ffi_type_uint32
# define ffi_type_slong ffi_type_sint32
#elif LONG_MAX == FFI_64_BIT_MAX
# define ffi_type_ulong ffi_type_uint64
# define ffi_type_slong ffi_type_sint64
#else
#error "long size not supported"
#endif
/* These are defined in types.c. */
FFI_EXTERN ffi_type ffi_type_void;
FFI_EXTERN ffi_type ffi_type_uint8;
FFI_EXTERN ffi_type ffi_type_sint8;
FFI_EXTERN ffi_type ffi_type_uint16;
FFI_EXTERN ffi_type ffi_type_sint16;
FFI_EXTERN ffi_type ffi_type_uint32;
FFI_EXTERN ffi_type ffi_type_sint32;
FFI_EXTERN ffi_type ffi_type_uint64;
FFI_EXTERN ffi_type ffi_type_sint64;
FFI_EXTERN ffi_type ffi_type_float;
FFI_EXTERN ffi_type ffi_type_double;
FFI_EXTERN ffi_type ffi_type_pointer;
#if 1
FFI_EXTERN ffi_type ffi_type_longdouble;
#else
#define ffi_type_longdouble ffi_type_double
#endif
#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
FFI_EXTERN ffi_type ffi_type_complex_float;
FFI_EXTERN ffi_type ffi_type_complex_double;
#if 1
FFI_EXTERN ffi_type ffi_type_complex_longdouble;
#else
#define ffi_type_complex_longdouble ffi_type_complex_double
#endif
#endif
#endif /* LIBFFI_HIDE_BASIC_TYPES */
typedef enum {
FFI_OK = 0,
FFI_BAD_TYPEDEF,
FFI_BAD_ABI
} ffi_status;
typedef struct {
ffi_abi abi;
unsigned nargs;
ffi_type **arg_types;
ffi_type *rtype;
unsigned bytes;
unsigned flags;
#ifdef FFI_EXTRA_CIF_FIELDS
FFI_EXTRA_CIF_FIELDS;
#endif
} ffi_cif;
/* ---- Definitions for the raw API -------------------------------------- */
#ifndef FFI_SIZEOF_ARG
# if LONG_MAX == 2147483647
# define FFI_SIZEOF_ARG 4
# elif LONG_MAX == FFI_64_BIT_MAX
# define FFI_SIZEOF_ARG 8
# endif
#endif
#ifndef FFI_SIZEOF_JAVA_RAW
# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
#endif
typedef union {
ffi_sarg sint;
ffi_arg uint;
float flt;
char data[FFI_SIZEOF_ARG];
void* ptr;
} ffi_raw;
#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
/* This is a special case for mips64/n32 ABI (and perhaps others) where
sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
typedef union {
signed int sint;
unsigned int uint;
float flt;
char data[FFI_SIZEOF_JAVA_RAW];
void* ptr;
} ffi_java_raw;
#else
typedef ffi_raw ffi_java_raw;
#endif
FFI_API
void ffi_raw_call (ffi_cif *cif,
void (*fn)(void),
void *rvalue,
ffi_raw *avalue);
FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
FFI_API size_t ffi_raw_size (ffi_cif *cif);
/* This is analogous to the raw API, except it uses Java parameter
packing, even on 64-bit machines. I.e. on 64-bit machines longs
and doubles are followed by an empty 64-bit word. */
FFI_API
void ffi_java_raw_call (ffi_cif *cif,
void (*fn)(void),
void *rvalue,
ffi_java_raw *avalue);
FFI_API
void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw);
FFI_API
void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args);
FFI_API
size_t ffi_java_raw_size (ffi_cif *cif);
/* ---- Definitions for closures ----------------------------------------- */
#if FFI_CLOSURES
#ifdef _MSC_VER
__declspec(align(8))
#endif
typedef struct {
#if FFI_EXEC_TRAMPOLINE_TABLE
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
void (*fun)(ffi_cif*,void*,void**,void*);
void *user_data;
} ffi_closure
#ifdef __GNUC__
__attribute__((aligned (8)))
#endif
;
#ifndef __GNUC__
# ifdef __sgi
# pragma pack 0
# endif
#endif
FFI_API void *ffi_closure_alloc (size_t size, void **code);
FFI_API void ffi_closure_free (void *);
FFI_API ffi_status
ffi_prep_closure (ffi_closure*,
ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data)
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
__attribute__((deprecated ("use ffi_prep_closure_loc instead")))
#elif defined(__GNUC__) && __GNUC__ >= 3
__attribute__((deprecated))
#endif
;
FFI_API ffi_status
ffi_prep_closure_loc (ffi_closure*,
ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data,
void*codeloc);
#ifdef __sgi
# pragma pack 8
#endif
typedef struct {
#if FFI_EXEC_TRAMPOLINE_TABLE
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
#if !FFI_NATIVE_RAW_API
/* If this is enabled, then a raw closure has the same layout
as a regular closure. We use this to install an intermediate
handler to do the transaltion, void** -> ffi_raw*. */
void (*translate_args)(ffi_cif*,void*,void**,void*);
void *this_closure;
#endif
void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
void *user_data;
} ffi_raw_closure;
typedef struct {
#if FFI_EXEC_TRAMPOLINE_TABLE
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
#if !FFI_NATIVE_RAW_API
/* If this is enabled, then a raw closure has the same layout
as a regular closure. We use this to install an intermediate
handler to do the translation, void** -> ffi_raw*. */
void (*translate_args)(ffi_cif*,void*,void**,void*);
void *this_closure;
#endif
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
void *user_data;
} ffi_java_raw_closure;
FFI_API ffi_status
ffi_prep_raw_closure (ffi_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
void *user_data);
FFI_API ffi_status
ffi_prep_raw_closure_loc (ffi_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
void *user_data,
void *codeloc);
FFI_API ffi_status
ffi_prep_java_raw_closure (ffi_java_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
void *user_data);
FFI_API ffi_status
ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
void *user_data,
void *codeloc);
#endif /* FFI_CLOSURES */
#if FFI_GO_CLOSURES
typedef struct {
void *tramp;
ffi_cif *cif;
void (*fun)(ffi_cif*,void*,void**,void*);
} ffi_go_closure;
FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*));
FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
void **avalue, void *closure);
#endif /* FFI_GO_CLOSURES */
/* ---- Public interface definition -------------------------------------- */
FFI_API
ffi_status ffi_prep_cif(ffi_cif *cif,
ffi_abi abi,
unsigned int nargs,
ffi_type *rtype,
ffi_type **atypes);
FFI_API
ffi_status ffi_prep_cif_var(ffi_cif *cif,
ffi_abi abi,
unsigned int nfixedargs,
unsigned int ntotalargs,
ffi_type *rtype,
ffi_type **atypes);
FFI_API
void ffi_call(ffi_cif *cif,
void (*fn)(void),
void *rvalue,
void **avalue);
FFI_API
ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
size_t *offsets);
/* Useful for eliminating compiler warnings. */
#define FFI_FN(f) ((void (*)(void))f)
/* ---- Definitions shared with assembly code ---------------------------- */
#endif
/* If these change, update src/mips/ffitarget.h. */
#define FFI_TYPE_VOID 0
#define FFI_TYPE_INT 1
#define FFI_TYPE_FLOAT 2
#define FFI_TYPE_DOUBLE 3
#if 1
#define FFI_TYPE_LONGDOUBLE 4
#else
#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
#endif
#define FFI_TYPE_UINT8 5
#define FFI_TYPE_SINT8 6
#define FFI_TYPE_UINT16 7
#define FFI_TYPE_SINT16 8
#define FFI_TYPE_UINT32 9
#define FFI_TYPE_SINT32 10
#define FFI_TYPE_UINT64 11
#define FFI_TYPE_SINT64 12
#define FFI_TYPE_STRUCT 13
#define FFI_TYPE_POINTER 14
#define FFI_TYPE_COMPLEX 15
/* This should always refer to the last type code (for sanity checks). */
#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
#ifdef __cplusplus
}
#endif
#endif
#endif
\ No newline at end of file
#ifdef __i386__
/* -----------------------------------------------------------------*-C-*-
libffi 3.3-rc0 - Copyright (c) 2011, 2014 Anthony Green
- Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the ``Software''), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
/* -------------------------------------------------------------------
Most of the API is documented in doc/libffi.texi.
The raw API is designed to bypass some of the argument packing and
unpacking on architectures for which it can be avoided. Routines
are provided to emulate the raw API if the underlying platform
doesn't allow faster implementation.
More details on the raw API can be found in:
http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
and
http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
-------------------------------------------------------------------- */
#ifndef LIBFFI_H
#define LIBFFI_H
#ifdef __cplusplus
extern "C" {
#endif
/* Specify which architecture libffi is configured for. */
#ifndef X86_UNIX
#define X86_UNIX
#endif
/* ---- System configuration information --------------------------------- */
#include <ffitarget.h>
#ifndef LIBFFI_ASM
#if defined(_MSC_VER) && !defined(__clang__)
#define __attribute__(X)
#endif
#include <stddef.h>
#include <limits.h>
/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
But we can find it either under the correct ANSI name, or under GNU
C's internal name. */
#define FFI_64_BIT_MAX 9223372036854775807
#ifdef LONG_LONG_MAX
# define FFI_LONG_LONG_MAX LONG_LONG_MAX
#else
# ifdef LLONG_MAX
# define FFI_LONG_LONG_MAX LLONG_MAX
# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
# undef FFI_64_BIT_MAX
# define FFI_64_BIT_MAX 9223372036854775807LL
# endif /* _AIX52 or newer */
# else
# ifdef __GNUC__
# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
# endif
# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
# ifndef __PPC64__
# if defined (__IBMC__) || defined (__IBMCPP__)
# define FFI_LONG_LONG_MAX LONGLONG_MAX
# endif
# endif /* __PPC64__ */
# undef FFI_64_BIT_MAX
# define FFI_64_BIT_MAX 9223372036854775807LL
# endif
# endif
#endif
/* The closure code assumes that this works on pointers, i.e. a size_t
can hold a pointer. */
typedef struct _ffi_type
{
size_t size;
unsigned short alignment;
unsigned short type;
struct _ffi_type **elements;
} ffi_type;
/* Need minimal decorations for DLLs to work on Windows. GCC has
autoimport and autoexport. Always mark externally visible symbols
as dllimport for MSVC clients, even if it means an extra indirection
when using the static version of the library.
Besides, as a workaround, they can define FFI_BUILDING if they
*know* they are going to link with the static library. */
#if defined _MSC_VER
# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
# define FFI_API __declspec(dllexport)
# elif !defined FFI_BUILDING /* Importing libffi.DLL */
# define FFI_API __declspec(dllimport)
# else /* Building/linking static library */
# define FFI_API
# endif
#else
# define FFI_API
#endif
/* The externally visible type declarations also need the MSVC DLL
decorations, or they will not be exported from the object file. */
#if defined LIBFFI_HIDE_BASIC_TYPES
# define FFI_EXTERN FFI_API
#else
# define FFI_EXTERN extern FFI_API
#endif
#ifndef LIBFFI_HIDE_BASIC_TYPES
#if SCHAR_MAX == 127
# define ffi_type_uchar ffi_type_uint8
# define ffi_type_schar ffi_type_sint8
#else
#error "char size not supported"
#endif
#if SHRT_MAX == 32767
# define ffi_type_ushort ffi_type_uint16
# define ffi_type_sshort ffi_type_sint16
#elif SHRT_MAX == 2147483647
# define ffi_type_ushort ffi_type_uint32
# define ffi_type_sshort ffi_type_sint32
#else
#error "short size not supported"
#endif
#if INT_MAX == 32767
# define ffi_type_uint ffi_type_uint16
# define ffi_type_sint ffi_type_sint16
#elif INT_MAX == 2147483647
# define ffi_type_uint ffi_type_uint32
# define ffi_type_sint ffi_type_sint32
#elif INT_MAX == 9223372036854775807
# define ffi_type_uint ffi_type_uint64
# define ffi_type_sint ffi_type_sint64
#else
#error "int size not supported"
#endif
#if LONG_MAX == 2147483647
# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
#error "no 64-bit data type supported"
# endif
#elif LONG_MAX != FFI_64_BIT_MAX
#error "long size not supported"
#endif
#if LONG_MAX == 2147483647
# define ffi_type_ulong ffi_type_uint32
# define ffi_type_slong ffi_type_sint32
#elif LONG_MAX == FFI_64_BIT_MAX
# define ffi_type_ulong ffi_type_uint64
# define ffi_type_slong ffi_type_sint64
#else
#error "long size not supported"
#endif
/* These are defined in types.c. */
FFI_EXTERN ffi_type ffi_type_void;
FFI_EXTERN ffi_type ffi_type_uint8;
FFI_EXTERN ffi_type ffi_type_sint8;
FFI_EXTERN ffi_type ffi_type_uint16;
FFI_EXTERN ffi_type ffi_type_sint16;
FFI_EXTERN ffi_type ffi_type_uint32;
FFI_EXTERN ffi_type ffi_type_sint32;
FFI_EXTERN ffi_type ffi_type_uint64;
FFI_EXTERN ffi_type ffi_type_sint64;
FFI_EXTERN ffi_type ffi_type_float;
FFI_EXTERN ffi_type ffi_type_double;
FFI_EXTERN ffi_type ffi_type_pointer;
#if 1
FFI_EXTERN ffi_type ffi_type_longdouble;
#else
#define ffi_type_longdouble ffi_type_double
#endif
#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
FFI_EXTERN ffi_type ffi_type_complex_float;
FFI_EXTERN ffi_type ffi_type_complex_double;
#if 1
FFI_EXTERN ffi_type ffi_type_complex_longdouble;
#else
#define ffi_type_complex_longdouble ffi_type_complex_double
#endif
#endif
#endif /* LIBFFI_HIDE_BASIC_TYPES */
typedef enum {
FFI_OK = 0,
FFI_BAD_TYPEDEF,
FFI_BAD_ABI
} ffi_status;
typedef struct {
ffi_abi abi;
unsigned nargs;
ffi_type **arg_types;
ffi_type *rtype;
unsigned bytes;
unsigned flags;
#ifdef FFI_EXTRA_CIF_FIELDS
FFI_EXTRA_CIF_FIELDS;
#endif
} ffi_cif;
/* ---- Definitions for the raw API -------------------------------------- */
#ifndef FFI_SIZEOF_ARG
# if LONG_MAX == 2147483647
# define FFI_SIZEOF_ARG 4
# elif LONG_MAX == FFI_64_BIT_MAX
# define FFI_SIZEOF_ARG 8
# endif
#endif
#ifndef FFI_SIZEOF_JAVA_RAW
# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
#endif
typedef union {
ffi_sarg sint;
ffi_arg uint;
float flt;
char data[FFI_SIZEOF_ARG];
void* ptr;
} ffi_raw;
#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
/* This is a special case for mips64/n32 ABI (and perhaps others) where
sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
typedef union {
signed int sint;
unsigned int uint;
float flt;
char data[FFI_SIZEOF_JAVA_RAW];
void* ptr;
} ffi_java_raw;
#else
typedef ffi_raw ffi_java_raw;
#endif
FFI_API
void ffi_raw_call (ffi_cif *cif,
void (*fn)(void),
void *rvalue,
ffi_raw *avalue);
FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
FFI_API size_t ffi_raw_size (ffi_cif *cif);
/* This is analogous to the raw API, except it uses Java parameter
packing, even on 64-bit machines. I.e. on 64-bit machines longs
and doubles are followed by an empty 64-bit word. */
FFI_API
void ffi_java_raw_call (ffi_cif *cif,
void (*fn)(void),
void *rvalue,
ffi_java_raw *avalue);
FFI_API
void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw);
FFI_API
void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args);
FFI_API
size_t ffi_java_raw_size (ffi_cif *cif);
/* ---- Definitions for closures ----------------------------------------- */
#if FFI_CLOSURES
#ifdef _MSC_VER
__declspec(align(8))
#endif
typedef struct {
#if 0
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
void (*fun)(ffi_cif*,void*,void**,void*);
void *user_data;
} ffi_closure
#ifdef __GNUC__
__attribute__((aligned (8)))
#endif
;
#ifndef __GNUC__
# ifdef __sgi
# pragma pack 0
# endif
#endif
FFI_API void *ffi_closure_alloc (size_t size, void **code);
FFI_API void ffi_closure_free (void *);
FFI_API ffi_status
ffi_prep_closure (ffi_closure*,
ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data)
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
__attribute__((deprecated ("use ffi_prep_closure_loc instead")))
#elif defined(__GNUC__) && __GNUC__ >= 3
__attribute__((deprecated))
#endif
;
FFI_API ffi_status
ffi_prep_closure_loc (ffi_closure*,
ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data,
void*codeloc);
#ifdef __sgi
# pragma pack 8
#endif
typedef struct {
#if 0
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
#if !FFI_NATIVE_RAW_API
/* If this is enabled, then a raw closure has the same layout
as a regular closure. We use this to install an intermediate
handler to do the transaltion, void** -> ffi_raw*. */
void (*translate_args)(ffi_cif*,void*,void**,void*);
void *this_closure;
#endif
void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
void *user_data;
} ffi_raw_closure;
typedef struct {
#if 0
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
#if !FFI_NATIVE_RAW_API
/* If this is enabled, then a raw closure has the same layout
as a regular closure. We use this to install an intermediate
handler to do the translation, void** -> ffi_raw*. */
void (*translate_args)(ffi_cif*,void*,void**,void*);
void *this_closure;
#endif
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
void *user_data;
} ffi_java_raw_closure;
FFI_API ffi_status
ffi_prep_raw_closure (ffi_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
void *user_data);
FFI_API ffi_status
ffi_prep_raw_closure_loc (ffi_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
void *user_data,
void *codeloc);
FFI_API ffi_status
ffi_prep_java_raw_closure (ffi_java_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
void *user_data);
FFI_API ffi_status
ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
void *user_data,
void *codeloc);
#endif /* FFI_CLOSURES */
#if FFI_GO_CLOSURES
typedef struct {
void *tramp;
ffi_cif *cif;
void (*fun)(ffi_cif*,void*,void**,void*);
} ffi_go_closure;
FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*));
FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
void **avalue, void *closure);
#endif /* FFI_GO_CLOSURES */
/* ---- Public interface definition -------------------------------------- */
FFI_API
ffi_status ffi_prep_cif(ffi_cif *cif,
ffi_abi abi,
unsigned int nargs,
ffi_type *rtype,
ffi_type **atypes);
FFI_API
ffi_status ffi_prep_cif_var(ffi_cif *cif,
ffi_abi abi,
unsigned int nfixedargs,
unsigned int ntotalargs,
ffi_type *rtype,
ffi_type **atypes);
FFI_API
void ffi_call(ffi_cif *cif,
void (*fn)(void),
void *rvalue,
void **avalue);
FFI_API
ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
size_t *offsets);
/* Useful for eliminating compiler warnings. */
#define FFI_FN(f) ((void (*)(void))f)
/* ---- Definitions shared with assembly code ---------------------------- */
#endif
/* If these change, update src/mips/ffitarget.h. */
#define FFI_TYPE_VOID 0
#define FFI_TYPE_INT 1
#define FFI_TYPE_FLOAT 2
#define FFI_TYPE_DOUBLE 3
#if 1
#define FFI_TYPE_LONGDOUBLE 4
#else
#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
#endif
#define FFI_TYPE_UINT8 5
#define FFI_TYPE_SINT8 6
#define FFI_TYPE_UINT16 7
#define FFI_TYPE_SINT16 8
#define FFI_TYPE_UINT32 9
#define FFI_TYPE_SINT32 10
#define FFI_TYPE_UINT64 11
#define FFI_TYPE_SINT64 12
#define FFI_TYPE_STRUCT 13
#define FFI_TYPE_POINTER 14
#define FFI_TYPE_COMPLEX 15
/* This should always refer to the last type code (for sanity checks). */
#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
#ifdef __cplusplus
}
#endif
#endif
#endif
\ No newline at end of file
#ifdef __x86_64__
/* -----------------------------------------------------------------*-C-*-
libffi 3.3-rc0 - Copyright (c) 2011, 2014 Anthony Green
- Copyright (c) 1996-2003, 2007, 2008 Red Hat, Inc.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the ``Software''), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
/* -------------------------------------------------------------------
Most of the API is documented in doc/libffi.texi.
The raw API is designed to bypass some of the argument packing and
unpacking on architectures for which it can be avoided. Routines
are provided to emulate the raw API if the underlying platform
doesn't allow faster implementation.
More details on the raw API can be found in:
http://gcc.gnu.org/ml/java/1999-q3/msg00138.html
and
http://gcc.gnu.org/ml/java/1999-q3/msg00174.html
-------------------------------------------------------------------- */
#ifndef LIBFFI_H
#define LIBFFI_H
#ifdef __cplusplus
extern "C" {
#endif
/* Specify which architecture libffi is configured for. */
#ifndef X86_64
#define X86_64
#endif
/* ---- System configuration information --------------------------------- */
#include <ffitarget.h>
#ifndef LIBFFI_ASM
#if defined(_MSC_VER) && !defined(__clang__)
#define __attribute__(X)
#endif
#include <stddef.h>
#include <limits.h>
/* LONG_LONG_MAX is not always defined (not if STRICT_ANSI, for example).
But we can find it either under the correct ANSI name, or under GNU
C's internal name. */
#define FFI_64_BIT_MAX 9223372036854775807
#ifdef LONG_LONG_MAX
# define FFI_LONG_LONG_MAX LONG_LONG_MAX
#else
# ifdef LLONG_MAX
# define FFI_LONG_LONG_MAX LLONG_MAX
# ifdef _AIX52 /* or newer has C99 LLONG_MAX */
# undef FFI_64_BIT_MAX
# define FFI_64_BIT_MAX 9223372036854775807LL
# endif /* _AIX52 or newer */
# else
# ifdef __GNUC__
# define FFI_LONG_LONG_MAX __LONG_LONG_MAX__
# endif
# ifdef _AIX /* AIX 5.1 and earlier have LONGLONG_MAX */
# ifndef __PPC64__
# if defined (__IBMC__) || defined (__IBMCPP__)
# define FFI_LONG_LONG_MAX LONGLONG_MAX
# endif
# endif /* __PPC64__ */
# undef FFI_64_BIT_MAX
# define FFI_64_BIT_MAX 9223372036854775807LL
# endif
# endif
#endif
/* The closure code assumes that this works on pointers, i.e. a size_t
can hold a pointer. */
typedef struct _ffi_type
{
size_t size;
unsigned short alignment;
unsigned short type;
struct _ffi_type **elements;
} ffi_type;
/* Need minimal decorations for DLLs to work on Windows. GCC has
autoimport and autoexport. Always mark externally visible symbols
as dllimport for MSVC clients, even if it means an extra indirection
when using the static version of the library.
Besides, as a workaround, they can define FFI_BUILDING if they
*know* they are going to link with the static library. */
#if defined _MSC_VER
# if defined FFI_BUILDING_DLL /* Building libffi.DLL with msvcc.sh */
# define FFI_API __declspec(dllexport)
# elif !defined FFI_BUILDING /* Importing libffi.DLL */
# define FFI_API __declspec(dllimport)
# else /* Building/linking static library */
# define FFI_API
# endif
#else
# define FFI_API
#endif
/* The externally visible type declarations also need the MSVC DLL
decorations, or they will not be exported from the object file. */
#if defined LIBFFI_HIDE_BASIC_TYPES
# define FFI_EXTERN FFI_API
#else
# define FFI_EXTERN extern FFI_API
#endif
#ifndef LIBFFI_HIDE_BASIC_TYPES
#if SCHAR_MAX == 127
# define ffi_type_uchar ffi_type_uint8
# define ffi_type_schar ffi_type_sint8
#else
#error "char size not supported"
#endif
#if SHRT_MAX == 32767
# define ffi_type_ushort ffi_type_uint16
# define ffi_type_sshort ffi_type_sint16
#elif SHRT_MAX == 2147483647
# define ffi_type_ushort ffi_type_uint32
# define ffi_type_sshort ffi_type_sint32
#else
#error "short size not supported"
#endif
#if INT_MAX == 32767
# define ffi_type_uint ffi_type_uint16
# define ffi_type_sint ffi_type_sint16
#elif INT_MAX == 2147483647
# define ffi_type_uint ffi_type_uint32
# define ffi_type_sint ffi_type_sint32
#elif INT_MAX == 9223372036854775807
# define ffi_type_uint ffi_type_uint64
# define ffi_type_sint ffi_type_sint64
#else
#error "int size not supported"
#endif
#if LONG_MAX == 2147483647
# if FFI_LONG_LONG_MAX != FFI_64_BIT_MAX
#error "no 64-bit data type supported"
# endif
#elif LONG_MAX != FFI_64_BIT_MAX
#error "long size not supported"
#endif
#if LONG_MAX == 2147483647
# define ffi_type_ulong ffi_type_uint32
# define ffi_type_slong ffi_type_sint32
#elif LONG_MAX == FFI_64_BIT_MAX
# define ffi_type_ulong ffi_type_uint64
# define ffi_type_slong ffi_type_sint64
#else
#error "long size not supported"
#endif
/* These are defined in types.c. */
FFI_EXTERN ffi_type ffi_type_void;
FFI_EXTERN ffi_type ffi_type_uint8;
FFI_EXTERN ffi_type ffi_type_sint8;
FFI_EXTERN ffi_type ffi_type_uint16;
FFI_EXTERN ffi_type ffi_type_sint16;
FFI_EXTERN ffi_type ffi_type_uint32;
FFI_EXTERN ffi_type ffi_type_sint32;
FFI_EXTERN ffi_type ffi_type_uint64;
FFI_EXTERN ffi_type ffi_type_sint64;
FFI_EXTERN ffi_type ffi_type_float;
FFI_EXTERN ffi_type ffi_type_double;
FFI_EXTERN ffi_type ffi_type_pointer;
#if 1
FFI_EXTERN ffi_type ffi_type_longdouble;
#else
#define ffi_type_longdouble ffi_type_double
#endif
#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
FFI_EXTERN ffi_type ffi_type_complex_float;
FFI_EXTERN ffi_type ffi_type_complex_double;
#if 1
FFI_EXTERN ffi_type ffi_type_complex_longdouble;
#else
#define ffi_type_complex_longdouble ffi_type_complex_double
#endif
#endif
#endif /* LIBFFI_HIDE_BASIC_TYPES */
typedef enum {
FFI_OK = 0,
FFI_BAD_TYPEDEF,
FFI_BAD_ABI
} ffi_status;
typedef struct {
ffi_abi abi;
unsigned nargs;
ffi_type **arg_types;
ffi_type *rtype;
unsigned bytes;
unsigned flags;
#ifdef FFI_EXTRA_CIF_FIELDS
FFI_EXTRA_CIF_FIELDS;
#endif
} ffi_cif;
/* ---- Definitions for the raw API -------------------------------------- */
#ifndef FFI_SIZEOF_ARG
# if LONG_MAX == 2147483647
# define FFI_SIZEOF_ARG 4
# elif LONG_MAX == FFI_64_BIT_MAX
# define FFI_SIZEOF_ARG 8
# endif
#endif
#ifndef FFI_SIZEOF_JAVA_RAW
# define FFI_SIZEOF_JAVA_RAW FFI_SIZEOF_ARG
#endif
typedef union {
ffi_sarg sint;
ffi_arg uint;
float flt;
char data[FFI_SIZEOF_ARG];
void* ptr;
} ffi_raw;
#if FFI_SIZEOF_JAVA_RAW == 4 && FFI_SIZEOF_ARG == 8
/* This is a special case for mips64/n32 ABI (and perhaps others) where
sizeof(void *) is 4 and FFI_SIZEOF_ARG is 8. */
typedef union {
signed int sint;
unsigned int uint;
float flt;
char data[FFI_SIZEOF_JAVA_RAW];
void* ptr;
} ffi_java_raw;
#else
typedef ffi_raw ffi_java_raw;
#endif
FFI_API
void ffi_raw_call (ffi_cif *cif,
void (*fn)(void),
void *rvalue,
ffi_raw *avalue);
FFI_API void ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw);
FFI_API void ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args);
FFI_API size_t ffi_raw_size (ffi_cif *cif);
/* This is analogous to the raw API, except it uses Java parameter
packing, even on 64-bit machines. I.e. on 64-bit machines longs
and doubles are followed by an empty 64-bit word. */
FFI_API
void ffi_java_raw_call (ffi_cif *cif,
void (*fn)(void),
void *rvalue,
ffi_java_raw *avalue);
FFI_API
void ffi_java_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_java_raw *raw);
FFI_API
void ffi_java_raw_to_ptrarray (ffi_cif *cif, ffi_java_raw *raw, void **args);
FFI_API
size_t ffi_java_raw_size (ffi_cif *cif);
/* ---- Definitions for closures ----------------------------------------- */
#if FFI_CLOSURES
#ifdef _MSC_VER
__declspec(align(8))
#endif
typedef struct {
#if 0
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
void (*fun)(ffi_cif*,void*,void**,void*);
void *user_data;
} ffi_closure
#ifdef __GNUC__
__attribute__((aligned (8)))
#endif
;
#ifndef __GNUC__
# ifdef __sgi
# pragma pack 0
# endif
#endif
FFI_API void *ffi_closure_alloc (size_t size, void **code);
FFI_API void ffi_closure_free (void *);
FFI_API ffi_status
ffi_prep_closure (ffi_closure*,
ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data)
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 405)
__attribute__((deprecated ("use ffi_prep_closure_loc instead")))
#elif defined(__GNUC__) && __GNUC__ >= 3
__attribute__((deprecated))
#endif
;
FFI_API ffi_status
ffi_prep_closure_loc (ffi_closure*,
ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data,
void*codeloc);
#ifdef __sgi
# pragma pack 8
#endif
typedef struct {
#if 0
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
#if !FFI_NATIVE_RAW_API
/* If this is enabled, then a raw closure has the same layout
as a regular closure. We use this to install an intermediate
handler to do the transaltion, void** -> ffi_raw*. */
void (*translate_args)(ffi_cif*,void*,void**,void*);
void *this_closure;
#endif
void (*fun)(ffi_cif*,void*,ffi_raw*,void*);
void *user_data;
} ffi_raw_closure;
typedef struct {
#if 0
void *trampoline_table;
void *trampoline_table_entry;
#else
char tramp[FFI_TRAMPOLINE_SIZE];
#endif
ffi_cif *cif;
#if !FFI_NATIVE_RAW_API
/* If this is enabled, then a raw closure has the same layout
as a regular closure. We use this to install an intermediate
handler to do the translation, void** -> ffi_raw*. */
void (*translate_args)(ffi_cif*,void*,void**,void*);
void *this_closure;
#endif
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*);
void *user_data;
} ffi_java_raw_closure;
FFI_API ffi_status
ffi_prep_raw_closure (ffi_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
void *user_data);
FFI_API ffi_status
ffi_prep_raw_closure_loc (ffi_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
void *user_data,
void *codeloc);
FFI_API ffi_status
ffi_prep_java_raw_closure (ffi_java_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
void *user_data);
FFI_API ffi_status
ffi_prep_java_raw_closure_loc (ffi_java_raw_closure*,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_java_raw*,void*),
void *user_data,
void *codeloc);
#endif /* FFI_CLOSURES */
#if FFI_GO_CLOSURES
typedef struct {
void *tramp;
ffi_cif *cif;
void (*fun)(ffi_cif*,void*,void**,void*);
} ffi_go_closure;
FFI_API ffi_status ffi_prep_go_closure (ffi_go_closure*, ffi_cif *,
void (*fun)(ffi_cif*,void*,void**,void*));
FFI_API void ffi_call_go (ffi_cif *cif, void (*fn)(void), void *rvalue,
void **avalue, void *closure);
#endif /* FFI_GO_CLOSURES */
/* ---- Public interface definition -------------------------------------- */
FFI_API
ffi_status ffi_prep_cif(ffi_cif *cif,
ffi_abi abi,
unsigned int nargs,
ffi_type *rtype,
ffi_type **atypes);
FFI_API
ffi_status ffi_prep_cif_var(ffi_cif *cif,
ffi_abi abi,
unsigned int nfixedargs,
unsigned int ntotalargs,
ffi_type *rtype,
ffi_type **atypes);
FFI_API
void ffi_call(ffi_cif *cif,
void (*fn)(void),
void *rvalue,
void **avalue);
FFI_API
ffi_status ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type,
size_t *offsets);
/* Useful for eliminating compiler warnings. */
#define FFI_FN(f) ((void (*)(void))f)
/* ---- Definitions shared with assembly code ---------------------------- */
#endif
/* If these change, update src/mips/ffitarget.h. */
#define FFI_TYPE_VOID 0
#define FFI_TYPE_INT 1
#define FFI_TYPE_FLOAT 2
#define FFI_TYPE_DOUBLE 3
#if 1
#define FFI_TYPE_LONGDOUBLE 4
#else
#define FFI_TYPE_LONGDOUBLE FFI_TYPE_DOUBLE
#endif
#define FFI_TYPE_UINT8 5
#define FFI_TYPE_SINT8 6
#define FFI_TYPE_UINT16 7
#define FFI_TYPE_SINT16 8
#define FFI_TYPE_UINT32 9
#define FFI_TYPE_SINT32 10
#define FFI_TYPE_UINT64 11
#define FFI_TYPE_SINT64 12
#define FFI_TYPE_STRUCT 13
#define FFI_TYPE_POINTER 14
#define FFI_TYPE_COMPLEX 15
/* This should always refer to the last type code (for sanity checks). */
#define FFI_TYPE_LAST FFI_TYPE_COMPLEX
#ifdef __cplusplus
}
#endif
#endif
#endif
\ No newline at end of file
#if defined(__aarch64__) || defined(__arm64__)
/* fficonfig.h. Generated from fficonfig.h.in by configure. */
/* fficonfig.h.in. Generated from configure.ac by autoheader. */
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
systems. This function is required for `alloca.c' support on those systems.
*/
/* #undef CRAY_STACKSEG_END */
/* Define to 1 if using `alloca.c'. */
/* #undef C_ALLOCA */
/* Define to the flags needed for the .section .eh_frame directive. */
#define EH_FRAME_FLAGS "aw"
/* Define this if you want extra debugging. */
/* #undef FFI_DEBUG */
/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
#ifdef __APPLE__
#define FFI_EXEC_TRAMPOLINE_TABLE 1
#endif
/* Define this if you want to enable pax emulated trampolines */
/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
/* Cannot use malloc on this target, so, we revert to alternative means */
#ifdef linux
#define FFI_MMAP_EXEC_WRIT 1
#endif
/* Define this if you do not want support for the raw API. */
/* #undef FFI_NO_RAW_API */
/* Define this if you do not want support for aggregate types. */
/* #undef FFI_NO_STRUCTS */
/* Define to 1 if you have `alloca', as a function or macro. */
#define HAVE_ALLOCA 1
/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
*/
#define HAVE_ALLOCA_H 1
/* Define if your assembler supports .cfi_* directives. */
#define HAVE_AS_CFI_PSEUDO_OP 1
/* Define if your assembler supports .register. */
/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
/* Define if the compiler uses zarch features. */
/* #undef HAVE_AS_S390_ZARCH */
/* Define if your assembler and linker support unaligned PC relative relocs.
*/
/* #undef HAVE_AS_SPARC_UA_PCREL */
/* Define if your assembler supports unwind section type. */
/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
/* Define if your assembler supports PC relative relocs. */
/* #undef HAVE_AS_X86_PCREL */
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define if __attribute__((visibility("hidden"))) is supported. */
#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define if you have the long double type and it is bigger than a double */
/* #undef HAVE_LONG_DOUBLE */
/* Define if you support more than one size of the long double type */
/* #undef HAVE_LONG_DOUBLE_VARIANT */
/* Define to 1 if you have the `memcpy' function. */
#define HAVE_MEMCPY 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `mkostemp' function. */
/* #undef HAVE_MKOSTEMP */
/* Define to 1 if you have the `mmap' function. */
#define HAVE_MMAP 1
/* Define if mmap with MAP_ANON(YMOUS) works. */
#define HAVE_MMAP_ANON 1
/* Define if mmap of /dev/zero works. */
/* #undef HAVE_MMAP_DEV_ZERO */
/* Define if read-only mmap of a plain file works. */
#define HAVE_MMAP_FILE 1
/* Define if .eh_frame sections should be read-only. */
/* #undef HAVE_RO_EH_FRAME */
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/mman.h> header file. */
#define HAVE_SYS_MMAN_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if GNU symbol versioning is used for libatomic. */
/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
/* Define to the sub-directory where libtool stores uninstalled libraries. */
#define LT_OBJDIR ".libs/"
/* Name of package */
#define PACKAGE "libffi"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
/* Define to the full name of this package. */
#define PACKAGE_NAME "libffi"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libffi 3.3-rc0"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libffi"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "3.3-rc0"
/* The size of `double', as computed by sizeof. */
#define SIZEOF_DOUBLE 8
/* The size of `long double', as computed by sizeof. */
#define SIZEOF_LONG_DOUBLE 8
/* The size of `size_t', as computed by sizeof. */
#define SIZEOF_SIZE_T 8
/* If using the C implementation of alloca, define if you know the
direction of stack growth for your system; otherwise it will be
automatically deduced at runtime.
STACK_DIRECTION > 0 => grows toward higher addresses
STACK_DIRECTION < 0 => grows toward lower addresses
STACK_DIRECTION = 0 => direction of growth unknown */
/* #undef STACK_DIRECTION */
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define if symbols are underscored. */
#define SYMBOL_UNDERSCORE 1
/* Define this if you are using Purify and want to suppress spurious messages.
*/
/* #undef USING_PURIFY */
/* Version number of package */
#define VERSION "3.3-rc0"
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
#ifdef LIBFFI_ASM
#ifdef __APPLE__
#define FFI_HIDDEN(name) .private_extern name
#else
#define FFI_HIDDEN(name) .hidden name
#endif
#else
#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
#endif
#else
#ifdef LIBFFI_ASM
#define FFI_HIDDEN(name)
#else
#define FFI_HIDDEN
#endif
#endif
#endif
\ No newline at end of file
#ifdef __arm__
/* fficonfig.h. Generated from fficonfig.h.in by configure. */
/* fficonfig.h.in. Generated from configure.ac by autoheader. */
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
systems. This function is required for `alloca.c' support on those systems.
*/
/* #undef CRAY_STACKSEG_END */
/* Define to 1 if using `alloca.c'. */
/* #undef C_ALLOCA */
/* Define to the flags needed for the .section .eh_frame directive. */
#define EH_FRAME_FLAGS "aw"
/* Define this if you want extra debugging. */
/* #undef FFI_DEBUG */
/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
#ifdef __APPLE__
#define FFI_EXEC_TRAMPOLINE_TABLE 1
#endif
/* Define this if you want to enable pax emulated trampolines */
/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
/* Cannot use malloc on this target, so, we revert to alternative means */
#ifdef linux
#define FFI_MMAP_EXEC_WRIT 1
#endif
/* Define this if you do not want support for the raw API. */
/* #undef FFI_NO_RAW_API */
/* Define this if you do not want support for aggregate types. */
/* #undef FFI_NO_STRUCTS */
/* Define to 1 if you have `alloca', as a function or macro. */
#define HAVE_ALLOCA 1
/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
*/
#define HAVE_ALLOCA_H 1
/* Define if your assembler supports .cfi_* directives. */
#define HAVE_AS_CFI_PSEUDO_OP 1
/* Define if your assembler supports .register. */
/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
/* Define if the compiler uses zarch features. */
/* #undef HAVE_AS_S390_ZARCH */
/* Define if your assembler and linker support unaligned PC relative relocs.
*/
/* #undef HAVE_AS_SPARC_UA_PCREL */
/* Define if your assembler supports unwind section type. */
/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
/* Define if your assembler supports PC relative relocs. */
/* #undef HAVE_AS_X86_PCREL */
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define if __attribute__((visibility("hidden"))) is supported. */
#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define if you have the long double type and it is bigger than a double */
/* #undef HAVE_LONG_DOUBLE */
/* Define if you support more than one size of the long double type */
/* #undef HAVE_LONG_DOUBLE_VARIANT */
/* Define to 1 if you have the `memcpy' function. */
#define HAVE_MEMCPY 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `mkostemp' function. */
/* #undef HAVE_MKOSTEMP */
/* Define to 1 if you have the `mmap' function. */
#define HAVE_MMAP 1
/* Define if mmap with MAP_ANON(YMOUS) works. */
#define HAVE_MMAP_ANON 1
/* Define if mmap of /dev/zero works. */
/* #undef HAVE_MMAP_DEV_ZERO */
/* Define if read-only mmap of a plain file works. */
#define HAVE_MMAP_FILE 1
/* Define if .eh_frame sections should be read-only. */
/* #undef HAVE_RO_EH_FRAME */
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/mman.h> header file. */
#define HAVE_SYS_MMAN_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if GNU symbol versioning is used for libatomic. */
/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
/* Define to the sub-directory where libtool stores uninstalled libraries. */
#define LT_OBJDIR ".libs/"
/* Name of package */
#define PACKAGE "libffi"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
/* Define to the full name of this package. */
#define PACKAGE_NAME "libffi"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libffi 3.3-rc0"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libffi"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "3.3-rc0"
/* The size of `double', as computed by sizeof. */
#define SIZEOF_DOUBLE 8
/* The size of `long double', as computed by sizeof. */
#define SIZEOF_LONG_DOUBLE 8
/* The size of `size_t', as computed by sizeof. */
#define SIZEOF_SIZE_T 4
/* If using the C implementation of alloca, define if you know the
direction of stack growth for your system; otherwise it will be
automatically deduced at runtime.
STACK_DIRECTION > 0 => grows toward higher addresses
STACK_DIRECTION < 0 => grows toward lower addresses
STACK_DIRECTION = 0 => direction of growth unknown */
/* #undef STACK_DIRECTION */
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define if symbols are underscored. */
#define SYMBOL_UNDERSCORE 1
/* Define this if you are using Purify and want to suppress spurious messages.
*/
/* #undef USING_PURIFY */
/* Version number of package */
#define VERSION "3.3-rc0"
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
#ifdef LIBFFI_ASM
#ifdef __APPLE__
#define FFI_HIDDEN(name) .private_extern name
#else
#define FFI_HIDDEN(name) .hidden name
#endif
#else
#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
#endif
#else
#ifdef LIBFFI_ASM
#define FFI_HIDDEN(name)
#else
#define FFI_HIDDEN
#endif
#endif
#endif
\ No newline at end of file
#ifdef __i386__
/* fficonfig.h. Generated from fficonfig.h.in by configure. */
/* fficonfig.h.in. Generated from configure.ac by autoheader. */
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
systems. This function is required for `alloca.c' support on those systems.
*/
/* #undef CRAY_STACKSEG_END */
/* Define to 1 if using `alloca.c'. */
/* #undef C_ALLOCA */
/* Define to the flags needed for the .section .eh_frame directive. */
#define EH_FRAME_FLAGS "aw"
/* Define this if you want extra debugging. */
/* #undef FFI_DEBUG */
/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
/* Define this if you want to enable pax emulated trampolines */
/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
/* Cannot use malloc on this target, so, we revert to alternative means */
#define FFI_MMAP_EXEC_WRIT 1
/* Define this if you do not want support for the raw API. */
/* #undef FFI_NO_RAW_API */
/* Define this if you do not want support for aggregate types. */
/* #undef FFI_NO_STRUCTS */
/* Define to 1 if you have `alloca', as a function or macro. */
#define HAVE_ALLOCA 1
/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
*/
#define HAVE_ALLOCA_H 1
/* Define if your assembler supports .cfi_* directives. */
#define HAVE_AS_CFI_PSEUDO_OP 1
/* Define if your assembler supports .register. */
/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
/* Define if the compiler uses zarch features. */
/* #undef HAVE_AS_S390_ZARCH */
/* Define if your assembler and linker support unaligned PC relative relocs.
*/
/* #undef HAVE_AS_SPARC_UA_PCREL */
/* Define if your assembler supports unwind section type. */
/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
/* Define if your assembler supports PC relative relocs. */
#define HAVE_AS_X86_PCREL 1
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define if __attribute__((visibility("hidden"))) is supported. */
#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define if you have the long double type and it is bigger than a double */
#define HAVE_LONG_DOUBLE 1
/* Define if you support more than one size of the long double type */
/* #undef HAVE_LONG_DOUBLE_VARIANT */
/* Define to 1 if you have the `memcpy' function. */
#define HAVE_MEMCPY 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `mkostemp' function. */
/* #undef HAVE_MKOSTEMP */
/* Define to 1 if you have the `mmap' function. */
#define HAVE_MMAP 1
/* Define if mmap with MAP_ANON(YMOUS) works. */
#define HAVE_MMAP_ANON 1
/* Define if mmap of /dev/zero works. */
/* #undef HAVE_MMAP_DEV_ZERO */
/* Define if read-only mmap of a plain file works. */
#define HAVE_MMAP_FILE 1
/* Define if .eh_frame sections should be read-only. */
/* #undef HAVE_RO_EH_FRAME */
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/mman.h> header file. */
#define HAVE_SYS_MMAN_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if GNU symbol versioning is used for libatomic. */
/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
/* Define to the sub-directory where libtool stores uninstalled libraries. */
#define LT_OBJDIR ".libs/"
/* Name of package */
#define PACKAGE "libffi"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
/* Define to the full name of this package. */
#define PACKAGE_NAME "libffi"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libffi 3.3-rc0"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libffi"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "3.3-rc0"
/* The size of `double', as computed by sizeof. */
#define SIZEOF_DOUBLE 8
/* The size of `long double', as computed by sizeof. */
#define SIZEOF_LONG_DOUBLE 16
/* The size of `size_t', as computed by sizeof. */
#define SIZEOF_SIZE_T 4
/* If using the C implementation of alloca, define if you know the
direction of stack growth for your system; otherwise it will be
automatically deduced at runtime.
STACK_DIRECTION > 0 => grows toward higher addresses
STACK_DIRECTION < 0 => grows toward lower addresses
STACK_DIRECTION = 0 => direction of growth unknown */
/* #undef STACK_DIRECTION */
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define if symbols are underscored. */
#define SYMBOL_UNDERSCORE 1
/* Define this if you are using Purify and want to suppress spurious messages.
*/
/* #undef USING_PURIFY */
/* Version number of package */
#define VERSION "3.3-rc0"
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
#ifdef LIBFFI_ASM
#ifdef __APPLE__
#define FFI_HIDDEN(name) .private_extern name
#else
#define FFI_HIDDEN(name) .hidden name
#endif
#else
#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
#endif
#else
#ifdef LIBFFI_ASM
#define FFI_HIDDEN(name)
#else
#define FFI_HIDDEN
#endif
#endif
#endif
\ No newline at end of file
#ifdef __x86_64__
/* fficonfig.h. Generated from fficonfig.h.in by configure. */
/* fficonfig.h.in. Generated from configure.ac by autoheader. */
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP
systems. This function is required for `alloca.c' support on those systems.
*/
/* #undef CRAY_STACKSEG_END */
/* Define to 1 if using `alloca.c'. */
/* #undef C_ALLOCA */
/* Define to the flags needed for the .section .eh_frame directive. */
#define EH_FRAME_FLAGS "aw"
/* Define this if you want extra debugging. */
/* #undef FFI_DEBUG */
/* Cannot use PROT_EXEC on this target, so, we revert to alternative means */
/* #undef FFI_EXEC_TRAMPOLINE_TABLE */
/* Define this if you want to enable pax emulated trampolines */
/* #undef FFI_MMAP_EXEC_EMUTRAMP_PAX */
/* Cannot use malloc on this target, so, we revert to alternative means */
#define FFI_MMAP_EXEC_WRIT 1
/* Define this if you do not want support for the raw API. */
/* #undef FFI_NO_RAW_API */
/* Define this if you do not want support for aggregate types. */
/* #undef FFI_NO_STRUCTS */
/* Define to 1 if you have `alloca', as a function or macro. */
#define HAVE_ALLOCA 1
/* Define to 1 if you have <alloca.h> and it should be used (not on Ultrix).
*/
#define HAVE_ALLOCA_H 1
/* Define if your assembler supports .cfi_* directives. */
#define HAVE_AS_CFI_PSEUDO_OP 1
/* Define if your assembler supports .register. */
/* #undef HAVE_AS_REGISTER_PSEUDO_OP */
/* Define if the compiler uses zarch features. */
/* #undef HAVE_AS_S390_ZARCH */
/* Define if your assembler and linker support unaligned PC relative relocs.
*/
/* #undef HAVE_AS_SPARC_UA_PCREL */
/* Define if your assembler supports unwind section type. */
/* #undef HAVE_AS_X86_64_UNWIND_SECTION_TYPE */
/* Define if your assembler supports PC relative relocs. */
#define HAVE_AS_X86_PCREL 1
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define if __attribute__((visibility("hidden"))) is supported. */
#define HAVE_HIDDEN_VISIBILITY_ATTRIBUTE 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define if you have the long double type and it is bigger than a double */
#define HAVE_LONG_DOUBLE 1
/* Define if you support more than one size of the long double type */
/* #undef HAVE_LONG_DOUBLE_VARIANT */
/* Define to 1 if you have the `memcpy' function. */
#define HAVE_MEMCPY 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `mkostemp' function. */
/* #undef HAVE_MKOSTEMP */
/* Define to 1 if you have the `mmap' function. */
#define HAVE_MMAP 1
/* Define if mmap with MAP_ANON(YMOUS) works. */
#define HAVE_MMAP_ANON 1
/* Define if mmap of /dev/zero works. */
/* #undef HAVE_MMAP_DEV_ZERO */
/* Define if read-only mmap of a plain file works. */
#define HAVE_MMAP_FILE 1
/* Define if .eh_frame sections should be read-only. */
/* #undef HAVE_RO_EH_FRAME */
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/mman.h> header file. */
#define HAVE_SYS_MMAN_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if GNU symbol versioning is used for libatomic. */
/* #undef LIBFFI_GNU_SYMBOL_VERSIONING */
/* Define to the sub-directory where libtool stores uninstalled libraries. */
#define LT_OBJDIR ".libs/"
/* Name of package */
#define PACKAGE "libffi"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "http://github.com/libffi/libffi/issues"
/* Define to the full name of this package. */
#define PACKAGE_NAME "libffi"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "libffi 3.3-rc0"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "libffi"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "3.3-rc0"
/* The size of `double', as computed by sizeof. */
#define SIZEOF_DOUBLE 8
/* The size of `long double', as computed by sizeof. */
#define SIZEOF_LONG_DOUBLE 16
/* The size of `size_t', as computed by sizeof. */
#define SIZEOF_SIZE_T 8
/* If using the C implementation of alloca, define if you know the
direction of stack growth for your system; otherwise it will be
automatically deduced at runtime.
STACK_DIRECTION > 0 => grows toward higher addresses
STACK_DIRECTION < 0 => grows toward lower addresses
STACK_DIRECTION = 0 => direction of growth unknown */
/* #undef STACK_DIRECTION */
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define if symbols are underscored. */
#define SYMBOL_UNDERSCORE 1
/* Define this if you are using Purify and want to suppress spurious messages.
*/
/* #undef USING_PURIFY */
/* Version number of package */
#define VERSION "3.3-rc0"
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
#ifdef HAVE_HIDDEN_VISIBILITY_ATTRIBUTE
#ifdef LIBFFI_ASM
#ifdef __APPLE__
#define FFI_HIDDEN(name) .private_extern name
#else
#define FFI_HIDDEN(name) .hidden name
#endif
#else
#define FFI_HIDDEN __attribute__ ((visibility ("hidden")))
#endif
#else
#ifdef LIBFFI_ASM
#define FFI_HIDDEN(name)
#else
#define FFI_HIDDEN
#endif
#endif
#endif
\ No newline at end of file
#ifdef __aarch64__
/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#ifndef LIBFFI_TARGET_H
#define LIBFFI_TARGET_H
#ifndef LIBFFI_H
#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
#endif
#ifndef LIBFFI_ASM
#ifdef __ILP32__
#define FFI_SIZEOF_ARG 8
#define FFI_SIZEOF_JAVA_RAW 4
typedef unsigned long long ffi_arg;
typedef signed long long ffi_sarg;
#else
typedef unsigned long ffi_arg;
typedef signed long ffi_sarg;
#endif
typedef enum ffi_abi
{
FFI_FIRST_ABI = 0,
FFI_SYSV,
FFI_LAST_ABI,
FFI_DEFAULT_ABI = FFI_SYSV
} ffi_abi;
#endif
/* ---- Definitions for closures ----------------------------------------- */
#define FFI_CLOSURES 1
#define FFI_NATIVE_RAW_API 0
#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
#ifdef __MACH__
#define FFI_TRAMPOLINE_SIZE 16
#define FFI_TRAMPOLINE_CLOSURE_OFFSET 16
#else
#error "No trampoline table implementation"
#endif
#else
#define FFI_TRAMPOLINE_SIZE 24
#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
#endif
/* ---- Internal ---- */
#if defined (__APPLE__)
#define FFI_TARGET_SPECIFIC_VARIADIC
#define FFI_EXTRA_CIF_FIELDS unsigned aarch64_nfixedargs
#else
/* iOS reserves x18 for the system. Disable Go closures until
a new static chain is chosen. */
#define FFI_GO_CLOSURES 1
#endif
#define FFI_TARGET_HAS_COMPLEX_TYPE
#endif
#endif
\ No newline at end of file
#ifdef __arm__
/* -----------------------------------------------------------------*-C-*-
ffitarget.h - Copyright (c) 2012 Anthony Green
Copyright (c) 2010 CodeSourcery
Copyright (c) 1996-2003 Red Hat, Inc.
Target configuration macros for ARM.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
#ifndef LIBFFI_TARGET_H
#define LIBFFI_TARGET_H
#ifndef LIBFFI_H
#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
#endif
#ifndef LIBFFI_ASM
typedef unsigned long ffi_arg;
typedef signed long ffi_sarg;
typedef enum ffi_abi {
FFI_FIRST_ABI = 0,
FFI_SYSV,
FFI_VFP,
FFI_LAST_ABI,
#ifdef __ARM_PCS_VFP
FFI_DEFAULT_ABI = FFI_VFP,
#else
FFI_DEFAULT_ABI = FFI_SYSV,
#endif
} ffi_abi;
#endif
#define FFI_EXTRA_CIF_FIELDS \
int vfp_used; \
unsigned short vfp_reg_free, vfp_nargs; \
signed char vfp_args[16] \
#define FFI_TARGET_SPECIFIC_VARIADIC
#define FFI_TARGET_HAS_COMPLEX_TYPE
/* ---- Definitions for closures ----------------------------------------- */
#define FFI_CLOSURES 1
#define FFI_GO_CLOSURES 1
#define FFI_NATIVE_RAW_API 0
#if defined (FFI_EXEC_TRAMPOLINE_TABLE) && FFI_EXEC_TRAMPOLINE_TABLE
#ifdef __MACH__
#define FFI_TRAMPOLINE_SIZE 12
#define FFI_TRAMPOLINE_CLOSURE_OFFSET 8
#else
#error "No trampoline table implementation"
#endif
#else
#define FFI_TRAMPOLINE_SIZE 12
#define FFI_TRAMPOLINE_CLOSURE_OFFSET FFI_TRAMPOLINE_SIZE
#endif
#endif
#endif
\ No newline at end of file
#ifdef __i386__
/* -----------------------------------------------------------------*-C-*-
ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
Copyright (c) 1996-2003, 2010 Red Hat, Inc.
Copyright (C) 2008 Free Software Foundation, Inc.
Target configuration macros for x86 and x86-64.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
#ifndef LIBFFI_TARGET_H
#define LIBFFI_TARGET_H
#ifndef LIBFFI_H
#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
#endif
/* ---- System specific configurations ----------------------------------- */
/* For code common to all platforms on x86 and x86_64. */
#define X86_ANY
#if defined (X86_64) && defined (__i386__)
#undef X86_64
#define X86
#endif
#ifdef X86_WIN64
#define FFI_SIZEOF_ARG 8
#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
#endif
#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
#ifndef _MSC_VER
#define FFI_TARGET_HAS_COMPLEX_TYPE
#endif
/* ---- Generic type definitions ----------------------------------------- */
#ifndef LIBFFI_ASM
#ifdef X86_WIN64
#ifdef _MSC_VER
typedef unsigned __int64 ffi_arg;
typedef __int64 ffi_sarg;
#else
typedef unsigned long long ffi_arg;
typedef long long ffi_sarg;
#endif
#else
#if defined __x86_64__ && defined __ILP32__
#define FFI_SIZEOF_ARG 8
#define FFI_SIZEOF_JAVA_RAW 4
typedef unsigned long long ffi_arg;
typedef long long ffi_sarg;
#else
typedef unsigned long ffi_arg;
typedef signed long ffi_sarg;
#endif
#endif
typedef enum ffi_abi {
#if defined(X86_WIN64)
FFI_FIRST_ABI = 0,
FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
FFI_LAST_ABI,
#ifdef __GNUC__
FFI_DEFAULT_ABI = FFI_GNUW64
#else
FFI_DEFAULT_ABI = FFI_WIN64
#endif
#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
FFI_FIRST_ABI = 1,
FFI_UNIX64,
FFI_WIN64,
FFI_EFI64 = FFI_WIN64,
FFI_GNUW64,
FFI_LAST_ABI,
FFI_DEFAULT_ABI = FFI_UNIX64
#elif defined(X86_WIN32)
FFI_FIRST_ABI = 0,
FFI_SYSV = 1,
FFI_STDCALL = 2,
FFI_THISCALL = 3,
FFI_FASTCALL = 4,
FFI_MS_CDECL = 5,
FFI_PASCAL = 6,
FFI_REGISTER = 7,
FFI_LAST_ABI,
FFI_DEFAULT_ABI = FFI_MS_CDECL
#else
FFI_FIRST_ABI = 0,
FFI_SYSV = 1,
FFI_THISCALL = 3,
FFI_FASTCALL = 4,
FFI_STDCALL = 5,
FFI_PASCAL = 6,
FFI_REGISTER = 7,
FFI_MS_CDECL = 8,
FFI_LAST_ABI,
FFI_DEFAULT_ABI = FFI_SYSV
#endif
} ffi_abi;
#endif
/* ---- Definitions for closures ----------------------------------------- */
#define FFI_CLOSURES 1
#define FFI_GO_CLOSURES 1
#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
#if defined (X86_64) || defined(X86_WIN64) \
|| (defined (__x86_64__) && defined (X86_DARWIN))
# define FFI_TRAMPOLINE_SIZE 24
# define FFI_NATIVE_RAW_API 0
#else
# define FFI_TRAMPOLINE_SIZE 12
# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
#endif
#endif
#endif
\ No newline at end of file
#ifdef __x86_64__
/* -----------------------------------------------------------------*-C-*-
ffitarget.h - Copyright (c) 2012, 2014, 2018 Anthony Green
Copyright (c) 1996-2003, 2010 Red Hat, Inc.
Copyright (C) 2008 Free Software Foundation, Inc.
Target configuration macros for x86 and x86-64.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
#ifndef LIBFFI_TARGET_H
#define LIBFFI_TARGET_H
#ifndef LIBFFI_H
#error "Please do not include ffitarget.h directly into your source. Use ffi.h instead."
#endif
/* ---- System specific configurations ----------------------------------- */
/* For code common to all platforms on x86 and x86_64. */
#define X86_ANY
#if defined (X86_64) && defined (__i386__)
#undef X86_64
#define X86
#endif
#ifdef X86_WIN64
#define FFI_SIZEOF_ARG 8
#define USE_BUILTIN_FFS 0 /* not yet implemented in mingw-64 */
#endif
#define FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
#ifndef _MSC_VER
#define FFI_TARGET_HAS_COMPLEX_TYPE
#endif
/* ---- Generic type definitions ----------------------------------------- */
#ifndef LIBFFI_ASM
#ifdef X86_WIN64
#ifdef _MSC_VER
typedef unsigned __int64 ffi_arg;
typedef __int64 ffi_sarg;
#else
typedef unsigned long long ffi_arg;
typedef long long ffi_sarg;
#endif
#else
#if defined __x86_64__ && defined __ILP32__
#define FFI_SIZEOF_ARG 8
#define FFI_SIZEOF_JAVA_RAW 4
typedef unsigned long long ffi_arg;
typedef long long ffi_sarg;
#else
typedef unsigned long ffi_arg;
typedef signed long ffi_sarg;
#endif
#endif
typedef enum ffi_abi {
#if defined(X86_WIN64)
FFI_FIRST_ABI = 0,
FFI_WIN64, /* sizeof(long double) == 8 - microsoft compilers */
FFI_GNUW64, /* sizeof(long double) == 16 - GNU compilers */
FFI_LAST_ABI,
#ifdef __GNUC__
FFI_DEFAULT_ABI = FFI_GNUW64
#else
FFI_DEFAULT_ABI = FFI_WIN64
#endif
#elif defined(X86_64) || (defined (__x86_64__) && defined (X86_DARWIN))
FFI_FIRST_ABI = 1,
FFI_UNIX64,
FFI_WIN64,
FFI_EFI64 = FFI_WIN64,
FFI_GNUW64,
FFI_LAST_ABI,
FFI_DEFAULT_ABI = FFI_UNIX64
#elif defined(X86_WIN32)
FFI_FIRST_ABI = 0,
FFI_SYSV = 1,
FFI_STDCALL = 2,
FFI_THISCALL = 3,
FFI_FASTCALL = 4,
FFI_MS_CDECL = 5,
FFI_PASCAL = 6,
FFI_REGISTER = 7,
FFI_LAST_ABI,
FFI_DEFAULT_ABI = FFI_MS_CDECL
#else
FFI_FIRST_ABI = 0,
FFI_SYSV = 1,
FFI_THISCALL = 3,
FFI_FASTCALL = 4,
FFI_STDCALL = 5,
FFI_PASCAL = 6,
FFI_REGISTER = 7,
FFI_MS_CDECL = 8,
FFI_LAST_ABI,
FFI_DEFAULT_ABI = FFI_SYSV
#endif
} ffi_abi;
#endif
/* ---- Definitions for closures ----------------------------------------- */
#define FFI_CLOSURES 1
#define FFI_GO_CLOSURES 1
#define FFI_TYPE_SMALL_STRUCT_1B (FFI_TYPE_LAST + 1)
#define FFI_TYPE_SMALL_STRUCT_2B (FFI_TYPE_LAST + 2)
#define FFI_TYPE_SMALL_STRUCT_4B (FFI_TYPE_LAST + 3)
#define FFI_TYPE_MS_STRUCT (FFI_TYPE_LAST + 4)
#if defined (X86_64) || defined(X86_WIN64) \
|| (defined (__x86_64__) && defined (X86_DARWIN))
# define FFI_TRAMPOLINE_SIZE 24
# define FFI_NATIVE_RAW_API 0
#else
# define FFI_TRAMPOLINE_SIZE 12
# define FFI_NATIVE_RAW_API 1 /* x86 has native raw api support */
#endif
#endif
#endif
\ No newline at end of file
/* -----------------------------------------------------------------------
prep_cif.c - Copyright (c) 2011, 2012 Anthony Green
Copyright (c) 1996, 1998, 2007 Red Hat, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
#include <ffi.h>
#include <ffi_common.h>
#include <stdlib.h>
/* Round up to FFI_SIZEOF_ARG. */
#define STACK_ARG_SIZE(x) FFI_ALIGN(x, FFI_SIZEOF_ARG)
/* Perform machine independent initialization of aggregate type
specifications. */
static ffi_status initialize_aggregate(ffi_type *arg, size_t *offsets)
{
ffi_type **ptr;
if (UNLIKELY(arg == NULL || arg->elements == NULL))
return FFI_BAD_TYPEDEF;
arg->size = 0;
arg->alignment = 0;
ptr = &(arg->elements[0]);
if (UNLIKELY(ptr == 0))
return FFI_BAD_TYPEDEF;
while ((*ptr) != NULL)
{
if (UNLIKELY(((*ptr)->size == 0)
&& (initialize_aggregate((*ptr), NULL) != FFI_OK)))
return FFI_BAD_TYPEDEF;
/* Perform a sanity check on the argument type */
FFI_ASSERT_VALID_TYPE(*ptr);
arg->size = FFI_ALIGN(arg->size, (*ptr)->alignment);
if (offsets)
*offsets++ = arg->size;
arg->size += (*ptr)->size;
arg->alignment = (arg->alignment > (*ptr)->alignment) ?
arg->alignment : (*ptr)->alignment;
ptr++;
}
/* Structure size includes tail padding. This is important for
structures that fit in one register on ABIs like the PowerPC64
Linux ABI that right justify small structs in a register.
It's also needed for nested structure layout, for example
struct A { long a; char b; }; struct B { struct A x; char y; };
should find y at an offset of 2*sizeof(long) and result in a
total size of 3*sizeof(long). */
arg->size = FFI_ALIGN (arg->size, arg->alignment);
/* On some targets, the ABI defines that structures have an additional
alignment beyond the "natural" one based on their elements. */
#ifdef FFI_AGGREGATE_ALIGNMENT
if (FFI_AGGREGATE_ALIGNMENT > arg->alignment)
arg->alignment = FFI_AGGREGATE_ALIGNMENT;
#endif
if (arg->size == 0)
return FFI_BAD_TYPEDEF;
else
return FFI_OK;
}
#ifndef __CRIS__
/* The CRIS ABI specifies structure elements to have byte
alignment only, so it completely overrides this functions,
which assumes "natural" alignment and padding. */
/* Perform machine independent ffi_cif preparation, then call
machine dependent routine. */
/* For non variadic functions isvariadic should be 0 and
nfixedargs==ntotalargs.
For variadic calls, isvariadic should be 1 and nfixedargs
and ntotalargs set as appropriate. nfixedargs must always be >=1 */
ffi_status FFI_HIDDEN ffi_prep_cif_core(ffi_cif *cif, ffi_abi abi,
unsigned int isvariadic,
unsigned int nfixedargs,
unsigned int ntotalargs,
ffi_type *rtype, ffi_type **atypes)
{
unsigned bytes = 0;
unsigned int i;
ffi_type **ptr;
FFI_ASSERT(cif != NULL);
FFI_ASSERT((!isvariadic) || (nfixedargs >= 1));
FFI_ASSERT(nfixedargs <= ntotalargs);
if (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI))
return FFI_BAD_ABI;
cif->abi = abi;
cif->arg_types = atypes;
cif->nargs = ntotalargs;
cif->rtype = rtype;
cif->flags = 0;
#if HAVE_LONG_DOUBLE_VARIANT
ffi_prep_types (abi);
#endif
/* Initialize the return type if necessary */
if ((cif->rtype->size == 0)
&& (initialize_aggregate(cif->rtype, NULL) != FFI_OK))
return FFI_BAD_TYPEDEF;
#ifndef FFI_TARGET_HAS_COMPLEX_TYPE
if (rtype->type == FFI_TYPE_COMPLEX)
abort();
#endif
/* Perform a sanity check on the return type */
FFI_ASSERT_VALID_TYPE(cif->rtype);
/* x86, x86-64 and s390 stack space allocation is handled in prep_machdep. */
#if !defined FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
/* Make space for the return structure pointer */
if (cif->rtype->type == FFI_TYPE_STRUCT
#ifdef TILE
&& (cif->rtype->size > 10 * FFI_SIZEOF_ARG)
#endif
#ifdef XTENSA
&& (cif->rtype->size > 16)
#endif
#ifdef NIOS2
&& (cif->rtype->size > 8)
#endif
)
bytes = STACK_ARG_SIZE(sizeof(void*));
#endif
for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++)
{
/* Initialize any uninitialized aggregate type definitions */
if (((*ptr)->size == 0)
&& (initialize_aggregate((*ptr), NULL) != FFI_OK))
return FFI_BAD_TYPEDEF;
#ifndef FFI_TARGET_HAS_COMPLEX_TYPE
if ((*ptr)->type == FFI_TYPE_COMPLEX)
abort();
#endif
/* Perform a sanity check on the argument type, do this
check after the initialization. */
FFI_ASSERT_VALID_TYPE(*ptr);
#if !defined FFI_TARGET_SPECIFIC_STACK_SPACE_ALLOCATION
{
/* Add any padding if necessary */
if (((*ptr)->alignment - 1) & bytes)
bytes = (unsigned)FFI_ALIGN(bytes, (*ptr)->alignment);
#ifdef TILE
if (bytes < 10 * FFI_SIZEOF_ARG &&
bytes + STACK_ARG_SIZE((*ptr)->size) > 10 * FFI_SIZEOF_ARG)
{
/* An argument is never split between the 10 parameter
registers and the stack. */
bytes = 10 * FFI_SIZEOF_ARG;
}
#endif
#ifdef XTENSA
if (bytes <= 6*4 && bytes + STACK_ARG_SIZE((*ptr)->size) > 6*4)
bytes = 6*4;
#endif
bytes += STACK_ARG_SIZE((*ptr)->size);
}
#endif
}
cif->bytes = bytes;
/* Perform machine dependent cif processing */
#ifdef FFI_TARGET_SPECIFIC_VARIADIC
if (isvariadic)
return ffi_prep_cif_machdep_var(cif, nfixedargs, ntotalargs);
#endif
return ffi_prep_cif_machdep(cif);
}
#endif /* not __CRIS__ */
ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi, unsigned int nargs,
ffi_type *rtype, ffi_type **atypes)
{
return ffi_prep_cif_core(cif, abi, 0, nargs, nargs, rtype, atypes);
}
ffi_status ffi_prep_cif_var(ffi_cif *cif,
ffi_abi abi,
unsigned int nfixedargs,
unsigned int ntotalargs,
ffi_type *rtype,
ffi_type **atypes)
{
return ffi_prep_cif_core(cif, abi, 1, nfixedargs, ntotalargs, rtype, atypes);
}
#if FFI_CLOSURES
ffi_status
ffi_prep_closure (ffi_closure* closure,
ffi_cif* cif,
void (*fun)(ffi_cif*,void*,void**,void*),
void *user_data)
{
return ffi_prep_closure_loc (closure, cif, fun, user_data, closure);
}
#endif
ffi_status
ffi_get_struct_offsets (ffi_abi abi, ffi_type *struct_type, size_t *offsets)
{
if (! (abi > FFI_FIRST_ABI && abi < FFI_LAST_ABI))
return FFI_BAD_ABI;
if (struct_type->type != FFI_TYPE_STRUCT)
return FFI_BAD_TYPEDEF;
#if HAVE_LONG_DOUBLE_VARIANT
ffi_prep_types (abi);
#endif
return initialize_aggregate(struct_type, offsets);
}
/* -----------------------------------------------------------------------
raw_api.c - Copyright (c) 1999, 2008 Red Hat, Inc.
Author: Kresten Krab Thorup <krab@gnu.org>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
/* This file defines generic functions for use with the raw api. */
#include <ffi.h>
#include <ffi_common.h>
#if !FFI_NO_RAW_API
size_t
ffi_raw_size (ffi_cif *cif)
{
size_t result = 0;
int i;
ffi_type **at = cif->arg_types;
for (i = cif->nargs-1; i >= 0; i--, at++)
{
#if !FFI_NO_STRUCTS
if ((*at)->type == FFI_TYPE_STRUCT)
result += FFI_ALIGN (sizeof (void*), FFI_SIZEOF_ARG);
else
#endif
result += FFI_ALIGN ((*at)->size, FFI_SIZEOF_ARG);
}
return result;
}
void
ffi_raw_to_ptrarray (ffi_cif *cif, ffi_raw *raw, void **args)
{
unsigned i;
ffi_type **tp = cif->arg_types;
#if WORDS_BIGENDIAN
for (i = 0; i < cif->nargs; i++, tp++, args++)
{
switch ((*tp)->type)
{
case FFI_TYPE_UINT8:
case FFI_TYPE_SINT8:
*args = (void*) ((char*)(raw++) + FFI_SIZEOF_ARG - 1);
break;
case FFI_TYPE_UINT16:
case FFI_TYPE_SINT16:
*args = (void*) ((char*)(raw++) + FFI_SIZEOF_ARG - 2);
break;
#if FFI_SIZEOF_ARG >= 4
case FFI_TYPE_UINT32:
case FFI_TYPE_SINT32:
*args = (void*) ((char*)(raw++) + FFI_SIZEOF_ARG - 4);
break;
#endif
#if !FFI_NO_STRUCTS
case FFI_TYPE_STRUCT:
*args = (raw++)->ptr;
break;
#endif
case FFI_TYPE_COMPLEX:
*args = (raw++)->ptr;
break;
case FFI_TYPE_POINTER:
*args = (void*) &(raw++)->ptr;
break;
default:
*args = raw;
raw += FFI_ALIGN ((*tp)->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG;
}
}
#else /* WORDS_BIGENDIAN */
#if !PDP
/* then assume little endian */
for (i = 0; i < cif->nargs; i++, tp++, args++)
{
#if !FFI_NO_STRUCTS
if ((*tp)->type == FFI_TYPE_STRUCT)
{
*args = (raw++)->ptr;
}
else
#endif
if ((*tp)->type == FFI_TYPE_COMPLEX)
{
*args = (raw++)->ptr;
}
else
{
*args = (void*) raw;
raw += FFI_ALIGN ((*tp)->size, sizeof (void*)) / sizeof (void*);
}
}
#else
#error "pdp endian not supported"
#endif /* ! PDP */
#endif /* WORDS_BIGENDIAN */
}
void
ffi_ptrarray_to_raw (ffi_cif *cif, void **args, ffi_raw *raw)
{
unsigned i;
ffi_type **tp = cif->arg_types;
for (i = 0; i < cif->nargs; i++, tp++, args++)
{
switch ((*tp)->type)
{
case FFI_TYPE_UINT8:
(raw++)->uint = *(UINT8*) (*args);
break;
case FFI_TYPE_SINT8:
(raw++)->sint = *(SINT8*) (*args);
break;
case FFI_TYPE_UINT16:
(raw++)->uint = *(UINT16*) (*args);
break;
case FFI_TYPE_SINT16:
(raw++)->sint = *(SINT16*) (*args);
break;
#if FFI_SIZEOF_ARG >= 4
case FFI_TYPE_UINT32:
(raw++)->uint = *(UINT32*) (*args);
break;
case FFI_TYPE_SINT32:
(raw++)->sint = *(SINT32*) (*args);
break;
#endif
#if !FFI_NO_STRUCTS
case FFI_TYPE_STRUCT:
(raw++)->ptr = *args;
break;
#endif
case FFI_TYPE_COMPLEX:
(raw++)->ptr = *args;
break;
case FFI_TYPE_POINTER:
(raw++)->ptr = **(void***) args;
break;
default:
memcpy ((void*) raw->data, (void*)*args, (*tp)->size);
raw += FFI_ALIGN ((*tp)->size, FFI_SIZEOF_ARG) / FFI_SIZEOF_ARG;
}
}
}
#if !FFI_NATIVE_RAW_API
/* This is a generic definition of ffi_raw_call, to be used if the
* native system does not provide a machine-specific implementation.
* Having this, allows code to be written for the raw API, without
* the need for system-specific code to handle input in that format;
* these following couple of functions will handle the translation forth
* and back automatically. */
void ffi_raw_call (ffi_cif *cif, void (*fn)(void), void *rvalue, ffi_raw *raw)
{
void **avalue = (void**) alloca (cif->nargs * sizeof (void*));
ffi_raw_to_ptrarray (cif, raw, avalue);
ffi_call (cif, fn, rvalue, avalue);
}
#if FFI_CLOSURES /* base system provides closures */
static void
ffi_translate_args (ffi_cif *cif, void *rvalue,
void **avalue, void *user_data)
{
ffi_raw *raw = (ffi_raw*)alloca (ffi_raw_size (cif));
ffi_raw_closure *cl = (ffi_raw_closure*)user_data;
ffi_ptrarray_to_raw (cif, avalue, raw);
(*cl->fun) (cif, rvalue, raw, cl->user_data);
}
ffi_status
ffi_prep_raw_closure_loc (ffi_raw_closure* cl,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
void *user_data,
void *codeloc)
{
ffi_status status;
status = ffi_prep_closure_loc ((ffi_closure*) cl,
cif,
&ffi_translate_args,
codeloc,
codeloc);
if (status == FFI_OK)
{
cl->fun = fun;
cl->user_data = user_data;
}
return status;
}
#endif /* FFI_CLOSURES */
#endif /* !FFI_NATIVE_RAW_API */
#if FFI_CLOSURES
/* Again, here is the generic version of ffi_prep_raw_closure, which
* will install an intermediate "hub" for translation of arguments from
* the pointer-array format, to the raw format */
ffi_status
ffi_prep_raw_closure (ffi_raw_closure* cl,
ffi_cif *cif,
void (*fun)(ffi_cif*,void*,ffi_raw*,void*),
void *user_data)
{
return ffi_prep_raw_closure_loc (cl, cif, fun, user_data, cl);
}
#endif /* FFI_CLOSURES */
#endif /* !FFI_NO_RAW_API */
/* -----------------------------------------------------------------------
types.c - Copyright (c) 1996, 1998 Red Hat, Inc.
Predefined ffi_types needed by libffi.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
----------------------------------------------------------------------- */
/* Hide the basic type definitions from the header file, so that we
can redefine them here as "const". */
#define LIBFFI_HIDE_BASIC_TYPES
#include <ffi.h>
#include <ffi_common.h>
/* Type definitions */
#define FFI_TYPEDEF(name, type, id, maybe_const)\
struct struct_align_##name { \
char c; \
type x; \
}; \
FFI_EXTERN \
maybe_const ffi_type ffi_type_##name = { \
sizeof(type), \
offsetof(struct struct_align_##name, x), \
id, NULL \
}
#define FFI_COMPLEX_TYPEDEF(name, type, maybe_const) \
static ffi_type *ffi_elements_complex_##name [2] = { \
(ffi_type *)(&ffi_type_##name), NULL \
}; \
struct struct_align_complex_##name { \
char c; \
_Complex type x; \
}; \
FFI_EXTERN \
maybe_const ffi_type ffi_type_complex_##name = { \
sizeof(_Complex type), \
offsetof(struct struct_align_complex_##name, x), \
FFI_TYPE_COMPLEX, \
(ffi_type **)ffi_elements_complex_##name \
}
/* Size and alignment are fake here. They must not be 0. */
FFI_EXTERN const ffi_type ffi_type_void = {
1, 1, FFI_TYPE_VOID, NULL
};
FFI_TYPEDEF(uint8, UINT8, FFI_TYPE_UINT8, const);
FFI_TYPEDEF(sint8, SINT8, FFI_TYPE_SINT8, const);
FFI_TYPEDEF(uint16, UINT16, FFI_TYPE_UINT16, const);
FFI_TYPEDEF(sint16, SINT16, FFI_TYPE_SINT16, const);
FFI_TYPEDEF(uint32, UINT32, FFI_TYPE_UINT32, const);
FFI_TYPEDEF(sint32, SINT32, FFI_TYPE_SINT32, const);
FFI_TYPEDEF(uint64, UINT64, FFI_TYPE_UINT64, const);
FFI_TYPEDEF(sint64, SINT64, FFI_TYPE_SINT64, const);
FFI_TYPEDEF(pointer, void*, FFI_TYPE_POINTER, const);
FFI_TYPEDEF(float, float, FFI_TYPE_FLOAT, const);
FFI_TYPEDEF(double, double, FFI_TYPE_DOUBLE, const);
#if !defined HAVE_LONG_DOUBLE_VARIANT || defined __alpha__
#define FFI_LDBL_CONST const
#else
#define FFI_LDBL_CONST
#endif
#ifdef __alpha__
/* Even if we're not configured to default to 128-bit long double,
maintain binary compatibility, as -mlong-double-128 can be used
at any time. */
/* Validate the hard-coded number below. */
# if defined(__LONG_DOUBLE_128__) && FFI_TYPE_LONGDOUBLE != 4
# error FFI_TYPE_LONGDOUBLE out of date
# endif
const ffi_type ffi_type_longdouble = { 16, 16, 4, NULL };
#elif FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
FFI_TYPEDEF(longdouble, long double, FFI_TYPE_LONGDOUBLE, FFI_LDBL_CONST);
#endif
#ifdef FFI_TARGET_HAS_COMPLEX_TYPE
FFI_COMPLEX_TYPEDEF(float, float, const);
FFI_COMPLEX_TYPEDEF(double, double, const);
#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE
FFI_COMPLEX_TYPEDEF(longdouble, long double, FFI_LDBL_CONST);
#endif
#endif
package com.android.internal.util;
import org.xmlpull.v1.XmlPullParserException;
import java.io.InputStream;
import java.util.HashMap;
public class XmlUtils {
public static final HashMap<String, ?> readMapXml(InputStream in) throws XmlPullParserException, java.io.IOException {
return null;
}
}
package com.swift.sandhook.xposedcompat;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import de.robv.android.xposed.XposedBridge;
/**
* @author Swift Gan
* Create: 2019/6/3
* Desc:
*/
public class HookInfo {
public Member origin;
public Method hook;
public Method backup;
public XposedBridge.AdditionalHookInfo additionalHookInfo;
}
package com.swift.sandhook.xposedcompat;
import android.app.Application;
import android.content.Context;
import com.swift.sandhook.HookLog;
import com.swift.sandhook.SandHook;
import com.swift.sandhook.SandHookConfig;
import com.swift.sandhook.wrapper.HookErrorException;
import com.swift.sandhook.wrapper.HookWrapper;
import com.swift.sandhook.wrapper.StubMethodsFactory;
import com.swift.sandhook.xposedcompat.utils.ApplicationUtils;
import com.swift.sandhook.xposedcompat.utils.ClassUtils;
import com.swift.sandhook.xposedcompat.utils.ComposeClassLoader;
import com.swift.sandhook.xposedcompat.utils.ProcessUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedInit;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
/**
* @author Swift Gan
* Create: 2019/6/3
* Desc:
*/
public class XposedCompat {
public volatile static boolean inited = false;
public volatile static SandHookConfig.LibLoader libLoader = new SandHookConfig.LibLoader() {
@Override
public void loadLib() {
System.loadLibrary("sandhook-xp");
}
};
public static Context context;
public static volatile ClassLoader classLoader;
public static String packageName;
public static String processName;
public static boolean isFirstApplication;
private static ClassLoader sandHookXposedClassLoader;
private static volatile int curSlot = 0;
public static volatile HookInfo[] hookInfos = new HookInfo[100];
static {
try {
init();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
public static boolean init() throws Throwable {
if (inited) return true;
libLoader.loadLib();
Method bridgeMethod = XposedCompat.class.getDeclaredMethod("hookBridge", int.class, Object.class, Object[].class);
init(XposedCompat.class, bridgeMethod, Object.class);
inited = true;
return true;
}
private native static void init(Class bridgeClass, Method bridgeMethod, Class ObjClass);
private native static long getJNITrampoline(int slot, boolean isStatic, char retShorty, char[] paramsShorty);
private native static void addHookMethod(Member hookMethod);
public static long getJNITrampoline(Member origin, int slot) {
if (origin instanceof Constructor) {
return getJNITrampoline(slot, false, ClassUtils.getShorty(Void.TYPE), ClassUtils.getShorties(((Constructor) origin).getParameterTypes()));
} else {
Method method = (Method) origin;
return getJNITrampoline(slot, Modifier.isStatic(method.getModifiers()), ClassUtils.getShorty(method.getReturnType()), ClassUtils.getShorties(method.getParameterTypes()));
}
}
private synchronized static int genSlot() {
curSlot++;
if (curSlot >= hookInfos.length) {
hookInfos = Arrays.copyOf(hookInfos, hookInfos.length + 30);
}
return curSlot;
}
public synchronized static boolean hookMethod(Member origin, XposedBridge.AdditionalHookInfo additionalHookInfo) {
Method hook = StubMethodsFactory.getStubMethod();
Method backup = StubMethodsFactory.getStubMethod();
int slot = genSlot();
long jniTrampoline = getJNITrampoline(origin, slot);
if (jniTrampoline == 0) {
return false;
}
if (!SandHook.setNativeEntry(origin, hook, jniTrampoline)) {
return false;
}
HookInfo hookInfo = new HookInfo();
hookInfo.origin = origin;
hookInfo.hook = hook;
hookInfo.backup = backup;
hookInfo.additionalHookInfo = additionalHookInfo;
hookInfos[slot] = hookInfo;
try {
SandHook.hook(new HookWrapper.HookEntity(origin, hook, backup));
addHookMethod(hook);
return true;
} catch (HookErrorException e) {
HookLog.e("hook error!", e);
return false;
}
}
public static Object hookBridge(int slot, Object thiz, Object[] params) throws Throwable {
HookInfo hookInfo = hookInfos[slot];
if (XposedBridge.disableHooks) {
return SandHook.callOriginMethod(hookInfo.origin, hookInfo.backup, thiz, params);
}
Object[] snapshot = hookInfo.additionalHookInfo.callbacks.getSnapshot();
if (snapshot == null || snapshot.length == 0) {
return SandHook.callOriginMethod(hookInfo.origin, hookInfo.backup, thiz, params);
}
XC_MethodHook.MethodHookParam param = new XC_MethodHook.MethodHookParam();
param.method = hookInfo.origin;
param.thisObject = thiz;
param.args = params;
int beforeIdx = 0;
do {
try {
((XC_MethodHook) snapshot[beforeIdx]).callBeforeHookedMethod(param);
} catch (Throwable t) {
// reset result (ignoring what the unexpectedly exiting callback did)
param.setResult(null);
param.returnEarly = false;
continue;
}
if (param.returnEarly) {
// skip remaining "before" callbacks and corresponding "after" callbacks
beforeIdx++;
break;
}
} while (++beforeIdx < snapshot.length);
// call original method if not requested otherwise
if (!param.returnEarly) {
try {
param.setResult(SandHook.callOriginMethod(hookInfo.origin, hookInfo.backup, thiz, param.args));
} catch (Throwable e) {
XposedBridge.log(e);
param.setThrowable(e);
}
}
// call "after method" callbacks
int afterIdx = beforeIdx - 1;
do {
Object lastResult = param.getResult();
Throwable lastThrowable = param.getThrowable();
try {
((XC_MethodHook) snapshot[afterIdx]).callAfterHookedMethod(param);
} catch (Throwable t) {
XposedBridge.log(t);
if (lastThrowable == null)
param.setResult(lastResult);
else
param.setThrowable(lastThrowable);
}
} while (--afterIdx >= 0);
if (!param.hasThrowable()) {
return param.getResult();
} else {
throw param.getThrowable();
}
}
public static void loadModule(String modulePath, String moduleOdexDir, String moduleSoPath,ClassLoader classLoader) {
XposedInit.loadModule(modulePath, moduleOdexDir, moduleSoPath, classLoader);
}
public static void addXposedModuleCallback(IXposedHookLoadPackage module) {
XposedBridge.hookLoadPackage(new IXposedHookLoadPackage.Wrapper(module));
}
public static void callXposedModuleInit() throws Throwable {
//prepare LoadPackageParam
XC_LoadPackage.LoadPackageParam packageParam = new XC_LoadPackage.LoadPackageParam(XposedBridge.sLoadedPackageCallbacks);
Application application = ApplicationUtils.currentApplication();
if (application != null) {
if (packageParam.packageName == null) {
packageParam.packageName = application.getPackageName();
}
if (packageParam.processName == null) {
packageParam.processName = ProcessUtils.getProcessName(application);
}
if (packageParam.classLoader == null) {
packageParam.classLoader = application.getClassLoader();
}
if (packageParam.appInfo == null) {
packageParam.appInfo = application.getApplicationInfo();
}
}
XC_LoadPackage.callAll(packageParam);
}
public static ClassLoader getSandHookXposedClassLoader(ClassLoader appOriginClassLoader, ClassLoader sandBoxHostClassLoader) {
if (sandHookXposedClassLoader != null) {
return sandHookXposedClassLoader;
} else {
sandHookXposedClassLoader = new ComposeClassLoader(sandBoxHostClassLoader, appOriginClassLoader);
return sandHookXposedClassLoader;
}
}
}
package com.swift.sandhook.xposedcompat.utils;
import android.app.Application;
import java.lang.reflect.Method;
public class ApplicationUtils {
private static Class classActivityThread;
private static Method currentApplicationMethod;
static Application application;
public static Application currentApplication() {
if (application != null)
return application;
if (currentApplicationMethod == null) {
try {
classActivityThread = Class.forName("android.app.ActivityThread");
currentApplicationMethod = classActivityThread.getDeclaredMethod("currentApplication");
} catch (Exception e) {
e.printStackTrace();
}
}
if (currentApplicationMethod == null)
return null;
try {
application = (Application) currentApplicationMethod.invoke(null);
} catch (Exception e) {
}
return application;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package com.swift.sandhook.xposedcompat.utils;
import java.util.HashMap;
import java.util.Map;
/**
* <p>Operates on classes without using reflection.</p>
*
* <p>This class handles invalid {@code null} inputs as best it can.
* Each method documents its behaviour in more detail.</p>
*
* <p>The notion of a {@code canonical name} includes the human
* readable name for the type, for example {@code int[]}. The
* non-canonical method variants work with the JVM names, such as
* {@code [I}. </p>
*
* @since 2.0
* @version $Id: ClassUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
*/
public class ClassUtils {
public static final String EMPTY = "";
/**
* <p>The package separator character: <code>'&#x2e;' == {@value}</code>.</p>
*/
public static final char PACKAGE_SEPARATOR_CHAR = '.';
/**
* <p>The package separator String: {@code "&#x2e;"}.</p>
*/
public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR);
/**
* <p>The inner class separator character: <code>'$' == {@value}</code>.</p>
*/
public static final char INNER_CLASS_SEPARATOR_CHAR = '$';
/**
* <p>The inner class separator String: {@code "$"}.</p>
*/
public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR);
/**
* Maps primitive {@code Class}es to their corresponding wrapper {@code Class}.
*/
private static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<Class<?>, Class<?>>();
static {
primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
primitiveWrapperMap.put(Byte.TYPE, Byte.class);
primitiveWrapperMap.put(Character.TYPE, Character.class);
primitiveWrapperMap.put(Short.TYPE, Short.class);
primitiveWrapperMap.put(Integer.TYPE, Integer.class);
primitiveWrapperMap.put(Long.TYPE, Long.class);
primitiveWrapperMap.put(Double.TYPE, Double.class);
primitiveWrapperMap.put(Float.TYPE, Float.class);
primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
}
/**
* Maps wrapper {@code Class}es to their corresponding primitive types.
*/
private static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<Class<?>, Class<?>>();
static {
for (Class<?> primitiveClass : primitiveWrapperMap.keySet()) {
Class<?> wrapperClass = primitiveWrapperMap.get(primitiveClass);
if (!primitiveClass.equals(wrapperClass)) {
wrapperPrimitiveMap.put(wrapperClass, primitiveClass);
}
}
}
/**
* Maps a primitive class name to its corresponding abbreviation used in array class names.
*/
private static final Map<String, String> abbreviationMap = new HashMap<String, String>();
/**
* Maps an abbreviation used in array class names to corresponding primitive class name.
*/
private static final Map<String, String> reverseAbbreviationMap = new HashMap<String, String>();
/**
* Add primitive type abbreviation to maps of abbreviations.
*
* @param primitive Canonical name of primitive type
* @param abbreviation Corresponding abbreviation of primitive type
*/
private static void addAbbreviation(String primitive, String abbreviation) {
abbreviationMap.put(primitive, abbreviation);
reverseAbbreviationMap.put(abbreviation, primitive);
}
/**
* Feed abbreviation maps
*/
static {
addAbbreviation("int", "I");
addAbbreviation("boolean", "Z");
addAbbreviation("float", "F");
addAbbreviation("long", "J");
addAbbreviation("short", "S");
addAbbreviation("byte", "B");
addAbbreviation("double", "D");
addAbbreviation("char", "C");
addAbbreviation("void", "V");
}
/**
* <p>ClassUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as
* {@code ClassUtils.getShortClassName(cls)}.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public ClassUtils() {
super();
}
// Short class name
// ----------------------------------------------------------------------
/**
* <p>Gets the class name minus the package name for an {@code Object}.</p>
*
* @param object the class to get the short name for, may be null
* @param valueIfNull the value to return if null
* @return the class name of the object without the package name, or the null value
*/
public static String getShortClassName(Object object, String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getShortClassName(object.getClass());
}
/**
* <p>Gets the class name minus the package name from a {@code Class}.</p>
*
* <p>Consider using the Java 5 API {@link Class#getSimpleName()} instead.
* The one known difference is that this code will return {@code "Map.Entry"} while
* the {@code java.lang.Class} variant will simply return {@code "Entry"}. </p>
*
* @param cls the class to get the short name for.
* @return the class name without the package name or an empty string
*/
public static String getShortClassName(Class<?> cls) {
if (cls == null) {
return EMPTY;
}
return getShortClassName(cls.getName());
}
public static char[] getShorties(Class[] classes) {
if (classes == null)
return new char[0];
char[] res = new char[classes.length];
for (int i = 0; i < classes.length; i++) {
res[i] = getShorty(classes[i]);
}
return res;
}
public static char getShorty(Class clazz) {
if (clazz == null)
return 'V';
String className = clazz.getName();
String shortyStr = abbreviationMap.get(className);
if (shortyStr != null) {
return shortyStr.charAt(0);
} else {
return 'L';
}
}
/**
* <p>Gets the class name minus the package name from a String.</p>
*
* <p>The string passed in is assumed to be a class name - it is not checked.</p>
* <p>Note that this method differs from Class.getSimpleName() in that this will
* return {@code "Map.Entry"} whilst the {@code java.lang.Class} variant will simply
* return {@code "Entry"}. </p>
*
* @param className the className to get the short name for
* @return the class name of the class without the package name or an empty string
*/
public static String getShortClassName(String className) {
if (className == null) {
return EMPTY;
}
if (className.length() == 0) {
return EMPTY;
}
StringBuilder arrayPrefix = new StringBuilder();
// Handle array encoding
if (className.startsWith("[")) {
while (className.charAt(0) == '[') {
className = className.substring(1);
arrayPrefix.append("[]");
}
// Strip Object type encoding
if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
className = className.substring(1, className.length() - 1);
}
}
if (reverseAbbreviationMap.containsKey(className)) {
className = reverseAbbreviationMap.get(className);
}
int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
int innerIdx = className.indexOf(
INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
String out = className.substring(lastDotIdx + 1);
if (innerIdx != -1) {
out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
}
return out + arrayPrefix;
}
}
package com.swift.sandhook.xposedcompat.utils;
public class ComposeClassLoader extends ClassLoader {
private final ClassLoader mAppClassLoader;
public ComposeClassLoader(ClassLoader parent, ClassLoader appClassLoader) {
super(parent);
mAppClassLoader = appClassLoader;
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
Class clazz = null;
try {
clazz = mAppClassLoader.loadClass(name);
} catch (ClassNotFoundException e) {
// IGNORE.
}
if (clazz == null) {
clazz = super.loadClass(name, resolve);
}
if (clazz == null) {
throw new ClassNotFoundException();
}
return clazz;
}
}
package com.swift.sandhook.xposedcompat.utils;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by swift_gan on 2017/11/23.
*/
public class ProcessUtils {
private static volatile String processName = null;
public static String getProcessName(Context context) {
if (!TextUtils.isEmpty(processName))
return processName;
processName = doGetProcessName(context);
return processName;
}
private static String doGetProcessName(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
if (runningApps == null) {
return null;
}
for (ActivityManager.RunningAppProcessInfo proInfo : runningApps) {
if (proInfo.pid == android.os.Process.myPid()) {
if (proInfo.processName != null) {
return proInfo.processName;
}
}
}
return context.getPackageName();
}
public static boolean isMainProcess(Context context) {
String processName = getProcessName(context);
String pkgName = context.getPackageName();
if (!TextUtils.isEmpty(processName) && !TextUtils.equals(processName, pkgName)) {
return false;
} else {
return true;
}
}
public static List<ResolveInfo> findActivitiesForPackage(Context context, String packageName) {
final PackageManager packageManager = context.getPackageManager();
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
mainIntent.setPackage(packageName);
final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
return apps != null ? apps : new ArrayList<ResolveInfo>();
}
}
package de.robv.android.xposed;
/**
* Hook the initialization of Java-based command-line tools (like pm).
*
* @hide Xposed no longer hooks command-line tools, therefore this interface shouldn't be
* implemented anymore.
*/
public interface IXposedHookCmdInit extends IXposedMod {
/**
* Called very early during startup of a command-line tool.
* @param startupParam Details about the module itself and the started process.
* @throws Throwable Everything is caught, but it will prevent further initialization of the module.
*/
void initCmdApp(StartupParam startupParam) throws Throwable;
/** Data holder for {@link #initCmdApp}. */
final class StartupParam {
/*package*/ StartupParam() {}
/** The path to the module's APK. */
public String modulePath;
/** The class name of the tools that the hook was invoked for. */
public String startClassName;
}
}
package de.robv.android.xposed;
//import android.content.res.XResources;
import de.robv.android.xposed.callbacks.XC_InitPackageResources;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
/**
* Get notified when the resources for an app are initialized.
* In {@link #handleInitPackageResources}, resource replacements can be created.
*
* <p>This interface should be implemented by the module's main class. Xposed will take care of
* registering it as a callback automatically.
*/
public interface IXposedHookInitPackageResources extends IXposedMod {
/**
* This method is called when resources for an app are being initialized.
* Modules can call special methods of the {@link XResources} class in order to replace resources.
*
* @param resparam Information about the resources.
* @throws Throwable Everything the callback throws is caught and logged.
*/
void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable;
/** @hide */
final class Wrapper extends XC_InitPackageResources {
private final IXposedHookInitPackageResources instance;
public Wrapper(IXposedHookInitPackageResources instance) {
this.instance = instance;
}
@Override
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
instance.handleInitPackageResources(resparam);
}
}
}
package de.robv.android.xposed;
import android.app.Application;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
/**
* Get notified when an app ("Android package") is loaded.
* This is especially useful to hook some app-specific methods.
*
* <p>This interface should be implemented by the module's main class. Xposed will take care of
* registering it as a callback automatically.
*/
public interface IXposedHookLoadPackage extends IXposedMod {
/**
* This method is called when an app is loaded. It's called very early, even before
* {@link Application#onCreate} is called.
* Modules can set up their app-specific hooks here.
*
* @param lpparam Information about the app.
* @throws Throwable Everything the callback throws is caught and logged.
*/
void handleLoadPackage(LoadPackageParam lpparam) throws Throwable;
/** @hide */
final class Wrapper extends XC_LoadPackage {
private final IXposedHookLoadPackage instance;
public Wrapper(IXposedHookLoadPackage instance) {
this.instance = instance;
}
@Override
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
instance.handleLoadPackage(lpparam);
}
}
}
package de.robv.android.xposed;
/**
* Hook the initialization of Zygote process(es), from which all the apps are forked.
*
* <p>Implement this interface in your module's main class in order to be notified when Android is
* starting up. In {@link IXposedHookZygoteInit}, you can modify objects and place hooks that should
* be applied for every app. Only the Android framework/system classes are available at that point
* in time. Use {@code null} as class loader for {@link XposedHelpers#findAndHookMethod(String, ClassLoader, String, Object...)}
* and its variants.
*
* <p>If you want to hook one/multiple specific apps, use {@link IXposedHookLoadPackage} instead.
*/
public interface IXposedHookZygoteInit extends IXposedMod {
/**
* Called very early during startup of Zygote.
* @param startupParam Details about the module itself and the started process.
* @throws Throwable everything is caught, but will prevent further initialization of the module.
*/
void initZygote(StartupParam startupParam) throws Throwable;
/** Data holder for {@link #initZygote}. */
final class StartupParam {
/*package*/ StartupParam() {}
/** The path to the module's APK. */
public String modulePath;
/**
* Always {@code true} on 32-bit ROMs. On 64-bit, it's only {@code true} for the primary
* process that starts the system_server.
*/
public boolean startsSystemServer;
}
}
package de.robv.android.xposed;
/** Marker interface for Xposed modules. Cannot be implemented directly. */
/* package */ interface IXposedMod {}
package de.robv.android.xposed;
import de.robv.android.xposed.services.BaseService;
import de.robv.android.xposed.services.DirectAccessService;
/**
* A helper to work with (or without) SELinux, abstracting much of its big complexity.
*/
public final class SELinuxHelper {
private SELinuxHelper() {}
/**
* Determines whether SELinux is disabled or enabled.
*
* @return A boolean indicating whether SELinux is enabled.
*/
public static boolean isSELinuxEnabled() {
return sIsSELinuxEnabled;
}
/**
* Determines whether SELinux is permissive or enforcing.
*
* @return A boolean indicating whether SELinux is enforcing.
*/
public static boolean isSELinuxEnforced() {
return sIsSELinuxEnabled;
}
/**
* Gets the security context of the current process.
*
* @return A String representing the security context of the current process.
*/
public static String getContext() {
return null;
}
/**
* Retrieve the service to be used when accessing files in {@code /data/data/*}.
*
* <p class="caution"><strong>IMPORTANT:</strong> If you call this from the Zygote process,
* don't re-use the result in different process!
*
* @return An instance of the service.
*/
public static BaseService getAppDataFileService() {
if (sServiceAppDataFile != null)
return sServiceAppDataFile;
return new DirectAccessService();
}
// ----------------------------------------------------------------------------
private static boolean sIsSELinuxEnabled = false;
private static BaseService sServiceAppDataFile = new DirectAccessService();
}
package de.robv.android.xposed;
import java.lang.reflect.Member;
import de.robv.android.xposed.callbacks.IXUnhook;
import de.robv.android.xposed.callbacks.XCallback;
/**
* Callback class for method hooks.
*
* <p>Usually, anonymous subclasses of this class are created which override
* {@link #beforeHookedMethod} and/or {@link #afterHookedMethod}.
*/
public abstract class XC_MethodHook extends XCallback {
/**
* Creates a new callback with default priority.
*/
@SuppressWarnings("deprecation")
public XC_MethodHook() {
super();
}
/**
* Creates a new callback with a specific priority.
*
* <p class="note">Note that {@link #afterHookedMethod} will be called in reversed order, i.e.
* the callback with the highest priority will be called last. This way, the callback has the
* final control over the return value. {@link #beforeHookedMethod} is called as usual, i.e.
* highest priority first.
*
* @param priority See {@link XCallback#priority}.
*/
public XC_MethodHook(int priority) {
super(priority);
}
/**
* Called before the invocation of the method.
*
* <p>You can use {@link MethodHookParam#setResult} and {@link MethodHookParam#setThrowable}
* to prevent the original method from being called.
*
* <p>Note that implementations shouldn't call {@code super(param)}, it's not necessary.
*
* @param param Information about the method call.
* @throws Throwable Everything the callback throws is caught and logged.
*/
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {}
public void callBeforeHookedMethod(MethodHookParam param) throws Throwable {
beforeHookedMethod(param);
}
/**
* Called after the invocation of the method.
*
* <p>You can use {@link MethodHookParam#setResult} and {@link MethodHookParam#setThrowable}
* to modify the return value of the original method.
*
* <p>Note that implementations shouldn't call {@code super(param)}, it's not necessary.
*
* @param param Information about the method call.
* @throws Throwable Everything the callback throws is caught and logged.
*/
protected void afterHookedMethod(MethodHookParam param) throws Throwable {}
public void callAfterHookedMethod(MethodHookParam param) throws Throwable {
afterHookedMethod(param);
}
/**
* Wraps information about the method call and allows to influence it.
*/
public static final class MethodHookParam extends Param {
/** @hide */
@SuppressWarnings("deprecation")
public MethodHookParam() {
super();
}
/** The hooked method/constructor. */
public Member method;
/** The {@code this} reference for an instance method, or {@code null} for static methods. */
public Object thisObject;
/** Arguments to the method call. */
public Object[] args;
private Object result = null;
private Throwable throwable = null;
public boolean returnEarly = false;
/** Returns the result of the method call. */
public Object getResult() {
return result;
}
/**
* Modify the result of the method call.
*
* <p>If called from {@link #beforeHookedMethod}, it prevents the call to the original method.
*/
public void setResult(Object result) {
this.result = result;
this.throwable = null;
this.returnEarly = true;
}
/** Returns the {@link Throwable} thrown by the method, or {@code null}. */
public Throwable getThrowable() {
return throwable;
}
/** Returns true if an exception was thrown by the method. */
public boolean hasThrowable() {
return throwable != null;
}
/**
* Modify the exception thrown of the method call.
*
* <p>If called from {@link #beforeHookedMethod}, it prevents the call to the original method.
*/
public void setThrowable(Throwable throwable) {
this.throwable = throwable;
this.result = null;
this.returnEarly = true;
}
/** Returns the result of the method call, or throws the Throwable caused by it. */
public Object getResultOrThrowable() throws Throwable {
if (throwable != null)
throw throwable;
return result;
}
}
/**
* An object with which the method/constructor can be unhooked.
*/
public class Unhook implements IXUnhook<XC_MethodHook> {
private final Member hookMethod;
/*package*/ Unhook(Member hookMethod) {
this.hookMethod = hookMethod;
}
/**
* Returns the method/constructor that has been hooked.
*/
public Member getHookedMethod() {
return hookMethod;
}
@Override
public XC_MethodHook getCallback() {
return XC_MethodHook.this;
}
@SuppressWarnings("deprecation")
@Override
public void unhook() {
XposedBridge.unhookMethod(hookMethod, XC_MethodHook.this);
}
}
}
package de.robv.android.xposed;
import de.robv.android.xposed.callbacks.XCallback;
/**
* A special case of {@link XC_MethodHook} which completely replaces the original method.
*/
public abstract class XC_MethodReplacement extends XC_MethodHook {
/**
* Creates a new callback with default priority.
*/
public XC_MethodReplacement() {
super();
}
/**
* Creates a new callback with a specific priority.
*
* @param priority See {@link XCallback#priority}.
*/
public XC_MethodReplacement(int priority) {
super(priority);
}
/** @hide */
@Override
protected final void beforeHookedMethod(MethodHookParam param) throws Throwable {
try {
Object result = replaceHookedMethod(param);
param.setResult(result);
} catch (Throwable t) {
param.setThrowable(t);
}
}
/** @hide */
@Override
@SuppressWarnings("EmptyMethod")
protected final void afterHookedMethod(MethodHookParam param) throws Throwable {}
/**
* Shortcut for replacing a method completely. Whatever is returned/thrown here is taken
* instead of the result of the original method (which will not be called).
*
* <p>Note that implementations shouldn't call {@code super(param)}, it's not necessary.
*
* @param param Information about the method call.
* @throws Throwable Anything that is thrown by the callback will be passed on to the original caller.
*/
@SuppressWarnings("UnusedParameters")
protected abstract Object replaceHookedMethod(MethodHookParam param) throws Throwable;
/**
* Predefined callback that skips the method without replacements.
*/
public static final XC_MethodReplacement DO_NOTHING = new XC_MethodReplacement(PRIORITY_HIGHEST*2) {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
return null;
}
};
/**
* Creates a callback which always returns a specific value.
*
* @param result The value that should be returned to callers of the hooked method.
*/
public static XC_MethodReplacement returnConstant(final Object result) {
return returnConstant(PRIORITY_DEFAULT, result);
}
/**
* Like {@link #returnConstant(Object)}, but allows to specify a priority for the callback.
*
* @param priority See {@link XCallback#priority}.
* @param result The value that should be returned to callers of the hooked method.
*/
public static XC_MethodReplacement returnConstant(int priority, final Object result) {
return new XC_MethodReplacement(priority) {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
return result;
}
};
}
}
package de.robv.android.xposed;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import com.android.internal.util.XmlUtils;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import de.robv.android.xposed.services.FileResult;
/**
* This class is basically the same as SharedPreferencesImpl from AOSP, but
* read-only and without listeners support. Instead, it is made to be
* compatible with all ROMs.
*/
public final class XSharedPreferences implements SharedPreferences {
private static final String TAG = "XSharedPreferences";
private final File mFile;
private final String mFilename;
private Map<String, Object> mMap;
private boolean mLoaded = false;
private long mLastModified;
private long mFileSize;
/**
* Read settings from the specified file.
* @param prefFile The file to read the preferences from.
*/
public XSharedPreferences(File prefFile) {
mFile = prefFile;
mFilename = mFile.getAbsolutePath();
startLoadFromDisk();
}
/**
* Read settings from the default preferences for a package.
* These preferences are returned by {@link PreferenceManager#getDefaultSharedPreferences}.
* @param packageName The package name.
*/
public XSharedPreferences(String packageName) {
this(packageName, packageName + "_preferences");
}
/**
* Read settings from a custom preferences file for a package.
* These preferences are returned by {@link Context#getSharedPreferences(String, int)}.
* @param packageName The package name.
* @param prefFileName The file name without ".xml".
*/
public XSharedPreferences(String packageName, String prefFileName) {
mFile = new File(Environment.getDataDirectory(), "data/" + packageName + "/shared_prefs/" + prefFileName + ".xml");
mFilename = mFile.getAbsolutePath();
startLoadFromDisk();
}
/**
* Tries to make the preferences file world-readable.
*
* <p><strong>Warning:</strong> This is only meant to work around permission "fix" functions that are part
* of some recoveries. It doesn't replace the need to open preferences with {@code MODE_WORLD_READABLE}
* in the module's UI code. Otherwise, Android will set stricter permissions again during the next save.
*
* <p>This will only work if executed as root (e.g. {@code initZygote()}) and only if SELinux is disabled.
*
* @return {@code true} in case the file could be made world-readable.
*/
@SuppressLint("SetWorldReadable")
public boolean makeWorldReadable() {
if (!SELinuxHelper.getAppDataFileService().hasDirectFileAccess())
return false; // It doesn't make much sense to make the file readable if we wouldn't be able to access it anyway.
if (!mFile.exists()) // Just in case - the file should never be created if it doesn't exist.
return false;
return mFile.setReadable(true, false);
}
/**
* Returns the file that is backing these preferences.
*
* <p><strong>Warning:</strong> The file might not be accessible directly.
*/
public File getFile() {
return mFile;
}
private void startLoadFromDisk() {
synchronized (this) {
mLoaded = false;
}
new Thread("XSharedPreferences-load") {
@Override
public void run() {
synchronized (XSharedPreferences.this) {
loadFromDiskLocked();
}
}
}.start();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void loadFromDiskLocked() {
if (mLoaded) {
return;
}
Map map = null;
FileResult result = null;
try {
result = SELinuxHelper.getAppDataFileService().getFileInputStream(mFilename, mFileSize, mLastModified);
if (result.stream != null) {
map = XmlUtils.readMapXml(result.stream);
result.stream.close();
} else {
// The file is unchanged, keep the current values
map = mMap;
}
} catch (XmlPullParserException e) {
Log.w(TAG, "getSharedPreferences", e);
} catch (FileNotFoundException ignored) {
// SharedPreferencesImpl has a canRead() check, so it doesn't log anything in case the file doesn't exist
} catch (IOException e) {
Log.w(TAG, "getSharedPreferences", e);
} finally {
if (result != null && result.stream != null) {
try {
result.stream.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
mLoaded = true;
if (map != null) {
mMap = map;
mLastModified = result.mtime;
mFileSize = result.size;
} else {
mMap = new HashMap<>();
}
notifyAll();
}
/**
* Reload the settings from file if they have changed.
*
* <p><strong>Warning:</strong> With enforcing SELinux, this call might be quite expensive.
*/
public synchronized void reload() {
if (hasFileChanged())
startLoadFromDisk();
}
/**
* Check whether the file has changed since the last time it has been loaded.
*
* <p><strong>Warning:</strong> With enforcing SELinux, this call might be quite expensive.
*/
public synchronized boolean hasFileChanged() {
try {
FileResult result = SELinuxHelper.getAppDataFileService().statFile(mFilename);
return mLastModified != result.mtime || mFileSize != result.size;
} catch (FileNotFoundException ignored) {
// SharedPreferencesImpl doesn't log anything in case the file doesn't exist
return true;
} catch (IOException e) {
Log.w(TAG, "hasFileChanged", e);
return true;
}
}
private void awaitLoadedLocked() {
while (!mLoaded) {
try {
wait();
} catch (InterruptedException unused) {
}
}
}
/** @hide */
@Override
public Map<String, ?> getAll() {
synchronized (this) {
awaitLoadedLocked();
return new HashMap<>(mMap);
}
}
/** @hide */
@Override
public String getString(String key, String defValue) {
synchronized (this) {
awaitLoadedLocked();
String v = (String)mMap.get(key);
return v != null ? v : defValue;
}
}
/** @hide */
@Override
@SuppressWarnings("unchecked")
public Set<String> getStringSet(String key, Set<String> defValues) {
synchronized (this) {
awaitLoadedLocked();
Set<String> v = (Set<String>) mMap.get(key);
return v != null ? v : defValues;
}
}
/** @hide */
@Override
public int getInt(String key, int defValue) {
synchronized (this) {
awaitLoadedLocked();
Integer v = (Integer)mMap.get(key);
return v != null ? v : defValue;
}
}
/** @hide */
@Override
public long getLong(String key, long defValue) {
synchronized (this) {
awaitLoadedLocked();
Long v = (Long)mMap.get(key);
return v != null ? v : defValue;
}
}
/** @hide */
@Override
public float getFloat(String key, float defValue) {
synchronized (this) {
awaitLoadedLocked();
Float v = (Float)mMap.get(key);
return v != null ? v : defValue;
}
}
/** @hide */
@Override
public boolean getBoolean(String key, boolean defValue) {
synchronized (this) {
awaitLoadedLocked();
Boolean v = (Boolean)mMap.get(key);
return v != null ? v : defValue;
}
}
/** @hide */
@Override
public boolean contains(String key) {
synchronized (this) {
awaitLoadedLocked();
return mMap.containsKey(key);
}
}
/** @deprecated Not supported by this implementation. */
@Deprecated
@Override
public Editor edit() {
throw new UnsupportedOperationException("read-only implementation");
}
/** @deprecated Not supported by this implementation. */
@Deprecated
@Override
public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
throw new UnsupportedOperationException("listeners are not supported in this implementation");
}
/** @deprecated Not supported by this implementation. */
@Deprecated
@Override
public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
throw new UnsupportedOperationException("listeners are not supported in this implementation");
}
}
package de.robv.android.xposed;
import android.annotation.SuppressLint;
import android.util.Log;
import com.swift.sandhook.HookLog;
import com.swift.sandhook.SandHook;
import com.swift.sandhook.xposedcompat.XposedCompat;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import de.robv.android.xposed.callbacks.XC_InitPackageResources;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
/**
* This class contains most of Xposed's central logic, such as initialization and callbacks used by
* the native side. It also includes methods to add new hooks.
*/
@SuppressWarnings("JniMissingFunction")
public final class XposedBridge {
/**
* The system class loader which can be used to locate Android framework classes.
* Application classes cannot be retrieved from it.
*
* @see ClassLoader#getSystemClassLoader
*/
public static final ClassLoader BOOTCLASSLOADER = XposedBridge.class.getClassLoader();
/** @hide */
public static final String TAG = "SandXposed";
/** @deprecated Use {@link #getXposedVersion()} instead. */
@Deprecated
public static int XPOSED_BRIDGE_VERSION;
/*package*/ static boolean isZygote = true; // ed: RuntimeInit.main() tool process not supported yet
private static int runtime = 2;
private static final int RUNTIME_DALVIK = 1;
private static final int RUNTIME_ART = 2;
public static boolean disableHooks = false;
// This field is set "magically" on MIUI.
/*package*/ static long BOOT_START_TIME;
private static final Object[] EMPTY_ARRAY = new Object[0];
// built-in handlers
public static final Map<Member, CopyOnWriteSortedSet<XC_MethodHook>> sHookedMethodCallbacks = new HashMap<>();
public static final CopyOnWriteSortedSet<XC_LoadPackage> sLoadedPackageCallbacks = new CopyOnWriteSortedSet<>();
/*package*/ static final CopyOnWriteSortedSet<XC_InitPackageResources> sInitPackageResourcesCallbacks = new CopyOnWriteSortedSet<>();
private XposedBridge() {}
/**
* Called when native methods and other things are initialized, but before preloading classes etc.
* @hide
*/
@SuppressWarnings("deprecation")
public static void main(String[] args) {
}
private static void initXResources() throws IOException {
}
@SuppressLint("SetWorldReadable")
private static File ensureSuperDexFile(String clz, Class<?> realSuperClz, Class<?> topClz) throws IOException {
return null;
}
/**
* Returns the currently installed version of the Xposed framework.
*/
public static int getXposedVersion() {
return 90;
}
/**
* Writes a message to the Xposed error log.
*
* <p class="warning"><b>DON'T FLOOD THE LOG!!!</b> This is only meant for error logging.
* If you want to write information/debug messages, use logcat.
*
* @param text The log message.
*/
public synchronized static void log(String text) {
if (HookLog.DEBUG) {
Log.i(TAG, text);
}
}
/**
* Logs a stack trace to the Xposed error log.
*
* <p class="warning"><b>DON'T FLOOD THE LOG!!!</b> This is only meant for error logging.
* If you want to write information/debug messages, use logcat.
*
* @param t The Throwable object for the stack trace.
*/
public synchronized static void log(Throwable t) {
if (HookLog.DEBUG) {
Log.e(TAG, Log.getStackTraceString(t));
}
}
/**
* Hook any method (or constructor) with the specified callback. See below for some wrappers
* that make it easier to find a method/constructor in one step.
*
* @param hookMethod The method to be hooked.
* @param callback The callback to be executed when the hooked method is called.
* @return An object that can be used to remove the hook.
*
* @see XposedHelpers#findAndHookMethod(String, ClassLoader, String, Object...)
* @see XposedHelpers#findAndHookMethod(Class, String, Object...)
* @see #hookAllMethods
* @see XposedHelpers#findAndHookConstructor(String, ClassLoader, Object...)
* @see XposedHelpers#findAndHookConstructor(Class, Object...)
* @see #hookAllConstructors
*/
public static XC_MethodHook.Unhook hookMethod(Member hookMethod, XC_MethodHook callback) {
if (!(hookMethod instanceof Method) && !(hookMethod instanceof Constructor<?>)) {
throw new IllegalArgumentException("Only methods and constructors can be hooked: " + hookMethod.toString());
} else if (hookMethod.getDeclaringClass().isInterface()) {
throw new IllegalArgumentException("Cannot hook interfaces: " + hookMethod.toString());
} else if (Modifier.isAbstract(hookMethod.getModifiers())) {
throw new IllegalArgumentException("Cannot hook abstract methods: " + hookMethod.toString());
}
if (callback == null) {
throw new IllegalArgumentException("callback should not be null!");
}
boolean newMethod = false;
CopyOnWriteSortedSet<XC_MethodHook> callbacks;
synchronized (sHookedMethodCallbacks) {
callbacks = sHookedMethodCallbacks.get(hookMethod);
if (callbacks == null) {
callbacks = new CopyOnWriteSortedSet<>();
sHookedMethodCallbacks.put(hookMethod, callbacks);
newMethod = true;
}
}
callbacks.add(callback);
if (newMethod) {
Class<?> declaringClass = hookMethod.getDeclaringClass();
Class<?>[] parameterTypes;
Class<?> returnType;
if (runtime == RUNTIME_ART) {
parameterTypes = null;
returnType = null;
} else if (hookMethod instanceof Method) {
parameterTypes = ((Method) hookMethod).getParameterTypes();
returnType = ((Method) hookMethod).getReturnType();
} else {
parameterTypes = ((Constructor<?>) hookMethod).getParameterTypes();
returnType = null;
}
AdditionalHookInfo additionalInfo = new AdditionalHookInfo(callbacks, parameterTypes, returnType);
hookMethod(hookMethod, additionalInfo);
}
return callback.new Unhook(hookMethod);
}
/**
* Removes the callback for a hooked method/constructor.
*
* @deprecated Use {@link XC_MethodHook.Unhook#unhook} instead. An instance of the {@code Unhook}
* class is returned when you hook the method.
*
* @param hookMethod The method for which the callback should be removed.
* @param callback The reference to the callback as specified in {@link #hookMethod}.
*/
@Deprecated
public static void unhookMethod(Member hookMethod, XC_MethodHook callback) {
CopyOnWriteSortedSet<XC_MethodHook> callbacks;
synchronized (sHookedMethodCallbacks) {
callbacks = sHookedMethodCallbacks.get(hookMethod);
if (callbacks == null)
return;
}
callbacks.remove(callback);
}
/**
* Hooks all methods with a certain name that were declared in the specified class. Inherited
* methods and constructors are not considered. For constructors, use
* {@link #hookAllConstructors} instead.
*
* @param hookClass The class to check for declared methods.
* @param methodName The name of the method(s) to hook.
* @param callback The callback to be executed when the hooked methods are called.
* @return A set containing one object for each found method which can be used to unhook it.
*/
@SuppressWarnings("UnusedReturnValue")
public static Set<XC_MethodHook.Unhook> hookAllMethods(Class<?> hookClass, String methodName, XC_MethodHook callback) {
Set<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (Member method : hookClass.getDeclaredMethods())
if (method.getName().equals(methodName))
unhooks.add(hookMethod(method, callback));
return unhooks;
}
/**
* Hook all constructors of the specified class.
*
* @param hookClass The class to check for constructors.
* @param callback The callback to be executed when the hooked constructors are called.
* @return A set containing one object for each found constructor which can be used to unhook it.
*/
@SuppressWarnings("UnusedReturnValue")
public static Set<XC_MethodHook.Unhook> hookAllConstructors(Class<?> hookClass, XC_MethodHook callback) {
Set<XC_MethodHook.Unhook> unhooks = new HashSet<>();
for (Member constructor : hookClass.getDeclaredConstructors())
unhooks.add(hookMethod(constructor, callback));
return unhooks;
}
/**
* Adds a callback to be executed when an app ("Android package") is loaded.
*
* <p class="note">You probably don't need to call this. Simply implement {@link IXposedHookLoadPackage}
* in your module class and Xposed will take care of registering it as a callback.
*
* @param callback The callback to be executed.
* @hide
*/
public static void hookLoadPackage(XC_LoadPackage callback) {
synchronized (sLoadedPackageCallbacks) {
sLoadedPackageCallbacks.add(callback);
}
}
/**
* Adds a callback to be executed when the resources for an app are initialized.
*
* <p class="note">You probably don't need to call this. Simply implement {@link IXposedHookInitPackageResources}
* in your module class and Xposed will take care of registering it as a callback.
*
* @param callback The callback to be executed.
* @hide
*/
public static void hookInitPackageResources(XC_InitPackageResources callback) {
// TODO not supported yet
}
/**
* Intercept every call to the specified method and call a handler function instead.
* @param method The method to intercept
*/
private synchronized static void hookMethod(Member method, AdditionalHookInfo additionalInfoObj) {
XposedCompat.hookMethod(method, additionalInfoObj);
}
@SuppressWarnings("unused")
public static Object invokeOriginalMethod(final Member method, final Object thisObject,
final Object[] args)
throws NullPointerException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
try {
return SandHook.callOriginMethod(method, thisObject, args);
} catch (NullPointerException e) {
throw e;
} catch (IllegalAccessException e) {
throw e;
} catch (IllegalArgumentException e) {
throw e;
} catch (InvocationTargetException e) {
throw e;
} catch (Throwable throwable) {
throw new InvocationTargetException(throwable);
}
}
/**
* Basically the same as {@link Method#invoke}, but calls the original method
* as it was before the interception by Xposed. Also, access permissions are not checked.
*
* <p class="caution">There are very few cases where this method is needed. A common mistake is
* to replace a method and then invoke the original one based on dynamic conditions. This
* creates overhead and skips further hooks by other modules. Instead, just hook (don't replace)
* the method and call {@code param.setResult(null)} in {@link XC_MethodHook#beforeHookedMethod}
* if the original method should be skipped.
*
* @param method The method to be called.
* @param thisObject For non-static calls, the "this" pointer, otherwise {@code null}.
* @param args Arguments for the method call as Object[] array.
* @return The result returned from the invoked method.
* @throws NullPointerException
* if {@code receiver == null} for a non-static method
* @throws IllegalAccessException
* if this method is not accessible (see {@link AccessibleObject})
* @throws IllegalArgumentException
* if the number of arguments doesn't match the number of parameters, the receiver
* is incompatible with the declaring class, or an argument could not be unboxed
* or converted by a widening conversion to the corresponding parameter type
* @throws InvocationTargetException
* if an exception was thrown by the invoked method
*/
/** @hide */
public static final class CopyOnWriteSortedSet<E> {
private transient volatile Object[] elements = EMPTY_ARRAY;
@SuppressWarnings("UnusedReturnValue")
public synchronized boolean add(E e) {
int index = indexOf(e);
if (index >= 0)
return false;
Object[] newElements = new Object[elements.length + 1];
System.arraycopy(elements, 0, newElements, 0, elements.length);
newElements[elements.length] = e;
Arrays.sort(newElements);
elements = newElements;
return true;
}
@SuppressWarnings("UnusedReturnValue")
public synchronized boolean remove(E e) {
int index = indexOf(e);
if (index == -1)
return false;
Object[] newElements = new Object[elements.length - 1];
System.arraycopy(elements, 0, newElements, 0, index);
System.arraycopy(elements, index + 1, newElements, index, elements.length - index - 1);
elements = newElements;
return true;
}
private int indexOf(Object o) {
for (int i = 0; i < elements.length; i++) {
if (o.equals(elements[i]))
return i;
}
return -1;
}
public Object[] getSnapshot() {
return elements;
}
}
public static class AdditionalHookInfo {
public final CopyOnWriteSortedSet<XC_MethodHook> callbacks;
public final Class<?>[] parameterTypes;
public final Class<?> returnType;
private AdditionalHookInfo(CopyOnWriteSortedSet<XC_MethodHook> callbacks, Class<?>[] parameterTypes, Class<?> returnType) {
this.callbacks = callbacks;
this.parameterTypes = parameterTypes;
this.returnType = returnType;
}
}
}
package de.robv.android.xposed;
import android.content.res.AssetManager;
import android.content.res.Resources;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipFile;
import dalvik.system.DexFile;
import external.org.apache.commons.lang3.ClassUtils;
import external.org.apache.commons.lang3.reflect.MemberUtils;
/**
* Helpers that simplify hooking and calling methods/constructors, getting and settings fields, ...
*/
public final class XposedHelpers {
private XposedHelpers() {}
private static final HashMap<String, Field> fieldCache = new HashMap<>();
private static final HashMap<String, Method> methodCache = new HashMap<>();
private static final HashMap<String, Constructor<?>> constructorCache = new HashMap<>();
private static final WeakHashMap<Object, HashMap<String, Object>> additionalFields = new WeakHashMap<>();
private static final HashMap<String, ThreadLocal<AtomicInteger>> sMethodDepth = new HashMap<>();
/**
* Look up a class with the specified class loader.
*
* <p>There are various allowed syntaxes for the class name, but it's recommended to use one of
* these:
* <ul>
* <li>{@code java.lang.String}
* <li>{@code java.lang.String[]} (array)
* <li>{@code android.app.ActivityThread.ResourcesKey}
* <li>{@code android.app.ActivityThread$ResourcesKey}
* </ul>
*
* @param className The class name in one of the formats mentioned above.
* @param classLoader The class loader, or {@code null} for the boot class loader.
* @return A reference to the class.
* @throws ClassNotFoundError In case the class was not found.
*/
public static Class<?> findClass(String className, ClassLoader classLoader) {
if (classLoader == null)
classLoader = XposedBridge.BOOTCLASSLOADER;
try {
return ClassUtils.getClass(classLoader, className, false);
} catch (ClassNotFoundException e) {
throw new ClassNotFoundError(e);
}
}
/**
* Look up and return a class if it exists.
* Like {@link #findClass}, but doesn't throw an exception if the class doesn't exist.
*
* @param className The class name.
* @param classLoader The class loader, or {@code null} for the boot class loader.
* @return A reference to the class, or {@code null} if it doesn't exist.
*/
public static Class<?> findClassIfExists(String className, ClassLoader classLoader) {
try {
return findClass(className, classLoader);
} catch (ClassNotFoundError e) {
return null;
}
}
/**
* Look up a field in a class and set it to accessible.
*
* @param clazz The class which either declares or inherits the field.
* @param fieldName The field name.
* @return A reference to the field.
* @throws NoSuchFieldError In case the field was not found.
*/
public static Field findField(Class<?> clazz, String fieldName) {
String fullFieldName = clazz.getName() + '#' + fieldName;
if (fieldCache.containsKey(fullFieldName)) {
Field field = fieldCache.get(fullFieldName);
if (field == null)
throw new NoSuchFieldError(fullFieldName);
return field;
}
try {
Field field = findFieldRecursiveImpl(clazz, fieldName);
field.setAccessible(true);
fieldCache.put(fullFieldName, field);
return field;
} catch (NoSuchFieldException e) {
fieldCache.put(fullFieldName, null);
throw new NoSuchFieldError(fullFieldName);
}
}
/**
* Look up and return a field if it exists.
* Like {@link #findField}, but doesn't throw an exception if the field doesn't exist.
*
* @param clazz The class which either declares or inherits the field.
* @param fieldName The field name.
* @return A reference to the field, or {@code null} if it doesn't exist.
*/
public static Field findFieldIfExists(Class<?> clazz, String fieldName) {
try {
return findField(clazz, fieldName);
} catch (NoSuchFieldError e) {
return null;
}
}
private static Field findFieldRecursiveImpl(Class<?> clazz, String fieldName) throws NoSuchFieldException {
try {
return clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
while (true) {
clazz = clazz.getSuperclass();
if (clazz == null || clazz.equals(Object.class))
break;
try {
return clazz.getDeclaredField(fieldName);
} catch (NoSuchFieldException ignored) {}
}
throw e;
}
}
/**
* Returns the first field of the given type in a class.
* Might be useful for Proguard'ed classes to identify fields with unique types.
*
* @param clazz The class which either declares or inherits the field.
* @param type The type of the field.
* @return A reference to the first field of the given type.
* @throws NoSuchFieldError In case no matching field was not found.
*/
public static Field findFirstFieldByExactType(Class<?> clazz, Class<?> type) {
Class<?> clz = clazz;
do {
for (Field field : clz.getDeclaredFields()) {
if (field.getType() == type) {
field.setAccessible(true);
return field;
}
}
} while ((clz = clz.getSuperclass()) != null);
throw new NoSuchFieldError("Field of type " + type.getName() + " in class " + clazz.getName());
}
/**
* Look up a method and hook it. See {@link #findAndHookMethod(String, ClassLoader, String, Object...)}
* for details.
*/
public static XC_MethodHook.Unhook findAndHookMethod(Class<?> clazz, String methodName, Object... parameterTypesAndCallback) {
if (parameterTypesAndCallback.length == 0 || !(parameterTypesAndCallback[parameterTypesAndCallback.length-1] instanceof XC_MethodHook))
throw new IllegalArgumentException("no callback defined");
XC_MethodHook callback = (XC_MethodHook) parameterTypesAndCallback[parameterTypesAndCallback.length-1];
Method m = findMethodExact(clazz, methodName, getParameterClasses(clazz.getClassLoader(), parameterTypesAndCallback));
return XposedBridge.hookMethod(m, callback);
}
/**
* Look up a method and hook it. The last argument must be the callback for the hook.
*
* <p>This combines calls to {@link #findMethodExact(Class, String, Object...)} and
* {@link XposedBridge#hookMethod}.
*
* <p class="warning">The method must be declared or overridden in the given class, inherited
* methods are not considered! That's because each method implementation exists only once in
* the memory, and when classes inherit it, they just get another reference to the implementation.
* Hooking a method therefore applies to all classes inheriting the same implementation. You
* have to expect that the hook applies to subclasses (unless they override the method), but you
* shouldn't have to worry about hooks applying to superclasses, hence this "limitation".
* There could be undesired or even dangerous hooks otherwise, e.g. if you hook
* {@code SomeClass.equals()} and that class doesn't override the {@code equals()} on some ROMs,
* making you hook {@code Object.equals()} instead.
*
* <p>There are two ways to specify the parameter types. If you already have a reference to the
* {@link Class}, use that. For Android framework classes, you can often use something like
* {@code String.class}. If you don't have the class reference, you can simply use the
* full class name as a string, e.g. {@code java.lang.String} or {@code com.example.MyClass}.
* It will be passed to {@link #findClass} with the same class loader that is used for the target
* method, see its documentation for the allowed notations.
*
* <p>Primitive types, such as {@code int}, can be specified using {@code int.class} (recommended)
* or {@code Integer.TYPE}. Note that {@code Integer.class} doesn't refer to {@code int} but to
* {@code Integer}, which is a normal class (boxed primitive). Therefore it must not be used when
* the method expects an {@code int} parameter - it has to be used for {@code Integer} parameters
* though, so check the method signature in detail.
*
* <p>As last argument to this method (after the list of target method parameters), you need
* to specify the callback that should be executed when the method is invoked. It's usually
* an anonymous subclass of {@link XC_MethodHook} or {@link XC_MethodReplacement}.
*
* <p><b>Example</b>
* <pre class="prettyprint">
* // In order to hook this method ...
* package com.example;
* public class SomeClass {
* public int doSomething(String s, int i, MyClass m) {
* ...
* }
* }
*
* // ... you can use this call:
* findAndHookMethod("com.example.SomeClass", lpparam.classLoader, String.class, int.class, "com.example.MyClass", new XC_MethodHook() {
* &#64;Override
* protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
* String oldText = (String) param.args[0];
* Log.d("MyModule", oldText);
*
* param.args[0] = "test";
* param.args[1] = 42; // auto-boxing is working here
* setBooleanField(param.args[2], "great", true);
*
* // This would not work (as MyClass can't be resolved at compile time):
* // MyClass myClass = (MyClass) param.args[2];
* // myClass.great = true;
* }
* });
* </pre>
*
* @param className The name of the class which implements the method.
* @param classLoader The class loader for resolving the target and parameter classes.
* @param methodName The target method name.
* @param parameterTypesAndCallback The parameter types of the target method, plus the callback.
* @throws NoSuchMethodError In case the method was not found.
* @throws ClassNotFoundError In case the target class or one of the parameter types couldn't be resolved.
* @return An object which can be used to remove the callback again.
*/
public static XC_MethodHook.Unhook findAndHookMethod(String className, ClassLoader classLoader, String methodName, Object... parameterTypesAndCallback) {
return findAndHookMethod(findClass(className, classLoader), methodName, parameterTypesAndCallback);
}
/**
* Look up a method in a class and set it to accessible.
* See {@link #findMethodExact(String, ClassLoader, String, Object...)} for details.
*/
public static Method findMethodExact(Class<?> clazz, String methodName, Object... parameterTypes) {
return findMethodExact(clazz, methodName, getParameterClasses(clazz.getClassLoader(), parameterTypes));
}
/**
* Look up and return a method if it exists.
* See {@link #findMethodExactIfExists(String, ClassLoader, String, Object...)} for details.
*/
public static Method findMethodExactIfExists(Class<?> clazz, String methodName, Object... parameterTypes) {
try {
return findMethodExact(clazz, methodName, parameterTypes);
} catch (ClassNotFoundError | NoSuchMethodError e) {
return null;
}
}
/**
* Look up a method in a class and set it to accessible.
* The method must be declared or overridden in the given class.
*
* <p>See {@link #findAndHookMethod(String, ClassLoader, String, Object...)} for details about
* the method and parameter type resolution.
*
* @param className The name of the class which implements the method.
* @param classLoader The class loader for resolving the target and parameter classes.
* @param methodName The target method name.
* @param parameterTypes The parameter types of the target method.
* @throws NoSuchMethodError In case the method was not found.
* @throws ClassNotFoundError In case the target class or one of the parameter types couldn't be resolved.
* @return A reference to the method.
*/
public static Method findMethodExact(String className, ClassLoader classLoader, String methodName, Object... parameterTypes) {
return findMethodExact(findClass(className, classLoader), methodName, getParameterClasses(classLoader, parameterTypes));
}
/**
* Look up and return a method if it exists.
* Like {@link #findMethodExact(String, ClassLoader, String, Object...)}, but doesn't throw an
* exception if the method doesn't exist.
*
* @param className The name of the class which implements the method.
* @param classLoader The class loader for resolving the target and parameter classes.
* @param methodName The target method name.
* @param parameterTypes The parameter types of the target method.
* @return A reference to the method, or {@code null} if it doesn't exist.
*/
public static Method findMethodExactIfExists(String className, ClassLoader classLoader, String methodName, Object... parameterTypes) {
try {
return findMethodExact(className, classLoader, methodName, parameterTypes);
} catch (ClassNotFoundError | NoSuchMethodError e) {
return null;
}
}
/**
* Look up a method in a class and set it to accessible.
* See {@link #findMethodExact(String, ClassLoader, String, Object...)} for details.
*
* <p>This variant requires that you already have reference to all the parameter types.
*/
public static Method findMethodExact(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
String fullMethodName = clazz.getName() + '#' + methodName + getParametersString(parameterTypes) + "#exact";
if (methodCache.containsKey(fullMethodName)) {
Method method = methodCache.get(fullMethodName);
if (method == null)
throw new NoSuchMethodError(fullMethodName);
return method;
}
try {
Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
methodCache.put(fullMethodName, method);
return method;
} catch (NoSuchMethodException e) {
methodCache.put(fullMethodName, null);
throw new NoSuchMethodError(fullMethodName);
}
}
/**
* Returns an array of all methods declared/overridden in a class with the specified parameter types.
*
* <p>The return type is optional, it will not be compared if it is {@code null}.
* Use {@code void.class} if you want to search for methods returning nothing.
*
* @param clazz The class to look in.
* @param returnType The return type, or {@code null} (see above).
* @param parameterTypes The parameter types.
* @return An array with matching methods, all set to accessible already.
*/
public static Method[] findMethodsByExactParameters(Class<?> clazz, Class<?> returnType, Class<?>... parameterTypes) {
List<Method> result = new LinkedList<>();
for (Method method : clazz.getDeclaredMethods()) {
if (returnType != null && returnType != method.getReturnType())
continue;
Class<?>[] methodParameterTypes = method.getParameterTypes();
if (parameterTypes.length != methodParameterTypes.length)
continue;
boolean match = true;
for (int i = 0; i < parameterTypes.length; i++) {
if (parameterTypes[i] != methodParameterTypes[i]) {
match = false;
break;
}
}
if (!match)
continue;
method.setAccessible(true);
result.add(method);
}
return result.toArray(new Method[result.size()]);
}
/**
* Look up a method in a class and set it to accessible.
*
* <p>This does'nt only look for exact matches, but for the best match. All considered candidates
* must be compatible with the given parameter types, i.e. the parameters must be assignable
* to the method's formal parameters. Inherited methods are considered here.
*
* @param clazz The class which declares, inherits or overrides the method.
* @param methodName The method name.
* @param parameterTypes The types of the method's parameters.
* @return A reference to the best-matching method.
* @throws NoSuchMethodError In case no suitable method was found.
*/
public static Method findMethodBestMatch(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
String fullMethodName = clazz.getName() + '#' + methodName + getParametersString(parameterTypes) + "#bestmatch";
if (methodCache.containsKey(fullMethodName)) {
Method method = methodCache.get(fullMethodName);
if (method == null)
throw new NoSuchMethodError(fullMethodName);
return method;
}
try {
Method method = findMethodExact(clazz, methodName, parameterTypes);
methodCache.put(fullMethodName, method);
return method;
} catch (NoSuchMethodError ignored) {}
Method bestMatch = null;
Class<?> clz = clazz;
boolean considerPrivateMethods = true;
do {
for (Method method : clz.getDeclaredMethods()) {
// don't consider private methods of superclasses
if (!considerPrivateMethods && Modifier.isPrivate(method.getModifiers()))
continue;
// compare name and parameters
if (method.getName().equals(methodName) && ClassUtils.isAssignable(parameterTypes, method.getParameterTypes(), true)) {
// get accessible version of method
if (bestMatch == null || MemberUtils.compareParameterTypes(
method.getParameterTypes(),
bestMatch.getParameterTypes(),
parameterTypes) < 0) {
bestMatch = method;
}
}
}
considerPrivateMethods = false;
} while ((clz = clz.getSuperclass()) != null);
if (bestMatch != null) {
bestMatch.setAccessible(true);
methodCache.put(fullMethodName, bestMatch);
return bestMatch;
} else {
NoSuchMethodError e = new NoSuchMethodError(fullMethodName);
methodCache.put(fullMethodName, null);
throw e;
}
}
/**
* Look up a method in a class and set it to accessible.
*
* <p>See {@link #findMethodBestMatch(Class, String, Class...)} for details. This variant
* determines the parameter types from the classes of the given objects.
*/
public static Method findMethodBestMatch(Class<?> clazz, String methodName, Object... args) {
return findMethodBestMatch(clazz, methodName, getParameterTypes(args));
}
/**
* Look up a method in a class and set it to accessible.
*
* <p>See {@link #findMethodBestMatch(Class, String, Class...)} for details. This variant
* determines the parameter types from the classes of the given objects. For any item that is
* {@code null}, the type is taken from {@code parameterTypes} instead.
*/
public static Method findMethodBestMatch(Class<?> clazz, String methodName, Class<?>[] parameterTypes, Object[] args) {
Class<?>[] argsClasses = null;
for (int i = 0; i < parameterTypes.length; i++) {
if (parameterTypes[i] != null)
continue;
if (argsClasses == null)
argsClasses = getParameterTypes(args);
parameterTypes[i] = argsClasses[i];
}
return findMethodBestMatch(clazz, methodName, parameterTypes);
}
/**
* Returns an array with the classes of the given objects.
*/
public static Class<?>[] getParameterTypes(Object... args) {
Class<?>[] clazzes = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) {
clazzes[i] = (args[i] != null) ? args[i].getClass() : null;
}
return clazzes;
}
/**
* Retrieve classes from an array, where each element might either be a Class
* already, or a String with the full class name.
*/
private static Class<?>[] getParameterClasses(ClassLoader classLoader, Object[] parameterTypesAndCallback) {
Class<?>[] parameterClasses = null;
for (int i = parameterTypesAndCallback.length - 1; i >= 0; i--) {
Object type = parameterTypesAndCallback[i];
if (type == null)
throw new ClassNotFoundError("parameter type must not be null", null);
// ignore trailing callback
if (type instanceof XC_MethodHook)
continue;
if (parameterClasses == null)
parameterClasses = new Class<?>[i+1];
if (type instanceof Class)
parameterClasses[i] = (Class<?>) type;
else if (type instanceof String)
parameterClasses[i] = findClass((String) type, classLoader);
else
throw new ClassNotFoundError("parameter type must either be specified as Class or String", null);
}
// if there are no arguments for the method
if (parameterClasses == null)
parameterClasses = new Class<?>[0];
return parameterClasses;
}
/**
* Returns an array of the given classes.
*/
public static Class<?>[] getClassesAsArray(Class<?>... clazzes) {
return clazzes;
}
private static String getParametersString(Class<?>... clazzes) {
StringBuilder sb = new StringBuilder("(");
boolean first = true;
for (Class<?> clazz : clazzes) {
if (first)
first = false;
else
sb.append(",");
if (clazz != null)
sb.append(clazz.getCanonicalName());
else
sb.append("null");
}
sb.append(")");
return sb.toString();
}
/**
* Look up a constructor of a class and set it to accessible.
* See {@link #findMethodExact(String, ClassLoader, String, Object...)} for details.
*/
public static Constructor<?> findConstructorExact(Class<?> clazz, Object... parameterTypes) {
return findConstructorExact(clazz, getParameterClasses(clazz.getClassLoader(), parameterTypes));
}
/**
* Look up and return a constructor if it exists.
* See {@link #findMethodExactIfExists(String, ClassLoader, String, Object...)} for details.
*/
public static Constructor<?> findConstructorExactIfExists(Class<?> clazz, Object... parameterTypes) {
try {
return findConstructorExact(clazz, parameterTypes);
} catch (ClassNotFoundError | NoSuchMethodError e) {
return null;
}
}
/**
* Look up a constructor of a class and set it to accessible.
* See {@link #findMethodExact(String, ClassLoader, String, Object...)} for details.
*/
public static Constructor<?> findConstructorExact(String className, ClassLoader classLoader, Object... parameterTypes) {
return findConstructorExact(findClass(className, classLoader), getParameterClasses(classLoader, parameterTypes));
}
/**
* Look up and return a constructor if it exists.
* See {@link #findMethodExactIfExists(String, ClassLoader, String, Object...)} for details.
*/
public static Constructor<?> findConstructorExactIfExists(String className, ClassLoader classLoader, Object... parameterTypes) {
try {
return findConstructorExact(className, classLoader, parameterTypes);
} catch (ClassNotFoundError | NoSuchMethodError e) {
return null;
}
}
/**
* Look up a constructor of a class and set it to accessible.
* See {@link #findMethodExact(String, ClassLoader, String, Object...)} for details.
*/
public static Constructor<?> findConstructorExact(Class<?> clazz, Class<?>... parameterTypes) {
String fullConstructorName = clazz.getName() + getParametersString(parameterTypes) + "#exact";
if (constructorCache.containsKey(fullConstructorName)) {
Constructor<?> constructor = constructorCache.get(fullConstructorName);
if (constructor == null)
throw new NoSuchMethodError(fullConstructorName);
return constructor;
}
try {
Constructor<?> constructor = clazz.getDeclaredConstructor(parameterTypes);
constructor.setAccessible(true);
constructorCache.put(fullConstructorName, constructor);
return constructor;
} catch (NoSuchMethodException e) {
constructorCache.put(fullConstructorName, null);
throw new NoSuchMethodError(fullConstructorName);
}
}
/**
* Look up a constructor and hook it. See {@link #findAndHookMethod(String, ClassLoader, String, Object...)}
* for details.
*/
public static XC_MethodHook.Unhook findAndHookConstructor(Class<?> clazz, Object... parameterTypesAndCallback) {
if (parameterTypesAndCallback.length == 0 || !(parameterTypesAndCallback[parameterTypesAndCallback.length-1] instanceof XC_MethodHook))
throw new IllegalArgumentException("no callback defined");
XC_MethodHook callback = (XC_MethodHook) parameterTypesAndCallback[parameterTypesAndCallback.length-1];
Constructor<?> m = findConstructorExact(clazz, getParameterClasses(clazz.getClassLoader(), parameterTypesAndCallback));
return XposedBridge.hookMethod(m, callback);
}
/**
* Look up a constructor and hook it. See {@link #findAndHookMethod(String, ClassLoader, String, Object...)}
* for details.
*/
public static XC_MethodHook.Unhook findAndHookConstructor(String className, ClassLoader classLoader, Object... parameterTypesAndCallback) {
return findAndHookConstructor(findClass(className, classLoader), parameterTypesAndCallback);
}
/**
* Look up a constructor in a class and set it to accessible.
*
* <p>See {@link #findMethodBestMatch(Class, String, Class...)} for details.
*/
public static Constructor<?> findConstructorBestMatch(Class<?> clazz, Class<?>... parameterTypes) {
String fullConstructorName = clazz.getName() + getParametersString(parameterTypes) + "#bestmatch";
if (constructorCache.containsKey(fullConstructorName)) {
Constructor<?> constructor = constructorCache.get(fullConstructorName);
if (constructor == null)
throw new NoSuchMethodError(fullConstructorName);
return constructor;
}
try {
Constructor<?> constructor = findConstructorExact(clazz, parameterTypes);
constructorCache.put(fullConstructorName, constructor);
return constructor;
} catch (NoSuchMethodError ignored) {}
Constructor<?> bestMatch = null;
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
for (Constructor<?> constructor : constructors) {
// compare name and parameters
if (ClassUtils.isAssignable(parameterTypes, constructor.getParameterTypes(), true)) {
// get accessible version of method
if (bestMatch == null || MemberUtils.compareParameterTypes(
constructor.getParameterTypes(),
bestMatch.getParameterTypes(),
parameterTypes) < 0) {
bestMatch = constructor;
}
}
}
if (bestMatch != null) {
bestMatch.setAccessible(true);
constructorCache.put(fullConstructorName, bestMatch);
return bestMatch;
} else {
NoSuchMethodError e = new NoSuchMethodError(fullConstructorName);
constructorCache.put(fullConstructorName, null);
throw e;
}
}
/**
* Look up a constructor in a class and set it to accessible.
*
* <p>See {@link #findMethodBestMatch(Class, String, Class...)} for details. This variant
* determines the parameter types from the classes of the given objects.
*/
public static Constructor<?> findConstructorBestMatch(Class<?> clazz, Object... args) {
return findConstructorBestMatch(clazz, getParameterTypes(args));
}
/**
* Look up a constructor in a class and set it to accessible.
*
* <p>See {@link #findMethodBestMatch(Class, String, Class...)} for details. This variant
* determines the parameter types from the classes of the given objects. For any item that is
* {@code null}, the type is taken from {@code parameterTypes} instead.
*/
public static Constructor<?> findConstructorBestMatch(Class<?> clazz, Class<?>[] parameterTypes, Object[] args) {
Class<?>[] argsClasses = null;
for (int i = 0; i < parameterTypes.length; i++) {
if (parameterTypes[i] != null)
continue;
if (argsClasses == null)
argsClasses = getParameterTypes(args);
parameterTypes[i] = argsClasses[i];
}
return findConstructorBestMatch(clazz, parameterTypes);
}
/**
* Thrown when a class loader is unable to find a class. Unlike {@link ClassNotFoundException},
* callers are not forced to explicitly catch this. If uncaught, the error will be passed to the
* next caller in the stack.
*/
public static final class ClassNotFoundError extends Error {
private static final long serialVersionUID = -1070936889459514628L;
/** @hide */
public ClassNotFoundError(Throwable cause) {
super(cause);
}
/** @hide */
public ClassNotFoundError(String detailMessage, Throwable cause) {
super(detailMessage, cause);
}
}
/**
* Returns the index of the first parameter declared with the given type.
*
* @throws NoSuchFieldError if there is no parameter with that type.
* @hide
*/
public static int getFirstParameterIndexByType(Member method, Class<?> type) {
Class<?>[] classes = (method instanceof Method) ?
((Method) method).getParameterTypes() : ((Constructor) method).getParameterTypes();
for (int i = 0 ; i < classes.length; i++) {
if (classes[i] == type) {
return i;
}
}
throw new NoSuchFieldError("No parameter of type " + type + " found in " + method);
}
/**
* Returns the index of the parameter declared with the given type, ensuring that there is exactly one such parameter.
*
* @throws NoSuchFieldError if there is no or more than one parameter with that type.
* @hide
*/
public static int getParameterIndexByType(Member method, Class<?> type) {
Class<?>[] classes = (method instanceof Method) ?
((Method) method).getParameterTypes() : ((Constructor) method).getParameterTypes();
int idx = -1;
for (int i = 0 ; i < classes.length; i++) {
if (classes[i] == type) {
if (idx == -1) {
idx = i;
} else {
throw new NoSuchFieldError("More than one parameter of type " + type + " found in " + method);
}
}
}
if (idx != -1) {
return idx;
} else {
throw new NoSuchFieldError("No parameter of type " + type + " found in " + method);
}
}
//#################################################################################################
/** Sets the value of an object field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static void setObjectField(Object obj, String fieldName, Object value) {
try {
findField(obj.getClass(), fieldName).set(obj, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a {@code boolean} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static void setBooleanField(Object obj, String fieldName, boolean value) {
try {
findField(obj.getClass(), fieldName).setBoolean(obj, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a {@code byte} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static void setByteField(Object obj, String fieldName, byte value) {
try {
findField(obj.getClass(), fieldName).setByte(obj, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a {@code char} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static void setCharField(Object obj, String fieldName, char value) {
try {
findField(obj.getClass(), fieldName).setChar(obj, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a {@code double} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static void setDoubleField(Object obj, String fieldName, double value) {
try {
findField(obj.getClass(), fieldName).setDouble(obj, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a {@code float} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static void setFloatField(Object obj, String fieldName, float value) {
try {
findField(obj.getClass(), fieldName).setFloat(obj, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of an {@code int} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static void setIntField(Object obj, String fieldName, int value) {
try {
findField(obj.getClass(), fieldName).setInt(obj, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a {@code long} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static void setLongField(Object obj, String fieldName, long value) {
try {
findField(obj.getClass(), fieldName).setLong(obj, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a {@code short} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static void setShortField(Object obj, String fieldName, short value) {
try {
findField(obj.getClass(), fieldName).setShort(obj, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
//#################################################################################################
/** Returns the value of an object field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static Object getObjectField(Object obj, String fieldName) {
try {
return findField(obj.getClass(), fieldName).get(obj);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** For inner classes, returns the surrounding instance, i.e. the {@code this} reference of the surrounding class. */
public static Object getSurroundingThis(Object obj) {
return getObjectField(obj, "this$0");
}
/** Returns the value of a {@code boolean} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public static boolean getBooleanField(Object obj, String fieldName) {
try {
return findField(obj.getClass(), fieldName).getBoolean(obj);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Returns the value of a {@code byte} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static byte getByteField(Object obj, String fieldName) {
try {
return findField(obj.getClass(), fieldName).getByte(obj);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Returns the value of a {@code char} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static char getCharField(Object obj, String fieldName) {
try {
return findField(obj.getClass(), fieldName).getChar(obj);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Returns the value of a {@code double} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static double getDoubleField(Object obj, String fieldName) {
try {
return findField(obj.getClass(), fieldName).getDouble(obj);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Returns the value of a {@code float} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static float getFloatField(Object obj, String fieldName) {
try {
return findField(obj.getClass(), fieldName).getFloat(obj);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Returns the value of an {@code int} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static int getIntField(Object obj, String fieldName) {
try {
return findField(obj.getClass(), fieldName).getInt(obj);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Returns the value of a {@code long} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static long getLongField(Object obj, String fieldName) {
try {
return findField(obj.getClass(), fieldName).getLong(obj);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Returns the value of a {@code short} field in the given object instance. A class reference is not sufficient! See also {@link #findField}. */
public static short getShortField(Object obj, String fieldName) {
try {
return findField(obj.getClass(), fieldName).getShort(obj);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
//#################################################################################################
/** Sets the value of a static object field in the given class. See also {@link #findField}. */
public static void setStaticObjectField(Class<?> clazz, String fieldName, Object value) {
try {
findField(clazz, fieldName).set(null, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code boolean} field in the given class. See also {@link #findField}. */
public static void setStaticBooleanField(Class<?> clazz, String fieldName, boolean value) {
try {
findField(clazz, fieldName).setBoolean(null, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code byte} field in the given class. See also {@link #findField}. */
public static void setStaticByteField(Class<?> clazz, String fieldName, byte value) {
try {
findField(clazz, fieldName).setByte(null, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code char} field in the given class. See also {@link #findField}. */
public static void setStaticCharField(Class<?> clazz, String fieldName, char value) {
try {
findField(clazz, fieldName).setChar(null, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code double} field in the given class. See also {@link #findField}. */
public static void setStaticDoubleField(Class<?> clazz, String fieldName, double value) {
try {
findField(clazz, fieldName).setDouble(null, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code float} field in the given class. See also {@link #findField}. */
public static void setStaticFloatField(Class<?> clazz, String fieldName, float value) {
try {
findField(clazz, fieldName).setFloat(null, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code int} field in the given class. See also {@link #findField}. */
public static void setStaticIntField(Class<?> clazz, String fieldName, int value) {
try {
findField(clazz, fieldName).setInt(null, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code long} field in the given class. See also {@link #findField}. */
public static void setStaticLongField(Class<?> clazz, String fieldName, long value) {
try {
findField(clazz, fieldName).setLong(null, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code short} field in the given class. See also {@link #findField}. */
public static void setStaticShortField(Class<?> clazz, String fieldName, short value) {
try {
findField(clazz, fieldName).setShort(null, value);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
//#################################################################################################
/** Returns the value of a static object field in the given class. See also {@link #findField}. */
public static Object getStaticObjectField(Class<?> clazz, String fieldName) {
try {
return findField(clazz, fieldName).get(null);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Returns the value of a static {@code boolean} field in the given class. See also {@link #findField}. */
public static boolean getStaticBooleanField(Class<?> clazz, String fieldName) {
try {
return findField(clazz, fieldName).getBoolean(null);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code byte} field in the given class. See also {@link #findField}. */
public static byte getStaticByteField(Class<?> clazz, String fieldName) {
try {
return findField(clazz, fieldName).getByte(null);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code char} field in the given class. See also {@link #findField}. */
public static char getStaticCharField(Class<?> clazz, String fieldName) {
try {
return findField(clazz, fieldName).getChar(null);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code double} field in the given class. See also {@link #findField}. */
public static double getStaticDoubleField(Class<?> clazz, String fieldName) {
try {
return findField(clazz, fieldName).getDouble(null);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code float} field in the given class. See also {@link #findField}. */
public static float getStaticFloatField(Class<?> clazz, String fieldName) {
try {
return findField(clazz, fieldName).getFloat(null);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code int} field in the given class. See also {@link #findField}. */
public static int getStaticIntField(Class<?> clazz, String fieldName) {
try {
return findField(clazz, fieldName).getInt(null);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code long} field in the given class. See also {@link #findField}. */
public static long getStaticLongField(Class<?> clazz, String fieldName) {
try {
return findField(clazz, fieldName).getLong(null);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
/** Sets the value of a static {@code short} field in the given class. See also {@link #findField}. */
public static short getStaticShortField(Class<?> clazz, String fieldName) {
try {
return findField(clazz, fieldName).getShort(null);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
}
}
//#################################################################################################
/**
* Calls an instance or static method of the given object.
* The method is resolved using {@link #findMethodBestMatch(Class, String, Object...)}.
*
* @param obj The object instance. A class reference is not sufficient!
* @param methodName The method name.
* @param args The arguments for the method call.
* @throws NoSuchMethodError In case no suitable method was found.
* @throws InvocationTargetError In case an exception was thrown by the invoked method.
*/
public static Object callMethod(Object obj, String methodName, Object... args) {
try {
return findMethodBestMatch(obj.getClass(), methodName, args).invoke(obj, args);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
} catch (InvocationTargetException e) {
throw new InvocationTargetError(e.getCause());
}
}
/**
* Calls an instance or static method of the given object.
* See {@link #callMethod(Object, String, Object...)}.
*
* <p>This variant allows you to specify parameter types, which can help in case there are multiple
* methods with the same name, especially if you call it with {@code null} parameters.
*/
public static Object callMethod(Object obj, String methodName, Class<?>[] parameterTypes, Object... args) {
try {
return findMethodBestMatch(obj.getClass(), methodName, parameterTypes, args).invoke(obj, args);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
} catch (InvocationTargetException e) {
throw new InvocationTargetError(e.getCause());
}
}
/**
* Calls a static method of the given class.
* The method is resolved using {@link #findMethodBestMatch(Class, String, Object...)}.
*
* @param clazz The class reference.
* @param methodName The method name.
* @param args The arguments for the method call.
* @throws NoSuchMethodError In case no suitable method was found.
* @throws InvocationTargetError In case an exception was thrown by the invoked method.
*/
public static Object callStaticMethod(Class<?> clazz, String methodName, Object... args) {
try {
return findMethodBestMatch(clazz, methodName, args).invoke(null, args);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
} catch (InvocationTargetException e) {
throw new InvocationTargetError(e.getCause());
}
}
/**
* Calls a static method of the given class.
* See {@link #callStaticMethod(Class, String, Object...)}.
*
* <p>This variant allows you to specify parameter types, which can help in case there are multiple
* methods with the same name, especially if you call it with {@code null} parameters.
*/
public static Object callStaticMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes, Object... args) {
try {
return findMethodBestMatch(clazz, methodName, parameterTypes, args).invoke(null, args);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
} catch (InvocationTargetException e) {
throw new InvocationTargetError(e.getCause());
}
}
/**
* This class provides a wrapper for an exception thrown by a method invocation.
*
* @see #callMethod(Object, String, Object...)
* @see #callStaticMethod(Class, String, Object...)
* @see #newInstance(Class, Object...)
*/
public static final class InvocationTargetError extends Error {
private static final long serialVersionUID = -1070936889459514628L;
/** @hide */
public InvocationTargetError(Throwable cause) {
super(cause);
}
}
//#################################################################################################
/**
* Creates a new instance of the given class.
* The constructor is resolved using {@link #findConstructorBestMatch(Class, Object...)}.
*
* @param clazz The class reference.
* @param args The arguments for the constructor call.
* @throws NoSuchMethodError In case no suitable constructor was found.
* @throws InvocationTargetError In case an exception was thrown by the invoked method.
* @throws InstantiationError In case the class cannot be instantiated.
*/
public static Object newInstance(Class<?> clazz, Object... args) {
try {
return findConstructorBestMatch(clazz, args).newInstance(args);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
} catch (InvocationTargetException e) {
throw new InvocationTargetError(e.getCause());
} catch (InstantiationException e) {
throw new InstantiationError(e.getMessage());
}
}
/**
* Creates a new instance of the given class.
* See {@link #newInstance(Class, Object...)}.
*
* <p>This variant allows you to specify parameter types, which can help in case there are multiple
* constructors with the same name, especially if you call it with {@code null} parameters.
*/
public static Object newInstance(Class<?> clazz, Class<?>[] parameterTypes, Object... args) {
try {
return findConstructorBestMatch(clazz, parameterTypes, args).newInstance(args);
} catch (IllegalAccessException e) {
// should not happen
XposedBridge.log(e);
throw new IllegalAccessError(e.getMessage());
} catch (IllegalArgumentException e) {
throw e;
} catch (InvocationTargetException e) {
throw new InvocationTargetError(e.getCause());
} catch (InstantiationException e) {
throw new InstantiationError(e.getMessage());
}
}
//#################################################################################################
/**
* Attaches any value to an object instance. This simulates adding an instance field.
* The value can be retrieved again with {@link #getAdditionalInstanceField}.
*
* @param obj The object instance for which the value should be stored.
* @param key The key in the value map for this object instance.
* @param value The value to store.
* @return The previously stored value for this instance/key combination, or {@code null} if there was none.
*/
public static Object setAdditionalInstanceField(Object obj, String key, Object value) {
if (obj == null)
throw new NullPointerException("object must not be null");
if (key == null)
throw new NullPointerException("key must not be null");
HashMap<String, Object> objectFields;
synchronized (additionalFields) {
objectFields = additionalFields.get(obj);
if (objectFields == null) {
objectFields = new HashMap<>();
additionalFields.put(obj, objectFields);
}
}
synchronized (objectFields) {
return objectFields.put(key, value);
}
}
/**
* Returns a value which was stored with {@link #setAdditionalInstanceField}.
*
* @param obj The object instance for which the value has been stored.
* @param key The key in the value map for this object instance.
* @return The stored value for this instance/key combination, or {@code null} if there is none.
*/
public static Object getAdditionalInstanceField(Object obj, String key) {
if (obj == null)
throw new NullPointerException("object must not be null");
if (key == null)
throw new NullPointerException("key must not be null");
HashMap<String, Object> objectFields;
synchronized (additionalFields) {
objectFields = additionalFields.get(obj);
if (objectFields == null)
return null;
}
synchronized (objectFields) {
return objectFields.get(key);
}
}
/**
* Removes and returns a value which was stored with {@link #setAdditionalInstanceField}.
*
* @param obj The object instance for which the value has been stored.
* @param key The key in the value map for this object instance.
* @return The previously stored value for this instance/key combination, or {@code null} if there was none.
*/
public static Object removeAdditionalInstanceField(Object obj, String key) {
if (obj == null)
throw new NullPointerException("object must not be null");
if (key == null)
throw new NullPointerException("key must not be null");
HashMap<String, Object> objectFields;
synchronized (additionalFields) {
objectFields = additionalFields.get(obj);
if (objectFields == null)
return null;
}
synchronized (objectFields) {
return objectFields.remove(key);
}
}
/** Like {@link #setAdditionalInstanceField}, but the value is stored for the class of {@code obj}. */
public static Object setAdditionalStaticField(Object obj, String key, Object value) {
return setAdditionalInstanceField(obj.getClass(), key, value);
}
/** Like {@link #getAdditionalInstanceField}, but the value is returned for the class of {@code obj}. */
public static Object getAdditionalStaticField(Object obj, String key) {
return getAdditionalInstanceField(obj.getClass(), key);
}
/** Like {@link #removeAdditionalInstanceField}, but the value is removed and returned for the class of {@code obj}. */
public static Object removeAdditionalStaticField(Object obj, String key) {
return removeAdditionalInstanceField(obj.getClass(), key);
}
/** Like {@link #setAdditionalInstanceField}, but the value is stored for {@code clazz}. */
public static Object setAdditionalStaticField(Class<?> clazz, String key, Object value) {
return setAdditionalInstanceField(clazz, key, value);
}
/** Like {@link #setAdditionalInstanceField}, but the value is returned for {@code clazz}. */
public static Object getAdditionalStaticField(Class<?> clazz, String key) {
return getAdditionalInstanceField(clazz, key);
}
/** Like {@link #setAdditionalInstanceField}, but the value is removed and returned for {@code clazz}. */
public static Object removeAdditionalStaticField(Class<?> clazz, String key) {
return removeAdditionalInstanceField(clazz, key);
}
//#################################################################################################
/**
* Loads an asset from a resource object and returns the content as {@code byte} array.
*
* @param res The resources from which the asset should be loaded.
* @param path The path to the asset, as in {@link AssetManager#open}.
* @return The content of the asset.
*/
public static byte[] assetAsByteArray(Resources res, String path) throws IOException {
return inputStreamToByteArray(res.getAssets().open(path));
}
/*package*/ static byte[] inputStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
byte[] temp = new byte[1024];
int read;
while ((read = is.read(temp)) > 0) {
buf.write(temp, 0, read);
}
is.close();
return buf.toByteArray();
}
/**
* Invokes the {@link Closeable#close()} method, ignoring IOExceptions.
*/
/*package*/ static void closeSilently(Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException ignored) {}
}
}
/**
* Invokes the {@link DexFile#close()} method, ignoring IOExceptions.
*/
/*package*/ static void closeSilently(DexFile dexFile) {
if (dexFile != null) {
try {
dexFile.close();
} catch (IOException ignored) {}
}
}
/**
* Invokes the {@link ZipFile#close()} method, ignoring IOExceptions.
*/
/*package*/ static void closeSilently(ZipFile zipFile) {
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException ignored) {}
}
}
/**
* Returns the lowercase hex string representation of a file's MD5 hash sum.
*/
public static String getMD5Sum(String file) throws IOException {
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[8192];
int read;
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
is.close();
byte[] md5sum = digest.digest();
BigInteger bigInt = new BigInteger(1, md5sum);
return bigInt.toString(16);
} catch (NoSuchAlgorithmException e) {
return "";
}
}
//#################################################################################################
/**
* Increments the depth counter for the given method.
*
* <p>The intention of the method depth counter is to keep track of the call depth for recursive
* methods, e.g. to override parameters only for the outer call. The Xposed framework uses this
* to load drawable replacements only once per call, even when multiple
* {@link Resources#getDrawable} variants call each other.
*
* @param method The method name. Should be prefixed with a unique, module-specific string.
* @return The updated depth.
*/
public static int incrementMethodDepth(String method) {
return getMethodDepthCounter(method).get().incrementAndGet();
}
/**
* Decrements the depth counter for the given method.
* See {@link #incrementMethodDepth} for details.
*
* @param method The method name. Should be prefixed with a unique, module-specific string.
* @return The updated depth.
*/
public static int decrementMethodDepth(String method) {
return getMethodDepthCounter(method).get().decrementAndGet();
}
/**
* Returns the current depth counter for the given method.
* See {@link #incrementMethodDepth} for details.
*
* @param method The method name. Should be prefixed with a unique, module-specific string.
* @return The updated depth.
*/
public static int getMethodDepth(String method) {
return getMethodDepthCounter(method).get().get();
}
private static ThreadLocal<AtomicInteger> getMethodDepthCounter(String method) {
synchronized (sMethodDepth) {
ThreadLocal<AtomicInteger> counter = sMethodDepth.get(method);
if (counter == null) {
counter = new ThreadLocal<AtomicInteger>() {
@Override
protected AtomicInteger initialValue() {
return new AtomicInteger();
}
};
sMethodDepth.put(method, counter);
}
return counter;
}
}
/*package*/ static boolean fileContains(File file, String str) throws IOException {
// There are certainly more efficient algorithms (e.g. Boyer-Moore used in grep),
// but the naive approach should be sufficient here.
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
String line;
while ((line = in.readLine()) != null) {
if (line.contains(str)) {
return true;
}
}
return false;
} finally {
closeSilently(in);
}
}
//#################################################################################################
/**
* Returns the method that is overridden by the given method.
* It returns {@code null} if the method doesn't override another method or if that method is
* abstract, i.e. if this is the first implementation in the hierarchy.
*/
/*package*/ static Method getOverriddenMethod(Method method) {
int modifiers = method.getModifiers();
if (Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers)) {
return null;
}
String name = method.getName();
Class<?>[] parameters = method.getParameterTypes();
Class<?> clazz = method.getDeclaringClass().getSuperclass();
while (clazz != null) {
try {
Method superMethod = clazz.getDeclaredMethod(name, parameters);
modifiers = superMethod.getModifiers();
if (!Modifier.isPrivate(modifiers) && !Modifier.isAbstract(modifiers)) {
return superMethod;
} else {
return null;
}
} catch (NoSuchMethodException ignored) {
clazz = clazz.getSuperclass();
}
}
return null;
}
/**
* Returns all methods which this class overrides.
*/
/*package*/ static Set<Method> getOverriddenMethods(Class<?> clazz) {
Set<Method> methods = new HashSet<>();
for (Method method : clazz.getDeclaredMethods()) {
Method overridden = getOverriddenMethod(method);
if (overridden != null) {
methods.add(overridden);
}
}
return methods;
}
//#################################################################################################
// TODO helpers for view traversing
/*To make it easier, I will try and implement some more helpers:
- add view before/after existing view (I already mentioned that I think)
- get index of view in its parent
- get next/previous sibling (maybe with an optional argument "type", that might be ImageView.class and gives you the next sibling that is an ImageView)?
- get next/previous element (similar to the above, but would also work if the next element has a different parent, it would just go up the hierarchy and then down again until it finds a matching element)
- find the first child that is an instance of a specified class
- find all (direct or indirect) children of a specified class
*/
}
package de.robv.android.xposed;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import dalvik.system.DexClassLoader;
import dalvik.system.DexFile;
import static de.robv.android.xposed.XposedHelpers.closeSilently;
public final class XposedInit {
private static final String TAG = XposedBridge.TAG;
private static final String INSTANT_RUN_CLASS = "com.android.tools.fd.runtime.BootstrapApplication";
// TODO not supported yet
private static boolean disableResources = true;
private XposedInit() {
}
private static volatile AtomicBoolean bootstrapHooked = new AtomicBoolean(false);
/**
* Hook some methods which we want to create an easier interface for developers.
*/
/*package*/
static void hookResources() throws Throwable {
// ed: not for now
}
private static boolean needsToCloseFilesForFork() {
// ed: we always start to do our work after forking finishes
return false;
}
/**
* Try to load all modules defined in <code>INSTALLER_DATA_BASE_DIR/conf/modules.list</code>
*/
private static volatile AtomicBoolean modulesLoaded = new AtomicBoolean(false);
/**
* Load a module from an APK by calling the init(String) method for all classes defined
* in <code>assets/xposed_init</code>.
*/
public static void loadModule(String modulePath, String moduleOdexDir, String moduleSoPath,ClassLoader topClassLoader) {
if (!new File(modulePath).exists()) {
Log.e(TAG, " File does not exist");
return;
}
DexFile dexFile;
try {
dexFile = new DexFile(modulePath);
} catch (IOException e) {
Log.e(TAG, " Cannot load module", e);
return;
}
if (dexFile.loadClass(INSTANT_RUN_CLASS, topClassLoader) != null) {
Log.e(TAG, " Cannot load module, please disable \"Instant Run\" in Android Studio.");
closeSilently(dexFile);
return;
}
if (dexFile.loadClass(XposedBridge.class.getName(), topClassLoader) != null) {
Log.e(TAG, " Cannot load module:");
Log.e(TAG, " The Xposed API classes are compiled into the module's APK.");
Log.e(TAG, " This may cause strange issues and must be fixed by the module developer.");
Log.e(TAG, " For details, see: http://api.xposed.info/using.html");
closeSilently(dexFile);
return;
}
closeSilently(dexFile);
ZipFile zipFile = null;
InputStream is;
try {
zipFile = new ZipFile(modulePath);
ZipEntry zipEntry = zipFile.getEntry("assets/xposed_init");
if (zipEntry == null) {
Log.e(TAG, " assets/xposed_init not found in the APK");
closeSilently(zipFile);
return;
}
is = zipFile.getInputStream(zipEntry);
} catch (IOException e) {
Log.e(TAG, " Cannot read assets/xposed_init in the APK", e);
closeSilently(zipFile);
return;
}
ClassLoader mcl = new DexClassLoader(modulePath, moduleOdexDir, moduleSoPath, topClassLoader);
BufferedReader moduleClassesReader = new BufferedReader(new InputStreamReader(is));
try {
String moduleClassName;
while ((moduleClassName = moduleClassesReader.readLine()) != null) {
moduleClassName = moduleClassName.trim();
if (moduleClassName.isEmpty() || moduleClassName.startsWith("#"))
continue;
try {
Log.i(TAG, " Loading class " + moduleClassName);
Class<?> moduleClass = mcl.loadClass(moduleClassName);
if (!IXposedMod.class.isAssignableFrom(moduleClass)) {
Log.e(TAG, " This class doesn't implement any sub-interface of IXposedMod, skipping it");
continue;
} else if (disableResources && IXposedHookInitPackageResources.class.isAssignableFrom(moduleClass)) {
Log.e(TAG, " This class requires resource-related hooks (which are disabled), skipping it.");
continue;
}
final Object moduleInstance = moduleClass.newInstance();
if (true) {
//fake
if (moduleInstance instanceof IXposedHookZygoteInit) {
IXposedHookZygoteInit.StartupParam param = new IXposedHookZygoteInit.StartupParam();
param.modulePath = modulePath;
param.startsSystemServer = false;
((IXposedHookZygoteInit) moduleInstance).initZygote(param);
}
if (moduleInstance instanceof IXposedHookLoadPackage)
XposedBridge.hookLoadPackage(new IXposedHookLoadPackage.Wrapper((IXposedHookLoadPackage) moduleInstance));
//not support now
//so off
if (moduleInstance instanceof IXposedHookInitPackageResources) {
throw new UnsupportedOperationException("can not hook resource!");
}
} else {
//not support now
//so off
if (moduleInstance instanceof IXposedHookCmdInit) {
throw new UnsupportedOperationException("can not hook cmd!");
}
}
} catch (Throwable t) {
Log.e(TAG, " Failed to load class " + moduleClassName, t);
}
}
} catch (IOException e) {
Log.e(TAG, " Failed to load module from " + modulePath, e);
} finally {
closeSilently(is);
closeSilently(zipFile);
}
}
}
package de.robv.android.xposed.callbacks;
import de.robv.android.xposed.IXposedHookZygoteInit;
/**
* Interface for objects that can be used to remove callbacks.
*
* <p class="warning">Just like hooking methods etc., unhooking applies only to the current process.
* In other process (or when the app is removed from memory and then restarted), the hook will still
* be active. The Zygote process (see {@link IXposedHookZygoteInit}) is an exception, the hook won't
* be inherited by any future processes forked from it in the future.
*
* @param <T> The class of the callback.
*/
public interface IXUnhook<T> {
/**
* Returns the callback that has been registered.
*/
T getCallback();
/**
* Removes the callback.
*/
void unhook();
}
package de.robv.android.xposed.callbacks;
//import android.content.res.XResources;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.XposedBridge.CopyOnWriteSortedSet;
/**
* This class is only used for internal purposes, except for the {@link InitPackageResourcesParam}
* subclass.
*/
public abstract class XC_InitPackageResources extends XCallback implements IXposedHookInitPackageResources {
/**
* Creates a new callback with default priority.
* @hide
*/
@SuppressWarnings("deprecation")
public XC_InitPackageResources() {
super();
}
/**
* Creates a new callback with a specific priority.
*
* @param priority See {@link XCallback#priority}.
* @hide
*/
public XC_InitPackageResources(int priority) {
super(priority);
}
/**
* Wraps information about the resources being initialized.
*/
public static final class InitPackageResourcesParam extends Param {
/** @hide */
public InitPackageResourcesParam(CopyOnWriteSortedSet<XC_InitPackageResources> callbacks) {
super(callbacks);
}
/** The name of the package for which resources are being loaded. */
public String packageName;
/**
* Reference to the resources that can be used for calls to
* {@link XResources#setReplacement(String, String, String, Object)}.
*/
//public XResources res;
}
/** @hide */
@Override
protected void call(Param param) throws Throwable {
if (param instanceof InitPackageResourcesParam)
handleInitPackageResources((InitPackageResourcesParam) param);
}
}
package de.robv.android.xposed.callbacks;
//import android.content.res.XResources;
//import android.content.res.XResources.ResourceNames;
import android.view.View;
import de.robv.android.xposed.XposedBridge.CopyOnWriteSortedSet;
/**
* Callback for hooking layouts. Such callbacks can be passed to {@link XResources#hookLayout}
* and its variants.
*/
public abstract class XC_LayoutInflated extends XCallback {
/**
* Creates a new callback with default priority.
*/
@SuppressWarnings("deprecation")
public XC_LayoutInflated() {
super();
}
/**
* Creates a new callback with a specific priority.
*
* @param priority See {@link XCallback#priority}.
*/
public XC_LayoutInflated(int priority) {
super(priority);
}
/**
* Wraps information about the inflated layout.
*/
public static final class LayoutInflatedParam extends Param {
/** @hide */
public LayoutInflatedParam(CopyOnWriteSortedSet<XC_LayoutInflated> callbacks) {
super(callbacks);
}
/** The view that has been created from the layout. */
public View view;
/** Container with the ID and name of the underlying resource. */
// public ResourceNames resNames;
/** Directory from which the layout was actually loaded (e.g. "layout-sw600dp"). */
// public String variant;
/** Resources containing the layout. */
// public XResources res;
}
/** @hide */
@Override
protected void call(Param param) throws Throwable {
if (param instanceof LayoutInflatedParam)
handleLayoutInflated((LayoutInflatedParam) param);
}
/**
* This method is called when the hooked layout has been inflated.
*
* @param liparam Information about the layout and the inflated view.
* @throws Throwable Everything the callback throws is caught and logged.
*/
public abstract void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable;
/**
* An object with which the callback can be removed.
*/
public class Unhook implements IXUnhook<XC_LayoutInflated> {
private final String resDir;
private final int id;
/** @hide */
public Unhook(String resDir, int id) {
this.resDir = resDir;
this.id = id;
}
/**
* Returns the resource ID of the hooked layout.
*/
public int getId() {
return id;
}
@Override
public XC_LayoutInflated getCallback() {
return XC_LayoutInflated.this;
}
@Override
public void unhook() {
// XResources.unhookLayout(resDir, id, XC_LayoutInflated.this);
}
}
}
package de.robv.android.xposed.callbacks;
import android.content.pm.ApplicationInfo;
import com.swift.sandhook.xposedcompat.XposedCompat;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XposedBridge.CopyOnWriteSortedSet;
/**
* This class is only used for internal purposes, except for the {@link LoadPackageParam}
* subclass.
*/
public abstract class XC_LoadPackage extends XCallback implements IXposedHookLoadPackage {
/**
* Creates a new callback with default priority.
* @hide
*/
@SuppressWarnings("deprecation")
public XC_LoadPackage() {
super();
}
/**
* Creates a new callback with a specific priority.
*
* @param priority See {@link XCallback#priority}.
* @hide
*/
public XC_LoadPackage(int priority) {
super(priority);
}
/**
* Wraps information about the app being loaded.
*/
public static final class LoadPackageParam extends Param {
/** @hide */
public LoadPackageParam(CopyOnWriteSortedSet<XC_LoadPackage> callbacks) {
super(callbacks);
}
/** The name of the package being loaded. */
public String packageName = XposedCompat.packageName;
/** The process in which the package is executed. */
public String processName = XposedCompat.processName;
/** The ClassLoader used for this package. */
public ClassLoader classLoader = XposedCompat.classLoader;
/** More information about the application being loaded. */
public ApplicationInfo appInfo = XposedCompat.context.getApplicationInfo();
/** Set to {@code true} if this is the first (and main) application for this process. */
public boolean isFirstApplication = XposedCompat.isFirstApplication;
}
/** @hide */
@Override
protected void call(Param param) throws Throwable {
if (param instanceof LoadPackageParam)
handleLoadPackage((LoadPackageParam) param);
}
}
package de.robv.android.xposed.callbacks;
import android.os.Bundle;
import java.io.Serializable;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedBridge.CopyOnWriteSortedSet;
/**
* Base class for Xposed callbacks.
*
* This class only keeps a priority for ordering multiple callbacks.
* The actual (abstract) callback methods are added by subclasses.
*/
public abstract class XCallback implements Comparable<XCallback> {
/**
* Callback priority, higher number means earlier execution.
*
* <p>This is usually set to {@link #PRIORITY_DEFAULT}. However, in case a certain callback should
* be executed earlier or later a value between {@link #PRIORITY_HIGHEST} and {@link #PRIORITY_LOWEST}
* can be set instead. The values are just for orientation though, Xposed doesn't enforce any
* boundaries on the priority values.
*/
public final int priority;
/** @deprecated This constructor can't be hidden for technical reasons. Nevertheless, don't use it! */
@Deprecated
public XCallback() {
this.priority = PRIORITY_DEFAULT;
}
/** @hide */
public XCallback(int priority) {
this.priority = priority;
}
/**
* Base class for Xposed callback parameters.
*/
public static abstract class Param {
/** @hide */
public final Object[] callbacks;
private Bundle extra;
/** @deprecated This constructor can't be hidden for technical reasons. Nevertheless, don't use it! */
@Deprecated
protected Param() {
callbacks = null;
}
/** @hide */
protected Param(CopyOnWriteSortedSet<? extends XCallback> callbacks) {
this.callbacks = callbacks.getSnapshot();
}
/**
* This can be used to store any data for the scope of the callback.
*
* <p>Use this instead of instance variables, as it has a clear reference to e.g. each
* separate call to a method, even when the same method is called recursively.
*
* @see #setObjectExtra
* @see #getObjectExtra
*/
public synchronized Bundle getExtra() {
if (extra == null)
extra = new Bundle();
return extra;
}
/**
* Returns an object stored with {@link #setObjectExtra}.
*/
public Object getObjectExtra(String key) {
Serializable o = getExtra().getSerializable(key);
if (o instanceof SerializeWrapper)
return ((SerializeWrapper) o).object;
return null;
}
/**
* Stores any object for the scope of the callback. For data types that support it, use
* the {@link Bundle} returned by {@link #getExtra} instead.
*/
public void setObjectExtra(String key, Object o) {
getExtra().putSerializable(key, new SerializeWrapper(o));
}
private static class SerializeWrapper implements Serializable {
private static final long serialVersionUID = 1L;
private final Object object;
public SerializeWrapper(Object o) {
object = o;
}
}
}
/** @hide */
public static void callAll(Param param) {
if (param.callbacks == null)
throw new IllegalStateException("This object was not created for use with callAll");
for (int i = 0; i < param.callbacks.length; i++) {
try {
((XCallback) param.callbacks[i]).call(param);
} catch (Throwable t) { XposedBridge.log(t); }
}
}
/** @hide */
protected void call(Param param) throws Throwable {}
/** @hide */
@Override
public int compareTo(XCallback other) {
if (this == other)
return 0;
// order descending by priority
if (other.priority != this.priority)
return other.priority - this.priority;
// then randomly
else if (System.identityHashCode(this) < System.identityHashCode(other))
return -1;
else
return 1;
}
/** The default priority, see {@link #priority}. */
public static final int PRIORITY_DEFAULT = 50;
/** Execute this callback late, see {@link #priority}. */
public static final int PRIORITY_LOWEST = -10000;
/** Execute this callback early, see {@link #priority}. */
public static final int PRIORITY_HIGHEST = 10000;
}
/**
* Contains the base classes for callbacks.
*
* <p>For historical reasons, {@link de.robv.android.xposed.XC_MethodHook} and
* {@link de.robv.android.xposed.XC_MethodReplacement} are directly in the
* {@code de.robv.android.xposed} package.
*/
package de.robv.android.xposed.callbacks;
package de.robv.android.xposed.services;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import de.robv.android.xposed.SELinuxHelper;
/**
* General definition of a file access service provided by the Xposed framework.
*
* <p>References to a concrete subclass should generally be retrieved from {@link SELinuxHelper}.
*/
public abstract class BaseService {
/** Flag for {@link #checkFileAccess}: Read access. */
public static final int R_OK = 4;
/** Flag for {@link #checkFileAccess}: Write access. */
public static final int W_OK = 2;
/** Flag for {@link #checkFileAccess}: Executable access. */
public static final int X_OK = 1;
/** Flag for {@link #checkFileAccess}: File/directory exists. */
public static final int F_OK = 0;
/**
* Checks whether the services accesses files directly (instead of using IPC).
*
* @return {@code true} in case direct access is possible.
*/
public boolean hasDirectFileAccess() {
return false;
}
/**
* Check whether a file is accessible. SELinux might enforce stricter checks.
*
* @param filename The absolute path of the file to check.
* @param mode The mode for POSIX's {@code access()} function.
* @return The result of the {@code access()} function.
*/
public abstract boolean checkFileAccess(String filename, int mode);
/**
* Check whether a file exists.
*
* @param filename The absolute path of the file to check.
* @return The result of the {@code access()} function.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean checkFileExists(String filename) {
return checkFileAccess(filename, F_OK);
}
/**
* Determine the size and modification time of a file.
*
* @param filename The absolute path of the file to check.
* @return A {@link FileResult} object holding the result.
* @throws IOException In case an error occurred while retrieving the information.
*/
public abstract FileResult statFile(String filename) throws IOException;
/**
* Determine the size time of a file.
*
* @param filename The absolute path of the file to check.
* @return The file size.
* @throws IOException In case an error occurred while retrieving the information.
*/
public long getFileSize(String filename) throws IOException {
return statFile(filename).size;
}
/**
* Determine the size time of a file.
*
* @param filename The absolute path of the file to check.
* @return The file modification time.
* @throws IOException In case an error occurred while retrieving the information.
*/
public long getFileModificationTime(String filename) throws IOException {
return statFile(filename).mtime;
}
/**
* Read a file into memory.
*
* @param filename The absolute path of the file to read.
* @return A {@code byte} array with the file content.
* @throws IOException In case an error occurred while reading the file.
*/
public abstract byte[] readFile(String filename) throws IOException;
/**
* Read a file into memory, but only if it has changed since the last time.
*
* @param filename The absolute path of the file to read.
* @param previousSize File size of last read.
* @param previousTime File modification time of last read.
* @return A {@link FileResult} object holding the result.
* <p>The {@link FileResult#content} field might be {@code null} if the file
* is unmodified ({@code previousSize} and {@code previousTime} are still valid).
* @throws IOException In case an error occurred while reading the file.
*/
public abstract FileResult readFile(String filename, long previousSize, long previousTime) throws IOException;
/**
* Read a file into memory, optionally only if it has changed since the last time.
*
* @param filename The absolute path of the file to read.
* @param offset Number of bytes to skip at the beginning of the file.
* @param length Number of bytes to read (0 means read to end of file).
* @param previousSize Optional: File size of last read.
* @param previousTime Optional: File modification time of last read.
* @return A {@link FileResult} object holding the result.
* <p>The {@link FileResult#content} field might be {@code null} if the file
* is unmodified ({@code previousSize} and {@code previousTime} are still valid).
* @throws IOException In case an error occurred while reading the file.
*/
public abstract FileResult readFile(String filename, int offset, int length,
long previousSize, long previousTime) throws IOException;
/**
* Get a stream to the file content.
* Depending on the service, it may or may not be read completely into memory.
*
* @param filename The absolute path of the file to read.
* @return An {@link InputStream} to the file content.
* @throws IOException In case an error occurred while reading the file.
*/
public InputStream getFileInputStream(String filename) throws IOException {
return new ByteArrayInputStream(readFile(filename));
}
/**
* Get a stream to the file content, but only if it has changed since the last time.
* Depending on the service, it may or may not be read completely into memory.
*
* @param filename The absolute path of the file to read.
* @param previousSize Optional: File size of last read.
* @param previousTime Optional: File modification time of last read.
* @return A {@link FileResult} object holding the result.
* <p>The {@link FileResult#stream} field might be {@code null} if the file
* is unmodified ({@code previousSize} and {@code previousTime} are still valid).
* @throws IOException In case an error occurred while reading the file.
*/
public FileResult getFileInputStream(String filename, long previousSize, long previousTime) throws IOException {
FileResult result = readFile(filename, previousSize, previousTime);
if (result.content == null)
return result;
return new FileResult(new ByteArrayInputStream(result.content), result.size, result.mtime);
}
// ----------------------------------------------------------------------------
/*package*/ BaseService() {}
/*package*/ static void ensureAbsolutePath(String filename) {
if (!filename.startsWith("/")) {
throw new IllegalArgumentException("Only absolute filenames are allowed: " + filename);
}
}
/*package*/ static void throwCommonIOException(int errno, String errorMsg, String filename, String defaultText) throws IOException {
switch (errno) {
case 1: // EPERM
case 13: // EACCES
throw new FileNotFoundException(errorMsg != null ? errorMsg : "Permission denied: " + filename);
case 2: // ENOENT
throw new FileNotFoundException(errorMsg != null ? errorMsg : "No such file or directory: " + filename);
case 12: // ENOMEM
throw new OutOfMemoryError(errorMsg);
case 21: // EISDIR
throw new FileNotFoundException(errorMsg != null ? errorMsg : "Is a directory: " + filename);
default:
throw new IOException(errorMsg != null ? errorMsg : "Error " + errno + defaultText + filename);
}
}
}
package de.robv.android.xposed.services;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/** @hide */
public final class DirectAccessService extends BaseService {
@Override
public boolean hasDirectFileAccess() {
return true;
}
@SuppressWarnings("RedundantIfStatement")
@Override
public boolean checkFileAccess(String filename, int mode) {
File file = new File(filename);
if (mode == F_OK && !file.exists()) return false;
if ((mode & R_OK) != 0 && !file.canRead()) return false;
if ((mode & W_OK) != 0 && !file.canWrite()) return false;
if ((mode & X_OK) != 0 && !file.canExecute()) return false;
return true;
}
@Override
public boolean checkFileExists(String filename) {
return new File(filename).exists();
}
@Override
public FileResult statFile(String filename) throws IOException {
File file = new File(filename);
return new FileResult(file.length(), file.lastModified());
}
@Override
public byte[] readFile(String filename) throws IOException {
File file = new File(filename);
byte content[] = new byte[(int)file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(content);
fis.close();
return content;
}
@Override
public FileResult readFile(String filename, long previousSize, long previousTime) throws IOException {
File file = new File(filename);
long size = file.length();
long time = file.lastModified();
if (previousSize == size && previousTime == time)
return new FileResult(size, time);
return new FileResult(readFile(filename), size, time);
}
@Override
public FileResult readFile(String filename, int offset, int length, long previousSize, long previousTime) throws IOException {
File file = new File(filename);
long size = file.length();
long time = file.lastModified();
if (previousSize == size && previousTime == time)
return new FileResult(size, time);
// Shortcut for the simple case
if (offset <= 0 && length <= 0)
return new FileResult(readFile(filename), size, time);
// Check range
if (offset > 0 && offset >= size) {
throw new IllegalArgumentException("Offset " + offset + " is out of range for " + filename);
} else if (offset < 0) {
offset = 0;
}
if (length > 0 && (offset + length) > size) {
throw new IllegalArgumentException("Length " + length + " is out of range for " + filename);
} else if (length <= 0) {
length = (int) (size - offset);
}
byte content[] = new byte[length];
FileInputStream fis = new FileInputStream(file);
fis.skip(offset);
fis.read(content);
fis.close();
return new FileResult(content, size, time);
}
/**
* {@inheritDoc}
* <p>This implementation returns a BufferedInputStream instead of loading the file into memory.
*/
@Override
public InputStream getFileInputStream(String filename) throws IOException {
return new BufferedInputStream(new FileInputStream(filename), 16*1024);
}
/**
* {@inheritDoc}
* <p>This implementation returns a BufferedInputStream instead of loading the file into memory.
*/
@Override
public FileResult getFileInputStream(String filename, long previousSize, long previousTime) throws IOException {
File file = new File(filename);
long size = file.length();
long time = file.lastModified();
if (previousSize == size && previousTime == time)
return new FileResult(size, time);
return new FileResult(new BufferedInputStream(new FileInputStream(filename), 16*1024), size, time);
}
}
package de.robv.android.xposed.services;
import java.io.InputStream;
/**
* Holder for the result of a {@link BaseService#readFile} or {@link BaseService#statFile} call.
*/
public final class FileResult {
/** File content, might be {@code null} if the file wasn't read. */
public final byte[] content;
/** File input stream, might be {@code null} if the file wasn't read. */
public final InputStream stream;
/** File size. */
public final long size;
/** File last modification time. */
public final long mtime;
/*package*/ public FileResult(long size, long mtime) {
this.content = null;
this.stream = null;
this.size = size;
this.mtime = mtime;
}
/*package*/ public FileResult(byte[] content, long size, long mtime) {
this.content = content;
this.stream = null;
this.size = size;
this.mtime = mtime;
}
/*package*/ public FileResult(InputStream stream, long size, long mtime) {
this.content = null;
this.stream = stream;
this.size = size;
this.mtime = mtime;
}
/** @hide */
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
if (content != null) {
sb.append("content.length: ");
sb.append(content.length);
sb.append(", ");
}
if (stream != null) {
sb.append("stream: ");
sb.append(stream.toString());
sb.append(", ");
}
sb.append("size: ");
sb.append(size);
sb.append(", mtime: ");
sb.append(mtime);
sb.append("}");
return sb.toString();
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3;
/**
* <p>Operations on {@link CharSequence} that are
* {@code null} safe.</p>
*
* @see CharSequence
* @since 3.0
* @version $Id: CharSequenceUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
*/
public class CharSequenceUtils {
/**
* <p>{@code CharSequenceUtils} instances should NOT be constructed in
* standard programming. </p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public CharSequenceUtils() {
super();
}
//-----------------------------------------------------------------------
/**
* <p>Returns a new {@code CharSequence} that is a subsequence of this
* sequence starting with the {@code char} value at the specified index.</p>
*
* <p>This provides the {@code CharSequence} equivalent to {@link String#substring(int)}.
* The length (in {@code char}) of the returned sequence is {@code length() - start},
* so if {@code start == end} then an empty sequence is returned.</p>
*
* @param cs the specified subsequence, null returns null
* @param start the start index, inclusive, valid
* @return a new subsequence, may be null
* @throws IndexOutOfBoundsException if {@code start} is negative or if
* {@code start} is greater than {@code length()}
*/
public static CharSequence subSequence(CharSequence cs, int start) {
return cs == null ? null : cs.subSequence(start, cs.length());
}
//-----------------------------------------------------------------------
/**
* <p>Finds the first index in the {@code CharSequence} that matches the
* specified character.</p>
*
* @param cs the {@code CharSequence} to be processed, not null
* @param searchChar the char to be searched for
* @param start the start index, negative starts at the string start
* @return the index where the search char was found, -1 if not found
*/
static int indexOf(CharSequence cs, int searchChar, int start) {
if (cs instanceof String) {
return ((String) cs).indexOf(searchChar, start);
} else {
int sz = cs.length();
if (start < 0) {
start = 0;
}
for (int i = start; i < sz; i++) {
if (cs.charAt(i) == searchChar) {
return i;
}
}
return -1;
}
}
/**
* Used by the indexOf(CharSequence methods) as a green implementation of indexOf.
*
* @param cs the {@code CharSequence} to be processed
* @param searchChar the {@code CharSequence} to be searched for
* @param start the start index
* @return the index where the search sequence was found
*/
static int indexOf(CharSequence cs, CharSequence searchChar, int start) {
return cs.toString().indexOf(searchChar.toString(), start);
// if (cs instanceof String && searchChar instanceof String) {
// // TODO: Do we assume searchChar is usually relatively small;
// // If so then calling toString() on it is better than reverting to
// // the green implementation in the else block
// return ((String) cs).indexOf((String) searchChar, start);
// } else {
// // TODO: Implement rather than convert to String
// return cs.toString().indexOf(searchChar.toString(), start);
// }
}
/**
* <p>Finds the last index in the {@code CharSequence} that matches the
* specified character.</p>
*
* @param cs the {@code CharSequence} to be processed
* @param searchChar the char to be searched for
* @param start the start index, negative returns -1, beyond length starts at end
* @return the index where the search char was found, -1 if not found
*/
static int lastIndexOf(CharSequence cs, int searchChar, int start) {
if (cs instanceof String) {
return ((String) cs).lastIndexOf(searchChar, start);
} else {
int sz = cs.length();
if (start < 0) {
return -1;
}
if (start >= sz) {
start = sz - 1;
}
for (int i = start; i >= 0; --i) {
if (cs.charAt(i) == searchChar) {
return i;
}
}
return -1;
}
}
/**
* Used by the lastIndexOf(CharSequence methods) as a green implementation of lastIndexOf
*
* @param cs the {@code CharSequence} to be processed
* @param searchChar the {@code CharSequence} to be searched for
* @param start the start index
* @return the index where the search sequence was found
*/
static int lastIndexOf(CharSequence cs, CharSequence searchChar, int start) {
return cs.toString().lastIndexOf(searchChar.toString(), start);
// if (cs instanceof String && searchChar instanceof String) {
// // TODO: Do we assume searchChar is usually relatively small;
// // If so then calling toString() on it is better than reverting to
// // the green implementation in the else block
// return ((String) cs).lastIndexOf((String) searchChar, start);
// } else {
// // TODO: Implement rather than convert to String
// return cs.toString().lastIndexOf(searchChar.toString(), start);
// }
}
/**
* Green implementation of toCharArray.
*
* @param cs the {@code CharSequence} to be processed
* @return the resulting char array
*/
static char[] toCharArray(CharSequence cs) {
if (cs instanceof String) {
return ((String) cs).toCharArray();
} else {
int sz = cs.length();
char[] array = new char[cs.length()];
for (int i = 0; i < sz; i++) {
array[i] = cs.charAt(i);
}
return array;
}
}
/**
* Green implementation of regionMatches.
*
* @param cs the {@code CharSequence} to be processed
* @param ignoreCase whether or not to be case insensitive
* @param thisStart the index to start on the {@code cs} CharSequence
* @param substring the {@code CharSequence} to be looked for
* @param start the index to start on the {@code substring} CharSequence
* @param length character length of the region
* @return whether the region matched
*/
static boolean regionMatches(CharSequence cs, boolean ignoreCase, int thisStart,
CharSequence substring, int start, int length) {
if (cs instanceof String && substring instanceof String) {
return ((String) cs).regionMatches(ignoreCase, thisStart, (String) substring, start, length);
} else {
// TODO: Implement rather than convert to String
return cs.toString().regionMatches(ignoreCase, thisStart, substring.toString(), start, length);
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3;
/**
* <p>Operations on char primitives and Character objects.</p>
*
* <p>This class tries to handle {@code null} input gracefully.
* An exception will not be thrown for a {@code null} input.
* Each method documents its behaviour in more detail.</p>
*
* <p>#ThreadSafe#</p>
* @since 2.1
* @version $Id: CharUtils.java 1158279 2011-08-16 14:06:45Z ggregory $
*/
public class CharUtils {
private static final String[] CHAR_STRING_ARRAY = new String[128];
/**
* {@code \u000a} linefeed LF ('\n').
*
* @see <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#101089">JLF: Escape Sequences
* for Character and String Literals</a>
* @since 2.2
*/
public static final char LF = '\n';
/**
* {@code \u000d} carriage return CR ('\r').
*
* @see <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#101089">JLF: Escape Sequences
* for Character and String Literals</a>
* @since 2.2
*/
public static final char CR = '\r';
static {
for (char c = 0; c < CHAR_STRING_ARRAY.length; c++) {
CHAR_STRING_ARRAY[c] = String.valueOf(c);
}
}
/**
* <p>{@code CharUtils} instances should NOT be constructed in standard programming.
* Instead, the class should be used as {@code CharUtils.toString('c');}.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean instance
* to operate.</p>
*/
public CharUtils() {
super();
}
//-----------------------------------------------------------------------
/**
* <p>Converts the character to a Character.</p>
*
* <p>For ASCII 7 bit characters, this uses a cache that will return the
* same Character object each time.</p>
*
* <pre>
* CharUtils.toCharacterObject(' ') = ' '
* CharUtils.toCharacterObject('A') = 'A'
* </pre>
*
* @deprecated Java 5 introduced {@link Character#valueOf(char)} which caches chars 0 through 127.
* @param ch the character to convert
* @return a Character of the specified character
*/
@Deprecated
public static Character toCharacterObject(char ch) {
return Character.valueOf(ch);
}
/**
* <p>Converts the String to a Character using the first character, returning
* null for empty Strings.</p>
*
* <p>For ASCII 7 bit characters, this uses a cache that will return the
* same Character object each time.</p>
*
* <pre>
* CharUtils.toCharacterObject(null) = null
* CharUtils.toCharacterObject("") = null
* CharUtils.toCharacterObject("A") = 'A'
* CharUtils.toCharacterObject("BA") = 'B'
* </pre>
*
* @param str the character to convert
* @return the Character value of the first letter of the String
*/
public static Character toCharacterObject(String str) {
if (StringUtils.isEmpty(str)) {
return null;
}
return Character.valueOf(str.charAt(0));
}
//-----------------------------------------------------------------------
/**
* <p>Converts the Character to a char throwing an exception for {@code null}.</p>
*
* <pre>
* CharUtils.toChar(' ') = ' '
* CharUtils.toChar('A') = 'A'
* CharUtils.toChar(null) throws IllegalArgumentException
* </pre>
*
* @param ch the character to convert
* @return the char value of the Character
* @throws IllegalArgumentException if the Character is null
*/
public static char toChar(Character ch) {
if (ch == null) {
throw new IllegalArgumentException("The Character must not be null");
}
return ch.charValue();
}
/**
* <p>Converts the Character to a char handling {@code null}.</p>
*
* <pre>
* CharUtils.toChar(null, 'X') = 'X'
* CharUtils.toChar(' ', 'X') = ' '
* CharUtils.toChar('A', 'X') = 'A'
* </pre>
*
* @param ch the character to convert
* @param defaultValue the value to use if the Character is null
* @return the char value of the Character or the default if null
*/
public static char toChar(Character ch, char defaultValue) {
if (ch == null) {
return defaultValue;
}
return ch.charValue();
}
//-----------------------------------------------------------------------
/**
* <p>Converts the String to a char using the first character, throwing
* an exception on empty Strings.</p>
*
* <pre>
* CharUtils.toChar("A") = 'A'
* CharUtils.toChar("BA") = 'B'
* CharUtils.toChar(null) throws IllegalArgumentException
* CharUtils.toChar("") throws IllegalArgumentException
* </pre>
*
* @param str the character to convert
* @return the char value of the first letter of the String
* @throws IllegalArgumentException if the String is empty
*/
public static char toChar(String str) {
if (StringUtils.isEmpty(str)) {
throw new IllegalArgumentException("The String must not be empty");
}
return str.charAt(0);
}
/**
* <p>Converts the String to a char using the first character, defaulting
* the value on empty Strings.</p>
*
* <pre>
* CharUtils.toChar(null, 'X') = 'X'
* CharUtils.toChar("", 'X') = 'X'
* CharUtils.toChar("A", 'X') = 'A'
* CharUtils.toChar("BA", 'X') = 'B'
* </pre>
*
* @param str the character to convert
* @param defaultValue the value to use if the Character is null
* @return the char value of the first letter of the String or the default if null
*/
public static char toChar(String str, char defaultValue) {
if (StringUtils.isEmpty(str)) {
return defaultValue;
}
return str.charAt(0);
}
//-----------------------------------------------------------------------
/**
* <p>Converts the character to the Integer it represents, throwing an
* exception if the character is not numeric.</p>
*
* <p>This method coverts the char '1' to the int 1 and so on.</p>
*
* <pre>
* CharUtils.toIntValue('3') = 3
* CharUtils.toIntValue('A') throws IllegalArgumentException
* </pre>
*
* @param ch the character to convert
* @return the int value of the character
* @throws IllegalArgumentException if the character is not ASCII numeric
*/
public static int toIntValue(char ch) {
if (isAsciiNumeric(ch) == false) {
throw new IllegalArgumentException("The character " + ch + " is not in the range '0' - '9'");
}
return ch - 48;
}
/**
* <p>Converts the character to the Integer it represents, throwing an
* exception if the character is not numeric.</p>
*
* <p>This method coverts the char '1' to the int 1 and so on.</p>
*
* <pre>
* CharUtils.toIntValue('3', -1) = 3
* CharUtils.toIntValue('A', -1) = -1
* </pre>
*
* @param ch the character to convert
* @param defaultValue the default value to use if the character is not numeric
* @return the int value of the character
*/
public static int toIntValue(char ch, int defaultValue) {
if (isAsciiNumeric(ch) == false) {
return defaultValue;
}
return ch - 48;
}
/**
* <p>Converts the character to the Integer it represents, throwing an
* exception if the character is not numeric.</p>
*
* <p>This method coverts the char '1' to the int 1 and so on.</p>
*
* <pre>
* CharUtils.toIntValue('3') = 3
* CharUtils.toIntValue(null) throws IllegalArgumentException
* CharUtils.toIntValue('A') throws IllegalArgumentException
* </pre>
*
* @param ch the character to convert, not null
* @return the int value of the character
* @throws IllegalArgumentException if the Character is not ASCII numeric or is null
*/
public static int toIntValue(Character ch) {
if (ch == null) {
throw new IllegalArgumentException("The character must not be null");
}
return toIntValue(ch.charValue());
}
/**
* <p>Converts the character to the Integer it represents, throwing an
* exception if the character is not numeric.</p>
*
* <p>This method coverts the char '1' to the int 1 and so on.</p>
*
* <pre>
* CharUtils.toIntValue(null, -1) = -1
* CharUtils.toIntValue('3', -1) = 3
* CharUtils.toIntValue('A', -1) = -1
* </pre>
*
* @param ch the character to convert
* @param defaultValue the default value to use if the character is not numeric
* @return the int value of the character
*/
public static int toIntValue(Character ch, int defaultValue) {
if (ch == null) {
return defaultValue;
}
return toIntValue(ch.charValue(), defaultValue);
}
//-----------------------------------------------------------------------
/**
* <p>Converts the character to a String that contains the one character.</p>
*
* <p>For ASCII 7 bit characters, this uses a cache that will return the
* same String object each time.</p>
*
* <pre>
* CharUtils.toString(' ') = " "
* CharUtils.toString('A') = "A"
* </pre>
*
* @param ch the character to convert
* @return a String containing the one specified character
*/
public static String toString(char ch) {
if (ch < 128) {
return CHAR_STRING_ARRAY[ch];
}
return new String(new char[] {ch});
}
/**
* <p>Converts the character to a String that contains the one character.</p>
*
* <p>For ASCII 7 bit characters, this uses a cache that will return the
* same String object each time.</p>
*
* <p>If {@code null} is passed in, {@code null} will be returned.</p>
*
* <pre>
* CharUtils.toString(null) = null
* CharUtils.toString(' ') = " "
* CharUtils.toString('A') = "A"
* </pre>
*
* @param ch the character to convert
* @return a String containing the one specified character
*/
public static String toString(Character ch) {
if (ch == null) {
return null;
}
return toString(ch.charValue());
}
//--------------------------------------------------------------------------
/**
* <p>Converts the string to the Unicode format '\u0020'.</p>
*
* <p>This format is the Java source code format.</p>
*
* <pre>
* CharUtils.unicodeEscaped(' ') = "\u0020"
* CharUtils.unicodeEscaped('A') = "\u0041"
* </pre>
*
* @param ch the character to convert
* @return the escaped Unicode string
*/
public static String unicodeEscaped(char ch) {
if (ch < 0x10) {
return "\\u000" + Integer.toHexString(ch);
} else if (ch < 0x100) {
return "\\u00" + Integer.toHexString(ch);
} else if (ch < 0x1000) {
return "\\u0" + Integer.toHexString(ch);
}
return "\\u" + Integer.toHexString(ch);
}
/**
* <p>Converts the string to the Unicode format '\u0020'.</p>
*
* <p>This format is the Java source code format.</p>
*
* <p>If {@code null} is passed in, {@code null} will be returned.</p>
*
* <pre>
* CharUtils.unicodeEscaped(null) = null
* CharUtils.unicodeEscaped(' ') = "\u0020"
* CharUtils.unicodeEscaped('A') = "\u0041"
* </pre>
*
* @param ch the character to convert, may be null
* @return the escaped Unicode string, null if null input
*/
public static String unicodeEscaped(Character ch) {
if (ch == null) {
return null;
}
return unicodeEscaped(ch.charValue());
}
//--------------------------------------------------------------------------
/**
* <p>Checks whether the character is ASCII 7 bit.</p>
*
* <pre>
* CharUtils.isAscii('a') = true
* CharUtils.isAscii('A') = true
* CharUtils.isAscii('3') = true
* CharUtils.isAscii('-') = true
* CharUtils.isAscii('\n') = true
* CharUtils.isAscii('&copy;') = false
* </pre>
*
* @param ch the character to check
* @return true if less than 128
*/
public static boolean isAscii(char ch) {
return ch < 128;
}
/**
* <p>Checks whether the character is ASCII 7 bit printable.</p>
*
* <pre>
* CharUtils.isAsciiPrintable('a') = true
* CharUtils.isAsciiPrintable('A') = true
* CharUtils.isAsciiPrintable('3') = true
* CharUtils.isAsciiPrintable('-') = true
* CharUtils.isAsciiPrintable('\n') = false
* CharUtils.isAsciiPrintable('&copy;') = false
* </pre>
*
* @param ch the character to check
* @return true if between 32 and 126 inclusive
*/
public static boolean isAsciiPrintable(char ch) {
return ch >= 32 && ch < 127;
}
/**
* <p>Checks whether the character is ASCII 7 bit control.</p>
*
* <pre>
* CharUtils.isAsciiControl('a') = false
* CharUtils.isAsciiControl('A') = false
* CharUtils.isAsciiControl('3') = false
* CharUtils.isAsciiControl('-') = false
* CharUtils.isAsciiControl('\n') = true
* CharUtils.isAsciiControl('&copy;') = false
* </pre>
*
* @param ch the character to check
* @return true if less than 32 or equals 127
*/
public static boolean isAsciiControl(char ch) {
return ch < 32 || ch == 127;
}
/**
* <p>Checks whether the character is ASCII 7 bit alphabetic.</p>
*
* <pre>
* CharUtils.isAsciiAlpha('a') = true
* CharUtils.isAsciiAlpha('A') = true
* CharUtils.isAsciiAlpha('3') = false
* CharUtils.isAsciiAlpha('-') = false
* CharUtils.isAsciiAlpha('\n') = false
* CharUtils.isAsciiAlpha('&copy;') = false
* </pre>
*
* @param ch the character to check
* @return true if between 65 and 90 or 97 and 122 inclusive
*/
public static boolean isAsciiAlpha(char ch) {
return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z');
}
/**
* <p>Checks whether the character is ASCII 7 bit alphabetic upper case.</p>
*
* <pre>
* CharUtils.isAsciiAlphaUpper('a') = false
* CharUtils.isAsciiAlphaUpper('A') = true
* CharUtils.isAsciiAlphaUpper('3') = false
* CharUtils.isAsciiAlphaUpper('-') = false
* CharUtils.isAsciiAlphaUpper('\n') = false
* CharUtils.isAsciiAlphaUpper('&copy;') = false
* </pre>
*
* @param ch the character to check
* @return true if between 65 and 90 inclusive
*/
public static boolean isAsciiAlphaUpper(char ch) {
return ch >= 'A' && ch <= 'Z';
}
/**
* <p>Checks whether the character is ASCII 7 bit alphabetic lower case.</p>
*
* <pre>
* CharUtils.isAsciiAlphaLower('a') = true
* CharUtils.isAsciiAlphaLower('A') = false
* CharUtils.isAsciiAlphaLower('3') = false
* CharUtils.isAsciiAlphaLower('-') = false
* CharUtils.isAsciiAlphaLower('\n') = false
* CharUtils.isAsciiAlphaLower('&copy;') = false
* </pre>
*
* @param ch the character to check
* @return true if between 97 and 122 inclusive
*/
public static boolean isAsciiAlphaLower(char ch) {
return ch >= 'a' && ch <= 'z';
}
/**
* <p>Checks whether the character is ASCII 7 bit numeric.</p>
*
* <pre>
* CharUtils.isAsciiNumeric('a') = false
* CharUtils.isAsciiNumeric('A') = false
* CharUtils.isAsciiNumeric('3') = true
* CharUtils.isAsciiNumeric('-') = false
* CharUtils.isAsciiNumeric('\n') = false
* CharUtils.isAsciiNumeric('&copy;') = false
* </pre>
*
* @param ch the character to check
* @return true if between 48 and 57 inclusive
*/
public static boolean isAsciiNumeric(char ch) {
return ch >= '0' && ch <= '9';
}
/**
* <p>Checks whether the character is ASCII 7 bit numeric.</p>
*
* <pre>
* CharUtils.isAsciiAlphanumeric('a') = true
* CharUtils.isAsciiAlphanumeric('A') = true
* CharUtils.isAsciiAlphanumeric('3') = true
* CharUtils.isAsciiAlphanumeric('-') = false
* CharUtils.isAsciiAlphanumeric('\n') = false
* CharUtils.isAsciiAlphanumeric('&copy;') = false
* </pre>
*
* @param ch the character to check
* @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive
*/
public static boolean isAsciiAlphanumeric(char ch) {
return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9');
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
/**
* <p>Operates on classes without using reflection.</p>
*
* <p>This class handles invalid {@code null} inputs as best it can.
* Each method documents its behaviour in more detail.</p>
*
* <p>The notion of a {@code canonical name} includes the human
* readable name for the type, for example {@code int[]}. The
* non-canonical method variants work with the JVM names, such as
* {@code [I}. </p>
*
* @since 2.0
* @version $Id: ClassUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
*/
public class ClassUtils {
/**
* <p>The package separator character: <code>'&#x2e;' == {@value}</code>.</p>
*/
public static final char PACKAGE_SEPARATOR_CHAR = '.';
/**
* <p>The package separator String: {@code "&#x2e;"}.</p>
*/
public static final String PACKAGE_SEPARATOR = String.valueOf(PACKAGE_SEPARATOR_CHAR);
/**
* <p>The inner class separator character: <code>'$' == {@value}</code>.</p>
*/
public static final char INNER_CLASS_SEPARATOR_CHAR = '$';
/**
* <p>The inner class separator String: {@code "$"}.</p>
*/
public static final String INNER_CLASS_SEPARATOR = String.valueOf(INNER_CLASS_SEPARATOR_CHAR);
/**
* Maps primitive {@code Class}es to their corresponding wrapper {@code Class}.
*/
private static final Map<Class<?>, Class<?>> primitiveWrapperMap = new HashMap<Class<?>, Class<?>>();
static {
primitiveWrapperMap.put(Boolean.TYPE, Boolean.class);
primitiveWrapperMap.put(Byte.TYPE, Byte.class);
primitiveWrapperMap.put(Character.TYPE, Character.class);
primitiveWrapperMap.put(Short.TYPE, Short.class);
primitiveWrapperMap.put(Integer.TYPE, Integer.class);
primitiveWrapperMap.put(Long.TYPE, Long.class);
primitiveWrapperMap.put(Double.TYPE, Double.class);
primitiveWrapperMap.put(Float.TYPE, Float.class);
primitiveWrapperMap.put(Void.TYPE, Void.TYPE);
}
/**
* Maps wrapper {@code Class}es to their corresponding primitive types.
*/
private static final Map<Class<?>, Class<?>> wrapperPrimitiveMap = new HashMap<Class<?>, Class<?>>();
static {
for (Class<?> primitiveClass : primitiveWrapperMap.keySet()) {
Class<?> wrapperClass = primitiveWrapperMap.get(primitiveClass);
if (!primitiveClass.equals(wrapperClass)) {
wrapperPrimitiveMap.put(wrapperClass, primitiveClass);
}
}
}
/**
* Maps a primitive class name to its corresponding abbreviation used in array class names.
*/
private static final Map<String, String> abbreviationMap = new HashMap<String, String>();
/**
* Maps an abbreviation used in array class names to corresponding primitive class name.
*/
private static final Map<String, String> reverseAbbreviationMap = new HashMap<String, String>();
/**
* Add primitive type abbreviation to maps of abbreviations.
*
* @param primitive Canonical name of primitive type
* @param abbreviation Corresponding abbreviation of primitive type
*/
private static void addAbbreviation(String primitive, String abbreviation) {
abbreviationMap.put(primitive, abbreviation);
reverseAbbreviationMap.put(abbreviation, primitive);
}
/**
* Feed abbreviation maps
*/
static {
addAbbreviation("int", "I");
addAbbreviation("boolean", "Z");
addAbbreviation("float", "F");
addAbbreviation("long", "J");
addAbbreviation("short", "S");
addAbbreviation("byte", "B");
addAbbreviation("double", "D");
addAbbreviation("char", "C");
}
/**
* <p>ClassUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as
* {@code ClassUtils.getShortClassName(cls)}.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public ClassUtils() {
super();
}
// Short class name
// ----------------------------------------------------------------------
/**
* <p>Gets the class name minus the package name for an {@code Object}.</p>
*
* @param object the class to get the short name for, may be null
* @param valueIfNull the value to return if null
* @return the class name of the object without the package name, or the null value
*/
public static String getShortClassName(Object object, String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getShortClassName(object.getClass());
}
/**
* <p>Gets the class name minus the package name from a {@code Class}.</p>
*
* <p>Consider using the Java 5 API {@link Class#getSimpleName()} instead.
* The one known difference is that this code will return {@code "Map.Entry"} while
* the {@code java.lang.Class} variant will simply return {@code "Entry"}. </p>
*
* @param cls the class to get the short name for.
* @return the class name without the package name or an empty string
*/
public static String getShortClassName(Class<?> cls) {
if (cls == null) {
return StringUtils.EMPTY;
}
return getShortClassName(cls.getName());
}
/**
* <p>Gets the class name minus the package name from a String.</p>
*
* <p>The string passed in is assumed to be a class name - it is not checked.</p>
* <p>Note that this method differs from Class.getSimpleName() in that this will
* return {@code "Map.Entry"} whilst the {@code java.lang.Class} variant will simply
* return {@code "Entry"}. </p>
*
* @param className the className to get the short name for
* @return the class name of the class without the package name or an empty string
*/
public static String getShortClassName(String className) {
if (className == null) {
return StringUtils.EMPTY;
}
if (className.length() == 0) {
return StringUtils.EMPTY;
}
StringBuilder arrayPrefix = new StringBuilder();
// Handle array encoding
if (className.startsWith("[")) {
while (className.charAt(0) == '[') {
className = className.substring(1);
arrayPrefix.append("[]");
}
// Strip Object type encoding
if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
className = className.substring(1, className.length() - 1);
}
}
if (reverseAbbreviationMap.containsKey(className)) {
className = reverseAbbreviationMap.get(className);
}
int lastDotIdx = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
int innerIdx = className.indexOf(
INNER_CLASS_SEPARATOR_CHAR, lastDotIdx == -1 ? 0 : lastDotIdx + 1);
String out = className.substring(lastDotIdx + 1);
if (innerIdx != -1) {
out = out.replace(INNER_CLASS_SEPARATOR_CHAR, PACKAGE_SEPARATOR_CHAR);
}
return out + arrayPrefix;
}
/**
* <p>Null-safe version of <code>aClass.getSimpleName()</code></p>
*
* @param cls the class for which to get the simple name.
* @return the simple class name.
* @since 3.0
* @see Class#getSimpleName()
*/
public static String getSimpleName(Class<?> cls) {
if (cls == null) {
return StringUtils.EMPTY;
}
return cls.getSimpleName();
}
/**
* <p>Null-safe version of <code>aClass.getSimpleName()</code></p>
*
* @param object the object for which to get the simple class name.
* @param valueIfNull the value to return if <code>object</code> is <code>null</code>
* @return the simple class name.
* @since 3.0
* @see Class#getSimpleName()
*/
public static String getSimpleName(Object object, String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getSimpleName(object.getClass());
}
// Package name
// ----------------------------------------------------------------------
/**
* <p>Gets the package name of an {@code Object}.</p>
*
* @param object the class to get the package name for, may be null
* @param valueIfNull the value to return if null
* @return the package name of the object, or the null value
*/
public static String getPackageName(Object object, String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getPackageName(object.getClass());
}
/**
* <p>Gets the package name of a {@code Class}.</p>
*
* @param cls the class to get the package name for, may be {@code null}.
* @return the package name or an empty string
*/
public static String getPackageName(Class<?> cls) {
if (cls == null) {
return StringUtils.EMPTY;
}
return getPackageName(cls.getName());
}
/**
* <p>Gets the package name from a {@code String}.</p>
*
* <p>The string passed in is assumed to be a class name - it is not checked.</p>
* <p>If the class is unpackaged, return an empty string.</p>
*
* @param className the className to get the package name for, may be {@code null}
* @return the package name or an empty string
*/
public static String getPackageName(String className) {
if (className == null || className.length() == 0) {
return StringUtils.EMPTY;
}
// Strip array encoding
while (className.charAt(0) == '[') {
className = className.substring(1);
}
// Strip Object type encoding
if (className.charAt(0) == 'L' && className.charAt(className.length() - 1) == ';') {
className = className.substring(1);
}
int i = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
if (i == -1) {
return StringUtils.EMPTY;
}
return className.substring(0, i);
}
// Superclasses/Superinterfaces
// ----------------------------------------------------------------------
/**
* <p>Gets a {@code List} of superclasses for the given class.</p>
*
* @param cls the class to look up, may be {@code null}
* @return the {@code List} of superclasses in order going up from this one
* {@code null} if null input
*/
public static List<Class<?>> getAllSuperclasses(Class<?> cls) {
if (cls == null) {
return null;
}
List<Class<?>> classes = new ArrayList<Class<?>>();
Class<?> superclass = cls.getSuperclass();
while (superclass != null) {
classes.add(superclass);
superclass = superclass.getSuperclass();
}
return classes;
}
/**
* <p>Gets a {@code List} of all interfaces implemented by the given
* class and its superclasses.</p>
*
* <p>The order is determined by looking through each interface in turn as
* declared in the source file and following its hierarchy up. Then each
* superclass is considered in the same way. Later duplicates are ignored,
* so the order is maintained.</p>
*
* @param cls the class to look up, may be {@code null}
* @return the {@code List} of interfaces in order,
* {@code null} if null input
*/
public static List<Class<?>> getAllInterfaces(Class<?> cls) {
if (cls == null) {
return null;
}
LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<Class<?>>();
getAllInterfaces(cls, interfacesFound);
return new ArrayList<Class<?>>(interfacesFound);
}
/**
* Get the interfaces for the specified class.
*
* @param cls the class to look up, may be {@code null}
* @param interfacesFound the {@code Set} of interfaces for the class
*/
private static void getAllInterfaces(Class<?> cls, HashSet<Class<?>> interfacesFound) {
while (cls != null) {
Class<?>[] interfaces = cls.getInterfaces();
for (Class<?> i : interfaces) {
if (interfacesFound.add(i)) {
getAllInterfaces(i, interfacesFound);
}
}
cls = cls.getSuperclass();
}
}
// Convert list
// ----------------------------------------------------------------------
/**
* <p>Given a {@code List} of class names, this method converts them into classes.</p>
*
* <p>A new {@code List} is returned. If the class name cannot be found, {@code null}
* is stored in the {@code List}. If the class name in the {@code List} is
* {@code null}, {@code null} is stored in the output {@code List}.</p>
*
* @param classNames the classNames to change
* @return a {@code List} of Class objects corresponding to the class names,
* {@code null} if null input
* @throws ClassCastException if classNames contains a non String entry
*/
public static List<Class<?>> convertClassNamesToClasses(List<String> classNames) {
if (classNames == null) {
return null;
}
List<Class<?>> classes = new ArrayList<Class<?>>(classNames.size());
for (String className : classNames) {
try {
classes.add(Class.forName(className));
} catch (Exception ex) {
classes.add(null);
}
}
return classes;
}
/**
* <p>Given a {@code List} of {@code Class} objects, this method converts
* them into class names.</p>
*
* <p>A new {@code List} is returned. {@code null} objects will be copied into
* the returned list as {@code null}.</p>
*
* @param classes the classes to change
* @return a {@code List} of class names corresponding to the Class objects,
* {@code null} if null input
* @throws ClassCastException if {@code classes} contains a non-{@code Class} entry
*/
public static List<String> convertClassesToClassNames(List<Class<?>> classes) {
if (classes == null) {
return null;
}
List<String> classNames = new ArrayList<String>(classes.size());
for (Class<?> cls : classes) {
if (cls == null) {
classNames.add(null);
} else {
classNames.add(cls.getName());
}
}
return classNames;
}
// Is assignable
// ----------------------------------------------------------------------
/**
* <p>Checks if an array of Classes can be assigned to another array of Classes.</p>
*
* <p>This method calls {@link #isAssignable(Class, Class) isAssignable} for each
* Class pair in the input arrays. It can be used to check if a set of arguments
* (the first parameter) are suitably compatible with a set of method parameter types
* (the second parameter).</p>
*
* <p>Unlike the {@link Class#isAssignableFrom(Class)} method, this
* method takes into account widenings of primitive classes and
* {@code null}s.</p>
*
* <p>Primitive widenings allow an int to be assigned to a {@code long},
* {@code float} or {@code double}. This method returns the correct
* result for these cases.</p>
*
* <p>{@code Null} may be assigned to any reference type. This method will
* return {@code true} if {@code null} is passed in and the toClass is
* non-primitive.</p>
*
* <p>Specifically, this method tests whether the type represented by the
* specified {@code Class} parameter can be converted to the type
* represented by this {@code Class} object via an identity conversion
* widening primitive or widening reference conversion. See
* <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
* sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
*
* <p><strong>Since Lang 3.0,</strong> this method will default behavior for
* calculating assignability between primitive and wrapper types <em>corresponding
* to the running Java version</em>; i.e. autoboxing will be the default
* behavior in VMs running Java versions >= 1.5.</p>
*
* @param classArray the array of Classes to check, may be {@code null}
* @param toClassArray the array of Classes to try to assign into, may be {@code null}
* @return {@code true} if assignment possible
*/
public static boolean isAssignable(Class<?>[] classArray, Class<?>... toClassArray) {
return isAssignable(classArray, toClassArray, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5));
}
/**
* <p>Checks if an array of Classes can be assigned to another array of Classes.</p>
*
* <p>This method calls {@link #isAssignable(Class, Class) isAssignable} for each
* Class pair in the input arrays. It can be used to check if a set of arguments
* (the first parameter) are suitably compatible with a set of method parameter types
* (the second parameter).</p>
*
* <p>Unlike the {@link Class#isAssignableFrom(Class)} method, this
* method takes into account widenings of primitive classes and
* {@code null}s.</p>
*
* <p>Primitive widenings allow an int to be assigned to a {@code long},
* {@code float} or {@code double}. This method returns the correct
* result for these cases.</p>
*
* <p>{@code Null} may be assigned to any reference type. This method will
* return {@code true} if {@code null} is passed in and the toClass is
* non-primitive.</p>
*
* <p>Specifically, this method tests whether the type represented by the
* specified {@code Class} parameter can be converted to the type
* represented by this {@code Class} object via an identity conversion
* widening primitive or widening reference conversion. See
* <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
* sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
*
* @param classArray the array of Classes to check, may be {@code null}
* @param toClassArray the array of Classes to try to assign into, may be {@code null}
* @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
* @return {@code true} if assignment possible
*/
public static boolean isAssignable(Class<?>[] classArray, Class<?>[] toClassArray, boolean autoboxing) {
if (ArrayUtils.isSameLength(classArray, toClassArray) == false) {
return false;
}
if (classArray == null) {
classArray = ArrayUtils.EMPTY_CLASS_ARRAY;
}
if (toClassArray == null) {
toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY;
}
for (int i = 0; i < classArray.length; i++) {
if (isAssignable(classArray[i], toClassArray[i], autoboxing) == false) {
return false;
}
}
return true;
}
/**
* Returns whether the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
* {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
*
* @param type
* The class to query or null.
* @return true if the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character},
* {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
* @since 3.1
*/
public static boolean isPrimitiveOrWrapper(Class<?> type) {
if (type == null) {
return false;
}
return type.isPrimitive() || isPrimitiveWrapper(type);
}
/**
* Returns whether the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short},
* {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
*
* @param type
* The class to query or null.
* @return true if the given {@code type} is a primitive wrapper ({@link Boolean}, {@link Byte}, {@link Character}, {@link Short},
* {@link Integer}, {@link Long}, {@link Double}, {@link Float}).
* @since 3.1
*/
public static boolean isPrimitiveWrapper(Class<?> type) {
return wrapperPrimitiveMap.containsKey(type);
}
/**
* <p>Checks if one {@code Class} can be assigned to a variable of
* another {@code Class}.</p>
*
* <p>Unlike the {@link Class#isAssignableFrom(Class)} method,
* this method takes into account widenings of primitive classes and
* {@code null}s.</p>
*
* <p>Primitive widenings allow an int to be assigned to a long, float or
* double. This method returns the correct result for these cases.</p>
*
* <p>{@code Null} may be assigned to any reference type. This method
* will return {@code true} if {@code null} is passed in and the
* toClass is non-primitive.</p>
*
* <p>Specifically, this method tests whether the type represented by the
* specified {@code Class} parameter can be converted to the type
* represented by this {@code Class} object via an identity conversion
* widening primitive or widening reference conversion. See
* <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
* sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
*
* <p><strong>Since Lang 3.0,</strong> this method will default behavior for
* calculating assignability between primitive and wrapper types <em>corresponding
* to the running Java version</em>; i.e. autoboxing will be the default
* behavior in VMs running Java versions >= 1.5.</p>
*
* @param cls the Class to check, may be null
* @param toClass the Class to try to assign into, returns false if null
* @return {@code true} if assignment possible
*/
public static boolean isAssignable(Class<?> cls, Class<?> toClass) {
return isAssignable(cls, toClass, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5));
}
/**
* <p>Checks if one {@code Class} can be assigned to a variable of
* another {@code Class}.</p>
*
* <p>Unlike the {@link Class#isAssignableFrom(Class)} method,
* this method takes into account widenings of primitive classes and
* {@code null}s.</p>
*
* <p>Primitive widenings allow an int to be assigned to a long, float or
* double. This method returns the correct result for these cases.</p>
*
* <p>{@code Null} may be assigned to any reference type. This method
* will return {@code true} if {@code null} is passed in and the
* toClass is non-primitive.</p>
*
* <p>Specifically, this method tests whether the type represented by the
* specified {@code Class} parameter can be converted to the type
* represented by this {@code Class} object via an identity conversion
* widening primitive or widening reference conversion. See
* <em><a href="http://java.sun.com/docs/books/jls/">The Java Language Specification</a></em>,
* sections 5.1.1, 5.1.2 and 5.1.4 for details.</p>
*
* @param cls the Class to check, may be null
* @param toClass the Class to try to assign into, returns false if null
* @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers
* @return {@code true} if assignment possible
*/
public static boolean isAssignable(Class<?> cls, Class<?> toClass, boolean autoboxing) {
if (toClass == null) {
return false;
}
// have to check for null, as isAssignableFrom doesn't
if (cls == null) {
return !toClass.isPrimitive();
}
//autoboxing:
if (autoboxing) {
if (cls.isPrimitive() && !toClass.isPrimitive()) {
cls = primitiveToWrapper(cls);
if (cls == null) {
return false;
}
}
if (toClass.isPrimitive() && !cls.isPrimitive()) {
cls = wrapperToPrimitive(cls);
if (cls == null) {
return false;
}
}
}
if (cls.equals(toClass)) {
return true;
}
if (cls.isPrimitive()) {
if (toClass.isPrimitive() == false) {
return false;
}
if (Integer.TYPE.equals(cls)) {
return Long.TYPE.equals(toClass)
|| Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Long.TYPE.equals(cls)) {
return Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Boolean.TYPE.equals(cls)) {
return false;
}
if (Double.TYPE.equals(cls)) {
return false;
}
if (Float.TYPE.equals(cls)) {
return Double.TYPE.equals(toClass);
}
if (Character.TYPE.equals(cls)) {
return Integer.TYPE.equals(toClass)
|| Long.TYPE.equals(toClass)
|| Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Short.TYPE.equals(cls)) {
return Integer.TYPE.equals(toClass)
|| Long.TYPE.equals(toClass)
|| Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
if (Byte.TYPE.equals(cls)) {
return Short.TYPE.equals(toClass)
|| Integer.TYPE.equals(toClass)
|| Long.TYPE.equals(toClass)
|| Float.TYPE.equals(toClass)
|| Double.TYPE.equals(toClass);
}
// should never get here
return false;
}
return toClass.isAssignableFrom(cls);
}
/**
* <p>Converts the specified primitive Class object to its corresponding
* wrapper Class object.</p>
*
* <p>NOTE: From v2.2, this method handles {@code Void.TYPE},
* returning {@code Void.TYPE}.</p>
*
* @param cls the class to convert, may be null
* @return the wrapper class for {@code cls} or {@code cls} if
* {@code cls} is not a primitive. {@code null} if null input.
* @since 2.1
*/
public static Class<?> primitiveToWrapper(Class<?> cls) {
Class<?> convertedClass = cls;
if (cls != null && cls.isPrimitive()) {
convertedClass = primitiveWrapperMap.get(cls);
}
return convertedClass;
}
/**
* <p>Converts the specified array of primitive Class objects to an array of
* its corresponding wrapper Class objects.</p>
*
* @param classes the class array to convert, may be null or empty
* @return an array which contains for each given class, the wrapper class or
* the original class if class is not a primitive. {@code null} if null input.
* Empty array if an empty array passed in.
* @since 2.1
*/
public static Class<?>[] primitivesToWrappers(Class<?>... classes) {
if (classes == null) {
return null;
}
if (classes.length == 0) {
return classes;
}
Class<?>[] convertedClasses = new Class[classes.length];
for (int i = 0; i < classes.length; i++) {
convertedClasses[i] = primitiveToWrapper(classes[i]);
}
return convertedClasses;
}
/**
* <p>Converts the specified wrapper class to its corresponding primitive
* class.</p>
*
* <p>This method is the counter part of {@code primitiveToWrapper()}.
* If the passed in class is a wrapper class for a primitive type, this
* primitive type will be returned (e.g. {@code Integer.TYPE} for
* {@code Integer.class}). For other classes, or if the parameter is
* <b>null</b>, the return value is <b>null</b>.</p>
*
* @param cls the class to convert, may be <b>null</b>
* @return the corresponding primitive type if {@code cls} is a
* wrapper class, <b>null</b> otherwise
* @see #primitiveToWrapper(Class)
* @since 2.4
*/
public static Class<?> wrapperToPrimitive(Class<?> cls) {
return wrapperPrimitiveMap.get(cls);
}
/**
* <p>Converts the specified array of wrapper Class objects to an array of
* its corresponding primitive Class objects.</p>
*
* <p>This method invokes {@code wrapperToPrimitive()} for each element
* of the passed in array.</p>
*
* @param classes the class array to convert, may be null or empty
* @return an array which contains for each given class, the primitive class or
* <b>null</b> if the original class is not a wrapper class. {@code null} if null input.
* Empty array if an empty array passed in.
* @see #wrapperToPrimitive(Class)
* @since 2.4
*/
public static Class<?>[] wrappersToPrimitives(Class<?>... classes) {
if (classes == null) {
return null;
}
if (classes.length == 0) {
return classes;
}
Class<?>[] convertedClasses = new Class[classes.length];
for (int i = 0; i < classes.length; i++) {
convertedClasses[i] = wrapperToPrimitive(classes[i]);
}
return convertedClasses;
}
// Inner class
// ----------------------------------------------------------------------
/**
* <p>Is the specified class an inner class or static nested class.</p>
*
* @param cls the class to check, may be null
* @return {@code true} if the class is an inner or static nested class,
* false if not or {@code null}
*/
public static boolean isInnerClass(Class<?> cls) {
return cls != null && cls.getEnclosingClass() != null;
}
// Class loading
// ----------------------------------------------------------------------
/**
* Returns the class represented by {@code className} using the
* {@code classLoader}. This implementation supports the syntaxes
* "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
* "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
*
* @param classLoader the class loader to use to load the class
* @param className the class name
* @param initialize whether the class must be initialized
* @return the class represented by {@code className} using the {@code classLoader}
* @throws ClassNotFoundException if the class is not found
*/
public static Class<?> getClass(
ClassLoader classLoader, String className, boolean initialize) throws ClassNotFoundException {
try {
Class<?> clazz;
if (abbreviationMap.containsKey(className)) {
String clsName = "[" + abbreviationMap.get(className);
clazz = Class.forName(clsName, initialize, classLoader).getComponentType();
} else {
clazz = Class.forName(toCanonicalName(className), initialize, classLoader);
}
return clazz;
} catch (ClassNotFoundException ex) {
// allow path separators (.) as inner class name separators
int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR_CHAR);
if (lastDotIndex != -1) {
try {
return getClass(classLoader, className.substring(0, lastDotIndex) +
INNER_CLASS_SEPARATOR_CHAR + className.substring(lastDotIndex + 1),
initialize);
} catch (ClassNotFoundException ex2) { // NOPMD
// ignore exception
}
}
throw ex;
}
}
/**
* Returns the (initialized) class represented by {@code className}
* using the {@code classLoader}. This implementation supports
* the syntaxes "{@code java.util.Map.Entry[]}",
* "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}",
* and "{@code [Ljava.util.Map$Entry;}".
*
* @param classLoader the class loader to use to load the class
* @param className the class name
* @return the class represented by {@code className} using the {@code classLoader}
* @throws ClassNotFoundException if the class is not found
*/
public static Class<?> getClass(ClassLoader classLoader, String className) throws ClassNotFoundException {
return getClass(classLoader, className, true);
}
/**
* Returns the (initialized) class represented by {@code className}
* using the current thread's context class loader. This implementation
* supports the syntaxes "{@code java.util.Map.Entry[]}",
* "{@code java.util.Map$Entry[]}", "{@code [Ljava.util.Map.Entry;}",
* and "{@code [Ljava.util.Map$Entry;}".
*
* @param className the class name
* @return the class represented by {@code className} using the current thread's context class loader
* @throws ClassNotFoundException if the class is not found
*/
public static Class<?> getClass(String className) throws ClassNotFoundException {
return getClass(className, true);
}
/**
* Returns the class represented by {@code className} using the
* current thread's context class loader. This implementation supports the
* syntaxes "{@code java.util.Map.Entry[]}", "{@code java.util.Map$Entry[]}",
* "{@code [Ljava.util.Map.Entry;}", and "{@code [Ljava.util.Map$Entry;}".
*
* @param className the class name
* @param initialize whether the class must be initialized
* @return the class represented by {@code className} using the current thread's context class loader
* @throws ClassNotFoundException if the class is not found
*/
public static Class<?> getClass(String className, boolean initialize) throws ClassNotFoundException {
ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
ClassLoader loader = contextCL == null ? ClassUtils.class.getClassLoader() : contextCL;
return getClass(loader, className, initialize);
}
// Public method
// ----------------------------------------------------------------------
/**
* <p>Returns the desired Method much like {@code Class.getMethod}, however
* it ensures that the returned Method is from a public class or interface and not
* from an anonymous inner class. This means that the Method is invokable and
* doesn't fall foul of Java bug
* <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>).
*
* <code><pre>Set set = Collections.unmodifiableSet(...);
* Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]);
* Object result = method.invoke(set, new Object[]);</pre></code>
* </p>
*
* @param cls the class to check, not null
* @param methodName the name of the method
* @param parameterTypes the list of parameters
* @return the method
* @throws NullPointerException if the class is null
* @throws SecurityException if a a security violation occured
* @throws NoSuchMethodException if the method is not found in the given class
* or if the metothod doen't conform with the requirements
*/
public static Method getPublicMethod(Class<?> cls, String methodName, Class<?>... parameterTypes)
throws SecurityException, NoSuchMethodException {
Method declaredMethod = cls.getMethod(methodName, parameterTypes);
if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
return declaredMethod;
}
List<Class<?>> candidateClasses = new ArrayList<Class<?>>();
candidateClasses.addAll(getAllInterfaces(cls));
candidateClasses.addAll(getAllSuperclasses(cls));
for (Class<?> candidateClass : candidateClasses) {
if (!Modifier.isPublic(candidateClass.getModifiers())) {
continue;
}
Method candidateMethod;
try {
candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
} catch (NoSuchMethodException ex) {
continue;
}
if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
return candidateMethod;
}
}
throw new NoSuchMethodException("Can't find a public method for " +
methodName + " " + ArrayUtils.toString(parameterTypes));
}
// ----------------------------------------------------------------------
/**
* Converts a class name to a JLS style class name.
*
* @param className the class name
* @return the converted name
*/
private static String toCanonicalName(String className) {
className = StringUtils.deleteWhitespace(className);
if (className == null) {
throw new NullPointerException("className must not be null.");
} else if (className.endsWith("[]")) {
StringBuilder classNameBuffer = new StringBuilder();
while (className.endsWith("[]")) {
className = className.substring(0, className.length() - 2);
classNameBuffer.append("[");
}
String abbreviation = abbreviationMap.get(className);
if (abbreviation != null) {
classNameBuffer.append(abbreviation);
} else {
classNameBuffer.append("L").append(className).append(";");
}
className = classNameBuffer.toString();
}
return className;
}
/**
* <p>Converts an array of {@code Object} in to an array of {@code Class} objects.
* If any of these objects is null, a null element will be inserted into the array.</p>
*
* <p>This method returns {@code null} for a {@code null} input array.</p>
*
* @param array an {@code Object} array
* @return a {@code Class} array, {@code null} if null array input
* @since 2.4
*/
public static Class<?>[] toClass(Object... array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return ArrayUtils.EMPTY_CLASS_ARRAY;
}
Class<?>[] classes = new Class[array.length];
for (int i = 0; i < array.length; i++) {
classes[i] = array[i] == null ? null : array[i].getClass();
}
return classes;
}
// Short canonical name
// ----------------------------------------------------------------------
/**
* <p>Gets the canonical name minus the package name for an {@code Object}.</p>
*
* @param object the class to get the short name for, may be null
* @param valueIfNull the value to return if null
* @return the canonical name of the object without the package name, or the null value
* @since 2.4
*/
public static String getShortCanonicalName(Object object, String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getShortCanonicalName(object.getClass().getName());
}
/**
* <p>Gets the canonical name minus the package name from a {@code Class}.</p>
*
* @param cls the class to get the short name for.
* @return the canonical name without the package name or an empty string
* @since 2.4
*/
public static String getShortCanonicalName(Class<?> cls) {
if (cls == null) {
return StringUtils.EMPTY;
}
return getShortCanonicalName(cls.getName());
}
/**
* <p>Gets the canonical name minus the package name from a String.</p>
*
* <p>The string passed in is assumed to be a canonical name - it is not checked.</p>
*
* @param canonicalName the class name to get the short name for
* @return the canonical name of the class without the package name or an empty string
* @since 2.4
*/
public static String getShortCanonicalName(String canonicalName) {
return ClassUtils.getShortClassName(getCanonicalName(canonicalName));
}
// Package name
// ----------------------------------------------------------------------
/**
* <p>Gets the package name from the canonical name of an {@code Object}.</p>
*
* @param object the class to get the package name for, may be null
* @param valueIfNull the value to return if null
* @return the package name of the object, or the null value
* @since 2.4
*/
public static String getPackageCanonicalName(Object object, String valueIfNull) {
if (object == null) {
return valueIfNull;
}
return getPackageCanonicalName(object.getClass().getName());
}
/**
* <p>Gets the package name from the canonical name of a {@code Class}.</p>
*
* @param cls the class to get the package name for, may be {@code null}.
* @return the package name or an empty string
* @since 2.4
*/
public static String getPackageCanonicalName(Class<?> cls) {
if (cls == null) {
return StringUtils.EMPTY;
}
return getPackageCanonicalName(cls.getName());
}
/**
* <p>Gets the package name from the canonical name. </p>
*
* <p>The string passed in is assumed to be a canonical name - it is not checked.</p>
* <p>If the class is unpackaged, return an empty string.</p>
*
* @param canonicalName the canonical name to get the package name for, may be {@code null}
* @return the package name or an empty string
* @since 2.4
*/
public static String getPackageCanonicalName(String canonicalName) {
return ClassUtils.getPackageName(getCanonicalName(canonicalName));
}
/**
* <p>Converts a given name of class into canonical format.
* If name of class is not a name of array class it returns
* unchanged name.</p>
* <p>Example:
* <ul>
* <li>{@code getCanonicalName("[I") = "int[]"}</li>
* <li>{@code getCanonicalName("[Ljava.lang.String;") = "java.lang.String[]"}</li>
* <li>{@code getCanonicalName("java.lang.String") = "java.lang.String"}</li>
* </ul>
* </p>
*
* @param className the name of class
* @return canonical form of class name
* @since 2.4
*/
private static String getCanonicalName(String className) {
className = StringUtils.deleteWhitespace(className);
if (className == null) {
return null;
} else {
int dim = 0;
while (className.startsWith("[")) {
dim++;
className = className.substring(1);
}
if (dim < 1) {
return className;
} else {
if (className.startsWith("L")) {
className = className.substring(
1,
className.endsWith(";")
? className.length() - 1
: className.length());
} else {
if (className.length() > 0) {
className = reverseAbbreviationMap.get(className.substring(0, 1));
}
}
StringBuilder canonicalClassNameBuffer = new StringBuilder(className);
for (int i = 0; i < dim; i++) {
canonicalClassNameBuffer.append("[]");
}
return canonicalClassNameBuffer.toString();
}
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3;
/**
* <p>An enum representing all the versions of the Java specification.
* This is intended to mirror available values from the
* <em>java.specification.version</em> System property. </p>
*
* @since 3.0
* @version $Id: $
*/
public enum JavaVersion {
/**
* The Java version reported by Android. This is not an official Java version number.
*/
JAVA_0_9(1.5f, "0.9"),
/**
* Java 1.1.
*/
JAVA_1_1(1.1f, "1.1"),
/**
* Java 1.2.
*/
JAVA_1_2(1.2f, "1.2"),
/**
* Java 1.3.
*/
JAVA_1_3(1.3f, "1.3"),
/**
* Java 1.4.
*/
JAVA_1_4(1.4f, "1.4"),
/**
* Java 1.5.
*/
JAVA_1_5(1.5f, "1.5"),
/**
* Java 1.6.
*/
JAVA_1_6(1.6f, "1.6"),
/**
* Java 1.7.
*/
JAVA_1_7(1.7f, "1.7"),
/**
* Java 1.8.
*/
JAVA_1_8(1.8f, "1.8");
/**
* The float value.
*/
private float value;
/**
* The standard name.
*/
private String name;
/**
* Constructor.
*
* @param value the float value
* @param name the standard name, not null
*/
JavaVersion(final float value, final String name) {
this.value = value;
this.name = name;
}
//-----------------------------------------------------------------------
/**
* <p>Whether this version of Java is at least the version of Java passed in.</p>
*
* <p>For example:<br />
* {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}<p>
*
* @param requiredVersion the version to check against, not null
* @return true if this version is equal to or greater than the specified version
*/
public boolean atLeast(JavaVersion requiredVersion) {
return this.value >= requiredVersion.value;
}
/**
* Transforms the given string with a Java version number to the
* corresponding constant of this enumeration class. This method is used
* internally.
*
* @param nom the Java version as string
* @return the corresponding enumeration constant or <b>null</b> if the
* version is unknown
*/
// helper for static importing
static JavaVersion getJavaVersion(final String nom) {
return get(nom);
}
/**
* Transforms the given string with a Java version number to the
* corresponding constant of this enumeration class. This method is used
* internally.
*
* @param nom the Java version as string
* @return the corresponding enumeration constant or <b>null</b> if the
* version is unknown
*/
static JavaVersion get(final String nom) {
if ("0.9".equals(nom)) {
return JAVA_0_9;
} else if ("1.1".equals(nom)) {
return JAVA_1_1;
} else if ("1.2".equals(nom)) {
return JAVA_1_2;
} else if ("1.3".equals(nom)) {
return JAVA_1_3;
} else if ("1.4".equals(nom)) {
return JAVA_1_4;
} else if ("1.5".equals(nom)) {
return JAVA_1_5;
} else if ("1.6".equals(nom)) {
return JAVA_1_6;
} else if ("1.7".equals(nom)) {
return JAVA_1_7;
} else if ("1.8".equals(nom)) {
return JAVA_1_8;
} else {
return null;
}
}
//-----------------------------------------------------------------------
/**
* <p>The string value is overridden to return the standard name.</p>
*
* <p>For example, <code>"1.5"</code>.</p>
*
* @return the name, not null
*/
@Override
public String toString() {
return name;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import external.org.apache.commons.lang3.exception.CloneFailedException;
import external.org.apache.commons.lang3.mutable.MutableInt;
/**
* <p>Operations on {@code Object}.</p>
*
* <p>This class tries to handle {@code null} input gracefully.
* An exception will generally not be thrown for a {@code null} input.
* Each method documents its behaviour in more detail.</p>
*
* <p>#ThreadSafe#</p>
* @since 1.0
* @version $Id: ObjectUtils.java 1199894 2011-11-09 17:53:59Z ggregory $
*/
//@Immutable
public class ObjectUtils {
/**
* <p>Singleton used as a {@code null} placeholder where
* {@code null} has another meaning.</p>
*
* <p>For example, in a {@code HashMap} the
* {@link HashMap#get(Object)} method returns
* {@code null} if the {@code Map} contains {@code null} or if there
* is no matching key. The {@code Null} placeholder can be used to
* distinguish between these two cases.</p>
*
* <p>Another example is {@code Hashtable}, where {@code null}
* cannot be stored.</p>
*
* <p>This instance is Serializable.</p>
*/
public static final Null NULL = new Null();
/**
* <p>{@code ObjectUtils} instances should NOT be constructed in
* standard programming. Instead, the static methods on the class should
* be used, such as {@code ObjectUtils.defaultIfNull("a","b");}.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public ObjectUtils() {
super();
}
// Defaulting
//-----------------------------------------------------------------------
/**
* <p>Returns a default value if the object passed is {@code null}.</p>
*
* <pre>
* ObjectUtils.defaultIfNull(null, null) = null
* ObjectUtils.defaultIfNull(null, "") = ""
* ObjectUtils.defaultIfNull(null, "zz") = "zz"
* ObjectUtils.defaultIfNull("abc", *) = "abc"
* ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
* </pre>
*
* @param <T> the type of the object
* @param object the {@code Object} to test, may be {@code null}
* @param defaultValue the default value to return, may be {@code null}
* @return {@code object} if it is not {@code null}, defaultValue otherwise
*/
public static <T> T defaultIfNull(T object, T defaultValue) {
return object != null ? object : defaultValue;
}
/**
* <p>Returns the first value in the array which is not {@code null}.
* If all the values are {@code null} or the array is {@code null}
* or empty then {@code null} is returned.</p>
*
* <pre>
* ObjectUtils.firstNonNull(null, null) = null
* ObjectUtils.firstNonNull(null, "") = ""
* ObjectUtils.firstNonNull(null, null, "") = ""
* ObjectUtils.firstNonNull(null, "zz") = "zz"
* ObjectUtils.firstNonNull("abc", *) = "abc"
* ObjectUtils.firstNonNull(null, "xyz", *) = "xyz"
* ObjectUtils.firstNonNull(Boolean.TRUE, *) = Boolean.TRUE
* ObjectUtils.firstNonNull() = null
* </pre>
*
* @param <T> the component type of the array
* @param values the values to test, may be {@code null} or empty
* @return the first value from {@code values} which is not {@code null},
* or {@code null} if there are no non-null values
* @since 3.0
*/
public static <T> T firstNonNull(T... values) {
if (values != null) {
for (T val : values) {
if (val != null) {
return val;
}
}
}
return null;
}
// Null-safe equals/hashCode
//-----------------------------------------------------------------------
/**
* <p>Compares two objects for equality, where either one or both
* objects may be {@code null}.</p>
*
* <pre>
* ObjectUtils.equals(null, null) = true
* ObjectUtils.equals(null, "") = false
* ObjectUtils.equals("", null) = false
* ObjectUtils.equals("", "") = true
* ObjectUtils.equals(Boolean.TRUE, null) = false
* ObjectUtils.equals(Boolean.TRUE, "true") = false
* ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE) = true
* ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
* </pre>
*
* @param object1 the first object, may be {@code null}
* @param object2 the second object, may be {@code null}
* @return {@code true} if the values of both objects are the same
*/
public static boolean equals(Object object1, Object object2) {
if (object1 == object2) {
return true;
}
if (object1 == null || object2 == null) {
return false;
}
return object1.equals(object2);
}
/**
* <p>Compares two objects for inequality, where either one or both
* objects may be {@code null}.</p>
*
* <pre>
* ObjectUtils.notEqual(null, null) = false
* ObjectUtils.notEqual(null, "") = true
* ObjectUtils.notEqual("", null) = true
* ObjectUtils.notEqual("", "") = false
* ObjectUtils.notEqual(Boolean.TRUE, null) = true
* ObjectUtils.notEqual(Boolean.TRUE, "true") = true
* ObjectUtils.notEqual(Boolean.TRUE, Boolean.TRUE) = false
* ObjectUtils.notEqual(Boolean.TRUE, Boolean.FALSE) = true
* </pre>
*
* @param object1 the first object, may be {@code null}
* @param object2 the second object, may be {@code null}
* @return {@code false} if the values of both objects are the same
*/
public static boolean notEqual(Object object1, Object object2) {
return ObjectUtils.equals(object1, object2) == false;
}
/**
* <p>Gets the hash code of an object returning zero when the
* object is {@code null}.</p>
*
* <pre>
* ObjectUtils.hashCode(null) = 0
* ObjectUtils.hashCode(obj) = obj.hashCode()
* </pre>
*
* @param obj the object to obtain the hash code of, may be {@code null}
* @return the hash code of the object, or zero if null
* @since 2.1
*/
public static int hashCode(Object obj) {
// hashCode(Object) retained for performance, as hash code is often critical
return obj == null ? 0 : obj.hashCode();
}
/**
* <p>Gets the hash code for multiple objects.</p>
*
* <p>This allows a hash code to be rapidly calculated for a number of objects.
* The hash code for a single object is the <em>not</em> same as {@link #hashCode(Object)}.
* The hash code for multiple objects is the same as that calculated by an
* {@code ArrayList} containing the specified objects.</p>
*
* <pre>
* ObjectUtils.hashCodeMulti() = 1
* ObjectUtils.hashCodeMulti((Object[]) null) = 1
* ObjectUtils.hashCodeMulti(a) = 31 + a.hashCode()
* ObjectUtils.hashCodeMulti(a,b) = (31 + a.hashCode()) * 31 + b.hashCode()
* ObjectUtils.hashCodeMulti(a,b,c) = ((31 + a.hashCode()) * 31 + b.hashCode()) * 31 + c.hashCode()
* </pre>
*
* @param objects the objects to obtain the hash code of, may be {@code null}
* @return the hash code of the objects, or zero if null
* @since 3.0
*/
public static int hashCodeMulti(Object... objects) {
int hash = 1;
if (objects != null) {
for (Object object : objects) {
hash = hash * 31 + ObjectUtils.hashCode(object);
}
}
return hash;
}
// Identity ToString
//-----------------------------------------------------------------------
/**
* <p>Gets the toString that would be produced by {@code Object}
* if a class did not override toString itself. {@code null}
* will return {@code null}.</p>
*
* <pre>
* ObjectUtils.identityToString(null) = null
* ObjectUtils.identityToString("") = "java.lang.String@1e23"
* ObjectUtils.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
* </pre>
*
* @param object the object to create a toString for, may be
* {@code null}
* @return the default toString text, or {@code null} if
* {@code null} passed in
*/
public static String identityToString(Object object) {
if (object == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
identityToString(buffer, object);
return buffer.toString();
}
/**
* <p>Appends the toString that would be produced by {@code Object}
* if a class did not override toString itself. {@code null}
* will throw a NullPointerException for either of the two parameters. </p>
*
* <pre>
* ObjectUtils.identityToString(buf, "") = buf.append("java.lang.String@1e23"
* ObjectUtils.identityToString(buf, Boolean.TRUE) = buf.append("java.lang.Boolean@7fa"
* ObjectUtils.identityToString(buf, Boolean.TRUE) = buf.append("java.lang.Boolean@7fa")
* </pre>
*
* @param buffer the buffer to append to
* @param object the object to create a toString for
* @since 2.4
*/
public static void identityToString(StringBuffer buffer, Object object) {
if (object == null) {
throw new NullPointerException("Cannot get the toString of a null identity");
}
buffer.append(object.getClass().getName())
.append('@')
.append(Integer.toHexString(System.identityHashCode(object)));
}
// ToString
//-----------------------------------------------------------------------
/**
* <p>Gets the {@code toString} of an {@code Object} returning
* an empty string ("") if {@code null} input.</p>
*
* <pre>
* ObjectUtils.toString(null) = ""
* ObjectUtils.toString("") = ""
* ObjectUtils.toString("bat") = "bat"
* ObjectUtils.toString(Boolean.TRUE) = "true"
* </pre>
*
* @see StringUtils#defaultString(String)
* @see String#valueOf(Object)
* @param obj the Object to {@code toString}, may be null
* @return the passed in Object's toString, or nullStr if {@code null} input
* @since 2.0
*/
public static String toString(Object obj) {
return obj == null ? "" : obj.toString();
}
/**
* <p>Gets the {@code toString} of an {@code Object} returning
* a specified text if {@code null} input.</p>
*
* <pre>
* ObjectUtils.toString(null, null) = null
* ObjectUtils.toString(null, "null") = "null"
* ObjectUtils.toString("", "null") = ""
* ObjectUtils.toString("bat", "null") = "bat"
* ObjectUtils.toString(Boolean.TRUE, "null") = "true"
* </pre>
*
* @see StringUtils#defaultString(String,String)
* @see String#valueOf(Object)
* @param obj the Object to {@code toString}, may be null
* @param nullStr the String to return if {@code null} input, may be null
* @return the passed in Object's toString, or nullStr if {@code null} input
* @since 2.0
*/
public static String toString(Object obj, String nullStr) {
return obj == null ? nullStr : obj.toString();
}
// Comparable
//-----------------------------------------------------------------------
/**
* <p>Null safe comparison of Comparables.</p>
*
* @param <T> type of the values processed by this method
* @param values the set of comparable values, may be null
* @return
* <ul>
* <li>If any objects are non-null and unequal, the lesser object.
* <li>If all objects are non-null and equal, the first.
* <li>If any of the comparables are null, the lesser of the non-null objects.
* <li>If all the comparables are null, null is returned.
* </ul>
*/
public static <T extends Comparable<? super T>> T min(T... values) {
T result = null;
if (values != null) {
for (T value : values) {
if (compare(value, result, true) < 0) {
result = value;
}
}
}
return result;
}
/**
* <p>Null safe comparison of Comparables.</p>
*
* @param <T> type of the values processed by this method
* @param values the set of comparable values, may be null
* @return
* <ul>
* <li>If any objects are non-null and unequal, the greater object.
* <li>If all objects are non-null and equal, the first.
* <li>If any of the comparables are null, the greater of the non-null objects.
* <li>If all the comparables are null, null is returned.
* </ul>
*/
public static <T extends Comparable<? super T>> T max(T... values) {
T result = null;
if (values != null) {
for (T value : values) {
if (compare(value, result, false) > 0) {
result = value;
}
}
}
return result;
}
/**
* <p>Null safe comparison of Comparables.
* {@code null} is assumed to be less than a non-{@code null} value.</p>
*
* @param <T> type of the values processed by this method
* @param c1 the first comparable, may be null
* @param c2 the second comparable, may be null
* @return a negative value if c1 < c2, zero if c1 = c2
* and a positive value if c1 > c2
*/
public static <T extends Comparable<? super T>> int compare(T c1, T c2) {
return compare(c1, c2, false);
}
/**
* <p>Null safe comparison of Comparables.</p>
*
* @param <T> type of the values processed by this method
* @param c1 the first comparable, may be null
* @param c2 the second comparable, may be null
* @param nullGreater if true {@code null} is considered greater
* than a non-{@code null} value or if false {@code null} is
* considered less than a Non-{@code null} value
* @return a negative value if c1 < c2, zero if c1 = c2
* and a positive value if c1 > c2
* @see Comparator#compare(Object, Object)
*/
public static <T extends Comparable<? super T>> int compare(T c1, T c2, boolean nullGreater) {
if (c1 == c2) {
return 0;
} else if (c1 == null) {
return nullGreater ? 1 : -1;
} else if (c2 == null) {
return nullGreater ? -1 : 1;
}
return c1.compareTo(c2);
}
/**
* Find the "best guess" middle value among comparables. If there is an even
* number of total values, the lower of the two middle values will be returned.
* @param <T> type of values processed by this method
* @param items to compare
* @return T at middle position
* @throws NullPointerException if items is {@code null}
* @throws IllegalArgumentException if items is empty or contains {@code null} values
* @since 3.0.1
*/
public static <T extends Comparable<? super T>> T median(T... items) {
Validate.notEmpty(items);
Validate.noNullElements(items);
TreeSet<T> sort = new TreeSet<T>();
Collections.addAll(sort, items);
@SuppressWarnings("unchecked") //we know all items added were T instances
T result = (T) sort.toArray()[(sort.size() - 1) / 2];
return result;
}
/**
* Find the "best guess" middle value among comparables. If there is an even
* number of total values, the lower of the two middle values will be returned.
* @param <T> type of values processed by this method
* @param comparator to use for comparisons
* @param items to compare
* @return T at middle position
* @throws NullPointerException if items or comparator is {@code null}
* @throws IllegalArgumentException if items is empty or contains {@code null} values
* @since 3.0.1
*/
public static <T> T median(Comparator<T> comparator, T... items) {
Validate.notEmpty(items, "null/empty items");
Validate.noNullElements(items);
Validate.notNull(comparator, "null comparator");
TreeSet<T> sort = new TreeSet<T>(comparator);
Collections.addAll(sort, items);
@SuppressWarnings("unchecked") //we know all items added were T instances
T result = (T) sort.toArray()[(sort.size() - 1) / 2];
return result;
}
// Mode
//-----------------------------------------------------------------------
/**
* Find the most frequently occurring item.
*
* @param <T> type of values processed by this method
* @param items to check
* @return most populous T, {@code null} if non-unique or no items supplied
* @since 3.0.1
*/
public static <T> T mode(T... items) {
if (ArrayUtils.isNotEmpty(items)) {
HashMap<T, MutableInt> occurrences = new HashMap<T, MutableInt>(items.length);
for (T t : items) {
MutableInt count = occurrences.get(t);
if (count == null) {
occurrences.put(t, new MutableInt(1));
} else {
count.increment();
}
}
T result = null;
int max = 0;
for (Map.Entry<T, MutableInt> e : occurrences.entrySet()) {
int cmp = e.getValue().intValue();
if (cmp == max) {
result = null;
} else if (cmp > max) {
max = cmp;
result = e.getKey();
}
}
return result;
}
return null;
}
// cloning
//-----------------------------------------------------------------------
/**
* <p>Clone an object.</p>
*
* @param <T> the type of the object
* @param obj the object to clone, null returns null
* @return the clone if the object implements {@link Cloneable} otherwise {@code null}
* @throws CloneFailedException if the object is cloneable and the clone operation fails
* @since 3.0
*/
public static <T> T clone(final T obj) {
if (obj instanceof Cloneable) {
final Object result;
if (obj.getClass().isArray()) {
final Class<?> componentType = obj.getClass().getComponentType();
if (!componentType.isPrimitive()) {
result = ((Object[]) obj).clone();
} else {
int length = Array.getLength(obj);
result = Array.newInstance(componentType, length);
while (length-- > 0) {
Array.set(result, length, Array.get(obj, length));
}
}
} else {
try {
final Method clone = obj.getClass().getMethod("clone");
result = clone.invoke(obj);
} catch (final NoSuchMethodException e) {
throw new CloneFailedException("Cloneable type "
+ obj.getClass().getName()
+ " has no clone method", e);
} catch (final IllegalAccessException e) {
throw new CloneFailedException("Cannot clone Cloneable type "
+ obj.getClass().getName(), e);
} catch (final InvocationTargetException e) {
throw new CloneFailedException("Exception cloning Cloneable type "
+ obj.getClass().getName(), e.getCause());
}
}
@SuppressWarnings("unchecked")
final T checked = (T) result;
return checked;
}
return null;
}
/**
* <p>Clone an object if possible.</p>
*
* <p>This method is similar to {@link #clone(Object)}, but will return the provided
* instance as the return value instead of {@code null} if the instance
* is not cloneable. This is more convenient if the caller uses different
* implementations (e.g. of a service) and some of the implementations do not allow concurrent
* processing or have state. In such cases the implementation can simply provide a proper
* clone implementation and the caller's code does not have to change.</p>
*
* @param <T> the type of the object
* @param obj the object to clone, null returns null
* @return the clone if the object implements {@link Cloneable} otherwise the object itself
* @throws CloneFailedException if the object is cloneable and the clone operation fails
* @since 3.0
*/
public static <T> T cloneIfPossible(final T obj) {
final T clone = clone(obj);
return clone == null ? obj : clone;
}
// Null
//-----------------------------------------------------------------------
/**
* <p>Class used as a null placeholder where {@code null}
* has another meaning.</p>
*
* <p>For example, in a {@code HashMap} the
* {@link HashMap#get(Object)} method returns
* {@code null} if the {@code Map} contains {@code null} or if there is
* no matching key. The {@code Null} placeholder can be used to distinguish
* between these two cases.</p>
*
* <p>Another example is {@code Hashtable}, where {@code null}
* cannot be stored.</p>
*/
public static class Null implements Serializable {
/**
* Required for serialization support. Declare serialization compatibility with Commons Lang 1.0
*
* @see Serializable
*/
private static final long serialVersionUID = 7092611880189329093L;
/**
* Restricted constructor - singleton.
*/
Null() {
super();
}
/**
* <p>Ensure singleton.</p>
*
* @return the singleton value
*/
private Object readResolve() {
return ObjectUtils.NULL;
}
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3;
import java.io.File;
/**
* <p>
* Helpers for {@code java.lang.System}.
* </p>
* <p>
* If a system property cannot be read due to security restrictions, the corresponding field in this class will be set
* to {@code null} and a message will be written to {@code System.err}.
* </p>
* <p>
* #ThreadSafe#
* </p>
*
* @since 1.0
* @version $Id: SystemUtils.java 1199816 2011-11-09 16:11:34Z bayard $
*/
public class SystemUtils {
/**
* The prefix String for all Windows OS.
*/
private static final String OS_NAME_WINDOWS_PREFIX = "Windows";
// System property constants
// -----------------------------------------------------------------------
// These MUST be declared first. Other constants depend on this.
/**
* The System property key for the user home directory.
*/
private static final String USER_HOME_KEY = "user.home";
/**
* The System property key for the user directory.
*/
private static final String USER_DIR_KEY = "user.dir";
/**
* The System property key for the Java IO temporary directory.
*/
private static final String JAVA_IO_TMPDIR_KEY = "java.io.tmpdir";
/**
* The System property key for the Java home directory.
*/
private static final String JAVA_HOME_KEY = "java.home";
/**
* <p>
* The {@code awt.toolkit} System Property.
* </p>
* <p>
* Holds a class name, on Windows XP this is {@code sun.awt.windows.WToolkit}.
* </p>
* <p>
* <b>On platforms without a GUI, this value is {@code null}.</b>
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.1
*/
public static final String AWT_TOOLKIT = getSystemProperty("awt.toolkit");
/**
* <p>
* The {@code file.encoding} System Property.
* </p>
* <p>
* File encoding, such as {@code Cp1252}.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.2
*/
public static final String FILE_ENCODING = getSystemProperty("file.encoding");
/**
* <p>
* The {@code file.separator} System Property. File separator (<code>&quot;/&quot;</code> on UNIX).
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String FILE_SEPARATOR = getSystemProperty("file.separator");
/**
* <p>
* The {@code java.awt.fonts} System Property.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.1
*/
public static final String JAVA_AWT_FONTS = getSystemProperty("java.awt.fonts");
/**
* <p>
* The {@code java.awt.graphicsenv} System Property.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.1
*/
public static final String JAVA_AWT_GRAPHICSENV = getSystemProperty("java.awt.graphicsenv");
/**
* <p>
* The {@code java.awt.headless} System Property. The value of this property is the String {@code "true"} or
* {@code "false"}.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @see #isJavaAwtHeadless()
* @since 2.1
* @since Java 1.4
*/
public static final String JAVA_AWT_HEADLESS = getSystemProperty("java.awt.headless");
/**
* <p>
* The {@code java.awt.printerjob} System Property.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.1
*/
public static final String JAVA_AWT_PRINTERJOB = getSystemProperty("java.awt.printerjob");
/**
* <p>
* The {@code java.class.path} System Property. Java class path.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_CLASS_PATH = getSystemProperty("java.class.path");
/**
* <p>
* The {@code java.class.version} System Property. Java class format version number.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_CLASS_VERSION = getSystemProperty("java.class.version");
/**
* <p>
* The {@code java.compiler} System Property. Name of JIT compiler to use. First in JDK version 1.2. Not used in Sun
* JDKs after 1.2.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.2. Not used in Sun versions after 1.2.
*/
public static final String JAVA_COMPILER = getSystemProperty("java.compiler");
/**
* <p>
* The {@code java.endorsed.dirs} System Property. Path of endorsed directory or directories.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.4
*/
public static final String JAVA_ENDORSED_DIRS = getSystemProperty("java.endorsed.dirs");
/**
* <p>
* The {@code java.ext.dirs} System Property. Path of extension directory or directories.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.3
*/
public static final String JAVA_EXT_DIRS = getSystemProperty("java.ext.dirs");
/**
* <p>
* The {@code java.home} System Property. Java installation directory.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_HOME = getSystemProperty(JAVA_HOME_KEY);
/**
* <p>
* The {@code java.io.tmpdir} System Property. Default temp file path.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_IO_TMPDIR = getSystemProperty(JAVA_IO_TMPDIR_KEY);
/**
* <p>
* The {@code java.library.path} System Property. List of paths to search when loading libraries.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_LIBRARY_PATH = getSystemProperty("java.library.path");
/**
* <p>
* The {@code java.runtime.name} System Property. Java Runtime Environment name.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.3
*/
public static final String JAVA_RUNTIME_NAME = getSystemProperty("java.runtime.name");
/**
* <p>
* The {@code java.runtime.version} System Property. Java Runtime Environment version.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.3
*/
public static final String JAVA_RUNTIME_VERSION = getSystemProperty("java.runtime.version");
/**
* <p>
* The {@code java.specification.name} System Property. Java Runtime Environment specification name.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_SPECIFICATION_NAME = getSystemProperty("java.specification.name");
/**
* <p>
* The {@code java.specification.vendor} System Property. Java Runtime Environment specification vendor.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_SPECIFICATION_VENDOR = getSystemProperty("java.specification.vendor");
/**
* <p>
* The {@code java.specification.version} System Property. Java Runtime Environment specification version.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.3
*/
public static final String JAVA_SPECIFICATION_VERSION = getSystemProperty("java.specification.version");
private static final JavaVersion JAVA_SPECIFICATION_VERSION_AS_ENUM = JavaVersion.get(JAVA_SPECIFICATION_VERSION);
/**
* <p>
* The {@code java.util.prefs.PreferencesFactory} System Property. A class name.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.1
* @since Java 1.4
*/
public static final String JAVA_UTIL_PREFS_PREFERENCES_FACTORY =
getSystemProperty("java.util.prefs.PreferencesFactory");
/**
* <p>
* The {@code java.vendor} System Property. Java vendor-specific string.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_VENDOR = getSystemProperty("java.vendor");
/**
* <p>
* The {@code java.vendor.url} System Property. Java vendor URL.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_VENDOR_URL = getSystemProperty("java.vendor.url");
/**
* <p>
* The {@code java.version} System Property. Java version number.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String JAVA_VERSION = getSystemProperty("java.version");
/**
* <p>
* The {@code java.vm.info} System Property. Java Virtual Machine implementation info.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.2
*/
public static final String JAVA_VM_INFO = getSystemProperty("java.vm.info");
/**
* <p>
* The {@code java.vm.name} System Property. Java Virtual Machine implementation name.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_NAME = getSystemProperty("java.vm.name");
/**
* <p>
* The {@code java.vm.specification.name} System Property. Java Virtual Machine specification name.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_SPECIFICATION_NAME = getSystemProperty("java.vm.specification.name");
/**
* <p>
* The {@code java.vm.specification.vendor} System Property. Java Virtual Machine specification vendor.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_SPECIFICATION_VENDOR = getSystemProperty("java.vm.specification.vendor");
/**
* <p>
* The {@code java.vm.specification.version} System Property. Java Virtual Machine specification version.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_SPECIFICATION_VERSION = getSystemProperty("java.vm.specification.version");
/**
* <p>
* The {@code java.vm.vendor} System Property. Java Virtual Machine implementation vendor.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_VENDOR = getSystemProperty("java.vm.vendor");
/**
* <p>
* The {@code java.vm.version} System Property. Java Virtual Machine implementation version.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.2
*/
public static final String JAVA_VM_VERSION = getSystemProperty("java.vm.version");
/**
* <p>
* The {@code line.separator} System Property. Line separator (<code>&quot;\n&quot;</code> on UNIX).
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String LINE_SEPARATOR = getSystemProperty("line.separator");
/**
* <p>
* The {@code os.arch} System Property. Operating system architecture.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String OS_ARCH = getSystemProperty("os.arch");
/**
* <p>
* The {@code os.name} System Property. Operating system name.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String OS_NAME = getSystemProperty("os.name");
/**
* <p>
* The {@code os.version} System Property. Operating system version.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String OS_VERSION = getSystemProperty("os.version");
/**
* <p>
* The {@code path.separator} System Property. Path separator (<code>&quot;:&quot;</code> on UNIX).
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String PATH_SEPARATOR = getSystemProperty("path.separator");
/**
* <p>
* The {@code user.country} or {@code user.region} System Property. User's country code, such as {@code GB}. First
* in Java version 1.2 as {@code user.region}. Renamed to {@code user.country} in 1.4
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.2
*/
public static final String USER_COUNTRY = getSystemProperty("user.country") == null ?
getSystemProperty("user.region") : getSystemProperty("user.country");
/**
* <p>
* The {@code user.dir} System Property. User's current working directory.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String USER_DIR = getSystemProperty(USER_DIR_KEY);
/**
* <p>
* The {@code user.home} System Property. User's home directory.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String USER_HOME = getSystemProperty(USER_HOME_KEY);
/**
* <p>
* The {@code user.language} System Property. User's language code, such as {@code "en"}.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.0
* @since Java 1.2
*/
public static final String USER_LANGUAGE = getSystemProperty("user.language");
/**
* <p>
* The {@code user.name} System Property. User's account name.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since Java 1.1
*/
public static final String USER_NAME = getSystemProperty("user.name");
/**
* <p>
* The {@code user.timezone} System Property. For example: {@code "America/Los_Angeles"}.
* </p>
* <p>
* Defaults to {@code null} if the runtime does not have security access to read this property or the property does
* not exist.
* </p>
* <p>
* This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or
* {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of
* sync with that System property.
* </p>
*
* @since 2.1
*/
public static final String USER_TIMEZONE = getSystemProperty("user.timezone");
// Java version checks
// -----------------------------------------------------------------------
// These MUST be declared after those above as they depend on the
// values being set up
/**
* <p>
* Is {@code true} if this is Java version 1.1 (also 1.1.x versions).
* </p>
* <p>
* The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}.
* </p>
*/
public static final boolean IS_JAVA_1_1 = getJavaVersionMatches("1.1");
/**
* <p>
* Is {@code true} if this is Java version 1.2 (also 1.2.x versions).
* </p>
* <p>
* The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}.
* </p>
*/
public static final boolean IS_JAVA_1_2 = getJavaVersionMatches("1.2");
/**
* <p>
* Is {@code true} if this is Java version 1.3 (also 1.3.x versions).
* </p>
* <p>
* The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}.
* </p>
*/
public static final boolean IS_JAVA_1_3 = getJavaVersionMatches("1.3");
/**
* <p>
* Is {@code true} if this is Java version 1.4 (also 1.4.x versions).
* </p>
* <p>
* The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}.
* </p>
*/
public static final boolean IS_JAVA_1_4 = getJavaVersionMatches("1.4");
/**
* <p>
* Is {@code true} if this is Java version 1.5 (also 1.5.x versions).
* </p>
* <p>
* The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}.
* </p>
*/
public static final boolean IS_JAVA_1_5 = getJavaVersionMatches("1.5");
/**
* <p>
* Is {@code true} if this is Java version 1.6 (also 1.6.x versions).
* </p>
* <p>
* The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}.
* </p>
*/
public static final boolean IS_JAVA_1_6 = getJavaVersionMatches("1.6");
/**
* <p>
* Is {@code true} if this is Java version 1.7 (also 1.7.x versions).
* </p>
* <p>
* The field will return {@code false} if {@link #JAVA_VERSION} is {@code null}.
* </p>
*
* @since 3.0
*/
public static final boolean IS_JAVA_1_7 = getJavaVersionMatches("1.7");
// Operating system checks
// -----------------------------------------------------------------------
// These MUST be declared after those above as they depend on the
// values being set up
// OS names from http://www.vamphq.com/os.html
// Selected ones included - please advise dev@commons.apache.org
// if you want another added or a mistake corrected
/**
* <p>
* Is {@code true} if this is AIX.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_AIX = getOSMatchesName("AIX");
/**
* <p>
* Is {@code true} if this is HP-UX.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_HP_UX = getOSMatchesName("HP-UX");
/**
* <p>
* Is {@code true} if this is Irix.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_IRIX = getOSMatchesName("Irix");
/**
* <p>
* Is {@code true} if this is Linux.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_LINUX = getOSMatchesName("Linux") || getOSMatchesName("LINUX");
/**
* <p>
* Is {@code true} if this is Mac.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_MAC = getOSMatchesName("Mac");
/**
* <p>
* Is {@code true} if this is Mac.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_MAC_OSX = getOSMatchesName("Mac OS X");
/**
* <p>
* Is {@code true} if this is FreeBSD.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 3.1
*/
public static final boolean IS_OS_FREE_BSD = getOSMatchesName("FreeBSD");
/**
* <p>
* Is {@code true} if this is OpenBSD.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 3.1
*/
public static final boolean IS_OS_OPEN_BSD = getOSMatchesName("OpenBSD");
/**
* <p>
* Is {@code true} if this is NetBSD.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 3.1
*/
public static final boolean IS_OS_NET_BSD = getOSMatchesName("NetBSD");
/**
* <p>
* Is {@code true} if this is OS/2.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_OS2 = getOSMatchesName("OS/2");
/**
* <p>
* Is {@code true} if this is Solaris.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_SOLARIS = getOSMatchesName("Solaris");
/**
* <p>
* Is {@code true} if this is SunOS.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_SUN_OS = getOSMatchesName("SunOS");
/**
* <p>
* Is {@code true} if this is a UNIX like system, as in any of AIX, HP-UX, Irix, Linux, MacOSX, Solaris or SUN OS.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.1
*/
public static final boolean IS_OS_UNIX = IS_OS_AIX || IS_OS_HP_UX || IS_OS_IRIX || IS_OS_LINUX || IS_OS_MAC_OSX
|| IS_OS_SOLARIS || IS_OS_SUN_OS || IS_OS_FREE_BSD || IS_OS_OPEN_BSD || IS_OS_NET_BSD;
/**
* <p>
* Is {@code true} if this is Windows.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS = getOSMatchesName(OS_NAME_WINDOWS_PREFIX);
/**
* <p>
* Is {@code true} if this is Windows 2000.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_2000 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.0");
/**
* <p>
* Is {@code true} if this is Windows 2003.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 3.1
*/
public static final boolean IS_OS_WINDOWS_2003 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.2");
/**
* <p>
* Is {@code true} if this is Windows 2008.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 3.1
*/
public static final boolean IS_OS_WINDOWS_2008 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " Server 2008", "6.1");
/**
* <p>
* Is {@code true} if this is Windows 95.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_95 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.0");
// Java 1.2 running on Windows98 returns 'Windows 95', hence the above
/**
* <p>
* Is {@code true} if this is Windows 98.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_98 = getOSMatches(OS_NAME_WINDOWS_PREFIX + " 9", "4.1");
// Java 1.2 running on Windows98 returns 'Windows 95', hence the above
/**
* <p>
* Is {@code true} if this is Windows ME.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_ME = getOSMatches(OS_NAME_WINDOWS_PREFIX, "4.9");
// Java 1.2 running on WindowsME may return 'Windows 95', hence the above
/**
* <p>
* Is {@code true} if this is Windows NT.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_NT = getOSMatchesName(OS_NAME_WINDOWS_PREFIX + " NT");
// Windows 2000 returns 'Windows 2000' but may suffer from same Java1.2 problem
/**
* <p>
* Is {@code true} if this is Windows XP.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.0
*/
public static final boolean IS_OS_WINDOWS_XP = getOSMatches(OS_NAME_WINDOWS_PREFIX, "5.1");
// -----------------------------------------------------------------------
/**
* <p>
* Is {@code true} if this is Windows Vista.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 2.4
*/
public static final boolean IS_OS_WINDOWS_VISTA = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.0");
/**
* <p>
* Is {@code true} if this is Windows 7.
* </p>
* <p>
* The field will return {@code false} if {@code OS_NAME} is {@code null}.
* </p>
*
* @since 3.0
*/
public static final boolean IS_OS_WINDOWS_7 = getOSMatches(OS_NAME_WINDOWS_PREFIX, "6.1");
/**
* <p>
* Gets the Java home directory as a {@code File}.
* </p>
*
* @return a directory
* @throws SecurityException if a security manager exists and its {@code checkPropertyAccess} method doesn't allow
* access to the specified system property.
* @see System#getProperty(String)
* @since 2.1
*/
public static File getJavaHome() {
return new File(System.getProperty(JAVA_HOME_KEY));
}
/**
* <p>
* Gets the Java IO temporary directory as a {@code File}.
* </p>
*
* @return a directory
* @throws SecurityException if a security manager exists and its {@code checkPropertyAccess} method doesn't allow
* access to the specified system property.
* @see System#getProperty(String)
* @since 2.1
*/
public static File getJavaIoTmpDir() {
return new File(System.getProperty(JAVA_IO_TMPDIR_KEY));
}
/**
* <p>
* Decides if the Java version matches.
* </p>
*
* @param versionPrefix the prefix for the java version
* @return true if matches, or false if not or can't determine
*/
private static boolean getJavaVersionMatches(String versionPrefix) {
return isJavaVersionMatch(JAVA_SPECIFICATION_VERSION, versionPrefix);
}
/**
* Decides if the operating system matches.
*
* @param osNamePrefix the prefix for the os name
* @param osVersionPrefix the prefix for the version
* @return true if matches, or false if not or can't determine
*/
private static boolean getOSMatches(String osNamePrefix, String osVersionPrefix) {
return isOSMatch(OS_NAME, OS_VERSION, osNamePrefix, osVersionPrefix);
}
/**
* Decides if the operating system matches.
*
* @param osNamePrefix the prefix for the os name
* @return true if matches, or false if not or can't determine
*/
private static boolean getOSMatchesName(String osNamePrefix) {
return isOSNameMatch(OS_NAME, osNamePrefix);
}
// -----------------------------------------------------------------------
/**
* <p>
* Gets a System property, defaulting to {@code null} if the property cannot be read.
* </p>
* <p>
* If a {@code SecurityException} is caught, the return value is {@code null} and a message is written to
* {@code System.err}.
* </p>
*
* @param property the system property name
* @return the system property value or {@code null} if a security problem occurs
*/
private static String getSystemProperty(String property) {
try {
return System.getProperty(property);
} catch (SecurityException ex) {
// we are not allowed to look at this property
System.err.println("Caught a SecurityException reading the system property '" + property
+ "'; the SystemUtils property value will default to null.");
return null;
}
}
/**
* <p>
* Gets the user directory as a {@code File}.
* </p>
*
* @return a directory
* @throws SecurityException if a security manager exists and its {@code checkPropertyAccess} method doesn't allow
* access to the specified system property.
* @see System#getProperty(String)
* @since 2.1
*/
public static File getUserDir() {
return new File(System.getProperty(USER_DIR_KEY));
}
/**
* <p>
* Gets the user home directory as a {@code File}.
* </p>
*
* @return a directory
* @throws SecurityException if a security manager exists and its {@code checkPropertyAccess} method doesn't allow
* access to the specified system property.
* @see System#getProperty(String)
* @since 2.1
*/
public static File getUserHome() {
return new File(System.getProperty(USER_HOME_KEY));
}
/**
* Returns whether the {@link #JAVA_AWT_HEADLESS} value is {@code true}.
*
* @return {@code true} if {@code JAVA_AWT_HEADLESS} is {@code "true"}, {@code false} otherwise.
* @see #JAVA_AWT_HEADLESS
* @since 2.1
* @since Java 1.4
*/
public static boolean isJavaAwtHeadless() {
return JAVA_AWT_HEADLESS != null ? JAVA_AWT_HEADLESS.equals(Boolean.TRUE.toString()) : false;
}
/**
* <p>
* Is the Java version at least the requested version.
* </p>
* <p>
* Example input:
* </p>
* <ul>
* <li>{@code 1.2f} to test for Java 1.2</li>
* <li>{@code 1.31f} to test for Java 1.3.1</li>
* </ul>
*
* @param requiredVersion the required version, for example 1.31f
* @return {@code true} if the actual version is equal or greater than the required version
*/
public static boolean isJavaVersionAtLeast(JavaVersion requiredVersion) {
return JAVA_SPECIFICATION_VERSION_AS_ENUM.atLeast(requiredVersion);
}
/**
* <p>
* Decides if the Java version matches.
* </p>
* <p>
* This method is package private instead of private to support unit test invocation.
* </p>
*
* @param version the actual Java version
* @param versionPrefix the prefix for the expected Java version
* @return true if matches, or false if not or can't determine
*/
static boolean isJavaVersionMatch(String version, String versionPrefix) {
if (version == null) {
return false;
}
return version.startsWith(versionPrefix);
}
/**
* Decides if the operating system matches.
* <p>
* This method is package private instead of private to support unit test invocation.
* </p>
*
* @param osName the actual OS name
* @param osVersion the actual OS version
* @param osNamePrefix the prefix for the expected OS name
* @param osVersionPrefix the prefix for the expected OS version
* @return true if matches, or false if not or can't determine
*/
static boolean isOSMatch(String osName, String osVersion, String osNamePrefix, String osVersionPrefix) {
if (osName == null || osVersion == null) {
return false;
}
return osName.startsWith(osNamePrefix) && osVersion.startsWith(osVersionPrefix);
}
/**
* Decides if the operating system matches.
* <p>
* This method is package private instead of private to support unit test invocation.
* </p>
*
* @param osName the actual OS name
* @param osNamePrefix the prefix for the expected OS name
* @return true if matches, or false if not or can't determine
*/
static boolean isOSNameMatch(String osName, String osNamePrefix) {
if (osName == null) {
return false;
}
return osName.startsWith(osNamePrefix);
}
// -----------------------------------------------------------------------
/**
* <p>
* SystemUtils instances should NOT be constructed in standard programming. Instead, the class should be used as
* {@code SystemUtils.FILE_SEPARATOR}.
* </p>
* <p>
* This constructor is public to permit tools that require a JavaBean instance to operate.
* </p>
*/
public SystemUtils() {
super();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
/**
* <p>This class assists in validating arguments. The validation methods are
* based along the following principles:
* <ul>
* <li>An invalid {@code null} argument causes a {@link NullPointerException}.</li>
* <li>A non-{@code null} argument causes an {@link IllegalArgumentException}.</li>
* <li>An invalid index into an array/collection/map/string causes an {@link IndexOutOfBoundsException}.</li>
* </ul>
*
* <p>All exceptions messages are
* <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax">format strings</a>
* as defined by the Java platform. For example:</p>
*
* <pre>
* Validate.isTrue(i > 0, "The value must be greater than zero: %d", i);
* Validate.notNull(surname, "The surname must not be %s", null);
* </pre>
*
* <p>#ThreadSafe#</p>
* @version $Id: Validate.java 1199983 2011-11-09 21:41:24Z ggregory $
* @see String#format(String, Object...)
* @since 2.0
*/
public class Validate {
private static final String DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE =
"The value %s is not in the specified exclusive range of %s to %s";
private static final String DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE =
"The value %s is not in the specified inclusive range of %s to %s";
private static final String DEFAULT_MATCHES_PATTERN_EX = "The string %s does not match the pattern %s";
private static final String DEFAULT_IS_NULL_EX_MESSAGE = "The validated object is null";
private static final String DEFAULT_IS_TRUE_EX_MESSAGE = "The validated expression is false";
private static final String DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE =
"The validated array contains null element at index: %d";
private static final String DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE =
"The validated collection contains null element at index: %d";
private static final String DEFAULT_NOT_BLANK_EX_MESSAGE = "The validated character sequence is blank";
private static final String DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE = "The validated array is empty";
private static final String DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE =
"The validated character sequence is empty";
private static final String DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE = "The validated collection is empty";
private static final String DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE = "The validated map is empty";
private static final String DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE = "The validated array index is invalid: %d";
private static final String DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE =
"The validated character sequence index is invalid: %d";
private static final String DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE =
"The validated collection index is invalid: %d";
private static final String DEFAULT_VALID_STATE_EX_MESSAGE = "The validated state is false";
private static final String DEFAULT_IS_ASSIGNABLE_EX_MESSAGE = "Cannot assign a %s to a %s";
private static final String DEFAULT_IS_INSTANCE_OF_EX_MESSAGE = "Expected type: %s, actual: %s";
/**
* Constructor. This class should not normally be instantiated.
*/
public Validate() {
super();
}
// isTrue
//---------------------------------------------------------------------------------
/**
* <p>Validate that the argument condition is {@code true}; otherwise
* throwing an exception with the specified message. This method is useful when
* validating according to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.</p>
*
* <pre>Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);</pre>
*
* <p>For performance reasons, the long value is passed as a separate parameter and
* appended to the exception message only in the case of an error.</p>
*
* @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param value the value to append to the message when invalid
* @throws IllegalArgumentException if expression is {@code false}
* @see #isTrue(boolean)
* @see #isTrue(boolean, String, double)
* @see #isTrue(boolean, String, Object...)
*/
public static void isTrue(boolean expression, String message, long value) {
if (expression == false) {
throw new IllegalArgumentException(String.format(message, Long.valueOf(value)));
}
}
/**
* <p>Validate that the argument condition is {@code true}; otherwise
* throwing an exception with the specified message. This method is useful when
* validating according to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.</p>
*
* <pre>Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);</pre>
*
* <p>For performance reasons, the double value is passed as a separate parameter and
* appended to the exception message only in the case of an error.</p>
*
* @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param value the value to append to the message when invalid
* @throws IllegalArgumentException if expression is {@code false}
* @see #isTrue(boolean)
* @see #isTrue(boolean, String, long)
* @see #isTrue(boolean, String, Object...)
*/
public static void isTrue(boolean expression, String message, double value) {
if (expression == false) {
throw new IllegalArgumentException(String.format(message, Double.valueOf(value)));
}
}
/**
* <p>Validate that the argument condition is {@code true}; otherwise
* throwing an exception with the specified message. This method is useful when
* validating according to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.</p>
*
* <pre>
* Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max);
* Validate.isTrue(myObject.isOk(), "The object is not okay");</pre>
*
* @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @throws IllegalArgumentException if expression is {@code false}
* @see #isTrue(boolean)
* @see #isTrue(boolean, String, long)
* @see #isTrue(boolean, String, double)
*/
public static void isTrue(boolean expression, String message, Object... values) {
if (expression == false) {
throw new IllegalArgumentException(String.format(message, values));
}
}
/**
* <p>Validate that the argument condition is {@code true}; otherwise
* throwing an exception. This method is useful when validating according
* to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.</p>
*
* <pre>
* Validate.isTrue(i > 0);
* Validate.isTrue(myObject.isOk());</pre>
*
* <p>The message of the exception is &quot;The validated expression is
* false&quot;.</p>
*
* @param expression the boolean expression to check
* @throws IllegalArgumentException if expression is {@code false}
* @see #isTrue(boolean, String, long)
* @see #isTrue(boolean, String, double)
* @see #isTrue(boolean, String, Object...)
*/
public static void isTrue(boolean expression) {
if (expression == false) {
throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE);
}
}
// notNull
//---------------------------------------------------------------------------------
/**
* <p>Validate that the specified argument is not {@code null};
* otherwise throwing an exception.
*
* <pre>Validate.notNull(myObject, "The object must not be null");</pre>
*
* <p>The message of the exception is &quot;The validated object is
* null&quot;.</p>
*
* @param <T> the object type
* @param object the object to check
* @return the validated object (never {@code null} for method chaining)
* @throws NullPointerException if the object is {@code null}
* @see #notNull(Object, String, Object...)
*/
public static <T> T notNull(T object) {
return notNull(object, DEFAULT_IS_NULL_EX_MESSAGE);
}
/**
* <p>Validate that the specified argument is not {@code null};
* otherwise throwing an exception with the specified message.
*
* <pre>Validate.notNull(myObject, "The object must not be null");</pre>
*
* @param <T> the object type
* @param object the object to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message
* @return the validated object (never {@code null} for method chaining)
* @throws NullPointerException if the object is {@code null}
* @see #notNull(Object)
*/
public static <T> T notNull(T object, String message, Object... values) {
if (object == null) {
throw new NullPointerException(String.format(message, values));
}
return object;
}
// notEmpty array
//---------------------------------------------------------------------------------
/**
* <p>Validate that the specified argument array is neither {@code null}
* nor a length of zero (no elements); otherwise throwing an exception
* with the specified message.
*
* <pre>Validate.notEmpty(myArray, "The array must not be empty");</pre>
*
* @param <T> the array type
* @param array the array to check, validated not null by this method
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @return the validated array (never {@code null} method for chaining)
* @throws NullPointerException if the array is {@code null}
* @throws IllegalArgumentException if the array is empty
* @see #notEmpty(Object[])
*/
public static <T> T[] notEmpty(T[] array, String message, Object... values) {
if (array == null) {
throw new NullPointerException(String.format(message, values));
}
if (array.length == 0) {
throw new IllegalArgumentException(String.format(message, values));
}
return array;
}
/**
* <p>Validate that the specified argument array is neither {@code null}
* nor a length of zero (no elements); otherwise throwing an exception.
*
* <pre>Validate.notEmpty(myArray);</pre>
*
* <p>The message in the exception is &quot;The validated array is
* empty&quot;.
*
* @param <T> the array type
* @param array the array to check, validated not null by this method
* @return the validated array (never {@code null} method for chaining)
* @throws NullPointerException if the array is {@code null}
* @throws IllegalArgumentException if the array is empty
* @see #notEmpty(Object[], String, Object...)
*/
public static <T> T[] notEmpty(T[] array) {
return notEmpty(array, DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE);
}
// notEmpty collection
//---------------------------------------------------------------------------------
/**
* <p>Validate that the specified argument collection is neither {@code null}
* nor a size of zero (no elements); otherwise throwing an exception
* with the specified message.
*
* <pre>Validate.notEmpty(myCollection, "The collection must not be empty");</pre>
*
* @param <T> the collection type
* @param collection the collection to check, validated not null by this method
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @return the validated collection (never {@code null} method for chaining)
* @throws NullPointerException if the collection is {@code null}
* @throws IllegalArgumentException if the collection is empty
* @see #notEmpty(Object[])
*/
public static <T extends Collection<?>> T notEmpty(T collection, String message, Object... values) {
if (collection == null) {
throw new NullPointerException(String.format(message, values));
}
if (collection.isEmpty()) {
throw new IllegalArgumentException(String.format(message, values));
}
return collection;
}
/**
* <p>Validate that the specified argument collection is neither {@code null}
* nor a size of zero (no elements); otherwise throwing an exception.
*
* <pre>Validate.notEmpty(myCollection);</pre>
*
* <p>The message in the exception is &quot;The validated collection is
* empty&quot;.</p>
*
* @param <T> the collection type
* @param collection the collection to check, validated not null by this method
* @return the validated collection (never {@code null} method for chaining)
* @throws NullPointerException if the collection is {@code null}
* @throws IllegalArgumentException if the collection is empty
* @see #notEmpty(Collection, String, Object...)
*/
public static <T extends Collection<?>> T notEmpty(T collection) {
return notEmpty(collection, DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE);
}
// notEmpty map
//---------------------------------------------------------------------------------
/**
* <p>Validate that the specified argument map is neither {@code null}
* nor a size of zero (no elements); otherwise throwing an exception
* with the specified message.
*
* <pre>Validate.notEmpty(myMap, "The map must not be empty");</pre>
*
* @param <T> the map type
* @param map the map to check, validated not null by this method
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @return the validated map (never {@code null} method for chaining)
* @throws NullPointerException if the map is {@code null}
* @throws IllegalArgumentException if the map is empty
* @see #notEmpty(Object[])
*/
public static <T extends Map<?, ?>> T notEmpty(T map, String message, Object... values) {
if (map == null) {
throw new NullPointerException(String.format(message, values));
}
if (map.isEmpty()) {
throw new IllegalArgumentException(String.format(message, values));
}
return map;
}
/**
* <p>Validate that the specified argument map is neither {@code null}
* nor a size of zero (no elements); otherwise throwing an exception.
*
* <pre>Validate.notEmpty(myMap);</pre>
*
* <p>The message in the exception is &quot;The validated map is
* empty&quot;.</p>
*
* @param <T> the map type
* @param map the map to check, validated not null by this method
* @return the validated map (never {@code null} method for chaining)
* @throws NullPointerException if the map is {@code null}
* @throws IllegalArgumentException if the map is empty
* @see #notEmpty(Map, String, Object...)
*/
public static <T extends Map<?, ?>> T notEmpty(T map) {
return notEmpty(map, DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE);
}
// notEmpty string
//---------------------------------------------------------------------------------
/**
* <p>Validate that the specified argument character sequence is
* neither {@code null} nor a length of zero (no characters);
* otherwise throwing an exception with the specified message.
*
* <pre>Validate.notEmpty(myString, "The string must not be empty");</pre>
*
* @param <T> the character sequence type
* @param chars the character sequence to check, validated not null by this method
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @return the validated character sequence (never {@code null} method for chaining)
* @throws NullPointerException if the character sequence is {@code null}
* @throws IllegalArgumentException if the character sequence is empty
* @see #notEmpty(CharSequence)
*/
public static <T extends CharSequence> T notEmpty(T chars, String message, Object... values) {
if (chars == null) {
throw new NullPointerException(String.format(message, values));
}
if (chars.length() == 0) {
throw new IllegalArgumentException(String.format(message, values));
}
return chars;
}
/**
* <p>Validate that the specified argument character sequence is
* neither {@code null} nor a length of zero (no characters);
* otherwise throwing an exception with the specified message.
*
* <pre>Validate.notEmpty(myString);</pre>
*
* <p>The message in the exception is &quot;The validated
* character sequence is empty&quot;.</p>
*
* @param <T> the character sequence type
* @param chars the character sequence to check, validated not null by this method
* @return the validated character sequence (never {@code null} method for chaining)
* @throws NullPointerException if the character sequence is {@code null}
* @throws IllegalArgumentException if the character sequence is empty
* @see #notEmpty(CharSequence, String, Object...)
*/
public static <T extends CharSequence> T notEmpty(T chars) {
return notEmpty(chars, DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE);
}
// notBlank string
//---------------------------------------------------------------------------------
/**
* <p>Validate that the specified argument character sequence is
* neither {@code null}, a length of zero (no characters), empty
* nor whitespace; otherwise throwing an exception with the specified
* message.
*
* <pre>Validate.notBlank(myString, "The string must not be blank");</pre>
*
* @param <T> the character sequence type
* @param chars the character sequence to check, validated not null by this method
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @return the validated character sequence (never {@code null} method for chaining)
* @throws NullPointerException if the character sequence is {@code null}
* @throws IllegalArgumentException if the character sequence is blank
* @see #notBlank(CharSequence)
*
* @since 3.0
*/
public static <T extends CharSequence> T notBlank(T chars, String message, Object... values) {
if (chars == null) {
throw new NullPointerException(String.format(message, values));
}
if (StringUtils.isBlank(chars)) {
throw new IllegalArgumentException(String.format(message, values));
}
return chars;
}
/**
* <p>Validate that the specified argument character sequence is
* neither {@code null}, a length of zero (no characters), empty
* nor whitespace; otherwise throwing an exception.
*
* <pre>Validate.notBlank(myString);</pre>
*
* <p>The message in the exception is &quot;The validated character
* sequence is blank&quot;.</p>
*
* @param <T> the character sequence type
* @param chars the character sequence to check, validated not null by this method
* @return the validated character sequence (never {@code null} method for chaining)
* @throws NullPointerException if the character sequence is {@code null}
* @throws IllegalArgumentException if the character sequence is blank
* @see #notBlank(CharSequence, String, Object...)
*
* @since 3.0
*/
public static <T extends CharSequence> T notBlank(T chars) {
return notBlank(chars, DEFAULT_NOT_BLANK_EX_MESSAGE);
}
// noNullElements array
//---------------------------------------------------------------------------------
/**
* <p>Validate that the specified argument array is neither
* {@code null} nor contains any elements that are {@code null};
* otherwise throwing an exception with the specified message.
*
* <pre>Validate.noNullElements(myArray, "The array contain null at position %d");</pre>
*
* <p>If the array is {@code null}, then the message in the exception
* is &quot;The validated object is null&quot;.</p>
*
* <p>If the array has a {@code null} element, then the iteration
* index of the invalid element is appended to the {@code values}
* argument.</p>
*
* @param <T> the array type
* @param array the array to check, validated not null by this method
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @return the validated array (never {@code null} method for chaining)
* @throws NullPointerException if the array is {@code null}
* @throws IllegalArgumentException if an element is {@code null}
* @see #noNullElements(Object[])
*/
public static <T> T[] noNullElements(T[] array, String message, Object... values) {
Validate.notNull(array);
for (int i = 0; i < array.length; i++) {
if (array[i] == null) {
Object[] values2 = ArrayUtils.add(values, Integer.valueOf(i));
throw new IllegalArgumentException(String.format(message, values2));
}
}
return array;
}
/**
* <p>Validate that the specified argument array is neither
* {@code null} nor contains any elements that are {@code null};
* otherwise throwing an exception.
*
* <pre>Validate.noNullElements(myArray);</pre>
*
* <p>If the array is {@code null}, then the message in the exception
* is &quot;The validated object is null&quot;.</p>
*
* <p>If the array has a {@code null} element, then the message in the
* exception is &quot;The validated array contains null element at index:
* &quot followed by the index.</p>
*
* @param <T> the array type
* @param array the array to check, validated not null by this method
* @return the validated array (never {@code null} method for chaining)
* @throws NullPointerException if the array is {@code null}
* @throws IllegalArgumentException if an element is {@code null}
* @see #noNullElements(Object[], String, Object...)
*/
public static <T> T[] noNullElements(T[] array) {
return noNullElements(array, DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE);
}
// noNullElements iterable
//---------------------------------------------------------------------------------
/**
* <p>Validate that the specified argument iterable is neither
* {@code null} nor contains any elements that are {@code null};
* otherwise throwing an exception with the specified message.
*
* <pre>Validate.noNullElements(myCollection, "The collection contains null at position %d");</pre>
*
* <p>If the iterable is {@code null}, then the message in the exception
* is &quot;The validated object is null&quot;.</p>
*
* <p>If the iterable has a {@code null} element, then the iteration
* index of the invalid element is appended to the {@code values}
* argument.</p>
*
* @param <T> the iterable type
* @param iterable the iterable to check, validated not null by this method
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @return the validated iterable (never {@code null} method for chaining)
* @throws NullPointerException if the array is {@code null}
* @throws IllegalArgumentException if an element is {@code null}
* @see #noNullElements(Iterable)
*/
public static <T extends Iterable<?>> T noNullElements(T iterable, String message, Object... values) {
Validate.notNull(iterable);
int i = 0;
for (Iterator<?> it = iterable.iterator(); it.hasNext(); i++) {
if (it.next() == null) {
Object[] values2 = ArrayUtils.addAll(values, Integer.valueOf(i));
throw new IllegalArgumentException(String.format(message, values2));
}
}
return iterable;
}
/**
* <p>Validate that the specified argument iterable is neither
* {@code null} nor contains any elements that are {@code null};
* otherwise throwing an exception.
*
* <pre>Validate.noNullElements(myCollection);</pre>
*
* <p>If the iterable is {@code null}, then the message in the exception
* is &quot;The validated object is null&quot;.</p>
*
* <p>If the array has a {@code null} element, then the message in the
* exception is &quot;The validated iterable contains null element at index:
* &quot followed by the index.</p>
*
* @param <T> the iterable type
* @param iterable the iterable to check, validated not null by this method
* @return the validated iterable (never {@code null} method for chaining)
* @throws NullPointerException if the array is {@code null}
* @throws IllegalArgumentException if an element is {@code null}
* @see #noNullElements(Iterable, String, Object...)
*/
public static <T extends Iterable<?>> T noNullElements(T iterable) {
return noNullElements(iterable, DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE);
}
// validIndex array
//---------------------------------------------------------------------------------
/**
* <p>Validates that the index is within the bounds of the argument
* array; otherwise throwing an exception with the specified message.</p>
*
* <pre>Validate.validIndex(myArray, 2, "The array index is invalid: ");</pre>
*
* <p>If the array is {@code null}, then the message of the exception
* is &quot;The validated object is null&quot;.</p>
*
* @param <T> the array type
* @param array the array to check, validated not null by this method
* @param index the index to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @return the validated array (never {@code null} for method chaining)
* @throws NullPointerException if the array is {@code null}
* @throws IndexOutOfBoundsException if the index is invalid
* @see #validIndex(Object[], int)
*
* @since 3.0
*/
public static <T> T[] validIndex(T[] array, int index, String message, Object... values) {
Validate.notNull(array);
if (index < 0 || index >= array.length) {
throw new IndexOutOfBoundsException(String.format(message, values));
}
return array;
}
/**
* <p>Validates that the index is within the bounds of the argument
* array; otherwise throwing an exception.</p>
*
* <pre>Validate.validIndex(myArray, 2);</pre>
*
* <p>If the array is {@code null}, then the message of the exception
* is &quot;The validated object is null&quot;.</p>
*
* <p>If the index is invalid, then the message of the exception is
* &quot;The validated array index is invalid: &quot; followed by the
* index.</p>
*
* @param <T> the array type
* @param array the array to check, validated not null by this method
* @param index the index to check
* @return the validated array (never {@code null} for method chaining)
* @throws NullPointerException if the array is {@code null}
* @throws IndexOutOfBoundsException if the index is invalid
* @see #validIndex(Object[], int, String, Object...)
*
* @since 3.0
*/
public static <T> T[] validIndex(T[] array, int index) {
return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index));
}
// validIndex collection
//---------------------------------------------------------------------------------
/**
* <p>Validates that the index is within the bounds of the argument
* collection; otherwise throwing an exception with the specified message.</p>
*
* <pre>Validate.validIndex(myCollection, 2, "The collection index is invalid: ");</pre>
*
* <p>If the collection is {@code null}, then the message of the
* exception is &quot;The validated object is null&quot;.</p>
*
* @param <T> the collection type
* @param collection the collection to check, validated not null by this method
* @param index the index to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @return the validated collection (never {@code null} for chaining)
* @throws NullPointerException if the collection is {@code null}
* @throws IndexOutOfBoundsException if the index is invalid
* @see #validIndex(Collection, int)
*
* @since 3.0
*/
public static <T extends Collection<?>> T validIndex(T collection, int index, String message, Object... values) {
Validate.notNull(collection);
if (index < 0 || index >= collection.size()) {
throw new IndexOutOfBoundsException(String.format(message, values));
}
return collection;
}
/**
* <p>Validates that the index is within the bounds of the argument
* collection; otherwise throwing an exception.</p>
*
* <pre>Validate.validIndex(myCollection, 2);</pre>
*
* <p>If the index is invalid, then the message of the exception
* is &quot;The validated collection index is invalid: &quot;
* followed by the index.</p>
*
* @param <T> the collection type
* @param collection the collection to check, validated not null by this method
* @param index the index to check
* @return the validated collection (never {@code null} for method chaining)
* @throws NullPointerException if the collection is {@code null}
* @throws IndexOutOfBoundsException if the index is invalid
* @see #validIndex(Collection, int, String, Object...)
*
* @since 3.0
*/
public static <T extends Collection<?>> T validIndex(T collection, int index) {
return validIndex(collection, index, DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE, Integer.valueOf(index));
}
// validIndex string
//---------------------------------------------------------------------------------
/**
* <p>Validates that the index is within the bounds of the argument
* character sequence; otherwise throwing an exception with the
* specified message.</p>
*
* <pre>Validate.validIndex(myStr, 2, "The string index is invalid: ");</pre>
*
* <p>If the character sequence is {@code null}, then the message
* of the exception is &quot;The validated object is null&quot;.</p>
*
* @param <T> the character sequence type
* @param chars the character sequence to check, validated not null by this method
* @param index the index to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @return the validated character sequence (never {@code null} for method chaining)
* @throws NullPointerException if the character sequence is {@code null}
* @throws IndexOutOfBoundsException if the index is invalid
* @see #validIndex(CharSequence, int)
*
* @since 3.0
*/
public static <T extends CharSequence> T validIndex(T chars, int index, String message, Object... values) {
Validate.notNull(chars);
if (index < 0 || index >= chars.length()) {
throw new IndexOutOfBoundsException(String.format(message, values));
}
return chars;
}
/**
* <p>Validates that the index is within the bounds of the argument
* character sequence; otherwise throwing an exception.</p>
*
* <pre>Validate.validIndex(myStr, 2);</pre>
*
* <p>If the character sequence is {@code null}, then the message
* of the exception is &quot;The validated object is
* null&quot;.</p>
*
* <p>If the index is invalid, then the message of the exception
* is &quot;The validated character sequence index is invalid: &quot;
* followed by the index.</p>
*
* @param <T> the character sequence type
* @param chars the character sequence to check, validated not null by this method
* @param index the index to check
* @return the validated character sequence (never {@code null} for method chaining)
* @throws NullPointerException if the character sequence is {@code null}
* @throws IndexOutOfBoundsException if the index is invalid
* @see #validIndex(CharSequence, int, String, Object...)
*
* @since 3.0
*/
public static <T extends CharSequence> T validIndex(T chars, int index) {
return validIndex(chars, index, DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE, Integer.valueOf(index));
}
// validState
//---------------------------------------------------------------------------------
/**
* <p>Validate that the stateful condition is {@code true}; otherwise
* throwing an exception. This method is useful when validating according
* to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.</p>
*
* <pre>
* Validate.validState(field > 0);
* Validate.validState(this.isOk());</pre>
*
* <p>The message of the exception is &quot;The validated state is
* false&quot;.</p>
*
* @param expression the boolean expression to check
* @throws IllegalStateException if expression is {@code false}
* @see #validState(boolean, String, Object...)
*
* @since 3.0
*/
public static void validState(boolean expression) {
if (expression == false) {
throw new IllegalStateException(DEFAULT_VALID_STATE_EX_MESSAGE);
}
}
/**
* <p>Validate that the stateful condition is {@code true}; otherwise
* throwing an exception with the specified message. This method is useful when
* validating according to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.</p>
*
* <pre>Validate.validState(this.isOk(), "The state is not OK: %s", myObject);</pre>
*
* @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @throws IllegalStateException if expression is {@code false}
* @see #validState(boolean)
*
* @since 3.0
*/
public static void validState(boolean expression, String message, Object... values) {
if (expression == false) {
throw new IllegalStateException(String.format(message, values));
}
}
// matchesPattern
//---------------------------------------------------------------------------------
/**
* <p>Validate that the specified argument character sequence matches the specified regular
* expression pattern; otherwise throwing an exception.</p>
*
* <pre>Validate.matchesPattern("hi", "[a-z]*");</pre>
*
* <p>The syntax of the pattern is the one used in the {@link Pattern} class.</p>
*
* @param input the character sequence to validate, not null
* @param pattern the regular expression pattern, not null
* @throws IllegalArgumentException if the character sequence does not match the pattern
* @see #matchesPattern(CharSequence, String, String, Object...)
*
* @since 3.0
*/
public static void matchesPattern(CharSequence input, String pattern) {
if (Pattern.matches(pattern, input) == false) {
throw new IllegalArgumentException(String.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern));
}
}
/**
* <p>Validate that the specified argument character sequence matches the specified regular
* expression pattern; otherwise throwing an exception with the specified message.</p>
*
* <pre>Validate.matchesPattern("hi", "[a-z]*", "%s does not match %s", "hi" "[a-z]*");</pre>
*
* <p>The syntax of the pattern is the one used in the {@link Pattern} class.</p>
*
* @param input the character sequence to validate, not null
* @param pattern the regular expression pattern, not null
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @throws IllegalArgumentException if the character sequence does not match the pattern
* @see #matchesPattern(CharSequence, String)
*
* @since 3.0
*/
public static void matchesPattern(CharSequence input, String pattern, String message, Object... values) {
if (Pattern.matches(pattern, input) == false) {
throw new IllegalArgumentException(String.format(message, values));
}
}
// inclusiveBetween
//---------------------------------------------------------------------------------
/**
* <p>Validate that the specified argument object fall between the two
* inclusive values specified; otherwise, throws an exception.</p>
*
* <pre>Validate.inclusiveBetween(0, 2, 1);</pre>
*
* @param <T> the type of the argument object
* @param start the inclusive start value, not null
* @param end the inclusive end value, not null
* @param value the object to validate, not null
* @throws IllegalArgumentException if the value falls out of the boundaries
* @see #inclusiveBetween(Object, Object, Comparable, String, Object...)
*
* @since 3.0
*/
public static <T> void inclusiveBetween(T start, T end, Comparable<T> value) {
if (value.compareTo(start) < 0 || value.compareTo(end) > 0) {
throw new IllegalArgumentException(String.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
}
}
/**
* <p>Validate that the specified argument object fall between the two
* inclusive values specified; otherwise, throws an exception with the
* specified message.</p>
*
* <pre>Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");</pre>
*
* @param <T> the type of the argument object
* @param start the inclusive start value, not null
* @param end the inclusive end value, not null
* @param value the object to validate, not null
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @throws IllegalArgumentException if the value falls out of the boundaries
* @see #inclusiveBetween(Object, Object, Comparable)
*
* @since 3.0
*/
public static <T> void inclusiveBetween(T start, T end, Comparable<T> value, String message, Object... values) {
if (value.compareTo(start) < 0 || value.compareTo(end) > 0) {
throw new IllegalArgumentException(String.format(message, values));
}
}
// exclusiveBetween
//---------------------------------------------------------------------------------
/**
* <p>Validate that the specified argument object fall between the two
* exclusive values specified; otherwise, throws an exception.</p>
*
* <pre>Validate.inclusiveBetween(0, 2, 1);</pre>
*
* @param <T> the type of the argument object
* @param start the exclusive start value, not null
* @param end the exclusive end value, not null
* @param value the object to validate, not null
* @throws IllegalArgumentException if the value falls out of the boundaries
* @see #exclusiveBetween(Object, Object, Comparable, String, Object...)
*
* @since 3.0
*/
public static <T> void exclusiveBetween(T start, T end, Comparable<T> value) {
if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
throw new IllegalArgumentException(String.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end));
}
}
/**
* <p>Validate that the specified argument object fall between the two
* exclusive values specified; otherwise, throws an exception with the
* specified message.</p>
*
* <pre>Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");</pre>
*
* @param <T> the type of the argument object
* @param start the exclusive start value, not null
* @param end the exclusive end value, not null
* @param value the object to validate, not null
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @throws IllegalArgumentException if the value falls out of the boundaries
* @see #exclusiveBetween(Object, Object, Comparable)
*
* @since 3.0
*/
public static <T> void exclusiveBetween(T start, T end, Comparable<T> value, String message, Object... values) {
if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) {
throw new IllegalArgumentException(String.format(message, values));
}
}
// isInstanceOf
//---------------------------------------------------------------------------------
/**
* Validates that the argument is an instance of the specified class, if not throws an exception.
*
* <p>This method is useful when validating according to an arbitrary class</p>
*
* <pre>Validate.isInstanceOf(OkClass.class, object);</pre>
*
* <p>The message of the exception is &quot;Expected type: {type}, actual: {obj_type}&quot;</p>
*
* @param type the class the object must be validated against, not null
* @param obj the object to check, null throws an exception
* @throws IllegalArgumentException if argument is not of specified class
* @see #isInstanceOf(Class, Object, String, Object...)
*
* @since 3.0
*/
public static void isInstanceOf(Class<?> type, Object obj) {
if (type.isInstance(obj) == false) {
throw new IllegalArgumentException(String.format(DEFAULT_IS_INSTANCE_OF_EX_MESSAGE, type.getName(),
obj == null ? "null" : obj.getClass().getName()));
}
}
/**
* <p>Validate that the argument is an instance of the specified class; otherwise
* throwing an exception with the specified message. This method is useful when
* validating according to an arbitrary class</p>
*
* <pre>Validate.isInstanceOf(OkClass.classs, object, "Wrong class, object is of class %s",
* object.getClass().getName());</pre>
*
* @param type the class the object must be validated against, not null
* @param obj the object to check, null throws an exception
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @throws IllegalArgumentException if argument is not of specified class
* @see #isInstanceOf(Class, Object)
*
* @since 3.0
*/
public static void isInstanceOf(Class<?> type, Object obj, String message, Object... values) {
if (type.isInstance(obj) == false) {
throw new IllegalArgumentException(String.format(message, values));
}
}
// isAssignableFrom
//---------------------------------------------------------------------------------
/**
* Validates that the argument can be converted to the specified class, if not, throws an exception.
*
* <p>This method is useful when validating that there will be no casting errors.</p>
*
* <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre>
*
* <p>The message format of the exception is &quot;Cannot assign {type} to {superType}&quot;</p>
*
* @param superType the class the class must be validated against, not null
* @param type the class to check, not null
* @throws IllegalArgumentException if type argument is not assignable to the specified superType
* @see #isAssignableFrom(Class, Class, String, Object...)
*
* @since 3.0
*/
public static void isAssignableFrom(Class<?> superType, Class<?> type) {
if (superType.isAssignableFrom(type) == false) {
throw new IllegalArgumentException(String.format(DEFAULT_IS_ASSIGNABLE_EX_MESSAGE, type == null ? "null" : type.getName(),
superType.getName()));
}
}
/**
* Validates that the argument can be converted to the specified class, if not throws an exception.
*
* <p>This method is useful when validating if there will be no casting errors.</p>
*
* <pre>Validate.isAssignableFrom(SuperClass.class, object.getClass());</pre>
*
* <p>The message of the exception is &quot;The validated object can not be converted to the&quot;
* followed by the name of the class and &quot;class&quot;</p>
*
* @param superType the class the class must be validated against, not null
* @param type the class to check, not null
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @throws IllegalArgumentException if argument can not be converted to the specified class
* @see #isAssignableFrom(Class, Class)
*/
public static void isAssignableFrom(Class<?> superType, Class<?> type, String message, Object... values) {
if (superType.isAssignableFrom(type) == false) {
throw new IllegalArgumentException(String.format(message, values));
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.builder;
/**
* <p>
* The Builder interface is designed to designate a class as a <em>builder</em>
* object in the Builder design pattern. Builders are capable of creating and
* configuring objects or results that normally take multiple steps to construct
* or are very complex to derive.
* </p>
*
* <p>
* The builder interface defines a single method, {@link #build()}, that
* classes must implement. The result of this method should be the final
* configured object or result after all building operations are performed.
* </p>
*
* <p>
* It is a recommended practice that the methods supplied to configure the
* object or result being built return a reference to {@code this} so that
* method calls can be chained together.
* </p>
*
* <p>
* Example Builder:
* <code><pre>
* class FontBuilder implements Builder&lt;Font&gt; {
* private Font font;
*
* public FontBuilder(String fontName) {
* this.font = new Font(fontName, Font.PLAIN, 12);
* }
*
* public FontBuilder bold() {
* this.font = this.font.deriveFont(Font.BOLD);
* return this; // Reference returned so calls can be chained
* }
*
* public FontBuilder size(float pointSize) {
* this.font = this.font.deriveFont(pointSize);
* return this; // Reference returned so calls can be chained
* }
*
* // Other Font construction methods
*
* public Font build() {
* return this.font;
* }
* }
* </pre></code>
*
* Example Builder Usage:
* <code><pre>
* Font bold14ptSansSerifFont = new FontBuilder(Font.SANS_SERIF).bold()
* .size(14.0f)
* .build();
* </pre></code>
* </p>
*
* @param <T> the type of object that the builder will construct or compute.
*
* @since 3.0
* @version $Id: Builder.java 1088899 2011-04-05 05:31:27Z bayard $
*/
public interface Builder<T> {
/**
* Returns a reference to the object being constructed or result being
* calculated by the builder.
*
* @return the object constructed or result calculated by the builder.
*/
public T build();
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.builder;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Comparator;
import external.org.apache.commons.lang3.ArrayUtils;
/**
* Assists in implementing {@link Comparable#compareTo(Object)} methods.
*
* It is consistent with <code>equals(Object)</code> and
* <code>hashcode()</code> built with {@link EqualsBuilder} and
* {@link HashCodeBuilder}.</p>
*
* <p>Two Objects that compare equal using <code>equals(Object)</code> should normally
* also compare equal using <code>compareTo(Object)</code>.</p>
*
* <p>All relevant fields should be included in the calculation of the
* comparison. Derived fields may be ignored. The same fields, in the same
* order, should be used in both <code>compareTo(Object)</code> and
* <code>equals(Object)</code>.</p>
*
* <p>To use this class write code as follows:</p>
*
* <pre>
* public class MyClass {
* String field1;
* int field2;
* boolean field3;
*
* ...
*
* public int compareTo(Object o) {
* MyClass myClass = (MyClass) o;
* return new CompareToBuilder()
* .appendSuper(super.compareTo(o)
* .append(this.field1, myClass.field1)
* .append(this.field2, myClass.field2)
* .append(this.field3, myClass.field3)
* .toComparison();
* }
* }
* </pre>
*
* <p>Alternatively, there are {@link #reflectionCompare(Object, Object) reflectionCompare} methods that use
* reflection to determine the fields to append. Because fields can be private,
* <code>reflectionCompare</code> uses {@link AccessibleObject#setAccessible(boolean)} to
* bypass normal access control checks. This will fail under a security manager,
* unless the appropriate permissions are set up correctly. It is also
* slower than appending explicitly.</p>
*
* <p>A typical implementation of <code>compareTo(Object)</code> using
* <code>reflectionCompare</code> looks like:</p>
* <pre>
* public int compareTo(Object o) {
* return CompareToBuilder.reflectionCompare(this, o);
* }
* </pre>
*
* @see Comparable
* @see Object#equals(Object)
* @see Object#hashCode()
* @see EqualsBuilder
* @see HashCodeBuilder
* @since 1.0
* @version $Id: CompareToBuilder.java 1199735 2011-11-09 13:11:07Z sebb $
*/
public class CompareToBuilder implements Builder<Integer> {
/**
* Current state of the comparison as appended fields are checked.
*/
private int comparison;
/**
* <p>Constructor for CompareToBuilder.</p>
*
* <p>Starts off assuming that the objects are equal. Multiple calls are
* then made to the various append methods, followed by a call to
* {@link #toComparison} to get the result.</p>
*/
public CompareToBuilder() {
super();
comparison = 0;
}
//-----------------------------------------------------------------------
/**
* <p>Compares two <code>Object</code>s via reflection.</p>
*
* <p>Fields can be private, thus <code>AccessibleObject.setAccessible</code>
* is used to bypass normal access control checks. This will fail under a
* security manager unless the appropriate permissions are set.</p>
*
* <ul>
* <li>Static fields will not be compared</li>
* <li>Transient members will be not be compared, as they are likely derived
* fields</li>
* <li>Superclass fields will be compared</li>
* </ul>
*
* <p>If both <code>lhs</code> and <code>rhs</code> are <code>null</code>,
* they are considered equal.</p>
*
* @param lhs left-hand object
* @param rhs right-hand object
* @return a negative integer, zero, or a positive integer as <code>lhs</code>
* is less than, equal to, or greater than <code>rhs</code>
* @throws NullPointerException if either (but not both) parameters are
* <code>null</code>
* @throws ClassCastException if <code>rhs</code> is not assignment-compatible
* with <code>lhs</code>
*/
public static int reflectionCompare(Object lhs, Object rhs) {
return reflectionCompare(lhs, rhs, false, null);
}
/**
* <p>Compares two <code>Object</code>s via reflection.</p>
*
* <p>Fields can be private, thus <code>AccessibleObject.setAccessible</code>
* is used to bypass normal access control checks. This will fail under a
* security manager unless the appropriate permissions are set.</p>
*
* <ul>
* <li>Static fields will not be compared</li>
* <li>If <code>compareTransients</code> is <code>true</code>,
* compares transient members. Otherwise ignores them, as they
* are likely derived fields.</li>
* <li>Superclass fields will be compared</li>
* </ul>
*
* <p>If both <code>lhs</code> and <code>rhs</code> are <code>null</code>,
* they are considered equal.</p>
*
* @param lhs left-hand object
* @param rhs right-hand object
* @param compareTransients whether to compare transient fields
* @return a negative integer, zero, or a positive integer as <code>lhs</code>
* is less than, equal to, or greater than <code>rhs</code>
* @throws NullPointerException if either <code>lhs</code> or <code>rhs</code>
* (but not both) is <code>null</code>
* @throws ClassCastException if <code>rhs</code> is not assignment-compatible
* with <code>lhs</code>
*/
public static int reflectionCompare(Object lhs, Object rhs, boolean compareTransients) {
return reflectionCompare(lhs, rhs, compareTransients, null);
}
/**
* <p>Compares two <code>Object</code>s via reflection.</p>
*
* <p>Fields can be private, thus <code>AccessibleObject.setAccessible</code>
* is used to bypass normal access control checks. This will fail under a
* security manager unless the appropriate permissions are set.</p>
*
* <ul>
* <li>Static fields will not be compared</li>
* <li>If <code>compareTransients</code> is <code>true</code>,
* compares transient members. Otherwise ignores them, as they
* are likely derived fields.</li>
* <li>Superclass fields will be compared</li>
* </ul>
*
* <p>If both <code>lhs</code> and <code>rhs</code> are <code>null</code>,
* they are considered equal.</p>
*
* @param lhs left-hand object
* @param rhs right-hand object
* @param excludeFields Collection of String fields to exclude
* @return a negative integer, zero, or a positive integer as <code>lhs</code>
* is less than, equal to, or greater than <code>rhs</code>
* @throws NullPointerException if either <code>lhs</code> or <code>rhs</code>
* (but not both) is <code>null</code>
* @throws ClassCastException if <code>rhs</code> is not assignment-compatible
* with <code>lhs</code>
* @since 2.2
*/
public static int reflectionCompare(Object lhs, Object rhs, Collection<String> excludeFields) {
return reflectionCompare(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
}
/**
* <p>Compares two <code>Object</code>s via reflection.</p>
*
* <p>Fields can be private, thus <code>AccessibleObject.setAccessible</code>
* is used to bypass normal access control checks. This will fail under a
* security manager unless the appropriate permissions are set.</p>
*
* <ul>
* <li>Static fields will not be compared</li>
* <li>If <code>compareTransients</code> is <code>true</code>,
* compares transient members. Otherwise ignores them, as they
* are likely derived fields.</li>
* <li>Superclass fields will be compared</li>
* </ul>
*
* <p>If both <code>lhs</code> and <code>rhs</code> are <code>null</code>,
* they are considered equal.</p>
*
* @param lhs left-hand object
* @param rhs right-hand object
* @param excludeFields array of fields to exclude
* @return a negative integer, zero, or a positive integer as <code>lhs</code>
* is less than, equal to, or greater than <code>rhs</code>
* @throws NullPointerException if either <code>lhs</code> or <code>rhs</code>
* (but not both) is <code>null</code>
* @throws ClassCastException if <code>rhs</code> is not assignment-compatible
* with <code>lhs</code>
* @since 2.2
*/
public static int reflectionCompare(Object lhs, Object rhs, String... excludeFields) {
return reflectionCompare(lhs, rhs, false, null, excludeFields);
}
/**
* <p>Compares two <code>Object</code>s via reflection.</p>
*
* <p>Fields can be private, thus <code>AccessibleObject.setAccessible</code>
* is used to bypass normal access control checks. This will fail under a
* security manager unless the appropriate permissions are set.</p>
*
* <ul>
* <li>Static fields will not be compared</li>
* <li>If the <code>compareTransients</code> is <code>true</code>,
* compares transient members. Otherwise ignores them, as they
* are likely derived fields.</li>
* <li>Compares superclass fields up to and including <code>reflectUpToClass</code>.
* If <code>reflectUpToClass</code> is <code>null</code>, compares all superclass fields.</li>
* </ul>
*
* <p>If both <code>lhs</code> and <code>rhs</code> are <code>null</code>,
* they are considered equal.</p>
*
* @param lhs left-hand object
* @param rhs right-hand object
* @param compareTransients whether to compare transient fields
* @param reflectUpToClass last superclass for which fields are compared
* @param excludeFields fields to exclude
* @return a negative integer, zero, or a positive integer as <code>lhs</code>
* is less than, equal to, or greater than <code>rhs</code>
* @throws NullPointerException if either <code>lhs</code> or <code>rhs</code>
* (but not both) is <code>null</code>
* @throws ClassCastException if <code>rhs</code> is not assignment-compatible
* with <code>lhs</code>
* @since 2.2 (2.0 as <code>reflectionCompare(Object, Object, boolean, Class)</code>)
*/
public static int reflectionCompare(
Object lhs,
Object rhs,
boolean compareTransients,
Class<?> reflectUpToClass,
String... excludeFields) {
if (lhs == rhs) {
return 0;
}
if (lhs == null || rhs == null) {
throw new NullPointerException();
}
Class<?> lhsClazz = lhs.getClass();
if (!lhsClazz.isInstance(rhs)) {
throw new ClassCastException();
}
CompareToBuilder compareToBuilder = new CompareToBuilder();
reflectionAppend(lhs, rhs, lhsClazz, compareToBuilder, compareTransients, excludeFields);
while (lhsClazz.getSuperclass() != null && lhsClazz != reflectUpToClass) {
lhsClazz = lhsClazz.getSuperclass();
reflectionAppend(lhs, rhs, lhsClazz, compareToBuilder, compareTransients, excludeFields);
}
return compareToBuilder.toComparison();
}
/**
* <p>Appends to <code>builder</code> the comparison of <code>lhs</code>
* to <code>rhs</code> using the fields defined in <code>clazz</code>.</p>
*
* @param lhs left-hand object
* @param rhs right-hand object
* @param clazz <code>Class</code> that defines fields to be compared
* @param builder <code>CompareToBuilder</code> to append to
* @param useTransients whether to compare transient fields
* @param excludeFields fields to exclude
*/
private static void reflectionAppend(
Object lhs,
Object rhs,
Class<?> clazz,
CompareToBuilder builder,
boolean useTransients,
String[] excludeFields) {
Field[] fields = clazz.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
for (int i = 0; i < fields.length && builder.comparison == 0; i++) {
Field f = fields[i];
if (!ArrayUtils.contains(excludeFields, f.getName())
&& (f.getName().indexOf('$') == -1)
&& (useTransients || !Modifier.isTransient(f.getModifiers()))
&& (!Modifier.isStatic(f.getModifiers()))) {
try {
builder.append(f.get(lhs), f.get(rhs));
} catch (IllegalAccessException e) {
// This can't happen. Would get a Security exception instead.
// Throw a runtime exception in case the impossible happens.
throw new InternalError("Unexpected IllegalAccessException");
}
}
}
}
//-----------------------------------------------------------------------
/**
* <p>Appends to the <code>builder</code> the <code>compareTo(Object)</code>
* result of the superclass.</p>
*
* @param superCompareTo result of calling <code>super.compareTo(Object)</code>
* @return this - used to chain append calls
* @since 2.0
*/
public CompareToBuilder appendSuper(int superCompareTo) {
if (comparison != 0) {
return this;
}
comparison = superCompareTo;
return this;
}
//-----------------------------------------------------------------------
/**
* <p>Appends to the <code>builder</code> the comparison of
* two <code>Object</code>s.</p>
*
* <ol>
* <li>Check if <code>lhs == rhs</code></li>
* <li>Check if either <code>lhs</code> or <code>rhs</code> is <code>null</code>,
* a <code>null</code> object is less than a non-<code>null</code> object</li>
* <li>Check the object contents</li>
* </ol>
*
* <p><code>lhs</code> must either be an array or implement {@link Comparable}.</p>
*
* @param lhs left-hand object
* @param rhs right-hand object
* @return this - used to chain append calls
* @throws ClassCastException if <code>rhs</code> is not assignment-compatible
* with <code>lhs</code>
*/
public CompareToBuilder append(Object lhs, Object rhs) {
return append(lhs, rhs, null);
}
/**
* <p>Appends to the <code>builder</code> the comparison of
* two <code>Object</code>s.</p>
*
* <ol>
* <li>Check if <code>lhs == rhs</code></li>
* <li>Check if either <code>lhs</code> or <code>rhs</code> is <code>null</code>,
* a <code>null</code> object is less than a non-<code>null</code> object</li>
* <li>Check the object contents</li>
* </ol>
*
* <p>If <code>lhs</code> is an array, array comparison methods will be used.
* Otherwise <code>comparator</code> will be used to compare the objects.
* If <code>comparator</code> is <code>null</code>, <code>lhs</code> must
* implement {@link Comparable} instead.</p>
*
* @param lhs left-hand object
* @param rhs right-hand object
* @param comparator <code>Comparator</code> used to compare the objects,
* <code>null</code> means treat lhs as <code>Comparable</code>
* @return this - used to chain append calls
* @throws ClassCastException if <code>rhs</code> is not assignment-compatible
* with <code>lhs</code>
* @since 2.0
*/
public CompareToBuilder append(Object lhs, Object rhs, Comparator<?> comparator) {
if (comparison != 0) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null) {
comparison = -1;
return this;
}
if (rhs == null) {
comparison = +1;
return this;
}
if (lhs.getClass().isArray()) {
// switch on type of array, to dispatch to the correct handler
// handles multi dimensional arrays
// throws a ClassCastException if rhs is not the correct array type
if (lhs instanceof long[]) {
append((long[]) lhs, (long[]) rhs);
} else if (lhs instanceof int[]) {
append((int[]) lhs, (int[]) rhs);
} else if (lhs instanceof short[]) {
append((short[]) lhs, (short[]) rhs);
} else if (lhs instanceof char[]) {
append((char[]) lhs, (char[]) rhs);
} else if (lhs instanceof byte[]) {
append((byte[]) lhs, (byte[]) rhs);
} else if (lhs instanceof double[]) {
append((double[]) lhs, (double[]) rhs);
} else if (lhs instanceof float[]) {
append((float[]) lhs, (float[]) rhs);
} else if (lhs instanceof boolean[]) {
append((boolean[]) lhs, (boolean[]) rhs);
} else {
// not an array of primitives
// throws a ClassCastException if rhs is not an array
append((Object[]) lhs, (Object[]) rhs, comparator);
}
} else {
// the simple case, not an array, just test the element
if (comparator == null) {
@SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc
final Comparable<Object> comparable = (Comparable<Object>) lhs;
comparison = comparable.compareTo(rhs);
} else {
@SuppressWarnings("unchecked") // assume this can be done; if not throw CCE as per Javadoc
final Comparator<Object> comparator2 = (Comparator<Object>) comparator;
comparison = comparator2.compare(lhs, rhs);
}
}
return this;
}
//-------------------------------------------------------------------------
/**
* Appends to the <code>builder</code> the comparison of
* two <code>long</code>s.
*
* @param lhs left-hand value
* @param rhs right-hand value
* @return this - used to chain append calls
*/
public CompareToBuilder append(long lhs, long rhs) {
if (comparison != 0) {
return this;
}
comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0));
return this;
}
/**
* Appends to the <code>builder</code> the comparison of
* two <code>int</code>s.
*
* @param lhs left-hand value
* @param rhs right-hand value
* @return this - used to chain append calls
*/
public CompareToBuilder append(int lhs, int rhs) {
if (comparison != 0) {
return this;
}
comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0));
return this;
}
/**
* Appends to the <code>builder</code> the comparison of
* two <code>short</code>s.
*
* @param lhs left-hand value
* @param rhs right-hand value
* @return this - used to chain append calls
*/
public CompareToBuilder append(short lhs, short rhs) {
if (comparison != 0) {
return this;
}
comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0));
return this;
}
/**
* Appends to the <code>builder</code> the comparison of
* two <code>char</code>s.
*
* @param lhs left-hand value
* @param rhs right-hand value
* @return this - used to chain append calls
*/
public CompareToBuilder append(char lhs, char rhs) {
if (comparison != 0) {
return this;
}
comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0));
return this;
}
/**
* Appends to the <code>builder</code> the comparison of
* two <code>byte</code>s.
*
* @param lhs left-hand value
* @param rhs right-hand value
* @return this - used to chain append calls
*/
public CompareToBuilder append(byte lhs, byte rhs) {
if (comparison != 0) {
return this;
}
comparison = ((lhs < rhs) ? -1 : ((lhs > rhs) ? 1 : 0));
return this;
}
/**
* <p>Appends to the <code>builder</code> the comparison of
* two <code>double</code>s.</p>
*
* <p>This handles NaNs, Infinities, and <code>-0.0</code>.</p>
*
* <p>It is compatible with the hash code generated by
* <code>HashCodeBuilder</code>.</p>
*
* @param lhs left-hand value
* @param rhs right-hand value
* @return this - used to chain append calls
*/
public CompareToBuilder append(double lhs, double rhs) {
if (comparison != 0) {
return this;
}
comparison = Double.compare(lhs, rhs);
return this;
}
/**
* <p>Appends to the <code>builder</code> the comparison of
* two <code>float</code>s.</p>
*
* <p>This handles NaNs, Infinities, and <code>-0.0</code>.</p>
*
* <p>It is compatible with the hash code generated by
* <code>HashCodeBuilder</code>.</p>
*
* @param lhs left-hand value
* @param rhs right-hand value
* @return this - used to chain append calls
*/
public CompareToBuilder append(float lhs, float rhs) {
if (comparison != 0) {
return this;
}
comparison = Float.compare(lhs, rhs);
return this;
}
/**
* Appends to the <code>builder</code> the comparison of
* two <code>booleans</code>s.
*
* @param lhs left-hand value
* @param rhs right-hand value
* @return this - used to chain append calls
*/
public CompareToBuilder append(boolean lhs, boolean rhs) {
if (comparison != 0) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == false) {
comparison = -1;
} else {
comparison = +1;
}
return this;
}
//-----------------------------------------------------------------------
/**
* <p>Appends to the <code>builder</code> the deep comparison of
* two <code>Object</code> arrays.</p>
*
* <ol>
* <li>Check if arrays are the same using <code>==</code></li>
* <li>Check if for <code>null</code>, <code>null</code> is less than non-<code>null</code></li>
* <li>Check array length, a short length array is less than a long length array</li>
* <li>Check array contents element by element using {@link #append(Object, Object, Comparator)}</li>
* </ol>
*
* <p>This method will also will be called for the top level of multi-dimensional,
* ragged, and multi-typed arrays.</p>
*
* @param lhs left-hand array
* @param rhs right-hand array
* @return this - used to chain append calls
* @throws ClassCastException if <code>rhs</code> is not assignment-compatible
* with <code>lhs</code>
*/
public CompareToBuilder append(Object[] lhs, Object[] rhs) {
return append(lhs, rhs, null);
}
/**
* <p>Appends to the <code>builder</code> the deep comparison of
* two <code>Object</code> arrays.</p>
*
* <ol>
* <li>Check if arrays are the same using <code>==</code></li>
* <li>Check if for <code>null</code>, <code>null</code> is less than non-<code>null</code></li>
* <li>Check array length, a short length array is less than a long length array</li>
* <li>Check array contents element by element using {@link #append(Object, Object, Comparator)}</li>
* </ol>
*
* <p>This method will also will be called for the top level of multi-dimensional,
* ragged, and multi-typed arrays.</p>
*
* @param lhs left-hand array
* @param rhs right-hand array
* @param comparator <code>Comparator</code> to use to compare the array elements,
* <code>null</code> means to treat <code>lhs</code> elements as <code>Comparable</code>.
* @return this - used to chain append calls
* @throws ClassCastException if <code>rhs</code> is not assignment-compatible
* with <code>lhs</code>
* @since 2.0
*/
public CompareToBuilder append(Object[] lhs, Object[] rhs, Comparator<?> comparator) {
if (comparison != 0) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null) {
comparison = -1;
return this;
}
if (rhs == null) {
comparison = +1;
return this;
}
if (lhs.length != rhs.length) {
comparison = (lhs.length < rhs.length) ? -1 : +1;
return this;
}
for (int i = 0; i < lhs.length && comparison == 0; i++) {
append(lhs[i], rhs[i], comparator);
}
return this;
}
/**
* <p>Appends to the <code>builder</code> the deep comparison of
* two <code>long</code> arrays.</p>
*
* <ol>
* <li>Check if arrays are the same using <code>==</code></li>
* <li>Check if for <code>null</code>, <code>null</code> is less than non-<code>null</code></li>
* <li>Check array length, a shorter length array is less than a longer length array</li>
* <li>Check array contents element by element using {@link #append(long, long)}</li>
* </ol>
*
* @param lhs left-hand array
* @param rhs right-hand array
* @return this - used to chain append calls
*/
public CompareToBuilder append(long[] lhs, long[] rhs) {
if (comparison != 0) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null) {
comparison = -1;
return this;
}
if (rhs == null) {
comparison = +1;
return this;
}
if (lhs.length != rhs.length) {
comparison = (lhs.length < rhs.length) ? -1 : +1;
return this;
}
for (int i = 0; i < lhs.length && comparison == 0; i++) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Appends to the <code>builder</code> the deep comparison of
* two <code>int</code> arrays.</p>
*
* <ol>
* <li>Check if arrays are the same using <code>==</code></li>
* <li>Check if for <code>null</code>, <code>null</code> is less than non-<code>null</code></li>
* <li>Check array length, a shorter length array is less than a longer length array</li>
* <li>Check array contents element by element using {@link #append(int, int)}</li>
* </ol>
*
* @param lhs left-hand array
* @param rhs right-hand array
* @return this - used to chain append calls
*/
public CompareToBuilder append(int[] lhs, int[] rhs) {
if (comparison != 0) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null) {
comparison = -1;
return this;
}
if (rhs == null) {
comparison = +1;
return this;
}
if (lhs.length != rhs.length) {
comparison = (lhs.length < rhs.length) ? -1 : +1;
return this;
}
for (int i = 0; i < lhs.length && comparison == 0; i++) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Appends to the <code>builder</code> the deep comparison of
* two <code>short</code> arrays.</p>
*
* <ol>
* <li>Check if arrays are the same using <code>==</code></li>
* <li>Check if for <code>null</code>, <code>null</code> is less than non-<code>null</code></li>
* <li>Check array length, a shorter length array is less than a longer length array</li>
* <li>Check array contents element by element using {@link #append(short, short)}</li>
* </ol>
*
* @param lhs left-hand array
* @param rhs right-hand array
* @return this - used to chain append calls
*/
public CompareToBuilder append(short[] lhs, short[] rhs) {
if (comparison != 0) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null) {
comparison = -1;
return this;
}
if (rhs == null) {
comparison = +1;
return this;
}
if (lhs.length != rhs.length) {
comparison = (lhs.length < rhs.length) ? -1 : +1;
return this;
}
for (int i = 0; i < lhs.length && comparison == 0; i++) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Appends to the <code>builder</code> the deep comparison of
* two <code>char</code> arrays.</p>
*
* <ol>
* <li>Check if arrays are the same using <code>==</code></li>
* <li>Check if for <code>null</code>, <code>null</code> is less than non-<code>null</code></li>
* <li>Check array length, a shorter length array is less than a longer length array</li>
* <li>Check array contents element by element using {@link #append(char, char)}</li>
* </ol>
*
* @param lhs left-hand array
* @param rhs right-hand array
* @return this - used to chain append calls
*/
public CompareToBuilder append(char[] lhs, char[] rhs) {
if (comparison != 0) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null) {
comparison = -1;
return this;
}
if (rhs == null) {
comparison = +1;
return this;
}
if (lhs.length != rhs.length) {
comparison = (lhs.length < rhs.length) ? -1 : +1;
return this;
}
for (int i = 0; i < lhs.length && comparison == 0; i++) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Appends to the <code>builder</code> the deep comparison of
* two <code>byte</code> arrays.</p>
*
* <ol>
* <li>Check if arrays are the same using <code>==</code></li>
* <li>Check if for <code>null</code>, <code>null</code> is less than non-<code>null</code></li>
* <li>Check array length, a shorter length array is less than a longer length array</li>
* <li>Check array contents element by element using {@link #append(byte, byte)}</li>
* </ol>
*
* @param lhs left-hand array
* @param rhs right-hand array
* @return this - used to chain append calls
*/
public CompareToBuilder append(byte[] lhs, byte[] rhs) {
if (comparison != 0) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null) {
comparison = -1;
return this;
}
if (rhs == null) {
comparison = +1;
return this;
}
if (lhs.length != rhs.length) {
comparison = (lhs.length < rhs.length) ? -1 : +1;
return this;
}
for (int i = 0; i < lhs.length && comparison == 0; i++) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Appends to the <code>builder</code> the deep comparison of
* two <code>double</code> arrays.</p>
*
* <ol>
* <li>Check if arrays are the same using <code>==</code></li>
* <li>Check if for <code>null</code>, <code>null</code> is less than non-<code>null</code></li>
* <li>Check array length, a shorter length array is less than a longer length array</li>
* <li>Check array contents element by element using {@link #append(double, double)}</li>
* </ol>
*
* @param lhs left-hand array
* @param rhs right-hand array
* @return this - used to chain append calls
*/
public CompareToBuilder append(double[] lhs, double[] rhs) {
if (comparison != 0) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null) {
comparison = -1;
return this;
}
if (rhs == null) {
comparison = +1;
return this;
}
if (lhs.length != rhs.length) {
comparison = (lhs.length < rhs.length) ? -1 : +1;
return this;
}
for (int i = 0; i < lhs.length && comparison == 0; i++) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Appends to the <code>builder</code> the deep comparison of
* two <code>float</code> arrays.</p>
*
* <ol>
* <li>Check if arrays are the same using <code>==</code></li>
* <li>Check if for <code>null</code>, <code>null</code> is less than non-<code>null</code></li>
* <li>Check array length, a shorter length array is less than a longer length array</li>
* <li>Check array contents element by element using {@link #append(float, float)}</li>
* </ol>
*
* @param lhs left-hand array
* @param rhs right-hand array
* @return this - used to chain append calls
*/
public CompareToBuilder append(float[] lhs, float[] rhs) {
if (comparison != 0) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null) {
comparison = -1;
return this;
}
if (rhs == null) {
comparison = +1;
return this;
}
if (lhs.length != rhs.length) {
comparison = (lhs.length < rhs.length) ? -1 : +1;
return this;
}
for (int i = 0; i < lhs.length && comparison == 0; i++) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Appends to the <code>builder</code> the deep comparison of
* two <code>boolean</code> arrays.</p>
*
* <ol>
* <li>Check if arrays are the same using <code>==</code></li>
* <li>Check if for <code>null</code>, <code>null</code> is less than non-<code>null</code></li>
* <li>Check array length, a shorter length array is less than a longer length array</li>
* <li>Check array contents element by element using {@link #append(boolean, boolean)}</li>
* </ol>
*
* @param lhs left-hand array
* @param rhs right-hand array
* @return this - used to chain append calls
*/
public CompareToBuilder append(boolean[] lhs, boolean[] rhs) {
if (comparison != 0) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null) {
comparison = -1;
return this;
}
if (rhs == null) {
comparison = +1;
return this;
}
if (lhs.length != rhs.length) {
comparison = (lhs.length < rhs.length) ? -1 : +1;
return this;
}
for (int i = 0; i < lhs.length && comparison == 0; i++) {
append(lhs[i], rhs[i]);
}
return this;
}
//-----------------------------------------------------------------------
/**
* Returns a negative integer, a positive integer, or zero as
* the <code>builder</code> has judged the "left-hand" side
* as less than, greater than, or equal to the "right-hand"
* side.
*
* @return final comparison result
* @see #build()
*/
public int toComparison() {
return comparison;
}
/**
* Returns a negative Integer, a positive Integer, or zero as
* the <code>builder</code> has judged the "left-hand" side
* as less than, greater than, or equal to the "right-hand"
* side.
*
* @return final comparison result as an Integer
* @see #toComparison()
* @since 3.0
*/
public Integer build() {
return Integer.valueOf(toComparison());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.builder;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import external.org.apache.commons.lang3.ArrayUtils;
import external.org.apache.commons.lang3.tuple.Pair;
/**
* <p>Assists in implementing {@link Object#equals(Object)} methods.</p>
*
* <p> This class provides methods to build a good equals method for any
* class. It follows rules laid out in
* <a href="http://java.sun.com/docs/books/effective/index.html">Effective Java</a>
* , by Joshua Bloch. In particular the rule for comparing <code>doubles</code>,
* <code>floats</code>, and arrays can be tricky. Also, making sure that
* <code>equals()</code> and <code>hashCode()</code> are consistent can be
* difficult.</p>
*
* <p>Two Objects that compare as equals must generate the same hash code,
* but two Objects with the same hash code do not have to be equal.</p>
*
* <p>All relevant fields should be included in the calculation of equals.
* Derived fields may be ignored. In particular, any field used in
* generating a hash code must be used in the equals method, and vice
* versa.</p>
*
* <p>Typical use for the code is as follows:</p>
* <pre>
* public boolean equals(Object obj) {
* if (obj == null) { return false; }
* if (obj == this) { return true; }
* if (obj.getClass() != getClass()) {
* return false;
* }
* MyClass rhs = (MyClass) obj;
* return new EqualsBuilder()
* .appendSuper(super.equals(obj))
* .append(field1, rhs.field1)
* .append(field2, rhs.field2)
* .append(field3, rhs.field3)
* .isEquals();
* }
* </pre>
*
* <p> Alternatively, there is a method that uses reflection to determine
* the fields to test. Because these fields are usually private, the method,
* <code>reflectionEquals</code>, uses <code>AccessibleObject.setAccessible</code> to
* change the visibility of the fields. This will fail under a security
* manager, unless the appropriate permissions are set up correctly. It is
* also slower than testing explicitly.</p>
*
* <p> A typical invocation for this method would look like:</p>
* <pre>
* public boolean equals(Object obj) {
* return EqualsBuilder.reflectionEquals(this, obj);
* }
* </pre>
*
* @since 1.0
* @version $Id: EqualsBuilder.java 1091531 2011-04-12 18:29:49Z ggregory $
*/
public class EqualsBuilder implements Builder<Boolean> {
/**
* <p>
* A registry of objects used by reflection methods to detect cyclical object references and avoid infinite loops.
* </p>
*
* @since 3.0
*/
private static final ThreadLocal<Set<Pair<IDKey, IDKey>>> REGISTRY = new ThreadLocal<Set<Pair<IDKey, IDKey>>>();
/*
* NOTE: we cannot store the actual objects in a HashSet, as that would use the very hashCode()
* we are in the process of calculating.
*
* So we generate a one-to-one mapping from the original object to a new object.
*
* Now HashSet uses equals() to determine if two elements with the same hashcode really
* are equal, so we also need to ensure that the replacement objects are only equal
* if the original objects are identical.
*
* The original implementation (2.4 and before) used the System.indentityHashCode()
* method - however this is not guaranteed to generate unique ids (e.g. LANG-459)
*
* We now use the IDKey helper class (adapted from org.apache.axis.utils.IDKey)
* to disambiguate the duplicate ids.
*/
/**
* <p>
* Returns the registry of object pairs being traversed by the reflection
* methods in the current thread.
* </p>
*
* @return Set the registry of objects being traversed
* @since 3.0
*/
static Set<Pair<IDKey, IDKey>> getRegistry() {
return REGISTRY.get();
}
/**
* <p>
* Converters value pair into a register pair.
* </p>
*
* @param lhs <code>this</code> object
* @param rhs the other object
*
* @return the pair
*/
static Pair<IDKey, IDKey> getRegisterPair(Object lhs, Object rhs) {
IDKey left = new IDKey(lhs);
IDKey right = new IDKey(rhs);
return Pair.of(left, right);
}
/**
* <p>
* Returns <code>true</code> if the registry contains the given object pair.
* Used by the reflection methods to avoid infinite loops.
* Objects might be swapped therefore a check is needed if the object pair
* is registered in given or swapped order.
* </p>
*
* @param lhs <code>this</code> object to lookup in registry
* @param rhs the other object to lookup on registry
* @return boolean <code>true</code> if the registry contains the given object.
* @since 3.0
*/
static boolean isRegistered(Object lhs, Object rhs) {
Set<Pair<IDKey, IDKey>> registry = getRegistry();
Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
Pair<IDKey, IDKey> swappedPair = Pair.of(pair.getLeft(), pair.getRight());
return registry != null
&& (registry.contains(pair) || registry.contains(swappedPair));
}
/**
* <p>
* Registers the given object pair.
* Used by the reflection methods to avoid infinite loops.
* </p>
*
* @param lhs <code>this</code> object to register
* @param rhs the other object to register
*/
static void register(Object lhs, Object rhs) {
synchronized (EqualsBuilder.class) {
if (getRegistry() == null) {
REGISTRY.set(new HashSet<Pair<IDKey, IDKey>>());
}
}
Set<Pair<IDKey, IDKey>> registry = getRegistry();
Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
registry.add(pair);
}
/**
* <p>
* Unregisters the given object pair.
* </p>
*
* <p>
* Used by the reflection methods to avoid infinite loops.
*
* @param lhs <code>this</code> object to unregister
* @param rhs the other object to unregister
* @since 3.0
*/
static void unregister(Object lhs, Object rhs) {
Set<Pair<IDKey, IDKey>> registry = getRegistry();
if (registry != null) {
Pair<IDKey, IDKey> pair = getRegisterPair(lhs, rhs);
registry.remove(pair);
synchronized (EqualsBuilder.class) {
//read again
registry = getRegistry();
if (registry != null && registry.isEmpty()) {
REGISTRY.remove();
}
}
}
}
/**
* If the fields tested are equals.
* The default value is <code>true</code>.
*/
private boolean isEquals = true;
/**
* <p>Constructor for EqualsBuilder.</p>
*
* <p>Starts off assuming that equals is <code>true</code>.</p>
* @see Object#equals(Object)
*/
public EqualsBuilder() {
// do nothing for now.
}
//-------------------------------------------------------------------------
/**
* <p>This method uses reflection to determine if the two <code>Object</code>s
* are equal.</p>
*
* <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
* fields. This means that it will throw a security exception if run under
* a security manager, if the permissions are not set up correctly. It is also
* not as efficient as testing explicitly.</p>
*
* <p>Transient members will be not be tested, as they are likely derived
* fields, and not part of the value of the Object.</p>
*
* <p>Static fields will not be tested. Superclass fields will be included.</p>
*
* @param lhs <code>this</code> object
* @param rhs the other object
* @param excludeFields Collection of String field names to exclude from testing
* @return <code>true</code> if the two Objects have tested equals.
*/
public static boolean reflectionEquals(Object lhs, Object rhs, Collection<String> excludeFields) {
return reflectionEquals(lhs, rhs, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
}
/**
* <p>This method uses reflection to determine if the two <code>Object</code>s
* are equal.</p>
*
* <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
* fields. This means that it will throw a security exception if run under
* a security manager, if the permissions are not set up correctly. It is also
* not as efficient as testing explicitly.</p>
*
* <p>Transient members will be not be tested, as they are likely derived
* fields, and not part of the value of the Object.</p>
*
* <p>Static fields will not be tested. Superclass fields will be included.</p>
*
* @param lhs <code>this</code> object
* @param rhs the other object
* @param excludeFields array of field names to exclude from testing
* @return <code>true</code> if the two Objects have tested equals.
*/
public static boolean reflectionEquals(Object lhs, Object rhs, String... excludeFields) {
return reflectionEquals(lhs, rhs, false, null, excludeFields);
}
/**
* <p>This method uses reflection to determine if the two <code>Object</code>s
* are equal.</p>
*
* <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
* fields. This means that it will throw a security exception if run under
* a security manager, if the permissions are not set up correctly. It is also
* not as efficient as testing explicitly.</p>
*
* <p>If the TestTransients parameter is set to <code>true</code>, transient
* members will be tested, otherwise they are ignored, as they are likely
* derived fields, and not part of the value of the <code>Object</code>.</p>
*
* <p>Static fields will not be tested. Superclass fields will be included.</p>
*
* @param lhs <code>this</code> object
* @param rhs the other object
* @param testTransients whether to include transient fields
* @return <code>true</code> if the two Objects have tested equals.
*/
public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients) {
return reflectionEquals(lhs, rhs, testTransients, null);
}
/**
* <p>This method uses reflection to determine if the two <code>Object</code>s
* are equal.</p>
*
* <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private
* fields. This means that it will throw a security exception if run under
* a security manager, if the permissions are not set up correctly. It is also
* not as efficient as testing explicitly.</p>
*
* <p>If the testTransients parameter is set to <code>true</code>, transient
* members will be tested, otherwise they are ignored, as they are likely
* derived fields, and not part of the value of the <code>Object</code>.</p>
*
* <p>Static fields will not be included. Superclass fields will be appended
* up to and including the specified superclass. A null superclass is treated
* as java.lang.Object.</p>
*
* @param lhs <code>this</code> object
* @param rhs the other object
* @param testTransients whether to include transient fields
* @param reflectUpToClass the superclass to reflect up to (inclusive),
* may be <code>null</code>
* @param excludeFields array of field names to exclude from testing
* @return <code>true</code> if the two Objects have tested equals.
* @since 2.0
*/
public static boolean reflectionEquals(Object lhs, Object rhs, boolean testTransients, Class<?> reflectUpToClass,
String... excludeFields) {
if (lhs == rhs) {
return true;
}
if (lhs == null || rhs == null) {
return false;
}
// Find the leaf class since there may be transients in the leaf
// class or in classes between the leaf and root.
// If we are not testing transients or a subclass has no ivars,
// then a subclass can test equals to a superclass.
Class<?> lhsClass = lhs.getClass();
Class<?> rhsClass = rhs.getClass();
Class<?> testClass;
if (lhsClass.isInstance(rhs)) {
testClass = lhsClass;
if (!rhsClass.isInstance(lhs)) {
// rhsClass is a subclass of lhsClass
testClass = rhsClass;
}
} else if (rhsClass.isInstance(lhs)) {
testClass = rhsClass;
if (!lhsClass.isInstance(rhs)) {
// lhsClass is a subclass of rhsClass
testClass = lhsClass;
}
} else {
// The two classes are not related.
return false;
}
EqualsBuilder equalsBuilder = new EqualsBuilder();
try {
reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields);
while (testClass.getSuperclass() != null && testClass != reflectUpToClass) {
testClass = testClass.getSuperclass();
reflectionAppend(lhs, rhs, testClass, equalsBuilder, testTransients, excludeFields);
}
} catch (IllegalArgumentException e) {
// In this case, we tried to test a subclass vs. a superclass and
// the subclass has ivars or the ivars are transient and
// we are testing transients.
// If a subclass has ivars that we are trying to test them, we get an
// exception and we know that the objects are not equal.
return false;
}
return equalsBuilder.isEquals();
}
/**
* <p>Appends the fields and values defined by the given object of the
* given Class.</p>
*
* @param lhs the left hand object
* @param rhs the right hand object
* @param clazz the class to append details of
* @param builder the builder to append to
* @param useTransients whether to test transient fields
* @param excludeFields array of field names to exclude from testing
*/
private static void reflectionAppend(
Object lhs,
Object rhs,
Class<?> clazz,
EqualsBuilder builder,
boolean useTransients,
String[] excludeFields) {
if (isRegistered(lhs, rhs)) {
return;
}
try {
register(lhs, rhs);
Field[] fields = clazz.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
for (int i = 0; i < fields.length && builder.isEquals; i++) {
Field f = fields[i];
if (!ArrayUtils.contains(excludeFields, f.getName())
&& (f.getName().indexOf('$') == -1)
&& (useTransients || !Modifier.isTransient(f.getModifiers()))
&& (!Modifier.isStatic(f.getModifiers()))) {
try {
builder.append(f.get(lhs), f.get(rhs));
} catch (IllegalAccessException e) {
//this can't happen. Would get a Security exception instead
//throw a runtime exception in case the impossible happens.
throw new InternalError("Unexpected IllegalAccessException");
}
}
}
} finally {
unregister(lhs, rhs);
}
}
//-------------------------------------------------------------------------
/**
* <p>Adds the result of <code>super.equals()</code> to this builder.</p>
*
* @param superEquals the result of calling <code>super.equals()</code>
* @return EqualsBuilder - used to chain calls.
* @since 2.0
*/
public EqualsBuilder appendSuper(boolean superEquals) {
if (isEquals == false) {
return this;
}
isEquals = superEquals;
return this;
}
//-------------------------------------------------------------------------
/**
* <p>Test if two <code>Object</code>s are equal using their
* <code>equals</code> method.</p>
*
* @param lhs the left hand object
* @param rhs the right hand object
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(Object lhs, Object rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
Class<?> lhsClass = lhs.getClass();
if (!lhsClass.isArray()) {
// The simple case, not an array, just test the element
isEquals = lhs.equals(rhs);
} else if (lhs.getClass() != rhs.getClass()) {
// Here when we compare different dimensions, for example: a boolean[][] to a boolean[]
this.setEquals(false);
}
// 'Switch' on type of array, to dispatch to the correct handler
// This handles multi dimensional arrays of the same depth
else if (lhs instanceof long[]) {
append((long[]) lhs, (long[]) rhs);
} else if (lhs instanceof int[]) {
append((int[]) lhs, (int[]) rhs);
} else if (lhs instanceof short[]) {
append((short[]) lhs, (short[]) rhs);
} else if (lhs instanceof char[]) {
append((char[]) lhs, (char[]) rhs);
} else if (lhs instanceof byte[]) {
append((byte[]) lhs, (byte[]) rhs);
} else if (lhs instanceof double[]) {
append((double[]) lhs, (double[]) rhs);
} else if (lhs instanceof float[]) {
append((float[]) lhs, (float[]) rhs);
} else if (lhs instanceof boolean[]) {
append((boolean[]) lhs, (boolean[]) rhs);
} else {
// Not an array of primitives
append((Object[]) lhs, (Object[]) rhs);
}
return this;
}
/**
* <p>
* Test if two <code>long</code> s are equal.
* </p>
*
* @param lhs
* the left hand <code>long</code>
* @param rhs
* the right hand <code>long</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(long lhs, long rhs) {
if (isEquals == false) {
return this;
}
isEquals = (lhs == rhs);
return this;
}
/**
* <p>Test if two <code>int</code>s are equal.</p>
*
* @param lhs the left hand <code>int</code>
* @param rhs the right hand <code>int</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(int lhs, int rhs) {
if (isEquals == false) {
return this;
}
isEquals = (lhs == rhs);
return this;
}
/**
* <p>Test if two <code>short</code>s are equal.</p>
*
* @param lhs the left hand <code>short</code>
* @param rhs the right hand <code>short</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(short lhs, short rhs) {
if (isEquals == false) {
return this;
}
isEquals = (lhs == rhs);
return this;
}
/**
* <p>Test if two <code>char</code>s are equal.</p>
*
* @param lhs the left hand <code>char</code>
* @param rhs the right hand <code>char</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(char lhs, char rhs) {
if (isEquals == false) {
return this;
}
isEquals = (lhs == rhs);
return this;
}
/**
* <p>Test if two <code>byte</code>s are equal.</p>
*
* @param lhs the left hand <code>byte</code>
* @param rhs the right hand <code>byte</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(byte lhs, byte rhs) {
if (isEquals == false) {
return this;
}
isEquals = (lhs == rhs);
return this;
}
/**
* <p>Test if two <code>double</code>s are equal by testing that the
* pattern of bits returned by <code>doubleToLong</code> are equal.</p>
*
* <p>This handles NaNs, Infinities, and <code>-0.0</code>.</p>
*
* <p>It is compatible with the hash code generated by
* <code>HashCodeBuilder</code>.</p>
*
* @param lhs the left hand <code>double</code>
* @param rhs the right hand <code>double</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(double lhs, double rhs) {
if (isEquals == false) {
return this;
}
return append(Double.doubleToLongBits(lhs), Double.doubleToLongBits(rhs));
}
/**
* <p>Test if two <code>float</code>s are equal byt testing that the
* pattern of bits returned by doubleToLong are equal.</p>
*
* <p>This handles NaNs, Infinities, and <code>-0.0</code>.</p>
*
* <p>It is compatible with the hash code generated by
* <code>HashCodeBuilder</code>.</p>
*
* @param lhs the left hand <code>float</code>
* @param rhs the right hand <code>float</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(float lhs, float rhs) {
if (isEquals == false) {
return this;
}
return append(Float.floatToIntBits(lhs), Float.floatToIntBits(rhs));
}
/**
* <p>Test if two <code>booleans</code>s are equal.</p>
*
* @param lhs the left hand <code>boolean</code>
* @param rhs the right hand <code>boolean</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(boolean lhs, boolean rhs) {
if (isEquals == false) {
return this;
}
isEquals = (lhs == rhs);
return this;
}
/**
* <p>Performs a deep comparison of two <code>Object</code> arrays.</p>
*
* <p>This also will be called for the top level of
* multi-dimensional, ragged, and multi-typed arrays.</p>
*
* @param lhs the left hand <code>Object[]</code>
* @param rhs the right hand <code>Object[]</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(Object[] lhs, Object[] rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
if (lhs.length != rhs.length) {
this.setEquals(false);
return this;
}
for (int i = 0; i < lhs.length && isEquals; ++i) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Deep comparison of array of <code>long</code>. Length and all
* values are compared.</p>
*
* <p>The method {@link #append(long, long)} is used.</p>
*
* @param lhs the left hand <code>long[]</code>
* @param rhs the right hand <code>long[]</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(long[] lhs, long[] rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
if (lhs.length != rhs.length) {
this.setEquals(false);
return this;
}
for (int i = 0; i < lhs.length && isEquals; ++i) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Deep comparison of array of <code>int</code>. Length and all
* values are compared.</p>
*
* <p>The method {@link #append(int, int)} is used.</p>
*
* @param lhs the left hand <code>int[]</code>
* @param rhs the right hand <code>int[]</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(int[] lhs, int[] rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
if (lhs.length != rhs.length) {
this.setEquals(false);
return this;
}
for (int i = 0; i < lhs.length && isEquals; ++i) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Deep comparison of array of <code>short</code>. Length and all
* values are compared.</p>
*
* <p>The method {@link #append(short, short)} is used.</p>
*
* @param lhs the left hand <code>short[]</code>
* @param rhs the right hand <code>short[]</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(short[] lhs, short[] rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
if (lhs.length != rhs.length) {
this.setEquals(false);
return this;
}
for (int i = 0; i < lhs.length && isEquals; ++i) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Deep comparison of array of <code>char</code>. Length and all
* values are compared.</p>
*
* <p>The method {@link #append(char, char)} is used.</p>
*
* @param lhs the left hand <code>char[]</code>
* @param rhs the right hand <code>char[]</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(char[] lhs, char[] rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
if (lhs.length != rhs.length) {
this.setEquals(false);
return this;
}
for (int i = 0; i < lhs.length && isEquals; ++i) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Deep comparison of array of <code>byte</code>. Length and all
* values are compared.</p>
*
* <p>The method {@link #append(byte, byte)} is used.</p>
*
* @param lhs the left hand <code>byte[]</code>
* @param rhs the right hand <code>byte[]</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(byte[] lhs, byte[] rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
if (lhs.length != rhs.length) {
this.setEquals(false);
return this;
}
for (int i = 0; i < lhs.length && isEquals; ++i) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Deep comparison of array of <code>double</code>. Length and all
* values are compared.</p>
*
* <p>The method {@link #append(double, double)} is used.</p>
*
* @param lhs the left hand <code>double[]</code>
* @param rhs the right hand <code>double[]</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(double[] lhs, double[] rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
if (lhs.length != rhs.length) {
this.setEquals(false);
return this;
}
for (int i = 0; i < lhs.length && isEquals; ++i) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Deep comparison of array of <code>float</code>. Length and all
* values are compared.</p>
*
* <p>The method {@link #append(float, float)} is used.</p>
*
* @param lhs the left hand <code>float[]</code>
* @param rhs the right hand <code>float[]</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(float[] lhs, float[] rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
if (lhs.length != rhs.length) {
this.setEquals(false);
return this;
}
for (int i = 0; i < lhs.length && isEquals; ++i) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Deep comparison of array of <code>boolean</code>. Length and all
* values are compared.</p>
*
* <p>The method {@link #append(boolean, boolean)} is used.</p>
*
* @param lhs the left hand <code>boolean[]</code>
* @param rhs the right hand <code>boolean[]</code>
* @return EqualsBuilder - used to chain calls.
*/
public EqualsBuilder append(boolean[] lhs, boolean[] rhs) {
if (isEquals == false) {
return this;
}
if (lhs == rhs) {
return this;
}
if (lhs == null || rhs == null) {
this.setEquals(false);
return this;
}
if (lhs.length != rhs.length) {
this.setEquals(false);
return this;
}
for (int i = 0; i < lhs.length && isEquals; ++i) {
append(lhs[i], rhs[i]);
}
return this;
}
/**
* <p>Returns <code>true</code> if the fields that have been checked
* are all equal.</p>
*
* @return boolean
*/
public boolean isEquals() {
return this.isEquals;
}
/**
* <p>Returns <code>true</code> if the fields that have been checked
* are all equal.</p>
*
* @return <code>true</code> if all of the fields that have been checked
* are equal, <code>false</code> otherwise.
*
* @since 3.0
*/
public Boolean build() {
return Boolean.valueOf(isEquals());
}
/**
* Sets the <code>isEquals</code> value.
*
* @param isEquals The value to set.
* @since 2.1
*/
protected void setEquals(boolean isEquals) {
this.isEquals = isEquals;
}
/**
* Reset the EqualsBuilder so you can use the same object again
* @since 2.5
*/
public void reset() {
this.isEquals = true;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.builder;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import external.org.apache.commons.lang3.ArrayUtils;
/**
* <p>
* Assists in implementing {@link Object#hashCode()} methods.
* </p>
*
* <p>
* This class enables a good <code>hashCode</code> method to be built for any class. It follows the rules laid out in
* the book <a href="http://java.sun.com/docs/books/effective/index.html">Effective Java</a> by Joshua Bloch. Writing a
* good <code>hashCode</code> method is actually quite difficult. This class aims to simplify the process.
* </p>
*
* <p>
* The following is the approach taken. When appending a data field, the current total is multiplied by the
* multiplier then a relevant value
* for that data type is added. For example, if the current hashCode is 17, and the multiplier is 37, then
* appending the integer 45 will create a hashcode of 674, namely 17 * 37 + 45.
* </p>
*
* <p>
* All relevant fields from the object should be included in the <code>hashCode</code> method. Derived fields may be
* excluded. In general, any field used in the <code>equals</code> method must be used in the <code>hashCode</code>
* method.
* </p>
*
* <p>
* To use this class write code as follows:
* </p>
*
* <pre>
* public class Person {
* String name;
* int age;
* boolean smoker;
* ...
*
* public int hashCode() {
* // you pick a hard-coded, randomly chosen, non-zero, odd number
* // ideally different for each class
* return new HashCodeBuilder(17, 37).
* append(name).
* append(age).
* append(smoker).
* toHashCode();
* }
* }
* </pre>
*
* <p>
* If required, the superclass <code>hashCode()</code> can be added using {@link #appendSuper}.
* </p>
*
* <p>
* Alternatively, there is a method that uses reflection to determine the fields to test. Because these fields are
* usually private, the method, <code>reflectionHashCode</code>, uses <code>AccessibleObject.setAccessible</code>
* to change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions
* are set up correctly. It is also slower than testing explicitly.
* </p>
*
* <p>
* A typical invocation for this method would look like:
* </p>
*
* <pre>
* public int hashCode() {
* return HashCodeBuilder.reflectionHashCode(this);
* }
* </pre>
*
* @since 1.0
* @version $Id: HashCodeBuilder.java 1144929 2011-07-10 18:26:16Z ggregory $
*/
public class HashCodeBuilder implements Builder<Integer> {
/**
* <p>
* A registry of objects used by reflection methods to detect cyclical object references and avoid infinite loops.
* </p>
*
* @since 2.3
*/
private static final ThreadLocal<Set<IDKey>> REGISTRY = new ThreadLocal<Set<IDKey>>();
/*
* NOTE: we cannot store the actual objects in a HashSet, as that would use the very hashCode()
* we are in the process of calculating.
*
* So we generate a one-to-one mapping from the original object to a new object.
*
* Now HashSet uses equals() to determine if two elements with the same hashcode really
* are equal, so we also need to ensure that the replacement objects are only equal
* if the original objects are identical.
*
* The original implementation (2.4 and before) used the System.indentityHashCode()
* method - however this is not guaranteed to generate unique ids (e.g. LANG-459)
*
* We now use the IDKey helper class (adapted from org.apache.axis.utils.IDKey)
* to disambiguate the duplicate ids.
*/
/**
* <p>
* Returns the registry of objects being traversed by the reflection methods in the current thread.
* </p>
*
* @return Set the registry of objects being traversed
* @since 2.3
*/
static Set<IDKey> getRegistry() {
return REGISTRY.get();
}
/**
* <p>
* Returns <code>true</code> if the registry contains the given object. Used by the reflection methods to avoid
* infinite loops.
* </p>
*
* @param value
* The object to lookup in the registry.
* @return boolean <code>true</code> if the registry contains the given object.
* @since 2.3
*/
static boolean isRegistered(Object value) {
Set<IDKey> registry = getRegistry();
return registry != null && registry.contains(new IDKey(value));
}
/**
* <p>
* Appends the fields and values defined by the given object of the given <code>Class</code>.
* </p>
*
* @param object
* the object to append details of
* @param clazz
* the class to append details of
* @param builder
* the builder to append to
* @param useTransients
* whether to use transient fields
* @param excludeFields
* Collection of String field names to exclude from use in calculation of hash code
*/
private static void reflectionAppend(Object object, Class<?> clazz, HashCodeBuilder builder, boolean useTransients,
String[] excludeFields) {
if (isRegistered(object)) {
return;
}
try {
register(object);
Field[] fields = clazz.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
for (Field field : fields) {
if (!ArrayUtils.contains(excludeFields, field.getName())
&& (field.getName().indexOf('$') == -1)
&& (useTransients || !Modifier.isTransient(field.getModifiers()))
&& (!Modifier.isStatic(field.getModifiers()))) {
try {
Object fieldValue = field.get(object);
builder.append(fieldValue);
} catch (IllegalAccessException e) {
// this can't happen. Would get a Security exception instead
// throw a runtime exception in case the impossible happens.
throw new InternalError("Unexpected IllegalAccessException");
}
}
}
} finally {
unregister(object);
}
}
/**
* <p>
* This method uses reflection to build a valid hash code.
* </p>
*
* <p>
* It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will
* throw a security exception if run under a security manager, if the permissions are not set up correctly. It is
* also not as efficient as testing explicitly.
* </p>
*
* <p>
* Transient members will be not be used, as they are likely derived fields, and not part of the value of the
* <code>Object</code>.
* </p>
*
* <p>
* Static fields will not be tested. Superclass fields will be included.
* </p>
*
* <p>
* Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class,
* however this is not vital. Prime numbers are preferred, especially for the multiplier.
* </p>
*
* @param initialNonZeroOddNumber
* a non-zero, odd number used as the initial value
* @param multiplierNonZeroOddNumber
* a non-zero, odd number used as the multiplier
* @param object
* the Object to create a <code>hashCode</code> for
* @return int hash code
* @throws IllegalArgumentException
* if the Object is <code>null</code>
* @throws IllegalArgumentException
* if the number is zero or even
*/
public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object) {
return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, false, null);
}
/**
* <p>
* This method uses reflection to build a valid hash code.
* </p>
*
* <p>
* It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will
* throw a security exception if run under a security manager, if the permissions are not set up correctly. It is
* also not as efficient as testing explicitly.
* </p>
*
* <p>
* If the TestTransients parameter is set to <code>true</code>, transient members will be tested, otherwise they
* are ignored, as they are likely derived fields, and not part of the value of the <code>Object</code>.
* </p>
*
* <p>
* Static fields will not be tested. Superclass fields will be included.
* </p>
*
* <p>
* Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class,
* however this is not vital. Prime numbers are preferred, especially for the multiplier.
* </p>
*
* @param initialNonZeroOddNumber
* a non-zero, odd number used as the initial value
* @param multiplierNonZeroOddNumber
* a non-zero, odd number used as the multiplier
* @param object
* the Object to create a <code>hashCode</code> for
* @param testTransients
* whether to include transient fields
* @return int hash code
* @throws IllegalArgumentException
* if the Object is <code>null</code>
* @throws IllegalArgumentException
* if the number is zero or even
*/
public static int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, Object object,
boolean testTransients) {
return reflectionHashCode(initialNonZeroOddNumber, multiplierNonZeroOddNumber, object, testTransients, null);
}
/**
* <p>
* This method uses reflection to build a valid hash code.
* </p>
*
* <p>
* It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will
* throw a security exception if run under a security manager, if the permissions are not set up correctly. It is
* also not as efficient as testing explicitly.
* </p>
*
* <p>
* If the TestTransients parameter is set to <code>true</code>, transient members will be tested, otherwise they
* are ignored, as they are likely derived fields, and not part of the value of the <code>Object</code>.
* </p>
*
* <p>
* Static fields will not be included. Superclass fields will be included up to and including the specified
* superclass. A null superclass is treated as java.lang.Object.
* </p>
*
* <p>
* Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class,
* however this is not vital. Prime numbers are preferred, especially for the multiplier.
* </p>
*
* @param <T>
* the type of the object involved
* @param initialNonZeroOddNumber
* a non-zero, odd number used as the initial value
* @param multiplierNonZeroOddNumber
* a non-zero, odd number used as the multiplier
* @param object
* the Object to create a <code>hashCode</code> for
* @param testTransients
* whether to include transient fields
* @param reflectUpToClass
* the superclass to reflect up to (inclusive), may be <code>null</code>
* @param excludeFields
* array of field names to exclude from use in calculation of hash code
* @return int hash code
* @throws IllegalArgumentException
* if the Object is <code>null</code>
* @throws IllegalArgumentException
* if the number is zero or even
* @since 2.0
*/
public static <T> int reflectionHashCode(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber, T object,
boolean testTransients, Class<? super T> reflectUpToClass, String... excludeFields) {
if (object == null) {
throw new IllegalArgumentException("The object to build a hash code for must not be null");
}
HashCodeBuilder builder = new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber);
Class<?> clazz = object.getClass();
reflectionAppend(object, clazz, builder, testTransients, excludeFields);
while (clazz.getSuperclass() != null && clazz != reflectUpToClass) {
clazz = clazz.getSuperclass();
reflectionAppend(object, clazz, builder, testTransients, excludeFields);
}
return builder.toHashCode();
}
/**
* <p>
* This method uses reflection to build a valid hash code.
* </p>
*
* <p>
* This constructor uses two hard coded choices for the constants needed to build a hash code.
* </p>
*
* <p>
* It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will
* throw a security exception if run under a security manager, if the permissions are not set up correctly. It is
* also not as efficient as testing explicitly.
* </p>
*
* <P>
* If the TestTransients parameter is set to <code>true</code>, transient members will be tested, otherwise they
* are ignored, as they are likely derived fields, and not part of the value of the <code>Object</code>.
* </p>
*
* <p>
* Static fields will not be tested. Superclass fields will be included.
* </p>
*
* @param object
* the Object to create a <code>hashCode</code> for
* @param testTransients
* whether to include transient fields
* @return int hash code
* @throws IllegalArgumentException
* if the object is <code>null</code>
*/
public static int reflectionHashCode(Object object, boolean testTransients) {
return reflectionHashCode(17, 37, object, testTransients, null);
}
/**
* <p>
* This method uses reflection to build a valid hash code.
* </p>
*
* <p>
* This constructor uses two hard coded choices for the constants needed to build a hash code.
* </p>
*
* <p>
* It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will
* throw a security exception if run under a security manager, if the permissions are not set up correctly. It is
* also not as efficient as testing explicitly.
* </p>
*
* <p>
* Transient members will be not be used, as they are likely derived fields, and not part of the value of the
* <code>Object</code>.
* </p>
*
* <p>
* Static fields will not be tested. Superclass fields will be included.
* </p>
*
* @param object
* the Object to create a <code>hashCode</code> for
* @param excludeFields
* Collection of String field names to exclude from use in calculation of hash code
* @return int hash code
* @throws IllegalArgumentException
* if the object is <code>null</code>
*/
public static int reflectionHashCode(Object object, Collection<String> excludeFields) {
return reflectionHashCode(object, ReflectionToStringBuilder.toNoNullStringArray(excludeFields));
}
// -------------------------------------------------------------------------
/**
* <p>
* This method uses reflection to build a valid hash code.
* </p>
*
* <p>
* This constructor uses two hard coded choices for the constants needed to build a hash code.
* </p>
*
* <p>
* It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will
* throw a security exception if run under a security manager, if the permissions are not set up correctly. It is
* also not as efficient as testing explicitly.
* </p>
*
* <p>
* Transient members will be not be used, as they are likely derived fields, and not part of the value of the
* <code>Object</code>.
* </p>
*
* <p>
* Static fields will not be tested. Superclass fields will be included.
* </p>
*
* @param object
* the Object to create a <code>hashCode</code> for
* @param excludeFields
* array of field names to exclude from use in calculation of hash code
* @return int hash code
* @throws IllegalArgumentException
* if the object is <code>null</code>
*/
public static int reflectionHashCode(Object object, String... excludeFields) {
return reflectionHashCode(17, 37, object, false, null, excludeFields);
}
/**
* <p>
* Registers the given object. Used by the reflection methods to avoid infinite loops.
* </p>
*
* @param value
* The object to register.
*/
static void register(Object value) {
synchronized (HashCodeBuilder.class) {
if (getRegistry() == null) {
REGISTRY.set(new HashSet<IDKey>());
}
}
getRegistry().add(new IDKey(value));
}
/**
* <p>
* Unregisters the given object.
* </p>
*
* <p>
* Used by the reflection methods to avoid infinite loops.
*
* @param value
* The object to unregister.
* @since 2.3
*/
static void unregister(Object value) {
Set<IDKey> registry = getRegistry();
if (registry != null) {
registry.remove(new IDKey(value));
synchronized (HashCodeBuilder.class) {
//read again
registry = getRegistry();
if (registry != null && registry.isEmpty()) {
REGISTRY.remove();
}
}
}
}
/**
* Constant to use in building the hashCode.
*/
private final int iConstant;
/**
* Running total of the hashCode.
*/
private int iTotal = 0;
/**
* <p>
* Uses two hard coded choices for the constants needed to build a <code>hashCode</code>.
* </p>
*/
public HashCodeBuilder() {
iConstant = 37;
iTotal = 17;
}
/**
* <p>
* Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class,
* however this is not vital.
* </p>
*
* <p>
* Prime numbers are preferred, especially for the multiplier.
* </p>
*
* @param initialNonZeroOddNumber
* a non-zero, odd number used as the initial value
* @param multiplierNonZeroOddNumber
* a non-zero, odd number used as the multiplier
* @throws IllegalArgumentException
* if the number is zero or even
*/
public HashCodeBuilder(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber) {
if (initialNonZeroOddNumber == 0) {
throw new IllegalArgumentException("HashCodeBuilder requires a non zero initial value");
}
if (initialNonZeroOddNumber % 2 == 0) {
throw new IllegalArgumentException("HashCodeBuilder requires an odd initial value");
}
if (multiplierNonZeroOddNumber == 0) {
throw new IllegalArgumentException("HashCodeBuilder requires a non zero multiplier");
}
if (multiplierNonZeroOddNumber % 2 == 0) {
throw new IllegalArgumentException("HashCodeBuilder requires an odd multiplier");
}
iConstant = multiplierNonZeroOddNumber;
iTotal = initialNonZeroOddNumber;
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>boolean</code>.
* </p>
* <p>
* This adds <code>1</code> when true, and <code>0</code> when false to the <code>hashCode</code>.
* </p>
* <p>
* This is in contrast to the standard <code>java.lang.Boolean.hashCode</code> handling, which computes
* a <code>hashCode</code> value of <code>1231</code> for <code>java.lang.Boolean</code> instances
* that represent <code>true</code> or <code>1237</code> for <code>java.lang.Boolean</code> instances
* that represent <code>false</code>.
* </p>
* <p>
* This is in accordance with the <quote>Effective Java</quote> design.
* </p>
*
* @param value
* the boolean to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(boolean value) {
iTotal = iTotal * iConstant + (value ? 0 : 1);
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>boolean</code> array.
* </p>
*
* @param array
* the array to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(boolean[] array) {
if (array == null) {
iTotal = iTotal * iConstant;
} else {
for (boolean element : array) {
append(element);
}
}
return this;
}
// -------------------------------------------------------------------------
/**
* <p>
* Append a <code>hashCode</code> for a <code>byte</code>.
* </p>
*
* @param value
* the byte to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(byte value) {
iTotal = iTotal * iConstant + value;
return this;
}
// -------------------------------------------------------------------------
/**
* <p>
* Append a <code>hashCode</code> for a <code>byte</code> array.
* </p>
*
* @param array
* the array to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(byte[] array) {
if (array == null) {
iTotal = iTotal * iConstant;
} else {
for (byte element : array) {
append(element);
}
}
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>char</code>.
* </p>
*
* @param value
* the char to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(char value) {
iTotal = iTotal * iConstant + value;
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>char</code> array.
* </p>
*
* @param array
* the array to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(char[] array) {
if (array == null) {
iTotal = iTotal * iConstant;
} else {
for (char element : array) {
append(element);
}
}
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>double</code>.
* </p>
*
* @param value
* the double to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(double value) {
return append(Double.doubleToLongBits(value));
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>double</code> array.
* </p>
*
* @param array
* the array to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(double[] array) {
if (array == null) {
iTotal = iTotal * iConstant;
} else {
for (double element : array) {
append(element);
}
}
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>float</code>.
* </p>
*
* @param value
* the float to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(float value) {
iTotal = iTotal * iConstant + Float.floatToIntBits(value);
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>float</code> array.
* </p>
*
* @param array
* the array to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(float[] array) {
if (array == null) {
iTotal = iTotal * iConstant;
} else {
for (float element : array) {
append(element);
}
}
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for an <code>int</code>.
* </p>
*
* @param value
* the int to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(int value) {
iTotal = iTotal * iConstant + value;
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for an <code>int</code> array.
* </p>
*
* @param array
* the array to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(int[] array) {
if (array == null) {
iTotal = iTotal * iConstant;
} else {
for (int element : array) {
append(element);
}
}
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>long</code>.
* </p>
*
* @param value
* the long to add to the <code>hashCode</code>
* @return this
*/
// NOTE: This method uses >> and not >>> as Effective Java and
// Long.hashCode do. Ideally we should switch to >>> at
// some stage. There are backwards compat issues, so
// that will have to wait for the time being. cf LANG-342.
public HashCodeBuilder append(long value) {
iTotal = iTotal * iConstant + ((int) (value ^ (value >> 32)));
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>long</code> array.
* </p>
*
* @param array
* the array to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(long[] array) {
if (array == null) {
iTotal = iTotal * iConstant;
} else {
for (long element : array) {
append(element);
}
}
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for an <code>Object</code>.
* </p>
*
* @param object
* the Object to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(Object object) {
if (object == null) {
iTotal = iTotal * iConstant;
} else {
if(object.getClass().isArray()) {
// 'Switch' on type of array, to dispatch to the correct handler
// This handles multi dimensional arrays
if (object instanceof long[]) {
append((long[]) object);
} else if (object instanceof int[]) {
append((int[]) object);
} else if (object instanceof short[]) {
append((short[]) object);
} else if (object instanceof char[]) {
append((char[]) object);
} else if (object instanceof byte[]) {
append((byte[]) object);
} else if (object instanceof double[]) {
append((double[]) object);
} else if (object instanceof float[]) {
append((float[]) object);
} else if (object instanceof boolean[]) {
append((boolean[]) object);
} else {
// Not an array of primitives
append((Object[]) object);
}
} else {
iTotal = iTotal * iConstant + object.hashCode();
}
}
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for an <code>Object</code> array.
* </p>
*
* @param array
* the array to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(Object[] array) {
if (array == null) {
iTotal = iTotal * iConstant;
} else {
for (Object element : array) {
append(element);
}
}
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>short</code>.
* </p>
*
* @param value
* the short to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(short value) {
iTotal = iTotal * iConstant + value;
return this;
}
/**
* <p>
* Append a <code>hashCode</code> for a <code>short</code> array.
* </p>
*
* @param array
* the array to add to the <code>hashCode</code>
* @return this
*/
public HashCodeBuilder append(short[] array) {
if (array == null) {
iTotal = iTotal * iConstant;
} else {
for (short element : array) {
append(element);
}
}
return this;
}
/**
* <p>
* Adds the result of super.hashCode() to this builder.
* </p>
*
* @param superHashCode
* the result of calling <code>super.hashCode()</code>
* @return this HashCodeBuilder, used to chain calls.
* @since 2.0
*/
public HashCodeBuilder appendSuper(int superHashCode) {
iTotal = iTotal * iConstant + superHashCode;
return this;
}
/**
* <p>
* Return the computed <code>hashCode</code>.
* </p>
*
* @return <code>hashCode</code> based on the fields appended
*/
public int toHashCode() {
return iTotal;
}
/**
* Returns the computed <code>hashCode</code>.
*
* @return <code>hashCode</code> based on the fields appended
*
* @since 3.0
*/
public Integer build() {
return Integer.valueOf(toHashCode());
}
/**
* <p>
* The computed <code>hashCode</code> from toHashCode() is returned due to the likelihood
* of bugs in mis-calling toHashCode() and the unlikeliness of it mattering what the hashCode for
* HashCodeBuilder itself is.</p>
*
* @return <code>hashCode</code> based on the fields appended
* @since 2.5
*/
@Override
public int hashCode() {
return toHashCode();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package external.org.apache.commons.lang3.builder;
// adapted from org.apache.axis.utils.IDKey
/**
* Wrap an identity key (System.identityHashCode())
* so that an object can only be equal() to itself.
*
* This is necessary to disambiguate the occasional duplicate
* identityHashCodes that can occur.
*
*/
final class IDKey {
private final Object value;
private final int id;
/**
* Constructor for IDKey
* @param _value The value
*/
public IDKey(Object _value) {
// This is the Object hashcode
id = System.identityHashCode(_value);
// There have been some cases (LANG-459) that return the
// same identity hash code for different objects. So
// the value is also added to disambiguate these cases.
value = _value;
}
/**
* returns hashcode - i.e. the system identity hashcode.
* @return the hashcode
*/
@Override
public int hashCode() {
return id;
}
/**
* checks if instances are equal
* @param other The other object to compare to
* @return if the instances are for the same object
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof IDKey)) {
return false;
}
IDKey idKey = (IDKey) other;
if (id != idKey.id) {
return false;
}
// Note that identity equals is used.
return value == idKey.value;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.builder;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import external.org.apache.commons.lang3.ArrayUtils;
import external.org.apache.commons.lang3.ClassUtils;
/**
* <p>
* Assists in implementing {@link Object#toString()} methods using reflection.
* </p>
* <p>
* This class uses reflection to determine the fields to append. Because these fields are usually private, the class
* uses {@link AccessibleObject#setAccessible(AccessibleObject[], boolean)} to
* change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are
* set up correctly.
* </p>
* <p>
* Using reflection to access (private) fields circumvents any synchronization protection guarding access to these
* fields. If a toString method cannot safely read a field, you should exclude it from the toString method, or use
* synchronization consistent with the class' lock management around the invocation of the method. Take special care to
* exclude non-thread-safe collection classes, because these classes may throw ConcurrentModificationException if
* modified while the toString method is executing.
* </p>
* <p>
* A typical invocation for this method would look like:
* </p>
* <pre>
* public String toString() {
* return ReflectionToStringBuilder.toString(this);
* }
* </pre>
* <p>
* You can also use the builder to debug 3rd party objects:
* </p>
* <pre>
* System.out.println(&quot;An object: &quot; + ReflectionToStringBuilder.toString(anObject));
* </pre>
* <p>
* A subclass can control field output by overriding the methods:
* <ul>
* <li>{@link #accept(Field)}</li>
* <li>{@link #getValue(Field)}</li>
* </ul>
* </p>
* <p>
* For example, this method does <i>not</i> include the <code>password</code> field in the returned <code>String</code>:
* </p>
* <pre>
* public String toString() {
* return (new ReflectionToStringBuilder(this) {
* protected boolean accept(Field f) {
* return super.accept(f) &amp;&amp; !f.getName().equals(&quot;password&quot;);
* }
* }).toString();
* }
* </pre>
* <p>
* The exact format of the <code>toString</code> is determined by the {@link ToStringStyle} passed into the constructor.
* </p>
*
* @since 2.0
* @version $Id: ReflectionToStringBuilder.java 1200177 2011-11-10 06:14:33Z ggregory $
*/
public class ReflectionToStringBuilder extends ToStringBuilder {
/**
* <p>
* Builds a <code>toString</code> value using the default <code>ToStringStyle</code> through reflection.
* </p>
*
* <p>
* It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will
* throw a security exception if run under a security manager, if the permissions are not set up correctly. It is
* also not as efficient as testing explicitly.
* </p>
*
* <p>
* Transient members will be not be included, as they are likely derived. Static fields will not be included.
* Superclass fields will be appended.
* </p>
*
* @param object
* the Object to be output
* @return the String result
* @throws IllegalArgumentException
* if the Object is <code>null</code>
*/
public static String toString(Object object) {
return toString(object, null, false, false, null);
}
/**
* <p>
* Builds a <code>toString</code> value through reflection.
* </p>
*
* <p>
* It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will
* throw a security exception if run under a security manager, if the permissions are not set up correctly. It is
* also not as efficient as testing explicitly.
* </p>
*
* <p>
* Transient members will be not be included, as they are likely derived. Static fields will not be included.
* Superclass fields will be appended.
* </p>
*
* <p>
* If the style is <code>null</code>, the default <code>ToStringStyle</code> is used.
* </p>
*
* @param object
* the Object to be output
* @param style
* the style of the <code>toString</code> to create, may be <code>null</code>
* @return the String result
* @throws IllegalArgumentException
* if the Object or <code>ToStringStyle</code> is <code>null</code>
*/
public static String toString(Object object, ToStringStyle style) {
return toString(object, style, false, false, null);
}
/**
* <p>
* Builds a <code>toString</code> value through reflection.
* </p>
*
* <p>
* It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will
* throw a security exception if run under a security manager, if the permissions are not set up correctly. It is
* also not as efficient as testing explicitly.
* </p>
*
* <p>
* If the <code>outputTransients</code> is <code>true</code>, transient members will be output, otherwise they
* are ignored, as they are likely derived fields, and not part of the value of the Object.
* </p>
*
* <p>
* Static fields will not be included. Superclass fields will be appended.
* </p>
*
* <p>
* If the style is <code>null</code>, the default <code>ToStringStyle</code> is used.
* </p>
*
* @param object
* the Object to be output
* @param style
* the style of the <code>toString</code> to create, may be <code>null</code>
* @param outputTransients
* whether to include transient fields
* @return the String result
* @throws IllegalArgumentException
* if the Object is <code>null</code>
*/
public static String toString(Object object, ToStringStyle style, boolean outputTransients) {
return toString(object, style, outputTransients, false, null);
}
/**
* <p>
* Builds a <code>toString</code> value through reflection.
* </p>
*
* <p>
* It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will
* throw a security exception if run under a security manager, if the permissions are not set up correctly. It is
* also not as efficient as testing explicitly.
* </p>
*
* <p>
* If the <code>outputTransients</code> is <code>true</code>, transient fields will be output, otherwise they
* are ignored, as they are likely derived fields, and not part of the value of the Object.
* </p>
*
* <p>
* If the <code>outputStatics</code> is <code>true</code>, static fields will be output, otherwise they are
* ignored.
* </p>
*
* <p>
* Static fields will not be included. Superclass fields will be appended.
* </p>
*
* <p>
* If the style is <code>null</code>, the default <code>ToStringStyle</code> is used.
* </p>
*
* @param object
* the Object to be output
* @param style
* the style of the <code>toString</code> to create, may be <code>null</code>
* @param outputTransients
* whether to include transient fields
* @param outputStatics
* whether to include transient fields
* @return the String result
* @throws IllegalArgumentException
* if the Object is <code>null</code>
* @since 2.1
*/
public static String toString(Object object, ToStringStyle style, boolean outputTransients, boolean outputStatics) {
return toString(object, style, outputTransients, outputStatics, null);
}
/**
* <p>
* Builds a <code>toString</code> value through reflection.
* </p>
*
* <p>
* It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will
* throw a security exception if run under a security manager, if the permissions are not set up correctly. It is
* also not as efficient as testing explicitly.
* </p>
*
* <p>
* If the <code>outputTransients</code> is <code>true</code>, transient fields will be output, otherwise they
* are ignored, as they are likely derived fields, and not part of the value of the Object.
* </p>
*
* <p>
* If the <code>outputStatics</code> is <code>true</code>, static fields will be output, otherwise they are
* ignored.
* </p>
*
* <p>
* Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as
* <code>java.lang.Object</code>.
* </p>
*
* <p>
* If the style is <code>null</code>, the default <code>ToStringStyle</code> is used.
* </p>
*
* @param <T>
* the type of the object
* @param object
* the Object to be output
* @param style
* the style of the <code>toString</code> to create, may be <code>null</code>
* @param outputTransients
* whether to include transient fields
* @param outputStatics
* whether to include static fields
* @param reflectUpToClass
* the superclass to reflect up to (inclusive), may be <code>null</code>
* @return the String result
* @throws IllegalArgumentException
* if the Object is <code>null</code>
* @since 2.1
*/
public static <T> String toString(
T object, ToStringStyle style, boolean outputTransients,
boolean outputStatics, Class<? super T> reflectUpToClass) {
return new ReflectionToStringBuilder(object, style, null, reflectUpToClass, outputTransients, outputStatics)
.toString();
}
/**
* Builds a String for a toString method excluding the given field names.
*
* @param object
* The object to "toString".
* @param excludeFieldNames
* The field names to exclude. Null excludes nothing.
* @return The toString value.
*/
public static String toStringExclude(Object object, Collection<String> excludeFieldNames) {
return toStringExclude(object, toNoNullStringArray(excludeFieldNames));
}
/**
* Converts the given Collection into an array of Strings. The returned array does not contain <code>null</code>
* entries. Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException} if an array element
* is <code>null</code>.
*
* @param collection
* The collection to convert
* @return A new array of Strings.
*/
static String[] toNoNullStringArray(Collection<String> collection) {
if (collection == null) {
return ArrayUtils.EMPTY_STRING_ARRAY;
}
return toNoNullStringArray(collection.toArray());
}
/**
* Returns a new array of Strings without null elements. Internal method used to normalize exclude lists
* (arrays and collections). Note that {@link Arrays#sort(Object[])} will throw an {@link NullPointerException}
* if an array element is <code>null</code>.
*
* @param array
* The array to check
* @return The given array or a new array without null.
*/
static String[] toNoNullStringArray(Object[] array) {
List<String> list = new ArrayList<String>(array.length);
for (Object e : array) {
if (e != null) {
list.add(e.toString());
}
}
return list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
/**
* Builds a String for a toString method excluding the given field names.
*
* @param object
* The object to "toString".
* @param excludeFieldNames
* The field names to exclude
* @return The toString value.
*/
public static String toStringExclude(Object object, String... excludeFieldNames) {
return new ReflectionToStringBuilder(object).setExcludeFieldNames(excludeFieldNames).toString();
}
/**
* Whether or not to append static fields.
*/
private boolean appendStatics = false;
/**
* Whether or not to append transient fields.
*/
private boolean appendTransients = false;
/**
* Which field names to exclude from output. Intended for fields like <code>"password"</code>.
*
* @since 3.0 this is protected instead of private
*/
protected String[] excludeFieldNames;
/**
* The last super class to stop appending fields for.
*/
private Class<?> upToClass = null;
/**
* <p>
* Constructor.
* </p>
*
* <p>
* This constructor outputs using the default style set with <code>setDefaultStyle</code>.
* </p>
*
* @param object
* the Object to build a <code>toString</code> for, must not be <code>null</code>
* @throws IllegalArgumentException
* if the Object passed in is <code>null</code>
*/
public ReflectionToStringBuilder(Object object) {
super(object);
}
/**
* <p>
* Constructor.
* </p>
*
* <p>
* If the style is <code>null</code>, the default style is used.
* </p>
*
* @param object
* the Object to build a <code>toString</code> for, must not be <code>null</code>
* @param style
* the style of the <code>toString</code> to create, may be <code>null</code>
* @throws IllegalArgumentException
* if the Object passed in is <code>null</code>
*/
public ReflectionToStringBuilder(Object object, ToStringStyle style) {
super(object, style);
}
/**
* <p>
* Constructor.
* </p>
*
* <p>
* If the style is <code>null</code>, the default style is used.
* </p>
*
* <p>
* If the buffer is <code>null</code>, a new one is created.
* </p>
*
* @param object
* the Object to build a <code>toString</code> for
* @param style
* the style of the <code>toString</code> to create, may be <code>null</code>
* @param buffer
* the <code>StringBuffer</code> to populate, may be <code>null</code>
* @throws IllegalArgumentException
* if the Object passed in is <code>null</code>
*/
public ReflectionToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {
super(object, style, buffer);
}
/**
* Constructor.
*
* @param <T>
* the type of the object
* @param object
* the Object to build a <code>toString</code> for
* @param style
* the style of the <code>toString</code> to create, may be <code>null</code>
* @param buffer
* the <code>StringBuffer</code> to populate, may be <code>null</code>
* @param reflectUpToClass
* the superclass to reflect up to (inclusive), may be <code>null</code>
* @param outputTransients
* whether to include transient fields
* @param outputStatics
* whether to include static fields
* @since 2.1
*/
public <T> ReflectionToStringBuilder(
T object, ToStringStyle style, StringBuffer buffer,
Class<? super T> reflectUpToClass, boolean outputTransients, boolean outputStatics) {
super(object, style, buffer);
this.setUpToClass(reflectUpToClass);
this.setAppendTransients(outputTransients);
this.setAppendStatics(outputStatics);
}
/**
* Returns whether or not to append the given <code>Field</code>.
* <ul>
* <li>Transient fields are appended only if {@link #isAppendTransients()} returns <code>true</code>.
* <li>Static fields are appended only if {@link #isAppendStatics()} returns <code>true</code>.
* <li>Inner class fields are not appened.</li>
* </ul>
*
* @param field
* The Field to test.
* @return Whether or not to append the given <code>Field</code>.
*/
protected boolean accept(Field field) {
if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
// Reject field from inner class.
return false;
}
if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {
// Reject transient fields.
return false;
}
if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {
// Reject static fields.
return false;
}
if (this.excludeFieldNames != null
&& Arrays.binarySearch(this.excludeFieldNames, field.getName()) >= 0) {
// Reject fields from the getExcludeFieldNames list.
return false;
}
return true;
}
/**
* <p>
* Appends the fields and values defined by the given object of the given Class.
* </p>
*
* <p>
* If a cycle is detected as an object is &quot;toString()'ed&quot;, such an object is rendered as if
* <code>Object.toString()</code> had been called and not implemented by the object.
* </p>
*
* @param clazz
* The class of object parameter
*/
protected void appendFieldsIn(Class<?> clazz) {
if (clazz.isArray()) {
this.reflectionAppendArray(this.getObject());
return;
}
Field[] fields = clazz.getDeclaredFields();
AccessibleObject.setAccessible(fields, true);
for (Field field : fields) {
String fieldName = field.getName();
if (this.accept(field)) {
try {
// Warning: Field.get(Object) creates wrappers objects
// for primitive types.
Object fieldValue = this.getValue(field);
this.append(fieldName, fieldValue);
} catch (IllegalAccessException ex) {
//this can't happen. Would get a Security exception
// instead
//throw a runtime exception in case the impossible
// happens.
throw new InternalError("Unexpected IllegalAccessException: " + ex.getMessage());
}
}
}
}
/**
* @return Returns the excludeFieldNames.
*/
public String[] getExcludeFieldNames() {
return this.excludeFieldNames.clone();
}
/**
* <p>
* Gets the last super class to stop appending fields for.
* </p>
*
* @return The last super class to stop appending fields for.
*/
public Class<?> getUpToClass() {
return this.upToClass;
}
/**
* <p>
* Calls <code>java.lang.reflect.Field.get(Object)</code>.
* </p>
*
* @param field
* The Field to query.
* @return The Object from the given Field.
*
* @throws IllegalArgumentException
* see {@link Field#get(Object)}
* @throws IllegalAccessException
* see {@link Field#get(Object)}
*
* @see Field#get(Object)
*/
protected Object getValue(Field field) throws IllegalArgumentException, IllegalAccessException {
return field.get(this.getObject());
}
/**
* <p>
* Gets whether or not to append static fields.
* </p>
*
* @return Whether or not to append static fields.
* @since 2.1
*/
public boolean isAppendStatics() {
return this.appendStatics;
}
/**
* <p>
* Gets whether or not to append transient fields.
* </p>
*
* @return Whether or not to append transient fields.
*/
public boolean isAppendTransients() {
return this.appendTransients;
}
/**
* <p>
* Append to the <code>toString</code> an <code>Object</code> array.
* </p>
*
* @param array
* the array to add to the <code>toString</code>
* @return this
*/
public ReflectionToStringBuilder reflectionAppendArray(Object array) {
this.getStyle().reflectionAppendArrayDetail(this.getStringBuffer(), null, array);
return this;
}
/**
* <p>
* Sets whether or not to append static fields.
* </p>
*
* @param appendStatics
* Whether or not to append static fields.
* @since 2.1
*/
public void setAppendStatics(boolean appendStatics) {
this.appendStatics = appendStatics;
}
/**
* <p>
* Sets whether or not to append transient fields.
* </p>
*
* @param appendTransients
* Whether or not to append transient fields.
*/
public void setAppendTransients(boolean appendTransients) {
this.appendTransients = appendTransients;
}
/**
* Sets the field names to exclude.
*
* @param excludeFieldNamesParam
* The excludeFieldNames to excluding from toString or <code>null</code>.
* @return <code>this</code>
*/
public ReflectionToStringBuilder setExcludeFieldNames(String... excludeFieldNamesParam) {
if (excludeFieldNamesParam == null) {
this.excludeFieldNames = null;
} else {
//clone and remove nulls
this.excludeFieldNames = toNoNullStringArray(excludeFieldNamesParam);
Arrays.sort(this.excludeFieldNames);
}
return this;
}
/**
* <p>
* Sets the last super class to stop appending fields for.
* </p>
*
* @param clazz
* The last super class to stop appending fields for.
*/
public void setUpToClass(Class<?> clazz) {
if (clazz != null) {
Object object = getObject();
if (object != null && clazz.isInstance(object) == false) {
throw new IllegalArgumentException("Specified class is not a superclass of the object");
}
}
this.upToClass = clazz;
}
/**
* <p>
* Gets the String built by this builder.
* </p>
*
* @return the built string
*/
@Override
public String toString() {
if (this.getObject() == null) {
return this.getStyle().getNullText();
}
Class<?> clazz = this.getObject().getClass();
this.appendFieldsIn(clazz);
while (clazz.getSuperclass() != null && clazz != this.getUpToClass()) {
clazz = clazz.getSuperclass();
this.appendFieldsIn(clazz);
}
return super.toString();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.builder;
import external.org.apache.commons.lang3.ObjectUtils;
/**
* <p>Assists in implementing {@link Object#toString()} methods.</p>
*
* <p>This class enables a good and consistent <code>toString()</code> to be built for any
* class or object. This class aims to simplify the process by:</p>
* <ul>
* <li>allowing field names</li>
* <li>handling all types consistently</li>
* <li>handling nulls consistently</li>
* <li>outputting arrays and multi-dimensional arrays</li>
* <li>enabling the detail level to be controlled for Objects and Collections</li>
* <li>handling class hierarchies</li>
* </ul>
*
* <p>To use this class write code as follows:</p>
*
* <pre>
* public class Person {
* String name;
* int age;
* boolean smoker;
*
* ...
*
* public String toString() {
* return new ToStringBuilder(this).
* append("name", name).
* append("age", age).
* append("smoker", smoker).
* toString();
* }
* }
* </pre>
*
* <p>This will produce a toString of the format:
* <code>Person@7f54[name=Stephen,age=29,smoker=false]</code></p>
*
* <p>To add the superclass <code>toString</code>, use {@link #appendSuper}.
* To append the <code>toString</code> from an object that is delegated
* to (or any other object), use {@link #appendToString}.</p>
*
* <p>Alternatively, there is a method that uses reflection to determine
* the fields to test. Because these fields are usually private, the method,
* <code>reflectionToString</code>, uses <code>AccessibleObject.setAccessible</code> to
* change the visibility of the fields. This will fail under a security manager,
* unless the appropriate permissions are set up correctly. It is also
* slower than testing explicitly.</p>
*
* <p>A typical invocation for this method would look like:</p>
*
* <pre>
* public String toString() {
* return ToStringBuilder.reflectionToString(this);
* }
* </pre>
*
* <p>You can also use the builder to debug 3rd party objects:</p>
*
* <pre>
* System.out.println("An object: " + ToStringBuilder.reflectionToString(anObject));
* </pre>
*
* <p>The exact format of the <code>toString</code> is determined by
* the {@link ToStringStyle} passed into the constructor.</p>
*
* @since 1.0
* @version $Id: ToStringBuilder.java 1088899 2011-04-05 05:31:27Z bayard $
*/
public class ToStringBuilder implements Builder<String> {
/**
* The default style of output to use, not null.
*/
private static volatile ToStringStyle defaultStyle = ToStringStyle.DEFAULT_STYLE;
//----------------------------------------------------------------------------
/**
* <p>Gets the default <code>ToStringStyle</code> to use.</p>
*
* <p>This method gets a singleton default value, typically for the whole JVM.
* Changing this default should generally only be done during application startup.
* It is recommended to pass a <code>ToStringStyle</code> to the constructor instead
* of using this global default.</p>
*
* <p>This method can be used from multiple threads.
* Internally, a <code>volatile</code> variable is used to provide the guarantee
* that the latest value set using {@link #setDefaultStyle} is the value returned.
* It is strongly recommended that the default style is only changed during application startup.</p>
*
* <p>One reason for changing the default could be to have a verbose style during
* development and a compact style in production.</p>
*
* @return the default <code>ToStringStyle</code>, never null
*/
public static ToStringStyle getDefaultStyle() {
return defaultStyle;
}
/**
* <p>Sets the default <code>ToStringStyle</code> to use.</p>
*
* <p>This method sets a singleton default value, typically for the whole JVM.
* Changing this default should generally only be done during application startup.
* It is recommended to pass a <code>ToStringStyle</code> to the constructor instead
* of changing this global default.</p>
*
* <p>This method is not intended for use from multiple threads.
* Internally, a <code>volatile</code> variable is used to provide the guarantee
* that the latest value set is the value returned from {@link #getDefaultStyle}.</p>
*
* @param style the default <code>ToStringStyle</code>
* @throws IllegalArgumentException if the style is <code>null</code>
*/
public static void setDefaultStyle(ToStringStyle style) {
if (style == null) {
throw new IllegalArgumentException("The style must not be null");
}
defaultStyle = style;
}
//----------------------------------------------------------------------------
/**
* <p>Uses <code>ReflectionToStringBuilder</code> to generate a
* <code>toString</code> for the specified object.</p>
*
* @param object the Object to be output
* @return the String result
* @see ReflectionToStringBuilder#toString(Object)
*/
public static String reflectionToString(Object object) {
return ReflectionToStringBuilder.toString(object);
}
/**
* <p>Uses <code>ReflectionToStringBuilder</code> to generate a
* <code>toString</code> for the specified object.</p>
*
* @param object the Object to be output
* @param style the style of the <code>toString</code> to create, may be <code>null</code>
* @return the String result
* @see ReflectionToStringBuilder#toString(Object,ToStringStyle)
*/
public static String reflectionToString(Object object, ToStringStyle style) {
return ReflectionToStringBuilder.toString(object, style);
}
/**
* <p>Uses <code>ReflectionToStringBuilder</code> to generate a
* <code>toString</code> for the specified object.</p>
*
* @param object the Object to be output
* @param style the style of the <code>toString</code> to create, may be <code>null</code>
* @param outputTransients whether to include transient fields
* @return the String result
* @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean)
*/
public static String reflectionToString(Object object, ToStringStyle style, boolean outputTransients) {
return ReflectionToStringBuilder.toString(object, style, outputTransients, false, null);
}
/**
* <p>Uses <code>ReflectionToStringBuilder</code> to generate a
* <code>toString</code> for the specified object.</p>
*
* @param <T> the type of the object
* @param object the Object to be output
* @param style the style of the <code>toString</code> to create, may be <code>null</code>
* @param outputTransients whether to include transient fields
* @param reflectUpToClass the superclass to reflect up to (inclusive), may be <code>null</code>
* @return the String result
* @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean,boolean,Class)
* @since 2.0
*/
public static <T> String reflectionToString(
T object,
ToStringStyle style,
boolean outputTransients,
Class<? super T> reflectUpToClass) {
return ReflectionToStringBuilder.toString(object, style, outputTransients, false, reflectUpToClass);
}
//----------------------------------------------------------------------------
/**
* Current toString buffer, not null.
*/
private final StringBuffer buffer;
/**
* The object being output, may be null.
*/
private final Object object;
/**
* The style of output to use, not null.
*/
private final ToStringStyle style;
/**
* <p>Constructs a builder for the specified object using the default output style.</p>
*
* <p>This default style is obtained from {@link #getDefaultStyle()}.</p>
*
* @param object the Object to build a <code>toString</code> for, not recommended to be null
*/
public ToStringBuilder(Object object) {
this(object, null, null);
}
/**
* <p>Constructs a builder for the specified object using the a defined output style.</p>
*
* <p>If the style is <code>null</code>, the default style is used.</p>
*
* @param object the Object to build a <code>toString</code> for, not recommended to be null
* @param style the style of the <code>toString</code> to create, null uses the default style
*/
public ToStringBuilder(Object object, ToStringStyle style) {
this(object, style, null);
}
/**
* <p>Constructs a builder for the specified object.</p>
*
* <p>If the style is <code>null</code>, the default style is used.</p>
*
* <p>If the buffer is <code>null</code>, a new one is created.</p>
*
* @param object the Object to build a <code>toString</code> for, not recommended to be null
* @param style the style of the <code>toString</code> to create, null uses the default style
* @param buffer the <code>StringBuffer</code> to populate, may be null
*/
public ToStringBuilder(Object object, ToStringStyle style, StringBuffer buffer) {
if (style == null) {
style = getDefaultStyle();
}
if (buffer == null) {
buffer = new StringBuffer(512);
}
this.buffer = buffer;
this.style = style;
this.object = object;
style.appendStart(buffer, object);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(boolean value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(boolean[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(byte value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(byte[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(char value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(char[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(double value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(double[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(float value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(float[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(int value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(int[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(long value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(long[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value.</p>
*
* @param obj the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(Object obj) {
style.append(buffer, null, obj, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(Object[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(short value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(short[] array) {
style.append(buffer, null, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, boolean value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>hashCode</code>
* @return this
*/
public ToStringBuilder append(String fieldName, boolean[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(String fieldName, boolean[] array, boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>byte</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, byte value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>byte</code> array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, byte[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(String fieldName, byte[] array, boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, char value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, char[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(String fieldName, char[] array, boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, double value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, double[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(String fieldName, double[] array, boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>float</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, float value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, float[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(String fieldName, float[] array, boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, int value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, int[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(String fieldName, int[] array, boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, long value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, long[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(String fieldName, long[] array, boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value.</p>
*
* @param fieldName the field name
* @param obj the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, Object obj) {
style.append(buffer, fieldName, obj, null);
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value.</p>
*
* @param fieldName the field name
* @param obj the value to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail,
* <code>false</code> for summary info
* @return this
*/
public ToStringBuilder append(String fieldName, Object obj, boolean fullDetail) {
style.append(buffer, fieldName, obj, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, Object[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(String fieldName, Object[] array, boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>short</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, short value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(String fieldName, short[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(String fieldName, short[] array, boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Appends with the same format as the default <code>Object toString()
* </code> method. Appends the class name followed by
* {@link System#identityHashCode(Object)}.</p>
*
* @param object the <code>Object</code> whose class name and id to output
* @return this
* @since 2.0
*/
public ToStringBuilder appendAsObjectToString(Object object) {
ObjectUtils.identityToString(this.getStringBuffer(), object);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append the <code>toString</code> from the superclass.</p>
*
* <p>This method assumes that the superclass uses the same <code>ToStringStyle</code>
* as this one.</p>
*
* <p>If <code>superToString</code> is <code>null</code>, no change is made.</p>
*
* @param superToString the result of <code>super.toString()</code>
* @return this
* @since 2.0
*/
public ToStringBuilder appendSuper(String superToString) {
if (superToString != null) {
style.appendSuper(buffer, superToString);
}
return this;
}
/**
* <p>Append the <code>toString</code> from another object.</p>
*
* <p>This method is useful where a class delegates most of the implementation of
* its properties to another class. You can then call <code>toString()</code> on
* the other class and pass the result into this method.</p>
*
* <pre>
* private AnotherObject delegate;
* private String fieldInThisClass;
*
* public String toString() {
* return new ToStringBuilder(this).
* appendToString(delegate.toString()).
* append(fieldInThisClass).
* toString();
* }</pre>
*
* <p>This method assumes that the other object uses the same <code>ToStringStyle</code>
* as this one.</p>
*
* <p>If the <code>toString</code> is <code>null</code>, no change is made.</p>
*
* @param toString the result of <code>toString()</code> on another object
* @return this
* @since 2.0
*/
public ToStringBuilder appendToString(String toString) {
if (toString != null) {
style.appendToString(buffer, toString);
}
return this;
}
/**
* <p>Returns the <code>Object</code> being output.</p>
*
* @return The object being output.
* @since 2.0
*/
public Object getObject() {
return object;
}
/**
* <p>Gets the <code>StringBuffer</code> being populated.</p>
*
* @return the <code>StringBuffer</code> being populated
*/
public StringBuffer getStringBuffer() {
return buffer;
}
//----------------------------------------------------------------------------
/**
* <p>Gets the <code>ToStringStyle</code> being used.</p>
*
* @return the <code>ToStringStyle</code> being used
* @since 2.0
*/
public ToStringStyle getStyle() {
return style;
}
/**
* <p>Returns the built <code>toString</code>.</p>
*
* <p>This method appends the end of data indicator, and can only be called once.
* Use {@link #getStringBuffer} to get the current string state.</p>
*
* <p>If the object is <code>null</code>, return the style's <code>nullText</code></p>
*
* @return the String <code>toString</code>
*/
@Override
public String toString() {
if (this.getObject() == null) {
this.getStringBuffer().append(this.getStyle().getNullText());
} else {
style.appendEnd(this.getStringBuffer(), this.getObject());
}
return this.getStringBuffer().toString();
}
/**
* Returns the String that was build as an object representation. The
* default implementation utilizes the {@link #toString()} implementation.
*
* @return the String <code>toString</code>
*
* @see #toString()
*
* @since 3.0
*/
public String build() {
return toString();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.builder;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;
import java.util.WeakHashMap;
import external.org.apache.commons.lang3.ClassUtils;
import external.org.apache.commons.lang3.ObjectUtils;
import external.org.apache.commons.lang3.SystemUtils;
/**
* <p>Controls <code>String</code> formatting for {@link ToStringBuilder}.
* The main public interface is always via <code>ToStringBuilder</code>.</p>
*
* <p>These classes are intended to be used as <code>Singletons</code>.
* There is no need to instantiate a new style each time. A program
* will generally use one of the predefined constants on this class.
* Alternatively, the {@link StandardToStringStyle} class can be used
* to set the individual settings. Thus most styles can be achieved
* without subclassing.</p>
*
* <p>If required, a subclass can override as many or as few of the
* methods as it requires. Each object type (from <code>boolean</code>
* to <code>long</code> to <code>Object</code> to <code>int[]</code>) has
* its own methods to output it. Most have two versions, detail and summary.
*
* <p>For example, the detail version of the array based methods will
* output the whole array, whereas the summary method will just output
* the array length.</p>
*
* <p>If you want to format the output of certain objects, such as dates, you
* must create a subclass and override a method.
* <pre>
* public class MyStyle extends ToStringStyle {
* protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
* if (value instanceof Date) {
* value = new SimpleDateFormat("yyyy-MM-dd").format(value);
* }
* buffer.append(value);
* }
* }
* </pre>
* </p>
*
* @since 1.0
* @version $Id: ToStringStyle.java 1091066 2011-04-11 13:30:11Z mbenson $
*/
public abstract class ToStringStyle implements Serializable {
/**
* Serialization version ID.
*/
private static final long serialVersionUID = -2587890625525655916L;
/**
* The default toString style. Using the Using the <code>Person</code>
* example from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* Person@182f0db[name=John Doe,age=33,smoker=false]
* </pre>
*/
public static final ToStringStyle DEFAULT_STYLE = new DefaultToStringStyle();
/**
* The multi line toString style. Using the Using the <code>Person</code>
* example from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* Person@182f0db[
* name=John Doe
* age=33
* smoker=false
* ]
* </pre>
*/
public static final ToStringStyle MULTI_LINE_STYLE = new MultiLineToStringStyle();
/**
* The no field names toString style. Using the Using the
* <code>Person</code> example from {@link ToStringBuilder}, the output
* would look like this:
*
* <pre>
* Person@182f0db[John Doe,33,false]
* </pre>
*/
public static final ToStringStyle NO_FIELD_NAMES_STYLE = new NoFieldNameToStringStyle();
/**
* The short prefix toString style. Using the <code>Person</code> example
* from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* Person[name=John Doe,age=33,smoker=false]
* </pre>
*
* @since 2.1
*/
public static final ToStringStyle SHORT_PREFIX_STYLE = new ShortPrefixToStringStyle();
/**
* The simple toString style. Using the Using the <code>Person</code>
* example from {@link ToStringBuilder}, the output would look like this:
*
* <pre>
* John Doe,33,false
* </pre>
*/
public static final ToStringStyle SIMPLE_STYLE = new SimpleToStringStyle();
/**
* <p>
* A registry of objects used by <code>reflectionToString</code> methods
* to detect cyclical object references and avoid infinite loops.
* </p>
*/
private static final ThreadLocal<WeakHashMap<Object, Object>> REGISTRY =
new ThreadLocal<WeakHashMap<Object,Object>>();
/**
* <p>
* Returns the registry of objects being traversed by the <code>reflectionToString</code>
* methods in the current thread.
* </p>
*
* @return Set the registry of objects being traversed
*/
static Map<Object, Object> getRegistry() {
return REGISTRY.get();
}
/**
* <p>
* Returns <code>true</code> if the registry contains the given object.
* Used by the reflection methods to avoid infinite loops.
* </p>
*
* @param value
* The object to lookup in the registry.
* @return boolean <code>true</code> if the registry contains the given
* object.
*/
static boolean isRegistered(Object value) {
Map<Object, Object> m = getRegistry();
return m != null && m.containsKey(value);
}
/**
* <p>
* Registers the given object. Used by the reflection methods to avoid
* infinite loops.
* </p>
*
* @param value
* The object to register.
*/
static void register(Object value) {
if (value != null) {
Map<Object, Object> m = getRegistry();
if (m == null) {
REGISTRY.set(new WeakHashMap<Object, Object>());
}
getRegistry().put(value, null);
}
}
/**
* <p>
* Unregisters the given object.
* </p>
*
* <p>
* Used by the reflection methods to avoid infinite loops.
* </p>
*
* @param value
* The object to unregister.
*/
static void unregister(Object value) {
if (value != null) {
Map<Object, Object> m = getRegistry();
if (m != null) {
m.remove(value);
if (m.isEmpty()) {
REGISTRY.remove();
}
}
}
}
/**
* Whether to use the field names, the default is <code>true</code>.
*/
private boolean useFieldNames = true;
/**
* Whether to use the class name, the default is <code>true</code>.
*/
private boolean useClassName = true;
/**
* Whether to use short class names, the default is <code>false</code>.
*/
private boolean useShortClassName = false;
/**
* Whether to use the identity hash code, the default is <code>true</code>.
*/
private boolean useIdentityHashCode = true;
/**
* The content start <code>'['</code>.
*/
private String contentStart = "[";
/**
* The content end <code>']'</code>.
*/
private String contentEnd = "]";
/**
* The field name value separator <code>'='</code>.
*/
private String fieldNameValueSeparator = "=";
/**
* Whether the field separator should be added before any other fields.
*/
private boolean fieldSeparatorAtStart = false;
/**
* Whether the field separator should be added after any other fields.
*/
private boolean fieldSeparatorAtEnd = false;
/**
* The field separator <code>','</code>.
*/
private String fieldSeparator = ",";
/**
* The array start <code>'{'</code>.
*/
private String arrayStart = "{";
/**
* The array separator <code>','</code>.
*/
private String arraySeparator = ",";
/**
* The detail for array content.
*/
private boolean arrayContentDetail = true;
/**
* The array end <code>'}'</code>.
*/
private String arrayEnd = "}";
/**
* The value to use when fullDetail is <code>null</code>,
* the default value is <code>true</code>.
*/
private boolean defaultFullDetail = true;
/**
* The <code>null</code> text <code>'&lt;null&gt;'</code>.
*/
private String nullText = "<null>";
/**
* The summary size text start <code>'<size'</code>.
*/
private String sizeStartText = "<size=";
/**
* The summary size text start <code>'&gt;'</code>.
*/
private String sizeEndText = ">";
/**
* The summary object text start <code>'&lt;'</code>.
*/
private String summaryObjectStartText = "<";
/**
* The summary object text start <code>'&gt;'</code>.
*/
private String summaryObjectEndText = ">";
//----------------------------------------------------------------------------
/**
* <p>Constructor.</p>
*/
protected ToStringStyle() {
super();
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> the superclass toString.</p>
* <p>NOTE: It assumes that the toString has been created from the same ToStringStyle. </p>
*
* <p>A <code>null</code> <code>superToString</code> is ignored.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param superToString the <code>super.toString()</code>
* @since 2.0
*/
public void appendSuper(StringBuffer buffer, String superToString) {
appendToString(buffer, superToString);
}
/**
* <p>Append to the <code>toString</code> another toString.</p>
* <p>NOTE: It assumes that the toString has been created from the same ToStringStyle. </p>
*
* <p>A <code>null</code> <code>toString</code> is ignored.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param toString the additional <code>toString</code>
* @since 2.0
*/
public void appendToString(StringBuffer buffer, String toString) {
if (toString != null) {
int pos1 = toString.indexOf(contentStart) + contentStart.length();
int pos2 = toString.lastIndexOf(contentEnd);
if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) {
String data = toString.substring(pos1, pos2);
if (fieldSeparatorAtStart) {
removeLastFieldSeparator(buffer);
}
buffer.append(data);
appendFieldSeparator(buffer);
}
}
}
/**
* <p>Append to the <code>toString</code> the start of data indicator.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> to build a <code>toString</code> for
*/
public void appendStart(StringBuffer buffer, Object object) {
if (object != null) {
appendClassName(buffer, object);
appendIdentityHashCode(buffer, object);
appendContentStart(buffer);
if (fieldSeparatorAtStart) {
appendFieldSeparator(buffer);
}
}
}
/**
* <p>Append to the <code>toString</code> the end of data indicator.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> to build a
* <code>toString</code> for.
*/
public void appendEnd(StringBuffer buffer, Object object) {
if (this.fieldSeparatorAtEnd == false) {
removeLastFieldSeparator(buffer);
}
appendContentEnd(buffer);
unregister(object);
}
/**
* <p>Remove the last field separator from the buffer.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @since 2.0
*/
protected void removeLastFieldSeparator(StringBuffer buffer) {
int len = buffer.length();
int sepLen = fieldSeparator.length();
if (len > 0 && sepLen > 0 && len >= sepLen) {
boolean match = true;
for (int i = 0; i < sepLen; i++) {
if (buffer.charAt(len - 1 - i) != fieldSeparator.charAt(sepLen - 1 - i)) {
match = false;
break;
}
}
if (match) {
buffer.setLength(len - sepLen);
}
}
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value, printing the full <code>toString</code> of the
* <code>Object</code> passed in.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, Object value, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (value == null) {
appendNullText(buffer, fieldName);
} else {
appendInternal(buffer, fieldName, value, isFullDetail(fullDetail));
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>,
* correctly interpreting its type.</p>
*
* <p>This method performs the main lookup by Class type to correctly
* route arrays, <code>Collections</code>, <code>Maps</code> and
* <code>Objects</code> to the appropriate method.</p>
*
* <p>Either detail or summary views can be specified.</p>
*
* <p>If a cycle is detected, an object will be appended with the
* <code>Object.toString()</code> format.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
* @param detail output detail or not
*/
protected void appendInternal(StringBuffer buffer, String fieldName, Object value, boolean detail) {
if (isRegistered(value)
&& !(value instanceof Number || value instanceof Boolean || value instanceof Character)) {
appendCyclicObject(buffer, fieldName, value);
return;
}
register(value);
try {
if (value instanceof Collection<?>) {
if (detail) {
appendDetail(buffer, fieldName, (Collection<?>) value);
} else {
appendSummarySize(buffer, fieldName, ((Collection<?>) value).size());
}
} else if (value instanceof Map<?, ?>) {
if (detail) {
appendDetail(buffer, fieldName, (Map<?, ?>) value);
} else {
appendSummarySize(buffer, fieldName, ((Map<?, ?>) value).size());
}
} else if (value instanceof long[]) {
if (detail) {
appendDetail(buffer, fieldName, (long[]) value);
} else {
appendSummary(buffer, fieldName, (long[]) value);
}
} else if (value instanceof int[]) {
if (detail) {
appendDetail(buffer, fieldName, (int[]) value);
} else {
appendSummary(buffer, fieldName, (int[]) value);
}
} else if (value instanceof short[]) {
if (detail) {
appendDetail(buffer, fieldName, (short[]) value);
} else {
appendSummary(buffer, fieldName, (short[]) value);
}
} else if (value instanceof byte[]) {
if (detail) {
appendDetail(buffer, fieldName, (byte[]) value);
} else {
appendSummary(buffer, fieldName, (byte[]) value);
}
} else if (value instanceof char[]) {
if (detail) {
appendDetail(buffer, fieldName, (char[]) value);
} else {
appendSummary(buffer, fieldName, (char[]) value);
}
} else if (value instanceof double[]) {
if (detail) {
appendDetail(buffer, fieldName, (double[]) value);
} else {
appendSummary(buffer, fieldName, (double[]) value);
}
} else if (value instanceof float[]) {
if (detail) {
appendDetail(buffer, fieldName, (float[]) value);
} else {
appendSummary(buffer, fieldName, (float[]) value);
}
} else if (value instanceof boolean[]) {
if (detail) {
appendDetail(buffer, fieldName, (boolean[]) value);
} else {
appendSummary(buffer, fieldName, (boolean[]) value);
}
} else if (value.getClass().isArray()) {
if (detail) {
appendDetail(buffer, fieldName, (Object[]) value);
} else {
appendSummary(buffer, fieldName, (Object[]) value);
}
} else {
if (detail) {
appendDetail(buffer, fieldName, value);
} else {
appendSummary(buffer, fieldName, value);
}
}
} finally {
unregister(value);
}
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value that has been detected to participate in a cycle. This
* implementation will print the standard string value of the value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
*
* @since 2.2
*/
protected void appendCyclicObject(StringBuffer buffer, String fieldName, Object value) {
ObjectUtils.identityToString(buffer, value);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value, printing the full detail of the <code>Object</code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Object value) {
buffer.append(value);
}
/**
* <p>Append to the <code>toString</code> a <code>Collection</code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param coll the <code>Collection</code> to add to the
* <code>toString</code>, not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Collection<?> coll) {
buffer.append(coll);
}
/**
* <p>Append to the <code>toString</code> a <code>Map<code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param map the <code>Map</code> to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Map<?, ?> map) {
buffer.append(map);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value, printing a summary of the <code>Object</code>.</P>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, Object value) {
buffer.append(summaryObjectStartText);
buffer.append(getShortClassName(value.getClass()));
buffer.append(summaryObjectEndText);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, long value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, long value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, int value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, int value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, short value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, short value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, byte value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, byte value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, char value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, char value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, double value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, double value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, float value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, float value) {
buffer.append(value);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
*/
public void append(StringBuffer buffer, String fieldName, boolean value) {
appendFieldStart(buffer, fieldName);
appendDetail(buffer, fieldName, value);
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* value.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param value the value to add to the <code>toString</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, boolean value) {
buffer.append(value);
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, Object[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> the detail of an
* <code>Object</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, Object[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
Object item = array[i];
if (i > 0) {
buffer.append(arraySeparator);
}
if (item == null) {
appendNullText(buffer, fieldName);
} else {
appendInternal(buffer, fieldName, item, arrayContentDetail);
}
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> the detail of an array type.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
* @since 2.0
*/
protected void reflectionAppendArrayDetail(StringBuffer buffer, String fieldName, Object array) {
buffer.append(arrayStart);
int length = Array.getLength(array);
for (int i = 0; i < length; i++) {
Object item = Array.get(array, i);
if (i > 0) {
buffer.append(arraySeparator);
}
if (item == null) {
appendNullText(buffer, fieldName);
} else {
appendInternal(buffer, fieldName, item, arrayContentDetail);
}
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of an
* <code>Object</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, Object[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, long[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>long</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, long[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>long</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, long[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, int[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of an
* <code>int</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, int[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of an
* <code>int</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, int[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, short[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>short</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, short[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>short</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, short[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, byte[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>byte</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, byte[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>byte</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, byte[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, char[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>char</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, char[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>char</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, char[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, double[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>double</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, double[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>double</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, double[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, float[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>float</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, float[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>float</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, float[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
* @param array the array to add to the toString
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info, <code>null</code> for style decides
*/
public void append(StringBuffer buffer, String fieldName, boolean[] array, Boolean fullDetail) {
appendFieldStart(buffer, fieldName);
if (array == null) {
appendNullText(buffer, fieldName);
} else if (isFullDetail(fullDetail)) {
appendDetail(buffer, fieldName, array);
} else {
appendSummary(buffer, fieldName, array);
}
appendFieldEnd(buffer, fieldName);
}
/**
* <p>Append to the <code>toString</code> the detail of a
* <code>boolean</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendDetail(StringBuffer buffer, String fieldName, boolean[] array) {
buffer.append(arrayStart);
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(arraySeparator);
}
appendDetail(buffer, fieldName, array[i]);
}
buffer.append(arrayEnd);
}
/**
* <p>Append to the <code>toString</code> a summary of a
* <code>boolean</code> array.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param array the array to add to the <code>toString</code>,
* not <code>null</code>
*/
protected void appendSummary(StringBuffer buffer, String fieldName, boolean[] array) {
appendSummarySize(buffer, fieldName, array.length);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> the class name.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> whose name to output
*/
protected void appendClassName(StringBuffer buffer, Object object) {
if (useClassName && object != null) {
register(object);
if (useShortClassName) {
buffer.append(getShortClassName(object.getClass()));
} else {
buffer.append(object.getClass().getName());
}
}
}
/**
* <p>Append the {@link System#identityHashCode(Object)}.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param object the <code>Object</code> whose id to output
*/
protected void appendIdentityHashCode(StringBuffer buffer, Object object) {
if (this.isUseIdentityHashCode() && object!=null) {
register(object);
buffer.append('@');
buffer.append(Integer.toHexString(System.identityHashCode(object)));
}
}
/**
* <p>Append to the <code>toString</code> the content start.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
*/
protected void appendContentStart(StringBuffer buffer) {
buffer.append(contentStart);
}
/**
* <p>Append to the <code>toString</code> the content end.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
*/
protected void appendContentEnd(StringBuffer buffer) {
buffer.append(contentEnd);
}
/**
* <p>Append to the <code>toString</code> an indicator for <code>null</code>.</p>
*
* <p>The default indicator is <code>'&lt;null&gt;'</code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
*/
protected void appendNullText(StringBuffer buffer, String fieldName) {
buffer.append(nullText);
}
/**
* <p>Append to the <code>toString</code> the field separator.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
*/
protected void appendFieldSeparator(StringBuffer buffer) {
buffer.append(fieldSeparator);
}
/**
* <p>Append to the <code>toString</code> the field start.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name
*/
protected void appendFieldStart(StringBuffer buffer, String fieldName) {
if (useFieldNames && fieldName != null) {
buffer.append(fieldName);
buffer.append(fieldNameValueSeparator);
}
}
/**
* <p>Append to the <code>toString<code> the field end.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
*/
protected void appendFieldEnd(StringBuffer buffer, String fieldName) {
appendFieldSeparator(buffer);
}
/**
* <p>Append to the <code>toString</code> a size summary.</p>
*
* <p>The size summary is used to summarize the contents of
* <code>Collections</code>, <code>Maps</code> and arrays.</p>
*
* <p>The output consists of a prefix, the passed in size
* and a suffix.</p>
*
* <p>The default format is <code>'&lt;size=n&gt;'<code>.</p>
*
* @param buffer the <code>StringBuffer</code> to populate
* @param fieldName the field name, typically not used as already appended
* @param size the size to append
*/
protected void appendSummarySize(StringBuffer buffer, String fieldName, int size) {
buffer.append(sizeStartText);
buffer.append(size);
buffer.append(sizeEndText);
}
/**
* <p>Is this field to be output in full detail.</p>
*
* <p>This method converts a detail request into a detail level.
* The calling code may request full detail (<code>true</code>),
* but a subclass might ignore that and always return
* <code>false</code>. The calling code may pass in
* <code>null</code> indicating that it doesn't care about
* the detail level. In this case the default detail level is
* used.</p>
*
* @param fullDetailRequest the detail level requested
* @return whether full detail is to be shown
*/
protected boolean isFullDetail(Boolean fullDetailRequest) {
if (fullDetailRequest == null) {
return defaultFullDetail;
}
return fullDetailRequest.booleanValue();
}
/**
* <p>Gets the short class name for a class.</p>
*
* <p>The short class name is the classname excluding
* the package name.</p>
*
* @param cls the <code>Class</code> to get the short name of
* @return the short name
*/
protected String getShortClassName(Class<?> cls) {
return ClassUtils.getShortClassName(cls);
}
// Setters and getters for the customizable parts of the style
// These methods are not expected to be overridden, except to make public
// (They are not public so that immutable subclasses can be written)
//---------------------------------------------------------------------
/**
* <p>Gets whether to use the class name.</p>
*
* @return the current useClassName flag
*/
protected boolean isUseClassName() {
return useClassName;
}
/**
* <p>Sets whether to use the class name.</p>
*
* @param useClassName the new useClassName flag
*/
protected void setUseClassName(boolean useClassName) {
this.useClassName = useClassName;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to output short or long class names.</p>
*
* @return the current useShortClassName flag
* @since 2.0
*/
protected boolean isUseShortClassName() {
return useShortClassName;
}
/**
* <p>Sets whether to output short or long class names.</p>
*
* @param useShortClassName the new useShortClassName flag
* @since 2.0
*/
protected void setUseShortClassName(boolean useShortClassName) {
this.useShortClassName = useShortClassName;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to use the identity hash code.</p>
*
* @return the current useIdentityHashCode flag
*/
protected boolean isUseIdentityHashCode() {
return useIdentityHashCode;
}
/**
* <p>Sets whether to use the identity hash code.</p>
*
* @param useIdentityHashCode the new useIdentityHashCode flag
*/
protected void setUseIdentityHashCode(boolean useIdentityHashCode) {
this.useIdentityHashCode = useIdentityHashCode;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to use the field names passed in.</p>
*
* @return the current useFieldNames flag
*/
protected boolean isUseFieldNames() {
return useFieldNames;
}
/**
* <p>Sets whether to use the field names passed in.</p>
*
* @param useFieldNames the new useFieldNames flag
*/
protected void setUseFieldNames(boolean useFieldNames) {
this.useFieldNames = useFieldNames;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to use full detail when the caller doesn't
* specify.</p>
*
* @return the current defaultFullDetail flag
*/
protected boolean isDefaultFullDetail() {
return defaultFullDetail;
}
/**
* <p>Sets whether to use full detail when the caller doesn't
* specify.</p>
*
* @param defaultFullDetail the new defaultFullDetail flag
*/
protected void setDefaultFullDetail(boolean defaultFullDetail) {
this.defaultFullDetail = defaultFullDetail;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether to output array content detail.</p>
*
* @return the current array content detail setting
*/
protected boolean isArrayContentDetail() {
return arrayContentDetail;
}
/**
* <p>Sets whether to output array content detail.</p>
*
* @param arrayContentDetail the new arrayContentDetail flag
*/
protected void setArrayContentDetail(boolean arrayContentDetail) {
this.arrayContentDetail = arrayContentDetail;
}
//---------------------------------------------------------------------
/**
* <p>Gets the array start text.</p>
*
* @return the current array start text
*/
protected String getArrayStart() {
return arrayStart;
}
/**
* <p>Sets the array start text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param arrayStart the new array start text
*/
protected void setArrayStart(String arrayStart) {
if (arrayStart == null) {
arrayStart = "";
}
this.arrayStart = arrayStart;
}
//---------------------------------------------------------------------
/**
* <p>Gets the array end text.</p>
*
* @return the current array end text
*/
protected String getArrayEnd() {
return arrayEnd;
}
/**
* <p>Sets the array end text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param arrayEnd the new array end text
*/
protected void setArrayEnd(String arrayEnd) {
if (arrayEnd == null) {
arrayEnd = "";
}
this.arrayEnd = arrayEnd;
}
//---------------------------------------------------------------------
/**
* <p>Gets the array separator text.</p>
*
* @return the current array separator text
*/
protected String getArraySeparator() {
return arraySeparator;
}
/**
* <p>Sets the array separator text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param arraySeparator the new array separator text
*/
protected void setArraySeparator(String arraySeparator) {
if (arraySeparator == null) {
arraySeparator = "";
}
this.arraySeparator = arraySeparator;
}
//---------------------------------------------------------------------
/**
* <p>Gets the content start text.</p>
*
* @return the current content start text
*/
protected String getContentStart() {
return contentStart;
}
/**
* <p>Sets the content start text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param contentStart the new content start text
*/
protected void setContentStart(String contentStart) {
if (contentStart == null) {
contentStart = "";
}
this.contentStart = contentStart;
}
//---------------------------------------------------------------------
/**
* <p>Gets the content end text.</p>
*
* @return the current content end text
*/
protected String getContentEnd() {
return contentEnd;
}
/**
* <p>Sets the content end text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param contentEnd the new content end text
*/
protected void setContentEnd(String contentEnd) {
if (contentEnd == null) {
contentEnd = "";
}
this.contentEnd = contentEnd;
}
//---------------------------------------------------------------------
/**
* <p>Gets the field name value separator text.</p>
*
* @return the current field name value separator text
*/
protected String getFieldNameValueSeparator() {
return fieldNameValueSeparator;
}
/**
* <p>Sets the field name value separator text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param fieldNameValueSeparator the new field name value separator text
*/
protected void setFieldNameValueSeparator(String fieldNameValueSeparator) {
if (fieldNameValueSeparator == null) {
fieldNameValueSeparator = "";
}
this.fieldNameValueSeparator = fieldNameValueSeparator;
}
//---------------------------------------------------------------------
/**
* <p>Gets the field separator text.</p>
*
* @return the current field separator text
*/
protected String getFieldSeparator() {
return fieldSeparator;
}
/**
* <p>Sets the field separator text.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param fieldSeparator the new field separator text
*/
protected void setFieldSeparator(String fieldSeparator) {
if (fieldSeparator == null) {
fieldSeparator = "";
}
this.fieldSeparator = fieldSeparator;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether the field separator should be added at the start
* of each buffer.</p>
*
* @return the fieldSeparatorAtStart flag
* @since 2.0
*/
protected boolean isFieldSeparatorAtStart() {
return fieldSeparatorAtStart;
}
/**
* <p>Sets whether the field separator should be added at the start
* of each buffer.</p>
*
* @param fieldSeparatorAtStart the fieldSeparatorAtStart flag
* @since 2.0
*/
protected void setFieldSeparatorAtStart(boolean fieldSeparatorAtStart) {
this.fieldSeparatorAtStart = fieldSeparatorAtStart;
}
//---------------------------------------------------------------------
/**
* <p>Gets whether the field separator should be added at the end
* of each buffer.</p>
*
* @return fieldSeparatorAtEnd flag
* @since 2.0
*/
protected boolean isFieldSeparatorAtEnd() {
return fieldSeparatorAtEnd;
}
/**
* <p>Sets whether the field separator should be added at the end
* of each buffer.</p>
*
* @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag
* @since 2.0
*/
protected void setFieldSeparatorAtEnd(boolean fieldSeparatorAtEnd) {
this.fieldSeparatorAtEnd = fieldSeparatorAtEnd;
}
//---------------------------------------------------------------------
/**
* <p>Gets the text to output when <code>null</code> found.</p>
*
* @return the current text to output when null found
*/
protected String getNullText() {
return nullText;
}
/**
* <p>Sets the text to output when <code>null</code> found.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param nullText the new text to output when null found
*/
protected void setNullText(String nullText) {
if (nullText == null) {
nullText = "";
}
this.nullText = nullText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the start text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output before the size value.</p>
*
* @return the current start of size text
*/
protected String getSizeStartText() {
return sizeStartText;
}
/**
* <p>Sets the start text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output before the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param sizeStartText the new start of size text
*/
protected void setSizeStartText(String sizeStartText) {
if (sizeStartText == null) {
sizeStartText = "";
}
this.sizeStartText = sizeStartText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the end text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output after the size value.</p>
*
* @return the current end of size text
*/
protected String getSizeEndText() {
return sizeEndText;
}
/**
* <p>Sets the end text to output when a <code>Collection</code>,
* <code>Map</code> or array size is output.</p>
*
* <p>This is output after the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param sizeEndText the new end of size text
*/
protected void setSizeEndText(String sizeEndText) {
if (sizeEndText == null) {
sizeEndText = "";
}
this.sizeEndText = sizeEndText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the start text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output before the size value.</p>
*
* @return the current start of summary text
*/
protected String getSummaryObjectStartText() {
return summaryObjectStartText;
}
/**
* <p>Sets the start text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output before the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param summaryObjectStartText the new start of summary text
*/
protected void setSummaryObjectStartText(String summaryObjectStartText) {
if (summaryObjectStartText == null) {
summaryObjectStartText = "";
}
this.summaryObjectStartText = summaryObjectStartText;
}
//---------------------------------------------------------------------
/**
* <p>Gets the end text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output after the size value.</p>
*
* @return the current end of summary text
*/
protected String getSummaryObjectEndText() {
return summaryObjectEndText;
}
/**
* <p>Sets the end text to output when an <code>Object</code> is
* output in summary mode.</p>
*
* <p>This is output after the size value.</p>
*
* <p><code>null</code> is accepted, but will be converted to
* an empty String.</p>
*
* @param summaryObjectEndText the new end of summary text
*/
protected void setSummaryObjectEndText(String summaryObjectEndText) {
if (summaryObjectEndText == null) {
summaryObjectEndText = "";
}
this.summaryObjectEndText = summaryObjectEndText;
}
//----------------------------------------------------------------------------
/**
* <p>Default <code>ToStringStyle</code>.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class DefaultToStringStyle extends ToStringStyle {
/**
* Required for serialization support.
*
* @see Serializable
*/
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
DefaultToStringStyle() {
super();
}
/**
* <p>Ensure <code>Singleton</code> after serialization.</p>
*
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.DEFAULT_STYLE;
}
}
//----------------------------------------------------------------------------
/**
* <p><code>ToStringStyle</code> that does not print out
* the field names.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.
*/
private static final class NoFieldNameToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
NoFieldNameToStringStyle() {
super();
this.setUseFieldNames(false);
}
/**
* <p>Ensure <code>Singleton</code> after serialization.</p>
*
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.NO_FIELD_NAMES_STYLE;
}
}
//----------------------------------------------------------------------------
/**
* <p><code>ToStringStyle</code> that prints out the short
* class name and no identity hashcode.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class ShortPrefixToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
ShortPrefixToStringStyle() {
super();
this.setUseShortClassName(true);
this.setUseIdentityHashCode(false);
}
/**
* <p>Ensure <code>Singleton</ode> after serialization.</p>
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.SHORT_PREFIX_STYLE;
}
}
/**
* <p><code>ToStringStyle</code> that does not print out the
* classname, identity hashcode, content start or field name.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class SimpleToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
SimpleToStringStyle() {
super();
this.setUseClassName(false);
this.setUseIdentityHashCode(false);
this.setUseFieldNames(false);
this.setContentStart("");
this.setContentEnd("");
}
/**
* <p>Ensure <code>Singleton</ode> after serialization.</p>
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.SIMPLE_STYLE;
}
}
//----------------------------------------------------------------------------
/**
* <p><code>ToStringStyle</code> that outputs on multiple lines.</p>
*
* <p>This is an inner class rather than using
* <code>StandardToStringStyle</code> to ensure its immutability.</p>
*/
private static final class MultiLineToStringStyle extends ToStringStyle {
private static final long serialVersionUID = 1L;
/**
* <p>Constructor.</p>
*
* <p>Use the static constant rather than instantiating.</p>
*/
MultiLineToStringStyle() {
super();
this.setContentStart("[");
this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + " ");
this.setFieldSeparatorAtStart(true);
this.setContentEnd(SystemUtils.LINE_SEPARATOR + "]");
}
/**
* <p>Ensure <code>Singleton</code> after serialization.</p>
*
* @return the singleton
*/
private Object readResolve() {
return ToStringStyle.MULTI_LINE_STYLE;
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.exception;
/**
* Exception thrown when a clone cannot be created. In contrast to
* {@link CloneNotSupportedException} this is a {@link RuntimeException}.
*
* @since 3.0
*/
public class CloneFailedException extends RuntimeException {
// ~ Static fields/initializers ---------------------------------------------
private static final long serialVersionUID = 20091223L;
// ~ Constructors -----------------------------------------------------------
/**
* Constructs a CloneFailedException.
*
* @param message description of the exception
* @since upcoming
*/
public CloneFailedException(final String message) {
super(message);
}
/**
* Constructs a CloneFailedException.
*
* @param cause cause of the exception
* @since upcoming
*/
public CloneFailedException(final Throwable cause) {
super(cause);
}
/**
* Constructs a CloneFailedException.
*
* @param message description of the exception
* @param cause cause of the exception
* @since upcoming
*/
public CloneFailedException(final String message, final Throwable cause) {
super(message, cause);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.mutable;
/**
* Provides mutable access to a value.
* <p>
* <code>Mutable</code> is used as a generic interface to the implementations in this package.
* <p>
* A typical use case would be to enable a primitive or string to be passed to a method and allow that method to
* effectively change the value of the primitive/string. Another use case is to store a frequently changing primitive in
* a collection (for example a total in a map) without needing to create new Integer/Long wrapper objects.
*
* @since 2.1
* @param <T> the type to set and get
* @version $Id: Mutable.java 1153213 2011-08-02 17:35:39Z ggregory $
*/
public interface Mutable<T> {
/**
* Gets the value of this mutable.
*
* @return the stored value
*/
T getValue();
/**
* Sets the value of this mutable.
*
* @param value
* the value to store
* @throws NullPointerException
* if the object is null and null is invalid
* @throws ClassCastException
* if the type is invalid
*/
void setValue(T value);
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.mutable;
/**
* A mutable <code>int</code> wrapper.
* <p>
* Note that as MutableInt does not extend Integer, it is not treated by String.format as an Integer parameter.
*
* @see Integer
* @since 2.1
* @version $Id: MutableInt.java 1160571 2011-08-23 07:36:08Z bayard $
*/
public class MutableInt extends Number implements Comparable<MutableInt>, Mutable<Number> {
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 512176391864L;
/** The mutable value. */
private int value;
/**
* Constructs a new MutableInt with the default value of zero.
*/
public MutableInt() {
super();
}
/**
* Constructs a new MutableInt with the specified value.
*
* @param value the initial value to store
*/
public MutableInt(int value) {
super();
this.value = value;
}
/**
* Constructs a new MutableInt with the specified value.
*
* @param value the initial value to store, not null
* @throws NullPointerException if the object is null
*/
public MutableInt(Number value) {
super();
this.value = value.intValue();
}
/**
* Constructs a new MutableInt parsing the given string.
*
* @param value the string to parse, not null
* @throws NumberFormatException if the string cannot be parsed into an int
* @since 2.5
*/
public MutableInt(String value) throws NumberFormatException {
super();
this.value = Integer.parseInt(value);
}
//-----------------------------------------------------------------------
/**
* Gets the value as a Integer instance.
*
* @return the value as a Integer, never null
*/
public Integer getValue() {
return Integer.valueOf(this.value);
}
/**
* Sets the value.
*
* @param value the value to set
*/
public void setValue(int value) {
this.value = value;
}
/**
* Sets the value from any Number instance.
*
* @param value the value to set, not null
* @throws NullPointerException if the object is null
*/
public void setValue(Number value) {
this.value = value.intValue();
}
//-----------------------------------------------------------------------
/**
* Increments the value.
*
* @since Commons Lang 2.2
*/
public void increment() {
value++;
}
/**
* Decrements the value.
*
* @since Commons Lang 2.2
*/
public void decrement() {
value--;
}
//-----------------------------------------------------------------------
/**
* Adds a value to the value of this instance.
*
* @param operand the value to add, not null
* @since Commons Lang 2.2
*/
public void add(int operand) {
this.value += operand;
}
/**
* Adds a value to the value of this instance.
*
* @param operand the value to add, not null
* @throws NullPointerException if the object is null
* @since Commons Lang 2.2
*/
public void add(Number operand) {
this.value += operand.intValue();
}
/**
* Subtracts a value from the value of this instance.
*
* @param operand the value to subtract, not null
* @since Commons Lang 2.2
*/
public void subtract(int operand) {
this.value -= operand;
}
/**
* Subtracts a value from the value of this instance.
*
* @param operand the value to subtract, not null
* @throws NullPointerException if the object is null
* @since Commons Lang 2.2
*/
public void subtract(Number operand) {
this.value -= operand.intValue();
}
//-----------------------------------------------------------------------
// shortValue and byteValue rely on Number implementation
/**
* Returns the value of this MutableInt as an int.
*
* @return the numeric value represented by this object after conversion to type int.
*/
@Override
public int intValue() {
return value;
}
/**
* Returns the value of this MutableInt as a long.
*
* @return the numeric value represented by this object after conversion to type long.
*/
@Override
public long longValue() {
return value;
}
/**
* Returns the value of this MutableInt as a float.
*
* @return the numeric value represented by this object after conversion to type float.
*/
@Override
public float floatValue() {
return value;
}
/**
* Returns the value of this MutableInt as a double.
*
* @return the numeric value represented by this object after conversion to type double.
*/
@Override
public double doubleValue() {
return value;
}
//-----------------------------------------------------------------------
/**
* Gets this mutable as an instance of Integer.
*
* @return a Integer instance containing the value from this mutable, never null
*/
public Integer toInteger() {
return Integer.valueOf(intValue());
}
//-----------------------------------------------------------------------
/**
* Compares this object to the specified object. The result is <code>true</code> if and only if the argument is
* not <code>null</code> and is a <code>MutableInt</code> object that contains the same <code>int</code> value
* as this object.
*
* @param obj the object to compare with, null returns false
* @return <code>true</code> if the objects are the same; <code>false</code> otherwise.
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof MutableInt) {
return value == ((MutableInt) obj).intValue();
}
return false;
}
/**
* Returns a suitable hash code for this mutable.
*
* @return a suitable hash code
*/
@Override
public int hashCode() {
return value;
}
//-----------------------------------------------------------------------
/**
* Compares this mutable to another in ascending order.
*
* @param other the other mutable to compare to, not null
* @return negative if this is less, zero if equal, positive if greater
*/
public int compareTo(MutableInt other) {
int anotherVal = other.value;
return value < anotherVal ? -1 : (value == anotherVal ? 0 : 1);
}
//-----------------------------------------------------------------------
/**
* Returns the String value of this mutable.
*
* @return the mutable value as a string
*/
@Override
public String toString() {
return String.valueOf(value);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.reflect;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import external.org.apache.commons.lang3.ClassUtils;
/**
* Contains common code for working with Methods/Constructors, extracted and
* refactored from <code>MethodUtils</code> when it was imported from Commons
* BeanUtils.
*
* @since 2.5
* @version $Id: MemberUtils.java 1143537 2011-07-06 19:30:22Z joehni $
*/
public abstract class MemberUtils {
// TODO extract an interface to implement compareParameterSets(...)?
private static final int ACCESS_TEST = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE;
/** Array of primitive number types ordered by "promotability" */
private static final Class<?>[] ORDERED_PRIMITIVE_TYPES = { Byte.TYPE, Short.TYPE,
Character.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE };
/**
* XXX Default access superclass workaround
*
* When a public class has a default access superclass with public members,
* these members are accessible. Calling them from compiled code works fine.
* Unfortunately, on some JVMs, using reflection to invoke these members
* seems to (wrongly) prevent access even when the modifier is public.
* Calling setAccessible(true) solves the problem but will only work from
* sufficiently privileged code. Better workarounds would be gratefully
* accepted.
* @param o the AccessibleObject to set as accessible
*/
static void setAccessibleWorkaround(AccessibleObject o) {
if (o == null || o.isAccessible()) {
return;
}
Member m = (Member) o;
if (Modifier.isPublic(m.getModifiers())
&& isPackageAccess(m.getDeclaringClass().getModifiers())) {
try {
o.setAccessible(true);
} catch (SecurityException e) { // NOPMD
// ignore in favor of subsequent IllegalAccessException
}
}
}
/**
* Returns whether a given set of modifiers implies package access.
* @param modifiers to test
* @return true unless package/protected/private modifier detected
*/
static boolean isPackageAccess(int modifiers) {
return (modifiers & ACCESS_TEST) == 0;
}
/**
* Returns whether a Member is accessible.
* @param m Member to check
* @return true if <code>m</code> is accessible
*/
static boolean isAccessible(Member m) {
return m != null && Modifier.isPublic(m.getModifiers()) && !m.isSynthetic();
}
/**
* Compares the relative fitness of two sets of parameter types in terms of
* matching a third set of runtime parameter types, such that a list ordered
* by the results of the comparison would return the best match first
* (least).
*
* @param left the "left" parameter set
* @param right the "right" parameter set
* @param actual the runtime parameter types to match against
* <code>left</code>/<code>right</code>
* @return int consistent with <code>compare</code> semantics
*/
public static int compareParameterTypes(Class<?>[] left, Class<?>[] right, Class<?>[] actual) {
float leftCost = getTotalTransformationCost(actual, left);
float rightCost = getTotalTransformationCost(actual, right);
return leftCost < rightCost ? -1 : rightCost < leftCost ? 1 : 0;
}
/**
* Returns the sum of the object transformation cost for each class in the
* source argument list.
* @param srcArgs The source arguments
* @param destArgs The destination arguments
* @return The total transformation cost
*/
private static float getTotalTransformationCost(Class<?>[] srcArgs, Class<?>[] destArgs) {
float totalCost = 0.0f;
for (int i = 0; i < srcArgs.length; i++) {
Class<?> srcClass, destClass;
srcClass = srcArgs[i];
destClass = destArgs[i];
totalCost += getObjectTransformationCost(srcClass, destClass);
}
return totalCost;
}
/**
* Gets the number of steps required needed to turn the source class into
* the destination class. This represents the number of steps in the object
* hierarchy graph.
* @param srcClass The source class
* @param destClass The destination class
* @return The cost of transforming an object
*/
private static float getObjectTransformationCost(Class<?> srcClass, Class<?> destClass) {
if (destClass.isPrimitive()) {
return getPrimitivePromotionCost(srcClass, destClass);
}
float cost = 0.0f;
while (srcClass != null && !destClass.equals(srcClass)) {
if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) {
// slight penalty for interface match.
// we still want an exact match to override an interface match,
// but
// an interface match should override anything where we have to
// get a superclass.
cost += 0.25f;
break;
}
cost++;
srcClass = srcClass.getSuperclass();
}
/*
* If the destination class is null, we've travelled all the way up to
* an Object match. We'll penalize this by adding 1.5 to the cost.
*/
if (srcClass == null) {
cost += 1.5f;
}
return cost;
}
/**
* Gets the number of steps required to promote a primitive number to another
* type.
* @param srcClass the (primitive) source class
* @param destClass the (primitive) destination class
* @return The cost of promoting the primitive
*/
private static float getPrimitivePromotionCost(final Class<?> srcClass, final Class<?> destClass) {
float cost = 0.0f;
Class<?> cls = srcClass;
if (!cls.isPrimitive()) {
// slight unwrapping penalty
cost += 0.1f;
cls = ClassUtils.wrapperToPrimitive(cls);
}
for (int i = 0; cls != destClass && i < ORDERED_PRIMITIVE_TYPES.length; i++) {
if (cls == ORDERED_PRIMITIVE_TYPES[i]) {
cost += 0.1f;
if (i < ORDERED_PRIMITIVE_TYPES.length - 1) {
cls = ORDERED_PRIMITIVE_TYPES[i + 1];
}
}
}
return cost;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import external.org.apache.commons.lang3.ArrayUtils;
import external.org.apache.commons.lang3.ClassUtils;
/**
* <p>Utility reflection methods focused on methods, originally from Commons BeanUtils.
* Differences from the BeanUtils version may be noted, especially where similar functionality
* already existed within Lang.
* </p>
*
* <h3>Known Limitations</h3>
* <h4>Accessing Public Methods In A Default Access Superclass</h4>
* <p>There is an issue when invoking public methods contained in a default access superclass on JREs prior to 1.4.
* Reflection locates these methods fine and correctly assigns them as public.
* However, an <code>IllegalAccessException</code> is thrown if the method is invoked.</p>
*
* <p><code>MethodUtils</code> contains a workaround for this situation.
* It will attempt to call <code>setAccessible</code> on this method.
* If this call succeeds, then the method can be invoked as normal.
* This call will only succeed when the application has sufficient security privileges.
* If this call fails then the method may fail.</p>
*
* @since 2.5
* @version $Id: MethodUtils.java 1166253 2011-09-07 16:27:42Z ggregory $
*/
public class MethodUtils {
/**
* <p>MethodUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as
* <code>MethodUtils.getAccessibleMethod(method)</code>.</p>
*
* <p>This constructor is public to permit tools that require a JavaBean
* instance to operate.</p>
*/
public MethodUtils() {
super();
}
/**
* <p>Invokes a named method whose parameter type matches the object type.</p>
*
* <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
*
* <p>This method supports calls to methods taking primitive parameters
* via passing in wrapping classes. So, for example, a <code>Boolean</code> object
* would match a <code>boolean</code> primitive.</p>
*
* <p>This is a convenient wrapper for
* {@link #invokeMethod(Object object,String methodName, Object[] args, Class[] parameterTypes)}.
* </p>
*
* @param object invoke method on this object
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
* @return The value returned by the invoked method
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the method invoked
* @throws IllegalAccessException if the requested method is not accessible via reflection
*/
public static Object invokeMethod(Object object, String methodName,
Object... args) throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
if (args == null) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class<?>[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeMethod(object, methodName, args, parameterTypes);
}
/**
* <p>Invokes a named method whose parameter type matches the object type.</p>
*
* <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
*
* <p>This method supports calls to methods taking primitive parameters
* via passing in wrapping classes. So, for example, a <code>Boolean</code> object
* would match a <code>boolean</code> primitive.</p>
*
* @param object invoke method on this object
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
* @param parameterTypes match these parameters - treat null as empty array
* @return The value returned by the invoked method
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the method invoked
* @throws IllegalAccessException if the requested method is not accessible via reflection
*/
public static Object invokeMethod(Object object, String methodName,
Object[] args, Class<?>[] parameterTypes)
throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
if (parameterTypes == null) {
parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
}
if (args == null) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
Method method = getMatchingAccessibleMethod(object.getClass(),
methodName, parameterTypes);
if (method == null) {
throw new NoSuchMethodException("No such accessible method: "
+ methodName + "() on object: "
+ object.getClass().getName());
}
return method.invoke(object, args);
}
/**
* <p>Invokes a method whose parameter types match exactly the object
* types.</p>
*
* <p>This uses reflection to invoke the method obtained from a call to
* <code>getAccessibleMethod()</code>.</p>
*
* @param object invoke method on this object
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
* @return The value returned by the invoked method
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeExactMethod(Object object, String methodName,
Object... args) throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
if (args == null) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class<?>[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeExactMethod(object, methodName, args, parameterTypes);
}
/**
* <p>Invokes a method whose parameter types match exactly the parameter
* types given.</p>
*
* <p>This uses reflection to invoke the method obtained from a call to
* <code>getAccessibleMethod()</code>.</p>
*
* @param object invoke method on this object
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
* @param parameterTypes match these parameters - treat null as empty array
* @return The value returned by the invoked method
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeExactMethod(Object object, String methodName,
Object[] args, Class<?>[] parameterTypes)
throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
if (args == null) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
if (parameterTypes == null) {
parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
}
Method method = getAccessibleMethod(object.getClass(), methodName,
parameterTypes);
if (method == null) {
throw new NoSuchMethodException("No such accessible method: "
+ methodName + "() on object: "
+ object.getClass().getName());
}
return method.invoke(object, args);
}
/**
* <p>Invokes a static method whose parameter types match exactly the parameter
* types given.</p>
*
* <p>This uses reflection to invoke the method obtained from a call to
* {@link #getAccessibleMethod(Class, String, Class[])}.</p>
*
* @param cls invoke static method on this class
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
* @param parameterTypes match these parameters - treat null as empty array
* @return The value returned by the invoked method
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeExactStaticMethod(Class<?> cls, String methodName,
Object[] args, Class<?>[] parameterTypes)
throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
if (args == null) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
if (parameterTypes == null) {
parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
}
Method method = getAccessibleMethod(cls, methodName, parameterTypes);
if (method == null) {
throw new NoSuchMethodException("No such accessible method: "
+ methodName + "() on class: " + cls.getName());
}
return method.invoke(null, args);
}
/**
* <p>Invokes a named static method whose parameter type matches the object type.</p>
*
* <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
*
* <p>This method supports calls to methods taking primitive parameters
* via passing in wrapping classes. So, for example, a <code>Boolean</code> class
* would match a <code>boolean</code> primitive.</p>
*
* <p>This is a convenient wrapper for
* {@link #invokeStaticMethod(Class objectClass,String methodName,Object [] args,Class[] parameterTypes)}.
* </p>
*
* @param cls invoke static method on this class
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
* @return The value returned by the invoked method
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeStaticMethod(Class<?> cls, String methodName,
Object... args) throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
if (args == null) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class<?>[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeStaticMethod(cls, methodName, args, parameterTypes);
}
/**
* <p>Invokes a named static method whose parameter type matches the object type.</p>
*
* <p>This method delegates the method search to {@link #getMatchingAccessibleMethod(Class, String, Class[])}.</p>
*
* <p>This method supports calls to methods taking primitive parameters
* via passing in wrapping classes. So, for example, a <code>Boolean</code> class
* would match a <code>boolean</code> primitive.</p>
*
*
* @param cls invoke static method on this class
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
* @param parameterTypes match these parameters - treat null as empty array
* @return The value returned by the invoked method
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeStaticMethod(Class<?> cls, String methodName,
Object[] args, Class<?>[] parameterTypes)
throws NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
if (parameterTypes == null) {
parameterTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
}
if (args == null) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
Method method = getMatchingAccessibleMethod(cls, methodName,
parameterTypes);
if (method == null) {
throw new NoSuchMethodException("No such accessible method: "
+ methodName + "() on class: " + cls.getName());
}
return method.invoke(null, args);
}
/**
* <p>Invokes a static method whose parameter types match exactly the object
* types.</p>
*
* <p>This uses reflection to invoke the method obtained from a call to
* {@link #getAccessibleMethod(Class, String, Class[])}.</p>
*
* @param cls invoke static method on this class
* @param methodName get method with this name
* @param args use these arguments - treat null as empty array
* @return The value returned by the invoked method
*
* @throws NoSuchMethodException if there is no such accessible method
* @throws InvocationTargetException wraps an exception thrown by the
* method invoked
* @throws IllegalAccessException if the requested method is not accessible
* via reflection
*/
public static Object invokeExactStaticMethod(Class<?> cls, String methodName,
Object... args) throws NoSuchMethodException,
IllegalAccessException, InvocationTargetException {
if (args == null) {
args = ArrayUtils.EMPTY_OBJECT_ARRAY;
}
int arguments = args.length;
Class<?>[] parameterTypes = new Class[arguments];
for (int i = 0; i < arguments; i++) {
parameterTypes[i] = args[i].getClass();
}
return invokeExactStaticMethod(cls, methodName, args, parameterTypes);
}
/**
* <p>Returns an accessible method (that is, one that can be invoked via
* reflection) with given name and parameters. If no such method
* can be found, return <code>null</code>.
* This is just a convenient wrapper for
* {@link #getAccessibleMethod(Method method)}.</p>
*
* @param cls get method from this class
* @param methodName get method with this name
* @param parameterTypes with these parameters types
* @return The accessible method
*/
public static Method getAccessibleMethod(Class<?> cls, String methodName,
Class<?>... parameterTypes) {
try {
return getAccessibleMethod(cls.getMethod(methodName,
parameterTypes));
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* <p>Returns an accessible method (that is, one that can be invoked via
* reflection) that implements the specified Method. If no such method
* can be found, return <code>null</code>.</p>
*
* @param method The method that we wish to call
* @return The accessible method
*/
public static Method getAccessibleMethod(Method method) {
if (!MemberUtils.isAccessible(method)) {
return null;
}
// If the declaring class is public, we are done
Class<?> cls = method.getDeclaringClass();
if (Modifier.isPublic(cls.getModifiers())) {
return method;
}
String methodName = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
// Check the implemented interfaces and subinterfaces
method = getAccessibleMethodFromInterfaceNest(cls, methodName,
parameterTypes);
// Check the superclass chain
if (method == null) {
method = getAccessibleMethodFromSuperclass(cls, methodName,
parameterTypes);
}
return method;
}
/**
* <p>Returns an accessible method (that is, one that can be invoked via
* reflection) by scanning through the superclasses. If no such method
* can be found, return <code>null</code>.</p>
*
* @param cls Class to be checked
* @param methodName Method name of the method we wish to call
* @param parameterTypes The parameter type signatures
* @return the accessible method or <code>null</code> if not found
*/
private static Method getAccessibleMethodFromSuperclass(Class<?> cls,
String methodName, Class<?>... parameterTypes) {
Class<?> parentClass = cls.getSuperclass();
while (parentClass != null) {
if (Modifier.isPublic(parentClass.getModifiers())) {
try {
return parentClass.getMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
return null;
}
}
parentClass = parentClass.getSuperclass();
}
return null;
}
/**
* <p>Returns an accessible method (that is, one that can be invoked via
* reflection) that implements the specified method, by scanning through
* all implemented interfaces and subinterfaces. If no such method
* can be found, return <code>null</code>.</p>
*
* <p>There isn't any good reason why this method must be private.
* It is because there doesn't seem any reason why other classes should
* call this rather than the higher level methods.</p>
*
* @param cls Parent class for the interfaces to be checked
* @param methodName Method name of the method we wish to call
* @param parameterTypes The parameter type signatures
* @return the accessible method or <code>null</code> if not found
*/
private static Method getAccessibleMethodFromInterfaceNest(Class<?> cls,
String methodName, Class<?>... parameterTypes) {
Method method = null;
// Search up the superclass chain
for (; cls != null; cls = cls.getSuperclass()) {
// Check the implemented interfaces of the parent class
Class<?>[] interfaces = cls.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
// Is this interface public?
if (!Modifier.isPublic(interfaces[i].getModifiers())) {
continue;
}
// Does the method exist on this interface?
try {
method = interfaces[i].getDeclaredMethod(methodName,
parameterTypes);
} catch (NoSuchMethodException e) { // NOPMD
/*
* Swallow, if no method is found after the loop then this
* method returns null.
*/
}
if (method != null) {
break;
}
// Recursively check our parent interfaces
method = getAccessibleMethodFromInterfaceNest(interfaces[i],
methodName, parameterTypes);
if (method != null) {
break;
}
}
}
return method;
}
/**
* <p>Finds an accessible method that matches the given name and has compatible parameters.
* Compatible parameters mean that every method parameter is assignable from
* the given parameters.
* In other words, it finds a method with the given name
* that will take the parameters given.<p>
*
* <p>This method is used by
* {@link
* #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}.
*
* <p>This method can match primitive parameter by passing in wrapper classes.
* For example, a <code>Boolean</code> will match a primitive <code>boolean</code>
* parameter.
*
* @param cls find method in this class
* @param methodName find method with this name
* @param parameterTypes find method with most compatible parameters
* @return The accessible method
*/
public static Method getMatchingAccessibleMethod(Class<?> cls,
String methodName, Class<?>... parameterTypes) {
try {
Method method = cls.getMethod(methodName, parameterTypes);
MemberUtils.setAccessibleWorkaround(method);
return method;
} catch (NoSuchMethodException e) { // NOPMD - Swallow the exception
}
// search through all methods
Method bestMatch = null;
Method[] methods = cls.getMethods();
for (Method method : methods) {
// compare name and parameters
if (method.getName().equals(methodName) && ClassUtils.isAssignable(parameterTypes, method.getParameterTypes(), true)) {
// get accessible version of method
Method accessibleMethod = getAccessibleMethod(method);
if (accessibleMethod != null && (bestMatch == null || MemberUtils.compareParameterTypes(
accessibleMethod.getParameterTypes(),
bestMatch.getParameterTypes(),
parameterTypes) < 0)) {
bestMatch = accessibleMethod;
}
}
}
if (bestMatch != null) {
MemberUtils.setAccessibleWorkaround(bestMatch);
}
return bestMatch;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.tuple;
/**
* <p>An immutable pair consisting of two {@code Object} elements.</p>
*
* <p>Although the implementation is immutable, there is no restriction on the objects
* that may be stored. If mutable objects are stored in the pair, then the pair
* itself effectively becomes mutable. The class is also not {@code final}, so a subclass
* could add undesirable behaviour.</p>
*
* <p>#ThreadSafe# if the objects are threadsafe</p>
*
* @param <L> the left element type
* @param <R> the right element type
*
* @since Lang 3.0
* @version $Id: ImmutablePair.java 1127544 2011-05-25 14:35:42Z scolebourne $
*/
public final class ImmutablePair<L, R> extends Pair<L, R> {
/** Serialization version */
private static final long serialVersionUID = 4954918890077093841L;
/** Left object */
public final L left;
/** Right object */
public final R right;
/**
* <p>Obtains an immutable pair of from two objects inferring the generic types.</p>
*
* <p>This factory allows the pair to be created using inference to
* obtain the generic types.</p>
*
* @param <L> the left element type
* @param <R> the right element type
* @param left the left element, may be null
* @param right the right element, may be null
* @return a pair formed from the two parameters, not null
*/
public static <L, R> ImmutablePair<L, R> of(L left, R right) {
return new ImmutablePair<L, R>(left, right);
}
/**
* Create a new pair instance.
*
* @param left the left value, may be null
* @param right the right value, may be null
*/
public ImmutablePair(L left, R right) {
super();
this.left = left;
this.right = right;
}
//-----------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public L getLeft() {
return left;
}
/**
* {@inheritDoc}
*/
@Override
public R getRight() {
return right;
}
/**
* <p>Throws {@code UnsupportedOperationException}.</p>
*
* <p>This pair is immutable, so this operation is not supported.</p>
*
* @param value the value to set
* @return never
* @throws UnsupportedOperationException as this operation is not supported
*/
public R setValue(R value) {
throw new UnsupportedOperationException();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package external.org.apache.commons.lang3.tuple;
import java.io.Serializable;
import java.util.Map;
import external.org.apache.commons.lang3.ObjectUtils;
import external.org.apache.commons.lang3.builder.CompareToBuilder;
/**
* <p>A pair consisting of two elements.</p>
*
* <p>This class is an abstract implementation defining the basic API.
* It refers to the elements as 'left' and 'right'. It also implements the
* {@code Map.Entry} interface where the key is 'left' and the value is 'right'.</p>
*
* <p>Subclass implementations may be mutable or immutable.
* However, there is no restriction on the type of the stored objects that may be stored.
* If mutable objects are stored in the pair, then the pair itself effectively becomes mutable.</p>
*
* @param <L> the left element type
* @param <R> the right element type
*
* @since Lang 3.0
* @version $Id: Pair.java 1142401 2011-07-03 08:30:12Z bayard $
*/
public abstract class Pair<L, R> implements Map.Entry<L, R>, Comparable<Pair<L, R>>, Serializable {
/** Serialization version */
private static final long serialVersionUID = 4954918890077093841L;
/**
* <p>Obtains an immutable pair of from two objects inferring the generic types.</p>
*
* <p>This factory allows the pair to be created using inference to
* obtain the generic types.</p>
*
* @param <L> the left element type
* @param <R> the right element type
* @param left the left element, may be null
* @param right the right element, may be null
* @return a pair formed from the two parameters, not null
*/
public static <L, R> Pair<L, R> of(L left, R right) {
return new ImmutablePair<L, R>(left, right);
}
//-----------------------------------------------------------------------
/**
* <p>Gets the left element from this pair.</p>
*
* <p>When treated as a key-value pair, this is the key.</p>
*
* @return the left element, may be null
*/
public abstract L getLeft();
/**
* <p>Gets the right element from this pair.</p>
*
* <p>When treated as a key-value pair, this is the value.</p>
*
* @return the right element, may be null
*/
public abstract R getRight();
/**
* <p>Gets the key from this pair.</p>
*
* <p>This method implements the {@code Map.Entry} interface returning the
* left element as the key.</p>
*
* @return the left element as the key, may be null
*/
public final L getKey() {
return getLeft();
}
/**
* <p>Gets the value from this pair.</p>
*
* <p>This method implements the {@code Map.Entry} interface returning the
* right element as the value.</p>
*
* @return the right element as the value, may be null
*/
public R getValue() {
return getRight();
}
//-----------------------------------------------------------------------
/**
* <p>Compares the pair based on the left element followed by the right element.
* The types must be {@code Comparable}.</p>
*
* @param other the other pair, not null
* @return negative if this is less, zero if equal, positive if greater
*/
public int compareTo(Pair<L, R> other) {
return new CompareToBuilder().append(getLeft(), other.getLeft())
.append(getRight(), other.getRight()).toComparison();
}
/**
* <p>Compares this pair to another based on the two elements.</p>
*
* @param obj the object to compare to, null returns false
* @return true if the elements of the pair are equal
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Map.Entry<?, ?>) {
Map.Entry<?, ?> other = (Map.Entry<?, ?>) obj;
return ObjectUtils.equals(getKey(), other.getKey())
&& ObjectUtils.equals(getValue(), other.getValue());
}
return false;
}
/**
* <p>Returns a suitable hash code.
* The hash code follows the definition in {@code Map.Entry}.</p>
*
* @return the hash code
*/
@Override
public int hashCode() {
// see Map.Entry API specification
return (getKey() == null ? 0 : getKey().hashCode()) ^
(getValue() == null ? 0 : getValue().hashCode());
}
/**
* <p>Returns a String representation of this pair using the format {@code ($left,$right)}.</p>
*
* @return a string describing this object, not null
*/
@Override
public String toString() {
return new StringBuilder().append('(').append(getLeft()).append(',').append(getRight()).append(')').toString();
}
/**
* <p>Formats the receiver using the given format.</p>
*
* <p>This uses {@link java.util.Formattable} to perform the formatting. Two variables may
* be used to embed the left and right elements. Use {@code %1$s} for the left
* element (key) and {@code %2$s} for the right element (value).
* The default format used by {@code toString()} is {@code (%1$s,%2$s)}.</p>
*
* @param format the format string, optionally containing {@code %1$s} and {@code %2$s}, not null
* @return the formatted string, not null
*/
public String toString(String format) {
return String.format(format, getLeft(), getRight());
}
}
<resources>
<string name="app_name">xposedcompat_new</string>
</resources>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment