Commit ce894a8c authored by Star Diao's avatar Star Diao

delete some plugins

parent 7c4bf69f
apply plugin: 'com.android.library'
android {
compileSdkVersion 25
defaultConfig {
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
javaCompileOptions { annotationProcessorOptions { includeCompileClasspath = true } }
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
buildToolsVersion '26.0.2'
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
compile "com.android.support:support-v4:${PROJECT_SUPPORTLIBVERSION}"
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'
// compile project(':nexus')
compile 'cn.jiguang.sdk:jpush:3.1.6' // 此处以JPush 3.1.6 版本为例。
compile 'cn.jiguang.sdk:jcore:1.2.5' // 此处以JCore 1.2.5 版本为例。
compile project(':nexus')
compile project(':weex-framework')
}
repositories {
mavenCentral()
google()
maven { url 'http://192.168.12.122:8090/nexus/repository/maven-snapshots/' }
}
# 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
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontnote
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.app.IntentService
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class com.android.vending.licensing.ILicensingService
-dontwarn cn.jpush.**
-keep class cn.jpush.** { *; }
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.gsst.eros" >
<!--jpush-->
<permission
android:name="com.eros.wx.permission.JPUSH_MESSAGE"
android:protectionLevel="signature" />
<!-- Required 一些系统要求的权限,如访问网络等-->
<uses-permission android:name="com.eros.wx.permission.JPUSH_MESSAGE" />
<uses-permission android:name="android.permission.RECEIVE_USER_PRESENT" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application>
<!-- Required SDK 核心功能-->
<!-- 可配置android:process参数将PushService放在其他进程中 -->
<service
android:name="cn.jpush.android.service.PushService"
android:process=":pushcore"
android:exported="false">
<intent-filter>
<action android:name="cn.jpush.android.intent.REGISTER" />
<action android:name="cn.jpush.android.intent.REPORT" />
<action android:name="cn.jpush.android.intent.PushService" />
<action android:name="cn.jpush.android.intent.PUSH_TIME" />
</intent-filter>
</service>
<receiver
android:name="com.gsst.plugin.JPushErosPlugin$JPushReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="cn.jpush.android.intent.REGISTRATION" /> <!--Required 用户注册SDK的intent-->
<action android:name="cn.jpush.android.intent.MESSAGE_RECEIVED" /> <!--Required 用户接收SDK消息的intent-->
<action android:name="cn.jpush.android.intent.NOTIFICATION_RECEIVED" /> <!--Required 用户接收SDK通知栏信息的intent-->
<action android:name="cn.jpush.android.intent.NOTIFICATION_OPENED" /> <!--Required 用户打开自定义通知栏的intent-->
<action android:name="cn.jpush.android.intent.ACTION_RICHPUSH_CALLBACK" /> <!--Optional 用户接受Rich Push Javascript 回调函数的intent-->
<action android:name="cn.jpush.android.intent.CONNECTION" /><!-- 接收网络变化 连接/断开 since 1.6.3 -->
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
<!-- User defined. For test only 用户自定义接收消息器,3.0.7开始支持,目前新tag/alias接口设置结果会在该广播接收器对应的方法中回调 暂时无用-->
<receiver android:name="com.gsst.plugin.JPushErosPlugin$MyJPushMessageReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="cn.jpush.android.intent.RECEIVE_MESSAGE" />
<category android:name="${applicationId}" />
</intent-filter>
</receiver>
</application>
</manifest>
package com.gsst.plugin;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.OpenableColumns;
import android.util.Log;
import com.alibaba.weex.plugin.annotation.WeexModule;
import com.eros.framework.constant.WXEventCenter;
import com.eros.framework.event.mediator.EventCenter;
import com.eros.framework.manager.ManagerFactory;
import com.eros.framework.manager.impl.dispatcher.DispatchEventManager;
import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.common.WXModule;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.callback.Callback;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.service.JPushMessageReceiver;
/**
* Created by liuyuanxiao on 2018/5/4.
*/
@WeexModule(name = "jpushWeexPlugin", lazyLoad = true)
public class JPushErosPlugin extends WXModule {
private static Bundle mCachedBundle;
private static Bundle mRidBundle;
private final static String RECEIVE_NOTIFICATION = "receiveNotification";
private final static String RECEIVE_NOTIFICATION_OPEN = "receiveNotificationOpen";
private final static String RECEIVE_CUSTOM_MESSAGE = "receivePushMsg";
private final static String OPEN_NOTIFICATION = "openNotification";
private final static String RECEIVE_REGISTRATION_ID = "getRegistrationId";
private final static String CONNECTION_CHANGE = "connectionChange";
@JSMethod(uiThread = true)
public void setup(JSCallback receiveNotificationCallback,JSCallback receiveNotificationOpenCallback) {
// Toast.makeText(mWXSDKInstance.getContext(), "Hello Eros test Plugin", Toast.LENGTH_LONG).show();
JPushInterface.init(mWXSDKInstance.getContext());
//接收消息被打开时的推送事件
EventCenter.Event openNotifyEvent = new EventCenter.Event(mWXSDKInstance.getInstanceId(),
false, receiveNotificationOpenCallback, mWXSDKInstance.getBundleUrl(), RECEIVE_NOTIFICATION_OPEN);
Intent on = new Intent(WXEventCenter.EVENT_JS_ON);
on.putExtra("data", openNotifyEvent);
ManagerFactory.getManagerService(DispatchEventManager.class).getBus().post(on);
//接收消息时的推送事件(普通消息,自定义消息)
EventCenter.Event notifyEvent = new EventCenter.Event(mWXSDKInstance.getInstanceId(),
false, receiveNotificationCallback, mWXSDKInstance.getBundleUrl(), RECEIVE_NOTIFICATION);
Intent inten = new Intent(WXEventCenter.EVENT_JS_ON);
inten.putExtra("data", notifyEvent);
ManagerFactory.getManagerService(DispatchEventManager.class).getBus().post(inten);
Log.i("PLUGIN","init jpush") ;
}
@JSMethod(uiThread = true)
public void applyPushAuthority(){
JPushInterface.requestPermission(mWXSDKInstance.getContext());
}
@JSMethod(uiThread = true)
public void getLaunchAppNotification(){
}
@JSMethod(uiThread = true)
public void getRegistrationID(JSCallback callback){
Map<String,String> message = new HashMap<>() ;
String registrationID = "" ;
registrationID = JPushInterface.getRegistrationID(mWXSDKInstance.getContext()) ;
if((!"".equals(registrationID)) && registrationID != null){
callback.invoke(registrationID);
}
}
public static class JPushReceiver extends BroadcastReceiver {
public JPushReceiver() {
}
@Override
public void onReceive(Context context, Intent data) {
if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(data.getAction())) {
mCachedBundle = data.getExtras();
try {
String message = data.getStringExtra(JPushInterface.EXTRA_MESSAGE);
Intent emit = new Intent( WXEventCenter.EVENT_JS_EMIT);
emit.putExtra("data", new EventCenter.Emit(RECEIVE_CUSTOM_MESSAGE, message));
ManagerFactory.getManagerService(DispatchEventManager.class).getBus().post(emit);
} catch (Exception e) {
e.printStackTrace();
}
}
else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(data.getAction())) {
//收到推送下来的通知
mCachedBundle = data.getExtras();
try {
// 通知内容
String alertContent = mCachedBundle.getString(JPushInterface.EXTRA_ALERT);
// extra 字段的 json 字符串
String extras = mCachedBundle.getString(JPushInterface.EXTRA_EXTRA);
} catch (Exception e) {
e.printStackTrace();
}
} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(data.getAction())) {
mCachedBundle = data.getExtras();
try {
//用户点击打开了通知
// 通知内容
String alertContent = mCachedBundle.getString(JPushInterface.EXTRA_ALERT);
// extra 字段的 json 字符串
String extras = mCachedBundle.getString(JPushInterface.EXTRA_EXTRA);
//初始化activity
Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtras(mCachedBundle);
context.startActivity(intent);
//发送事件
Intent emit = new Intent( WXEventCenter.EVENT_JS_EMIT);
emit.putExtra("data", new EventCenter.Emit(RECEIVE_NOTIFICATION_OPEN, extras));
ManagerFactory.getManagerService(DispatchEventManager.class).getBus().post(emit);
} catch (Exception e) {
e.printStackTrace();
}
// 应用注册完成后会发送广播,在 JS 中 JPushModule.addGetRegistrationIdListener 接口可以第一时间得到 registrationId
// After JPush finished registering, will send this broadcast, use JPushModule.addGetRegistrationIdListener
// to get registrationId in the first instance.
} else if (JPushInterface.ACTION_REGISTRATION_ID.equals(data.getAction())) {
mRidBundle = data.getExtras();
try {
} catch (Exception e) {
e.printStackTrace();
}
} else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(data.getAction())) {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//暂时无用
public static class MyJPushMessageReceiver extends JPushMessageReceiver {
@Override
public void onTagOperatorResult(Context context, JPushMessage jPushMessage) {
String log = "action - onTagOperatorResult, sequence:" + jPushMessage.getSequence()
+ ", tags: " + jPushMessage.getTags();
super.onTagOperatorResult(context, jPushMessage);
}
@Override
public void onCheckTagOperatorResult(Context context,JPushMessage jPushMessage){
String log = "action - onCheckTagOperatorResult, sequence:" + jPushMessage.getSequence()
+ ", checktag: " + jPushMessage.getCheckTag();
super.onCheckTagOperatorResult(context, jPushMessage);
}
@Override
public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
String log = "action - onAliasOperatorResult, sequence:" + jPushMessage.getSequence()
+ ", alias: " + jPushMessage.getAlias();
super.onAliasOperatorResult(context, jPushMessage);
}
}
}
<resources>
<string name="app_name">pluginSimple</string>
</resources>
......@@ -2,6 +2,4 @@ include ':app',':weex-framework',':sdk',':nexus',':pgyplugin'
project(':weex-framework').projectDir = new File(settingsDir,'/eros-framework')
project(':sdk').projectDir = new File(settingsDir,'/nexus/sdk')
project(':nexus').projectDir = new File(settingsDir,'/nexus')
//project(':gsstJPush').projectDir = new File(settingsDir,'/gsstJPush')
project(':pgyplugin').projectDir = new File(settingsDir,'/pgyplugin')
//project(':wechatplugin').projectDir = new File(settingsDir,'/wechatplugin')
apply plugin: 'com.android.library'
android {
compileSdkVersion 26
// baseFeature true
defaultConfig {
minSdkVersion 17
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
buildToolsVersion '26.0.2'
}
dependencies {
compile 'com.android.support:appcompat-v7:25.3.1'
// api 'com.android.support.constraint:constraint-layout:1.1.3'
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'junit:junit:4.12'
compile 'com.android.support.test:runner:1.0.2'
compile 'com.android.support.test.espresso:espresso-core:3.0.2'
compile 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
compile project(':nexus')
}
repositories {
mavenCentral()
google()
maven { url 'http://192.168.12.122:8090/nexus/repository/maven-snapshots/' }
}
# 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
package com.gsst.cityclubstaff;
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.gsst.cityclubstaff.test", appContext.getPackageName());
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.gsst.cityclubstaff">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="false"
android:label="@string/app_name"
android:supportsRtl="true"
tools:replace="android:allowBackup">
</application>
</manifest>
\ No newline at end of file
package com.gsst.cityclubstaff;
public interface ModuleResultListener {
void onResult(Object o);
}
\ No newline at end of file
package com.gsst.cityclubstaff;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Utils {
/**
* Read bytes from InputStream
*
* @param inputStream stream
* @return ByteArray
* @throws IOException io error
*/
public static byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
public static File getCacheFolder(Context context) {
File cacheDir = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cacheDir = new File(Environment.getExternalStorageDirectory(), ".cache");
if (!cacheDir.isDirectory()) {
cacheDir.mkdirs();
}
}
if(!cacheDir.isDirectory()) {
cacheDir = context.getCacheDir(); //get system cache folder
}
return cacheDir;
}
public static File downloadAndCacheFile(Context context, String url) {
URL fileURL = null;
try {
fileURL = new URL(url);
Log.d(WechatModule.TAG, String.format("Start downloading file at %s.", url));
HttpURLConnection connection = (HttpURLConnection) fileURL.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.e(WechatModule.TAG, String.format("Failed to download file from %s, response code: %d.", url, connection.getResponseCode()));
return null;
}
InputStream inputStream = connection.getInputStream();
File cacheDir = getCacheFolder(context);
File cacheFile = new File(cacheDir, url.substring(url.lastIndexOf("/") + 1));
FileOutputStream outputStream = new FileOutputStream(cacheFile);
byte buffer[] = new byte[4096];
int dataSize;
while ((dataSize = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, dataSize);
}
outputStream.close();
Log.d(WechatModule.TAG, String.format("File was downloaded and saved at %s.", cacheFile.getAbsolutePath()));
return cacheFile;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.gsst.cityclubstaff;
import android.app.Activity;
import com.alibaba.weex.plugin.annotation.WeexModule;
import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.common.WXModule;
import com.alibaba.fastjson.JSONObject;
/**
* Created by Acathur on 23/10/2017.
* Copyright (c) 2017 Instapp. All rights reserved.
*/
@WeexModule(name = "wechat", lazyLoad = true)
public class Wechat extends WXModule {
@JSMethod
public void init(String appId, final JSCallback jsCallback){
WechatModule.getInstance(mWXSDKInstance.getContext()).init(appId, new ModuleResultListener() {
@Override
public void onResult(Object o) {
jsCallback.invoke(o);
}
});
}
@JSMethod
public void checkInstalled(final JSCallback jsCallback){
WechatModule.getInstance(mWXSDKInstance.getContext()).checkInstalled(new ModuleResultListener() {
@Override
public void onResult(Object o) {
jsCallback.invoke(o);
}
});
}
@JSMethod
public void share(JSONObject params, final JSCallback jsCallback){
WechatModule.getInstance(mWXSDKInstance.getContext()).share(params, new ModuleResultListener() {
@Override
public void onResult(Object o) {
jsCallback.invoke(o);
}
});
}
@JSMethod
public void pay(JSONObject params, final JSCallback jsCallback){
WechatModule.getInstance(mWXSDKInstance.getContext()).pay(params, new ModuleResultListener() {
@Override
public void onResult(Object o) {
jsCallback.invoke(o);
}
});
}
@JSMethod
public void auth(JSONObject params, final JSCallback jsCallback){
WechatModule.getInstance(mWXSDKInstance.getContext()).auth(params, new ModuleResultListener() {
@Override
public void onResult(Object o) {
jsCallback.invoke(o);
}
});
}
}
package com.gsst.cityclubstaff.wxapi;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.alibaba.fastjson.JSONObject;
import com.gsst.cityclubstaff.WechatModule;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
/**
* Created by Acathur on 19/10/2017.
* Copyright (c) 2017 Instapp. All rights reserved.
*/
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IWXAPI api = WechatModule.getWXAPIWithContext(this);
if (api == null) {
startMainActivity();
} else {
api.handleIntent(getIntent(), this);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
IWXAPI api = WechatModule.getWXAPIWithContext(this);
if (api == null) {
startMainActivity();
} else {
api.handleIntent(intent, this);
}
}
@Override
public void onResp(BaseResp resp) {
Log.d(WechatModule.TAG, "[BaseResp]");
Log.d(WechatModule.TAG, resp.toString());
String message = null;
JSONObject result = new JSONObject();
if (resp.errCode == 0) {
switch (resp.getType()) {
case ConstantsAPI.COMMAND_SENDAUTH:
SendAuth.Resp res = ((SendAuth.Resp) resp);
result.put("code", res.code);
result.put("state", res.state);
result.put("country", res.country);
result.put("lang", res.lang);
break;
default:
break;
}
} else {
switch (resp.errCode) {
case BaseResp.ErrCode.ERR_USER_CANCEL:
message = WechatModule.ERROR_WECHAT_RESPONSE_USER_CANCEL;
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
message = WechatModule.ERROR_WECHAT_RESPONSE_AUTH_DENIED;
break;
case BaseResp.ErrCode.ERR_SENT_FAILED:
message = WechatModule.ERROR_WECHAT_RESPONSE_SENT_FAILED;
break;
case BaseResp.ErrCode.ERR_UNSUPPORT:
message = WechatModule.ERROR_WECHAT_RESPONSE_UNSUPPORT;
break;
case BaseResp.ErrCode.ERR_COMM:
message = WechatModule.ERROR_WECHAT_RESPONSE_COMMON;
break;
default:
message = WechatModule.ERROR_WECHAT_RESPONSE_UNKNOWN;
break;
}
message = resp.errStr != null ? resp.errStr : message;
}
WechatModule.getInstance(this).onResp(resp.errCode, result, message);
finish();
}
@Override
public void onReq(BaseReq req) {
finish();
}
protected void startMainActivity() {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setPackage(getApplicationContext().getPackageName());
getApplicationContext().startActivity(intent);
}
}
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".wxapi.WXEntryActivity">
</android.support.constraint.ConstraintLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#2db7f5</color>
</resources>
<resources>
<string name="app_name">wechatplugin</string>
</resources>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
package com.gsst.cityclubstaff;
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
*.pyc
build32/
build64/
cmake-build-debug
cscope.out
cmake_minimum_required(VERSION 3.4.1)
project(WeexCore)
add_subdirectory(Source)
cmake_minimum_required(VERSION 3.4.1)
set(WEEXCORE_LIBRARY_NAME weexcore)
message("${ANDROID_STL} ")
if ("${ANDROID_STL}" STREQUAL "c++_static")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++1y")
elseif ("${ANDROID_STL}" STREQUAL "gnustl_static")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++1y")
endif ()
add_compile_options(-fexceptions)
add_definitions(-DGNU_SUPPORT=1)
add_definitions(-DJSONCPP_NO_LOCALE_SUPPORT=1)
add_definitions(-DDEBUG=1)
add_definitions(-DOS_ANDROID=1)
add_definitions(-DRENDER_LOG=0)
add_definitions(-DPERFORMANCE_LOG=0)
add_definitions(-DLAYOUT_LOG=0)
add_definitions(-DJSAPI_LOG=0)
add_definitions(-DDOM_PARSER_LOG=0)
set(COMMON_SRCS
./base/time_point.cc
./base/thread/thread_impl_posix.cc
./base/thread/thread_impl_android.cc
./base/message_loop/message_loop.cc
./base/message_loop/message_pump_posix.cc
./base/message_loop/message_pump_android.cc
./base/third_party/icu/icu_utf.cpp
./core/render/manager/render_manager.cpp
./core/render/page/render_page.cpp
./core/render/node/render_object.cpp
./core/render/node/factory/render_creator.cpp
./core/render/node/render_appbar.cpp
./core/render/node/render_list.cpp
./core/render/node/render_mask.cpp
./core/render/node/render_scroller.cpp
./core/render/node/render_text.cpp
./core/render/action/render_action_add_event.cpp
./core/render/action/render_action_remove_event.cpp
./core/render/action/render_action_add_element.cpp
./core/render/action/render_action_remove_element.cpp
./core/render/action/render_action_move_element.cpp
./core/render/action/render_action_createbody.cpp
./core/render/action/render_action_createfinish.cpp
./core/render/action/render_action_appendtree_createfinish.cpp
./core/render/action/render_action_layout.cpp
./core/render/action/render_action_update_attr.cpp
./core/render/action/render_action_update_style.cpp
./core/render/action/render_action_render_success.cpp
./core/render/action/render_action_trigger_vsync.cpp
./core/layout/layout.cpp
./core/layout/style.cpp
./core/css/css_value_getter.cpp
./core/config/core_environment.cpp
./core/moniter/render_performance.cpp
./core/bridge/platform/core_side_in_platform.cpp
./core/bridge/script/core_side_in_script.cpp
./core/parser/dom_wson.cpp
./core/data_render/ast.cc
./core/data_render/ast_builder.cc
./core/data_render/ast_factory.cc
./core/data_render/class.cc
./core/data_render/class_array.cc
./core/data_render/class_json.cc
./core/data_render/class_string.cc
./core/data_render/class_factory.cc
./core/data_render/class_object.cc
./core/data_render/code_generator.cc
./core/data_render/exec_state.cc
./core/data_render/object.cc
./core/data_render/parser.cc
./core/data_render/rax_jsx_ast.cc
./core/data_render/js_common_function.cc
./core/data_render/rax_parser.cc
./core/data_render/rax_parser_builder.cc
./core/data_render/rax_parser_context.cc
./core/data_render/rax_parser_scope.cc
./core/data_render/rax_parser_statistics.cc
./core/data_render/rax_source_locator.cc
./core/data_render/statement.cc
./core/data_render/string_table.cc
./core/data_render/table.cc
./core/data_render/token.cc
./core/data_render/tokenizer.cc
./core/data_render/vm.cc
./core/data_render/binary_file.cc
./core/data_render/vnode/vnode.cc
./core/data_render/vnode/vcomponent.cc
./core/data_render/vnode/vnode_exec_env.cc
./core/data_render/vnode/vnode_render_manager.cc
./core/data_render/vnode/vnode_render_context.cc
)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/wson)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/wson)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/third_party/json11)
SET(FINAL_ADD_LIBRARY
${COMMON_SRCS}
)
SET(FINAL_TARGET_LINK_LIBRARIES wson json11)
if (ANDROID)
## add_subdirectory for subdirectory has a CMakeLists.txt
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/IPC)
## include_directories for include head file
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/IPC)
set (ANDROID_SRCS
./android/jniprebuild/jni_load.cc
./android/base/jni/android_jni.cpp
./android/base/jni/jbytearray_ref.cpp
./android/base/jni/scoped_java_ref.cpp
./android/base/base64/base64.cpp
./android/base/base64/modp_base64/modp_b64.cc
./android/base/string/scoped_jstring.cpp
./android/base/string/scoped_jstring_utf8.cpp
./android/base/string/jstring_cache.cpp
./android/wrap/content_box_measurement_impl_android.cpp
./android/wrap/wx_debug_js_bridge.cpp
./android/wrap/native_render_object_utils_impl_android.cpp
./android/bridge/platform/android_side.cpp
./android/bridge/platform/android_bridge.cpp
./android/bridge/script/script_side_in_multi_so.cpp
./android/bridge/script/script_side_in_multi_process.cpp
./android/bridge/script_bridge_in_multi_so.cpp
./android/bridge/script_bridge_in_multi_process.cpp
./android/bridge/multi_process_and_so_initializer.cpp
./android/bridge/multi_so_initializer.cpp
./android/wrap/wml_bridge.cpp
./android/utils/cache_utils.cpp
./android/utils/params_utils.cpp
./android/utils/so_utils.cpp
./android/utils/IPCStringResult.cpp
./android/wrap/log_utils.cpp
./android/wrap/hash_set.cpp
./android/wrap/wx_map.cpp
./android/wrap/wx_js_object.cpp
./android/wrap/wx_bridge.cpp
./android/wrap/wx_params.cpp
./android/base/jni_type.cpp
./android/jsengine/multiprocess/WeexJSConnection.cpp
./android/jsengine/multiprocess/ExtendJSApi.cpp
)
SET(FINAL_ADD_LIBRARY
${FINAL_ADD_LIBRARY}
${ANDROID_SRCS}
)
SET(FINAL_TARGET_LINK_LIBRARIES
${FINAL_TARGET_LINK_LIBRARIES}
wson
android
weexipc
log
z
)
endif (ANDROID)
##if(iOS)
add_definitions(-DTARGET_OS_IPHONE=1)
##endif(iOS)
add_library(${WEEXCORE_LIBRARY_NAME} SHARED ${FINAL_ADD_LIBRARY})
target_include_directories(${WEEXCORE_LIBRARY_NAME} PUBLIC .)
target_link_libraries(${WEEXCORE_LIBRARY_NAME} ${FINAL_TARGET_LINK_LIBRARIES})
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCBUFFER_H
#define IPCBUFFER_H
#include <stddef.h>
// A buffer starts with msg.
class IPCBuffer {
public:
virtual ~IPCBuffer() = default;
virtual const void* get() = 0;
virtual size_t length() = 0;
};
#endif /* IPCBUFFER_H */
cmake_minimum_required(VERSION 3.4.1)
set(IPC_LIBRARY_NAME weexipc)
add_library(${IPC_LIBRARY_NAME} STATIC
./Serializing/IPCSerializer.cpp
./IPCResult.cpp
./IPCSender.cpp
./IPCException.cpp
./IPCCommunicator.cpp
./IPCHandler.cpp
./IPCListener.cpp
./IPCFutexPageQueue.cpp
./IPCFutexPageQueue.cpp
./ashmem.c
./IPCCheck.cpp
)
target_include_directories(${IPC_LIBRARY_NAME} PUBLIC .)
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCARGUMENTS_H
#define IPCARGUMENTS_H
#include "IPCType.h"
struct IPCString;
struct IPCByteArray;
class IPCArguments {
public:
virtual ~IPCArguments() = default;
template <typename T>
T get(int index)
{
return *static_cast<const T*>(getData(index));
}
const IPCString* getString(int index)
{
return static_cast<const IPCString*>(getData(index));
}
const IPCByteArray* getByteArray(int index)
{
return static_cast<const IPCByteArray*>(getData(index));
}
virtual const void* getData(int index) = 0;
virtual IPCType getType(int index) = 0;
virtual size_t getCount() = 0;
};
#endif /* IPCARGUMENTS_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCBYTEARRAY_H
#define IPCBYTEARRAY_H
#include <stddef.h>
struct IPCByteArray {
uint32_t length;
char content[1];
};
#endif /* IPCBYTEARRAY_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#if !defined(NDEBUG)
#include "IPCCheck.h"
#include <android/log.h>
#define TAG "linzj_IPC"
void reportCheckFailed(const char* msg, const char* file, int line)
{
__android_log_print(ANDROID_LOG_ERROR, TAG, msg, file, line);
__builtin_trap();
}
void reportUnreachable(const char* file, int line)
{
__android_log_print(ANDROID_LOG_ERROR, TAG, "unreachable statement reached %s %d", file, line);
__builtin_trap();
}
#endif
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCCHECK_H
#define IPCCHECK_H
#include <stdlib.h>
#if defined(NDEBUG)
#define IPC_DCHECK(b)
#define IPC_UNREACHABLE() abort()
#else
void reportCheckFailed(const char* msg, const char* file, int line);
void reportUnreachable(const char* file, int line);
#define IPC_DCHECK(b) \
if (!(b)) { \
reportCheckFailed("CHECK FAILED: " #b " at line %s %d", __FILE__, __LINE__); \
}
#define IPC_UNREACHABLE() reportUnreachable(__FILE__, __LINE__);
#endif
#endif /* IPCCHECK_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCCOMMUNICATOR_H
#define IPCCOMMUNICATOR_H
#include <memory>
class IPCResult;
class IPCArguments;
class IPCBuffer;
class IPCFutexPageQueue;
class IPCCommunicator {
protected:
explicit IPCCommunicator(IPCFutexPageQueue* futexPageQueue);
virtual ~IPCCommunicator();
std::unique_ptr<IPCResult> assembleResult();
std::unique_ptr<IPCArguments> assembleArguments();
std::unique_ptr<IPCBuffer> generateResultBuffer(IPCResult*);
void doSendBufferOnly(IPCBuffer* buffer);
uint32_t doReadPackage();
const char* getBlob();
void releaseBlob();
private:
void doSendBufferOnly(const void* data, size_t s);
size_t doSendBufferPage(const void* data, size_t s, size_t pageSize);
void doRecvBufferOnly(void* data, size_t s);
std::unique_ptr<char[]> m_package;
// weakref to a IPCFutexPageQueue object.
IPCFutexPageQueue* m_futexPageQueue;
};
#endif /* IPCCOMMUNICATOR_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#include "IPCException.h"
#include <stdarg.h>
#include <string>
struct IPCException::IPCExceptionImpl {
std::string str;
};
IPCException::IPCException(const char* fmt, ...)
: m_impl(new IPCExceptionImpl)
{
va_list ap;
char buffer[256];
va_start(ap, fmt);
vsnprintf(buffer, 256, fmt, ap);
va_end(ap);
m_impl->str.assign(buffer);
}
IPCException::~IPCException()
{
}
IPCException::IPCException(IPCException&& ex)
{
m_impl = std::move(ex.m_impl);
}
const char* IPCException::msg() const
{
return m_impl->str.c_str();
}
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCEXCEPTION_H
#define IPCEXCEPTION_H
#include <memory>
class IPCException {
public:
IPCException(const char* fmt, ...);
~IPCException();
IPCException(IPCException&& ex);
const char* msg() const;
private:
struct IPCExceptionImpl;
std::unique_ptr<IPCExceptionImpl> m_impl;
};
#endif /* IPCEXCEPTION_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#include "IPCFutexPageQueue.h"
#include "IPCCheck.h"
#include "IPCException.h"
#include "IPCLog.h"
#include "IPCType.h"
#include "futex.h"
#include <errno.h>
#include <sched.h>
#include <string.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>
IPCFutexPageQueue::IPCFutexPageQueue(void* sharedMemory, size_t s, size_t id)
: m_currentWrite(id)
, m_currentRead(id ^ 1)
, m_pageSize(s / m_pagesCount)
, m_sharedMemory(sharedMemory)
, m_tid(gettid())
{
IPC_DCHECK(s == ipc_size);
IPC_LOGD("id: %zu", id);
for (int i = m_currentWrite; i < m_pagesCount; i += 2) {
uint32_t* data = static_cast<uint32_t*>(getPage(i));
data[1] |= m_finishTag;
}
lock(m_currentWrite, true);
}
IPCFutexPageQueue::~IPCFutexPageQueue()
{
// build a terminate msg.
uint32_t* data = static_cast<uint32_t*>(getPage(m_currentWrite));
data[1] = sizeof(uint32_t) * 2;
data[2] = MSG_TERMINATE;
data[3] = static_cast<uint32_t>(IPCType::END);
try {
unlock(m_currentWrite);
} catch (IPCException& e) {
IPC_LOGE("%s", e.msg());
}
munmap(m_sharedMemory, m_pageSize << 2);
}
void IPCFutexPageQueue::stepWrite()
{
IPC_LOGD("stepWrite");
clearFinishedTag();
size_t current = m_currentWrite;
m_currentWrite = step(m_currentWrite);
lock(m_currentWrite, true);
unlock(current);
}
void IPCFutexPageQueue::unlock(size_t id)
{
IPC_LOGD("unlock: %zu", id);
volatile uint32_t* pageStart = static_cast<volatile uint32_t*>(getPage(id));
uint32_t l = m_tid;
if (__atomic_compare_exchange_n(pageStart, &l, 0,
false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
return;
}
if ((l & FUTEX_WAITERS) != 0) {
int futexReturn = __futex(pageStart, FUTEX_UNLOCK_PI, 0, nullptr);
if (futexReturn == -1) {
throw IPCException("failed to futex unlock %s", strerror(errno));
}
return;
} else if ((l & FUTEX_TID_MASK) != m_tid) {
throw IPCException("l is not equal to tid: %d %d", l, m_tid);
}
throw IPCException("expected lock value");
}
void IPCFutexPageQueue::lock(size_t id, bool checkFinish)
{
volatile uint32_t* pageStart = static_cast<volatile uint32_t*>(getPage(id));
uint32_t l = m_tid;
uint32_t expected = 0;
IPC_LOGD("lock: %zu", id);
// wait for the finished tag;
if (checkFinish) {
while (true) {
uint32_t finishedTag = pageStart[1];
if (finishedTag == m_finishTag) {
break;
}
struct timespec waitTime = { m_timeoutSec, 0 };
int futexReturn = __futex(pageStart + 1, FUTEX_WAIT, 0, &waitTime);
if (futexReturn == -1) {
int myerrno = errno;
if (myerrno == EINTR)
continue;
else if (myerrno == ETIMEDOUT) {
throw IPCException("IPCFutexPageQueue::lock timeout when waiting for finished");
} else if (myerrno == EAGAIN) {
// become m_finishTag when enter the linux kernel.
break;
} else {
throw IPCException("IPCException::lock waiting for finished tag %u: %s", pageStart[1], strerror(myerrno));
}
}
break;
}
}
if (__atomic_compare_exchange_n(pageStart, &expected, l,
false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
return;
}
errno = 0;
while (true) {
int futexReturn = __futex(pageStart, FUTEX_LOCK_PI, 1, nullptr);
if (futexReturn == -1 && errno != EINTR) {
volatile uint32_t* pageStart0 = static_cast<volatile uint32_t*>(getPage(0));
volatile uint32_t* pageStart1 = static_cast<volatile uint32_t*>(getPage(1));
volatile uint32_t* pageStart2 = static_cast<volatile uint32_t*>(getPage(2));
volatile uint32_t* pageStart3 = static_cast<volatile uint32_t*>(getPage(3));
throw IPCException("futex lock pi failed: %s, %x %d (%x %x %x %x)", strerror(errno), *pageStart, m_tid, *pageStart0, *pageStart1, *pageStart2, *pageStart3);
}
if (futexReturn == -1)
continue;
break;
}
l = *pageStart;
if ((l & FUTEX_OWNER_DIED)) {
unlock(id);
throw IPCException("original owner has die");
}
}
void* IPCFutexPageQueue::getPage(size_t id)
{
size_t offset = id * m_pageSize;
return static_cast<char*>(m_sharedMemory) + offset;
}
void IPCFutexPageQueue::lockReadPage()
{
IPC_LOGD("lockReadPage");
uint32_t* pageStart = static_cast<uint32_t*>(getPage(m_currentRead));
if (!*pageStart) {
// this page should be locked.
}
lock(m_currentRead, false);
}
void IPCFutexPageQueue::unlockReadPageAndStep()
{
IPC_LOGD("unlockReadPageAndStep");
setFinishedTag();
unlock(m_currentRead);
m_currentRead = step(m_currentRead);
}
void IPCFutexPageQueue::spinWaitPeer()
{
volatile uint32_t* pageStart = static_cast<volatile uint32_t*>(getPage(m_currentRead));
struct timespec start;
clock_gettime(CLOCK_MONOTONIC, &start);
while (!*pageStart) {
sched_yield();
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
if ((now.tv_sec - start.tv_sec) > m_timeoutSec)
throw IPCException("spinWaitPeer timeout");
}
}
void IPCFutexPageQueue::setFinishedTag()
{
uint32_t* pageStart = static_cast<uint32_t*>(getPage(m_currentRead));
uint32_t expected = 0;
if (__atomic_compare_exchange_n(pageStart + 1, &expected, m_finishTag,
false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
IPC_LOGD("setFinishedTag:waking writer");
__futex(pageStart + 1, FUTEX_WAKE, 1, nullptr);
return;
} else {
IPC_LOGD("setFinishedTag unexpected value: %u", expected);
}
}
void IPCFutexPageQueue::clearFinishedTag()
{
uint32_t* pageRead = static_cast<uint32_t*>(getPage(m_currentWrite));
pageRead[1] = 0;
__atomic_thread_fence(__ATOMIC_SEQ_CST);
}
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCFUTEXPAGEQUEUE_H
#define IPCFUTEXPAGEQUEUE_H
#include <stdint.h>
// shared memory page layout:
// futex uint32_t
// state word uint32_t
// package size uint32_t
// msg type uint32_t
// types[] uint32_t[]
//
// data whatever types indicate
// A page queue is composed of m_pagesCount pages
// and will use repeatedly.
class IPCFutexPageQueue {
public:
IPCFutexPageQueue(void* sharedMemory, size_t s, size_t id);
~IPCFutexPageQueue();
void stepWrite();
void lockReadPage();
void unlockReadPageAndStep();
void spinWaitPeer();
inline void* getCurrentReadPage() { return sizeof(uint32_t) * 2 + static_cast<char*>(getPage(m_currentRead)); }
inline void* getCurrentWritePage() { return sizeof(uint32_t) * 2 + static_cast<char*>(getPage(m_currentWrite)); }
inline size_t getPageSize() const { return m_pageSize - sizeof(uint32_t) * 2; }
static const size_t ipc_size = 2 * 1024 * 1024;
private:
void unlock(size_t id);
void lock(size_t id, bool checkFinish);
void* getPage(size_t id);
inline size_t step(size_t s) { return (s + 2) & (m_pagesCount - 1); }
void setFinishedTag();
void clearFinishedTag();
size_t m_currentWrite;
size_t m_currentRead;
size_t m_pageSize;
void* m_sharedMemory;
int m_tid;
static const uint32_t m_finishTag = static_cast<uint32_t>(1);
static const size_t m_pagesCount = 16;
static const int m_timeoutSec = 32;
};
#endif /* IPCFUTEXPAGEQUEUE_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#include "IPCHandler.h"
#include "IPCLog.h"
#include "IPCResult.h"
#include <unordered_map>
namespace {
class IPCHandlerImpl : public IPCHandler {
public:
std::unique_ptr<IPCResult> handle(uint32_t msg, IPCArguments*) override;
void registerHandler(int msg, const std::function<std::unique_ptr<IPCResult>(IPCArguments*)>& handler) override;
private:
typedef std::unordered_map<int, std::function<std::unique_ptr<IPCResult>(IPCArguments*)>> MapType;
MapType m_map;
};
std::unique_ptr<IPCResult> IPCHandlerImpl::handle(uint32_t msg, IPCArguments* arguments)
{
auto it = m_map.find(msg);
if (it == m_map.end()) {
IPC_LOGE("unable to find msg: %d", msg);
return createVoidResult();
}
return it->second(arguments);
}
void IPCHandlerImpl::registerHandler(int msg, const std::function<std::unique_ptr<IPCResult>(IPCArguments*)>& handler)
{
m_map.insert(MapType::value_type(msg, handler));
}
}
std::unique_ptr<IPCHandler> createIPCHandler()
{
return std::unique_ptr<IPCHandler>(new IPCHandlerImpl);
}
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCHANDLER_H
#define IPCHANDLER_H
#include <functional>
#include <memory>
#include <stdint.h>
class IPCResult;
class IPCArguments;
class IPCHandler {
public:
virtual ~IPCHandler() = default;
virtual std::unique_ptr<IPCResult> handle(uint32_t msg, IPCArguments*) = 0;
virtual void registerHandler(int msg, const std::function<std::unique_ptr<IPCResult>(IPCArguments*)>& handler) = 0;
};
std::unique_ptr<IPCHandler> createIPCHandler();
#endif /* IPCHANDLER_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#include "IPCListener.h"
#include "Buffering/IPCBuffer.h"
#include "IPCArguments.h"
#include "IPCCommunicator.h"
#include "IPCException.h"
#include "IPCHandler.h"
#include "IPCResult.h"
#include "IPCType.h"
#include <unistd.h>
namespace {
class IPCListenerImpl : public IPCCommunicator,
public IPCListener {
public:
IPCListenerImpl(IPCFutexPageQueue* futexPageQueue, IPCHandler* handler);
~IPCListenerImpl() override;
void listen() override;
private:
int m_fd;
IPCHandler* m_handler;
};
IPCListenerImpl::IPCListenerImpl(IPCFutexPageQueue* futexPageQueue, IPCHandler* handler)
: IPCCommunicator(futexPageQueue)
, m_handler(handler)
{
}
IPCListenerImpl::~IPCListenerImpl()
{
}
void IPCListenerImpl::listen()
{
while (true) {
uint32_t msg = doReadPackage();
bool isAsync = !!(msg & MSG_FLAG_ASYNC);
msg &= MSG_MASK;
if (msg == MSG_END)
throw IPCException("unexpected MSG_END");
else if (msg == MSG_TERMINATE) {
releaseBlob();
throw IPCException("peer terminates");
}
std::unique_ptr<IPCArguments> arguments = assembleArguments();
releaseBlob();
IPCArguments* pArguments = arguments.get();
std::unique_ptr<IPCResult> sendBack = m_handler->handle(msg, pArguments);
if (!isAsync) {
std::unique_ptr<IPCBuffer> resultBuffer = generateResultBuffer(sendBack.get());
doSendBufferOnly(resultBuffer.get());
}
}
}
}
std::unique_ptr<IPCListener> createIPCListener(IPCFutexPageQueue* futexPageQueue, IPCHandler* handler)
{
return std::unique_ptr<IPCListener>(new IPCListenerImpl(futexPageQueue, handler));
}
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCLISTENER_H
#define IPCLISTENER_H
#include <memory>
class IPCHandler;
class IPCFutexPageQueue;
class IPCListener {
public:
virtual ~IPCListener() = default;
virtual void listen() = 0;
};
std::unique_ptr<IPCListener> createIPCListener(IPCFutexPageQueue*, IPCHandler* handler);
#endif /* IPCLISTENER_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCLOG_H
#define IPCLOG_H
#include <android/log.h>
#define TAG "linzj_IPC"
#define IPC_LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#if defined(ENABLE_IPC_DEBUG_LOG) && ENABLE_IPC_DEBUG_LOG
#define IPC_LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#else
#define IPC_LOGD(...)
#endif
#endif /* IPCLOG_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCMESSAGEJS_H
#define IPCMESSAGEJS_H
// Message from Platform to Script in ScriptBridge
enum class IPCJSMsg {
INITFRAMEWORK,
EXECJSSERVICE,
TAKEHEAPSNAPSHOT,
EXECJS,
CREATEINSTANCE,
DESTORYINSTANCE,
EXECJSONINSTANCE,
EXECJSWITHRESULT,
EXECJSWITHCALLBACK,
UPDATEGLOBALCONFIG,
EXECTIMERCALLBACK,
INITAPPFRAMEWORK,
CREATEAPPCONTEXT,
EXECJSONAPPWITHRESULT,
CALLJSONAPPCONTEXT,
DESTORYAPPCONTEXT,
};
// Message from Script to Core in ScriptBridge
enum class IPCProxyMsg {
SETJSFVERSION,
REPORTEXCEPTION,
CALLNATIVE,
CALLNATIVEMODULE,
CALLNATIVECOMPONENT,
CALLADDELEMENT,
SETTIMEOUT,
NATIVELOG,
CALLCREATEBODY,
CALLUPDATEFINISH,
CALLCREATEFINISH,
CALLREFRESHFINISH,
CALLUPDATEATTRS,
CALLUPDATESTYLE,
CALLREMOVEELEMENT,
CALLMOVEELEMENT,
CALLADDEVENT,
CALLREMOVEEVENT,
CALLGCANVASLINK,
CALLT3DLINK,
SETINTERVAL,
CLEARINTERVAL,
POSTMESSAGE,
DISPATCHMESSAGE,
ONRECEIVEDRESULT,
};
// Message from Script to Core in ScriptBridge
// Message from Core to Platform in PlatformBridge
enum class IPCMsgFromCoreToPlatform {
INVOKE_MEASURE_FUNCTION = 100,
INVOKE_LAYOUT_BEFORE,
INVOKE_LAYOUT_AFTER,
SET_JS_VERSION,
REPORT_EXCEPTION,
CALL_NATIVE,
CALL_NATIVE_MODULE,
CALL_NATIVE_COMPONENT,
SET_TIMEOUT,
NATIVE_LOG,
UPDATE_FINISH,
REFRESH_FINISH,
ADD_EVENT,
REMOVE_EVENT,
CREATE_BODY,
ADD_ELEMENT,
LAYOUT,
UPDATE_STYLE,
UPDATE_ATTR,
CREATE_FINISH,
RENDER_SUCCESS,
REMOVE_ELEMENT,
MOVE_ELEMENT,
APPEND_TREE_CREATE_FINISH,
HAS_TRANSITION_PROS,
POST_MESSAGE,
DISPATCH_MESSAGE
};
// Message from Platform to Core in PlatformBridge
enum class IPCMsgFromPlatformToCore {
SET_DEFAULT_HEIGHT_AND_WIDTH_INTO_ROOT_DOM = 100,
ON_INSTANCE_CLOSE,
SET_STYLE_WIDTH,
SET_STYLE_HEIGHT,
SET_MARGIN,
SET_PADDING,
SET_POSITION,
MARK_DIRTY,
SET_VIEWPORT_WIDTH,
FORCE_LAYOUT,
NOTIFY_LAYOUT,
GET_FIRST_SCREEN_RENDER_TIME,
GET_RENDER_FINISH_TIME,
SET_RENDER_CONTAINER_WRAP_CONTENT,
BIND_MEASUREMENT_TO_RENDER_OBJECT,
REGISTER_CORE_ENV,
GET_RENDER_OBJECT,
UPDATE_RENDER_OBJECT_STYLE,
UPDATE_RENDER_OBJECT_ATTR,
COPY_RENDER_OBJECT,
SET_MEASURE_FUNCTION_ADAPTER,
SET_PLATFORM,
SET_DEVICE_WIDTH_AND_HEIGHT,
ADD_OPTION,
INIT_FRAMEWORK,
INIT_APP_FRAMEWORK,
CREATE_APP_CONTEXT,
EXEC_JS_ON_APP_WITH_RESULT,
CALL_JS_ON_APP_CONTEXT,
DESTROY_APP_CONTEXT,
EXEC_JS_SERVICE,
EXEC_TIME_CALLBACK,
EXEC_JS,
EXEC_JS_WITH_RESULT,
CREATE_INSTANCE,
EXEC_JS_ON_INSTANCE,
DESTROY_INSTANCE,
UPDATE_GLOBAL_CONFIG
};
#endif /* IPCMESSAGEJS_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#include "IPCResult.h"
#include <cstdlib>
namespace {
class VoidResult : public IPCResult {
public:
const void* getData() override;
IPCType getType() override;
const uint16_t* getStringContent() override;
size_t getStringLength() override;
const char* getByteArrayContent() override;
size_t getByteArrayLength() override;
};
template <typename T>
struct TypeTrait {
};
template <>
struct TypeTrait<int32_t> {
static const IPCType s_type = IPCType::INT32;
};
template <>
struct TypeTrait<int64_t> {
static const IPCType s_type = IPCType::INT64;
};
template <>
struct TypeTrait<double> {
static const IPCType s_type = IPCType::DOUBLE;
};
template <typename T>
class ValueResult : public IPCResult {
public:
explicit ValueResult(T val);
const void* getData() override;
IPCType getType() override;
const uint16_t* getStringContent() override;
size_t getStringLength() override;
const char* getByteArrayContent() override;
size_t getByteArrayLength() override;
private:
typedef T value_type;
typedef TypeTrait<value_type> trait_type;
value_type m_value;
static const IPCType s_type = trait_type::s_type;
};
class ByteArrayResult: public IPCResult{
public:
ByteArrayResult(const char* data, size_t length);
~ByteArrayResult();
const void* getData() override;
IPCType getType() override;
const uint16_t* getStringContent() override;
size_t getStringLength() override;
const char* getByteArrayContent() override;
size_t getByteArrayLength() override;
private:
char* m_data;
size_t m_length;
};
const void*
VoidResult::getData()
{
return nullptr;
}
IPCType VoidResult::getType()
{
return IPCType::VOID;
}
const uint16_t* VoidResult::getStringContent()
{
return nullptr;
}
size_t VoidResult::getStringLength()
{
return 0U;
}
const char* VoidResult::getByteArrayContent()
{
return nullptr;
}
size_t VoidResult::getByteArrayLength()
{
return 0U;
}
template <typename T>
ValueResult<T>::ValueResult(T val)
: m_value(val)
{
}
template <typename T>
const void* ValueResult<T>::getData()
{
return &m_value;
}
template <typename T>
IPCType ValueResult<T>::getType()
{
return s_type;
}
template <typename T>
const uint16_t* ValueResult<T>::getStringContent()
{
return nullptr;
}
template <typename T>
size_t ValueResult<T>::getStringLength()
{
return 0U;
}
template <typename T>
const char* ValueResult<T>::getByteArrayContent()
{
return nullptr;
}
template <typename T>
size_t ValueResult<T>::getByteArrayLength()
{
return 0U;
}
ByteArrayResult::ByteArrayResult(const char* data, size_t length):m_length(length)
{
if(length > 0){
m_data = (char*)malloc(length*sizeof(char));
memcpy(m_data, data, length);
}else{
m_data = nullptr;
}
}
IPCType ByteArrayResult::getType()
{
return IPCType::BYTEARRAY;
}
const void* ByteArrayResult::getData()
{
return nullptr;
}
const uint16_t* ByteArrayResult::getStringContent(){
return nullptr;
}
size_t ByteArrayResult::getStringLength(){
return 0l;
}
const char* ByteArrayResult::getByteArrayContent(){
return m_data;
}
size_t ByteArrayResult::getByteArrayLength(){
return m_length;
}
ByteArrayResult::~ByteArrayResult()
{
if (m_data){
free(m_data);
m_data= NULL;
}
m_length = 0;
}
}
std::unique_ptr<IPCResult> createVoidResult()
{
return std::unique_ptr<IPCResult>(new VoidResult);
}
std::unique_ptr<IPCResult> createInt32Result(int32_t val)
{
return std::unique_ptr<IPCResult>(new ValueResult<int32_t>(val));
}
std::unique_ptr<IPCResult> createInt64Result(int64_t val)
{
return std::unique_ptr<IPCResult>(new ValueResult<int64_t>(val));
}
std::unique_ptr<IPCResult> createDoubleResult(double val)
{
return std::unique_ptr<IPCResult>(new ValueResult<double>(val));
}
std::unique_ptr<IPCResult> createByteArrayResult(const char* data, size_t length){
return std::unique_ptr<IPCResult>(new ByteArrayResult(data, length));
}
class CharArrayResult : public IPCResult {
public:
CharArrayResult(char* chars);
// ByteArrayResult(const char* data);
~CharArrayResult();
const void* getData() override;
IPCType getType() override;
const uint16_t* getStringContent() override;
size_t getStringLength() override;
const char* getByteArrayContent() override;
size_t getByteArrayLength() override;
private:
char* m_char;
size_t m_length{ 0U };
};
CharArrayResult::CharArrayResult(char* chars)
: m_char(chars) {
m_length = strlen(m_char);
}
CharArrayResult::~CharArrayResult() {
delete[] m_char;
}
const void* CharArrayResult::getData()
{
return m_char;
}
IPCType CharArrayResult::getType()
{
return IPCType::CHARARRAY;
}
const uint16_t* CharArrayResult::getStringContent()
{
return nullptr;
}
size_t CharArrayResult::getStringLength()
{
return m_length;
}
const char* CharArrayResult::getByteArrayContent() {
return nullptr;
}
size_t CharArrayResult::getByteArrayLength() {
return 0U;
}
std::unique_ptr<IPCResult> createCharArrayResult(char* bytes) {
return std::unique_ptr<IPCResult>(new CharArrayResult(bytes));
}
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCRESULT_H
#define IPCRESULT_H
#include "IPCType.h"
#include <memory>
#include "IPCByteArray.h"
struct IPCString;
class IPCResult {
public:
virtual ~IPCResult() = default;
template <typename T>
T get()
{
return *static_cast<const T*>(getData());
}
virtual const void* getData() = 0;
virtual IPCType getType() = 0;
virtual const uint16_t* getStringContent() = 0;
virtual size_t getStringLength() = 0;
virtual const char* getByteArrayContent() = 0;
virtual size_t getByteArrayLength() = 0;
};
std::unique_ptr<IPCResult> createVoidResult();
std::unique_ptr<IPCResult> createInt32Result(int32_t val);
std::unique_ptr<IPCResult> createInt64Result(int64_t val);
std::unique_ptr<IPCResult> createDoubleResult(double val);
std::unique_ptr<IPCResult> createCharArrayResult(char* bytes);
std::unique_ptr<IPCResult> createByteArrayResult(const char* data, size_t length);
#endif /* IPCRESULT_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#include "IPCSender.h"
#include "Buffering/IPCBuffer.h"
#include "IPCArguments.h"
#include "IPCByteArray.h"
#include "IPCCheck.h"
#include "IPCCommunicator.h"
#include "IPCException.h"
#include "IPCHandler.h"
#include "IPCResult.h"
#include "IPCString.h"
#include "Serializing/IPCSerializer.h"
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <vector>
namespace {
class IPCSenderImpl : public IPCCommunicator, public IPCSender {
public:
IPCSenderImpl(IPCFutexPageQueue*, IPCHandler* handler);
~IPCSenderImpl();
std::unique_ptr<IPCResult> send(IPCBuffer*) override;
private:
bool checkBufferAsync(IPCBuffer* buffer);
IPCHandler* m_handler;
};
IPCSenderImpl::IPCSenderImpl(IPCFutexPageQueue* futexPageQueue, IPCHandler* handler)
: IPCCommunicator(futexPageQueue)
, m_handler(handler)
{
}
IPCSenderImpl::~IPCSenderImpl()
{
}
std::unique_ptr<IPCResult> IPCSenderImpl::send(IPCBuffer* buffer)
{
doSendBufferOnly(buffer);
if (checkBufferAsync(buffer))
return createVoidResult();
while (true) {
uint32_t msg = doReadPackage();
bool isAsync = !!(msg & MSG_FLAG_ASYNC);
msg &= MSG_MASK;
if (msg == MSG_END) {
std::unique_ptr<IPCResult> result = assembleResult();
releaseBlob();
return result;
} else if (msg == MSG_TERMINATE) {
releaseBlob();
throw IPCException("peer terminates");
}
std::unique_ptr<IPCArguments> arguments = assembleArguments();
releaseBlob();
std::unique_ptr<IPCResult> sendBack = m_handler->handle(msg, arguments.get());
if (!isAsync) {
std::unique_ptr<IPCBuffer> resultBuffer = generateResultBuffer(sendBack.get());
doSendBufferOnly(resultBuffer.get());
}
}
}
bool IPCSenderImpl::checkBufferAsync(IPCBuffer* buffer)
{
uint32_t msg = *static_cast<const uint32_t*>(buffer->get());
return !!(msg & MSG_FLAG_ASYNC);
}
}
std::unique_ptr<IPCSender> createIPCSender(IPCFutexPageQueue* futexPageQueue, IPCHandler* handler)
{
return std::unique_ptr<IPCSender>(new IPCSenderImpl(futexPageQueue, handler));
}
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCSENDER_H
#define IPCSENDER_H
#include <memory>
class IPCBuffer;
class IPCResult;
class IPCHandler;
class IPCFutexPageQueue;
class IPCSender {
public:
virtual ~IPCSender() = default;
virtual std::unique_ptr<IPCResult> send(IPCBuffer* buffer) = 0;
};
std::unique_ptr<IPCSender> createIPCSender(IPCFutexPageQueue*, IPCHandler* handler);
#endif /* IPCSENDER_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCSTRING_H
#define IPCSTRING_H
struct IPCString {
uint32_t length;
uint16_t content[1];
};
#endif /* IPCSTRING_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCTYPE_H
#define IPCTYPE_H
#include <stdint.h>
struct IPCPackage {
uint32_t packageSize;
uint32_t msg;
uint32_t type[1];
};
enum class IPCType {
INT32,
INT64,
FLOAT,
DOUBLE,
JSONSTRING,
STRING,
BYTEARRAY, /* terminated with zero. */
CHARARRAY,
VOID,
JSUNDEFINED,
END,
};
static const uint32_t MSG_MASK = (1U << 31) - 1;
static const uint32_t MSG_END = static_cast<uint32_t>(-1) & MSG_MASK;
static const uint32_t MSG_TERMINATE = static_cast<uint32_t>(-2) & MSG_MASK;
static const uint32_t MSG_NOT_SET = static_cast<uint32_t>(-3) & MSG_MASK;
static const uint32_t MSG_FLAG_ASYNC = 1U << 31;
#endif /* IPCTYPE_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#include "IPCSerializer.h"
#include "../Buffering/IPCBuffer.h"
#include "../IPCByteArray.h"
#include "../IPCCheck.h"
#include "../IPCString.h"
#include "../IPCType.h"
#include <sstream>
#include <stdlib.h>
#include <string>
#include <vector>
namespace {
class IPCSerializerImpl : public IPCSerializer {
public:
void setMsg(uint32_t msg) override;
void add(int32_t) override;
void add(int64_t) override;
void add(float) override;
void add(double) override;
void add(const uint16_t* data, size_t len) override;
void addJSON(const uint16_t* data, size_t len) override;
void add(const char* data, size_t len) override;
void add(const IPCByteArray* bytes) override;
void addJSUndefined() override;
void addVoid() override;
std::unique_ptr<IPCBuffer> finish() override;
private:
uint32_t m_msg{ MSG_END };
std::vector<uint32_t> m_types;
std::vector<std::unique_ptr<char[]>> m_datas;
};
class StringBasedIPCBufferImpl : public IPCBuffer {
public:
explicit StringBasedIPCBufferImpl(std::string&& s);
const void* get() override;
size_t length() override;
private:
std::string m_str;
};
void IPCSerializerImpl::setMsg(uint32_t msg)
{
m_msg = msg;
}
void IPCSerializerImpl::add(int32_t n)
{
std::unique_ptr<char[]> buffer(new char[sizeof(n)]);
*reinterpret_cast<int32_t*>(buffer.get()) = n;
m_types.emplace_back(static_cast<uint32_t>(IPCType::INT32));
m_datas.emplace_back(std::move(buffer));
}
void IPCSerializerImpl::add(int64_t n)
{
std::unique_ptr<char[]> buffer(new char[sizeof(n)]);
*reinterpret_cast<int64_t*>(buffer.get()) = n;
m_types.emplace_back(static_cast<uint32_t>(IPCType::INT64));
m_datas.emplace_back(std::move(buffer));
}
void IPCSerializerImpl::add(float n)
{
std::unique_ptr<char[]> buffer(new char[sizeof(n)]);
*reinterpret_cast<float*>(buffer.get()) = n;
m_types.emplace_back(static_cast<uint32_t>(IPCType::FLOAT));
m_datas.emplace_back(std::move(buffer));
}
void IPCSerializerImpl::add(double n)
{
std::unique_ptr<char[]> buffer(new char[sizeof(n)]);
*reinterpret_cast<double*>(buffer.get()) = n;
m_types.emplace_back(static_cast<uint32_t>(IPCType::DOUBLE));
m_datas.emplace_back(std::move(buffer));
}
void IPCSerializerImpl::add(const uint16_t* data, size_t len)
{
size_t byteLength = len * sizeof(uint16_t);
std::unique_ptr<char[]> buffer(new char[byteLength + sizeof(IPCString)]);
IPCString* s = reinterpret_cast<IPCString*>(buffer.get());
s->length = len;
memcpy(s->content, data, byteLength);
m_types.emplace_back(static_cast<uint32_t>(IPCType::STRING));
m_datas.emplace_back(std::move(buffer));
}
void IPCSerializerImpl::addJSON(const uint16_t* data, size_t len)
{
size_t byteLength = len * sizeof(uint16_t);
std::unique_ptr<char[]> buffer(new char[byteLength + sizeof(IPCString)]);
IPCString* s = reinterpret_cast<IPCString*>(buffer.get());
s->length = len;
memcpy(s->content, data, byteLength);
m_types.emplace_back(static_cast<uint32_t>(IPCType::JSONSTRING));
m_datas.emplace_back(std::move(buffer));
}
void IPCSerializerImpl::add(const char* data, size_t len)
{
size_t byteLength = len;
std::unique_ptr<char[]> buffer(new char[byteLength + sizeof(IPCByteArray)]);
IPCByteArray* s = reinterpret_cast<IPCByteArray*>(buffer.get());
s->length = len;
memcpy(s->content, data, byteLength);
s->content[byteLength] = '\0';
m_types.emplace_back(static_cast<uint32_t>(IPCType::BYTEARRAY));
m_datas.emplace_back(std::move(buffer));
}
void IPCSerializerImpl::add(const IPCByteArray* bytes) {
m_types.emplace_back(static_cast<uint32_t>(IPCType::BYTEARRAY));
// m_datas.emplace_back(std::move((std::unique_ptr<char[]>)bytes));
}
void IPCSerializerImpl::addJSUndefined()
{
m_types.emplace_back(static_cast<uint32_t>(IPCType::JSUNDEFINED));
m_datas.emplace_back();
}
void IPCSerializerImpl::addVoid()
{
m_types.emplace_back(static_cast<uint32_t>(IPCType::VOID));
m_datas.emplace_back();
}
std::unique_ptr<IPCBuffer> IPCSerializerImpl::finish()
{
IPC_DCHECK(m_types.size() > 0);
IPC_DCHECK(m_msg != MSG_NOT_SET);
std::ostringstream oss;
oss.write(reinterpret_cast<const char*>(&m_msg), sizeof(m_msg));
for (auto& type : m_types) {
oss.write(reinterpret_cast<const char*>(&type), sizeof(type));
}
uint32_t endOfType = static_cast<uint32_t>(IPCType::END);
oss.write(reinterpret_cast<const char*>(&endOfType), sizeof(endOfType));
int i = 0;
for (auto& data : m_datas) {
switch (static_cast<IPCType>(m_types[i])) {
case IPCType::INT32: {
oss.write(data.get(), sizeof(int32_t));
} break;
case IPCType::INT64: {
oss.write(data.get(), sizeof(int64_t));
} break;
case IPCType::FLOAT: {
oss.write(data.get(), sizeof(float));
} break;
case IPCType::DOUBLE: {
oss.write(data.get(), sizeof(double));
} break;
case IPCType::BYTEARRAY: {
IPCByteArray* a = reinterpret_cast<IPCByteArray*>(data.get());
size_t byteLength = a->length;
oss.write(reinterpret_cast<const char*>(&a->length), sizeof(a->length));
oss.write(reinterpret_cast<const char*>(a->content), byteLength);
} break;
case IPCType::JSONSTRING:
case IPCType::STRING: {
IPCString* s = reinterpret_cast<IPCString*>(data.get());
size_t byteLength = s->length * sizeof(uint16_t);
oss.write(reinterpret_cast<const char*>(&s->length), sizeof(s->length));
oss.write(reinterpret_cast<const char*>(s->content), byteLength);
} break;
case IPCType::JSUNDEFINED:
case IPCType::VOID:
break;
default:
IPC_UNREACHABLE();
}
++i;
}
m_types.clear();
m_datas.clear();
m_msg = MSG_NOT_SET;
std::unique_ptr<StringBasedIPCBufferImpl> bufferReturn(new StringBasedIPCBufferImpl(std::move(oss.str())));
return std::unique_ptr<IPCBuffer>(bufferReturn.release());
}
StringBasedIPCBufferImpl::StringBasedIPCBufferImpl(std::string&& s)
: m_str(std::move(s))
{
}
const void* StringBasedIPCBufferImpl::get()
{
return m_str.data();
}
size_t StringBasedIPCBufferImpl::length()
{
return m_str.length();
}
}
std::unique_ptr<IPCSerializer> createIPCSerializer()
{
return std::unique_ptr<IPCSerializer>(new IPCSerializerImpl);
}
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef IPCSERIALIZER_H
#define IPCSERIALIZER_H
#include <memory>
#include <stdint.h>
#include "IPCByteArray.h"
class IPCBuffer;
class IPCSerializer {
public:
virtual ~IPCSerializer() = default;
virtual void setMsg(uint32_t msg) = 0;
virtual void add(int32_t) = 0;
virtual void add(int64_t) = 0;
virtual void add(float) = 0;
virtual void add(double) = 0;
virtual void add(const uint16_t* data, size_t len) = 0;
virtual void addJSON(const uint16_t* data, size_t len) = 0;
virtual void add(const char* data, size_t len) = 0;
virtual void add(const IPCByteArray* bytes) = 0;
virtual void addJSUndefined() = 0;
virtual void addVoid() = 0;
virtual std::unique_ptr<IPCBuffer> finish() = 0;
};
std::unique_ptr<IPCSerializer> createIPCSerializer();
#endif /* IPCSERIALIZER_H */
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "ashmem.h"
#include <linux/ashmem.h>
#define ASHMEM_DEVICE "/dev/ashmem"
/*
* ashmem_create_region - creates a new ashmem region and returns the file
* descriptor, or <0 on error
*
* `name' is an optional label to give the region (visible in /proc/pid/maps)
* `size' is the size of the region, in page-aligned bytes
*/
int ashmem_create_region(const char* name, size_t size)
{
int fd, ret;
fd = open(ASHMEM_DEVICE, O_RDWR);
if (fd < 0)
return fd;
if (name) {
char buf[ASHMEM_NAME_LEN];
strlcpy(buf, name, sizeof(buf));
ret = ioctl(fd, ASHMEM_SET_NAME, buf);
if (ret < 0)
goto error;
}
ret = ioctl(fd, ASHMEM_SET_SIZE, size);
if (ret < 0)
goto error;
return fd;
error:
close(fd);
return ret;
}
int ashmem_set_prot_region(int fd, int prot)
{
return ioctl(fd, ASHMEM_SET_PROT_MASK, prot);
}
int ashmem_pin_region(int fd, size_t offset, size_t len)
{
struct ashmem_pin pin = { offset, len };
return ioctl(fd, ASHMEM_PIN, &pin);
}
int ashmem_unpin_region(int fd, size_t offset, size_t len)
{
struct ashmem_pin pin = { offset, len };
return ioctl(fd, ASHMEM_UNPIN, &pin);
}
int ashmem_get_size_region(int fd)
{
return ioctl(fd, ASHMEM_GET_SIZE, NULL);
}
int ashmem_purge_all(void)
{
const int fd = open(ASHMEM_DEVICE, O_RDWR);
if (fd < 0)
return fd;
const int ret = ioctl(fd, ASHMEM_PURGE_ALL_CACHES, 0);
close(fd);
return ret;
}
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Implementation of the user-space ashmem API for devices, which have our
* ashmem-enabled kernel. See ashmem-sim.c for the "fake" tmp-based version,
* used by the simulator.
*/
#ifndef _THIRD_PARTY_ASHMEM_H
#define _THIRD_PARTY_ASHMEM_H
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
int ashmem_create_region(const char* name, size_t size);
int ashmem_set_prot_region(int fd, int prot);
int ashmem_pin_region(int fd, size_t offset, size_t len);
int ashmem_unpin_region(int fd, size_t offset, size_t len);
int ashmem_get_size_region(int fd);
int ashmem_purge_all(void);
#ifdef __cplusplus
}
#endif
#ifndef __ASHMEMIOC /* in case someone included <linux/ashmem.h> too */
#define ASHMEM_NAME_LEN 256
#define ASHMEM_NAME_DEF "dev/ashmem"
/* Return values from ASHMEM_PIN: Was the mapping purged while unpinned? */
#define ASHMEM_NOT_PURGED 0
#define ASHMEM_WAS_PURGED 1
/* Return values from ASHMEM_UNPIN: Is the mapping now pinned or unpinned? */
#define ASHMEM_IS_UNPINNED 0
#define ASHMEM_IS_PINNED 1
#endif /* ! __ASHMEMIOC */
#endif /* _THIRD_PARTY_ASHMEM_H */
/*
* Copyright (C) 2008 The Android Open Source Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _BIONIC_FUTEX_H
#define _BIONIC_FUTEX_H
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <sys/cdefs.h>
#include <sys/syscall.h>
#include <unistd.h>
#define FUTEX_WAIT 0
#define FUTEX_WAKE 1
#define FUTEX_FD 2
#define FUTEX_REQUEUE 3
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define FUTEX_CMP_REQUEUE 4
#define FUTEX_WAKE_OP 5
#define FUTEX_LOCK_PI 6
#define FUTEX_UNLOCK_PI 7
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define FUTEX_TRYLOCK_PI 8
#define FUTEX_WAIT_BITSET 9
#define FUTEX_WAKE_BITSET 10
#define FUTEX_WAIT_REQUEUE_PI 11
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define FUTEX_CMP_REQUEUE_PI 12
#define FUTEX_PRIVATE_FLAG 128
#define FUTEX_CLOCK_REALTIME 256
#define FUTEX_CMD_MASK ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME)
#define FUTEX_TID_MASK 0x3fffffff
#define FUTEX_OWNER_DIED 0x40000000
#define FUTEX_WAITERS 0x80000000
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define FUTEX_WAIT_PRIVATE (FUTEX_WAIT | FUTEX_PRIVATE_FLAG)
#define FUTEX_WAKE_PRIVATE (FUTEX_WAKE | FUTEX_PRIVATE_FLAG)
#define FUTEX_REQUEUE_PRIVATE (FUTEX_REQUEUE | FUTEX_PRIVATE_FLAG)
#define FUTEX_CMP_REQUEUE_PRIVATE (FUTEX_CMP_REQUEUE | FUTEX_PRIVATE_FLAG)
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define FUTEX_WAKE_OP_PRIVATE (FUTEX_WAKE_OP | FUTEX_PRIVATE_FLAG)
#define FUTEX_LOCK_PI_PRIVATE (FUTEX_LOCK_PI | FUTEX_PRIVATE_FLAG)
#define FUTEX_UNLOCK_PI_PRIVATE (FUTEX_UNLOCK_PI | FUTEX_PRIVATE_FLAG)
#define FUTEX_TRYLOCK_PI_PRIVATE (FUTEX_TRYLOCK_PI | FUTEX_PRIVATE_FLAG)
/* WARNING: DO NOT EDIT, AUTO-GENERATED CODE - SEE TOP FOR INSTRUCTIONS */
#define FUTEX_WAIT_BITSET_PRIVATE (FUTEX_WAIT_BITSET | FUTEX_PRIVATE_FLAG)
#define FUTEX_WAKE_BITSET_PRIVATE (FUTEX_WAKE_BITSET | FUTEX_PRIVATE_FLAG)
#define FUTEX_WAIT_REQUEUE_PI_PRIVATE (FUTEX_WAIT_REQUEUE_PI | FUTEX_PRIVATE_FLAG)
#define FUTEX_CMP_REQUEUE_PI_PRIVATE (FUTEX_CMP_REQUEUE_PI | FUTEX_PRIVATE_FLAG)
#ifndef __predict_false
#define __predict_false(exp) __builtin_expect((exp) != 0, 0)
#endif // __predict_false
struct timespec;
static inline __always_inline int __futex(volatile void* ftx, int op, int value, const struct timespec* timeout)
{
// Our generated syscall assembler sets errno, but our callers (pthread functions) don't want to.
int result = syscall(__NR_futex, ftx, op, value, timeout);
return result;
}
static inline int __futex_wake(volatile void* ftx, int count)
{
return __futex(ftx, FUTEX_WAKE, count, NULL);
}
static inline int __futex_wake_ex(volatile void* ftx, bool shared, int count)
{
return __futex(ftx, shared ? FUTEX_WAKE : FUTEX_WAKE_PRIVATE, count, NULL);
}
static inline int __futex_wait(volatile void* ftx, int value, const struct timespec* timeout)
{
return __futex(ftx, FUTEX_WAIT, value, timeout);
}
static inline int __futex_wait_ex(volatile void* ftx, bool shared, int value, const struct timespec* timeout)
{
return __futex(ftx, shared ? FUTEX_WAIT : FUTEX_WAIT_PRIVATE, value, timeout);
}
#endif /* _BIONIC_FUTEX_H */
/**
* \file
* <PRE>
* High performance base64 encoder / decoder
* Version 1.3 -- 17-Mar-2006
*
* Copyright &copy; 2005, 2006, Nick Galbreath -- nickg [at] modp [dot] com
* All rights reserved.
*
* http://modp.com/release/base64
*
* Released under bsd license. See modp_b64.c for details.
* </pre>
*
* The default implementation is the standard b64 encoding with padding.
* It's easy to change this to use "URL safe" characters and to remove
* padding. See the modp_b64.c source code for details.
*
*/
#include "./base64.h"
#include <string.h>
bool Base64Encode(const std::string &input, std::string *output) {
std::string temp;
temp.resize(modp_b64_encode_len(input.size())); // makes room for null byte
// null terminates result since result is base64 text!
int input_size = static_cast<int>(input.size());
int output_size = modp_b64_encode(&(temp[0]), input.data(), input_size);
if (output_size < 0)
return false;
temp.resize(output_size); // strips off null byte
output->swap(temp);
return true;
}
bool Base64Decode(const std::string &input, std::string *output) {
std::string temp;
temp.resize(modp_b64_decode_len(input.size()));
// does not null terminate result since result is binary data!
int input_size = static_cast<int>(input.size());
int output_size = modp_b64_decode(&(temp[0]), input.data(), input_size);
if (output_size < 0)
return false;
temp.resize(output_size);
output->swap(temp);
return true;
}
\ No newline at end of file
/**
* \file
* <PRE>
* High performance base64 encoder / decoder
* Version 1.3 -- 17-Mar-2006
*
* Copyright &copy; 2005, 2006, Nick Galbreath -- nickg [at] modp [dot] com
* All rights reserved.
*
* http://modp.com/release/base64
*
* Released under bsd license. See modp_b64.c for details.
* </pre>
*
* The default implementation is the standard b64 encoding with padding.
* It's easy to change this to use "URL safe" characters and to remove
* padding. See the modp_b64.c source code for details.
*
*/
#include "./modp_base64/modp_b64.h"
// Encodes the input string in base64. Returns true if successful and false
// otherwise. The output string is only modified if successful.
bool Base64Encode(const std::string &input, std::string *output);
// Decodes the base64 input string. Returns true if successful and false
// otherwise. The output string is only modified if successful.
bool Base64Decode(const std::string &input, std::string *output);
/**
* \file
* <PRE>
* High performance base64 encoder / decoder
* Version 1.3 -- 17-Mar-2006
*
* Copyright &copy; 2005, 2006, Nick Galbreath -- nickg [at] modp [dot] com
* All rights reserved.
*
* http://modp.com/release/base64
*
* Released under bsd license. See modp_b64.c for details.
* </pre>
*
* The default implementation is the standard b64 encoding with padding.
* It's easy to change this to use "URL safe" characters and to remove
* padding. See the modp_b64.c source code for details.
*
*/
/* public header */
#include "modp_b64.h"
/*
* If you are ripping this out of the library, comment out the next
* line and uncomment the next lines as approrpiate
*/
//#include "config.h"
/* if on motoral, sun, ibm; uncomment this */
/* #define WORDS_BIGENDIAN 1 */
/* else for Intel, Amd; uncomment this */
/* #undef WORDS_BIGENDIAN */
#include "modp_b64_data.h"
#define BADCHAR 0x01FFFFFF
/**
* you can control if we use padding by commenting out this
* next line. However, I highly recommend you use padding and not
* using it should only be for compatability with a 3rd party.
* Also, 'no padding' is not tested!
*/
#define DOPAD 1
/*
* if we aren't doing padding
* set the pad character to NULL
*/
#ifndef DOPAD
#undef CHARPAD
#define CHARPAD '\0'
#endif
int modp_b64_encode(char *dest, const char *str, int len) {
int i;
uint8_t *p = (uint8_t *) dest;
/* unsigned here is important! */
uint8_t t1, t2, t3;
for (i = 0; i < len - 2; i += 3) {
t1 = str[i];
t2 = str[i + 1];
t3 = str[i + 2];
*p++ = e0[t1];
*p++ = e1[((t1 & 0x03) << 4) | ((t2 >> 4) & 0x0F)];
*p++ = e1[((t2 & 0x0F) << 2) | ((t3 >> 6) & 0x03)];
*p++ = e2[t3];
}
switch (len - i) {
case 0:
break;
case 1:
t1 = str[i];
*p++ = e0[t1];
*p++ = e1[(t1 & 0x03) << 4];
*p++ = CHARPAD;
*p++ = CHARPAD;
break;
default: /* case 2 */
t1 = str[i];
t2 = str[i + 1];
*p++ = e0[t1];
*p++ = e1[((t1 & 0x03) << 4) | ((t2 >> 4) & 0x0F)];
*p++ = e2[(t2 & 0x0F) << 2];
*p++ = CHARPAD;
}
*p = '\0';
return p - (uint8_t *) dest;
}
#ifdef WORDS_BIGENDIAN /* BIG ENDIAN -- SUN / IBM / MOTOROLA */
int modp_b64_decode(char* dest, const char* src, int len)
{
if (len == 0) return 0;
#ifdef DOPAD
/* if padding is used, then the message must be at least
4 chars and be a multiple of 4.
there can be at most 2 pad chars at the end */
if (len < 4 || (len % 4 != 0)) return -1;
if (src[len-1] == CHARPAD) {
len--;
if (src[len -1] == CHARPAD) {
len--;
}
}
#endif /* DOPAD */
int i;
int leftover = len % 4;
int chunks = (leftover == 0) ? len / 4 - 1 : len /4;
uint8_t* p = (uint8_t*) dest;
uint32_t x = 0;
uint32_t* destInt = (uint32_t*) p;
uint32_t* srcInt = (uint32_t*) src;
uint32_t y = *srcInt++;
for (i = 0; i < chunks; ++i) {
x = d0[y >> 24 & 0xff] | d1[y >> 16 & 0xff] |
d2[y >> 8 & 0xff] | d3[y & 0xff];
if (x >= BADCHAR) return -1;
*destInt = x << 8;
p += 3;
destInt = (uint32_t*)p;
y = *srcInt++;
}
switch (leftover) {
case 0:
x = d0[y >> 24 & 0xff] | d1[y >> 16 & 0xff] |
d2[y >> 8 & 0xff] | d3[y & 0xff];
if (x >= BADCHAR) return -1;
*p++ = ((uint8_t*)&x)[1];
*p++ = ((uint8_t*)&x)[2];
*p = ((uint8_t*)&x)[3];
return (chunks+1)*3;
case 1:
x = d3[y >> 24];
*p = (uint8_t)x;
break;
case 2:
x = d3[y >> 24] *64 + d3[(y >> 16) & 0xff];
*p = (uint8_t)(x >> 4);
break;
default: /* case 3 */
x = (d3[y >> 24] *64 + d3[(y >> 16) & 0xff])*64 +
d3[(y >> 8) & 0xff];
*p++ = (uint8_t) (x >> 10);
*p = (uint8_t) (x >> 2);
break;
}
if (x >= BADCHAR) return -1;
return 3*chunks + (6*leftover)/8;
}
#else /* LITTLE ENDIAN -- INTEL AND FRIENDS */
int modp_b64_decode(char *dest, const char *src, int len) {
if (len == 0) return 0;
#ifdef DOPAD
/*
* if padding is used, then the message must be at least
* 4 chars and be a multiple of 4
*/
if (len < 4 || (len % 4 != 0)) return -1; /* error */
/* there can be at most 2 pad chars at the end */
if (src[len - 1] == CHARPAD) {
len--;
if (src[len - 1] == CHARPAD) {
len--;
}
}
#endif
int i;
int leftover = len % 4;
int chunks = (leftover == 0) ? len / 4 - 1 : len / 4;
uint8_t *p = (uint8_t *) dest;
uint32_t x = 0;
uint32_t *destInt = (uint32_t *) p;
uint32_t *srcInt = (uint32_t *) src;
uint32_t y = *srcInt++;
for (i = 0; i < chunks; ++i) {
x = d0[y & 0xff] |
d1[(y >> 8) & 0xff] |
d2[(y >> 16) & 0xff] |
d3[(y >> 24) & 0xff];
if (x >= BADCHAR) return -1;
*destInt = x;
p += 3;
destInt = (uint32_t *) p;
y = *srcInt++;
}
switch (leftover) {
case 0:
x = d0[y & 0xff] |
d1[(y >> 8) & 0xff] |
d2[(y >> 16) & 0xff] |
d3[(y >> 24) & 0xff];
if (x >= BADCHAR) return -1;
*p++ = ((uint8_t *) (&x))[0];
*p++ = ((uint8_t *) (&x))[1];
*p = ((uint8_t *) (&x))[2];
return (chunks + 1) * 3;
break;
case 1: /* with padding this is an impossible case */
x = d0[y & 0xff];
*p = *((uint8_t *) (&x)); // i.e. first char/byte in int
break;
case 2: // * case 2, 1 output byte */
x = d0[y & 0xff] | d1[y >> 8 & 0xff];
*p = *((uint8_t *) (&x)); // i.e. first char
break;
default: /* case 3, 2 output bytes */
x = d0[y & 0xff] |
d1[y >> 8 & 0xff] |
d2[y >> 16 & 0xff]; /* 0x3c */
*p++ = ((uint8_t *) (&x))[0];
*p = ((uint8_t *) (&x))[1];
break;
}
if (x >= BADCHAR) return -1;
return 3 * chunks + (6 * leftover) / 8;
}
#endif /* if bigendian / else / endif */
/**
* \file
* <PRE>
* High performance base64 encoder / decoder
* Version 1.3 -- 17-Mar-2006
*
* Copyright &copy; 2005, 2006, Nick Galbreath -- nickg [at] modp [dot] com
* All rights reserved.
*
* http://modp.com/release/base64
*
* Released under bsd license. See modp_b64.c for details.
* </pre>
*
* The default implementation is the standard b64 encoding with padding.
* It's easy to change this to use "URL safe" characters and to remove
* padding. See the modp_b64.c source code for details.
*
*/
#ifndef MODP_B64
#define MODP_B64
#ifdef __cplusplus
extern "C" {
#endif
/**
* Encode a raw binary string into base 64.
* src contains the bytes
* len contains the number of bytes in the src
* dest should be allocated by the caller to contain
* at least modp_b64_encode_len(len) bytes (see below)
* This will contain the null-terminated b64 encoded result
* returns length of the destination string plus the ending null byte
* i.e. the result will be equal to strlen(dest) + 1
*
* Example
*
* \code
* char* src = ...;
* int srclen = ...; //the length of number of bytes in src
* char* dest = (char*) malloc(modp_b64_encode_len);
* int len = modp_b64_encode(dest, src, sourcelen);
* if (len == -1) {
* printf("Error\n");
* } else {
* printf("b64 = %s\n", dest);
* }
* \endcode
*
*/
int modp_b64_encode(char *dest, const char *str, int len);
/**
* Decode a base64 encoded string
*
* src should contain exactly len bytes of b64 characters.
* if src contains -any- non-base characters (such as white
* space, -1 is returned.
*
* dest should be allocated by the caller to contain at least
* len * 3 / 4 bytes.
*
* Returns the length (strlen) of the output, or -1 if unable to
* decode
*
* \code
* char* src = ...;
* int srclen = ...; // or if you don't know use strlen(src)
* char* dest = (char*) malloc(modp_b64_decode_len(srclen));
* int len = modp_b64_decode(dest, src, sourcelen);
* if (len == -1) { error }
* \endcode
*/
int modp_b64_decode(char *dest, const char *src, int len);
/**
* Given a source string of length len, this returns the amount of
* memory the destination string should have.
*
* remember, this is integer math
* 3 bytes turn into 4 chars
* ceiling[len / 3] * 4 + 1
*
* +1 is for any extra null.
*/
#define modp_b64_encode_len(A) ((A+2)/3 * 4 + 1)
/**
* Given a base64 string of length len,
* this returns the amount of memory required for output string
* It maybe be more than the actual number of bytes written.
* NOTE: remember this is integer math
* this allocates a bit more memory than traditional versions of b64
* decode 4 chars turn into 3 bytes
* floor[len * 3/4] + 2
*/
#define modp_b64_decode_len(A) (A / 4 * 3 + 2)
/**
* Will return the strlen of the output from encoding.
* This may be less than the required number of bytes allocated.
*
* This allows you to 'deserialized' a struct
* \code
* char* b64encoded = "...";
* int len = strlen(b64encoded);
*
* struct datastuff foo;
* if (modp_b64_encode_strlen(sizeof(struct datastuff)) != len) {
* // wrong size
* return false;
* } else {
* // safe to do;
* if (modp_b64_decode((char*) &foo, b64encoded, len) == -1) {
* // bad characters
* return false;
* }
* }
* // foo is filled out now
* \endcode
*/
#define modp_b64_encode_strlen(A) ((A + 2)/ 3 * 4)
#ifdef __cplusplus
}
#include <string>
inline std::string &modp_b64_encode(std::string &s) {
std::string x(modp_b64_encode_len(s.size()), '\0');
int d = modp_b64_encode(const_cast<char *>(x.data()), s.data(), s.size());
x.erase(d, std::string::npos);
s.swap(x);
return s;
}
/**
* base 64 decode a string (self-modifing)
* On failure, the string is empty.
*
* This function is for C++ only (duh)
*
* \param[in,out] s the string to be decoded
* \return a reference to the input string
*/
inline std::string &modp_b64_decode(std::string &s) {
std::string x(modp_b64_decode_len(s.size()), '\0');
int d = modp_b64_decode(const_cast<char *>(x.data()), s.data(), s.size());
if (d < 0) {
x.clear();
} else {
x.erase(d, std::string::npos);
}
s.swap(x);
return s;
}
#endif /* __cplusplus */
#endif /* MODP_B64 */
/**
* 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.
*/
#include "android_jni.h"
namespace {
JavaVM *g_jvm = nullptr;
}
namespace base {
namespace android {
void InitVM(JavaVM *vm) {
g_jvm = vm;
}
JNIEnv *AttachCurrentThread() {
JNIEnv *env = nullptr;
JavaVMAttachArgs args;
args.version = JNI_VERSION_1_4;
args.name = "weex_sdk_runtime";
args.group = nullptr;
jint ret = g_jvm->AttachCurrentThread(&env, &args);
return env;
}
void DetachFromVM() {
if (g_jvm) {
g_jvm->DetachCurrentThread();
}
}
ScopedLocalJavaRef<jclass> GetClass(JNIEnv *env, const char *class_name) {
jclass clazz;
clazz = env->FindClass(class_name);
return ScopedLocalJavaRef<jclass>(env, clazz);
}
jclass GetClass(JNIEnv *env, const char *class_name, intptr_t *class_id) {
if (*class_id) {
return reinterpret_cast<jclass>(*class_id);
}
ScopedGlobalJavaRef<jclass> clazz;
clazz.Reset(env, GetClass(env, class_name));
*class_id = reinterpret_cast<intptr_t>(clazz.Release());
return reinterpret_cast<jclass>(*class_id);
}
jmethodID GetMethod(JNIEnv *env, jclass clazz, MethodType type,
const char *method_name, const char *jni_signature) {
if (type == STATIC_METHOD) {
return env->GetStaticMethodID(clazz, method_name, jni_signature);
} else if (type == INSTANCE_METHOD) {
return env->GetMethodID(clazz, method_name, jni_signature);
}
return 0;
}
jmethodID GetMethod(JNIEnv *env, jclass clazz, MethodType type,
const char *method_name, const char *jni_signature, intptr_t *method_id) {
if (*method_id) {
return reinterpret_cast<jmethodID>(*method_id);
}
*method_id = reinterpret_cast<intptr_t>(GetMethod(env,
clazz, type, method_name, jni_signature));
return reinterpret_cast<jmethodID>(*method_id);
}
bool HasException(JNIEnv *env) {
return env->ExceptionCheck() != JNI_FALSE;
}
bool ClearException(JNIEnv *env) {
if (!HasException(env))
return false;
env->ExceptionDescribe();
env->ExceptionClear();
return true;
}
void CheckException(JNIEnv *env) {
if (!HasException(env))
return;
// Exception has been found, might as well tell breakpad about it.
jthrowable java_throwable = env->ExceptionOccurred();
if (java_throwable) {
// Clear the pending exception, since a local reference is now held.
env->ExceptionDescribe();
env->ExceptionClear();
}
// Now, feel good about it and die.
// CHECK(false) << "Please include Java exception stack in crash report";
}
} // namespace android
} // namespace base
/**
* 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.
*/
//
// Created by furture on 2018/5/31.
//
#include "jbytearray_ref.h"
namespace WeexCore {
JByteArrayRef::JByteArrayRef(JNIEnv *env, jbyteArray array) {
this->env = env;
this->array = array;
if(array != nullptr){
this->bytes = (char *) env->GetByteArrayElements(array, JNI_FALSE);
}
}
JByteArrayRef::~JByteArrayRef() {
if(array != nullptr){
env->ReleaseByteArrayElements(array, (jbyte*)bytes, 0);
array = nullptr;
}
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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