Merge "Do not register the callbacks in the constructor."
diff --git a/cmds/keystore/Android.mk b/cmds/keystore/Android.mk
index 15a199f..67dd9f8 100644
--- a/cmds/keystore/Android.mk
+++ b/cmds/keystore/Android.mk
@@ -19,14 +19,14 @@
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
-LOCAL_SRC_FILES := keystore.c
+LOCAL_SRC_FILES := keystore.cpp
LOCAL_C_INCLUDES := external/openssl/include
LOCAL_SHARED_LIBRARIES := libcutils libcrypto
LOCAL_MODULE:= keystore
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
-LOCAL_SRC_FILES := keystore_cli.c
+LOCAL_SRC_FILES := keystore_cli.cpp
LOCAL_C_INCLUDES := external/openssl/include
LOCAL_SHARED_LIBRARIES := libcutils libcrypto
LOCAL_MODULE:= keystore_cli
diff --git a/cmds/keystore/keystore.c b/cmds/keystore/keystore.c
deleted file mode 100644
index e34053b..0000000
--- a/cmds/keystore/keystore.c
+++ /dev/null
@@ -1,590 +0,0 @@
-/*
- * Copyright (C) 2009 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.
- */
-
-#include <stdio.h>
-#include <stdint.h>
-#include <string.h>
-#include <unistd.h>
-#include <signal.h>
-#include <errno.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <limits.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <arpa/inet.h>
-
-#include <openssl/aes.h>
-#include <openssl/evp.h>
-#include <openssl/md5.h>
-
-#define LOG_TAG "keystore"
-#include <cutils/log.h>
-#include <cutils/sockets.h>
-#include <private/android_filesystem_config.h>
-
-#include "keystore.h"
-
-/* KeyStore is a secured storage for key-value pairs. In this implementation,
- * each file stores one key-value pair. Keys are encoded in file names, and
- * values are encrypted with checksums. The encryption key is protected by a
- * user-defined password. To keep things simple, buffers are always larger than
- * the maximum space we needed, so boundary checks on buffers are omitted. */
-
-#define KEY_SIZE ((NAME_MAX - 15) / 2)
-#define VALUE_SIZE 32768
-#define PASSWORD_SIZE VALUE_SIZE
-
-/* Here is the encoding of keys. This is necessary in order to allow arbitrary
- * characters in keys. Characters in [0-~] are not encoded. Others are encoded
- * into two bytes. The first byte is one of [+-.] which represents the first
- * two bits of the character. The second byte encodes the rest of the bits into
- * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
- * that Base64 cannot be used here due to the need of prefix match on keys. */
-
-static int encode_key(char *out, uint8_t *in, int length)
-{
- int i;
- for (i = length; i > 0; --i, ++in, ++out) {
- if (*in >= '0' && *in <= '~') {
- *out = *in;
- } else {
- *out = '+' + (*in >> 6);
- *++out = '0' + (*in & 0x3F);
- ++length;
- }
- }
- *out = 0;
- return length;
-}
-
-static int decode_key(uint8_t *out, char *in, int length)
-{
- int i;
- for (i = 0; i < length; ++i, ++in, ++out) {
- if (*in >= '0' && *in <= '~') {
- *out = *in;
- } else {
- *out = (*in - '+') << 6;
- *out |= (*++in - '0') & 0x3F;
- --length;
- }
- }
- *out = 0;
- return length;
-}
-
-/* Here is the protocol used in both requests and responses:
- * code [length_1 message_1 ... length_n message_n] end-of-file
- * where code is one byte long and lengths are unsigned 16-bit integers in
- * network order. Thus the maximum length of a message is 65535 bytes. */
-
-static int the_socket = -1;
-
-static int recv_code(int8_t *code)
-{
- return recv(the_socket, code, 1, 0) == 1;
-}
-
-static int recv_message(uint8_t *message, int length)
-{
- uint8_t bytes[2];
- if (recv(the_socket, &bytes[0], 1, 0) != 1 ||
- recv(the_socket, &bytes[1], 1, 0) != 1) {
- return -1;
- } else {
- int offset = bytes[0] << 8 | bytes[1];
- if (length < offset) {
- return -1;
- }
- length = offset;
- offset = 0;
- while (offset < length) {
- int n = recv(the_socket, &message[offset], length - offset, 0);
- if (n <= 0) {
- return -1;
- }
- offset += n;
- }
- }
- return length;
-}
-
-static int recv_end_of_file()
-{
- uint8_t byte;
- return recv(the_socket, &byte, 1, 0) == 0;
-}
-
-static void send_code(int8_t code)
-{
- send(the_socket, &code, 1, 0);
-}
-
-static void send_message(uint8_t *message, int length)
-{
- uint16_t bytes = htons(length);
- send(the_socket, &bytes, 2, 0);
- send(the_socket, message, length, 0);
-}
-
-/* Here is the file format. There are two parts in blob.value, the secret and
- * the description. The secret is stored in ciphertext, and its original size
- * can be found in blob.length. The description is stored after the secret in
- * plaintext, and its size is specified in blob.info. The total size of the two
- * parts must be no more than VALUE_SIZE bytes. The first three bytes of the
- * file are reserved for future use and are always set to zero. Fields other
- * than blob.info, blob.length, and blob.value are modified by encrypt_blob()
- * and decrypt_blob(). Thus they should not be accessed from outside. */
-
-static int the_entropy = -1;
-
-static struct __attribute__((packed)) {
- uint8_t reserved[3];
- uint8_t info;
- uint8_t vector[AES_BLOCK_SIZE];
- uint8_t encrypted[0];
- uint8_t digest[MD5_DIGEST_LENGTH];
- uint8_t digested[0];
- int32_t length;
- uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
-} blob;
-
-static int8_t encrypt_blob(char *name, AES_KEY *aes_key)
-{
- uint8_t vector[AES_BLOCK_SIZE];
- int length;
- int fd;
-
- if (read(the_entropy, blob.vector, AES_BLOCK_SIZE) != AES_BLOCK_SIZE) {
- return SYSTEM_ERROR;
- }
-
- length = blob.length + (blob.value - blob.encrypted);
- length = (length + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE * AES_BLOCK_SIZE;
-
- if (blob.info != 0) {
- memmove(&blob.encrypted[length], &blob.value[blob.length], blob.info);
- }
-
- blob.length = htonl(blob.length);
- MD5(blob.digested, length - (blob.digested - blob.encrypted), blob.digest);
-
- memcpy(vector, blob.vector, AES_BLOCK_SIZE);
- AES_cbc_encrypt(blob.encrypted, blob.encrypted, length, aes_key, vector,
- AES_ENCRYPT);
-
- memset(blob.reserved, 0, sizeof(blob.reserved));
- length += (blob.encrypted - (uint8_t *)&blob) + blob.info;
-
- fd = open(".tmp", O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
- length -= write(fd, &blob, length);
- close(fd);
- return (length || rename(".tmp", name)) ? SYSTEM_ERROR : NO_ERROR;
-}
-
-static int8_t decrypt_blob(char *name, AES_KEY *aes_key)
-{
- int fd = open(name, O_RDONLY);
- int length;
-
- if (fd == -1) {
- return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
- }
- length = read(fd, &blob, sizeof(blob));
- close(fd);
-
- length -= (blob.encrypted - (uint8_t *)&blob) + blob.info;
- if (length < blob.value - blob.encrypted || length % AES_BLOCK_SIZE != 0) {
- return VALUE_CORRUPTED;
- }
-
- AES_cbc_encrypt(blob.encrypted, blob.encrypted, length, aes_key,
- blob.vector, AES_DECRYPT);
- length -= blob.digested - blob.encrypted;
- if (memcmp(blob.digest, MD5(blob.digested, length, NULL),
- MD5_DIGEST_LENGTH)) {
- return VALUE_CORRUPTED;
- }
-
- length -= blob.value - blob.digested;
- blob.length = ntohl(blob.length);
- if (blob.length < 0 || blob.length > length) {
- return VALUE_CORRUPTED;
- }
- if (blob.info != 0) {
- memmove(&blob.value[blob.length], &blob.value[length], blob.info);
- }
- return NO_ERROR;
-}
-
-/* Here are the actions. Each of them is a function without arguments. All
- * information is defined in global variables, which are set properly before
- * performing an action. The number of parameters required by each action is
- * fixed and defined in a table. If the return value of an action is positive,
- * it will be treated as a response code and transmitted to the client. Note
- * that the lengths of parameters are checked when they are received, so
- * boundary checks on parameters are omitted. */
-
-#define MAX_PARAM 2
-#define MAX_RETRY 4
-
-static uid_t uid = -1;
-static int8_t state = UNINITIALIZED;
-static int8_t retry = MAX_RETRY;
-
-static struct {
- int length;
- uint8_t value[VALUE_SIZE];
-} params[MAX_PARAM];
-
-static AES_KEY encryption_key;
-static AES_KEY decryption_key;
-
-static int8_t test()
-{
- return state;
-}
-
-static int8_t get()
-{
- char name[NAME_MAX];
- int n = sprintf(name, "%u_", uid);
- encode_key(&name[n], params[0].value, params[0].length);
- n = decrypt_blob(name, &decryption_key);
- if (n != NO_ERROR) {
- return n;
- }
- send_code(NO_ERROR);
- send_message(blob.value, blob.length);
- return -NO_ERROR;
-}
-
-static int8_t insert()
-{
- char name[NAME_MAX];
- int n = sprintf(name, "%u_", uid);
- encode_key(&name[n], params[0].value, params[0].length);
- blob.info = 0;
- blob.length = params[1].length;
- memcpy(blob.value, params[1].value, params[1].length);
- return encrypt_blob(name, &encryption_key);
-}
-
-static int8_t delete()
-{
- char name[NAME_MAX];
- int n = sprintf(name, "%u_", uid);
- encode_key(&name[n], params[0].value, params[0].length);
- return (unlink(name) && errno != ENOENT) ? SYSTEM_ERROR : NO_ERROR;
-}
-
-static int8_t exist()
-{
- char name[NAME_MAX];
- int n = sprintf(name, "%u_", uid);
- encode_key(&name[n], params[0].value, params[0].length);
- if (access(name, R_OK) == -1) {
- return (errno != ENOENT) ? SYSTEM_ERROR : KEY_NOT_FOUND;
- }
- return NO_ERROR;
-}
-
-static int8_t saw()
-{
- DIR *dir = opendir(".");
- struct dirent *file;
- char name[NAME_MAX];
- int n;
-
- if (!dir) {
- return SYSTEM_ERROR;
- }
- n = sprintf(name, "%u_", uid);
- n += encode_key(&name[n], params[0].value, params[0].length);
- send_code(NO_ERROR);
- while ((file = readdir(dir)) != NULL) {
- if (!strncmp(name, file->d_name, n)) {
- char *p = &file->d_name[n];
- params[0].length = decode_key(params[0].value, p, strlen(p));
- send_message(params[0].value, params[0].length);
- }
- }
- closedir(dir);
- return -NO_ERROR;
-}
-
-static int8_t reset()
-{
- DIR *dir = opendir(".");
- struct dirent *file;
-
- memset(&encryption_key, 0, sizeof(encryption_key));
- memset(&decryption_key, 0, sizeof(decryption_key));
- state = UNINITIALIZED;
- retry = MAX_RETRY;
-
- if (!dir) {
- return SYSTEM_ERROR;
- }
- while ((file = readdir(dir)) != NULL) {
- unlink(file->d_name);
- }
- closedir(dir);
- return NO_ERROR;
-}
-
-#define MASTER_KEY_FILE ".masterkey"
-#define MASTER_KEY_SIZE 16
-#define SALT_SIZE 16
-
-static void set_key(uint8_t *key, uint8_t *password, int length, uint8_t *salt)
-{
- if (salt) {
- PKCS5_PBKDF2_HMAC_SHA1((char *)password, length, salt, SALT_SIZE,
- 8192, MASTER_KEY_SIZE, key);
- } else {
- PKCS5_PBKDF2_HMAC_SHA1((char *)password, length, (uint8_t *)"keystore",
- sizeof("keystore"), 1024, MASTER_KEY_SIZE, key);
- }
-}
-
-/* Here is the history. To improve the security, the parameters to generate the
- * master key has been changed. To make a seamless transition, we update the
- * file using the same password when the user unlock it for the first time. If
- * any thing goes wrong during the transition, the new file will not overwrite
- * the old one. This avoids permanent damages of the existing data. */
-
-static int8_t password()
-{
- uint8_t key[MASTER_KEY_SIZE];
- AES_KEY aes_key;
- int8_t response = SYSTEM_ERROR;
-
- if (state == UNINITIALIZED) {
- if (read(the_entropy, blob.value, MASTER_KEY_SIZE) != MASTER_KEY_SIZE) {
- return SYSTEM_ERROR;
- }
- } else {
- int fd = open(MASTER_KEY_FILE, O_RDONLY);
- uint8_t *salt = NULL;
- if (fd != -1) {
- int length = read(fd, &blob, sizeof(blob));
- close(fd);
- if (length > SALT_SIZE && blob.info == SALT_SIZE) {
- salt = (uint8_t *)&blob + length - SALT_SIZE;
- }
- }
-
- set_key(key, params[0].value, params[0].length, salt);
- AES_set_decrypt_key(key, MASTER_KEY_SIZE * 8, &aes_key);
- response = decrypt_blob(MASTER_KEY_FILE, &aes_key);
- if (response == SYSTEM_ERROR) {
- return SYSTEM_ERROR;
- }
- if (response != NO_ERROR || blob.length != MASTER_KEY_SIZE) {
- if (retry <= 0) {
- reset();
- return UNINITIALIZED;
- }
- return WRONG_PASSWORD + --retry;
- }
-
- if (!salt && params[1].length == -1) {
- params[1] = params[0];
- }
- }
-
- if (params[1].length == -1) {
- memcpy(key, blob.value, MASTER_KEY_SIZE);
- } else {
- uint8_t *salt = &blob.value[MASTER_KEY_SIZE];
- if (read(the_entropy, salt, SALT_SIZE) != SALT_SIZE) {
- return SYSTEM_ERROR;
- }
-
- set_key(key, params[1].value, params[1].length, salt);
- AES_set_encrypt_key(key, MASTER_KEY_SIZE * 8, &aes_key);
- memcpy(key, blob.value, MASTER_KEY_SIZE);
- blob.info = SALT_SIZE;
- blob.length = MASTER_KEY_SIZE;
- response = encrypt_blob(MASTER_KEY_FILE, &aes_key);
- }
-
- if (response == NO_ERROR) {
- AES_set_encrypt_key(key, MASTER_KEY_SIZE * 8, &encryption_key);
- AES_set_decrypt_key(key, MASTER_KEY_SIZE * 8, &decryption_key);
- state = NO_ERROR;
- retry = MAX_RETRY;
- }
- return response;
-}
-
-static int8_t lock()
-{
- memset(&encryption_key, 0, sizeof(encryption_key));
- memset(&decryption_key, 0, sizeof(decryption_key));
- state = LOCKED;
- return NO_ERROR;
-}
-
-static int8_t unlock()
-{
- params[1].length = -1;
- return password();
-}
-
-/* Here are the permissions, actions, users, and the main function. */
-
-enum perm {
- TEST = 1,
- GET = 2,
- INSERT = 4,
- DELETE = 8,
- EXIST = 16,
- SAW = 32,
- RESET = 64,
- PASSWORD = 128,
- LOCK = 256,
- UNLOCK = 512,
-};
-
-static struct action {
- int8_t (*run)();
- int8_t code;
- int8_t state;
- uint32_t perm;
- int lengths[MAX_PARAM];
-} actions[] = {
- {test, 't', 0, TEST, {0}},
- {get, 'g', NO_ERROR, GET, {KEY_SIZE}},
- {insert, 'i', NO_ERROR, INSERT, {KEY_SIZE, VALUE_SIZE}},
- {delete, 'd', 0, DELETE, {KEY_SIZE}},
- {exist, 'e', 0, EXIST, {KEY_SIZE}},
- {saw, 's', 0, SAW, {KEY_SIZE}},
- {reset, 'r', 0, RESET, {0}},
- {password, 'p', 0, PASSWORD, {PASSWORD_SIZE, PASSWORD_SIZE}},
- {lock, 'l', NO_ERROR, LOCK, {0}},
- {unlock, 'u', LOCKED, UNLOCK, {PASSWORD_SIZE}},
- {NULL, 0 , 0, 0, {0}},
-};
-
-static struct user {
- uid_t uid;
- uid_t euid;
- uint32_t perms;
-} users[] = {
- {AID_SYSTEM, ~0, ~GET},
- {AID_VPN, AID_SYSTEM, GET},
- {AID_WIFI, AID_SYSTEM, GET},
- {AID_ROOT, AID_SYSTEM, GET},
- {AID_KEYCHAIN, AID_SYSTEM, TEST | GET | SAW},
- {~0, ~0, TEST | GET | INSERT | DELETE | EXIST | SAW},
-};
-
-static int8_t process(int8_t code) {
- struct user *user = users;
- struct action *action = actions;
- int i;
-
- while (~user->uid && user->uid != uid) {
- ++user;
- }
- while (action->code && action->code != code) {
- ++action;
- }
- if (!action->code) {
- return UNDEFINED_ACTION;
- }
- if (!(action->perm & user->perms)) {
- return PERMISSION_DENIED;
- }
- if (action->state && action->state != state) {
- return state;
- }
- if (~user->euid) {
- uid = user->euid;
- }
- for (i = 0; i < MAX_PARAM && action->lengths[i]; ++i) {
- params[i].length = recv_message(params[i].value, action->lengths[i]);
- if (params[i].length == -1) {
- return PROTOCOL_ERROR;
- }
- }
- if (!recv_end_of_file()) {
- return PROTOCOL_ERROR;
- }
- return action->run();
-}
-
-#define RANDOM_DEVICE "/dev/urandom"
-
-int main(int argc, char **argv)
-{
- int control_socket = android_get_control_socket("keystore");
- if (argc < 2) {
- LOGE("A directory must be specified!");
- return 1;
- }
- if (chdir(argv[1]) == -1) {
- LOGE("chdir: %s: %s", argv[1], strerror(errno));
- return 1;
- }
- if ((the_entropy = open(RANDOM_DEVICE, O_RDONLY)) == -1) {
- LOGE("open: %s: %s", RANDOM_DEVICE, strerror(errno));
- return 1;
- }
- if (listen(control_socket, 3) == -1) {
- LOGE("listen: %s", strerror(errno));
- return 1;
- }
-
- signal(SIGPIPE, SIG_IGN);
- if (access(MASTER_KEY_FILE, R_OK) == 0) {
- state = LOCKED;
- }
-
- while ((the_socket = accept(control_socket, NULL, 0)) != -1) {
- struct timeval tv = {.tv_sec = 3};
- struct ucred cred;
- socklen_t size = sizeof(cred);
- int8_t request;
-
- setsockopt(the_socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
- setsockopt(the_socket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
-
- if (getsockopt(the_socket, SOL_SOCKET, SO_PEERCRED, &cred, &size)) {
- LOGW("getsockopt: %s", strerror(errno));
- } else if (recv_code(&request)) {
- int8_t old_state = state;
- int8_t response;
- uid = cred.uid;
-
- if ((response = process(request)) > 0) {
- send_code(response);
- response = -response;
- }
-
- LOGI("uid: %d action: %c -> %d state: %d -> %d retry: %d",
- cred.uid, request, -response, old_state, state, retry);
- }
- close(the_socket);
- }
- LOGE("accept: %s", strerror(errno));
- return 1;
-}
diff --git a/cmds/keystore/keystore.cpp b/cmds/keystore/keystore.cpp
new file mode 100644
index 0000000..b48be6e
--- /dev/null
+++ b/cmds/keystore/keystore.cpp
@@ -0,0 +1,810 @@
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#include <stdio.h>
+#include <stdint.h>
+#include <string.h>
+#include <unistd.h>
+#include <signal.h>
+#include <errno.h>
+#include <dirent.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <arpa/inet.h>
+
+#include <openssl/aes.h>
+#include <openssl/evp.h>
+#include <openssl/md5.h>
+
+#define LOG_TAG "keystore"
+#include <cutils/log.h>
+#include <cutils/sockets.h>
+#include <private/android_filesystem_config.h>
+
+#include "keystore.h"
+
+/* KeyStore is a secured storage for key-value pairs. In this implementation,
+ * each file stores one key-value pair. Keys are encoded in file names, and
+ * values are encrypted with checksums. The encryption key is protected by a
+ * user-defined password. To keep things simple, buffers are always larger than
+ * the maximum space we needed, so boundary checks on buffers are omitted. */
+
+#define KEY_SIZE ((NAME_MAX - 15) / 2)
+#define VALUE_SIZE 32768
+#define PASSWORD_SIZE VALUE_SIZE
+
+struct Value {
+ int length;
+ uint8_t value[VALUE_SIZE];
+};
+
+/* Here is the encoding of keys. This is necessary in order to allow arbitrary
+ * characters in keys. Characters in [0-~] are not encoded. Others are encoded
+ * into two bytes. The first byte is one of [+-.] which represents the first
+ * two bits of the character. The second byte encodes the rest of the bits into
+ * [0-o]. Therefore in the worst case the length of a key gets doubled. Note
+ * that Base64 cannot be used here due to the need of prefix match on keys. */
+
+static int encode_key(char* out, uid_t uid, const Value* key) {
+ int n = snprintf(out, NAME_MAX, "%u_", uid);
+ out += n;
+ const uint8_t* in = key->value;
+ int length = key->length;
+ for (int i = length; i > 0; --i, ++in, ++out) {
+ if (*in >= '0' && *in <= '~') {
+ *out = *in;
+ } else {
+ *out = '+' + (*in >> 6);
+ *++out = '0' + (*in & 0x3F);
+ ++length;
+ }
+ }
+ *out = '\0';
+ return n + length;
+}
+
+static int decode_key(uint8_t* out, char* in, int length) {
+ for (int i = 0; i < length; ++i, ++in, ++out) {
+ if (*in >= '0' && *in <= '~') {
+ *out = *in;
+ } else {
+ *out = (*in - '+') << 6;
+ *out |= (*++in - '0') & 0x3F;
+ --length;
+ }
+ }
+ *out = '\0';
+ return length;
+}
+
+static size_t readFully(int fd, uint8_t* data, size_t size) {
+ size_t remaining = size;
+ while (remaining > 0) {
+ ssize_t n = TEMP_FAILURE_RETRY(read(fd, data, size));
+ if (n == -1 || n == 0) {
+ return size-remaining;
+ }
+ data += n;
+ remaining -= n;
+ }
+ return size;
+}
+
+static size_t writeFully(int fd, uint8_t* data, size_t size) {
+ size_t remaining = size;
+ while (remaining > 0) {
+ ssize_t n = TEMP_FAILURE_RETRY(write(fd, data, size));
+ if (n == -1 || n == 0) {
+ return size-remaining;
+ }
+ data += n;
+ remaining -= n;
+ }
+ return size;
+}
+
+class Entropy {
+public:
+ Entropy() : mRandom(-1) {}
+ ~Entropy() {
+ if (mRandom != -1) {
+ close(mRandom);
+ }
+ }
+
+ bool open() {
+ const char* randomDevice = "/dev/urandom";
+ mRandom = ::open(randomDevice, O_RDONLY);
+ if (mRandom == -1) {
+ LOGE("open: %s: %s", randomDevice, strerror(errno));
+ return false;
+ }
+ return true;
+ }
+
+ bool generate_random_data(uint8_t* data, size_t size) {
+ return (readFully(mRandom, data, size) == size);
+ }
+
+private:
+ int mRandom;
+};
+
+/* Here is the file format. There are two parts in blob.value, the secret and
+ * the description. The secret is stored in ciphertext, and its original size
+ * can be found in blob.length. The description is stored after the secret in
+ * plaintext, and its size is specified in blob.info. The total size of the two
+ * parts must be no more than VALUE_SIZE bytes. The first three bytes of the
+ * file are reserved for future use and are always set to zero. Fields other
+ * than blob.info, blob.length, and blob.value are modified by encryptBlob()
+ * and decryptBlob(). Thus they should not be accessed from outside. */
+
+struct __attribute__((packed)) blob {
+ uint8_t reserved[3];
+ uint8_t info;
+ uint8_t vector[AES_BLOCK_SIZE];
+ uint8_t encrypted[0];
+ uint8_t digest[MD5_DIGEST_LENGTH];
+ uint8_t digested[0];
+ int32_t length; // in network byte order when encrypted
+ uint8_t value[VALUE_SIZE + AES_BLOCK_SIZE];
+};
+
+class Blob {
+public:
+ Blob(uint8_t* value, int32_t valueLength, uint8_t* info, uint8_t infoLength) {
+ mBlob.length = valueLength;
+ memcpy(mBlob.value, value, valueLength);
+
+ mBlob.info = infoLength;
+ memcpy(mBlob.value + valueLength, info, infoLength);
+ }
+
+ Blob(blob b) {
+ mBlob = b;
+ }
+
+ Blob() {}
+
+ uint8_t* getValue() {
+ return mBlob.value;
+ }
+
+ int32_t getLength() {
+ return mBlob.length;
+ }
+
+ uint8_t getInfo() {
+ return mBlob.info;
+ }
+
+ ResponseCode encryptBlob(const char* filename, AES_KEY *aes_key, Entropy* entropy) {
+ if (!entropy->generate_random_data(mBlob.vector, AES_BLOCK_SIZE)) {
+ return SYSTEM_ERROR;
+ }
+
+ // data includes the value and the value's length
+ size_t dataLength = mBlob.length + sizeof(mBlob.length);
+ // pad data to the AES_BLOCK_SIZE
+ size_t digestedLength = ((dataLength + AES_BLOCK_SIZE - 1)
+ / AES_BLOCK_SIZE * AES_BLOCK_SIZE);
+ // encrypted data includes the digest value
+ size_t encryptedLength = digestedLength + MD5_DIGEST_LENGTH;
+ // move info after space for padding
+ memmove(&mBlob.encrypted[encryptedLength], &mBlob.value[mBlob.length], mBlob.info);
+ // zero padding area
+ memset(mBlob.value + mBlob.length, 0, digestedLength - dataLength);
+
+ mBlob.length = htonl(mBlob.length);
+ MD5(mBlob.digested, digestedLength, mBlob.digest);
+
+ uint8_t vector[AES_BLOCK_SIZE];
+ memcpy(vector, mBlob.vector, AES_BLOCK_SIZE);
+ AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength,
+ aes_key, vector, AES_ENCRYPT);
+
+ memset(mBlob.reserved, 0, sizeof(mBlob.reserved));
+ size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
+ size_t fileLength = encryptedLength + headerLength + mBlob.info;
+
+ const char* tmpFileName = ".tmp";
+ int out = open(tmpFileName, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
+ if (out == -1) {
+ return SYSTEM_ERROR;
+ }
+ size_t writtenBytes = writeFully(out, (uint8_t*) &mBlob, fileLength);
+ if (close(out) != 0) {
+ return SYSTEM_ERROR;
+ }
+ if (writtenBytes != fileLength) {
+ unlink(tmpFileName);
+ return SYSTEM_ERROR;
+ }
+ return (rename(tmpFileName, filename) == 0) ? NO_ERROR : SYSTEM_ERROR;
+ }
+
+ ResponseCode decryptBlob(const char* filename, AES_KEY *aes_key) {
+ int in = open(filename, O_RDONLY);
+ if (in == -1) {
+ return (errno == ENOENT) ? KEY_NOT_FOUND : SYSTEM_ERROR;
+ }
+ // fileLength may be less than sizeof(mBlob) since the in
+ // memory version has extra padding to tolerate rounding up to
+ // the AES_BLOCK_SIZE
+ size_t fileLength = readFully(in, (uint8_t*) &mBlob, sizeof(mBlob));
+ if (close(in) != 0) {
+ return SYSTEM_ERROR;
+ }
+ size_t headerLength = (mBlob.encrypted - (uint8_t*) &mBlob);
+ if (fileLength < headerLength) {
+ return VALUE_CORRUPTED;
+ }
+
+ ssize_t encryptedLength = fileLength - (headerLength + mBlob.info);
+ if (encryptedLength < 0 || encryptedLength % AES_BLOCK_SIZE != 0) {
+ return VALUE_CORRUPTED;
+ }
+ AES_cbc_encrypt(mBlob.encrypted, mBlob.encrypted, encryptedLength, aes_key,
+ mBlob.vector, AES_DECRYPT);
+ size_t digestedLength = encryptedLength - MD5_DIGEST_LENGTH;
+ uint8_t computedDigest[MD5_DIGEST_LENGTH];
+ MD5(mBlob.digested, digestedLength, computedDigest);
+ if (memcmp(mBlob.digest, computedDigest, MD5_DIGEST_LENGTH) != 0) {
+ return VALUE_CORRUPTED;
+ }
+
+ ssize_t maxValueLength = digestedLength - sizeof(mBlob.length);
+ mBlob.length = ntohl(mBlob.length);
+ if (mBlob.length < 0 || mBlob.length > maxValueLength) {
+ return VALUE_CORRUPTED;
+ }
+ if (mBlob.info != 0) {
+ // move info from after padding to after data
+ memmove(&mBlob.value[mBlob.length], &mBlob.value[maxValueLength], mBlob.info);
+ }
+ return NO_ERROR;
+ }
+
+private:
+ struct blob mBlob;
+};
+
+class KeyStore {
+public:
+ KeyStore(Entropy* entropy) : mEntropy(entropy), mRetry(MAX_RETRY) {
+ if (access(MASTER_KEY_FILE, R_OK) == 0) {
+ setState(STATE_LOCKED);
+ } else {
+ setState(STATE_UNINITIALIZED);
+ }
+ }
+
+ State getState() {
+ return mState;
+ }
+
+ int8_t getRetry() {
+ return mRetry;
+ }
+
+ ResponseCode initialize(Value* pw) {
+ if (!generateMasterKey()) {
+ return SYSTEM_ERROR;
+ }
+ ResponseCode response = writeMasterKey(pw);
+ if (response != NO_ERROR) {
+ return response;
+ }
+ setupMasterKeys();
+ return NO_ERROR;
+ }
+
+ ResponseCode writeMasterKey(Value* pw) {
+ uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
+ generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, mSalt);
+ AES_KEY passwordAesKey;
+ AES_set_encrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
+ Blob masterKeyBlob(mMasterKey, sizeof(mMasterKey), mSalt, sizeof(mSalt));
+ return masterKeyBlob.encryptBlob(MASTER_KEY_FILE, &passwordAesKey, mEntropy);
+ }
+
+ ResponseCode readMasterKey(Value* pw) {
+ int in = open(MASTER_KEY_FILE, O_RDONLY);
+ if (in == -1) {
+ return SYSTEM_ERROR;
+ }
+
+ // we read the raw blob to just to get the salt to generate
+ // the AES key, then we create the Blob to use with decryptBlob
+ blob rawBlob;
+ size_t length = readFully(in, (uint8_t*) &rawBlob, sizeof(rawBlob));
+ if (close(in) != 0) {
+ return SYSTEM_ERROR;
+ }
+ // find salt at EOF if present, otherwise we have an old file
+ uint8_t* salt;
+ if (length > SALT_SIZE && rawBlob.info == SALT_SIZE) {
+ salt = (uint8_t*) &rawBlob + length - SALT_SIZE;
+ } else {
+ salt = NULL;
+ }
+ uint8_t passwordKey[MASTER_KEY_SIZE_BYTES];
+ generateKeyFromPassword(passwordKey, MASTER_KEY_SIZE_BYTES, pw, salt);
+ AES_KEY passwordAesKey;
+ AES_set_decrypt_key(passwordKey, MASTER_KEY_SIZE_BITS, &passwordAesKey);
+ Blob masterKeyBlob(rawBlob);
+ ResponseCode response = masterKeyBlob.decryptBlob(MASTER_KEY_FILE, &passwordAesKey);
+ if (response == SYSTEM_ERROR) {
+ return SYSTEM_ERROR;
+ }
+ if (response == NO_ERROR && masterKeyBlob.getLength() == MASTER_KEY_SIZE_BYTES) {
+ // if salt was missing, generate one and write a new master key file with the salt.
+ if (salt == NULL) {
+ if (!generateSalt()) {
+ return SYSTEM_ERROR;
+ }
+ response = writeMasterKey(pw);
+ }
+ if (response == NO_ERROR) {
+ setupMasterKeys();
+ }
+ return response;
+ }
+ if (mRetry <= 0) {
+ reset();
+ return UNINITIALIZED;
+ }
+ --mRetry;
+ switch (mRetry) {
+ case 0: return WRONG_PASSWORD_0;
+ case 1: return WRONG_PASSWORD_1;
+ case 2: return WRONG_PASSWORD_2;
+ case 3: return WRONG_PASSWORD_3;
+ default: return WRONG_PASSWORD_3;
+ }
+ }
+
+ bool reset() {
+ clearMasterKeys();
+ setState(STATE_UNINITIALIZED);
+
+ DIR* dir = opendir(".");
+ struct dirent* file;
+
+ if (!dir) {
+ return false;
+ }
+ while ((file = readdir(dir)) != NULL) {
+ unlink(file->d_name);
+ }
+ closedir(dir);
+ return true;
+ }
+
+ bool isEmpty() {
+ DIR* dir = opendir(".");
+ struct dirent* file;
+ if (!dir) {
+ return true;
+ }
+ bool result = true;
+ while ((file = readdir(dir)) != NULL) {
+ if (isKeyFile(file->d_name)) {
+ result = false;
+ break;
+ }
+ }
+ closedir(dir);
+ return result;
+ }
+
+ void lock() {
+ clearMasterKeys();
+ setState(STATE_LOCKED);
+ }
+
+ ResponseCode get(const char* filename, Blob* keyBlob) {
+ return keyBlob->decryptBlob(filename, &mMasterKeyDecryption);
+ }
+
+ ResponseCode put(const char* filename, Blob* keyBlob) {
+ return keyBlob->encryptBlob(filename, &mMasterKeyEncryption, mEntropy);
+ }
+
+private:
+ static const char* MASTER_KEY_FILE;
+ static const int MASTER_KEY_SIZE_BYTES = 16;
+ static const int MASTER_KEY_SIZE_BITS = MASTER_KEY_SIZE_BYTES * 8;
+
+ static const int MAX_RETRY = 4;
+ static const size_t SALT_SIZE = 16;
+
+ Entropy* mEntropy;
+
+ State mState;
+ int8_t mRetry;
+
+ uint8_t mMasterKey[MASTER_KEY_SIZE_BYTES];
+ uint8_t mSalt[SALT_SIZE];
+
+ AES_KEY mMasterKeyEncryption;
+ AES_KEY mMasterKeyDecryption;
+
+ void setState(State state) {
+ mState = state;
+ if (mState == STATE_NO_ERROR || mState == STATE_UNINITIALIZED) {
+ mRetry = MAX_RETRY;
+ }
+ }
+
+ bool generateSalt() {
+ return mEntropy->generate_random_data(mSalt, sizeof(mSalt));
+ }
+
+ bool generateMasterKey() {
+ if (!mEntropy->generate_random_data(mMasterKey, sizeof(mMasterKey))) {
+ return false;
+ }
+ if (!generateSalt()) {
+ return false;
+ }
+ return true;
+ }
+
+ void setupMasterKeys() {
+ AES_set_encrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyEncryption);
+ AES_set_decrypt_key(mMasterKey, MASTER_KEY_SIZE_BITS, &mMasterKeyDecryption);
+ setState(STATE_NO_ERROR);
+ }
+
+ void clearMasterKeys() {
+ memset(mMasterKey, 0, sizeof(mMasterKey));
+ memset(mSalt, 0, sizeof(mSalt));
+ memset(&mMasterKeyEncryption, 0, sizeof(mMasterKeyEncryption));
+ memset(&mMasterKeyDecryption, 0, sizeof(mMasterKeyDecryption));
+ }
+
+ static void generateKeyFromPassword(uint8_t* key, ssize_t keySize, Value* pw, uint8_t* salt) {
+ size_t saltSize;
+ if (salt != NULL) {
+ saltSize = SALT_SIZE;
+ } else {
+ // pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
+ salt = (uint8_t*) "keystore";
+ // sizeof = 9, not strlen = 8
+ saltSize = sizeof("keystore");
+ }
+ PKCS5_PBKDF2_HMAC_SHA1((char*) pw->value, pw->length, salt, saltSize, 8192, keySize, key);
+ }
+
+ static bool isKeyFile(const char* filename) {
+ return ((strcmp(filename, MASTER_KEY_FILE) != 0)
+ && (strcmp(filename, ".") != 0)
+ && (strcmp(filename, "..") != 0));
+ }
+};
+
+const char* KeyStore::MASTER_KEY_FILE = ".masterkey";
+
+/* Here is the protocol used in both requests and responses:
+ * code [length_1 message_1 ... length_n message_n] end-of-file
+ * where code is one byte long and lengths are unsigned 16-bit integers in
+ * network order. Thus the maximum length of a message is 65535 bytes. */
+
+static int recv_code(int sock, int8_t* code) {
+ return recv(sock, code, 1, 0) == 1;
+}
+
+static int recv_message(int sock, uint8_t* message, int length) {
+ uint8_t bytes[2];
+ if (recv(sock, &bytes[0], 1, 0) != 1 ||
+ recv(sock, &bytes[1], 1, 0) != 1) {
+ return -1;
+ } else {
+ int offset = bytes[0] << 8 | bytes[1];
+ if (length < offset) {
+ return -1;
+ }
+ length = offset;
+ offset = 0;
+ while (offset < length) {
+ int n = recv(sock, &message[offset], length - offset, 0);
+ if (n <= 0) {
+ return -1;
+ }
+ offset += n;
+ }
+ }
+ return length;
+}
+
+static int recv_end_of_file(int sock) {
+ uint8_t byte;
+ return recv(sock, &byte, 1, 0) == 0;
+}
+
+static void send_code(int sock, int8_t code) {
+ send(sock, &code, 1, 0);
+}
+
+static void send_message(int sock, uint8_t* message, int length) {
+ uint16_t bytes = htons(length);
+ send(sock, &bytes, 2, 0);
+ send(sock, message, length, 0);
+}
+
+/* Here are the actions. Each of them is a function without arguments. All
+ * information is defined in global variables, which are set properly before
+ * performing an action. The number of parameters required by each action is
+ * fixed and defined in a table. If the return value of an action is positive,
+ * it will be treated as a response code and transmitted to the client. Note
+ * that the lengths of parameters are checked when they are received, so
+ * boundary checks on parameters are omitted. */
+
+static const ResponseCode NO_ERROR_RESPONSE_CODE_SENT = (ResponseCode) 0;
+
+static ResponseCode test(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*) {
+ return (ResponseCode) keyStore->getState();
+}
+
+static ResponseCode get(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value*) {
+ char filename[NAME_MAX];
+ encode_key(filename, uid, keyName);
+ Blob keyBlob;
+ ResponseCode responseCode = keyStore->get(filename, &keyBlob);
+ if (responseCode != NO_ERROR) {
+ return responseCode;
+ }
+ send_code(sock, NO_ERROR);
+ send_message(sock, keyBlob.getValue(), keyBlob.getLength());
+ return NO_ERROR_RESPONSE_CODE_SENT;
+}
+
+static ResponseCode insert(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value* val) {
+ char filename[NAME_MAX];
+ encode_key(filename, uid, keyName);
+ Blob keyBlob(val->value, val->length, 0, NULL);
+ return keyStore->put(filename, &keyBlob);
+}
+
+static ResponseCode del(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value*) {
+ char filename[NAME_MAX];
+ encode_key(filename, uid, keyName);
+ return (unlink(filename) && errno != ENOENT) ? SYSTEM_ERROR : NO_ERROR;
+}
+
+static ResponseCode exist(KeyStore* keyStore, int sock, uid_t uid, Value* keyName, Value*) {
+ char filename[NAME_MAX];
+ encode_key(filename, uid, keyName);
+ if (access(filename, R_OK) == -1) {
+ return (errno != ENOENT) ? SYSTEM_ERROR : KEY_NOT_FOUND;
+ }
+ return NO_ERROR;
+}
+
+static ResponseCode saw(KeyStore* keyStore, int sock, uid_t uid, Value* keyPrefix, Value*) {
+ DIR* dir = opendir(".");
+ if (!dir) {
+ return SYSTEM_ERROR;
+ }
+ char filename[NAME_MAX];
+ int n = encode_key(filename, uid, keyPrefix);
+ send_code(sock, NO_ERROR);
+
+ struct dirent* file;
+ while ((file = readdir(dir)) != NULL) {
+ if (!strncmp(filename, file->d_name, n)) {
+ char* p = &file->d_name[n];
+ keyPrefix->length = decode_key(keyPrefix->value, p, strlen(p));
+ send_message(sock, keyPrefix->value, keyPrefix->length);
+ }
+ }
+ closedir(dir);
+ return NO_ERROR_RESPONSE_CODE_SENT;
+}
+
+static ResponseCode reset(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*) {
+ return keyStore->reset() ? NO_ERROR : SYSTEM_ERROR;
+}
+
+/* Here is the history. To improve the security, the parameters to generate the
+ * master key has been changed. To make a seamless transition, we update the
+ * file using the same password when the user unlock it for the first time. If
+ * any thing goes wrong during the transition, the new file will not overwrite
+ * the old one. This avoids permanent damages of the existing data. */
+
+static ResponseCode password(KeyStore* keyStore, int sock, uid_t uid, Value* pw, Value*) {
+ switch (keyStore->getState()) {
+ case STATE_UNINITIALIZED: {
+ // generate master key, encrypt with password, write to file, initialize mMasterKey*.
+ return keyStore->initialize(pw);
+ }
+ case STATE_NO_ERROR: {
+ // rewrite master key with new password.
+ return keyStore->writeMasterKey(pw);
+ }
+ case STATE_LOCKED: {
+ // read master key, decrypt with password, initialize mMasterKey*.
+ return keyStore->readMasterKey(pw);
+ }
+ }
+ return SYSTEM_ERROR;
+}
+
+static ResponseCode lock(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*) {
+ keyStore->lock();
+ return NO_ERROR;
+}
+
+static ResponseCode unlock(KeyStore* keyStore, int sock, uid_t uid, Value* pw, Value* unused) {
+ return password(keyStore, sock, uid, pw, unused);
+}
+
+static ResponseCode zero(KeyStore* keyStore, int sock, uid_t uid, Value*, Value*) {
+ return keyStore->isEmpty() ? KEY_NOT_FOUND : NO_ERROR;
+}
+
+/* Here are the permissions, actions, users, and the main function. */
+
+enum perm {
+ TEST = 1,
+ GET = 2,
+ INSERT = 4,
+ DELETE = 8,
+ EXIST = 16,
+ SAW = 32,
+ RESET = 64,
+ PASSWORD = 128,
+ LOCK = 256,
+ UNLOCK = 512,
+ ZERO = 1024,
+};
+
+static const int MAX_PARAM = 2;
+
+static const State STATE_ANY = (State) 0;
+
+static struct action {
+ ResponseCode (*run)(KeyStore* keyStore, int sock, uid_t uid, Value* param1, Value* param2);
+ int8_t code;
+ State state;
+ uint32_t perm;
+ int lengths[MAX_PARAM];
+} actions[] = {
+ {test, 't', STATE_ANY, TEST, {0, 0}},
+ {get, 'g', STATE_NO_ERROR, GET, {KEY_SIZE, 0}},
+ {insert, 'i', STATE_NO_ERROR, INSERT, {KEY_SIZE, VALUE_SIZE}},
+ {del, 'd', STATE_ANY, DELETE, {KEY_SIZE, 0}},
+ {exist, 'e', STATE_ANY, EXIST, {KEY_SIZE, 0}},
+ {saw, 's', STATE_ANY, SAW, {KEY_SIZE, 0}},
+ {reset, 'r', STATE_ANY, RESET, {0, 0}},
+ {password, 'p', STATE_ANY, PASSWORD, {PASSWORD_SIZE, 0}},
+ {lock, 'l', STATE_NO_ERROR, LOCK, {0, 0}},
+ {unlock, 'u', STATE_LOCKED, UNLOCK, {PASSWORD_SIZE, 0}},
+ {zero, 'z', STATE_ANY, ZERO, {0, 0}},
+ {NULL, 0 , STATE_ANY, 0, {0, 0}},
+};
+
+static struct user {
+ uid_t uid;
+ uid_t euid;
+ uint32_t perms;
+} users[] = {
+ {AID_SYSTEM, ~0, ~GET},
+ {AID_VPN, AID_SYSTEM, GET},
+ {AID_WIFI, AID_SYSTEM, GET},
+ {AID_ROOT, AID_SYSTEM, GET},
+ {AID_KEYCHAIN, AID_SYSTEM, TEST | GET | SAW},
+ {~0, ~0, TEST | GET | INSERT | DELETE | EXIST | SAW},
+};
+
+static ResponseCode process(KeyStore* keyStore, int sock, uid_t uid, int8_t code) {
+ struct user* user = users;
+ struct action* action = actions;
+ int i;
+
+ while (~user->uid && user->uid != uid) {
+ ++user;
+ }
+ while (action->code && action->code != code) {
+ ++action;
+ }
+ if (!action->code) {
+ return UNDEFINED_ACTION;
+ }
+ if (!(action->perm & user->perms)) {
+ return PERMISSION_DENIED;
+ }
+ if (action->state != STATE_ANY && action->state != keyStore->getState()) {
+ return (ResponseCode) keyStore->getState();
+ }
+ if (~user->euid) {
+ uid = user->euid;
+ }
+ Value params[MAX_PARAM];
+ for (i = 0; i < MAX_PARAM && action->lengths[i] != 0; ++i) {
+ params[i].length = recv_message(sock, params[i].value, action->lengths[i]);
+ if (params[i].length < 0) {
+ return PROTOCOL_ERROR;
+ }
+ }
+ if (!recv_end_of_file(sock)) {
+ return PROTOCOL_ERROR;
+ }
+ return action->run(keyStore, sock, uid, ¶ms[0], ¶ms[1]);
+}
+
+int main(int argc, char* argv[]) {
+ int controlSocket = android_get_control_socket("keystore");
+ if (argc < 2) {
+ LOGE("A directory must be specified!");
+ return 1;
+ }
+ if (chdir(argv[1]) == -1) {
+ LOGE("chdir: %s: %s", argv[1], strerror(errno));
+ return 1;
+ }
+
+ Entropy entropy;
+ if (!entropy.open()) {
+ return 1;
+ }
+ if (listen(controlSocket, 3) == -1) {
+ LOGE("listen: %s", strerror(errno));
+ return 1;
+ }
+
+ signal(SIGPIPE, SIG_IGN);
+
+ KeyStore keyStore(&entropy);
+ int sock;
+ while ((sock = accept(controlSocket, NULL, 0)) != -1) {
+ struct timeval tv;
+ tv.tv_sec = 3;
+ setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+ setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
+
+ struct ucred cred;
+ socklen_t size = sizeof(cred);
+ int credResult = getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &cred, &size);
+ if (credResult != 0) {
+ LOGW("getsockopt: %s", strerror(errno));
+ } else {
+ int8_t request;
+ if (recv_code(sock, &request)) {
+ State old_state = keyStore.getState();
+ ResponseCode response = process(&keyStore, sock, cred.uid, request);
+ if (response == NO_ERROR_RESPONSE_CODE_SENT) {
+ response = NO_ERROR;
+ } else {
+ send_code(sock, response);
+ }
+ LOGI("uid: %d action: %c -> %d state: %d -> %d retry: %d",
+ cred.uid,
+ request, response,
+ old_state, keyStore.getState(),
+ keyStore.getRetry());
+ }
+ }
+ close(sock);
+ }
+ LOGE("accept: %s", strerror(errno));
+ return 1;
+}
diff --git a/cmds/keystore/keystore.h b/cmds/keystore/keystore.h
index 5ef51e9..5ae3d24 100644
--- a/cmds/keystore/keystore.h
+++ b/cmds/keystore/keystore.h
@@ -17,17 +17,27 @@
#ifndef __KEYSTORE_H__
#define __KEYSTORE_H__
-enum response_code {
- NO_ERROR = 1,
- LOCKED = 2,
- UNINITIALIZED = 3,
+// note state values overlap with ResponseCode for the purposes of the state() API
+enum State {
+ STATE_NO_ERROR = 1,
+ STATE_LOCKED = 2,
+ STATE_UNINITIALIZED = 3,
+};
+
+enum ResponseCode {
+ NO_ERROR = STATE_NO_ERROR, // 1
+ LOCKED = STATE_LOCKED, // 2
+ UNINITIALIZED = STATE_UNINITIALIZED, // 3
SYSTEM_ERROR = 4,
PROTOCOL_ERROR = 5,
PERMISSION_DENIED = 6,
KEY_NOT_FOUND = 7,
VALUE_CORRUPTED = 8,
UNDEFINED_ACTION = 9,
- WRONG_PASSWORD = 10,
+ WRONG_PASSWORD_0 = 10,
+ WRONG_PASSWORD_1 = 11,
+ WRONG_PASSWORD_2 = 12,
+ WRONG_PASSWORD_3 = 13, // MAX_RETRY = 4
};
#endif
diff --git a/cmds/keystore/keystore_cli.c b/cmds/keystore/keystore_cli.cpp
similarity index 67%
rename from cmds/keystore/keystore_cli.c
rename to cmds/keystore/keystore_cli.cpp
index e8afb5a..dcd3bcb 100644
--- a/cmds/keystore/keystore_cli.c
+++ b/cmds/keystore/keystore_cli.cpp
@@ -24,44 +24,40 @@
#include "keystore.h"
-char *responses[256] = {
- [NO_ERROR] = "No error",
- [LOCKED] = "Locked",
- [UNINITIALIZED] = "Uninitialized",
- [SYSTEM_ERROR] = "System error",
- [PROTOCOL_ERROR] = "Protocol error",
- [PERMISSION_DENIED] = "Permission denied",
- [KEY_NOT_FOUND] = "Key not found",
- [VALUE_CORRUPTED] = "Value corrupted",
- [UNDEFINED_ACTION] = "Undefined action",
- [WRONG_PASSWORD] = "Wrong password (last chance)",
- [WRONG_PASSWORD + 1] = "Wrong password (2 tries left)",
- [WRONG_PASSWORD + 2] = "Wrong password (3 tries left)",
- [WRONG_PASSWORD + 3] = "Wrong password (4 tries left)",
+static const char* responses[] = {
+ NULL,
+ /* [NO_ERROR] = */ "No error",
+ /* [LOCKED] = */ "Locked",
+ /* [UNINITIALIZED] = */ "Uninitialized",
+ /* [SYSTEM_ERROR] = */ "System error",
+ /* [PROTOCOL_ERROR] = */ "Protocol error",
+ /* [PERMISSION_DENIED] = */ "Permission denied",
+ /* [KEY_NOT_FOUND] = */ "Key not found",
+ /* [VALUE_CORRUPTED] = */ "Value corrupted",
+ /* [UNDEFINED_ACTION] = */ "Undefined action",
+ /* [WRONG_PASSWORD] = */ "Wrong password (last chance)",
+ /* [WRONG_PASSWORD + 1] = */ "Wrong password (2 tries left)",
+ /* [WRONG_PASSWORD + 2] = */ "Wrong password (3 tries left)",
+ /* [WRONG_PASSWORD + 3] = */ "Wrong password (4 tries left)",
};
-#define MAX_RESPONSE (WRONG_PASSWORD + 3)
-
-int main(int argc, char **argv)
+int main(int argc, char* argv[])
{
- uint8_t bytes[65536];
- uint8_t code;
- int sock, i;
-
if (argc < 2) {
printf("Usage: %s action [parameter ...]\n", argv[0]);
return 0;
}
- sock = socket_local_client("keystore", ANDROID_SOCKET_NAMESPACE_RESERVED,
- SOCK_STREAM);
+ int sock = socket_local_client("keystore", ANDROID_SOCKET_NAMESPACE_RESERVED,
+ SOCK_STREAM);
if (sock == -1) {
puts("Failed to connect");
return 1;
}
send(sock, argv[1], 1, 0);
- for (i = 2; i < argc; ++i) {
+ uint8_t bytes[65536];
+ for (int i = 2; i < argc; ++i) {
uint16_t length = strlen(argv[i]);
bytes[0] = length >> 8;
bytes[1] = length;
@@ -70,11 +66,13 @@
}
shutdown(sock, SHUT_WR);
+ uint8_t code;
if (recv(sock, &code, 1, 0) != 1) {
puts("Failed to receive");
return 1;
}
printf("%d %s\n", code , responses[code] ? responses[code] : "Unknown");
+ int i;
while ((i = recv(sock, &bytes[0], 1, 0)) == 1) {
int length;
int offset;
diff --git a/cmds/runtime/main_runtime.cpp b/cmds/runtime/main_runtime.cpp
index 785e4cc..dbff095 100644
--- a/cmds/runtime/main_runtime.cpp
+++ b/cmds/runtime/main_runtime.cpp
@@ -497,7 +497,7 @@
#ifndef HAVE_ANDROID_OS
QuickRuntime* runt = new QuickRuntime();
runt->start("com/android/server/SystemServer",
- false /* spontaneously fork system server from zygote */);
+ "" /* spontaneously fork system server from zygote */);
#endif
}
diff --git a/include/gui/Sensor.h b/include/gui/Sensor.h
index 2de07b1..e59757a 100644
--- a/include/gui/Sensor.h
+++ b/include/gui/Sensor.h
@@ -21,8 +21,9 @@
#include <sys/types.h>
#include <utils/Errors.h>
-#include <utils/String8.h>
#include <utils/Flattenable.h>
+#include <utils/String8.h>
+#include <utils/Timers.h>
#include <hardware/sensors.h>
@@ -64,6 +65,8 @@
float getResolution() const;
float getPowerUsage() const;
int32_t getMinDelay() const;
+ nsecs_t getMinDelayNs() const;
+ int32_t getVersion() const;
// Flattenable interface
virtual size_t getFlattenedSize() const;
@@ -83,6 +86,7 @@
float mResolution;
float mPower;
int32_t mMinDelay;
+ int32_t mVersion;
};
// ----------------------------------------------------------------------------
diff --git a/include/gui/SurfaceTexture.h b/include/gui/SurfaceTexture.h
index 43b2fa9..2b31462 100644
--- a/include/gui/SurfaceTexture.h
+++ b/include/gui/SurfaceTexture.h
@@ -197,8 +197,9 @@
mEglDisplay(EGL_NO_DISPLAY),
mBufferState(BufferSlot::FREE),
mRequestBufferCalled(false),
- mLastQueuedTransform(0),
- mLastQueuedTimestamp(0) {
+ mTransform(0),
+ mTimestamp(0) {
+ mCrop.makeInvalid();
}
// mGraphicBuffer points to the buffer allocated for this slot or is NULL
@@ -211,32 +212,56 @@
// mEglDisplay is the EGLDisplay used to create mEglImage.
EGLDisplay mEglDisplay;
- // mBufferState indicates whether the slot is currently accessible to a
- // client and should not be used by the SurfaceTexture object. It gets
- // set to true when dequeueBuffer returns the slot and is reset to false
- // when the client calls either queueBuffer or cancelBuffer on the slot.
- enum { DEQUEUED=-2, FREE=-1, QUEUED=0 };
- int8_t mBufferState;
+ // BufferState represents the different states in which a buffer slot
+ // can be.
+ enum BufferState {
+ // FREE indicates that the buffer is not currently being used and
+ // will not be used in the future until it gets dequeued and
+ // subseqently queued by the client.
+ FREE = 0,
+ // DEQUEUED indicates that the buffer has been dequeued by the
+ // client, but has not yet been queued or canceled. The buffer is
+ // considered 'owned' by the client, and the server should not use
+ // it for anything.
+ //
+ // Note that when in synchronous-mode (mSynchronousMode == true),
+ // the buffer that's currently attached to the texture may be
+ // dequeued by the client. That means that the current buffer can
+ // be in either the DEQUEUED or QUEUED state. In asynchronous mode,
+ // however, the current buffer is always in the QUEUED state.
+ DEQUEUED = 1,
+
+ // QUEUED indicates that the buffer has been queued by the client,
+ // and has not since been made available for the client to dequeue.
+ // Attaching the buffer to the texture does NOT transition the
+ // buffer away from the QUEUED state. However, in Synchronous mode
+ // the current buffer may be dequeued by the client under some
+ // circumstances. See the note about the current buffer in the
+ // documentation for DEQUEUED.
+ QUEUED = 2,
+ };
+
+ // mBufferState is the current state of this buffer slot.
+ BufferState mBufferState;
// mRequestBufferCalled is used for validating that the client did
// call requestBuffer() when told to do so. Technically this is not
// needed but useful for debugging and catching client bugs.
bool mRequestBufferCalled;
- // mLastQueuedCrop is the crop rectangle for the buffer that was most
- // recently queued. This gets set to mNextCrop each time queueBuffer gets
- // called.
- Rect mLastQueuedCrop;
+ // mCrop is the current crop rectangle for this buffer slot. This gets
+ // set to mNextCrop each time queueBuffer gets called for this buffer.
+ Rect mCrop;
- // mLastQueuedTransform is the transform identifier for the buffer that was
- // most recently queued. This gets set to mNextTransform each time
- // queueBuffer gets called.
- uint32_t mLastQueuedTransform;
+ // mTransform is the current transform flags for this buffer slot. This
+ // gets set to mNextTransform each time queueBuffer gets called for this
+ // slot.
+ uint32_t mTransform;
- // mLastQueuedTimestamp is the timestamp for the buffer that was most
- // recently queued. This gets set by queueBuffer.
- int64_t mLastQueuedTimestamp;
+ // mTimestamp is the current timestamp for this buffer slot. This gets
+ // to set by queueBuffer each time this slot is queued.
+ int64_t mTimestamp;
};
// mSlots is the array of buffer slots that must be mirrored on the client
diff --git a/include/ui/Input.h b/include/ui/Input.h
index ba1c6b4..c9f694a 100644
--- a/include/ui/Input.h
+++ b/include/ui/Input.h
@@ -655,11 +655,6 @@
// Oldest sample to consider when calculating the velocity.
static const nsecs_t MAX_AGE = 200 * 1000000; // 200 ms
- // When the total duration of the window of samples being averaged is less
- // than the window size, the resulting velocity is scaled to reduce the impact
- // of overestimation in short traces.
- static const nsecs_t MIN_WINDOW = 100 * 1000000; // 100 ms
-
// The minimum duration between samples when estimating velocity.
static const nsecs_t MIN_DURATION = 10 * 1000000; // 10 ms
@@ -674,6 +669,87 @@
int32_t mActivePointerId;
};
+
+/*
+ * Specifies parameters that govern pointer or wheel acceleration.
+ */
+struct VelocityControlParameters {
+ // A scale factor that is multiplied with the raw velocity deltas
+ // prior to applying any other velocity control factors. The scale
+ // factor should be used to adapt the input device resolution
+ // (eg. counts per inch) to the output device resolution (eg. pixels per inch).
+ //
+ // Must be a positive value.
+ // Default is 1.0 (no scaling).
+ float scale;
+
+ // The scaled speed at which acceleration begins to be applied.
+ // This value establishes the upper bound of a low speed regime for
+ // small precise motions that are performed without any acceleration.
+ //
+ // Must be a non-negative value.
+ // Default is 0.0 (no low threshold).
+ float lowThreshold;
+
+ // The scaled speed at which maximum acceleration is applied.
+ // The difference between highThreshold and lowThreshold controls
+ // the range of speeds over which the acceleration factor is interpolated.
+ // The wider the range, the smoother the acceleration.
+ //
+ // Must be a non-negative value greater than or equal to lowThreshold.
+ // Default is 0.0 (no high threshold).
+ float highThreshold;
+
+ // The acceleration factor.
+ // When the speed is above the low speed threshold, the velocity will scaled
+ // by an interpolated value between 1.0 and this amount.
+ //
+ // Must be a positive greater than or equal to 1.0.
+ // Default is 1.0 (no acceleration).
+ float acceleration;
+
+ VelocityControlParameters() :
+ scale(1.0f), lowThreshold(0.0f), highThreshold(0.0f), acceleration(1.0f) {
+ }
+
+ VelocityControlParameters(float scale, float lowThreshold,
+ float highThreshold, float acceleration) :
+ scale(scale), lowThreshold(lowThreshold),
+ highThreshold(highThreshold), acceleration(acceleration) {
+ }
+};
+
+/*
+ * Implements mouse pointer and wheel speed control and acceleration.
+ */
+class VelocityControl {
+public:
+ VelocityControl();
+
+ /* Sets the various parameters. */
+ void setParameters(const VelocityControlParameters& parameters);
+
+ /* Resets the current movement counters to zero.
+ * This has the effect of nullifying any acceleration. */
+ void reset();
+
+ /* Translates a raw movement delta into an appropriately
+ * scaled / accelerated delta based on the current velocity. */
+ void move(nsecs_t eventTime, float* deltaX, float* deltaY);
+
+private:
+ // If no movements are received within this amount of time,
+ // we assume the movement has stopped and reset the movement counters.
+ static const nsecs_t STOP_TIME = 500 * 1000000; // 500 ms
+
+ VelocityControlParameters mParameters;
+
+ nsecs_t mLastMovementTime;
+ VelocityTracker::Position mRawPosition;
+ VelocityTracker mVelocityTracker;
+};
+
+
/*
* Describes the characteristics and capabilities of an input device.
*/
diff --git a/include/utils/ResourceTypes.h b/include/utils/ResourceTypes.h
index 9e4e132..8a92cd6 100644
--- a/include/utils/ResourceTypes.h
+++ b/include/utils/ResourceTypes.h
@@ -841,6 +841,7 @@
DENSITY_DEFAULT = ACONFIGURATION_DENSITY_DEFAULT,
DENSITY_LOW = ACONFIGURATION_DENSITY_LOW,
DENSITY_MEDIUM = ACONFIGURATION_DENSITY_MEDIUM,
+ DENSITY_TV = ACONFIGURATION_DENSITY_TV,
DENSITY_HIGH = ACONFIGURATION_DENSITY_HIGH,
DENSITY_NONE = ACONFIGURATION_DENSITY_NONE
};
@@ -953,6 +954,7 @@
UI_MODE_TYPE_NORMAL = ACONFIGURATION_UI_MODE_TYPE_NORMAL,
UI_MODE_TYPE_DESK = ACONFIGURATION_UI_MODE_TYPE_DESK,
UI_MODE_TYPE_CAR = ACONFIGURATION_UI_MODE_TYPE_CAR,
+ UI_MODE_TYPE_TELEVISION = ACONFIGURATION_UI_MODE_TYPE_TELEVISION,
// uiMode bits for the night switch.
MASK_UI_MODE_NIGHT = 0x30,
@@ -1451,24 +1453,20 @@
// settings is the requested settings
inline bool match(const ResTable_config& settings) const {
if (imsi != 0) {
- if ((settings.mcc != 0 && mcc != 0
- && mcc != settings.mcc) ||
- (settings.mcc == 0 && mcc != 0)) {
+ if (mcc != 0 && mcc != settings.mcc) {
return false;
}
- if ((settings.mnc != 0 && mnc != 0
- && mnc != settings.mnc) ||
- (settings.mnc == 0 && mnc != 0)) {
+ if (mnc != 0 && mnc != settings.mnc) {
return false;
}
}
if (locale != 0) {
- if (settings.language[0] != 0 && language[0] != 0
+ if (language[0] != 0
&& (language[0] != settings.language[0]
|| language[1] != settings.language[1])) {
return false;
}
- if (settings.country[0] != 0 && country[0] != 0
+ if (country[0] != 0
&& (country[0] != settings.country[0]
|| country[1] != settings.country[1])) {
return false;
@@ -1479,66 +1477,56 @@
const int setScreenSize = settings.screenLayout&MASK_SCREENSIZE;
// Any screen sizes for larger screens than the setting do not
// match.
- if ((setScreenSize != 0 && screenSize != 0
- && screenSize > setScreenSize) ||
- (setScreenSize == 0 && screenSize != 0)) {
+ if (screenSize != 0 && screenSize > setScreenSize) {
return false;
}
const int screenLong = screenLayout&MASK_SCREENLONG;
const int setScreenLong = settings.screenLayout&MASK_SCREENLONG;
- if (setScreenLong != 0 && screenLong != 0
- && screenLong != setScreenLong) {
+ if (screenLong != 0 && screenLong != setScreenLong) {
return false;
}
const int uiModeType = uiMode&MASK_UI_MODE_TYPE;
const int setUiModeType = settings.uiMode&MASK_UI_MODE_TYPE;
- if (setUiModeType != 0 && uiModeType != 0
- && uiModeType != setUiModeType) {
+ if (uiModeType != 0 && uiModeType != setUiModeType) {
return false;
}
const int uiModeNight = uiMode&MASK_UI_MODE_NIGHT;
const int setUiModeNight = settings.uiMode&MASK_UI_MODE_NIGHT;
- if (setUiModeNight != 0 && uiModeNight != 0
- && uiModeNight != setUiModeNight) {
+ if (uiModeNight != 0 && uiModeNight != setUiModeNight) {
return false;
}
- if (settings.smallestScreenWidthDp != 0 && smallestScreenWidthDp != 0
+ if (smallestScreenWidthDp != 0
&& smallestScreenWidthDp > settings.smallestScreenWidthDp) {
return false;
}
}
if (screenSizeDp != 0) {
- if (settings.screenWidthDp != 0 && screenWidthDp != 0
- && screenWidthDp > settings.screenWidthDp) {
+ if (screenWidthDp != 0 && screenWidthDp > settings.screenWidthDp) {
//LOGI("Filtering out width %d in requested %d", screenWidthDp, settings.screenWidthDp);
return false;
}
- if (settings.screenHeightDp != 0 && screenHeightDp != 0
- && screenHeightDp > settings.screenHeightDp) {
+ if (screenHeightDp != 0 && screenHeightDp > settings.screenHeightDp) {
//LOGI("Filtering out height %d in requested %d", screenHeightDp, settings.screenHeightDp);
return false;
}
}
if (screenType != 0) {
- if (settings.orientation != 0 && orientation != 0
- && orientation != settings.orientation) {
+ if (orientation != 0 && orientation != settings.orientation) {
return false;
}
// density always matches - we can scale it. See isBetterThan
- if (settings.touchscreen != 0 && touchscreen != 0
- && touchscreen != settings.touchscreen) {
+ if (touchscreen != 0 && touchscreen != settings.touchscreen) {
return false;
}
}
if (input != 0) {
const int keysHidden = inputFlags&MASK_KEYSHIDDEN;
const int setKeysHidden = settings.inputFlags&MASK_KEYSHIDDEN;
- if (setKeysHidden != 0 && keysHidden != 0
- && keysHidden != setKeysHidden) {
+ if (keysHidden != 0 && keysHidden != setKeysHidden) {
// For compatibility, we count a request for KEYSHIDDEN_NO as also
// matching the more recent KEYSHIDDEN_SOFT. Basically
// KEYSHIDDEN_NO means there is some kind of keyboard available.
@@ -1550,36 +1538,29 @@
}
const int navHidden = inputFlags&MASK_NAVHIDDEN;
const int setNavHidden = settings.inputFlags&MASK_NAVHIDDEN;
- if (setNavHidden != 0 && navHidden != 0
- && navHidden != setNavHidden) {
+ if (navHidden != 0 && navHidden != setNavHidden) {
return false;
}
- if (settings.keyboard != 0 && keyboard != 0
- && keyboard != settings.keyboard) {
+ if (keyboard != 0 && keyboard != settings.keyboard) {
return false;
}
- if (settings.navigation != 0 && navigation != 0
- && navigation != settings.navigation) {
+ if (navigation != 0 && navigation != settings.navigation) {
return false;
}
}
if (screenSize != 0) {
- if (settings.screenWidth != 0 && screenWidth != 0
- && screenWidth > settings.screenWidth) {
+ if (screenWidth != 0 && screenWidth > settings.screenWidth) {
return false;
}
- if (settings.screenHeight != 0 && screenHeight != 0
- && screenHeight > settings.screenHeight) {
+ if (screenHeight != 0 && screenHeight > settings.screenHeight) {
return false;
}
}
if (version != 0) {
- if (settings.sdkVersion != 0 && sdkVersion != 0
- && sdkVersion > settings.sdkVersion) {
+ if (sdkVersion != 0 && sdkVersion > settings.sdkVersion) {
return false;
}
- if (settings.minorVersion != 0 && minorVersion != 0
- && minorVersion != settings.minorVersion) {
+ if (minorVersion != 0 && minorVersion != settings.minorVersion) {
return false;
}
}
diff --git a/libs/gui/Sensor.cpp b/libs/gui/Sensor.cpp
index b1f37ff..f9a2c04 100644
--- a/libs/gui/Sensor.cpp
+++ b/libs/gui/Sensor.cpp
@@ -89,6 +89,14 @@
return mMinDelay;
}
+nsecs_t Sensor::getMinDelayNs() const {
+ return getMinDelay() * 1000;
+}
+
+int32_t Sensor::getVersion() const {
+ return mVersion;
+}
+
size_t Sensor::getFlattenedSize() const
{
return sizeof(int32_t) + ((mName.length() + 3) & ~3) +
diff --git a/libs/gui/SurfaceTexture.cpp b/libs/gui/SurfaceTexture.cpp
index b08a5a8..ee97dcf 100644
--- a/libs/gui/SurfaceTexture.cpp
+++ b/libs/gui/SurfaceTexture.cpp
@@ -285,15 +285,19 @@
return -EINVAL;
}
- // make sure the client is not trying to dequeue more buffers
- // than allowed.
- const int avail = mBufferCount - (dequeuedCount+1);
- if (avail < (MIN_UNDEQUEUED_BUFFERS-int(mSynchronousMode))) {
- LOGE("dequeueBuffer: MIN_UNDEQUEUED_BUFFERS=%d exceeded (dequeued=%d)",
- MIN_UNDEQUEUED_BUFFERS-int(mSynchronousMode),
- dequeuedCount);
- // TODO: Enable this error report after we fix issue 4435022
- // return -EBUSY;
+ // See whether a buffer has been queued since the last setBufferCount so
+ // we know whether to perform the MIN_UNDEQUEUED_BUFFERS check below.
+ bool bufferHasBeenQueued = mCurrentTexture != INVALID_BUFFER_SLOT;
+ if (bufferHasBeenQueued) {
+ // make sure the client is not trying to dequeue more buffers
+ // than allowed.
+ const int avail = mBufferCount - (dequeuedCount+1);
+ if (avail < (MIN_UNDEQUEUED_BUFFERS-int(mSynchronousMode))) {
+ LOGE("dequeueBuffer: MIN_UNDEQUEUED_BUFFERS=%d exceeded (dequeued=%d)",
+ MIN_UNDEQUEUED_BUFFERS-int(mSynchronousMode),
+ dequeuedCount);
+ return -EBUSY;
+ }
}
// we're in synchronous mode and didn't find a buffer, we need to wait
@@ -390,49 +394,49 @@
sp<FrameAvailableListener> listener;
{ // scope for the lock
- Mutex::Autolock lock(mMutex);
- if (buf < 0 || buf >= mBufferCount) {
- LOGE("queueBuffer: slot index out of range [0, %d]: %d",
- mBufferCount, buf);
- return -EINVAL;
- } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
- LOGE("queueBuffer: slot %d is not owned by the client (state=%d)",
- buf, mSlots[buf].mBufferState);
- return -EINVAL;
- } else if (buf == mCurrentTexture) {
- LOGE("queueBuffer: slot %d is current!", buf);
- return -EINVAL;
- } else if (!mSlots[buf].mRequestBufferCalled) {
- LOGE("queueBuffer: slot %d was enqueued without requesting a buffer",
- buf);
- return -EINVAL;
- }
+ Mutex::Autolock lock(mMutex);
+ if (buf < 0 || buf >= mBufferCount) {
+ LOGE("queueBuffer: slot index out of range [0, %d]: %d",
+ mBufferCount, buf);
+ return -EINVAL;
+ } else if (mSlots[buf].mBufferState != BufferSlot::DEQUEUED) {
+ LOGE("queueBuffer: slot %d is not owned by the client (state=%d)",
+ buf, mSlots[buf].mBufferState);
+ return -EINVAL;
+ } else if (buf == mCurrentTexture) {
+ LOGE("queueBuffer: slot %d is current!", buf);
+ return -EINVAL;
+ } else if (!mSlots[buf].mRequestBufferCalled) {
+ LOGE("queueBuffer: slot %d was enqueued without requesting a "
+ "buffer", buf);
+ return -EINVAL;
+ }
- if (mQueue.empty()) {
- listener = mFrameAvailableListener;
- }
-
- if (mSynchronousMode) {
- // in synchronous mode we queue all buffers in a FIFO
- mQueue.push_back(buf);
- } else {
- // in asynchronous mode we only keep the most recent buffer
if (mQueue.empty()) {
+ listener = mFrameAvailableListener;
+ }
+
+ if (mSynchronousMode) {
+ // in synchronous mode we queue all buffers in a FIFO
mQueue.push_back(buf);
} else {
- Fifo::iterator front(mQueue.begin());
- // buffer currently queued is freed
- mSlots[*front].mBufferState = BufferSlot::FREE;
- // and we record the new buffer index in the queued list
- *front = buf;
+ // in asynchronous mode we only keep the most recent buffer
+ if (mQueue.empty()) {
+ mQueue.push_back(buf);
+ } else {
+ Fifo::iterator front(mQueue.begin());
+ // buffer currently queued is freed
+ mSlots[*front].mBufferState = BufferSlot::FREE;
+ // and we record the new buffer index in the queued list
+ *front = buf;
+ }
}
- }
- mSlots[buf].mBufferState = BufferSlot::QUEUED;
- mSlots[buf].mLastQueuedCrop = mNextCrop;
- mSlots[buf].mLastQueuedTransform = mNextTransform;
- mSlots[buf].mLastQueuedTimestamp = timestamp;
- mDequeueCondition.signal();
+ mSlots[buf].mBufferState = BufferSlot::QUEUED;
+ mSlots[buf].mCrop = mNextCrop;
+ mSlots[buf].mTransform = mNextTransform;
+ mSlots[buf].mTimestamp = timestamp;
+ mDequeueCondition.signal();
} // scope for the lock
// call back without lock held
@@ -540,9 +544,9 @@
mCurrentTexture = buf;
mCurrentTextureTarget = target;
mCurrentTextureBuf = mSlots[buf].mGraphicBuffer;
- mCurrentCrop = mSlots[buf].mLastQueuedCrop;
- mCurrentTransform = mSlots[buf].mLastQueuedTransform;
- mCurrentTimestamp = mSlots[buf].mLastQueuedTimestamp;
+ mCurrentCrop = mSlots[buf].mCrop;
+ mCurrentTransform = mSlots[buf].mTransform;
+ mCurrentTimestamp = mSlots[buf].mTimestamp;
mDequeueCondition.signal();
} else {
// We always bind the texture even if we don't update its contents.
@@ -826,12 +830,10 @@
const BufferSlot& slot(mSlots[i]);
snprintf(buffer, SIZE,
"%s%s[%02d] state=%-8s, crop=[%d,%d,%d,%d], transform=0x%02x, "
- "timestamp=%lld\n"
- ,
+ "timestamp=%lld\n",
prefix, (i==mCurrentTexture)?">":" ", i, stateName(slot.mBufferState),
- slot.mLastQueuedCrop.left, slot.mLastQueuedCrop.top,
- slot.mLastQueuedCrop.right, slot.mLastQueuedCrop.bottom,
- slot.mLastQueuedTransform, slot.mLastQueuedTimestamp
+ slot.mCrop.left, slot.mCrop.top, slot.mCrop.right, slot.mCrop.bottom,
+ slot.mTransform, slot.mTimestamp
);
result.append(buffer);
}
diff --git a/libs/gui/SurfaceTextureClient.cpp b/libs/gui/SurfaceTextureClient.cpp
index 6f10320..c20fcf2 100644
--- a/libs/gui/SurfaceTextureClient.cpp
+++ b/libs/gui/SurfaceTextureClient.cpp
@@ -117,7 +117,8 @@
mReqFormat, mReqUsage);
if (result < 0) {
LOGV("dequeueBuffer: ISurfaceTexture::dequeueBuffer(%d, %d, %d, %d)"
- "failed: %d", result, mReqWidth, mReqHeight, mReqFormat, mReqUsage);
+ "failed: %d", mReqWidth, mReqHeight, mReqFormat, mReqUsage,
+ result);
return result;
}
sp<GraphicBuffer>& gbuf(mSlots[buf]);
diff --git a/libs/gui/tests/SurfaceTextureClient_test.cpp b/libs/gui/tests/SurfaceTextureClient_test.cpp
index 59a4cc5..2f704c8 100644
--- a/libs/gui/tests/SurfaceTextureClient_test.cpp
+++ b/libs/gui/tests/SurfaceTextureClient_test.cpp
@@ -400,7 +400,9 @@
EXPECT_EQ(st->getCurrentBuffer().get(), buf[2]);
}
-TEST_F(SurfaceTextureClientTest, SurfaceTextureSyncModeDequeueCurrent) {
+// XXX: We currently have no hardware that properly handles dequeuing the
+// buffer that is currently bound to the texture.
+TEST_F(SurfaceTextureClientTest, DISABLED_SurfaceTextureSyncModeDequeueCurrent) {
sp<ANativeWindow> anw(mSTC);
sp<SurfaceTexture> st(mST);
android_native_buffer_t* buf[3];
@@ -429,10 +431,13 @@
android_native_buffer_t* buf[3];
ASSERT_EQ(OK, st->setSynchronousMode(true));
ASSERT_EQ(OK, native_window_set_buffer_count(anw.get(), 3));
+
+ // We should be able to dequeue all the buffers before we've queued any.
EXPECT_EQ(OK, anw->dequeueBuffer(anw.get(), &buf[0]));
EXPECT_EQ(OK, anw->dequeueBuffer(anw.get(), &buf[1]));
- EXPECT_EQ(-EBUSY, anw->dequeueBuffer(anw.get(), &buf[2]));
+ EXPECT_EQ(OK, anw->dequeueBuffer(anw.get(), &buf[2]));
+ ASSERT_EQ(OK, anw->cancelBuffer(anw.get(), buf[2]));
ASSERT_EQ(OK, anw->queueBuffer(anw.get(), buf[1]));
EXPECT_EQ(OK, st->updateTexImage());
@@ -440,11 +445,17 @@
EXPECT_EQ(OK, anw->dequeueBuffer(anw.get(), &buf[2]));
+ // Once we've queued a buffer, however we should not be able to dequeue more
+ // than (buffer-count - MIN_UNDEQUEUED_BUFFERS), which is 2 in this case.
+ EXPECT_EQ(-EBUSY, anw->dequeueBuffer(anw.get(), &buf[1]));
+
ASSERT_EQ(OK, anw->cancelBuffer(anw.get(), buf[0]));
ASSERT_EQ(OK, anw->cancelBuffer(anw.get(), buf[2]));
}
-TEST_F(SurfaceTextureClientTest, SurfaceTextureSyncModeWaitRetire) {
+// XXX: This is not expected to pass until the synchronization hacks are removed
+// from the SurfaceTexture class.
+TEST_F(SurfaceTextureClientTest, DISABLED_SurfaceTextureSyncModeWaitRetire) {
sp<ANativeWindow> anw(mSTC);
sp<SurfaceTexture> st(mST);
diff --git a/libs/ui/Input.cpp b/libs/ui/Input.cpp
index 1ba38a7..0af7f80 100644
--- a/libs/ui/Input.cpp
+++ b/libs/ui/Input.cpp
@@ -13,6 +13,10 @@
// Log debug messages about velocity tracking.
#define DEBUG_VELOCITY 0
+// Log debug messages about acceleration.
+#define DEBUG_ACCELERATION 0
+
+
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
@@ -20,6 +24,7 @@
#include <ui/Input.h>
#include <math.h>
+#include <limits.h>
#ifdef HAVE_ANDROID_OS
#include <binder/Parcel.h>
@@ -693,6 +698,10 @@
// --- VelocityTracker ---
+const uint32_t VelocityTracker::HISTORY_SIZE;
+const nsecs_t VelocityTracker::MAX_AGE;
+const nsecs_t VelocityTracker::MIN_DURATION;
+
VelocityTracker::VelocityTracker() {
clear();
}
@@ -881,14 +890,6 @@
// Make sure we used at least one sample.
if (samplesUsed != 0) {
- // Scale the velocity linearly if the window of samples is small.
- nsecs_t totalDuration = newestMovement.eventTime - oldestMovement.eventTime;
- if (totalDuration < MIN_WINDOW) {
- float scale = float(totalDuration) / float(MIN_WINDOW);
- accumVx *= scale;
- accumVy *= scale;
- }
-
*outVx = accumVx;
*outVy = accumVy;
return true;
@@ -902,6 +903,85 @@
}
+// --- VelocityControl ---
+
+const nsecs_t VelocityControl::STOP_TIME;
+
+VelocityControl::VelocityControl() {
+ reset();
+}
+
+void VelocityControl::setParameters(const VelocityControlParameters& parameters) {
+ mParameters = parameters;
+ reset();
+}
+
+void VelocityControl::reset() {
+ mLastMovementTime = LLONG_MIN;
+ mRawPosition.x = 0;
+ mRawPosition.y = 0;
+ mVelocityTracker.clear();
+}
+
+void VelocityControl::move(nsecs_t eventTime, float* deltaX, float* deltaY) {
+ if ((deltaX && *deltaX) || (deltaY && *deltaY)) {
+ if (eventTime >= mLastMovementTime + STOP_TIME) {
+#if DEBUG_ACCELERATION
+ LOGD("VelocityControl: stopped, last movement was %0.3fms ago",
+ (eventTime - mLastMovementTime) * 0.000001f);
+#endif
+ reset();
+ }
+
+ mLastMovementTime = eventTime;
+ if (deltaX) {
+ mRawPosition.x += *deltaX;
+ }
+ if (deltaY) {
+ mRawPosition.y += *deltaY;
+ }
+ mVelocityTracker.addMovement(eventTime, BitSet32(BitSet32::valueForBit(0)), &mRawPosition);
+
+ float vx, vy;
+ float scale = mParameters.scale;
+ if (mVelocityTracker.getVelocity(0, &vx, &vy)) {
+ float speed = hypotf(vx, vy) * scale;
+ if (speed >= mParameters.highThreshold) {
+ // Apply full acceleration above the high speed threshold.
+ scale *= mParameters.acceleration;
+ } else if (speed > mParameters.lowThreshold) {
+ // Linearly interpolate the acceleration to apply between the low and high
+ // speed thresholds.
+ scale *= 1 + (speed - mParameters.lowThreshold)
+ / (mParameters.highThreshold - mParameters.lowThreshold)
+ * (mParameters.acceleration - 1);
+ }
+
+#if DEBUG_ACCELERATION
+ LOGD("VelocityControl(%0.3f, %0.3f, %0.3f, %0.3f): "
+ "vx=%0.3f, vy=%0.3f, speed=%0.3f, accel=%0.3f",
+ mParameters.scale, mParameters.lowThreshold, mParameters.highThreshold,
+ mParameters.acceleration,
+ vx, vy, speed, scale / mParameters.scale);
+#endif
+ } else {
+#if DEBUG_ACCELERATION
+ LOGD("VelocityControl(%0.3f, %0.3f, %0.3f, %0.3f): unknown velocity",
+ mParameters.scale, mParameters.lowThreshold, mParameters.highThreshold,
+ mParameters.acceleration);
+#endif
+ }
+
+ if (deltaX) {
+ *deltaX *= scale;
+ }
+ if (deltaY) {
+ *deltaY *= scale;
+ }
+ }
+}
+
+
// --- InputDeviceInfo ---
InputDeviceInfo::InputDeviceInfo() {
diff --git a/libs/utils/BackupHelpers.cpp b/libs/utils/BackupHelpers.cpp
index e15875f..f933199 100644
--- a/libs/utils/BackupHelpers.cpp
+++ b/libs/utils/BackupHelpers.cpp
@@ -503,6 +503,16 @@
needExtended = true;
}
+ // Non-7bit-clean path also means needing pax extended format
+ if (!needExtended) {
+ for (size_t i = 0; i < filepath.length(); i++) {
+ if ((filepath[i] & 0x80) != 0) {
+ needExtended = true;
+ break;
+ }
+ }
+ }
+
int err = 0;
struct stat64 s;
if (lstat64(filepath.string(), &s) != 0) {
diff --git a/opengl/libs/Android.mk b/opengl/libs/Android.mk
index afefee6..ff45edc 100644
--- a/opengl/libs/Android.mk
+++ b/opengl/libs/Android.mk
@@ -14,7 +14,6 @@
EGL/eglApi.cpp \
EGL/trace.cpp \
EGL/getProcAddress.cpp.arm \
- EGL/hooks.cpp \
EGL/Loader.cpp \
#
diff --git a/opengl/libs/EGL/Loader.cpp b/opengl/libs/EGL/Loader.cpp
index da26229..e94e50e 100644
--- a/opengl/libs/EGL/Loader.cpp
+++ b/opengl/libs/EGL/Loader.cpp
@@ -26,11 +26,10 @@
#include <EGL/egl.h>
-#include "hooks.h"
-#include "egl_impl.h"
-
-#include "Loader.h"
+#include "egldefs.h"
#include "glesv2dbg.h"
+#include "hooks.h"
+#include "Loader.h"
// ----------------------------------------------------------------------------
namespace android {
diff --git a/opengl/libs/EGL/egl.cpp b/opengl/libs/EGL/egl.cpp
index 31fe306..b11db32 100644
--- a/opengl/libs/EGL/egl.cpp
+++ b/opengl/libs/EGL/egl.cpp
@@ -33,6 +33,7 @@
#include <utils/String8.h>
+#include "egldefs.h"
#include "egl_impl.h"
#include "egl_tls.h"
#include "glesv2dbg.h"
@@ -278,6 +279,71 @@
return res;
}
+void gl_unimplemented() {
+ LOGE("called unimplemented OpenGL ES API");
+}
+
+// ----------------------------------------------------------------------------
+
+#if USE_FAST_TLS_KEY
+
+// We have a dedicated TLS slot in bionic
+static inline gl_hooks_t const * volatile * get_tls_hooks() {
+ volatile void *tls_base = __get_tls();
+ gl_hooks_t const * volatile * tls_hooks =
+ reinterpret_cast<gl_hooks_t const * volatile *>(tls_base);
+ return tls_hooks;
+}
+
+void setGlThreadSpecific(gl_hooks_t const *value) {
+ gl_hooks_t const * volatile * tls_hooks = get_tls_hooks();
+ tls_hooks[TLS_SLOT_OPENGL_API] = value;
+}
+
+gl_hooks_t const* getGlThreadSpecific() {
+ gl_hooks_t const * volatile * tls_hooks = get_tls_hooks();
+ gl_hooks_t const* hooks = tls_hooks[TLS_SLOT_OPENGL_API];
+ if (hooks) return hooks;
+ return &gHooksNoContext;
+}
+
+#else
+
+void setGlThreadSpecific(gl_hooks_t const *value) {
+ pthread_setspecific(gGLWrapperKey, value);
+}
+
+gl_hooks_t const* getGlThreadSpecific() {
+ gl_hooks_t const* hooks = static_cast<gl_hooks_t*>(pthread_getspecific(gGLWrapperKey));
+ if (hooks) return hooks;
+ return &gHooksNoContext;
+}
+
+#endif
+
+// ----------------------------------------------------------------------------
+// GL / EGL hooks
+// ----------------------------------------------------------------------------
+
+#undef GL_ENTRY
+#undef EGL_ENTRY
+#define GL_ENTRY(_r, _api, ...) #_api,
+#define EGL_ENTRY(_r, _api, ...) #_api,
+
+char const * const gl_names[] = {
+ #include "entries.in"
+ NULL
+};
+
+char const * const egl_names[] = {
+ #include "egl_entries.in"
+ NULL
+};
+
+#undef GL_ENTRY
+#undef EGL_ENTRY
+
+
// ----------------------------------------------------------------------------
}; // namespace android
// ----------------------------------------------------------------------------
diff --git a/opengl/libs/EGL/egl_display.h b/opengl/libs/EGL/egl_display.h
index 8c482c3..113595f 100644
--- a/opengl/libs/EGL/egl_display.h
+++ b/opengl/libs/EGL/egl_display.h
@@ -30,6 +30,7 @@
#include <utils/SortedVector.h>
#include <utils/threads.h>
+#include "egldefs.h"
#include "hooks.h"
// ----------------------------------------------------------------------------
diff --git a/opengl/libs/EGL/egl_tls.h b/opengl/libs/EGL/egl_tls.h
index 8b31468..a7989ef 100644
--- a/opengl/libs/EGL/egl_tls.h
+++ b/opengl/libs/EGL/egl_tls.h
@@ -21,7 +21,12 @@
#include <EGL/egl.h>
+#include "egldefs.h"
+#include "hooks.h"
+
+// ----------------------------------------------------------------------------
namespace android {
+// ----------------------------------------------------------------------------
class DbgContext;
@@ -58,6 +63,16 @@
#define setError(_e, _r) egl_tls_t::setErrorEtc(__FUNCTION__, __LINE__, _e, _r)
+// ----------------------------------------------------------------------------
+
+#if EGL_TRACE
+
+extern gl_hooks_t const* getGLTraceThreadSpecific();
+
+#endif
+
+// ----------------------------------------------------------------------------
}; // namespace android
+// ----------------------------------------------------------------------------
#endif // ANDROID_EGL_TLS_H
diff --git a/opengl/libs/EGL/egldefs.h b/opengl/libs/EGL/egldefs.h
new file mode 100644
index 0000000..107acd9
--- /dev/null
+++ b/opengl/libs/EGL/egldefs.h
@@ -0,0 +1,71 @@
+/*
+ ** Copyright 2011, 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.
+ */
+
+#ifndef ANDROID_EGLDEFS_H
+#define ANDROID_EGLDEFS_H
+
+#include "hooks.h"
+
+// ----------------------------------------------------------------------------
+namespace android {
+// ----------------------------------------------------------------------------
+
+#define VERSION_MAJOR 1
+#define VERSION_MINOR 4
+
+// EGLDisplay are global, not attached to a given thread
+const unsigned int NUM_DISPLAYS = 1;
+
+enum {
+ IMPL_HARDWARE = 0,
+ IMPL_SOFTWARE,
+ IMPL_NUM_IMPLEMENTATIONS
+};
+
+enum {
+ GLESv1_INDEX = 0,
+ GLESv2_INDEX = 1,
+};
+
+// ----------------------------------------------------------------------------
+
+struct egl_connection_t
+{
+ inline egl_connection_t() : dso(0) { }
+ void * dso;
+ gl_hooks_t * hooks[2];
+ EGLint major;
+ EGLint minor;
+ egl_t egl;
+};
+
+// ----------------------------------------------------------------------------
+
+extern gl_hooks_t gHooks[2][IMPL_NUM_IMPLEMENTATIONS];
+extern gl_hooks_t gHooksNoContext;
+extern pthread_key_t gGLWrapperKey;
+extern "C" void gl_unimplemented();
+
+extern char const * const gl_names[];
+extern char const * const egl_names[];
+
+extern egl_connection_t gEGLImpl[IMPL_NUM_IMPLEMENTATIONS];
+
+// ----------------------------------------------------------------------------
+}; // namespace android
+// ----------------------------------------------------------------------------
+
+#endif /* ANDROID_EGLDEFS_H */
diff --git a/opengl/libs/EGL/getProcAddress.cpp b/opengl/libs/EGL/getProcAddress.cpp
index dcf8735..f89c865 100644
--- a/opengl/libs/EGL/getProcAddress.cpp
+++ b/opengl/libs/EGL/getProcAddress.cpp
@@ -20,6 +20,7 @@
#include <cutils/log.h>
+#include "egldefs.h"
#include "hooks.h"
// ----------------------------------------------------------------------------
@@ -34,7 +35,7 @@
#undef GL_EXTENSION_LIST
#undef GET_TLS
-#if defined(__arm__)
+#if USE_FAST_TLS_KEY
#ifdef HAVE_ARM_TLS_REGISTER
#define GET_TLS(reg) \
@@ -77,7 +78,7 @@
#define GL_EXTENSION(_n)
- #warning "eglGetProcAddress() partially supported on this architecture"
+ #warning "eglGetProcAddress() partially supported"
#endif
diff --git a/opengl/libs/EGL/hooks.cpp b/opengl/libs/EGL/hooks.cpp
deleted file mode 100644
index 72ad6b3..0000000
--- a/opengl/libs/EGL/hooks.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- ** Copyright 2009, 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.
- */
-
-#include <ctype.h>
-#include <stdlib.h>
-#include <errno.h>
-
-#include <cutils/log.h>
-
-#include "hooks.h"
-
-// ----------------------------------------------------------------------------
-namespace android {
-// ----------------------------------------------------------------------------
-
-void gl_unimplemented() {
- LOGE("called unimplemented OpenGL ES API");
-}
-
-
-// ----------------------------------------------------------------------------
-// GL / EGL hooks
-// ----------------------------------------------------------------------------
-
-#undef GL_ENTRY
-#undef EGL_ENTRY
-#define GL_ENTRY(_r, _api, ...) #_api,
-#define EGL_ENTRY(_r, _api, ...) #_api,
-
-char const * const gl_names[] = {
- #include "entries.in"
- NULL
-};
-
-char const * const egl_names[] = {
- #include "egl_entries.in"
- NULL
-};
-
-#undef GL_ENTRY
-#undef EGL_ENTRY
-
-
-// ----------------------------------------------------------------------------
-}; // namespace android
-// ----------------------------------------------------------------------------
-
diff --git a/opengl/libs/EGL/trace.cpp b/opengl/libs/EGL/trace.cpp
index f3e101b..0e934e2 100644
--- a/opengl/libs/EGL/trace.cpp
+++ b/opengl/libs/EGL/trace.cpp
@@ -26,6 +26,7 @@
#include <cutils/log.h>
+#include "egl_tls.h"
#include "hooks.h"
// ----------------------------------------------------------------------------
diff --git a/opengl/libs/egl_impl.h b/opengl/libs/egl_impl.h
index d24b047..a809316 100644
--- a/opengl/libs/egl_impl.h
+++ b/opengl/libs/egl_impl.h
@@ -25,27 +25,12 @@
#include "hooks.h"
-#define VERSION_MAJOR 1
-#define VERSION_MINOR 4
-
// ----------------------------------------------------------------------------
namespace android {
// ----------------------------------------------------------------------------
-struct egl_connection_t
-{
- inline egl_connection_t() : dso(0) { }
- void * dso;
- gl_hooks_t * hooks[2];
- EGLint major;
- EGLint minor;
- egl_t egl;
-};
-
EGLAPI EGLImageKHR egl_get_image_for_current_context(EGLImageKHR image);
-extern egl_connection_t gEGLImpl[IMPL_NUM_IMPLEMENTATIONS];
-
// ----------------------------------------------------------------------------
}; // namespace android
// ----------------------------------------------------------------------------
diff --git a/opengl/libs/hooks.h b/opengl/libs/hooks.h
index 812e26d..7ac88cd 100644
--- a/opengl/libs/hooks.h
+++ b/opengl/libs/hooks.h
@@ -54,22 +54,6 @@
namespace android {
// ----------------------------------------------------------------------------
-// EGLDisplay are global, not attached to a given thread
-const unsigned int NUM_DISPLAYS = 1;
-
-enum {
- IMPL_HARDWARE = 0,
- IMPL_SOFTWARE,
- IMPL_NUM_IMPLEMENTATIONS
-};
-
-enum {
- GLESv1_INDEX = 0,
- GLESv2_INDEX = 1,
-};
-
-// ----------------------------------------------------------------------------
-
// GL / EGL hooks
#undef GL_ENTRY
@@ -92,60 +76,8 @@
#undef GL_ENTRY
#undef EGL_ENTRY
-
-// ----------------------------------------------------------------------------
-
-extern gl_hooks_t gHooks[2][IMPL_NUM_IMPLEMENTATIONS];
-extern gl_hooks_t gHooksNoContext;
-extern pthread_key_t gGLWrapperKey;
-extern "C" void gl_unimplemented();
-
-extern char const * const gl_names[];
-extern char const * const egl_names[];
-
-// ----------------------------------------------------------------------------
-
-#if USE_FAST_TLS_KEY
-
-// We have a dedicated TLS slot in bionic
-static inline gl_hooks_t const * volatile * get_tls_hooks() {
- volatile void *tls_base = __get_tls();
- gl_hooks_t const * volatile * tls_hooks =
- reinterpret_cast<gl_hooks_t const * volatile *>(tls_base);
- return tls_hooks;
-}
-
-static inline void setGlThreadSpecific(gl_hooks_t const *value) {
- gl_hooks_t const * volatile * tls_hooks = get_tls_hooks();
- tls_hooks[TLS_SLOT_OPENGL_API] = value;
-}
-
-static gl_hooks_t const* getGlThreadSpecific() {
- gl_hooks_t const * volatile * tls_hooks = get_tls_hooks();
- gl_hooks_t const* hooks = tls_hooks[TLS_SLOT_OPENGL_API];
- if (hooks) return hooks;
- return &gHooksNoContext;
-}
-
-#else
-
-static inline void setGlThreadSpecific(gl_hooks_t const *value) {
- pthread_setspecific(gGLWrapperKey, value);
-}
-
-static gl_hooks_t const* getGlThreadSpecific() {
- gl_hooks_t const* hooks = static_cast<gl_hooks_t*>(pthread_getspecific(gGLWrapperKey));
- if (hooks) return hooks;
- return &gHooksNoContext;
-}
-
-#endif
-
-#if EGL_TRACE
-
-extern gl_hooks_t const* getGLTraceThreadSpecific();
-
-#endif
+EGLAPI void setGlThreadSpecific(gl_hooks_t const *value);
+EGLAPI gl_hooks_t const* getGlThreadSpecific();
// ----------------------------------------------------------------------------
}; // namespace android