diff options
127 files changed, 1618 insertions, 4176 deletions
diff --git a/adb/Android.mk b/adb/Android.mk index 3828ed3..8ebcbf0 100644 --- a/adb/Android.mk +++ b/adb/Android.mk @@ -63,9 +63,6 @@ LOCAL_SRC_FILES := \ file_sync_client.c \ $(EXTRA_SRCS) \ $(USB_SRCS) \ - usb_vendors.c - -LOCAL_C_INCLUDES += external/openssl/include ifneq ($(USE_SYSDEPS_WIN32),) LOCAL_SRC_FILES += sysdeps_win32.c @@ -78,7 +75,7 @@ LOCAL_CFLAGS += -D_XOPEN_SOURCE -D_GNU_SOURCE LOCAL_MODULE := adb LOCAL_MODULE_TAGS := debug -LOCAL_STATIC_LIBRARIES := libzipfile libunz libcrypto_static $(EXTRA_STATIC_LIBS) +LOCAL_STATIC_LIBRARIES := libzipfile libz libcrypto_static $(EXTRA_STATIC_LIBS) ifeq ($(USE_SYSDEPS_WIN32),) LOCAL_STATIC_LIBRARIES += libcutils endif @@ -113,6 +110,7 @@ LOCAL_SRC_FILES := \ jdwp_service.c \ framebuffer_service.c \ remount_service.c \ + set_verity_enable_state_service.c \ usb_linux_client.c LOCAL_CFLAGS := \ @@ -127,14 +125,27 @@ ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT))) LOCAL_CFLAGS += -DALLOW_ADBD_ROOT=1 endif +ifneq (,$(filter userdebug,$(TARGET_BUILD_VARIANT))) +LOCAL_CFLAGS += -DALLOW_ADBD_DISABLE_VERITY=1 +endif + LOCAL_MODULE := adbd LOCAL_FORCE_STATIC_EXECUTABLE := true LOCAL_MODULE_PATH := $(TARGET_ROOT_OUT_SBIN) LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_SBIN_UNSTRIPPED) +LOCAL_C_INCLUDES += system/extras/ext4_utils system/core/fs_mgr/include + +LOCAL_STATIC_LIBRARIES := liblog \ + libfs_mgr \ + libcutils \ + libc \ + libmincrypt \ + libselinux \ + libext4_utils_static -LOCAL_STATIC_LIBRARIES := liblog libcutils libc libmincrypt libselinux LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk + include $(BUILD_EXECUTABLE) @@ -157,7 +168,6 @@ LOCAL_SRC_FILES := \ file_sync_client.c \ get_my_path_linux.c \ usb_linux.c \ - usb_vendors.c \ fdevent.c LOCAL_CFLAGS := \ @@ -169,11 +179,9 @@ LOCAL_CFLAGS := \ -D_XOPEN_SOURCE \ -D_GNU_SOURCE -LOCAL_C_INCLUDES += external/openssl/include - LOCAL_MODULE := adb -LOCAL_STATIC_LIBRARIES := libzipfile libunz libcutils liblog +LOCAL_STATIC_LIBRARIES := libzipfile libz libcutils liblog LOCAL_SHARED_LIBRARIES := libcrypto @@ -41,8 +41,6 @@ #include <sys/prctl.h> #include <getopt.h> #include <selinux/selinux.h> -#else -#include "usb_vendors.h" #endif #if ADB_TRACE @@ -1320,7 +1318,6 @@ int adb_main(int is_daemon, int server_port) #ifdef WORKAROUND_BUG6558362 if(is_daemon) adb_set_affinity(); #endif - usb_vendors_init(); usb_init(); local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT); adb_auth_init(); @@ -1351,14 +1348,13 @@ int adb_main(int is_daemon, int server_port) ** AID_LOG to read system logs (adb logcat) ** AID_INPUT to diagnose input issues (getevent) ** AID_INET to diagnose network issues (netcfg, ping) - ** AID_GRAPHICS to access the frame buffer ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump) ** AID_SDCARD_R to allow reading from the SD card ** AID_SDCARD_RW to allow writing to the SD card ** AID_NET_BW_STATS to read out qtaguid statistics */ - gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS, - AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW, + gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_NET_BT, + AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW, AID_NET_BW_STATS }; if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) { exit(1); @@ -328,7 +328,10 @@ int handle_forward_request(const char* service, transport_type ttype, char* seri #if !ADB_HOST void framebuffer_service(int fd, void *cookie); +// Allow enable-verity to write to system and vendor block devices +int make_system_and_vendor_block_devices_writable(); void remount_service(int fd, void *cookie); +void set_verity_enabled_state_service(int fd, void* cookie); #endif /* packet allocator */ @@ -338,6 +341,9 @@ void put_apacket(apacket *p); int check_header(apacket *p); int check_data(apacket *p); +// Define it if you want to dump packets. +#define DEBUG_PACKETS 0 + #if !DEBUG_PACKETS #define print_packet(tag,p) do {} while (0) #endif @@ -375,7 +381,6 @@ void usb_kick(usb_handle *h); int is_adb_interface(int vid, int pid, int usb_class, int usb_subclass, int usb_protocol); #endif -unsigned host_to_le32(unsigned n); int adb_commandline(int argc, char **argv); int connection_state(atransport *t); diff --git a/adb/adb_auth.h b/adb/adb_auth.h index b24c674..54dd537 100644 --- a/adb/adb_auth.h +++ b/adb/adb_auth.h @@ -18,6 +18,7 @@ #define __ADB_AUTH_H void adb_auth_init(void); +int adb_auth_keygen(const char* filename); void adb_auth_verified(atransport *t); void send_auth_request(atransport *t); diff --git a/adb/adb_auth_host.c b/adb/adb_auth_host.c index c72fe42..a859199 100644 --- a/adb/adb_auth_host.c +++ b/adb/adb_auth_host.c @@ -15,9 +15,12 @@ */ #include <stdio.h> +#include <stdlib.h> #ifdef _WIN32 -# define WIN32_LEAN_AND_MEAN +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif # include "windows.h" # include "shlobj.h" #else @@ -114,18 +117,34 @@ out: static void get_user_info(char *buf, size_t len) { char hostname[1024], username[1024]; - int ret; + int ret = -1; + + if (getenv("HOSTNAME") != NULL) { + strncpy(hostname, getenv("HOSTNAME"), sizeof(hostname)); + hostname[sizeof(hostname)-1] = '\0'; + ret = 0; + } #ifndef _WIN32 - ret = gethostname(hostname, sizeof(hostname)); if (ret < 0) + ret = gethostname(hostname, sizeof(hostname)); #endif + if (ret < 0) strcpy(hostname, "unknown"); + ret = -1; + + if (getenv("LOGNAME") != NULL) { + strncpy(username, getenv("LOGNAME"), sizeof(username)); + username[sizeof(username)-1] = '\0'; + ret = 0; + } + #if !defined _WIN32 && !defined ADB_HOST_ON_TARGET - ret = getlogin_r(username, sizeof(username)); if (ret < 0) + ret = getlogin_r(username, sizeof(username)); #endif + if (ret < 0) strcpy(username, "unknown"); ret = snprintf(buf, len, " %s@%s", username, hostname); @@ -436,6 +455,11 @@ int adb_auth_get_userkey(unsigned char *data, size_t len) return ret + 1; } +int adb_auth_keygen(const char* filename) { + adb_trace_mask |= (1 << TRACE_AUTH); + return (generate_key(filename) == 0); +} + void adb_auth_init(void) { int ret; diff --git a/adb/adb_client.c b/adb/adb_client.c index eb1720d..ac5e15a 100644 --- a/adb/adb_client.c +++ b/adb/adb_client.c @@ -279,7 +279,7 @@ int adb_connect(const char *service) fd = _adb_connect(service); if(fd == -1) { - D("_adb_connect error: %s\n", __adb_error); + D("_adb_connect error: %s", __adb_error); } else if(fd == -2) { fprintf(stderr,"** daemon still not running\n"); } diff --git a/adb/adb_trace.h b/adb/adb_trace.h index 8a5d9f8..b8a2f4c 100644 --- a/adb/adb_trace.h +++ b/adb/adb_trace.h @@ -73,8 +73,9 @@ void adb_trace_init(void); if (ADB_TRACING) { \ int save_errno = errno; \ adb_mutex_lock(&D_lock); \ - fprintf(stderr, "%s::%s():", \ - __FILE__, __FUNCTION__); \ + fprintf(stderr, "%16s: %5d:%5lu | ", \ + __FUNCTION__, \ + getpid(), adb_thread_id()); \ errno = save_errno; \ fprintf(stderr, __VA_ARGS__ ); \ fflush(stderr); \ @@ -96,15 +97,16 @@ void adb_trace_init(void); } while (0) # define DD(...) \ do { \ - int save_errno = errno; \ - adb_mutex_lock(&D_lock); \ - fprintf(stderr, "%s::%s():", \ - __FILE__, __FUNCTION__); \ - errno = save_errno; \ - fprintf(stderr, __VA_ARGS__ ); \ - fflush(stderr); \ - adb_mutex_unlock(&D_lock); \ - errno = save_errno; \ + int save_errno = errno; \ + adb_mutex_lock(&D_lock); \ + fprintf(stderr, "%16s: %5d:%5lu | ", \ + __FUNCTION__, \ + getpid(), adb_thread_id()); \ + errno = save_errno; \ + fprintf(stderr, __VA_ARGS__ ); \ + fflush(stderr); \ + adb_mutex_unlock(&D_lock); \ + errno = save_errno; \ } while (0) #else # define D(...) \ diff --git a/adb/commandline.c b/adb/commandline.c index eea882d..f345787 100644 --- a/adb/commandline.c +++ b/adb/commandline.c @@ -29,13 +29,14 @@ #include "sysdeps.h" -#ifdef HAVE_TERMIO_H +#if !defined(_WIN32) #include <termios.h> #endif #define TRACE_TAG TRACE_ADB #include "adb.h" #include "adb_client.h" +#include "adb_auth.h" #include "file_sync_service.h" static int do_cmd(transport_type ttype, char* serial, char *cmd, ...); @@ -189,6 +190,11 @@ void help() "\n" " adb restore <file> - restore device contents from the <file> backup archive\n" "\n" + " adb disable-verity - disable dm-verity checking on USERDEBUG builds\n" + " adb enable-verity - re-enable dm-verity checking on USERDEBUG builds\n" + " adb keygen <file> - generate adb public/private key. The private key is stored in <file>,\n" + " and the public key is stored in <file>.pub. Any existing files\n" + " are overwritten.\n" " adb help - show this help message\n" " adb version - show version num\n" "\n" @@ -205,8 +211,7 @@ void help() " adb reboot-bootloader - reboots the device into the bootloader\n" " adb root - restarts the adbd daemon with root permissions\n" " adb usb - restarts the adbd daemon listening on USB\n" - " adb tcpip <port> - restarts the adbd daemon listening on TCP on the specified port" - "\n" + " adb tcpip <port> - restarts the adbd daemon listening on TCP on the specified port\n" "networking:\n" " adb ppp <tty> [parameters] - Run PPP over USB.\n" " Note: you should not automatically start a PPP connection.\n" @@ -235,7 +240,18 @@ int usage() return 1; } -#ifdef HAVE_TERMIO_H +#if defined(_WIN32) + +// Windows does not have <termio.h>. +static void stdin_raw_init(int fd) { + +} + +static void stdin_raw_restore(int fd) { + +} + +#else static struct termios tio_save; static void stdin_raw_init(int fd) @@ -309,11 +325,11 @@ static void copy_to_file(int inFd, int outFd) { long total = 0; D("copy_to_file(%d -> %d)\n", inFd, outFd); -#ifdef HAVE_TERMIO_H + if (inFd == STDIN_FILENO) { stdin_raw_init(STDIN_FILENO); } -#endif + for (;;) { if (inFd == STDIN_FILENO) { len = unix_read(inFd, buf, BUFSIZE); @@ -340,11 +356,11 @@ static void copy_to_file(int inFd, int outFd) { } total += len; } -#ifdef HAVE_TERMIO_H + if (inFd == STDIN_FILENO) { stdin_raw_restore(STDIN_FILENO); } -#endif + D("copy_to_file() finished after %lu bytes\n", total); free(buf); } @@ -385,9 +401,7 @@ static void *stdin_read_thread(void *x) case '.': if(state == 2) { fprintf(stderr,"\n* disconnect *\n"); -#ifdef HAVE_TERMIO_H stdin_raw_restore(fdi); -#endif exit(0); } default: @@ -419,14 +433,10 @@ int interactive_shell(void) fds[0] = fd; fds[1] = fdi; -#ifdef HAVE_TERMIO_H stdin_raw_init(fdi); -#endif adb_thread_create(&thr, stdin_read_thread, fds); read_and_dump(fd); -#ifdef HAVE_TERMIO_H stdin_raw_restore(fdi); -#endif return 0; } @@ -1158,17 +1168,17 @@ int adb_commandline(int argc, char **argv) } /* modifiers and flags */ - while(argc > 0) { - if(!strcmp(argv[0],"server")) { + while (argc > 0) { + if (!strcmp(argv[0],"server")) { is_server = 1; - } else if(!strcmp(argv[0],"nodaemon")) { + } else if (!strcmp(argv[0],"nodaemon")) { no_daemon = 1; } else if (!strcmp(argv[0], "fork-server")) { /* this is a special flag used only when the ADB client launches the ADB Server */ is_daemon = 1; - } else if(!strcmp(argv[0],"persist")) { + } else if (!strcmp(argv[0],"persist")) { persist = 1; - } else if(!strncmp(argv[0], "-p", 2)) { + } else if (!strncmp(argv[0], "-p", 2)) { const char *product = NULL; if (argv[0][2] == '\0') { if (argc < 2) return usage(); @@ -1188,7 +1198,7 @@ int adb_commandline(int argc, char **argv) if (isdigit(argv[0][2])) { serial = argv[0] + 2; } else { - if(argc < 2 || argv[0][2] != '\0') return usage(); + if (argc < 2 || argv[0][2] != '\0') return usage(); serial = argv[1]; argc--; argv++; @@ -1199,7 +1209,7 @@ int adb_commandline(int argc, char **argv) ttype = kTransportLocal; } else if (!strcmp(argv[0],"-a")) { gListenAll = 1; - } else if(!strncmp(argv[0], "-H", 2)) { + } else if (!strncmp(argv[0], "-H", 2)) { const char *hostname = NULL; if (argv[0][2] == '\0') { if (argc < 2) return usage(); @@ -1211,7 +1221,7 @@ int adb_commandline(int argc, char **argv) } adb_set_tcp_name(hostname); - } else if(!strncmp(argv[0], "-P", 2)) { + } else if (!strncmp(argv[0], "-P", 2)) { if (argv[0][2] == '\0') { if (argc < 2) return usage(); server_port_str = argv[1]; @@ -1250,20 +1260,51 @@ int adb_commandline(int argc, char **argv) } else { r = launch_server(server_port); } - if(r) { + if (r) { fprintf(stderr,"* could not start server *\n"); } return r; } -top: - if(argc == 0) { + if (argc == 0) { return usage(); } - /* adb_connect() commands */ + /* handle wait-for-* prefix */ + if (!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) { + char* service = argv[0]; + if (!strncmp(service, "wait-for-device", strlen("wait-for-device"))) { + if (ttype == kTransportUsb) { + service = "wait-for-usb"; + } else if (ttype == kTransportLocal) { + service = "wait-for-local"; + } else { + service = "wait-for-any"; + } + } + + format_host_command(buf, sizeof buf, service, ttype, serial); + + if (adb_command(buf)) { + D("failure: %s *\n",adb_error()); + fprintf(stderr,"error: %s\n", adb_error()); + return 1; + } + + /* Allow a command to be run after wait-for-device, + * e.g. 'adb wait-for-device shell'. + */ + if (argc == 1) { + return 0; + } - if(!strcmp(argv[0], "devices")) { + /* Fall through */ + argc--; + argv++; + } + + /* adb_connect() commands */ + if (!strcmp(argv[0], "devices")) { char *tmp; char *listopt; if (argc < 2) @@ -1276,7 +1317,7 @@ top: } snprintf(buf, sizeof buf, "host:%s%s", argv[0], listopt); tmp = adb_query(buf); - if(tmp) { + if (tmp) { printf("List of devices attached \n"); printf("%s\n", tmp); return 0; @@ -1284,8 +1325,7 @@ top: return 1; } } - - if(!strcmp(argv[0], "connect")) { + else if (!strcmp(argv[0], "connect")) { char *tmp; if (argc != 2) { fprintf(stderr, "Usage: adb connect <host>[:<port>]\n"); @@ -1293,15 +1333,14 @@ top: } snprintf(buf, sizeof buf, "host:connect:%s", argv[1]); tmp = adb_query(buf); - if(tmp) { + if (tmp) { printf("%s\n", tmp); return 0; } else { return 1; } } - - if(!strcmp(argv[0], "disconnect")) { + else if (!strcmp(argv[0], "disconnect")) { char *tmp; if (argc > 2) { fprintf(stderr, "Usage: adb disconnect [<host>[:<port>]]\n"); @@ -1313,19 +1352,17 @@ top: snprintf(buf, sizeof buf, "host:disconnect:"); } tmp = adb_query(buf); - if(tmp) { + if (tmp) { printf("%s\n", tmp); return 0; } else { return 1; } } - - if (!strcmp(argv[0], "emu")) { + else if (!strcmp(argv[0], "emu")) { return adb_send_emulator_command(argc, argv); } - - if(!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) { + else if (!strcmp(argv[0], "shell") || !strcmp(argv[0], "hell")) { int r; int fd; @@ -1336,7 +1373,7 @@ top: fflush(stdout); } - if(argc < 2) { + if (argc < 2) { D("starting interactive shell\n"); r = interactive_shell(); if (h) { @@ -1359,7 +1396,7 @@ top: for(;;) { D("interactive shell loop. buff=%s\n", buf); fd = adb_connect(buf); - if(fd >= 0) { + if (fd >= 0) { D("about to read_and_dump(fd=%d)\n", fd); read_and_dump(fd); D("read_and_dump() done.\n"); @@ -1370,7 +1407,7 @@ top: r = -1; } - if(persist) { + if (persist) { fprintf(stderr,"\n- waiting for device -\n"); adb_sleep_ms(1000); do_cmd(ttype, serial, "wait-for-device", 0); @@ -1384,8 +1421,7 @@ top: } } } - - if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) { + else if (!strcmp(argv[0], "exec-in") || !strcmp(argv[0], "exec-out")) { int exec_in = !strcmp(argv[0], "exec-in"); int fd; @@ -1414,30 +1450,31 @@ top: adb_close(fd); return 0; } - - if(!strcmp(argv[0], "kill-server")) { + else if (!strcmp(argv[0], "kill-server")) { int fd; fd = _adb_connect("host:kill"); - if(fd == -1) { + if (fd == -1) { fprintf(stderr,"* server not running *\n"); return 1; } return 0; } - - if(!strcmp(argv[0], "sideload")) { - if(argc != 2) return usage(); + else if (!strcmp(argv[0], "sideload")) { + if (argc != 2) return usage(); if (adb_sideload_host(argv[1])) { return 1; } else { return 0; } } - - if(!strcmp(argv[0], "remount") || !strcmp(argv[0], "reboot") - || !strcmp(argv[0], "reboot-bootloader") - || !strcmp(argv[0], "tcpip") || !strcmp(argv[0], "usb") - || !strcmp(argv[0], "root")) { + else if (!strcmp(argv[0], "remount") || + !strcmp(argv[0], "reboot") || + !strcmp(argv[0], "reboot-bootloader") || + !strcmp(argv[0], "tcpip") || + !strcmp(argv[0], "usb") || + !strcmp(argv[0], "root") || + !strcmp(argv[0], "disable-verity") || + !strcmp(argv[0], "enable-verity")) { char command[100]; if (!strcmp(argv[0], "reboot-bootloader")) snprintf(command, sizeof(command), "reboot:bootloader"); @@ -1446,7 +1483,7 @@ top: else snprintf(command, sizeof(command), "%s:", argv[0]); int fd = adb_connect(command); - if(fd >= 0) { + if (fd >= 0) { read_and_dump(fd); adb_close(fd); return 0; @@ -1454,49 +1491,13 @@ top: fprintf(stderr,"error: %s\n", adb_error()); return 1; } - - if(!strcmp(argv[0], "bugreport")) { + else if (!strcmp(argv[0], "bugreport")) { if (argc != 1) return usage(); do_cmd(ttype, serial, "shell", "bugreport", 0); return 0; } - /* adb_command() wrapper commands */ - - if(!strncmp(argv[0], "wait-for-", strlen("wait-for-"))) { - char* service = argv[0]; - if (!strncmp(service, "wait-for-device", strlen("wait-for-device"))) { - if (ttype == kTransportUsb) { - service = "wait-for-usb"; - } else if (ttype == kTransportLocal) { - service = "wait-for-local"; - } else { - service = "wait-for-any"; - } - } - - format_host_command(buf, sizeof buf, service, ttype, serial); - - if (adb_command(buf)) { - D("failure: %s *\n",adb_error()); - fprintf(stderr,"error: %s\n", adb_error()); - return 1; - } - - /* Allow a command to be run after wait-for-device, - * e.g. 'adb wait-for-device shell'. - */ - if(argc > 1) { - argc--; - argv++; - goto top; - } - return 0; - } - - if(!strcmp(argv[0], "forward") || - !strcmp(argv[0], "reverse")) - { + else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) { char host_prefix[64]; char reverse = (char) !strcmp(argv[0], "reverse"); char remove = 0; @@ -1581,21 +1582,18 @@ top: snprintf(buf, sizeof buf, "%s:%s:%s;%s", host_prefix, command, argv[1], argv[2]); } - if(adb_command(buf)) { + if (adb_command(buf)) { fprintf(stderr,"error: %s\n", adb_error()); return 1; } return 0; } - /* do_sync_*() commands */ - - if(!strcmp(argv[0], "ls")) { - if(argc != 2) return usage(); + else if (!strcmp(argv[0], "ls")) { + if (argc != 2) return usage(); return do_sync_ls(argv[1]); } - - if(!strcmp(argv[0], "push")) { + else if (!strcmp(argv[0], "push")) { int show_progress = 0; int copy_attrs = 0; // unused const char* lpath = NULL, *rpath = NULL; @@ -1608,8 +1606,7 @@ top: return usage(); } - - if(!strcmp(argv[0], "pull")) { + else if (!strcmp(argv[0], "pull")) { int show_progress = 0; int copy_attrs = 0; const char* rpath = NULL, *lpath = "."; @@ -1622,28 +1619,24 @@ top: return usage(); } - - if (!strcmp(argv[0], "install")) { + else if (!strcmp(argv[0], "install")) { if (argc < 2) return usage(); return install_app(ttype, serial, argc, argv); } - - if (!strcmp(argv[0], "install-multiple")) { + else if (!strcmp(argv[0], "install-multiple")) { if (argc < 2) return usage(); return install_multiple_app(ttype, serial, argc, argv); } - - if (!strcmp(argv[0], "uninstall")) { + else if (!strcmp(argv[0], "uninstall")) { if (argc < 2) return usage(); return uninstall_app(ttype, serial, argc, argv); } - - if(!strcmp(argv[0], "sync")) { + else if (!strcmp(argv[0], "sync")) { char *srcarg, *android_srcpath, *data_srcpath, *vendor_srcpath; int listonly = 0; int ret; - if(argc < 2) { + if (argc < 2) { /* No local path was specified. */ srcarg = NULL; } else if (argc >= 2 && strcmp(argv[1], "-l") == 0) { @@ -1653,20 +1646,20 @@ top: } else { srcarg = NULL; } - } else if(argc == 2) { + } else if (argc == 2) { /* A local path or "android"/"data" arg was specified. */ srcarg = argv[1]; } else { return usage(); } ret = find_sync_dirs(srcarg, &android_srcpath, &data_srcpath, &vendor_srcpath); - if(ret != 0) return usage(); + if (ret != 0) return usage(); - if(android_srcpath != NULL) + if (android_srcpath != NULL) ret = do_sync_sync(android_srcpath, "/system", listonly); - if(ret == 0 && vendor_srcpath != NULL) + if (ret == 0 && vendor_srcpath != NULL) ret = do_sync_sync(vendor_srcpath, "/vendor", listonly); - if(ret == 0 && data_srcpath != NULL) + if (ret == 0 && data_srcpath != NULL) ret = do_sync_sync(data_srcpath, "/data", listonly); free(android_srcpath); @@ -1674,10 +1667,8 @@ top: free(data_srcpath); return ret; } - /* passthrough commands */ - - if(!strcmp(argv[0],"get-state") || + else if (!strcmp(argv[0],"get-state") || !strcmp(argv[0],"get-serialno") || !strcmp(argv[0],"get-devpath")) { @@ -1685,42 +1676,38 @@ top: format_host_command(buf, sizeof buf, argv[0], ttype, serial); tmp = adb_query(buf); - if(tmp) { + if (tmp) { printf("%s\n", tmp); return 0; } else { return 1; } } - /* other commands */ - - if(!strcmp(argv[0],"status-window")) { + else if (!strcmp(argv[0],"status-window")) { status_window(ttype, serial); return 0; } - - if(!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) { + else if (!strcmp(argv[0],"logcat") || !strcmp(argv[0],"lolcat") || !strcmp(argv[0],"longcat")) { return logcat(ttype, serial, argc, argv); } - - if(!strcmp(argv[0],"ppp")) { + else if (!strcmp(argv[0],"ppp")) { return ppp(argc, argv); } - - if (!strcmp(argv[0], "start-server")) { + else if (!strcmp(argv[0], "start-server")) { return adb_connect("host:start-server"); } - - if (!strcmp(argv[0], "backup")) { + else if (!strcmp(argv[0], "backup")) { return backup(argc, argv); } - - if (!strcmp(argv[0], "restore")) { + else if (!strcmp(argv[0], "restore")) { return restore(argc, argv); } - - if (!strcmp(argv[0], "jdwp")) { + else if (!strcmp(argv[0], "keygen")) { + if (argc < 2) return usage(); + return adb_auth_keygen(argv[1]); + } + else if (!strcmp(argv[0], "jdwp")) { int fd = adb_connect("jdwp"); if (fd >= 0) { read_and_dump(fd); @@ -1731,14 +1718,12 @@ top: return -1; } } - /* "adb /?" is a common idiom under Windows */ - if(!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) { + else if (!strcmp(argv[0], "help") || !strcmp(argv[0], "/?")) { help(); return 0; } - - if(!strcmp(argv[0], "version")) { + else if (!strcmp(argv[0], "version")) { version(stdout); return 0; } diff --git a/adb/fdevent.c b/adb/fdevent.c index 43e600c..f5ecd14 100644 --- a/adb/fdevent.c +++ b/adb/fdevent.c @@ -661,6 +661,8 @@ void fdevent_subproc_setup() if(adb_socketpair(s)) { FATAL("cannot create shell-exit socket-pair\n"); } + D("socketpair: (%d,%d)", s[0], s[1]); + SHELL_EXIT_NOTIFY_FD = s[0]; fdevent *fde; fde = fdevent_create(s[1], fdevent_subproc_event_func, NULL); diff --git a/adb/file_sync_service.h b/adb/file_sync_service.h index 5dd2e80..c3c8574 100644 --- a/adb/file_sync_service.h +++ b/adb/file_sync_service.h @@ -17,22 +17,10 @@ #ifndef _FILE_SYNC_SERVICE_H_ #define _FILE_SYNC_SERVICE_H_ -#ifdef HAVE_BIG_ENDIAN -static inline unsigned __swap_uint32(unsigned x) -{ - return (((x) & 0xFF000000) >> 24) - | (((x) & 0x00FF0000) >> 8) - | (((x) & 0x0000FF00) << 8) - | (((x) & 0x000000FF) << 24); -} -#define htoll(x) __swap_uint32(x) -#define ltohl(x) __swap_uint32(x) -#define MKID(a,b,c,d) ((d) | ((c) << 8) | ((b) << 16) | ((a) << 24)) -#else #define htoll(x) (x) #define ltohl(x) (x) + #define MKID(a,b,c,d) ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24)) -#endif #define ID_STAT MKID('S','T','A','T') #define ID_LIST MKID('L','I','S','T') diff --git a/adb/framebuffer_service.c b/adb/framebuffer_service.c index 8cbe840..61578aa 100644 --- a/adb/framebuffer_service.c +++ b/adb/framebuffer_service.c @@ -76,6 +76,7 @@ void framebuffer_service(int fd, void *cookie) exit(1); } + close(fds[1]); fd_screencap = fds[0]; /* read w, h & format */ @@ -173,10 +174,9 @@ void framebuffer_service(int fd, void *cookie) } done: - TEMP_FAILURE_RETRY(waitpid(pid, NULL, 0)); - close(fds[0]); - close(fds[1]); + + TEMP_FAILURE_RETRY(waitpid(pid, NULL, 0)); pipefail: close(fd); } diff --git a/adb/get_my_path_darwin.c b/adb/get_my_path_darwin.c index 5b95d15..ff1396c 100644 --- a/adb/get_my_path_darwin.c +++ b/adb/get_my_path_darwin.c @@ -19,12 +19,12 @@ void get_my_path(char *s, size_t maxLen) { - ProcessSerialNumber psn; - GetCurrentProcess(&psn); - CFDictionaryRef dict; - dict = ProcessInformationCopyDictionary(&psn, 0xffffffff); - CFStringRef value = (CFStringRef)CFDictionaryGetValue(dict, - CFSTR("CFBundleExecutable")); - CFStringGetCString(value, s, maxLen, kCFStringEncodingUTF8); + CFBundleRef mainBundle = CFBundleGetMainBundle(); + CFURLRef executableURL = CFBundleCopyExecutableURL(mainBundle); + CFStringRef executablePathString = CFURLCopyFileSystemPath(executableURL, kCFURLPOSIXPathStyle); + CFRelease(executableURL); + + CFStringGetFileSystemRepresentation(executablePathString, s, maxLen); + CFRelease(executablePathString); } diff --git a/adb/jdwp_service.c b/adb/jdwp_service.c index cd62b55..3074e42 100644 --- a/adb/jdwp_service.c +++ b/adb/jdwp_service.c @@ -415,6 +415,7 @@ FoundIt: __FUNCTION__, strerror(errno)); return -1; } + D("socketpair: (%d,%d)", fds[0], fds[1]); proc->out_fds[ proc->out_count ] = fds[1]; if (++proc->out_count == 1) diff --git a/adb/remount_service.c b/adb/remount_service.c index 72d15a1..05d3169 100644 --- a/adb/remount_service.c +++ b/adb/remount_service.c @@ -14,6 +14,8 @@ * limitations under the License. */ +#include "sysdeps.h" + #include <errno.h> #include <fcntl.h> #include <stdio.h> @@ -22,7 +24,7 @@ #include <sys/mount.h> #include <unistd.h> -#include "sysdeps.h" +#include "cutils/properties.h" #define TRACE_TAG TRACE_ADB #include "adb.h" @@ -77,29 +79,57 @@ static int hasVendorPartition() return false; } +static int make_block_device_writable(const char* dir) +{ + char *dev = 0; + int fd = -1; + int OFF = 0; + int rc = -1; + + dev = find_mount(dir); + if (!dev) + goto errout; + + fd = unix_open(dev, O_RDONLY | O_CLOEXEC); + if (fd < 0) + goto errout; + + if (ioctl(fd, BLKROSET, &OFF)) { + goto errout; + } + + rc = 0; + +errout: + if (fd >= 0) { + adb_close(fd); + } + + if (dev) { + free(dev); + } + return rc; +} + /* Init mounts /system as read only, remount to enable writes. */ static int remount(const char* dir, int* dir_ro) { char *dev; - int fd; int OFF = 0; if (dir_ro == 0) { return 0; } + if (make_block_device_writable(dir)) { + return -1; + } + dev = find_mount(dir); if (!dev) return -1; - fd = unix_open(dev, O_RDONLY | O_CLOEXEC); - if (fd < 0) - return -1; - - ioctl(fd, BLKROSET, &OFF); - adb_close(fd); - *dir_ro = mount(dev, dir, "none", MS_REMOUNT, NULL); free(dev); @@ -112,9 +142,61 @@ static void write_string(int fd, const char* str) writex(fd, str, strlen(str)); } +int make_system_and_vendor_block_devices_writable(int fd) +{ + char buffer[200]; + if (make_block_device_writable("/system")) { + snprintf(buffer, sizeof(buffer), + "Failed to make system block device writable %s\n", + strerror(errno)); + write_string(fd, buffer); + return -1; + } + + if (hasVendorPartition() && make_block_device_writable("/vendor")) { + snprintf(buffer, sizeof(buffer), + "Failed to make vendor block device writable: %s\n", + strerror(errno)); + write_string(fd, buffer); + return -1; + } + + return 0; +} + void remount_service(int fd, void *cookie) { char buffer[200]; + char prop_buf[PROPERTY_VALUE_MAX]; + + bool system_verified = false, vendor_verified = false; + property_get("partition.system.verified", prop_buf, "0"); + if (!strcmp(prop_buf, "1")) { + system_verified = true; + } + + property_get("partition.vendor.verified", prop_buf, "0"); + if (!strcmp(prop_buf, "1")) { + vendor_verified = true; + } + + if (system_verified || vendor_verified) { + // Allow remount but warn of likely bad effects + bool both = system_verified && vendor_verified; + snprintf(buffer, sizeof(buffer), + "dm_verity is enabled on the %s%s%s partition%s.\n", + system_verified ? "system" : "", + both ? " and " : "", + vendor_verified ? "vendor" : "", + both ? "s" : ""); + write_string(fd, buffer); + snprintf(buffer, sizeof(buffer), + "Use \"adb disable-verity\" to disable verity.\n" + "If you do not, remount may succeed, however, you will still " + "not be able to write to these volumes.\n"); + write_string(fd, buffer); + } + if (remount("/system", &system_ro)) { snprintf(buffer, sizeof(buffer), "remount of system failed: %s\n",strerror(errno)); write_string(fd, buffer); @@ -135,4 +217,3 @@ void remount_service(int fd, void *cookie) adb_close(fd); } - diff --git a/adb/services.c b/adb/services.c index bcfc163..d5a4642 100644 --- a/adb/services.c +++ b/adb/services.c @@ -164,6 +164,7 @@ static int create_service_thread(void (*func)(int, void *), void *cookie) printf("cannot create service socket pair\n"); return -1; } + D("socketpair: (%d,%d)", s[0], s[1]); sti = malloc(sizeof(stinfo)); if(sti == 0) fatal("cannot allocate stinfo"); @@ -264,10 +265,11 @@ static int create_subproc_raw(const char *cmd, const char *arg0, const char *arg // 0 is parent socket, 1 is child socket int sv[2]; - if (unix_socketpair(AF_UNIX, SOCK_STREAM, 0, sv) < 0) { + if (adb_socketpair(sv) < 0) { printf("[ cannot create socket pair - %s ]\n", strerror(errno)); return -1; } + D("socketpair: (%d,%d)", sv[0], sv[1]); *pid = fork(); if (*pid < 0) { @@ -469,6 +471,10 @@ int service_to_fd(const char *name) free(cookie); } } + } else if(!strncmp(name, "disable-verity:", 15)) { + ret = create_service_thread(set_verity_enabled_state_service, (void*)0); + } else if(!strncmp(name, "enable-verity:", 15)) { + ret = create_service_thread(set_verity_enabled_state_service, (void*)1); #endif } if (ret >= 0) { diff --git a/adb/set_verity_enable_state_service.c b/adb/set_verity_enable_state_service.c new file mode 100644 index 0000000..1e22149 --- /dev/null +++ b/adb/set_verity_enable_state_service.c @@ -0,0 +1,217 @@ +/* + * Copyright (C) 2014 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 "sysdeps.h" + +#define TRACE_TAG TRACE_ADB +#include "adb.h" + +#include <stdio.h> +#include <stdarg.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <inttypes.h> + +#include "cutils/properties.h" +#include "ext4_sb.h" +#include <fs_mgr.h> + +#define FSTAB_PREFIX "/fstab." +struct fstab *fstab; + +__attribute__((__format__(printf, 2, 3))) __nonnull((2)) +static void write_console(int fd, const char* format, ...) +{ + char buffer[256]; + va_list args; + va_start (args, format); + vsnprintf (buffer, sizeof(buffer), format, args); + va_end (args); + + adb_write(fd, buffer, strnlen(buffer, sizeof(buffer))); +} + +static int get_target_device_size(int fd, const char *blk_device, + uint64_t *device_size) +{ + int data_device; + struct ext4_super_block sb; + struct fs_info info; + + info.len = 0; /* Only len is set to 0 to ask the device for real size. */ + + data_device = adb_open(blk_device, O_RDONLY | O_CLOEXEC); + if (data_device < 0) { + write_console(fd, "Error opening block device (%s)\n", strerror(errno)); + return -1; + } + + if (lseek64(data_device, 1024, SEEK_SET) < 0) { + write_console(fd, "Error seeking to superblock\n"); + adb_close(data_device); + return -1; + } + + if (adb_read(data_device, &sb, sizeof(sb)) != sizeof(sb)) { + write_console(fd, "Error reading superblock\n"); + adb_close(data_device); + return -1; + } + + ext4_parse_sb(&sb, &info); + *device_size = info.len; + + adb_close(data_device); + return 0; +} + +/* Turn verity on/off */ +static int set_verity_enabled_state(int fd, const char *block_device, + const char* mount_point, bool enable) +{ + uint32_t magic_number; + const uint32_t new_magic = enable ? VERITY_METADATA_MAGIC_NUMBER + : VERITY_METADATA_MAGIC_DISABLE; + uint64_t device_length; + int device; + int retval = -1; + + device = adb_open(block_device, O_RDWR | O_CLOEXEC); + if (device == -1) { + write_console(fd, "Could not open block device %s (%s).\n", + block_device, strerror(errno)); + write_console(fd, "Maybe run adb remount?\n"); + goto errout; + } + + // find the start of the verity metadata + if (get_target_device_size(fd, (char*)block_device, &device_length) < 0) { + write_console(fd, "Could not get target device size.\n"); + goto errout; + } + + if (lseek64(device, device_length, SEEK_SET) < 0) { + write_console(fd, + "Could not seek to start of verity metadata block.\n"); + goto errout; + } + + // check the magic number + if (adb_read(device, &magic_number, sizeof(magic_number)) + != sizeof(magic_number)) { + write_console(fd, "Couldn't read magic number!\n"); + goto errout; + } + + if (!enable && magic_number == VERITY_METADATA_MAGIC_DISABLE) { + write_console(fd, "Verity already disabled on %s\n", mount_point); + goto errout; + } + + if (enable && magic_number == VERITY_METADATA_MAGIC_NUMBER) { + write_console(fd, "Verity already enabled on %s\n", mount_point); + goto errout; + } + + if (magic_number != VERITY_METADATA_MAGIC_NUMBER + && magic_number != VERITY_METADATA_MAGIC_DISABLE) { + write_console(fd, + "Couldn't find verity metadata at offset %"PRIu64"!\n", + device_length); + goto errout; + } + + if (lseek64(device, device_length, SEEK_SET) < 0) { + write_console(fd, + "Could not seek to start of verity metadata block.\n"); + goto errout; + } + + if (adb_write(device, &new_magic, sizeof(new_magic)) != sizeof(new_magic)) { + write_console(fd, "Could not set verity %s flag on device %s with error %s\n", + enable ? "enabled" : "disabled", + block_device, + strerror(errno)); + goto errout; + } + + write_console(fd, "Verity %s on %s\n", + enable ? "enabled" : "disabled", + mount_point); + retval = 0; +errout: + if (device != -1) + adb_close(device); + return retval; +} + +void set_verity_enabled_state_service(int fd, void* cookie) +{ + bool enable = (cookie != NULL); +#ifdef ALLOW_ADBD_DISABLE_VERITY + char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)]; + char propbuf[PROPERTY_VALUE_MAX]; + int i; + bool any_changed = false; + + property_get("ro.secure", propbuf, "0"); + if (strcmp(propbuf, "1")) { + write_console(fd, "verity not enabled - ENG build\n"); + goto errout; + } + + property_get("ro.debuggable", propbuf, "0"); + if (strcmp(propbuf, "1")) { + write_console(fd, "verity cannot be disabled/enabled - USER build\n"); + goto errout; + } + + property_get("ro.hardware", propbuf, ""); + snprintf(fstab_filename, sizeof(fstab_filename), FSTAB_PREFIX"%s", propbuf); + + fstab = fs_mgr_read_fstab(fstab_filename); + if (!fstab) { + write_console(fd, "Failed to open %s\nMaybe run adb root?\n", + fstab_filename); + goto errout; + } + + if (enable && make_system_and_vendor_block_devices_writable(fd)) { + goto errout; + } + + /* Loop through entries looking for ones that vold manages */ + for (i = 0; i < fstab->num_entries; i++) { + if(fs_mgr_is_verified(&fstab->recs[i])) { + if (!set_verity_enabled_state(fd, fstab->recs[i].blk_device, + fstab->recs[i].mount_point, enable)) { + any_changed = true; + } + } + } + + if (any_changed) { + write_console(fd, + "Now reboot your device for settings to take effect\n"); + } +#else + write_console(fd, "%s-verity only works for userdebug builds\n", + enable ? "enable" : "disable"); +#endif + +errout: + adb_close(fd); +} diff --git a/adb/sysdeps.h b/adb/sysdeps.h index cc1f839..8d63d14 100644 --- a/adb/sysdeps.h +++ b/adb/sysdeps.h @@ -77,6 +77,11 @@ static __inline__ int adb_thread_create( adb_thread_t *thread, adb_thread_func return 0; } +static __inline__ unsigned long adb_thread_id() +{ + return GetCurrentThreadId(); +} + static __inline__ void close_on_exec(int fd) { /* nothing really */ @@ -516,6 +521,12 @@ static __inline__ char* adb_strtok_r(char *str, const char *delim, char **savep { return strtok_r(str, delim, saveptr); } + +static __inline__ unsigned long adb_thread_id() +{ + return (unsigned long)pthread_self(); +} + #undef strtok_r #define strtok_r ___xxx_strtok_r diff --git a/adb/sysdeps_win32.c b/adb/sysdeps_win32.c index b082c6d..e69ec2b 100644 --- a/adb/sysdeps_win32.c +++ b/adb/sysdeps_win32.c @@ -2,6 +2,7 @@ #include <winsock2.h> #include <windows.h> #include <stdio.h> +#include <stdlib.h> #include <errno.h> #define TRACE_TAG TRACE_SYSDEPS #include "adb.h" diff --git a/adb/transport.c b/adb/transport.c index f35880c..7db6a47 100644 --- a/adb/transport.c +++ b/adb/transport.c @@ -629,7 +629,7 @@ static void transport_registration_func(int _fd, unsigned ev, void *data) fatal_errno("cannot open transport socketpair"); } - D("transport: %s (%d,%d) starting\n", t->serial, s[0], s[1]); + D("transport: %s socketpair: (%d,%d) starting", t->serial, s[0], s[1]); t->transport_socket = s[0]; t->fd = s[1]; @@ -673,6 +673,7 @@ void init_transport_registration(void) if(adb_socketpair(s)){ fatal_errno("cannot open transport registration socketpair"); } + D("socketpair: (%d,%d)", s[0], s[1]); transport_registration_send = s[0]; transport_registration_recv = s[1]; diff --git a/adb/transport_local.c b/adb/transport_local.c index 948cc15..6c4e220 100644 --- a/adb/transport_local.c +++ b/adb/transport_local.c @@ -28,21 +28,6 @@ #define TRACE_TAG TRACE_TRANSPORT #include "adb.h" -#ifdef HAVE_BIG_ENDIAN -#define H4(x) (((x) & 0xFF000000) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | (((x) & 0x000000FF) << 24) -static inline void fix_endians(apacket *p) -{ - p->msg.command = H4(p->msg.command); - p->msg.arg0 = H4(p->msg.arg0); - p->msg.arg1 = H4(p->msg.arg1); - p->msg.data_length = H4(p->msg.data_length); - p->msg.data_check = H4(p->msg.data_check); - p->msg.magic = H4(p->msg.magic); -} -#else -#define fix_endians(p) do {} while (0) -#endif - #if ADB_HOST /* we keep a list of opened transports. The atransport struct knows to which * local transport it is connected. The list is used to detect when we're @@ -62,12 +47,6 @@ static int remote_read(apacket *p, atransport *t) return -1; } - fix_endians(p); - -#if 0 && defined HAVE_BIG_ENDIAN - D("read remote packet: %04x arg0=%0x arg1=%0x data_length=%0x data_check=%0x magic=%0x\n", - p->msg.command, p->msg.arg0, p->msg.arg1, p->msg.data_length, p->msg.data_check, p->msg.magic); -#endif if(check_header(p)) { D("bad header: terminated (data)\n"); return -1; @@ -90,12 +69,6 @@ static int remote_write(apacket *p, atransport *t) { int length = p->msg.data_length; - fix_endians(p); - -#if 0 && defined HAVE_BIG_ENDIAN - D("write remote packet: %04x arg0=%0x arg1=%0x data_length=%0x data_check=%0x magic=%0x\n", - p->msg.command, p->msg.arg0, p->msg.arg1, p->msg.data_length, p->msg.data_check, p->msg.magic); -#endif if(writex(t->sfd, &p->msg, sizeof(amessage) + length)) { D("remote local: write terminated\n"); return -1; diff --git a/adb/transport_usb.c b/adb/transport_usb.c index ee6b637..1138ddd 100644 --- a/adb/transport_usb.c +++ b/adb/transport_usb.c @@ -23,33 +23,6 @@ #define TRACE_TAG TRACE_TRANSPORT #include "adb.h" -#if ADB_HOST -#include "usb_vendors.h" -#endif - -#ifdef HAVE_BIG_ENDIAN -#define H4(x) (((x) & 0xFF000000) >> 24) | (((x) & 0x00FF0000) >> 8) | (((x) & 0x0000FF00) << 8) | (((x) & 0x000000FF) << 24) -static inline void fix_endians(apacket *p) -{ - p->msg.command = H4(p->msg.command); - p->msg.arg0 = H4(p->msg.arg0); - p->msg.arg1 = H4(p->msg.arg1); - p->msg.data_length = H4(p->msg.data_length); - p->msg.data_check = H4(p->msg.data_check); - p->msg.magic = H4(p->msg.magic); -} -unsigned host_to_le32(unsigned n) -{ - return H4(n); -} -#else -#define fix_endians(p) do {} while (0) -unsigned host_to_le32(unsigned n) -{ - return n; -} -#endif - static int remote_read(apacket *p, atransport *t) { if(usb_read(t->usb, &p->msg, sizeof(amessage))){ @@ -57,8 +30,6 @@ static int remote_read(apacket *p, atransport *t) return -1; } - fix_endians(p); - if(check_header(p)) { D("remote usb: check_header failed\n"); return -1; @@ -83,8 +54,6 @@ static int remote_write(apacket *p, atransport *t) { unsigned size = p->msg.data_length; - fix_endians(p); - if(usb_write(t->usb, &p->msg, sizeof(amessage))) { D("remote usb: 1 - write terminated\n"); return -1; @@ -131,18 +100,6 @@ void init_usb_transport(atransport *t, usb_handle *h, int state) #if ADB_HOST int is_adb_interface(int vid, int pid, int usb_class, int usb_subclass, int usb_protocol) { - unsigned i; - for (i = 0; i < vendorIdCount; i++) { - if (vid == vendorIds[i]) { - if (usb_class == ADB_CLASS && usb_subclass == ADB_SUBCLASS && - usb_protocol == ADB_PROTOCOL) { - return 1; - } - - return 0; - } - } - - return 0; + return (usb_class == ADB_CLASS && usb_subclass == ADB_SUBCLASS && usb_protocol == ADB_PROTOCOL); } #endif diff --git a/adb/usb_linux.c b/adb/usb_linux.c index f16bdd0..7d13a5d 100644 --- a/adb/usb_linux.c +++ b/adb/usb_linux.c @@ -237,8 +237,20 @@ static void find_usb_device(const char *base, // looks like ADB... ep1 = (struct usb_endpoint_descriptor *)bufptr; bufptr += USB_DT_ENDPOINT_SIZE; + // For USB 3.0 SuperSpeed devices, skip potential + // USB 3.0 SuperSpeed Endpoint Companion descriptor + if (bufptr+2 <= devdesc + desclength && + bufptr[0] == USB_DT_SS_EP_COMP_SIZE && + bufptr[1] == USB_DT_SS_ENDPOINT_COMP) { + bufptr += USB_DT_SS_EP_COMP_SIZE; + } ep2 = (struct usb_endpoint_descriptor *)bufptr; bufptr += USB_DT_ENDPOINT_SIZE; + if (bufptr+2 <= devdesc + desclength && + bufptr[0] == USB_DT_SS_EP_COMP_SIZE && + bufptr[1] == USB_DT_SS_ENDPOINT_COMP) { + bufptr += USB_DT_SS_EP_COMP_SIZE; + } if (bufptr > devdesc + desclength || ep1->bLength != USB_DT_ENDPOINT_SIZE || diff --git a/adb/usb_linux_client.c b/adb/usb_linux_client.c index 8426e0e..fd566f4 100644 --- a/adb/usb_linux_client.c +++ b/adb/usb_linux_client.c @@ -33,6 +33,7 @@ #define MAX_PACKET_SIZE_FS 64 #define MAX_PACKET_SIZE_HS 512 +#define MAX_PACKET_SIZE_SS 1024 #define cpu_to_le16(x) htole16(x) #define cpu_to_le32(x) htole32(x) @@ -55,71 +56,85 @@ struct usb_handle int bulk_in; /* "in" from the host's perspective => sink for adbd */ }; -static const struct { - struct usb_functionfs_descs_head header; - struct { - struct usb_interface_descriptor intf; - struct usb_endpoint_descriptor_no_audio source; - struct usb_endpoint_descriptor_no_audio sink; - } __attribute__((packed)) fs_descs, hs_descs; -} __attribute__((packed)) descriptors = { - .header = { - .magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC), - .length = cpu_to_le32(sizeof(descriptors)), - .fs_count = 3, - .hs_count = 3, +struct func_desc { + struct usb_interface_descriptor intf; + struct usb_endpoint_descriptor_no_audio source; + struct usb_endpoint_descriptor_no_audio sink; +} __attribute__((packed)); + +struct desc_v1 { + struct usb_functionfs_descs_head_v1 { + __le32 magic; + __le32 length; + __le32 fs_count; + __le32 hs_count; + } __attribute__((packed)) header; + struct func_desc fs_descs, hs_descs; +} __attribute__((packed)); + +struct desc_v2 { + struct usb_functionfs_descs_head_v2 { + __le32 magic; + __le32 length; + __le32 flags; + __le32 fs_count; + __le32 hs_count; + __le32 ss_count; + } __attribute__((packed)) header; + struct func_desc fs_descs, hs_descs; +} __attribute__((packed)); + +struct func_desc fs_descriptors = { + .intf = { + .bLength = sizeof(fs_descriptors.intf), + .bDescriptorType = USB_DT_INTERFACE, + .bInterfaceNumber = 0, + .bNumEndpoints = 2, + .bInterfaceClass = ADB_CLASS, + .bInterfaceSubClass = ADB_SUBCLASS, + .bInterfaceProtocol = ADB_PROTOCOL, + .iInterface = 1, /* first string from the provided table */ + }, + .source = { + .bLength = sizeof(fs_descriptors.source), + .bDescriptorType = USB_DT_ENDPOINT, + .bEndpointAddress = 1 | USB_DIR_OUT, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = MAX_PACKET_SIZE_FS, + }, + .sink = { + .bLength = sizeof(fs_descriptors.sink), + .bDescriptorType = USB_DT_ENDPOINT, + .bEndpointAddress = 2 | USB_DIR_IN, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = MAX_PACKET_SIZE_FS, }, - .fs_descs = { - .intf = { - .bLength = sizeof(descriptors.fs_descs.intf), - .bDescriptorType = USB_DT_INTERFACE, - .bInterfaceNumber = 0, - .bNumEndpoints = 2, - .bInterfaceClass = ADB_CLASS, - .bInterfaceSubClass = ADB_SUBCLASS, - .bInterfaceProtocol = ADB_PROTOCOL, - .iInterface = 1, /* first string from the provided table */ - }, - .source = { - .bLength = sizeof(descriptors.fs_descs.source), - .bDescriptorType = USB_DT_ENDPOINT, - .bEndpointAddress = 1 | USB_DIR_OUT, - .bmAttributes = USB_ENDPOINT_XFER_BULK, - .wMaxPacketSize = MAX_PACKET_SIZE_FS, - }, - .sink = { - .bLength = sizeof(descriptors.fs_descs.sink), - .bDescriptorType = USB_DT_ENDPOINT, - .bEndpointAddress = 2 | USB_DIR_IN, - .bmAttributes = USB_ENDPOINT_XFER_BULK, - .wMaxPacketSize = MAX_PACKET_SIZE_FS, - }, +}; + +struct func_desc hs_descriptors = { + .intf = { + .bLength = sizeof(hs_descriptors.intf), + .bDescriptorType = USB_DT_INTERFACE, + .bInterfaceNumber = 0, + .bNumEndpoints = 2, + .bInterfaceClass = ADB_CLASS, + .bInterfaceSubClass = ADB_SUBCLASS, + .bInterfaceProtocol = ADB_PROTOCOL, + .iInterface = 1, /* first string from the provided table */ + }, + .source = { + .bLength = sizeof(hs_descriptors.source), + .bDescriptorType = USB_DT_ENDPOINT, + .bEndpointAddress = 1 | USB_DIR_OUT, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = MAX_PACKET_SIZE_HS, }, - .hs_descs = { - .intf = { - .bLength = sizeof(descriptors.hs_descs.intf), - .bDescriptorType = USB_DT_INTERFACE, - .bInterfaceNumber = 0, - .bNumEndpoints = 2, - .bInterfaceClass = ADB_CLASS, - .bInterfaceSubClass = ADB_SUBCLASS, - .bInterfaceProtocol = ADB_PROTOCOL, - .iInterface = 1, /* first string from the provided table */ - }, - .source = { - .bLength = sizeof(descriptors.hs_descs.source), - .bDescriptorType = USB_DT_ENDPOINT, - .bEndpointAddress = 1 | USB_DIR_OUT, - .bmAttributes = USB_ENDPOINT_XFER_BULK, - .wMaxPacketSize = MAX_PACKET_SIZE_HS, - }, - .sink = { - .bLength = sizeof(descriptors.hs_descs.sink), - .bDescriptorType = USB_DT_ENDPOINT, - .bEndpointAddress = 2 | USB_DIR_IN, - .bmAttributes = USB_ENDPOINT_XFER_BULK, - .wMaxPacketSize = MAX_PACKET_SIZE_HS, - }, + .sink = { + .bLength = sizeof(hs_descriptors.sink), + .bDescriptorType = USB_DT_ENDPOINT, + .bEndpointAddress = 2 | USB_DIR_IN, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = MAX_PACKET_SIZE_HS, }, }; @@ -263,6 +278,17 @@ static void usb_adb_init() static void init_functionfs(struct usb_handle *h) { ssize_t ret; + struct desc_v1 v1_descriptor; + struct desc_v2 v2_descriptor; + + v2_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2); + v2_descriptor.header.length = cpu_to_le32(sizeof(v2_descriptor)); + v2_descriptor.header.flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC; + v2_descriptor.header.fs_count = 3; + v2_descriptor.header.hs_count = 3; + v2_descriptor.header.ss_count = 0; + v2_descriptor.fs_descs = fs_descriptors; + v2_descriptor.hs_descs = hs_descriptors; if (h->control < 0) { // might have already done this before D("OPENING %s\n", USB_FFS_ADB_EP0); @@ -272,10 +298,20 @@ static void init_functionfs(struct usb_handle *h) goto err; } - ret = adb_write(h->control, &descriptors, sizeof(descriptors)); + ret = adb_write(h->control, &v2_descriptor, sizeof(v2_descriptor)); if (ret < 0) { - D("[ %s: write descriptors failed: errno=%d ]\n", USB_FFS_ADB_EP0, errno); - goto err; + v1_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC); + v1_descriptor.header.length = cpu_to_le32(sizeof(v1_descriptor)); + v1_descriptor.header.fs_count = 3; + v1_descriptor.header.hs_count = 3; + v1_descriptor.fs_descs = fs_descriptors; + v1_descriptor.hs_descs = hs_descriptors; + D("[ %s: Switching to V1_descriptor format errno=%d ]\n", USB_FFS_ADB_EP0, errno); + ret = adb_write(h->control, &v1_descriptor, sizeof(v1_descriptor)); + if (ret < 0) { + D("[ %s: write descriptors failed: errno=%d ]\n", USB_FFS_ADB_EP0, errno); + goto err; + } } ret = adb_write(h->control, &strings, sizeof(strings)); diff --git a/adb/usb_osx.c b/adb/usb_osx.c index ee893f5..ba157f1 100644 --- a/adb/usb_osx.c +++ b/adb/usb_osx.c @@ -28,12 +28,11 @@ #define TRACE_TAG TRACE_USB #include "adb.h" -#include "usb_vendors.h" #define DBG D static IONotificationPortRef notificationPort = 0; -static io_iterator_t* notificationIterators; +static io_iterator_t notificationIterator; struct usb_handle { @@ -61,8 +60,6 @@ InitUSB() { CFMutableDictionaryRef matchingDict; CFRunLoopSourceRef runLoopSource; - SInt32 vendor, if_subclass, if_protocol; - unsigned i; //* To set up asynchronous notifications, create a notification port and //* add its run loop event source to the program's run loop @@ -70,47 +67,33 @@ InitUSB() runLoopSource = IONotificationPortGetRunLoopSource(notificationPort); CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopDefaultMode); - memset(notificationIterators, 0, sizeof(notificationIterators)); + //* Create our matching dictionary to find the Android device's + //* adb interface + //* IOServiceAddMatchingNotification consumes the reference, so we do + //* not need to release this + matchingDict = IOServiceMatching(kIOUSBInterfaceClassName); - //* loop through all supported vendors - for (i = 0; i < vendorIdCount; i++) { - //* Create our matching dictionary to find the Android device's - //* adb interface - //* IOServiceAddMatchingNotification consumes the reference, so we do - //* not need to release this - matchingDict = IOServiceMatching(kIOUSBInterfaceClassName); - - if (!matchingDict) { - DBG("ERR: Couldn't create USB matching dictionary.\n"); - return -1; - } - - //* Match based on vendor id, interface subclass and protocol - vendor = vendorIds[i]; - if_subclass = ADB_SUBCLASS; - if_protocol = ADB_PROTOCOL; - CFDictionarySetValue(matchingDict, CFSTR(kUSBVendorID), - CFNumberCreate(kCFAllocatorDefault, - kCFNumberSInt32Type, &vendor)); - CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceSubClass), - CFNumberCreate(kCFAllocatorDefault, - kCFNumberSInt32Type, &if_subclass)); - CFDictionarySetValue(matchingDict, CFSTR(kUSBInterfaceProtocol), - CFNumberCreate(kCFAllocatorDefault, - kCFNumberSInt32Type, &if_protocol)); - IOServiceAddMatchingNotification( - notificationPort, - kIOFirstMatchNotification, - matchingDict, - AndroidInterfaceAdded, - NULL, - ¬ificationIterators[i]); - - //* Iterate over set of matching interfaces to access already-present - //* devices and to arm the notification - AndroidInterfaceAdded(NULL, notificationIterators[i]); + if (!matchingDict) { + DBG("ERR: Couldn't create USB matching dictionary.\n"); + return -1; } + //* We have to get notifications for all potential candidates and test them + //* at connection time because the matching rules don't allow for a + //* USB interface class of 0xff for class+subclass+protocol matches + //* See https://developer.apple.com/library/mac/qa/qa1076/_index.html + IOServiceAddMatchingNotification( + notificationPort, + kIOFirstMatchNotification, + matchingDict, + AndroidInterfaceAdded, + NULL, + ¬ificationIterator); + + //* Iterate over set of matching interfaces to access already-present + //* devices and to arm the notification + AndroidInterfaceAdded(NULL, notificationIterator); + return 0; } @@ -126,6 +109,7 @@ AndroidInterfaceAdded(void *refCon, io_iterator_t iterator) HRESULT result; SInt32 score; UInt32 locationId; + UInt8 class, subclass, protocol; UInt16 vendor; UInt16 product; UInt8 serialIndex; @@ -156,6 +140,16 @@ AndroidInterfaceAdded(void *refCon, io_iterator_t iterator) continue; } + kr = (*iface)->GetInterfaceClass(iface, &class); + kr = (*iface)->GetInterfaceSubClass(iface, &subclass); + kr = (*iface)->GetInterfaceProtocol(iface, &protocol); + if(class != ADB_CLASS || subclass != ADB_SUBCLASS || protocol != ADB_PROTOCOL) { + // Ignore non-ADB devices. + DBG("Ignoring interface with incorrect class/subclass/protocol - %d, %d, %d\n", class, subclass, protocol); + (*iface)->Release(iface); + continue; + } + //* this gets us an ioservice, with which we will find the actual //* device; after getting a plugin, and querying the interface, of //* course. @@ -192,7 +186,6 @@ AndroidInterfaceAdded(void *refCon, io_iterator_t iterator) //* Now after all that, we actually have a ref to the device and //* the interface that matched our criteria - kr = (*dev)->GetDeviceVendor(dev, &vendor); kr = (*dev)->GetDeviceProduct(dev, &product); kr = (*dev)->GetLocationID(dev, &locationId); @@ -385,8 +378,6 @@ err_get_num_ep: void* RunLoopThread(void* unused) { - unsigned i; - InitUSB(); currentRunLoop = CFRunLoopGetCurrent(); @@ -399,9 +390,7 @@ void* RunLoopThread(void* unused) CFRunLoopRun(); currentRunLoop = 0; - for (i = 0; i < vendorIdCount; i++) { - IOObjectRelease(notificationIterators[i]); - } + IOObjectRelease(notificationIterator); IONotificationPortDestroy(notificationPort); DBG("RunLoopThread done\n"); @@ -416,9 +405,6 @@ void usb_init() { adb_thread_t tid; - notificationIterators = (io_iterator_t*)malloc( - vendorIdCount * sizeof(io_iterator_t)); - adb_mutex_init(&start_lock, NULL); adb_cond_init(&start_cond, NULL); @@ -443,11 +429,6 @@ void usb_cleanup() close_usb_devices(); if (currentRunLoop) CFRunLoopStop(currentRunLoop); - - if (notificationIterators != NULL) { - free(notificationIterators); - notificationIterators = NULL; - } } int usb_write(usb_handle *handle, const void *buf, int len) diff --git a/adb/usb_vendors.c b/adb/usb_vendors.c deleted file mode 100755 index b037268..0000000 --- a/adb/usb_vendors.c +++ /dev/null @@ -1,382 +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 "usb_vendors.h" - -#include <stdio.h> - -#ifdef _WIN32 -# define WIN32_LEAN_AND_MEAN -# include "windows.h" -# include "shlobj.h" -#else -# include <unistd.h> -# include <sys/stat.h> -#endif - -#include "sysdeps.h" -#include "adb.h" - -#define ANDROID_PATH ".android" -#define ANDROID_ADB_INI "adb_usb.ini" - -#define TRACE_TAG TRACE_USB - -/* Keep the list below sorted alphabetically by #define name */ -// Acer's USB Vendor ID -#define VENDOR_ID_ACER 0x0502 -// Alco's USB Vendor ID -#define VENDOR_ID_ALCO 0x1914 -// Allwinner's USB Vendor ID -#define VENDOR_ID_ALLWINNER 0x1F3A -// Amlogic's USB Vendor ID -#define VENDOR_ID_AMLOGIC 0x1b8e -// AnyDATA's USB Vendor ID -#define VENDOR_ID_ANYDATA 0x16D5 -// Archos's USB Vendor ID -#define VENDOR_ID_ARCHOS 0x0E79 -// Asus's USB Vendor ID -#define VENDOR_ID_ASUS 0x0b05 -// BYD's USB Vendor ID -#define VENDOR_ID_BYD 0x1D91 -// Compal's USB Vendor ID -#define VENDOR_ID_COMPAL 0x04B7 -// Compalcomm's USB Vendor ID -#define VENDOR_ID_COMPALCOMM 0x1219 -// Dell's USB Vendor ID -#define VENDOR_ID_DELL 0x413c -// ECS's USB Vendor ID -#define VENDOR_ID_ECS 0x03fc -// EMERGING_TECH's USB Vendor ID -#define VENDOR_ID_EMERGING_TECH 0x297F -// Emerson's USB Vendor ID -#define VENDOR_ID_EMERSON 0x2207 -// Foxconn's USB Vendor ID -#define VENDOR_ID_FOXCONN 0x0489 -// Fujitsu's USB Vendor ID -#define VENDOR_ID_FUJITSU 0x04C5 -// Funai's USB Vendor ID -#define VENDOR_ID_FUNAI 0x0F1C -// Garmin-Asus's USB Vendor ID -#define VENDOR_ID_GARMIN_ASUS 0x091E -// Gigabyte's USB Vendor ID -#define VENDOR_ID_GIGABYTE 0x0414 -// Gigaset's USB Vendor ID -#define VENDOR_ID_GIGASET 0x1E85 -// GIONEE's USB Vendor ID -#define VENDOR_ID_GIONEE 0x271D -// Google's USB Vendor ID -#define VENDOR_ID_GOOGLE 0x18d1 -// Haier's USB Vendor ID -#define VENDOR_ID_HAIER 0x201E -// Harris's USB Vendor ID -#define VENDOR_ID_HARRIS 0x19A5 -// Hisense's USB Vendor ID -#define VENDOR_ID_HISENSE 0x109b -// Honeywell's USB Vendor ID -#define VENDOR_ID_HONEYWELL 0x0c2e -// HP's USB Vendor ID -#define VENDOR_ID_HP 0x03f0 -// HTC's USB Vendor ID -#define VENDOR_ID_HTC 0x0bb4 -// Huawei's USB Vendor ID -#define VENDOR_ID_HUAWEI 0x12D1 -// INQ Mobile's USB Vendor ID -#define VENDOR_ID_INQ_MOBILE 0x2314 -// Intel's USB Vendor ID -#define VENDOR_ID_INTEL 0x8087 -// Intermec's USB Vendor ID -#define VENDOR_ID_INTERMEC 0x067e -// IRiver's USB Vendor ID -#define VENDOR_ID_IRIVER 0x2420 -// K-Touch's USB Vendor ID -#define VENDOR_ID_K_TOUCH 0x24E3 -// KT Tech's USB Vendor ID -#define VENDOR_ID_KT_TECH 0x2116 -// Kobo's USB Vendor ID -#define VENDOR_ID_KOBO 0x2237 -// Kyocera's USB Vendor ID -#define VENDOR_ID_KYOCERA 0x0482 -// Lab126's USB Vendor ID -#define VENDOR_ID_LAB126 0x1949 -// Lenovo's USB Vendor ID -#define VENDOR_ID_LENOVO 0x17EF -// LenovoMobile's USB Vendor ID -#define VENDOR_ID_LENOVOMOBILE 0x2006 -// LG's USB Vendor ID -#define VENDOR_ID_LGE 0x1004 -// Lumigon's USB Vendor ID -#define VENDOR_ID_LUMIGON 0x25E3 -// Micromax's USB Vendor ID -#define VENDOR_ID_MICROMAX 0x2A96 -// Motorola's USB Vendor ID -#define VENDOR_ID_MOTOROLA 0x22b8 -// MSI's USB Vendor ID -#define VENDOR_ID_MSI 0x0DB0 -// MTK's USB Vendor ID -#define VENDOR_ID_MTK 0x0e8d -// NEC's USB Vendor ID -#define VENDOR_ID_NEC 0x0409 -// B&N Nook's USB Vendor ID -#define VENDOR_ID_NOOK 0x2080 -// Nvidia's USB Vendor ID -#define VENDOR_ID_NVIDIA 0x0955 -// OPPO's USB Vendor ID -#define VENDOR_ID_OPPO 0x22D9 -// On-The-Go-Video's USB Vendor ID -#define VENDOR_ID_OTGV 0x2257 -// OUYA's USB Vendor ID -#define VENDOR_ID_OUYA 0x2836 -// Pantech's USB Vendor ID -#define VENDOR_ID_PANTECH 0x10A9 -// Pegatron's USB Vendor ID -#define VENDOR_ID_PEGATRON 0x1D4D -// Philips's USB Vendor ID -#define VENDOR_ID_PHILIPS 0x0471 -// Panasonic Mobile Communication's USB Vendor ID -#define VENDOR_ID_PMC 0x04DA -// Positivo's USB Vendor ID -#define VENDOR_ID_POSITIVO 0x1662 -// Prestigio's USB Vendor ID -#define VENDOR_ID_PRESTIGIO 0x29e4 -// Qisda's USB Vendor ID -#define VENDOR_ID_QISDA 0x1D45 -// Qualcomm's USB Vendor ID -#define VENDOR_ID_QUALCOMM 0x05c6 -// Quanta's USB Vendor ID -#define VENDOR_ID_QUANTA 0x0408 -// Razer's USB Vendor ID -#define VENDOR_ID_RAZER 0x1532 -// Rockchip's USB Vendor ID -#define VENDOR_ID_ROCKCHIP 0x2207 -// Samsung's USB Vendor ID -#define VENDOR_ID_SAMSUNG 0x04e8 -// Sharp's USB Vendor ID -#define VENDOR_ID_SHARP 0x04dd -// SK Telesys's USB Vendor ID -#define VENDOR_ID_SK_TELESYS 0x1F53 -// Smartisan's USB Vendor ID -#define VENDOR_ID_SMARTISAN 0x29a9 -// Sonim Tech's USB Vendor ID -#define VENDOR_ID_SONIM_TECH 0x1d9c -// Sony's USB Vendor ID -#define VENDOR_ID_SONY 0x054C -// Sony Ericsson's USB Vendor ID -#define VENDOR_ID_SONY_ERICSSON 0x0FCE -// T & A Mobile Phones' USB Vendor ID -#define VENDOR_ID_T_AND_A 0x1BBB -// TechFaith's USB Vendor ID -#define VENDOR_ID_TECHFAITH 0x1d09 -// Teleepoch's USB Vendor ID -#define VENDOR_ID_TELEEPOCH 0x2340 -// Texas Instruments's USB Vendor ID -#define VENDOR_ID_TI 0x0451 -// Toshiba's USB Vendor ID -#define VENDOR_ID_TOSHIBA 0x0930 -// TrekStor's USB Vendor ID -#define VENDOR_ID_TREKSTOR 0x1E68 -// Unowhy's USB Vendor ID -#define VENDOR_ID_UNOWHY 0x2A49 -// Vizio's USB Vendor ID -#define VENDOR_ID_VIZIO 0xE040 -// Wacom's USB Vendor ID -#define VENDOR_ID_WACOM 0x0531 -// Xiaomi's USB Vendor ID -#define VENDOR_ID_XIAOMI 0x2717 -// YotaDevices's USB Vendor ID -#define VENDOR_ID_YOTADEVICES 0x2916 -// Yulong Coolpad's USB Vendor ID -#define VENDOR_ID_YULONG_COOLPAD 0x1EBF -// ZTE's USB Vendor ID -#define VENDOR_ID_ZTE 0x19D2 -/* Keep the list above sorted alphabetically by #define name */ - -/** built-in vendor list */ -/* Keep the list below sorted alphabetically */ -int builtInVendorIds[] = { - VENDOR_ID_ACER, - VENDOR_ID_ALCO, - VENDOR_ID_ALLWINNER, - VENDOR_ID_AMLOGIC, - VENDOR_ID_ANYDATA, - VENDOR_ID_ARCHOS, - VENDOR_ID_ASUS, - VENDOR_ID_BYD, - VENDOR_ID_COMPAL, - VENDOR_ID_COMPALCOMM, - VENDOR_ID_DELL, - VENDOR_ID_ECS, - VENDOR_ID_EMERGING_TECH, - VENDOR_ID_EMERSON, - VENDOR_ID_FOXCONN, - VENDOR_ID_FUJITSU, - VENDOR_ID_FUNAI, - VENDOR_ID_GARMIN_ASUS, - VENDOR_ID_GIGABYTE, - VENDOR_ID_GIGASET, - VENDOR_ID_GIONEE, - VENDOR_ID_GOOGLE, - VENDOR_ID_HAIER, - VENDOR_ID_HARRIS, - VENDOR_ID_HISENSE, - VENDOR_ID_HONEYWELL, - VENDOR_ID_HP, - VENDOR_ID_HTC, - VENDOR_ID_HUAWEI, - VENDOR_ID_INQ_MOBILE, - VENDOR_ID_INTEL, - VENDOR_ID_INTERMEC, - VENDOR_ID_IRIVER, - VENDOR_ID_KOBO, - VENDOR_ID_K_TOUCH, - VENDOR_ID_KT_TECH, - VENDOR_ID_KYOCERA, - VENDOR_ID_LAB126, - VENDOR_ID_LENOVO, - VENDOR_ID_LENOVOMOBILE, - VENDOR_ID_LGE, - VENDOR_ID_LUMIGON, - VENDOR_ID_MICROMAX, - VENDOR_ID_MOTOROLA, - VENDOR_ID_MSI, - VENDOR_ID_MTK, - VENDOR_ID_NEC, - VENDOR_ID_NOOK, - VENDOR_ID_NVIDIA, - VENDOR_ID_OPPO, - VENDOR_ID_OTGV, - VENDOR_ID_OUYA, - VENDOR_ID_PANTECH, - VENDOR_ID_PEGATRON, - VENDOR_ID_PHILIPS, - VENDOR_ID_PMC, - VENDOR_ID_POSITIVO, - VENDOR_ID_PRESTIGIO, - VENDOR_ID_QISDA, - VENDOR_ID_QUALCOMM, - VENDOR_ID_QUANTA, - VENDOR_ID_RAZER, - VENDOR_ID_ROCKCHIP, - VENDOR_ID_SAMSUNG, - VENDOR_ID_SHARP, - VENDOR_ID_SK_TELESYS, - VENDOR_ID_SMARTISAN, - VENDOR_ID_SONIM_TECH, - VENDOR_ID_SONY, - VENDOR_ID_SONY_ERICSSON, - VENDOR_ID_T_AND_A, - VENDOR_ID_TECHFAITH, - VENDOR_ID_TELEEPOCH, - VENDOR_ID_TI, - VENDOR_ID_TOSHIBA, - VENDOR_ID_TREKSTOR, - VENDOR_ID_UNOWHY, - VENDOR_ID_VIZIO, - VENDOR_ID_WACOM, - VENDOR_ID_XIAOMI, - VENDOR_ID_YOTADEVICES, - VENDOR_ID_YULONG_COOLPAD, - VENDOR_ID_ZTE, -}; -/* Keep the list above sorted alphabetically */ - -#define BUILT_IN_VENDOR_COUNT (sizeof(builtInVendorIds)/sizeof(builtInVendorIds[0])) - -/* max number of supported vendor ids (built-in + 3rd party). increase as needed */ -#define VENDOR_COUNT_MAX 128 - -int vendorIds[VENDOR_COUNT_MAX]; -unsigned vendorIdCount = 0; - -int get_adb_usb_ini(char* buff, size_t len); - -void usb_vendors_init(void) -{ - if (VENDOR_COUNT_MAX < BUILT_IN_VENDOR_COUNT) { - fprintf(stderr, "VENDOR_COUNT_MAX not big enough for built-in vendor list.\n"); - exit(2); - } - - /* add the built-in vendors at the beginning of the array */ - memcpy(vendorIds, builtInVendorIds, sizeof(builtInVendorIds)); - - /* default array size is the number of built-in vendors */ - vendorIdCount = BUILT_IN_VENDOR_COUNT; - - if (VENDOR_COUNT_MAX == BUILT_IN_VENDOR_COUNT) - return; - - char temp[PATH_MAX]; - if (get_adb_usb_ini(temp, sizeof(temp)) == 0) { - FILE * f = fopen(temp, "rt"); - - if (f != NULL) { - /* The vendor id file is pretty basic. 1 vendor id per line. - Lines starting with # are comments */ - while (fgets(temp, sizeof(temp), f) != NULL) { - if (temp[0] == '#') - continue; - - long value = strtol(temp, NULL, 0); - if (errno == EINVAL || errno == ERANGE || value > INT_MAX || value < 0) { - fprintf(stderr, "Invalid content in %s. Quitting.\n", ANDROID_ADB_INI); - exit(2); - } - - vendorIds[vendorIdCount++] = (int)value; - - /* make sure we don't go beyond the array */ - if (vendorIdCount == VENDOR_COUNT_MAX) { - break; - } - } - fclose(f); - } - } -} - -/* Utils methods */ - -/* builds the path to the adb vendor id file. returns 0 if success */ -int build_path(char* buff, size_t len, const char* format, const char* home) -{ - if (snprintf(buff, len, format, home, ANDROID_PATH, ANDROID_ADB_INI) >= (signed)len) { - return 1; - } - - return 0; -} - -/* fills buff with the path to the adb vendor id file. returns 0 if success */ -int get_adb_usb_ini(char* buff, size_t len) -{ -#ifdef _WIN32 - const char* home = getenv("ANDROID_SDK_HOME"); - if (home != NULL) { - return build_path(buff, len, "%s\\%s\\%s", home); - } else { - char path[MAX_PATH]; - SHGetFolderPath( NULL, CSIDL_PROFILE, NULL, 0, path); - return build_path(buff, len, "%s\\%s\\%s", path); - } -#else - const char* home = getenv("HOME"); - if (home == NULL) - home = "/tmp"; - - return build_path(buff, len, "%s/%s/%s", home); -#endif -} diff --git a/adb/usb_vendors.h b/adb/usb_vendors.h deleted file mode 100644 index cee23a1..0000000 --- a/adb/usb_vendors.h +++ /dev/null @@ -1,25 +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. - */ - -#ifndef __USB_VENDORS_H -#define __USB_VENDORS_H - -extern int vendorIds[]; -extern unsigned vendorIdCount; - -void usb_vendors_init(void); - -#endif diff --git a/adb/usb_windows.c b/adb/usb_windows.c index b7ad913..a2d7226 100644 --- a/adb/usb_windows.c +++ b/adb/usb_windows.c @@ -21,6 +21,7 @@ #include <usb100.h> #include <adb_api.h> #include <stdio.h> +#include <stdlib.h> #include "sysdeps.h" diff --git a/adf/libadf/tests/Android.mk b/adf/libadf/tests/Android.mk new file mode 100644 index 0000000..93efafa --- /dev/null +++ b/adf/libadf/tests/Android.mk @@ -0,0 +1,22 @@ +# +# Copyright (C) 2013 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. +# +LOCAL_PATH := $(my-dir) + +include $(CLEAR_VARS) +LOCAL_SRC_FILES := adf_test.cpp +LOCAL_MODULE := adf-unit-tests +LOCAL_STATIC_LIBRARIES := libadf +include $(BUILD_NATIVE_TEST) diff --git a/adf/libadf/tests/adf_test.cpp b/adf/libadf/tests/adf_test.cpp new file mode 100644 index 0000000..d95330d --- /dev/null +++ b/adf/libadf/tests/adf_test.cpp @@ -0,0 +1,342 @@ +/* + * Copyright (C) 2013 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 <errno.h> +#include <fcntl.h> + +#include <adf/adf.h> +#include <gtest/gtest.h> +#include <sys/mman.h> + +class AdfTest : public testing::Test { +public: + AdfTest() : intf_id(0), intf(-1), eng_id(0), eng(-1) { } + + virtual void SetUp() { + int err = adf_device_open(dev_id, O_RDWR, &dev); + ASSERT_GE(err, 0) << "opening ADF device " << dev_id << + " failed: " << strerror(-err); + + err = adf_find_simple_post_configuration(&dev, fmt8888, n_fmt8888, + &intf_id, &eng_id); + ASSERT_GE(err, 0) << "finding ADF configuration failed: " << + strerror(-err); + + intf = adf_interface_open(&dev, intf_id, O_RDWR); + ASSERT_GE(intf, 0) << "opening ADF interface " << dev_id << "." << + intf_id << " failed: " << strerror(-intf); + + eng = adf_overlay_engine_open(&dev, eng_id, O_RDWR); + ASSERT_GE(eng, 0) << "opening ADF overlay engine " << dev_id << "." << + eng_id << " failed: " << strerror(-eng); + } + + virtual void TearDown() { + if (eng >= 0) + close(eng); + if (intf >= 0) + close(intf); + adf_device_close(&dev); + } + + void get8888Format(uint32_t &fmt, char fmt_str[ADF_FORMAT_STR_SIZE]) { + adf_overlay_engine_data data; + int err = adf_get_overlay_engine_data(eng, &data); + ASSERT_GE(err, 0) << "getting ADF overlay engine data failed: " << + strerror(-err); + + for (size_t i = 0; i < data.n_supported_formats; i++) { + for (size_t j = 0; j < n_fmt8888; j++) { + if (data.supported_formats[i] == fmt8888[j]) { + fmt = data.supported_formats[i]; + adf_format_str(fmt, fmt_str); + adf_free_overlay_engine_data(&data); + return; + } + } + } + + adf_free_overlay_engine_data(&data); + FAIL(); /* this should never happen */ + } + + void drawCheckerboard(void *buf, uint32_t w, uint32_t h, uint32_t pitch) { + uint8_t *buf8 = reinterpret_cast<uint8_t *>(buf); + for (uint32_t y = 0; y < h / 2; y++) { + uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch); + for (uint32_t x = 0; x < w / 2; x++) + scanline[x] = 0xFF0000FF; + for (uint32_t x = w / 2; x < w; x++) + scanline[x] = 0xFF00FFFF; + } + for (uint32_t y = h / 2; y < h; y++) { + uint32_t *scanline = reinterpret_cast<uint32_t *>(buf8 + y * pitch); + for (uint32_t x = 0; x < w / 2; x++) + scanline[x] = 0xFFFF00FF; + for (uint32_t x = w / 2; x < w; x++) + scanline[x] = 0xFFFFFFFF; + } + } + + /* various helpers to call ADF and die on failure */ + + void getInterfaceData(adf_interface_data &data) { + int err = adf_get_interface_data(intf, &data); + ASSERT_GE(err, 0) << "getting ADF interface data failed: " << + strerror(-err); + } + + void getCurrentMode(uint32_t &w, uint32_t &h) { + adf_interface_data data; + ASSERT_NO_FATAL_FAILURE(getInterfaceData(data)); + w = data.current_mode.hdisplay; + h = data.current_mode.vdisplay; + adf_free_interface_data(&data); + } + + void blank(uint8_t mode) { + int err = adf_interface_blank(intf, mode); + ASSERT_FALSE(err < 0 && err != -EBUSY) << + "unblanking interface failed: " << strerror(-err); + } + + void attach() { + int err = adf_device_attach(&dev, eng_id, intf_id); + ASSERT_FALSE(err < 0 && err != -EALREADY) << + "attaching overlay engine " << eng_id << " to interface " << + intf_id << " failed: " << strerror(-err); + } + + void detach() { + int err = adf_device_detach(&dev, eng_id, intf_id); + ASSERT_FALSE(err < 0 && err != -EINVAL) << + "detaching overlay engine " << eng_id << " from interface " << + intf_id << " failed: " << strerror(-err); + } + + void readVsyncTimestamp(uint64_t ×tamp) { + adf_event *event; + int err = adf_read_event(intf, &event); + ASSERT_GE(err, 0) << "reading ADF event failed: " << strerror(-err); + + ASSERT_EQ(ADF_EVENT_VSYNC, event->type); + ASSERT_EQ(sizeof(adf_vsync_event), event->length); + + adf_vsync_event *vsync_event = + reinterpret_cast<adf_vsync_event *>(event); + timestamp = vsync_event->timestamp; + free(event); + } + +protected: + adf_device dev; + adf_id_t intf_id; + int intf; + adf_id_t eng_id; + int eng; + +private: + const static adf_id_t dev_id = 0; + const static __u32 fmt8888[]; + const static size_t n_fmt8888; +}; + +const __u32 AdfTest::fmt8888[] = { + DRM_FORMAT_XRGB8888, + DRM_FORMAT_XBGR8888, + DRM_FORMAT_RGBX8888, + DRM_FORMAT_BGRX8888, + DRM_FORMAT_ARGB8888, + DRM_FORMAT_ABGR8888, + DRM_FORMAT_RGBA8888, + DRM_FORMAT_BGRA8888 +}; +const size_t AdfTest::n_fmt8888 = sizeof(fmt8888) / sizeof(fmt8888[0]); + +TEST(adf, devices) { + adf_id_t *devs; + ssize_t n_devs = adf_devices(&devs); + free(devs); + + ASSERT_GE(n_devs, 0) << "enumerating ADF devices failed: " << + strerror(-n_devs); + ASSERT_TRUE(devs != NULL); +} + +TEST_F(AdfTest, device_data) { + adf_device_data data; + int err = adf_get_device_data(&dev, &data); + ASSERT_GE(err, 0) << "getting ADF device data failed: " << strerror(-err); + + EXPECT_LT(data.n_attachments, ADF_MAX_ATTACHMENTS); + EXPECT_GT(data.n_allowed_attachments, 0); + EXPECT_LT(data.n_allowed_attachments, ADF_MAX_ATTACHMENTS); + EXPECT_LT(data.custom_data_size, ADF_MAX_CUSTOM_DATA_SIZE); + adf_free_device_data(&data); +} + +TEST_F(AdfTest, interface_data) { + adf_interface_data data; + ASSERT_NO_FATAL_FAILURE(getInterfaceData(data)); + + EXPECT_LT(data.type, ADF_INTF_TYPE_MAX); + EXPECT_LE(data.dpms_state, DRM_MODE_DPMS_OFF); + EXPECT_EQ(1, data.hotplug_detect); + EXPECT_GT(data.n_available_modes, 0); + EXPECT_LT(data.custom_data_size, ADF_MAX_CUSTOM_DATA_SIZE); + adf_free_interface_data(&data); +} + +TEST_F(AdfTest, overlay_engine_data) { + adf_overlay_engine_data data; + int err = adf_get_overlay_engine_data(eng, &data); + ASSERT_GE(err, 0) << "getting ADF overlay engine failed: " << + strerror(-err); + + EXPECT_GT(data.n_supported_formats, 0); + EXPECT_LT(data.n_supported_formats, ADF_MAX_SUPPORTED_FORMATS); + EXPECT_LT(data.custom_data_size, ADF_MAX_CUSTOM_DATA_SIZE); + adf_free_overlay_engine_data(&data); +} + +TEST_F(AdfTest, blank) { + int err = adf_interface_blank(intf, (uint8_t)-1); + EXPECT_EQ(-EINVAL, err) << "setting bogus DPMS mode should have failed"; + + err = adf_interface_blank(eng, DRM_MODE_DPMS_OFF); + EXPECT_EQ(-EINVAL, err) << "blanking overlay engine should have failed"; + + ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_OFF)); + err = adf_interface_blank(intf, DRM_MODE_DPMS_OFF); + EXPECT_EQ(-EBUSY, err) << "blanking interface twice should have failed"; + + ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON)); + err = adf_interface_blank(intf, DRM_MODE_DPMS_ON); + EXPECT_EQ(-EBUSY, err) << "unblanking interface twice should have failed"; + + adf_interface_data data; + ASSERT_NO_FATAL_FAILURE(getInterfaceData(data)); + EXPECT_EQ(DRM_MODE_DPMS_ON, data.dpms_state); + adf_free_interface_data(&data); +} + +TEST_F(AdfTest, event) { + int err = adf_set_event(intf, ADF_EVENT_TYPE_MAX, true); + EXPECT_EQ(-EINVAL, err) << "enabling bogus ADF event should have failed"; + + err = adf_set_event(intf, ADF_EVENT_TYPE_MAX, false); + EXPECT_EQ(-EINVAL, err) << "disabling bogus ADF event should have failed"; + + err = adf_set_event(intf, ADF_EVENT_VSYNC, true); + ASSERT_GE(err, 0) << "enabling vsync event failed: " << strerror(-err); + + err = adf_set_event(intf, ADF_EVENT_VSYNC, true); + EXPECT_EQ(-EALREADY, err) << + "enabling vsync event twice should have failed"; + + ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON)); + + uint64_t timestamp1, timestamp2; + ASSERT_NO_FATAL_FAILURE(readVsyncTimestamp(timestamp1)); + ASSERT_NO_FATAL_FAILURE(readVsyncTimestamp(timestamp2)); + EXPECT_GT(timestamp2, timestamp1); + + err = adf_set_event(intf, ADF_EVENT_VSYNC, false); + EXPECT_GE(err, 0) << "disabling vsync event failed: " << strerror(-err); + + err = adf_set_event(intf, ADF_EVENT_VSYNC, false); + EXPECT_EQ(-EALREADY, err) << + "disabling vsync event twice should have failed"; +} + +TEST_F(AdfTest, attach) { + ASSERT_NO_FATAL_FAILURE(attach()); + int err = adf_device_attach(&dev, eng_id, intf_id); + EXPECT_EQ(-EALREADY, err) << "attaching overlay engine " << eng_id << + " to interface " << intf_id << " twice should have failed"; + + ASSERT_NO_FATAL_FAILURE(detach()); + err = adf_device_detach(&dev, eng_id, intf_id); + EXPECT_EQ(-EINVAL, err) << "detaching overlay engine " << eng_id << + " from interface " << intf_id << " twice should have failed"; + + err = adf_device_attach(&dev, eng_id, ADF_MAX_INTERFACES); + EXPECT_EQ(-EINVAL, err) << "attaching overlay engine " << eng_id << + " to bogus interface should have failed"; + + err = adf_device_detach(&dev, eng_id, ADF_MAX_INTERFACES); + EXPECT_EQ(-EINVAL, err) << "detaching overlay engine " << eng_id << + " from bogus interface should have failed"; +} + +TEST_F(AdfTest, simple_buffer_alloc) { + uint32_t w = 0, h = 0; + ASSERT_NO_FATAL_FAILURE(getCurrentMode(w, h)); + + uint32_t format; + char format_str[ADF_FORMAT_STR_SIZE]; + ASSERT_NO_FATAL_FAILURE(get8888Format(format, format_str)); + + uint32_t offset; + uint32_t pitch; + int buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, format, &offset, + &pitch); + EXPECT_GE(buf_fd, 0) << "allocating " << w << "x" << h << " " << + format_str << " buffer failed: " << strerror(-buf_fd); + EXPECT_GE(pitch, w * 4); + close(buf_fd); + + buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, 0xDEADBEEF, &offset, + &pitch); + /* n.b.: ADF only allows simple buffers with built-in RGB formats, + so this should fail even if a driver supports custom format 0xDEADBEEF */ + EXPECT_EQ(-EINVAL, buf_fd) << + "allocating buffer with bogus format should have failed"; +} + +TEST_F(AdfTest, simple_buffer) { + uint32_t w = 0, h = 0; + ASSERT_NO_FATAL_FAILURE(getCurrentMode(w, h)); + + uint32_t format = 0; + char format_str[ADF_FORMAT_STR_SIZE]; + ASSERT_NO_FATAL_FAILURE(get8888Format(format, format_str)); + + uint32_t offset; + uint32_t pitch; + int buf_fd = adf_interface_simple_buffer_alloc(intf, w, h, format, &offset, + &pitch); + ASSERT_GE(buf_fd, 0) << "allocating " << w << "x" << h << " " << + format_str << " buffer failed: " << strerror(-buf_fd); + EXPECT_GE(pitch, w * 4); + + void *mapped = mmap(NULL, pitch * h, PROT_WRITE, MAP_SHARED, buf_fd, + offset); + ASSERT_NE(mapped, MAP_FAILED) << "mapping " << w << "x" << h << " " << + format_str << " buffer failed: " << strerror(-errno); + drawCheckerboard(mapped, w, h, pitch); + munmap(mapped, pitch * h); + + ASSERT_NO_FATAL_FAILURE(attach()); + ASSERT_NO_FATAL_FAILURE(blank(DRM_MODE_DPMS_ON)); + + int release_fence = adf_interface_simple_post(intf, eng_id, w, h, format, + buf_fd, offset, pitch, -1); + close(buf_fd); + ASSERT_GE(release_fence, 0) << "posting " << w << "x" << h << " " << + format_str << " buffer failed: " << strerror(-release_fence); + close(release_fence); +} diff --git a/fastboot/Android.mk b/fastboot/Android.mk index f03bbea..aa5b14a 100644 --- a/fastboot/Android.mk +++ b/fastboot/Android.mk @@ -53,7 +53,6 @@ endif LOCAL_STATIC_LIBRARIES := \ $(EXTRA_STATIC_LIBS) \ libzipfile \ - libunz \ libext4_utils_host \ libsparse_host \ libz diff --git a/fastboot/fastboot.c b/fastboot/fastboot.c index 43d05aa..959d3ad 100644 --- a/fastboot/fastboot.c +++ b/fastboot/fastboot.c @@ -244,7 +244,7 @@ int list_devices_callback(usb_ifc_info *info) // output compatible with "adb devices" if (!long_listing) { printf("%s\tfastboot\n", serial); - } else if (!info->device_path) { + } else if (strcmp("", info->device_path) == 0) { printf("%-22s fastboot\n", serial); } else { printf("%-22s fastboot %s\n", serial, info->device_path); @@ -988,6 +988,7 @@ int main(int argc, char **argv) unsigned sz; int status; int c; + int longindex; const struct option longopts[] = { {"base", required_argument, 0, 'b'}, @@ -996,13 +997,14 @@ int main(int argc, char **argv) {"ramdisk_offset", required_argument, 0, 'r'}, {"tags_offset", required_argument, 0, 't'}, {"help", 0, 0, 'h'}, + {"unbuffered", 0, 0, 0}, {0, 0, 0, 0} }; serial = getenv("ANDROID_SERIAL"); while (1) { - c = getopt_long(argc, argv, "wub:k:n:r:t:s:S:lp:c:i:m:h", longopts, NULL); + c = getopt_long(argc, argv, "wub:k:n:r:t:s:S:lp:c:i:m:h", longopts, &longindex); if (c < 0) { break; } @@ -1063,6 +1065,12 @@ int main(int argc, char **argv) break; case '?': return 1; + case 0: + if (strcmp("unbuffered", longopts[longindex].name) == 0) { + setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stderr, NULL, _IONBF, 0); + } + break; default: abort(); } diff --git a/fastboot/fastboot_protocol.txt b/fastboot/fastboot_protocol.txt index 2248992..37b1959 100644 --- a/fastboot/fastboot_protocol.txt +++ b/fastboot/fastboot_protocol.txt @@ -12,8 +12,8 @@ Basic Requirements ------------------ * Two bulk endpoints (in, out) are required -* Max packet size must be 64 bytes for full-speed and 512 bytes for - high-speed USB +* Max packet size must be 64 bytes for full-speed, 512 bytes for + high-speed and 1024 bytes for Super Speed USB. * The protocol is entirely host-driven and synchronous (unlike the multi-channel, bi-directional, asynchronous ADB protocol) diff --git a/fastboot/protocol.c b/fastboot/protocol.c index 84e9837..10a84c1 100644 --- a/fastboot/protocol.c +++ b/fastboot/protocol.c @@ -216,7 +216,7 @@ int fb_download_data(usb_handle *usb, const void *data, unsigned size) } } -#define USB_BUF_SIZE 512 +#define USB_BUF_SIZE 1024 static char usb_buf[USB_BUF_SIZE]; static int usb_buf_len; diff --git a/fastboot/usb_linux.c b/fastboot/usb_linux.c index fabbd51..022f364 100644 --- a/fastboot/usb_linux.c +++ b/fastboot/usb_linux.c @@ -223,6 +223,13 @@ static int filter_usb_device(char* sysfs_name, } else { out = ept->bEndpointAddress; } + + // For USB 3.0 devices skip the SS Endpoint Companion descriptor + if (check((struct usb_descriptor_hdr *)ptr, len, + USB_DT_SS_ENDPOINT_COMP, USB_DT_SS_EP_COMP_SIZE) == 0) { + len -= USB_DT_SS_EP_COMP_SIZE; + ptr += USB_DT_SS_EP_COMP_SIZE; + } } info.has_bulk_in = (in != -1); diff --git a/fastboot/usb_windows.c b/fastboot/usb_windows.c index 0d13863..a09610f 100644 --- a/fastboot/usb_windows.c +++ b/fastboot/usb_windows.c @@ -32,6 +32,7 @@ #include <usb100.h> #include <adb_api.h> #include <stdio.h> +#include <stdlib.h> #include "usb.h" diff --git a/fastboot/util_osx.c b/fastboot/util_osx.c index 26b832a..e718562 100644 --- a/fastboot/util_osx.c +++ b/fastboot/util_osx.c @@ -31,14 +31,15 @@ void get_my_path(char s[PATH_MAX]) { - char *x; - ProcessSerialNumber psn; - GetCurrentProcess(&psn); - CFDictionaryRef dict; - dict = ProcessInformationCopyDictionary(&psn, 0xffffffff); - CFStringRef value = (CFStringRef)CFDictionaryGetValue(dict, - CFSTR("CFBundleExecutable")); - CFStringGetCString(value, s, PATH_MAX - 1, kCFStringEncodingUTF8); + CFBundleRef mainBundle = CFBundleGetMainBundle(); + CFURLRef executableURL = CFBundleCopyExecutableURL(mainBundle); + CFStringRef executablePathString = CFURLCopyFileSystemPath(executableURL, kCFURLPOSIXPathStyle); + CFRelease(executableURL); + + CFStringGetFileSystemRepresentation(executablePathString, s, PATH_MAX-1); + CFRelease(executablePathString); + + char *x; x = strrchr(s, '/'); if(x) x[1] = 0; } diff --git a/fastbootd/commands/virtual_partitions.c b/fastbootd/commands/virtual_partitions.c index 813f485..9da4020 100644 --- a/fastbootd/commands/virtual_partitions.c +++ b/fastbootd/commands/virtual_partitions.c @@ -30,6 +30,9 @@ */ #include "commands/virtual_partitions.h" + +#include <string.h> + #include "debug.h" static struct virtual_partition *partitions = NULL; diff --git a/fastbootd/usb_linux_client.c b/fastbootd/usb_linux_client.c index 64420e9..2c678b9 100644 --- a/fastbootd/usb_linux_client.c +++ b/fastbootd/usb_linux_client.c @@ -69,71 +69,85 @@ struct usb_handle { struct transport_handle handle; }; -static const struct { - struct usb_functionfs_descs_head header; - struct { - struct usb_interface_descriptor intf; - struct usb_endpoint_descriptor_no_audio source; - struct usb_endpoint_descriptor_no_audio sink; - } __attribute__((packed)) fs_descs, hs_descs; -} __attribute__((packed)) descriptors = { - .header = { - .magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC), - .length = cpu_to_le32(sizeof(descriptors)), - .fs_count = 3, - .hs_count = 3, +struct func_desc { + struct usb_interface_descriptor intf; + struct usb_endpoint_descriptor_no_audio source; + struct usb_endpoint_descriptor_no_audio sink; +} __attribute__((packed)); + +struct desc_v1 { + struct usb_functionfs_descs_head_v1 { + __le32 magic; + __le32 length; + __le32 fs_count; + __le32 hs_count; + } __attribute__((packed)) header; + struct func_desc fs_descs, hs_descs; +} __attribute__((packed)); + +struct desc_v2 { + struct usb_functionfs_descs_head_v2 { + __le32 magic; + __le32 length; + __le32 flags; + __le32 fs_count; + __le32 hs_count; + __le32 ss_count; + } __attribute__((packed)) header; + struct func_desc fs_descs, hs_descs; +} __attribute__((packed)); + +struct func_desc fs_descriptors = { + .intf = { + .bLength = sizeof(fs_descriptors.intf), + .bDescriptorType = USB_DT_INTERFACE, + .bInterfaceNumber = 0, + .bNumEndpoints = 2, + .bInterfaceClass = FASTBOOT_CLASS, + .bInterfaceSubClass = FASTBOOT_SUBCLASS, + .bInterfaceProtocol = FASTBOOT_PROTOCOL, + .iInterface = 1, /* first string from the provided table */ }, - .fs_descs = { - .intf = { - .bLength = sizeof(descriptors.fs_descs.intf), - .bDescriptorType = USB_DT_INTERFACE, - .bInterfaceNumber = 0, - .bNumEndpoints = 2, - .bInterfaceClass = FASTBOOT_CLASS, - .bInterfaceSubClass = FASTBOOT_SUBCLASS, - .bInterfaceProtocol = FASTBOOT_PROTOCOL, - .iInterface = 1, /* first string from the provided table */ - }, - .source = { - .bLength = sizeof(descriptors.fs_descs.source), - .bDescriptorType = USB_DT_ENDPOINT, - .bEndpointAddress = 1 | USB_DIR_OUT, - .bmAttributes = USB_ENDPOINT_XFER_BULK, - .wMaxPacketSize = MAX_PACKET_SIZE_FS, - }, - .sink = { - .bLength = sizeof(descriptors.fs_descs.sink), - .bDescriptorType = USB_DT_ENDPOINT, - .bEndpointAddress = 2 | USB_DIR_IN, - .bmAttributes = USB_ENDPOINT_XFER_BULK, - .wMaxPacketSize = MAX_PACKET_SIZE_FS, - }, + .source = { + .bLength = sizeof(fs_descriptors.source), + .bDescriptorType = USB_DT_ENDPOINT, + .bEndpointAddress = 1 | USB_DIR_OUT, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = MAX_PACKET_SIZE_FS, }, - .hs_descs = { - .intf = { - .bLength = sizeof(descriptors.hs_descs.intf), - .bDescriptorType = USB_DT_INTERFACE, - .bInterfaceNumber = 0, - .bNumEndpoints = 2, - .bInterfaceClass = FASTBOOT_CLASS, - .bInterfaceSubClass = FASTBOOT_SUBCLASS, - .bInterfaceProtocol = FASTBOOT_PROTOCOL, - .iInterface = 1, /* first string from the provided table */ - }, - .source = { - .bLength = sizeof(descriptors.hs_descs.source), - .bDescriptorType = USB_DT_ENDPOINT, - .bEndpointAddress = 1 | USB_DIR_OUT, - .bmAttributes = USB_ENDPOINT_XFER_BULK, - .wMaxPacketSize = MAX_PACKET_SIZE_HS, - }, - .sink = { - .bLength = sizeof(descriptors.hs_descs.sink), - .bDescriptorType = USB_DT_ENDPOINT, - .bEndpointAddress = 2 | USB_DIR_IN, - .bmAttributes = USB_ENDPOINT_XFER_BULK, - .wMaxPacketSize = MAX_PACKET_SIZE_HS, - }, + .sink = { + .bLength = sizeof(fs_descriptors.sink), + .bDescriptorType = USB_DT_ENDPOINT, + .bEndpointAddress = 2 | USB_DIR_IN, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = MAX_PACKET_SIZE_FS, + }, +}; + +struct func_desc hs_descriptors = { + .intf = { + .bLength = sizeof(hs_descriptors.intf), + .bDescriptorType = USB_DT_INTERFACE, + .bInterfaceNumber = 0, + .bNumEndpoints = 2, + .bInterfaceClass = FASTBOOT_CLASS, + .bInterfaceSubClass = FASTBOOT_SUBCLASS, + .bInterfaceProtocol = FASTBOOT_PROTOCOL, + .iInterface = 1, /* first string from the provided table */ + }, + .source = { + .bLength = sizeof(hs_descriptors.source), + .bDescriptorType = USB_DT_ENDPOINT, + .bEndpointAddress = 1 | USB_DIR_OUT, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = MAX_PACKET_SIZE_HS, + }, + .sink = { + .bLength = sizeof(hs_descriptors.sink), + .bDescriptorType = USB_DT_ENDPOINT, + .bEndpointAddress = 2 | USB_DIR_IN, + .bmAttributes = USB_ENDPOINT_XFER_BULK, + .wMaxPacketSize = MAX_PACKET_SIZE_HS, }, }; @@ -161,6 +175,17 @@ static const struct { static int init_functionfs(struct usb_transport *usb_transport) { ssize_t ret; + struct desc_v1 v1_descriptor; + struct desc_v2 v2_descriptor; + + v2_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2); + v2_descriptor.header.length = cpu_to_le32(sizeof(v2_descriptor)); + v2_descriptor.header.flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC; + v2_descriptor.header.fs_count = 3; + v2_descriptor.header.hs_count = 3; + v2_descriptor.header.ss_count = 0; + v2_descriptor.fs_descs = fs_descriptors; + v2_descriptor.hs_descs = hs_descriptors; D(VERBOSE, "OPENING %s", USB_FFS_FASTBOOT_EP0); usb_transport->control = open(USB_FFS_FASTBOOT_EP0, O_RDWR); @@ -169,10 +194,20 @@ static int init_functionfs(struct usb_transport *usb_transport) goto err; } - ret = write(usb_transport->control, &descriptors, sizeof(descriptors)); + ret = write(usb_transport->control, &v2_descriptor, sizeof(v2_descriptor)); if (ret < 0) { - D(ERR, "[ %s: write descriptors failed: errno=%d ]", USB_FFS_FASTBOOT_EP0, errno); - goto err; + v1_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC); + v1_descriptor.header.length = cpu_to_le32(sizeof(v1_descriptor)); + v1_descriptor.header.fs_count = 3; + v1_descriptor.header.hs_count = 3; + v1_descriptor.fs_descs = fs_descriptors; + v1_descriptor.hs_descs = hs_descriptors; + D(ERR, "[ %s: Switching to V1_descriptor format errno=%d ]\n", USB_FFS_FASTBOOT_EP0, errno); + ret = write(usb_transport->control, &v1_descriptor, sizeof(v1_descriptor)); + if (ret < 0) { + D(ERR, "[ %s: write descriptors failed: errno=%d ]", USB_FFS_FASTBOOT_EP0, errno); + goto err; + } } ret = write(usb_transport->control, &strings, sizeof(strings)); diff --git a/fs_mgr/Android.mk b/fs_mgr/Android.mk index 7cffc37..61bf1ee 100644 --- a/fs_mgr/Android.mk +++ b/fs_mgr/Android.mk @@ -13,6 +13,10 @@ LOCAL_C_INCLUDES += system/extras/ext4_utils LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include LOCAL_CFLAGS := -Werror +ifneq (,$(filter userdebug,$(TARGET_BUILD_VARIANT))) +LOCAL_CFLAGS += -DALLOW_ADBD_DISABLE_VERITY=1 +endif + include $(BUILD_STATIC_LIBRARY) diff --git a/fs_mgr/fs_mgr.c b/fs_mgr/fs_mgr.c index 91e6c33..40878c1 100644 --- a/fs_mgr/fs_mgr.c +++ b/fs_mgr/fs_mgr.c @@ -245,6 +245,16 @@ static int device_is_debuggable() { return strcmp(value, "1") ? 0 : 1; } +static int device_is_secure() { + int ret = -1; + char value[PROP_VALUE_MAX]; + ret = __system_property_get("ro.secure", value); + /* If error, we want to fail secure */ + if (ret < 0) + return 1; + return strcmp(value, "0") ? 1 : 0; +} + /* * Tries to mount any of the consecutive fstab entries that match * the mountpoint of the one given by fstab->recs[start_idx]. @@ -350,9 +360,11 @@ int fs_mgr_mount_all(struct fstab *fstab) wait_for_file(fstab->recs[i].blk_device, WAIT_TIMEOUT); } - if ((fstab->recs[i].fs_mgr_flags & MF_VERIFY) && - !device_is_debuggable()) { - if (fs_mgr_setup_verity(&fstab->recs[i]) < 0) { + if ((fstab->recs[i].fs_mgr_flags & MF_VERIFY) && device_is_secure()) { + int rc = fs_mgr_setup_verity(&fstab->recs[i]); + if (device_is_debuggable() && rc == FS_MGR_SETUP_VERITY_DISABLED) { + INFO("Verity disabled"); + } else if (rc != FS_MGR_SETUP_VERITY_SUCCESS) { ERROR("Could not set up verified partition, skipping!\n"); continue; } @@ -467,9 +479,11 @@ int fs_mgr_do_mount(struct fstab *fstab, char *n_name, char *n_blk_device, fstab->recs[i].mount_point); } - if ((fstab->recs[i].fs_mgr_flags & MF_VERIFY) && - !device_is_debuggable()) { - if (fs_mgr_setup_verity(&fstab->recs[i]) < 0) { + if ((fstab->recs[i].fs_mgr_flags & MF_VERIFY) && device_is_secure()) { + int rc = fs_mgr_setup_verity(&fstab->recs[i]); + if (device_is_debuggable() && rc == FS_MGR_SETUP_VERITY_DISABLED) { + INFO("Verity disabled"); + } else if (rc != FS_MGR_SETUP_VERITY_SUCCESS) { ERROR("Could not set up verified partition, skipping!\n"); continue; } diff --git a/fs_mgr/fs_mgr_fstab.c b/fs_mgr/fs_mgr_fstab.c index 3f84179..ab8f128 100644 --- a/fs_mgr/fs_mgr_fstab.c +++ b/fs_mgr/fs_mgr_fstab.c @@ -418,6 +418,11 @@ int fs_mgr_is_nonremovable(struct fstab_rec *fstab) return fstab->fs_mgr_flags & MF_NONREMOVABLE; } +int fs_mgr_is_verified(struct fstab_rec *fstab) +{ + return fstab->fs_mgr_flags & MF_VERIFY; +} + int fs_mgr_is_encryptable(struct fstab_rec *fstab) { return fstab->fs_mgr_flags & (MF_CRYPT | MF_FORCECRYPT); diff --git a/fs_mgr/fs_mgr_priv_verity.h b/fs_mgr/fs_mgr_priv_verity.h index 6193784..f90e596 100644 --- a/fs_mgr/fs_mgr_priv_verity.h +++ b/fs_mgr/fs_mgr_priv_verity.h @@ -14,4 +14,7 @@ * limitations under the License. */ -int fs_mgr_setup_verity(struct fstab_rec *fstab);
\ No newline at end of file +#define FS_MGR_SETUP_VERITY_DISABLED -2 +#define FS_MGR_SETUP_VERITY_FAIL -1 +#define FS_MGR_SETUP_VERITY_SUCCESS 0 +int fs_mgr_setup_verity(struct fstab_rec *fstab); diff --git a/fs_mgr/fs_mgr_verity.c b/fs_mgr/fs_mgr_verity.c index 01f7844..ef7cf6e 100644 --- a/fs_mgr/fs_mgr_verity.c +++ b/fs_mgr/fs_mgr_verity.c @@ -43,7 +43,6 @@ #include "fs_mgr_priv_verity.h" #define VERITY_METADATA_SIZE 32768 -#define VERITY_METADATA_MAGIC_NUMBER 0xb001b001 #define VERITY_TABLE_RSA_KEY "/verity_key" extern struct fs_info info; @@ -125,28 +124,28 @@ static int get_target_device_size(char *blk_device, uint64_t *device_size) info.len = 0; /* Only len is set to 0 to ask the device for real size. */ - data_device = open(blk_device, O_RDONLY); - if (data_device < 0) { + data_device = TEMP_FAILURE_RETRY(open(blk_device, O_RDONLY | O_CLOEXEC)); + if (data_device == -1) { ERROR("Error opening block device (%s)", strerror(errno)); return -1; } - if (lseek64(data_device, 1024, SEEK_SET) < 0) { + if (TEMP_FAILURE_RETRY(lseek64(data_device, 1024, SEEK_SET)) < 0) { ERROR("Error seeking to superblock"); - close(data_device); + TEMP_FAILURE_RETRY(close(data_device)); return -1; } - if (read(data_device, &sb, sizeof(sb)) != sizeof(sb)) { + if (TEMP_FAILURE_RETRY(read(data_device, &sb, sizeof(sb))) != sizeof(sb)) { ERROR("Error reading superblock"); - close(data_device); + TEMP_FAILURE_RETRY(close(data_device)); return -1; } ext4_parse_sb(&sb, &info); *device_size = info.len; - close(data_device); + TEMP_FAILURE_RETRY(close(data_device)); return 0; } @@ -156,11 +155,13 @@ static int read_verity_metadata(char *block_device, char **signature, char **tab unsigned table_length; uint64_t device_length; int protocol_version; - FILE *device; - int retval = -1; + int device; + int retval = FS_MGR_SETUP_VERITY_FAIL; + *signature = 0; + *table = 0; - device = fopen(block_device, "r"); - if (!device) { + device = TEMP_FAILURE_RETRY(open(block_device, O_RDONLY | O_CLOEXEC)); + if (device == -1) { ERROR("Could not open block device %s (%s).\n", block_device, strerror(errno)); goto out; } @@ -170,23 +171,35 @@ static int read_verity_metadata(char *block_device, char **signature, char **tab ERROR("Could not get target device size.\n"); goto out; } - if (fseek(device, device_length, SEEK_SET) < 0) { + if (TEMP_FAILURE_RETRY(lseek64(device, device_length, SEEK_SET)) < 0) { ERROR("Could not seek to start of verity metadata block.\n"); goto out; } // check the magic number - if (!fread(&magic_number, sizeof(int), 1, device)) { + if (TEMP_FAILURE_RETRY(read(device, &magic_number, sizeof(magic_number))) != + sizeof(magic_number)) { ERROR("Couldn't read magic number!\n"); goto out; } + +#ifdef ALLOW_ADBD_DISABLE_VERITY + if (magic_number == VERITY_METADATA_MAGIC_DISABLE) { + retval = FS_MGR_SETUP_VERITY_DISABLED; + INFO("Attempt to cleanly disable verity - only works in USERDEBUG"); + goto out; + } +#endif + if (magic_number != VERITY_METADATA_MAGIC_NUMBER) { - ERROR("Couldn't find verity metadata at offset %"PRIu64"!\n", device_length); + ERROR("Couldn't find verity metadata at offset %"PRIu64"!\n", + device_length); goto out; } // check the protocol version - if (!fread(&protocol_version, sizeof(int), 1, device)) { + if (TEMP_FAILURE_RETRY(read(device, &protocol_version, + sizeof(protocol_version))) != sizeof(protocol_version)) { ERROR("Couldn't read verity metadata protocol version!\n"); goto out; } @@ -196,43 +209,49 @@ static int read_verity_metadata(char *block_device, char **signature, char **tab } // get the signature - *signature = (char*) malloc(RSANUMBYTES * sizeof(char)); + *signature = (char*) malloc(RSANUMBYTES); if (!*signature) { ERROR("Couldn't allocate memory for signature!\n"); goto out; } - if (!fread(*signature, RSANUMBYTES, 1, device)) { + if (TEMP_FAILURE_RETRY(read(device, *signature, RSANUMBYTES)) != RSANUMBYTES) { ERROR("Couldn't read signature from verity metadata!\n"); - free(*signature); goto out; } // get the size of the table - if (!fread(&table_length, sizeof(int), 1, device)) { + if (TEMP_FAILURE_RETRY(read(device, &table_length, sizeof(table_length))) != + sizeof(table_length)) { ERROR("Couldn't get the size of the verity table from metadata!\n"); - free(*signature); goto out; } // get the table + null terminator - table_length += 1; - *table = malloc(table_length); - if(!*table) { + *table = malloc(table_length + 1); + if (!*table) { ERROR("Couldn't allocate memory for verity table!\n"); goto out; } - if (!fgets(*table, table_length, device)) { + if (TEMP_FAILURE_RETRY(read(device, *table, table_length)) != + (ssize_t)table_length) { ERROR("Couldn't read the verity table from metadata!\n"); - free(*table); - free(*signature); goto out; } - retval = 0; + (*table)[table_length] = 0; + retval = FS_MGR_SETUP_VERITY_SUCCESS; out: - if (device) - fclose(device); + if (device != -1) + TEMP_FAILURE_RETRY(close(device)); + + if (retval != FS_MGR_SETUP_VERITY_SUCCESS) { + free(*table); + free(*signature); + *table = 0; + *signature = 0; + } + return retval; } @@ -360,10 +379,11 @@ static int set_verified_property(char *name) { int fs_mgr_setup_verity(struct fstab_rec *fstab) { int retval = -1; + int fd = -1; - char *verity_blk_name; - char *verity_table; - char *verity_table_signature; + char *verity_blk_name = 0; + char *verity_table = 0; + char *verity_table_signature = 0; char buffer[DM_BUF_SIZE]; struct dm_ioctl *io = (struct dm_ioctl *) buffer; @@ -380,11 +400,19 @@ int fs_mgr_setup_verity(struct fstab_rec *fstab) { return retval; } + // read the verity block at the end of the block device + // send error code up the chain so we can detect attempts to disable verity + retval = read_verity_metadata(fstab->blk_device, + &verity_table_signature, + &verity_table); + if (retval < 0) { + goto out; + } + // get the device mapper fd - int fd; if ((fd = open("/dev/device-mapper", O_RDWR)) < 0) { ERROR("Error opening device mapper (%s)", strerror(errno)); - return retval; + goto out; } // create the device @@ -399,14 +427,6 @@ int fs_mgr_setup_verity(struct fstab_rec *fstab) { goto out; } - verity_table = verity_table_signature = NULL; - // read the verity block at the end of the block device - if (read_verity_metadata(fstab->blk_device, - &verity_table_signature, - &verity_table) < 0) { - goto out; - } - // verify the signature on the table if (verify_table(verity_table_signature, verity_table, @@ -427,6 +447,7 @@ int fs_mgr_setup_verity(struct fstab_rec *fstab) { // assign the new verity block device as the block device free(fstab->blk_device); fstab->blk_device = verity_blk_name; + verity_blk_name = 0; // make sure we've set everything up properly if (test_access(fstab->blk_device) < 0) { @@ -437,6 +458,13 @@ int fs_mgr_setup_verity(struct fstab_rec *fstab) { retval = set_verified_property(mount_point); out: - close(fd); + if (fd != -1) { + close(fd); + } + + free(verity_table); + free(verity_table_signature); + free(verity_blk_name); + return retval; } diff --git a/fs_mgr/include/fs_mgr.h b/fs_mgr/include/fs_mgr.h index 0c7eb20..5e2ff41 100644 --- a/fs_mgr/include/fs_mgr.h +++ b/fs_mgr/include/fs_mgr.h @@ -20,6 +20,13 @@ #include <stdint.h> #include <linux/dm-ioctl.h> +// Magic number at start of verity metadata +#define VERITY_METADATA_MAGIC_NUMBER 0xb001b001 + +// Replacement magic number at start of verity metadata to cleanly +// turn verity off in userdebug builds. +#define VERITY_METADATA_MAGIC_DISABLE 0x46464f56 // "VOFF" + #ifdef __cplusplus extern "C" { #endif @@ -74,6 +81,7 @@ int fs_mgr_add_entry(struct fstab *fstab, struct fstab_rec *fs_mgr_get_entry_for_mount_point(struct fstab *fstab, const char *path); int fs_mgr_is_voldmanaged(struct fstab_rec *fstab); int fs_mgr_is_nonremovable(struct fstab_rec *fstab); +int fs_mgr_is_verified(struct fstab_rec *fstab); int fs_mgr_is_encryptable(struct fstab_rec *fstab); int fs_mgr_is_noemulatedsd(struct fstab_rec *fstab); int fs_mgr_swapon_all(struct fstab *fstab); diff --git a/healthd/BatteryMonitor.cpp b/healthd/BatteryMonitor.cpp index 4a6b702..06497c2 100644 --- a/healthd/BatteryMonitor.cpp +++ b/healthd/BatteryMonitor.cpp @@ -389,7 +389,6 @@ void BatteryMonitor::init(struct healthd_config *hc) { if (!strcmp(name, ".") || !strcmp(name, "..")) continue; - char buf[20]; // Look for "type" file in each subdirectory path.clear(); path.appendFormat("%s/%s/type", POWER_SUPPLY_SYSFS_PATH, name); diff --git a/healthd/BatteryPropertiesRegistrar.cpp b/healthd/BatteryPropertiesRegistrar.cpp index 74bcbfd..09667a1 100644 --- a/healthd/BatteryPropertiesRegistrar.cpp +++ b/healthd/BatteryPropertiesRegistrar.cpp @@ -48,13 +48,13 @@ void BatteryPropertiesRegistrar::registerListener(const sp<IBatteryPropertiesLis Mutex::Autolock _l(mRegistrationLock); // check whether this is a duplicate for (size_t i = 0; i < mListeners.size(); i++) { - if (mListeners[i]->asBinder() == listener->asBinder()) { + if (IInterface::asBinder(mListeners[i]) == IInterface::asBinder(listener)) { return; } } mListeners.add(listener); - listener->asBinder()->linkToDeath(this); + IInterface::asBinder(listener)->linkToDeath(this); } healthd_battery_update(); } @@ -64,8 +64,8 @@ void BatteryPropertiesRegistrar::unregisterListener(const sp<IBatteryPropertiesL return; Mutex::Autolock _l(mRegistrationLock); for (size_t i = 0; i < mListeners.size(); i++) { - if (mListeners[i]->asBinder() == listener->asBinder()) { - mListeners[i]->asBinder()->unlinkToDeath(this); + if (IInterface::asBinder(mListeners[i]) == IInterface::asBinder(listener)) { + IInterface::asBinder(mListeners[i])->unlinkToDeath(this); mListeners.removeAt(i); break; } @@ -93,7 +93,7 @@ void BatteryPropertiesRegistrar::binderDied(const wp<IBinder>& who) { Mutex::Autolock _l(mRegistrationLock); for (size_t i = 0; i < mListeners.size(); i++) { - if (mListeners[i]->asBinder() == who) { + if (IInterface::asBinder(mListeners[i]) == who) { mListeners.removeAt(i); break; } diff --git a/healthd/healthd.cpp b/healthd/healthd.cpp index 30a4b42..b34583d 100644 --- a/healthd/healthd.cpp +++ b/healthd/healthd.cpp @@ -64,7 +64,6 @@ static int epollfd; #define MAX_EPOLL_EVENTS 40 static int uevent_fd; static int wakealarm_fd; -static int binder_fd; // -1 for no epoll timeout static int awake_poll_interval = -1; diff --git a/healthd/healthd_mode_charger.cpp b/healthd/healthd_mode_charger.cpp index 394feb8..291cb6c 100644 --- a/healthd/healthd_mode_charger.cpp +++ b/healthd/healthd_mode_charger.cpp @@ -350,7 +350,6 @@ static void reset_animation(struct animation *anim) static void update_screen_state(struct charger *charger, int64_t now) { struct animation *batt_anim = charger->batt_anim; - int cur_frame; int disp_time; if (!batt_anim->run || now < charger->next_screen_transition) @@ -393,7 +392,6 @@ static void update_screen_state(struct charger *charger, int64_t now) /* animation starting, set up the animation */ if (batt_anim->cur_frame == 0) { int batt_cap; - int ret; LOGV("[%" PRId64 "] animation starting\n", now); batt_cap = get_battery_capacity(); @@ -517,7 +515,6 @@ static void set_next_key_check(struct charger *charger, static void process_key(struct charger *charger, int code, int64_t now) { struct key_state *key = &charger->keys[code]; - int64_t next_key_check; if (code == KEY_POWER) { if (key->down) { @@ -590,7 +587,6 @@ void healthd_mode_charger_heartbeat() { struct charger *charger = &charger_state; int64_t now = curr_time_ms(); - int ret; handle_input_state(charger, now); handle_power_supply_state(charger, now); @@ -625,8 +621,6 @@ int healthd_mode_charger_preparetowait(void) int64_t now = curr_time_ms(); int64_t next_event = INT64_MAX; int64_t timeout; - struct input_event ev; - int ret; LOGV("[%" PRId64 "] next screen: %" PRId64 " next key: %" PRId64 " next pwr: %" PRId64 "\n", now, charger->next_screen_transition, charger->next_key_check, diff --git a/include/cutils/aref.h b/include/cutils/aref.h index 460ac02..3bd36ea 100644 --- a/include/cutils/aref.h +++ b/include/cutils/aref.h @@ -20,11 +20,7 @@ #include <stddef.h> #include <sys/cdefs.h> -#ifdef ANDROID_SMP -#include <cutils/atomic-inline.h> -#else #include <cutils/atomic.h> -#endif __BEGIN_DECLS diff --git a/include/cutils/atomic-inline.h b/include/cutils/atomic-inline.h deleted file mode 100644 index 103c5b0..0000000 --- a/include/cutils/atomic-inline.h +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (C) 2014 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_CUTILS_ATOMIC_H -#include <cutils/atomic.h> -#endif diff --git a/include/cutils/trace.h b/include/cutils/trace.h index c863afd..59ff6c1 100644 --- a/include/cutils/trace.h +++ b/include/cutils/trace.h @@ -25,12 +25,8 @@ #include <sys/types.h> #include <unistd.h> -#include <cutils/compiler.h> -#ifdef ANDROID_SMP -#include <cutils/atomic-inline.h> -#else #include <cutils/atomic.h> -#endif +#include <cutils/compiler.h> __BEGIN_DECLS diff --git a/include/log/uio.h b/include/log/uio.h index a71f515..7059da5 100644 --- a/include/log/uio.h +++ b/include/log/uio.h @@ -14,20 +14,23 @@ * limitations under the License. */ -// -// implementation of sys/uio.h for platforms that don't have it (Win32) -// #ifndef _LIBS_CUTILS_UIO_H #define _LIBS_CUTILS_UIO_H -#ifdef HAVE_SYS_UIO_H +#if !defined(_WIN32) + #include <sys/uio.h> + #else #ifdef __cplusplus extern "C" { #endif +// +// Implementation of sys/uio.h for Win32. +// + #include <stddef.h> struct iovec { @@ -42,7 +45,7 @@ extern int writev( int fd, const struct iovec* vecs, int count ); } #endif -#endif /* !HAVE_SYS_UIO_H */ +#endif #endif /* _LIBS_UTILS_UIO_H */ diff --git a/include/private/android_filesystem_config.h b/include/private/android_filesystem_config.h index b2f91a5..5efe2e1 100644 --- a/include/private/android_filesystem_config.h +++ b/include/private/android_filesystem_config.h @@ -232,7 +232,6 @@ static const struct fs_path_config android_files[] = { { 00550, AID_ROOT, AID_SHELL, 0, "system/etc/init.goldfish.sh" }, { 00440, AID_ROOT, AID_SHELL, 0, "system/etc/init.trout.rc" }, { 00550, AID_ROOT, AID_SHELL, 0, "system/etc/init.ril" }, - { 00550, AID_ROOT, AID_SHELL, 0, "system/etc/init.testmenu" }, { 00550, AID_DHCP, AID_SHELL, 0, "system/etc/dhcpcd/dhcpcd-run-hooks" }, { 00444, AID_RADIO, AID_AUDIO, 0, "system/etc/AudioPara4.csv" }, { 00555, AID_ROOT, AID_ROOT, 0, "system/etc/ppp/*" }, diff --git a/include/utils/Compat.h b/include/utils/Compat.h index 20a6920..0df40a1 100644 --- a/include/utils/Compat.h +++ b/include/utils/Compat.h @@ -44,6 +44,17 @@ static inline ssize_t pread64(int fd, void* buf, size_t nbytes, off64_t offset) #endif /* + * Needed for cases where something should be constexpr if possible, but not + * being constexpr is fine if in pre-C++11 code (such as a const static float + * member variable). + */ +#if __cplusplus >= 201103L +#define CONSTEXPR constexpr +#else +#define CONSTEXPR +#endif + +/* * TEMP_FAILURE_RETRY is defined by some, but not all, versions of * <unistd.h>. (Alas, it is not as standard as we'd hoped!) So, if it's * not already defined, then define it here. diff --git a/include/utils/Endian.h b/include/utils/Endian.h index 19f2504..591cae0 100644 --- a/include/utils/Endian.h +++ b/include/utils/Endian.h @@ -20,21 +20,16 @@ #ifndef _LIBS_UTILS_ENDIAN_H #define _LIBS_UTILS_ENDIAN_H -#if defined(HAVE_ENDIAN_H) - -#include <endian.h> - -#else /*not HAVE_ENDIAN_H*/ +#if defined(__APPLE__) || defined(_WIN32) #define __BIG_ENDIAN 0x1000 #define __LITTLE_ENDIAN 0x0001 +#define __BYTE_ORDER __LITTLE_ENDIAN -#if defined(HAVE_LITTLE_ENDIAN) -# define __BYTE_ORDER __LITTLE_ENDIAN #else -# define __BYTE_ORDER __BIG_ENDIAN -#endif -#endif /*not HAVE_ENDIAN_H*/ +#include <endian.h> + +#endif #endif /*_LIBS_UTILS_ENDIAN_H*/ diff --git a/init/Android.mk b/init/Android.mk index 72c2272..8cda879 100644 --- a/init/Android.mk +++ b/init/Android.mk @@ -51,25 +51,9 @@ LOCAL_STATIC_LIBRARIES := \ libmincrypt \ libext4_utils_static -LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk +# Create symlinks +LOCAL_POST_INSTALL_CMD := $(hide) mkdir -p $(TARGET_ROOT_OUT)/sbin; \ + ln -sf ../init $(TARGET_ROOT_OUT)/sbin/ueventd; \ + ln -sf ../init $(TARGET_ROOT_OUT)/sbin/watchdogd include $(BUILD_EXECUTABLE) - -# Make a symlink from /sbin/ueventd and /sbin/watchdogd to /init -SYMLINKS := \ - $(TARGET_ROOT_OUT)/sbin/ueventd \ - $(TARGET_ROOT_OUT)/sbin/watchdogd - -$(SYMLINKS): INIT_BINARY := $(LOCAL_MODULE) -$(SYMLINKS): $(LOCAL_INSTALLED_MODULE) $(LOCAL_PATH)/Android.mk - @echo "Symlink: $@ -> ../$(INIT_BINARY)" - @mkdir -p $(dir $@) - @rm -rf $@ - $(hide) ln -sf ../$(INIT_BINARY) $@ - -ALL_DEFAULT_INSTALLED_MODULES += $(SYMLINKS) - -# We need this so that the installed files could be picked up based on the -# local module name -ALL_MODULES.$(LOCAL_MODULE).INSTALLED := \ - $(ALL_MODULES.$(LOCAL_MODULE).INSTALLED) $(SYMLINKS) diff --git a/init/builtins.c b/init/builtins.c index 7f4daa7..5d2a517 100644 --- a/init/builtins.c +++ b/init/builtins.c @@ -501,7 +501,6 @@ int do_mount_all(int nargs, char **args) int ret = -1; int child_ret = -1; int status; - const char *prop; struct fstab *fstab; if (nargs != 2) { diff --git a/init/devices.c b/init/devices.c index a95111a..dde43df 100644 --- a/init/devices.c +++ b/init/devices.c @@ -191,7 +191,6 @@ static bool perm_path_matches(const char *path, struct perms_ *dp) static mode_t get_device_perm(const char *path, const char **links, unsigned *uid, unsigned *gid) { - mode_t perm; struct listnode *node; struct perm_node *perm_node; struct perms_ *dp; @@ -497,15 +496,10 @@ static char **get_block_device_symlinks(struct uevent *uevent) struct platform_node *pdev; char *slash; const char *type; - int width; char buf[256]; char link_path[256]; - int fd; int link_num = 0; - int ret; char *p; - unsigned int size; - struct stat info; pdev = find_platform_device(uevent->path); if (pdev) { @@ -926,7 +920,6 @@ root_free_out: static void handle_firmware_event(struct uevent *uevent) { pid_t pid; - int ret; if(strcmp(uevent->subsystem, "firmware")) return; @@ -1045,15 +1038,18 @@ void device_init(void) fcntl(device_fd, F_SETFD, FD_CLOEXEC); fcntl(device_fd, F_SETFL, O_NONBLOCK); - if (stat(coldboot_done, &info) < 0) { + if (stat(COLDBOOT_DONE, &info) < 0) { t0 = get_usecs(); coldboot("/sys/class"); coldboot("/sys/block"); coldboot("/sys/devices"); t1 = get_usecs(); - fd = open(coldboot_done, O_WRONLY|O_CREAT, 0000); + fd = open(COLDBOOT_DONE, O_WRONLY|O_CREAT, 0000); close(fd); log_event_print("coldboot %ld uS\n", ((long) (t1 - t0))); + // t0 & t1 are unused if the log isn't doing anything. + (void)t0; + (void)t1; } else { log_event_print("skipping coldboot, already done\n"); } diff --git a/init/init.c b/init/init.c index 99474e6..2b82937 100644 --- a/init/init.c +++ b/init/init.c @@ -76,7 +76,6 @@ static char qemu[32]; static struct action *cur_action = NULL; static struct command *cur_command = NULL; -static struct listnode *command_queue = NULL; void notify_service_state(const char *name, const char *state) { @@ -170,7 +169,6 @@ void service_start(struct service *svc, const char *dynamic_args) struct stat s; pid_t pid; int needs_console; - int n; char *scon = NULL; int rc; @@ -578,10 +576,10 @@ void execute_one_command(void) static int wait_for_coldboot_done_action(int nargs, char **args) { int ret; - INFO("wait for %s\n", coldboot_done); - ret = wait_for_file(coldboot_done, COMMAND_RETRY_TIMEOUT); + INFO("wait for %s\n", COLDBOOT_DONE); + ret = wait_for_file(COLDBOOT_DONE, COMMAND_RETRY_TIMEOUT); if (ret) - ERROR("Timed out waiting for %s\n", coldboot_done); + ERROR("Timed out waiting for %s\n", COLDBOOT_DONE); return ret; } @@ -1003,9 +1001,6 @@ int main(int argc, char **argv) { int fd_count = 0; struct pollfd ufds[4]; - char *tmpdev; - char* debuggable; - char tmp[32]; int property_set_fd_init = 0; int signal_fd_init = 0; int keychord_fd_init = 0; diff --git a/init/init_parser.c b/init/init_parser.c index 6466db2..2b4db8e 100644 --- a/init/init_parser.c +++ b/init/init_parser.c @@ -187,19 +187,14 @@ static int push_chars(char **dst, int *len, const char *chars, int cnt) int expand_props(char *dst, const char *src, int dst_size) { - int cnt = 0; char *dst_ptr = dst; const char *src_ptr = src; - int src_len; - int idx = 0; int ret = 0; int left = dst_size - 1; if (!src || !dst || dst_size == 0) return -1; - src_len = strlen(src); - /* - variables can either be $x.y or ${x.y}, in case they are only part * of the string. * - will accept $$ as a literal $. @@ -847,7 +842,6 @@ static void parse_line_action(struct parse_state* state, int nargs, char **args) { struct command *cmd; struct action *act = state->context; - int (*func)(int nargs, char **args); int kw, n; if (nargs == 0) { diff --git a/init/property_service.c b/init/property_service.c index 44658c5..1f98e13 100644 --- a/init/property_service.c +++ b/init/property_service.c @@ -63,7 +63,6 @@ typedef struct { static int init_workspace(workspace *w, size_t size) { - void *data; int fd = open(PROP_FILENAME, O_RDONLY | O_NOFOLLOW); if (fd < 0) return -1; @@ -142,9 +141,6 @@ static int check_control_mac_perms(const char *name, char *sctx) */ static int check_perms(const char *name, char *sctx) { - int i; - unsigned int app_id; - if(!strncmp(name, "ro.", 3)) name +=3; @@ -261,7 +257,6 @@ void handle_property_set_fd() prop_msg msg; int s; int r; - int res; struct ucred cr; struct sockaddr_un addr; socklen_t addr_size = sizeof(addr); diff --git a/init/util.h b/init/util.h index 04b8129..4cfe99d 100644 --- a/init/util.h +++ b/init/util.h @@ -22,7 +22,7 @@ #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) -static const char *coldboot_done = "/dev/.coldboot_done"; +#define COLDBOOT_DONE "/dev/.coldboot_done" int mtd_name_to_number(const char *name); int create_socket(const char *name, int type, mode_t perm, diff --git a/libcutils/Android.mk b/libcutils/Android.mk index 6987e9c..7202704 100644 --- a/libcutils/Android.mk +++ b/libcutils/Android.mk @@ -16,13 +16,6 @@ LOCAL_PATH := $(my-dir) include $(CLEAR_VARS) -ifeq ($(TARGET_CPU_SMP),true) - targetSmpFlag := -DANDROID_SMP=1 -else - targetSmpFlag := -DANDROID_SMP=0 -endif -hostSmpFlag := -DANDROID_SMP=0 - commonSources := \ hashmap.c \ atomic.c.arm \ @@ -77,7 +70,6 @@ endif LOCAL_MODULE := libcutils LOCAL_SRC_FILES := $(commonSources) $(commonHostSources) dlmalloc_stubs.c LOCAL_STATIC_LIBRARIES := liblog -LOCAL_CFLAGS += $(hostSmpFlag) ifneq ($(HOST_OS),windows) LOCAL_CFLAGS += -Werror endif @@ -154,7 +146,7 @@ LOCAL_CFLAGS_x86_64 += -DHAVE_MEMSET16 -DHAVE_MEMSET32 LOCAL_C_INCLUDES := $(libcutils_c_includes) LOCAL_STATIC_LIBRARIES := liblog -LOCAL_CFLAGS += $(targetSmpFlag) -Werror -std=gnu90 +LOCAL_CFLAGS += -Werror -std=gnu90 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk include $(BUILD_STATIC_LIBRARY) @@ -164,7 +156,7 @@ LOCAL_MODULE := libcutils # liblog symbols present in libcutils. LOCAL_WHOLE_STATIC_LIBRARIES := libcutils liblog LOCAL_SHARED_LIBRARIES := liblog -LOCAL_CFLAGS += $(targetSmpFlag) -Werror +LOCAL_CFLAGS += -Werror LOCAL_C_INCLUDES := $(libcutils_c_includes) LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk include $(BUILD_SHARED_LIBRARY) diff --git a/libcutils/socket_local_client.c b/libcutils/socket_local_client.c index ddcc2da..7b42daa 100644 --- a/libcutils/socket_local_client.c +++ b/libcutils/socket_local_client.c @@ -52,7 +52,7 @@ int socket_make_sockaddr_un(const char *name, int namespaceId, switch (namespaceId) { case ANDROID_SOCKET_NAMESPACE_ABSTRACT: -#ifdef HAVE_LINUX_LOCAL_SOCKET_NAMESPACE +#if defined(__linux__) namelen = strlen(name); // Test with length +1 for the *initial* '\0'. @@ -67,7 +67,7 @@ int socket_make_sockaddr_un(const char *name, int namespaceId, p_addr->sun_path[0] = 0; memcpy(p_addr->sun_path + 1, name, namelen); -#else /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/ +#else /* this OS doesn't have the Linux abstract namespace */ namelen = strlen(name) + strlen(FILESYSTEM_SOCKET_PREFIX); @@ -79,7 +79,7 @@ int socket_make_sockaddr_un(const char *name, int namespaceId, strcpy(p_addr->sun_path, FILESYSTEM_SOCKET_PREFIX); strcat(p_addr->sun_path, name); -#endif /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/ +#endif break; case ANDROID_SOCKET_NAMESPACE_RESERVED: diff --git a/libcutils/socket_local_server.c b/libcutils/socket_local_server.c index 7628fe4..60eb86b 100644 --- a/libcutils/socket_local_server.c +++ b/libcutils/socket_local_server.c @@ -66,7 +66,7 @@ int socket_local_server_bind(int s, const char *name, int namespaceId) } /* basically: if this is a filesystem path, unlink first */ -#ifndef HAVE_LINUX_LOCAL_SOCKET_NAMESPACE +#if !defined(__linux__) if (1) { #else if (namespaceId == ANDROID_SOCKET_NAMESPACE_RESERVED diff --git a/libcutils/socket_network_client.c b/libcutils/socket_network_client.c index 4826033..e0031ba 100644 --- a/libcutils/socket_network_client.c +++ b/libcutils/socket_network_client.c @@ -45,7 +45,6 @@ int socket_network_client_timeout(const char *host, int port, int type, int time { struct hostent *hp; struct sockaddr_in addr; - socklen_t alen; int s; int flags = 0, error = 0, ret = 0; fd_set rset, wset; diff --git a/libion/ion.c b/libion/ion.c index 80bdc2a..a79525d 100644 --- a/libion/ion.c +++ b/libion/ion.c @@ -117,7 +117,6 @@ int ion_map(int fd, ion_user_handle_t handle, size_t length, int prot, int ion_share(int fd, ion_user_handle_t handle, int *share_fd) { - int map_fd; int ret; struct ion_fd_data data = { .handle = handle, diff --git a/libion/ion_test.c b/libion/ion_test.c index 8872282..b7d5583 100644 --- a/libion/ion_test.c +++ b/libion/ion_test.c @@ -164,8 +164,9 @@ void ion_share_test() printf("master->master? [%10s]\n", ptr); if (recvmsg(sd[0], &msg, 0) < 0) perror("master recv 1"); + close(fd); + _exit(0); } else { - struct msghdr msg; struct cmsghdr *cmsg; char* ptr; int fd, recv_fd; @@ -205,6 +206,7 @@ void ion_share_test() strcpy(ptr, "child"); printf("child sending msg 2\n"); sendmsg(sd[1], &child_msg, 0); + close(fd); } } diff --git a/liblog/fake_log_device.c b/liblog/fake_log_device.c index b8d87bb..117e154 100644 --- a/liblog/fake_log_device.c +++ b/liblog/fake_log_device.c @@ -320,9 +320,9 @@ static const char* getPriorityString(int priority) return priorityStrings[idx]; } -#ifndef HAVE_WRITEV +#if defined(_WIN32) /* - * Some platforms like WIN32 do not have writev(). + * WIN32 does not have writev(). * Make up something to replace it. */ static ssize_t fake_writev(int fd, const struct iovec *iov, int iovcnt) { diff --git a/liblog/log_read.c b/liblog/log_read.c index ca5a1a7..2f21a5d 100644 --- a/liblog/log_read.c +++ b/liblog/log_read.c @@ -72,7 +72,7 @@ int WEAK socket_make_sockaddr_un(const char *name, int namespaceId, switch (namespaceId) { case ANDROID_SOCKET_NAMESPACE_ABSTRACT: -#ifdef HAVE_LINUX_LOCAL_SOCKET_NAMESPACE +#if defined(__linux__) namelen = strlen(name); /* Test with length +1 for the *initial* '\0'. */ @@ -87,7 +87,7 @@ int WEAK socket_make_sockaddr_un(const char *name, int namespaceId, p_addr->sun_path[0] = 0; memcpy(p_addr->sun_path + 1, name, namelen); -#else /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/ +#else /* this OS doesn't have the Linux abstract namespace */ namelen = strlen(name) + strlen(FILESYSTEM_SOCKET_PREFIX); @@ -99,7 +99,7 @@ int WEAK socket_make_sockaddr_un(const char *name, int namespaceId, strcpy(p_addr->sun_path, FILESYSTEM_SOCKET_PREFIX); strcat(p_addr->sun_path, name); -#endif /*HAVE_LINUX_LOCAL_SOCKET_NAMESPACE*/ +#endif break; case ANDROID_SOCKET_NAMESPACE_RESERVED: diff --git a/liblog/logprint.c b/liblog/logprint.c index 9b5a543..5987782 100644 --- a/liblog/logprint.c +++ b/liblog/logprint.c @@ -344,15 +344,6 @@ error: return -1; } -static inline char * strip_end(char *str) -{ - char *end = str + strlen(str) - 1; - - while (end >= str && isspace(*end)) - *end-- = '\0'; - return str; -} - /** * Splits a wire-format buffer into an AndroidLogEntry * entry allocated by caller. Pointers will point directly into buf diff --git a/liblog/uio.c b/liblog/uio.c index 24a6507..f77cc49 100644 --- a/liblog/uio.c +++ b/liblog/uio.c @@ -14,7 +14,7 @@ * limitations under the License. */ -#ifndef HAVE_SYS_UIO_H +#if defined(_WIN32) #include <log/uio.h> #include <unistd.h> @@ -73,4 +73,4 @@ Exit: return total; } -#endif /* !HAVE_SYS_UIO_H */ +#endif diff --git a/libnetutils/dhcp_utils.c b/libnetutils/dhcp_utils.c index e1df874..0f7c384 100644 --- a/libnetutils/dhcp_utils.c +++ b/libnetutils/dhcp_utils.c @@ -166,14 +166,6 @@ static int fill_ip_info(const char *interface, return 0; } -static const char *ipaddr_to_string(in_addr_t addr) -{ - struct in_addr in_addr; - - in_addr.s_addr = addr; - return inet_ntoa(in_addr); -} - /* * Start the dhcp client daemon, and wait for it to finish * configuring the interface. @@ -242,7 +234,6 @@ int dhcp_do_request(const char *interface, return -1; } if (strcmp(prop_value, "ok") == 0) { - char dns_prop_name[PROPERTY_KEY_MAX]; if (fill_ip_info(interface, ipaddr, gateway, prefixLength, dns, server, lease, vendorInfo, domain, mtu) == -1) { return -1; diff --git a/libnetutils/dhcpclient.c b/libnetutils/dhcpclient.c index b58120e..700b02f 100644 --- a/libnetutils/dhcpclient.c +++ b/libnetutils/dhcpclient.c @@ -150,7 +150,7 @@ static const char *dhcp_type_to_name(uint32_t type) void dump_dhcp_info(dhcp_info *info) { - char addr[20], gway[20], mask[20]; + char addr[20], gway[20]; ALOGD("--- dhcp %s (%d) ---", dhcp_type_to_name(info->type), info->type); strcpy(addr, ipaddr(info->ipaddr)); diff --git a/libnetutils/ifc_utils.c b/libnetutils/ifc_utils.c index 913f51e..bfe7121 100644 --- a/libnetutils/ifc_utils.c +++ b/libnetutils/ifc_utils.c @@ -421,7 +421,6 @@ int ifc_clear_addresses(const char *name) { int ifc_set_hwaddr(const char *name, const void *ptr) { - int r; struct ifreq ifr; ifc_init_ifr(name, &ifr); diff --git a/libnetutils/packet.c b/libnetutils/packet.c index 3cdefb0..a878dd3 100644 --- a/libnetutils/packet.c +++ b/libnetutils/packet.c @@ -41,7 +41,7 @@ int fatal(); int open_raw_socket(const char *ifname __attribute__((unused)), uint8_t *hwaddr, int if_index) { - int s, flag; + int s; struct sockaddr_ll bindaddr; if((s = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IP))) < 0) { diff --git a/libpixelflinger/Android.mk b/libpixelflinger/Android.mk index da9829d..f1bd522 100644 --- a/libpixelflinger/Android.mk +++ b/libpixelflinger/Android.mk @@ -36,6 +36,7 @@ PIXELFLINGER_SRC_FILES_arm := \ ifeq ($(ARCH_ARM_HAVE_NEON),true) PIXELFLINGER_SRC_FILES_arm += col32cb16blend_neon.S +PIXELFLINGER_CFLAGS_arm += -D__ARM_HAVE_NEON endif PIXELFLINGER_SRC_FILES_arm64 := \ diff --git a/libpixelflinger/codeflinger/load_store.cpp b/libpixelflinger/codeflinger/load_store.cpp index 0a46eaa..e5a1ae0 100644 --- a/libpixelflinger/codeflinger/load_store.cpp +++ b/libpixelflinger/codeflinger/load_store.cpp @@ -20,10 +20,6 @@ #include <cutils/log.h> #include "GGLAssembler.h" -#ifdef __ARM_ARCH__ -#include <machine/cpu-features.h> -#endif - namespace android { // ---------------------------------------------------------------------------- @@ -117,20 +113,6 @@ void GGLAssembler::extract(integer_t& d, int s, int h, int l, int bits) #endif assert(h); -#if __ARM_ARCH__ >= 7 - const int mask = (1<<maskLen)-1; - if ((h == bits) && !l && (s != d.reg)) { - MOV(AL, 0, d.reg, s); // component = packed; - } else if ((h == bits) && l) { - MOV(AL, 0, d.reg, reg_imm(s, LSR, l)); // component = packed >> l; - } else if (!l && isValidImmediate(mask)) { - AND(AL, 0, d.reg, s, imm(mask)); // component = packed & mask; - } else if (!l && isValidImmediate(~mask)) { - BIC(AL, 0, d.reg, s, imm(~mask)); // component = packed & mask; - } else { - UBFX(AL, d.reg, s, l, maskLen); // component = (packed & mask) >> l; - } -#else if (h != bits) { const int mask = ((1<<maskLen)-1) << l; if (isValidImmediate(mask)) { @@ -153,7 +135,6 @@ void GGLAssembler::extract(integer_t& d, int s, int h, int l, int bits) if (s != d.reg) { MOV(AL, 0, d.reg, s); } -#endif d.s = maskLen; } diff --git a/libpixelflinger/codeflinger/texturing.cpp b/libpixelflinger/codeflinger/texturing.cpp index 81950bf..29a3742 100644 --- a/libpixelflinger/codeflinger/texturing.cpp +++ b/libpixelflinger/codeflinger/texturing.cpp @@ -25,10 +25,6 @@ #include "GGLAssembler.h" -#ifdef __ARM_ARCH__ -#include <machine/cpu-features.h> -#endif - namespace android { // --------------------------------------------------------------------------- @@ -888,106 +884,6 @@ void GGLAssembler::filter24( load(txPtr, texel, 0); } -#if __ARM_ARCH__ >= 6 -// ARMv6 version, using UXTB16, and scheduled for Cortex-A8 pipeline -void GGLAssembler::filter32( - const fragment_parts_t& parts, - pixel_t& texel, const texture_unit_t& tmu, - int U, int V, pointer_t& txPtr, - int FRAC_BITS) -{ - const int adjust = FRAC_BITS*2 - 8; - const int round = 0; - const int prescale = 16 - adjust; - - Scratch scratches(registerFile()); - - int pixel= scratches.obtain(); - int dh = scratches.obtain(); - int u = scratches.obtain(); - int k = scratches.obtain(); - - int temp = scratches.obtain(); - int dl = scratches.obtain(); - - int offsetrt = scratches.obtain(); - int offsetlb = scratches.obtain(); - - int pixellb = offsetlb; - - // RB -> U * V - CONTEXT_LOAD(offsetrt, generated_vars.rt); - CONTEXT_LOAD(offsetlb, generated_vars.lb); - if(!round) { - MOV(AL, 0, U, reg_imm(U, LSL, prescale)); - } - ADD(AL, 0, u, offsetrt, offsetlb); - - LDR(AL, pixel, txPtr.reg, reg_scale_pre(u)); - if (round) { - SMULBB(AL, u, U, V); - RSB(AL, 0, U, U, imm(1<<FRAC_BITS)); - } else { - SMULWB(AL, u, U, V); - RSB(AL, 0, U, U, imm(1<<(FRAC_BITS+prescale))); - } - UXTB16(AL, temp, pixel, 0); - if (round) { - ADD(AL, 0, u, u, imm(1<<(adjust-1))); - MOV(AL, 0, u, reg_imm(u, LSR, adjust)); - } - LDR(AL, pixellb, txPtr.reg, reg_scale_pre(offsetlb)); - MUL(AL, 0, dh, temp, u); - UXTB16(AL, temp, pixel, 8); - MUL(AL, 0, dl, temp, u); - RSB(AL, 0, k, u, imm(0x100)); - - // LB -> (1-U) * V - if (round) { - SMULBB(AL, u, U, V); - } else { - SMULWB(AL, u, U, V); - } - UXTB16(AL, temp, pixellb, 0); - if (round) { - ADD(AL, 0, u, u, imm(1<<(adjust-1))); - MOV(AL, 0, u, reg_imm(u, LSR, adjust)); - } - MLA(AL, 0, dh, temp, u, dh); - UXTB16(AL, temp, pixellb, 8); - MLA(AL, 0, dl, temp, u, dl); - SUB(AL, 0, k, k, u); - - // LT -> (1-U)*(1-V) - RSB(AL, 0, V, V, imm(1<<FRAC_BITS)); - LDR(AL, pixel, txPtr.reg); - if (round) { - SMULBB(AL, u, U, V); - } else { - SMULWB(AL, u, U, V); - } - UXTB16(AL, temp, pixel, 0); - if (round) { - ADD(AL, 0, u, u, imm(1<<(adjust-1))); - MOV(AL, 0, u, reg_imm(u, LSR, adjust)); - } - MLA(AL, 0, dh, temp, u, dh); - UXTB16(AL, temp, pixel, 8); - MLA(AL, 0, dl, temp, u, dl); - - // RT -> U*(1-V) - LDR(AL, pixel, txPtr.reg, reg_scale_pre(offsetrt)); - SUB(AL, 0, u, k, u); - UXTB16(AL, temp, pixel, 0); - MLA(AL, 0, dh, temp, u, dh); - UXTB16(AL, temp, pixel, 8); - MLA(AL, 0, dl, temp, u, dl); - - UXTB16(AL, dh, dh, 8); - UXTB16(AL, dl, dl, 8); - ORR(AL, 0, texel.reg, dh, reg_imm(dl, LSL, 8)); -} -#else void GGLAssembler::filter32( const fragment_parts_t& /*parts*/, pixel_t& texel, const texture_unit_t& /*tmu*/, @@ -1075,7 +971,6 @@ void GGLAssembler::filter32( AND(AL, 0, dl, dl, reg_imm(mask, LSL, 8)); ORR(AL, 0, texel.reg, dh, dl); } -#endif void GGLAssembler::build_texture_environment( component_t& fragment, diff --git a/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp b/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp index fd96f7e..5f58797 100644 --- a/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp +++ b/libpixelflinger/tests/arch-arm64/assembler/arm64_assembler_test.cpp @@ -493,16 +493,17 @@ void dataOpTest(dataOpTest_t test, ARMAssemblerInterface *a64asm, uint32_t Rd = if(i == Rd) continue; if(regs[i] != savedRegs[i]) { - printf("Test %x failed Reg(%d) tampered Expected(0x%"PRIx64")," - "Actual(0x%"PRIx64") t\n", test.id, i, savedRegs[i], regs[i]); + printf("Test %x failed Reg(%d) tampered Expected(0x%" PRIx64 ")," + "Actual(0x%" PRIx64 ") t\n", test.id, i, savedRegs[i], + regs[i]); return; } } if(test.checkRd == 1 && (uint64_t)regs[Rd] != test.postRdValue) { - printf("Test %x failed, Expected(%"PRIx64"), Actual(%"PRIx64")\n", - test.id, test.postRdValue, regs[Rd]); + printf("Test %x failed, Expected(%" PRIx64 "), Actual(%" PRIx64 ")\n", + test.id, test.postRdValue, regs[Rd]); } else if(test.checkFlag == 1 && flags[test.postFlag] == 0) { @@ -610,7 +611,7 @@ void dataTransferTest(dataTransferTest_t test, ARMAssemblerInterface *a64asm, if(regs[i] != savedRegs[i]) { printf("Test %x failed Reg(%d) tampered" - " Expected(0x%"PRIx64"), Actual(0x%"PRIx64") t\n", + " Expected(0x%" PRIx64 "), Actual(0x%" PRIx64 ") t\n", test.id, i, savedRegs[i], regs[i]); return; } @@ -619,13 +620,13 @@ void dataTransferTest(dataTransferTest_t test, ARMAssemblerInterface *a64asm, if((uint64_t)regs[Rd] != test.postRdValue) { printf("Test %x failed, " - "Expected in Rd(0x%"PRIx64"), Actual(0x%"PRIx64")\n", + "Expected in Rd(0x%" PRIx64 "), Actual(0x%" PRIx64 ")\n", test.id, test.postRdValue, regs[Rd]); } else if((uint64_t)regs[Rn] != (uint64_t)(&dataMem[test.postRnValue])) { printf("Test %x failed, " - "Expected in Rn(0x%"PRIx64"), Actual(0x%"PRIx64")\n", + "Expected in Rn(0x%" PRIx64 "), Actual(0x%" PRIx64 ")\n", test.id, test.postRnValue, regs[Rn] - (uint64_t)dataMem); } else if(test.checkMem == true) @@ -638,7 +639,7 @@ void dataTransferTest(dataTransferTest_t test, ARMAssemblerInterface *a64asm, if(value != test.postMemValue) { printf("Test %x failed, " - "Expected in Mem(0x%"PRIx64"), Actual(0x%"PRIx64")\n", + "Expected in Mem(0x%" PRIx64 "), Actual(0x%" PRIx64 ")\n", test.id, test.postMemValue, value); } else @@ -697,8 +698,8 @@ void dataTransferLDMSTM(ARMAssemblerInterface *a64asm) if(regs[j] != j) { printf("LDM/STM Test %x failed " - "Reg%d expected(0x%x) Actual(0x%"PRIx64") \n", - patterns[i],j,j,regs[j]); + "Reg%d expected(0x%x) Actual(0x%" PRIx64 ") \n", + patterns[i], j, j, regs[j]); break; } } diff --git a/libprocessgroup/processgroup.cpp b/libprocessgroup/processgroup.cpp index 49f5903..4b09f24 100644 --- a/libprocessgroup/processgroup.cpp +++ b/libprocessgroup/processgroup.cpp @@ -20,6 +20,7 @@ #include <assert.h> #include <dirent.h> #include <fcntl.h> +#include <inttypes.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> @@ -100,7 +101,7 @@ static int refillBuffer(struct ctx *ctx) ctx->buf_len += ret; ctx->buf[ctx->buf_len] = 0; - SLOGV("Read %d to buffer: %s", ret, ctx->buf); + SLOGV("Read %zd to buffer: %s", ret, ctx->buf); assert(ctx->buf_len <= sizeof(ctx->buf)); @@ -251,7 +252,7 @@ int killProcessGroup(uid_t uid, int initialPid, int signal) { int processes; int sleep_us = 100; - long startTime = android::uptimeMillis(); + int64_t startTime = android::uptimeMillis(); while ((processes = killProcessGroupOnce(uid, initialPid, signal)) > 0) { SLOGV("killed %d processes for processgroup %d\n", processes, initialPid); @@ -265,7 +266,7 @@ int killProcessGroup(uid_t uid, int initialPid, int signal) } } - SLOGV("Killed process group uid %d pid %d in %ldms, %d procs remain", uid, initialPid, + SLOGV("Killed process group uid %d pid %d in %" PRId64 "ms, %d procs remain", uid, initialPid, android::uptimeMillis()-startTime, processes); if (processes == 0) { @@ -279,12 +280,12 @@ static int mkdirAndChown(const char *path, mode_t mode, uid_t uid, gid_t gid) { int ret; - ret = mkdir(path, 0750); + ret = mkdir(path, mode); if (ret < 0 && errno != EEXIST) { return -errno; } - ret = chown(path, AID_SYSTEM, AID_SYSTEM); + ret = chown(path, uid, gid); if (ret < 0) { ret = -errno; rmdir(path); diff --git a/libsuspend/autosuspend_autosleep.c b/libsuspend/autosuspend_autosleep.c index 5451615..0d31e74 100644 --- a/libsuspend/autosuspend_autosleep.c +++ b/libsuspend/autosuspend_autosleep.c @@ -84,7 +84,6 @@ struct autosuspend_ops autosuspend_autosleep_ops = { struct autosuspend_ops *autosuspend_autosleep_init(void) { - int ret; char buf[80]; autosleep_fd = open(SYS_POWER_AUTOSLEEP, O_WRONLY); diff --git a/libutils/Android.mk b/libutils/Android.mk index e738c15..52de910 100644 --- a/libutils/Android.mk +++ b/libutils/Android.mk @@ -53,13 +53,6 @@ host_commonCflags += -DMB_CUR_MAX=1 endif endif -host_commonLdlibs := - -ifeq ($(TARGET_OS),linux) -host_commonLdlibs += -lrt -ldl -endif - - # For the host # ===================================================== include $(CLEAR_VARS) @@ -93,9 +86,6 @@ LOCAL_CFLAGS += -DALIGN_DOUBLE endif LOCAL_CFLAGS += -Werror -LOCAL_C_INCLUDES += \ - external/zlib - LOCAL_STATIC_LIBRARIES := \ libcutils diff --git a/libutils/FileMap.cpp b/libutils/FileMap.cpp index 6d92f74..f49b4f9 100644 --- a/libutils/FileMap.cpp +++ b/libutils/FileMap.cpp @@ -194,9 +194,9 @@ try_again: } // Provide guidance to the system. +#if !defined(_WIN32) int FileMap::advise(MapAdvice advice) { -#if HAVE_MADVISE int cc, sysAdvice; switch (advice) { @@ -214,7 +214,11 @@ int FileMap::advise(MapAdvice advice) if (cc != 0) ALOGW("madvise(%d) failed: %s\n", sysAdvice, strerror(errno)); return cc; +} + #else +int FileMap::advise(MapAdvice /* advice */) +{ return -1; -#endif // HAVE_MADVISE } +#endif diff --git a/libutils/SystemClock.cpp b/libutils/SystemClock.cpp index dbad581..ac3dd98 100644 --- a/libutils/SystemClock.cpp +++ b/libutils/SystemClock.cpp @@ -68,7 +68,7 @@ int64_t elapsedRealtime() */ #define DEBUG_TIMESTAMP 0 -#if DEBUG_TIMESTAMP && defined(ARCH_ARM) +#if DEBUG_TIMESTAMP && defined(__arm__) static inline void checkTimeStamps(int64_t timestamp, int64_t volatile *prevTimestampPtr, int volatile *prevMethodPtr, diff --git a/libutils/Unicode.cpp b/libutils/Unicode.cpp index 378d2a7..fb876c9 100644 --- a/libutils/Unicode.cpp +++ b/libutils/Unicode.cpp @@ -24,17 +24,10 @@ # undef nhtos # undef htons -# ifdef HAVE_LITTLE_ENDIAN -# define ntohl(x) ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) ) -# define htonl(x) ntohl(x) -# define ntohs(x) ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) ) -# define htons(x) ntohs(x) -# else -# define ntohl(x) (x) -# define htonl(x) (x) -# define ntohs(x) (x) -# define htons(x) (x) -# endif +# define ntohl(x) ( ((x) << 24) | (((x) >> 24) & 255) | (((x) << 8) & 0xff0000) | (((x) >> 8) & 0xff00) ) +# define htonl(x) ntohl(x) +# define ntohs(x) ( (((x) << 8) & 0xff00) | (((x) >> 8) & 255) ) +# define htons(x) ntohs(x) #else # include <netinet/in.h> #endif @@ -47,8 +40,9 @@ static const char32_t kByteMark = 0x00000080; // Surrogates aren't valid for UTF-32 characters, so define some // constants that will let us screen them out. static const char32_t kUnicodeSurrogateHighStart = 0x0000D800; -static const char32_t kUnicodeSurrogateHighEnd = 0x0000DBFF; -static const char32_t kUnicodeSurrogateLowStart = 0x0000DC00; +// Unused, here for completeness: +// static const char32_t kUnicodeSurrogateHighEnd = 0x0000DBFF; +// static const char32_t kUnicodeSurrogateLowStart = 0x0000DC00; static const char32_t kUnicodeSurrogateLowEnd = 0x0000DFFF; static const char32_t kUnicodeSurrogateStart = kUnicodeSurrogateHighStart; static const char32_t kUnicodeSurrogateEnd = kUnicodeSurrogateLowEnd; diff --git a/libziparchive/Android.mk b/libziparchive/Android.mk index 9bc6e61..ba7b74d 100644 --- a/libziparchive/Android.mk +++ b/libziparchive/Android.mk @@ -16,7 +16,6 @@ LOCAL_PATH := $(call my-dir) source_files := zip_archive.cc -includes := external/zlib include $(CLEAR_VARS) LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk @@ -25,16 +24,13 @@ LOCAL_SRC_FILES := ${source_files} LOCAL_STATIC_LIBRARIES := libz LOCAL_SHARED_LIBRARIES := libutils LOCAL_MODULE:= libziparchive -LOCAL_C_INCLUDES += ${includes} LOCAL_CFLAGS := -Werror include $(BUILD_STATIC_LIBRARY) include $(CLEAR_VARS) LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk -LOCAL_MODULE := libziparchive LOCAL_CPP_EXTENSION := .cc LOCAL_SRC_FILES := ${source_files} -LOCAL_C_INCLUDES += ${includes} LOCAL_STATIC_LIBRARIES := libz libutils LOCAL_MODULE:= libziparchive-host LOCAL_CFLAGS := -Werror @@ -46,10 +42,8 @@ include $(BUILD_HOST_STATIC_LIBRARY) include $(CLEAR_VARS) LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk -LOCAL_MODULE := libziparchive LOCAL_CPP_EXTENSION := .cc LOCAL_SRC_FILES := ${source_files} -LOCAL_C_INCLUDES += ${includes} LOCAL_STATIC_LIBRARIES := libz libutils LOCAL_SHARED_LIBRARIES := liblog LOCAL_MODULE:= libziparchive-host @@ -63,7 +57,7 @@ LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk LOCAL_MODULE := ziparchive-tests LOCAL_CPP_EXTENSION := .cc LOCAL_CFLAGS := -Werror -LOCAL_SRC_FILES := zip_archive_test.cc +LOCAL_SRC_FILES := zip_archive_test.cc entry_name_utils_test.cc LOCAL_SHARED_LIBRARIES := liblog LOCAL_STATIC_LIBRARIES := libziparchive libz libutils include $(BUILD_NATIVE_TEST) @@ -75,7 +69,7 @@ LOCAL_CPP_EXTENSION := .cc LOCAL_CFLAGS += \ -Werror \ -Wno-unnamed-type-template-args -LOCAL_SRC_FILES := zip_archive_test.cc +LOCAL_SRC_FILES := zip_archive_test.cc entry_name_utils_test.cc LOCAL_SHARED_LIBRARIES := libziparchive-host liblog LOCAL_STATIC_LIBRARIES := \ libz \ diff --git a/libziparchive/entry_name_utils-inl.h b/libziparchive/entry_name_utils-inl.h new file mode 100644 index 0000000..ddbc286 --- /dev/null +++ b/libziparchive/entry_name_utils-inl.h @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2014 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 LIBZIPARCHIVE_ENTRY_NAME_UTILS_INL_H_ +#define LIBZIPARCHIVE_ENTRY_NAME_UTILS_INL_H_ + +#include <stddef.h> +#include <stdint.h> + +// Check if |length| bytes at |entry_name| constitute a valid entry name. +// Entry names must be valid UTF-8 and must not contain '0'. +inline bool IsValidEntryName(const uint8_t* entry_name, const size_t length) { + for (size_t i = 0; i < length; ++i) { + const uint8_t byte = entry_name[i]; + if (byte == 0) { + return false; + } else if ((byte & 0x80) == 0) { + // Single byte sequence. + continue; + } else if ((byte & 0xc0) == 0x80 || (byte & 0xfe) == 0xfe) { + // Invalid sequence. + return false; + } else { + // 2-5 byte sequences. + for (uint8_t first = byte << 1; first & 0x80; first <<= 1) { + ++i; + + // Missing continuation byte.. + if (i == length) { + return false; + } + + // Invalid continuation byte. + const uint8_t continuation_byte = entry_name[i]; + if ((continuation_byte & 0xc0) != 0x80) { + return false; + } + } + } + } + + return true; +} + + +#endif // LIBZIPARCHIVE_ENTRY_NAME_UTILS_INL_H_ diff --git a/libziparchive/entry_name_utils_test.cc b/libziparchive/entry_name_utils_test.cc new file mode 100644 index 0000000..20715bb --- /dev/null +++ b/libziparchive/entry_name_utils_test.cc @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2014 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 "entry_name_utils-inl.h" + +#include <gtest/gtest.h> + +TEST(entry_name_utils, NullChars) { + // 'A', 'R', '\0', 'S', 'E' + const uint8_t zeroes[] = { 0x41, 0x52, 0x00, 0x53, 0x45 }; + ASSERT_FALSE(IsValidEntryName(zeroes, sizeof(zeroes))); + + const uint8_t zeroes_continuation_chars[] = { 0xc2, 0xa1, 0xc2, 0x00 }; + ASSERT_FALSE(IsValidEntryName(zeroes_continuation_chars, + sizeof(zeroes_continuation_chars))); +} + +TEST(entry_name_utils, InvalidSequence) { + // 0xfe is an invalid start byte + const uint8_t invalid[] = { 0x41, 0xfe }; + ASSERT_FALSE(IsValidEntryName(invalid, sizeof(invalid))); + + // 0x91 is an invalid start byte (it's a valid continuation byte). + const uint8_t invalid2[] = { 0x41, 0x91 }; + ASSERT_FALSE(IsValidEntryName(invalid2, sizeof(invalid2))); +} + +TEST(entry_name_utils, TruncatedContinuation) { + // Malayalam script with truncated bytes. There should be 2 bytes + // after 0xe0 + const uint8_t truncated[] = { 0xe0, 0xb4, 0x85, 0xe0, 0xb4 }; + ASSERT_FALSE(IsValidEntryName(truncated, sizeof(truncated))); + + // 0xc2 is the start of a 2 byte sequence that we've subsequently + // dropped. + const uint8_t truncated2[] = { 0xc2, 0xc2, 0xa1 }; + ASSERT_FALSE(IsValidEntryName(truncated2, sizeof(truncated2))); +} + +TEST(entry_name_utils, BadContinuation) { + // 0x41 is an invalid continuation char, since it's MSBs + // aren't "10..." (are 01). + const uint8_t bad[] = { 0xc2, 0xa1, 0xc2, 0x41 }; + ASSERT_FALSE(IsValidEntryName(bad, sizeof(bad))); + + // 0x41 is an invalid continuation char, since it's MSBs + // aren't "10..." (are 11). + const uint8_t bad2[] = { 0xc2, 0xa1, 0xc2, 0xfe }; + ASSERT_FALSE(IsValidEntryName(bad2, sizeof(bad2))); +} diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc index d5d4700..b6fd0d2 100644 --- a/libziparchive/zip_archive.cc +++ b/libziparchive/zip_archive.cc @@ -33,8 +33,10 @@ #include <JNIHelp.h> // TEMP_FAILURE_RETRY may or may not be in unistd +#include "entry_name_utils-inl.h" #include "ziparchive/zip_archive.h" + // This is for windows. If we don't open a file in binary mode, weird // things will happen. #ifndef O_BINARY @@ -193,7 +195,6 @@ struct DataDescriptor { #undef DISALLOW_IMPLICIT_CONSTRUCTORS static const uint32_t kGPBDDFlagMask = 0x0008; // mask value that signifies that the entry has a DD -static const uint32_t kMaxErrorLen = 1024; // The maximum size of a central directory or a file // comment in bytes. @@ -642,9 +643,8 @@ static int32_t ParseZipArchive(ZipArchive* archive) { const uint16_t comment_length = cdr->comment_length; const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord); - /* check that file name doesn't contain \0 character */ - if (memchr(file_name, 0, file_name_length) != NULL) { - ALOGW("Zip: entry name can't contain \\0 character"); + /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */ + if (!IsValidEntryName(file_name, file_name_length)) { goto bail; } @@ -744,7 +744,7 @@ static int32_t UpdateEntryFromDataDescriptor(int fd, // as a side effect of this call. static inline ssize_t ReadAtOffset(int fd, uint8_t* buf, size_t len, off64_t off) { -#ifdef HAVE_PREAD +#if !defined(_WIN32) return TEMP_FAILURE_RETRY(pread64(fd, buf, len, off)); #else // The only supported platform that doesn't support pread at the moment @@ -756,7 +756,7 @@ static inline ssize_t ReadAtOffset(int fd, uint8_t* buf, size_t len, } return TEMP_FAILURE_RETRY(read(fd, buf, len)); -#endif // HAVE_PREAD +#endif } static int32_t FindEntry(const ZipArchive* archive, const int ent, diff --git a/libzipfile/Android.mk b/libzipfile/Android.mk index 12a2229..f054e15 100644 --- a/libzipfile/Android.mk +++ b/libzipfile/Android.mk @@ -7,13 +7,10 @@ LOCAL_SRC_FILES:= \ centraldir.c \ zipfile.c -LOCAL_STATIC_LIBRARIES := \ - libunz +LOCAL_STATIC_LIBRARIES := libz LOCAL_MODULE:= libzipfile -LOCAL_C_INCLUDES += external/zlib - LOCAL_CFLAGS := -Werror LOCAL_MULTILIB := both @@ -27,13 +24,10 @@ LOCAL_SRC_FILES:= \ centraldir.c \ zipfile.c -LOCAL_STATIC_LIBRARIES := \ - libunz +LOCAL_STATIC_LIBRARIES := libz LOCAL_MODULE:= libzipfile -LOCAL_C_INCLUDES += external/zlib - LOCAL_CFLAGS := -Werror include $(BUILD_STATIC_LIBRARY) @@ -45,12 +39,10 @@ include $(CLEAR_VARS) LOCAL_SRC_FILES:= \ test_zipfile.c -LOCAL_STATIC_LIBRARIES := libzipfile libunz +LOCAL_STATIC_LIBRARIES := libzipfile libz LOCAL_MODULE := test_zipfile -LOCAL_C_INCLUDES += external/zlib - LOCAL_CFLAGS := -Werror include $(BUILD_HOST_EXECUTABLE) diff --git a/lmkd/lmkd.c b/lmkd/lmkd.c index a534a24..7bbc811 100644 --- a/lmkd/lmkd.c +++ b/lmkd/lmkd.c @@ -607,7 +607,6 @@ static int kill_one_process(struct proc *procp, int other_free, int other_file, static int find_and_kill_process(int other_free, int other_file, bool first) { int i; - int r; int min_score_adj = OOM_ADJUST_MAX + 1; int minfree = 0; int killed_size = 0; @@ -643,7 +642,6 @@ retry: } static void mp_event(uint32_t events __unused) { - int i; int ret; unsigned long long evcount; struct sysmeminfo mi; diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp index 6306f5c..79f2ebd 100644 --- a/logcat/logcat.cpp +++ b/logcat/logcat.cpp @@ -455,36 +455,31 @@ int main(int argc, char **argv) delete dev; } - dev = devices = new log_device_t("main", false, 'm'); - android::g_devCount = 1; - if (android_name_to_log_id("system") == LOG_ID_SYSTEM) { - dev->next = new log_device_t("system", false, 's'); - if (dev->next) { - dev = dev->next; - android::g_devCount++; + devices = dev = NULL; + android::g_devCount = 0; + needBinary = false; + for(int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) { + const char *name = android_log_id_to_name((log_id_t)i); + log_id_t log_id = android_name_to_log_id(name); + + if (log_id != (log_id_t)i) { + continue; } - } - if (android_name_to_log_id("radio") == LOG_ID_RADIO) { - dev->next = new log_device_t("radio", false, 'r'); - if (dev->next) { - dev = dev->next; - android::g_devCount++; + + bool binary = strcmp(name, "events") == 0; + log_device_t* d = new log_device_t(name, binary, *name); + + if (dev) { + dev->next = d; + dev = d; + } else { + devices = dev = d; } - } - if (android_name_to_log_id("events") == LOG_ID_EVENTS) { - dev->next = new log_device_t("events", true, 'e'); - if (dev->next) { - dev = dev->next; - android::g_devCount++; + android::g_devCount++; + if (binary) { needBinary = true; } } - if (android_name_to_log_id("crash") == LOG_ID_CRASH) { - dev->next = new log_device_t("crash", false, 'c'); - if (dev->next) { - android::g_devCount++; - } - } break; } diff --git a/logcat/tests/logcat_test.cpp b/logcat/tests/logcat_test.cpp index b1412ff..b358485 100644 --- a/logcat/tests/logcat_test.cpp +++ b/logcat/tests/logcat_test.cpp @@ -548,7 +548,6 @@ TEST(logcat, logrotate_suffix) { static const char rotated_log_filename_prefix[] = "log.txt."; static const size_t rotated_log_filename_prefix_len = strlen(rotated_log_filename_prefix); - static const char total[] = "total "; static const char log_filename[] = "log.txt"; if (!strncmp(buffer, rotated_log_filename_prefix, rotated_log_filename_prefix_len)) { diff --git a/logd/LogAudit.cpp b/logd/LogAudit.cpp index 51feff3..c7c0249 100644 --- a/logd/LogAudit.cpp +++ b/logd/LogAudit.cpp @@ -19,7 +19,6 @@ #include <limits.h> #include <stdarg.h> #include <stdlib.h> -#include <sys/klog.h> #include <sys/prctl.h> #include <sys/uio.h> #include <syslog.h> @@ -33,21 +32,23 @@ '0' + (LOG_AUTH | (PRI)) % 10, \ '>' -LogAudit::LogAudit(LogBuffer *buf, LogReader *reader, int fdDmsg) +LogAudit::LogAudit(LogBuffer *buf, LogReader *reader, int fdDmesg) : SocketListener(getLogSocket(), false) , logbuf(buf) , reader(reader) - , fdDmesg(-1) { + , fdDmesg(fdDmesg) + , initialized(false) { static const char auditd_message[] = { KMSG_PRIORITY(LOG_INFO), 'l', 'o', 'g', 'd', '.', 'a', 'u', 'd', 'i', 't', 'd', ':', ' ', 's', 't', 'a', 'r', 't', '\n' }; - write(fdDmsg, auditd_message, sizeof(auditd_message)); - logDmesg(); - fdDmesg = fdDmsg; + write(fdDmesg, auditd_message, sizeof(auditd_message)); } bool LogAudit::onDataAvailable(SocketClient *cli) { - prctl(PR_SET_NAME, "logd.auditd"); + if (!initialized) { + prctl(PR_SET_NAME, "logd.auditd"); + initialized = true; + } struct audit_message rep; @@ -60,7 +61,8 @@ bool LogAudit::onDataAvailable(SocketClient *cli) { return false; } - logPrint("type=%d %.*s", rep.nlh.nlmsg_type, rep.nlh.nlmsg_len, rep.data); + logPrint("type=%d %.*s", + rep.nlh.nlmsg_type, rep.nlh.nlmsg_len, rep.data); return true; } @@ -87,7 +89,7 @@ int LogAudit::logPrint(const char *fmt, ...) { } bool info = strstr(str, " permissive=1") || strstr(str, " policy loaded "); - if (fdDmesg >= 0) { + if ((fdDmesg >= 0) && initialized) { struct iovec iov[3]; static const char log_info[] = { KMSG_PRIORITY(LOG_INFO) }; static const char log_warning[] = { KMSG_PRIORITY(LOG_WARNING) }; @@ -213,34 +215,23 @@ int LogAudit::logPrint(const char *fmt, ...) { return rc; } -void LogAudit::logDmesg() { - int len = klogctl(KLOG_SIZE_BUFFER, NULL, 0); - if (len <= 0) { - return; +int LogAudit::log(char *buf) { + char *audit = strstr(buf, " audit("); + if (!audit) { + return 0; } - len++; - char buf[len]; - - int rc = klogctl(KLOG_READ_ALL, buf, len); - - buf[len - 1] = '\0'; - - for(char *tok = buf; (rc >= 0) && ((tok = strtok(tok, "\r\n"))); tok = NULL) { - char *audit = strstr(tok, " audit("); - if (!audit) { - continue; - } + *audit = '\0'; - *audit++ = '\0'; - - char *type = strstr(tok, "type="); - if (type) { - rc = logPrint("%s %s", type, audit); - } else { - rc = logPrint("%s", audit); - } + int rc; + char *type = strstr(buf, "type="); + if (type) { + rc = logPrint("%s %s", type, audit + 1); + } else { + rc = logPrint("%s", audit + 1); } + *audit = ' '; + return rc; } int LogAudit::getLogSocket() { @@ -248,7 +239,7 @@ int LogAudit::getLogSocket() { if (fd < 0) { return fd; } - if (audit_set_pid(fd, getpid(), WAIT_YES) < 0) { + if (audit_setup(fd, getpid()) < 0) { audit_close(fd); fd = -1; } diff --git a/logd/LogAudit.h b/logd/LogAudit.h index 111030a..f977be9 100644 --- a/logd/LogAudit.h +++ b/logd/LogAudit.h @@ -24,16 +24,17 @@ class LogAudit : public SocketListener { LogBuffer *logbuf; LogReader *reader; int fdDmesg; + bool initialized; public: LogAudit(LogBuffer *buf, LogReader *reader, int fdDmesg); + int log(char *buf); protected: virtual bool onDataAvailable(SocketClient *cli); private: static int getLogSocket(); - void logDmesg(); int logPrint(const char *fmt, ...) __attribute__ ((__format__ (__printf__, 2, 3))); }; diff --git a/logd/libaudit.c b/logd/libaudit.c index ca88d1b..d00d579 100644 --- a/logd/libaudit.c +++ b/logd/libaudit.c @@ -162,7 +162,7 @@ out: return rc; } -int audit_set_pid(int fd, uint32_t pid, rep_wait_t wmode) +int audit_setup(int fd, uint32_t pid) { int rc; struct audit_message rep; @@ -176,7 +176,8 @@ int audit_set_pid(int fd, uint32_t pid, rep_wait_t wmode) * and the the mask set to AUDIT_STATUS_PID */ status.pid = pid; - status.mask = AUDIT_STATUS_PID; + status.mask = AUDIT_STATUS_PID | AUDIT_STATUS_RATE_LIMIT; + status.rate_limit = 20; // audit entries per second /* Let the kernel know this pid will be registering for audit events */ rc = audit_send(fd, AUDIT_SET, &status, sizeof(status)); @@ -188,24 +189,21 @@ int audit_set_pid(int fd, uint32_t pid, rep_wait_t wmode) /* * In a request where we need to wait for a response, wait for the message * and discard it. This message confirms and sync's us with the kernel. - * This daemon is now registered as the audit logger. Only wait if the - * wmode is != WAIT_NO + * This daemon is now registered as the audit logger. + * + * TODO + * If the daemon dies and restarts the message didn't come back, + * so I went to non-blocking and it seemed to fix the bug. + * Need to investigate further. */ - if (wmode != WAIT_NO) { - /* TODO - * If the daemon dies and restarts the message didn't come back, - * so I went to non-blocking and it seemed to fix the bug. - * Need to investigate further. - */ - audit_get_reply(fd, &rep, GET_REPLY_NONBLOCKING, 0); - } + audit_get_reply(fd, &rep, GET_REPLY_NONBLOCKING, 0); return 0; } int audit_open() { - return socket(PF_NETLINK, SOCK_RAW, NETLINK_AUDIT); + return socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT); } int audit_get_reply(int fd, struct audit_message *rep, reply_t block, int peek) diff --git a/logd/libaudit.h b/logd/libaudit.h index cb114f9..b9e330d 100644 --- a/logd/libaudit.h +++ b/logd/libaudit.h @@ -37,11 +37,6 @@ typedef enum { GET_REPLY_NONBLOCKING } reply_t; -typedef enum { - WAIT_NO, - WAIT_YES -} rep_wait_t; - /* type == AUDIT_SIGNAL_INFO */ struct audit_sig_info { uid_t uid; @@ -92,12 +87,10 @@ extern int audit_get_reply(int fd, struct audit_message *rep, reply_t block, * The fd returned by a call to audit_open() * @param pid * The pid whom to set as the reciever of audit messages - * @param wmode - * Whether or not to block on the underlying socket io calls. * @return * This function returns 0 on success, -errno on error. */ -extern int audit_set_pid(int fd, uint32_t pid, rep_wait_t wmode); +extern int audit_setup(int fd, uint32_t pid); __END_DECLS diff --git a/logd/main.cpp b/logd/main.cpp index 54da7e3..946a9a0 100644 --- a/logd/main.cpp +++ b/logd/main.cpp @@ -22,6 +22,7 @@ #include <stdlib.h> #include <string.h> #include <sys/capability.h> +#include <sys/klog.h> #include <sys/prctl.h> #include <sys/stat.h> #include <sys/types.h> @@ -195,6 +196,23 @@ int main() { if (auditd) { // failure is an option ... messages are in dmesg (required by standard) LogAudit *al = new LogAudit(logBuf, reader, fdDmesg); + + int len = klogctl(KLOG_SIZE_BUFFER, NULL, 0); + if (len > 0) { + len++; + char buf[len]; + + int rc = klogctl(KLOG_READ_ALL, buf, len); + + buf[len - 1] = '\0'; + + for(char *ptr, *tok = buf; + (rc >= 0) && ((tok = strtok_r(tok, "\r\n", &ptr))); + tok = NULL) { + rc = al->log(tok); + } + } + if (al->startListener()) { delete al; close(fdDmesg); diff --git a/rootdir/etc/init.testmenu b/rootdir/etc/init.testmenu deleted file mode 100755 index 7ae16d5..0000000 --- a/rootdir/etc/init.testmenu +++ /dev/null @@ -1,322 +0,0 @@ -#!/system/bin/sh - -atdev=/dev/omap_csmi_tty0 -pppdev=/dev/omap_csmi_tty1 - -n1=`cat /data/phoneentry1 2>/dev/null` -n2=`cat /data/phoneentry2 2>/dev/null` -n3=`cat /data/phoneentry3 2>/dev/null` -n1=${n1:-"*#06#"} -n2=${n2:-"*#06#"} -n3=${n3:-"*#06#"} -phoneoutputpid= -eventoutputpid= -notifypid= -notifytoggle=false -pppdpid= -powerdidletime=120 - -# map phone specific keys -setkey -k 0xe4 -v 0x23 # map # -setkey -k 0xe3 -v 0x2a # map * -setkey -k 231 -v 513 # map send to newline -#setkey -k 0x67 -v 0x20b # map up to scroll back -#setkey -k 0x6c -v 0x20a # map down to scroll forward -setkey -k 0x73 -v 0x20b # map volume up to scroll back -setkey -k 0x72 -v 0x20a # map volume down to scroll forward -setkey -k 0x60 -v 0x211 # map PoC to next console - -# tuttle keys -setkey -k 0x38 -v 0x703 # map leftalt to alt -setkey -k 0x9b -v 0x703 # map mail to alt -setkey -t 8 -k 0x9b -v 0x703 # map alt-mail to alt -setkey -t 8 -k 0x10 -v 0x21 # map alt-q to ! -setkey -t 8 -k 0x11 -v 0x31 # map alt-w to 1 -setkey -t 8 -k 0x12 -v 0x32 # map alt-e to 2 -setkey -t 8 -k 0x13 -v 0x33 # map alt-r to 3 -setkey -t 8 -k 0x14 -v 0x2b # map alt-t to + -setkey -t 8 -k 0x15 -v 0x28 # map alt-y to ( -setkey -t 8 -k 0x16 -v 0x29 # map alt-u to ) -setkey -t 8 -k 0x17 -v 0x2d # map alt-i to - -setkey -t 8 -k 0x18 -v 0x5f # map alt-o to _ -setkey -t 8 -k 0x19 -v 0x22 # map alt-p to " -setkey -t 8 -k 0x1e -v 0x23 # map alt-a to # -setkey -t 8 -k 0x1f -v 0x34 # map alt-s to 4 -setkey -t 8 -k 0x20 -v 0x35 # map alt-d to 5 -setkey -t 8 -k 0x21 -v 0x36 # map alt-f to 6 -setkey -t 8 -k 0x22 -v 0x2f # map alt-g to / -setkey -t 8 -k 0x23 -v 0x3f # map alt-h to ? -setkey -t 8 -k 0x24 -v 0xa3 # map alt-j to pound -setkey -t 8 -k 0x25 -v 0x24 # map alt-k to $ -setkey -t 8 -k 0x2c -v 0x2a # map alt-z to * -setkey -t 8 -k 0x2d -v 0x37 # map alt-x to 7 -setkey -t 8 -k 0x2e -v 0x38 # map alt-c to 8 -setkey -t 8 -k 0x2f -v 0x39 # map alt-v to 9 -setkey -t 8 -k 0x30 -v 0x7c # map alt-b to | -setkey -t 8 -k 0x31 -v 0x40 # map alt-n to @ -setkey -t 8 -k 0x32 -v 0x3d # map alt-m to = -setkey -t 8 -k 0x33 -v 0x3b # map alt-, to ; -setkey -t 8 -k 0x34 -v 0x3a # map alt-. to : -setkey -t 8 -k 0x0f -v 0x30 # map alt-tab to 0 -setkey -t 8 -k 0x67 -v 0x20b # map alt-up to scroll back -setkey -t 8 -k 0x6c -v 0x20a # map alt-down to scroll forward - -while true -do - echo - echo "------------------------------" - echo " 1: init commands" - echo " 2: call commands" - echo " 3: misc phone" - echo " 4: phone debug output" - echo " 5: test data connection" - echo " 6: start runtime" - echo " 7: start runtime w/output" - echo " 8: stop runtime" - echo " 9: misc" - echo -n ": " - while true - do - c=`readtty -t 50 -f -a 1234567890#` - case "$c" in - "" ) ;; - * ) break; - esac - done - echo Got key -$c- - case $c in - "1" ) - while true; do - echo - echo "------------------------------" - echo " 1: Print phone output" - echo " 2: ATQ0V1E1+CMEE=2;+CREG=0" - echo " 3: AT+CFUN=1" - echo " 4: AT+COPS=0" - echo " 5: AT+CREG?" - echo " 6: Stop phone output" - echo " 0: back" - echo -n ": " - c=`readtty -f -a 1234560#` - echo Got key -$c- - case "$c" in - "1" ) kill $phoneoutputpid; cat $atdev & phoneoutputpid=$! ;; - "2" ) echo -e "ATQ0V1E1+CMEE=2;+CREG=0\r" >$atdev;; - "3" ) echo -e "AT+CFUN=1\r" >$atdev;; - "4" ) echo -e "AT+COPS=0\r" >$atdev;; - "5" ) echo -e "AT+CREG?\r" >$atdev;; - "6" ) kill $phoneoutputpid; phoneoutputpid= ;; - "0" ) break;; - esac - done - ;; - "2" ) - while true; do - echo - echo "------------------------------" - echo " 1: Dial: ATD $n1;" - echo " 2: Dial: ATD $n2;" - echo " 3: Dial: ATD $n3;" - echo " 4: Set number for 1" - echo " 5: Set number for 2" - echo " 6: Set number for 3" - echo " 7: Dial: ATD ...;" - echo " 8: Hang up: ATH" - echo " 9: Answer: ATA" - echo " 0: back" - echo -n ": " - c=`readtty -f -a 1234567890#` - echo Got key -$c- - case "$c" in - "1" ) echo "Dialing $n1"; echo -e "ATD $n1;\r" >$atdev;; - "2" ) echo "Dialing $n2"; echo -e "ATD $n2;\r" >$atdev;; - "3" ) echo "Dialing $n3"; echo -e "ATD $n3;\r" >$atdev;; - "4" ) echo -n "Number: "; read n1; echo $n1 >/data/phoneentry1;; - "5" ) echo -n "Number: "; read n2; echo $n2 >/data/phoneentry2;; - "6" ) echo -n "Number: "; read n3; echo $n3 >/data/phoneentry3;; - "7" ) echo -n "Number: "; read n; echo "Dialing $n"; echo -e "ATD $n;\r" >$atdev;; - "8" ) echo -e "ATH\r" >$atdev;; - "9" ) echo -e "ATA\r" >$atdev;; - "0" ) break;; - esac - done - ;; - "3" ) - while true; do - echo - echo "------------------------------" - echo " 1: Save FFS data" - echo " 2: Load user FFS data" - echo " 3: Load system FFS data" - echo " 4: Reset FFS data" - echo " 5: Set uplink gain" - echo " 6: Set echo" - echo " 7: cat /dev/omap_csmi_battery_t" - echo " 8: cat /dev/omap_csmi_htc" - echo " 0: back" - echo -n ": " - c=`readtty -f -a 123456780#` - echo Got key -$c- - case "$c" in - "1" ) cat /dev/omap_csmi_ffs >/data/ffsdata;; - "2" ) cat /data/ffsdata >/dev/omap_csmi_ffs;; - "3" ) cat /system/ffsdata >/dev/omap_csmi_ffs;; - "4" ) echo - >/dev/omap_csmi_ffs;; - "5" ) - echo -n "Gain: "; read g; - echo gu$g >/tmp/gain; - cat /tmp/gain 2>/dev/null >/dev/omap_csmi_audio_tes - ;; - "6" ) - echo -n "Echo param (hex): "; read e; - echo "e0x$e" >/tmp/echo; - cat /tmp/echo 2>/dev/null >/dev/omap_csmi_audio_tes - ;; - "7" ) cat /dev/omap_csmi_battery_t;; - "8" ) cat /dev/omap_csmi_htc;; - "0" ) break;; - esac - done - ;; - "4" ) - while true; do - echo - echo "------------------------------" - echo " 1: Toggle debug I/O" - echo " 2: Toggle debug Flow" - echo " 3: Toggle debug Interrupt" - echo " 4: Toggle debug Info" - echo " 5: Toggle GSM run state" - echo " 6: Clear GSM data area" - echo " 0: back" - echo -n ": " - c=`readtty -f -a 1234560#` - echo Got key -$c- - case "$c" in - "1" ) echo -n "i" >/sys/devices/system/omap_csmi/debug;; - "2" ) echo -n "f" >/sys/devices/system/omap_csmi/debug;; - "3" ) echo -n "I" >/sys/devices/system/omap_csmi/debug;; - "4" ) echo -n "F" >/sys/devices/system/omap_csmi/debug;; - "5" ) echo -n "s" >/sys/devices/system/omap_csmi/debug;; - "6" ) echo -n "c" >/sys/devices/system/omap_csmi/debug;; - "0" ) break;; - esac - done - ;; - "5" ) - while true; do - echo - echo "------------------------------" - echo " 1: Start pppd - userspace" - echo " 2: Start pppd - kernel" - echo " 3: Start pppd - kernel <at1" - echo " 4: Configure ppp data to at2" - echo " 5: Test with HTTP GET" - echo " 6: Kill pppd" - echo " 0: back" - echo -n ": " - c=`readtty -f -a 1234560#` - echo Got key -$c- - case "$c" in - "1" ) kill $pppdpid; pppd notty < $pppdev > $pppdev & pppdpid=$!;; - "2" ) kill $pppdpid; pppd nodetach $pppdev & pppdpid=$!;; - "3" ) kill &pppdpid; pppd nodetach $pppdev connect "sh -c \"chat -v -f /etc/ppp/connect-data <$atdev >$atdev\"" & pppdpid=$!;; - "4" ) echo -e 'AT%DATA=2,"UART",1,,"SER","UART",0\r' >$atdev;; - "5" ) test-data-connection;; - "6" ) kill $pppdpid; pppdpid=;; - "0" ) break;; - esac - done - ;; - "6" ) - echo - echo ------------------------ - echo Starting android runtime - echo ------------------------ - start - ;; - "7" ) - echo - echo ------------------------ - echo Starting android runtime - echo ------------------------ - if exists /data/singleproc - then - single_process="-s" - else - single_process="" - fi - start runtime $single_process - ;; - "8" ) - stop - ;; - "9" ) - while true; do - echo - echo "------------------------------" - echo " 1: Print events" - echo " 2: Stop event output" - if $notifytoggle - then - echo " 3: stop notify" - else - echo " 3: notify /sys/android_power" - fi - echo " 4: start powerd" - echo " 5: start powerd verbose" - echo " 6: stop powerd" - echo " 7: set powerd idletime ($powerdidletime)" - echo " 8: start multitap shell" - if exists /data/singleproc - then - echo " 9: enable multiprocess" - else - echo " 9: disable multiprocess" - fi - echo " c: start shell" - echo " 0: back" - echo -n ": " - c=`readtty -f -a 1234567890c#` - echo Got key -$c- - case "$c" in - "1" ) kill $eventoutputpid; getevent & eventoutputpid=$! ;; - "2" ) kill $eventoutputpid; eventoutputpid= ;; - "3" ) - if $notifytoggle - then - kill $notifypid - notifypid= - notifytoggle=false - else - kill $notifypid - notify -m 0x00000002 -c 0 -p -v 0 -w 30 /sys/android_power & - notifypid=$! - notifytoggle=true - fi - ;; - "4" ) start powerd -i $powerdidletime ;; - "5" ) start powerd -i $powerdidletime -v ;; - "6" ) stop powerd ;; - "7" ) echo -n "Idle time (seconds): "; read powerdidletime ;; - "8" ) - readtty -f -p -t 10 -e "[ ~" | sh -i - ;; - "9" ) - if exists /data/singleproc - then - echo "Enabling multiprocess environment." - rm /data/singleproc - else - echo "Disabling multiprocess environment." - echo >/data/singleproc "true" - fi - ;; - "c" ) sh -i <>/dev/tty0 1>&0 2>&1 ;; - "0" ) break;; - esac - done - ;; - esac -done - diff --git a/sdcard/sdcard.c b/sdcard/sdcard.c index d7bccea..a48906a 100644 --- a/sdcard/sdcard.c +++ b/sdcard/sdcard.c @@ -1836,7 +1836,7 @@ static int run(const char* source_path, const char* dest_path, uid_t uid, "fd=%i,rootmode=40000,default_permissions,allow_other,user_id=%d,group_id=%d", fd, uid, gid); - res = mount("/dev/fuse", dest_path, "fuse", MS_NOSUID | MS_NODEV, opts); + res = mount("/dev/fuse", dest_path, "fuse", MS_NOSUID | MS_NODEV | MS_NOEXEC, opts); if (res < 0) { ERROR("cannot mount fuse filesystem: %s\n", strerror(errno)); goto error; diff --git a/toolbox/Android.mk b/toolbox/Android.mk index 3304e2a..249f91e 100644 --- a/toolbox/Android.mk +++ b/toolbox/Android.mk @@ -7,6 +7,10 @@ common_cflags := \ -I$(LOCAL_PATH)/upstream-netbsd/include/ \ -include bsd-compatibility.h \ +# Temporary, remove after cleanup. b/18632512 +common_cflags += -Wno-unused-variable \ + -Wno-unused-but-set-variable + include $(CLEAR_VARS) LOCAL_SRC_FILES := upstream-netbsd/bin/cat/cat.c @@ -52,13 +56,6 @@ LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk include $(BUILD_STATIC_LIBRARY) include $(CLEAR_VARS) -LOCAL_SRC_FILES := upstream-freebsd/usr.bin/false/false.c -LOCAL_CFLAGS += $(common_cflags) -Dmain=false_main -LOCAL_MODULE := libtoolbox_false -LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk -include $(BUILD_STATIC_LIBRARY) - -include $(CLEAR_VARS) LOCAL_SRC_FILES := \ upstream-netbsd/usr.bin/grep/fastgrep.c \ upstream-netbsd/usr.bin/grep/file.c \ @@ -71,13 +68,6 @@ LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk include $(BUILD_STATIC_LIBRARY) include $(CLEAR_VARS) -LOCAL_SRC_FILES := upstream-netbsd/bin/kill/kill.c -LOCAL_CFLAGS += $(common_cflags) -Dmain=kill_main -LOCAL_MODULE := libtoolbox_kill -LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk -include $(BUILD_STATIC_LIBRARY) - -include $(CLEAR_VARS) LOCAL_SRC_FILES := upstream-netbsd/bin/ln/ln.c LOCAL_CFLAGS += $(common_cflags) -Dmain=ln_main LOCAL_MODULE := libtoolbox_ln @@ -92,13 +82,6 @@ LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk include $(BUILD_STATIC_LIBRARY) include $(CLEAR_VARS) -LOCAL_SRC_FILES := upstream-netbsd/usr.bin/printenv/printenv.c -LOCAL_CFLAGS += $(common_cflags) -Dmain=printenv_main -LOCAL_MODULE := libtoolbox_printenv -LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk -include $(BUILD_STATIC_LIBRARY) - -include $(CLEAR_VARS) LOCAL_SRC_FILES := upstream-netbsd/bin/rm/rm.c LOCAL_CFLAGS += $(common_cflags) -Dmain=rm_main LOCAL_MODULE := libtoolbox_rm @@ -112,27 +95,6 @@ LOCAL_MODULE := libtoolbox_rmdir LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk include $(BUILD_STATIC_LIBRARY) -include $(CLEAR_VARS) -LOCAL_SRC_FILES := upstream-netbsd/bin/sleep/sleep.c -LOCAL_CFLAGS += $(common_cflags) -Dmain=sleep_main -LOCAL_MODULE := libtoolbox_sleep -LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk -include $(BUILD_STATIC_LIBRARY) - -include $(CLEAR_VARS) -LOCAL_SRC_FILES := upstream-netbsd/bin/sync/sync.c -LOCAL_CFLAGS += $(common_cflags) -Dmain=sync_main -LOCAL_MODULE := libtoolbox_sync -LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk -include $(BUILD_STATIC_LIBRARY) - -include $(CLEAR_VARS) -LOCAL_SRC_FILES := upstream-freebsd/usr.bin/true/true.c -LOCAL_CFLAGS += $(common_cflags) -Dmain=true_main -LOCAL_MODULE := libtoolbox_true -LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk -include $(BUILD_STATIC_LIBRARY) - include $(CLEAR_VARS) @@ -142,26 +104,18 @@ BSD_TOOLS := \ cp \ dd \ du \ - false \ grep \ - kill \ ln \ mv \ - printenv \ rm \ rmdir \ - sleep \ - sync \ - true \ OUR_TOOLS := \ chcon \ chmod \ - clear \ cmp \ date \ df \ - dmesg \ getenforce \ getevent \ getprop \ @@ -170,29 +124,23 @@ OUR_TOOLS := \ id \ ifconfig \ iftop \ - insmod \ ioctl \ ionice \ load_policy \ log \ ls \ - lsmod \ lsof \ md5 \ mkdir \ mknod \ - mkswap \ mount \ nandread \ netstat \ newfs_msdos \ - nohup \ notify \ ps \ - readlink \ renice \ restorecon \ - rmmod \ route \ runcon \ schedtop \ @@ -203,13 +151,10 @@ OUR_TOOLS := \ smd \ start \ stop \ - swapoff \ - swapon \ top \ touch \ umount \ uptime \ - vmstat \ watchprops \ wipe \ @@ -235,16 +180,14 @@ LOCAL_SHARED_LIBRARIES := \ libcutils \ libselinux \ -# libusbhost is only used by lsusb, and that isn't usually included in toolbox. -# The linker strips out all the unused library code in the normal case. -LOCAL_STATIC_LIBRARIES := \ - libusbhost \ - LOCAL_WHOLE_STATIC_LIBRARIES := $(patsubst %,libtoolbox_%,$(BSD_TOOLS)) LOCAL_MODULE := toolbox LOCAL_ADDITIONAL_DEPENDENCIES += $(LOCAL_PATH)/Android.mk +# Install the symlinks. +LOCAL_POST_INSTALL_CMD := $(hide) $(foreach t,$(ALL_TOOLS),ln -sf toolbox $(TARGET_OUT)/bin/$(t);) + # Including this will define $(intermediates). # include $(BUILD_EXECUTABLE) @@ -258,22 +201,6 @@ $(TOOLS_H): $(LOCAL_PATH)/Android.mk $(TOOLS_H): $(transform-generated-source) -# Make symbolic link launchers for each tool. -SYMLINKS := $(addprefix $(TARGET_OUT)/bin/,$(ALL_TOOLS)) -$(SYMLINKS): TOOLBOX_BINARY := $(LOCAL_MODULE) -$(SYMLINKS): $(LOCAL_INSTALLED_MODULE) $(LOCAL_PATH)/Android.mk - @echo "Symlink: $@ -> $(TOOLBOX_BINARY)" - @mkdir -p $(dir $@) - @rm -rf $@ - $(hide) ln -sf $(TOOLBOX_BINARY) $@ - -ALL_DEFAULT_INSTALLED_MODULES += $(SYMLINKS) - -# We need this so that the installed files could be picked up based on the -# local module name -ALL_MODULES.$(LOCAL_MODULE).INSTALLED := \ - $(ALL_MODULES.$(LOCAL_MODULE).INSTALLED) $(SYMLINKS) - # We only want 'r' on userdebug and eng builds. include $(CLEAR_VARS) diff --git a/toolbox/alarm.c b/toolbox/alarm.c deleted file mode 100644 index 9bd58aa..0000000 --- a/toolbox/alarm.c +++ /dev/null @@ -1,190 +0,0 @@ -#include <stdio.h> -#include <stdlib.h> -#include <fcntl.h> -#include <string.h> -#include <errno.h> -#include <time.h> -#include <asm/ioctl.h> -//#include <linux/rtc.h> -#include <linux/android_alarm.h> - -int alarm_main(int argc, char *argv[]) -{ - int c; - int res; - struct tm tm; - time_t t; - struct timespec ts; -// struct rtc_time rtc_time; - char strbuf[26]; - int afd; - int nfd; -// struct timeval timeout = { 0, 0 }; - int wait = 0; - fd_set rfds; - const char wake_lock_id[] = "alarm_test"; - int waitalarmmask = 0; - - int useutc = 0; - android_alarm_type_t alarmtype_low = ANDROID_ALARM_RTC_WAKEUP; - android_alarm_type_t alarmtype_high = ANDROID_ALARM_RTC_WAKEUP; - android_alarm_type_t alarmtype = 0; - - do { - //c = getopt(argc, argv, "uw:"); - c = getopt(argc, argv, "uwat:"); - if (c == EOF) - break; - switch (c) { - case 'u': - useutc = 1; - break; - case 't': - alarmtype_low = alarmtype_high = strtol(optarg, NULL, 0); - break; - case 'a': - alarmtype_low = ANDROID_ALARM_RTC_WAKEUP; - alarmtype_high = ANDROID_ALARM_TYPE_COUNT - 1; - break; - case 'w': - //timeout.tv_sec = strtol(optarg, NULL, 0); - wait = 1; - break; - case '?': - fprintf(stderr, "%s: invalid option -%c\n", - argv[0], optopt); - exit(1); - } - } while (1); - if(optind + 2 < argc) { - fprintf(stderr,"%s [-uwa] [-t type] [seconds]\n", argv[0]); - return 1; - } - - afd = open("/dev/alarm", O_RDWR); - if(afd < 0) { - fprintf(stderr, "Unable to open rtc: %s\n", strerror(errno)); - return 1; - } - - if(optind == argc) { - for(alarmtype = alarmtype_low; alarmtype <= alarmtype_high; alarmtype++) { - waitalarmmask |= 1U << alarmtype; - } -#if 0 - res = ioctl(fd, RTC_ALM_READ, &tm); - if(res < 0) { - fprintf(stderr, "Unable to read alarm: %s\n", strerror(errno)); - return 1; - } -#endif -#if 0 - t = timegm(&tm); - if(useutc) - gmtime_r(&t, &tm); - else - localtime_r(&t, &tm); -#endif -#if 0 - asctime_r(&tm, strbuf); - printf("%s", strbuf); -#endif - } - else if(optind + 1 == argc) { -#if 0 - res = ioctl(fd, RTC_RD_TIME, &tm); - if(res < 0) { - fprintf(stderr, "Unable to set alarm: %s\n", strerror(errno)); - return 1; - } - asctime_r(&tm, strbuf); - printf("Now: %s", strbuf); - time(&tv.tv_sec); -#endif -#if 0 - time(&ts.tv_sec); - ts.tv_nsec = 0; - - //strptime(argv[optind], NULL, &tm); - //tv.tv_sec = mktime(&tm); - //tv.tv_usec = 0; -#endif - for(alarmtype = alarmtype_low; alarmtype <= alarmtype_high; alarmtype++) { - waitalarmmask |= 1U << alarmtype; - res = ioctl(afd, ANDROID_ALARM_GET_TIME(alarmtype), &ts); - if(res < 0) { - fprintf(stderr, "Unable to get current time: %s\n", strerror(errno)); - return 1; - } - ts.tv_sec += strtol(argv[optind], NULL, 0); - //strtotimeval(argv[optind], &tv); - gmtime_r(&ts.tv_sec, &tm); - printf("time %s -> %ld.%09ld\n", argv[optind], ts.tv_sec, ts.tv_nsec); - asctime_r(&tm, strbuf); - printf("Requested %s", strbuf); - - res = ioctl(afd, ANDROID_ALARM_SET(alarmtype), &ts); - if(res < 0) { - fprintf(stderr, "Unable to set alarm: %s\n", strerror(errno)); - return 1; - } - } -#if 0 - res = ioctl(fd, RTC_ALM_SET, &tm); - if(res < 0) { - fprintf(stderr, "Unable to set alarm: %s\n", strerror(errno)); - return 1; - } - res = ioctl(fd, RTC_AIE_ON); - if(res < 0) { - fprintf(stderr, "Unable to enable alarm: %s\n", strerror(errno)); - return 1; - } -#endif - } - else { - fprintf(stderr,"%s [-u] [date]\n", argv[0]); - return 1; - } - - if(wait) { - while(waitalarmmask) { - printf("wait for alarm %x\n", waitalarmmask); - res = ioctl(afd, ANDROID_ALARM_WAIT); - if(res < 0) { - fprintf(stderr, "alarm wait failed\n"); - } - printf("got alarm %x\n", res); - waitalarmmask &= ~res; - nfd = open("/sys/android_power/acquire_full_wake_lock", O_RDWR); - write(nfd, wake_lock_id, sizeof(wake_lock_id) - 1); - close(nfd); - //sleep(5); - nfd = open("/sys/android_power/release_wake_lock", O_RDWR); - write(nfd, wake_lock_id, sizeof(wake_lock_id) - 1); - close(nfd); - } - printf("done\n"); - } -#if 0 - FD_ZERO(&rfds); - FD_SET(fd, &rfds); - res = select(fd + 1, &rfds, NULL, NULL, &timeout); - if(res < 0) { - fprintf(stderr, "select failed: %s\n", strerror(errno)); - return 1; - } - if(res > 0) { - int event; - read(fd, &event, sizeof(event)); - fprintf(stderr, "got %x\n", event); - } - else { - fprintf(stderr, "timeout waiting for alarm\n"); - } -#endif - - close(afd); - - return 0; -} diff --git a/toolbox/clear.c b/toolbox/clear.c deleted file mode 100644 index df46ad2..0000000 --- a/toolbox/clear.c +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2012, 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. - * * Neither the name of Google, Inc. nor the names of its contributors - * may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * 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. - */ - -#include <stdio.h> - -int clear_main(int argc, char **argv) { - /* This prints the clear screen and move cursor to top-left corner control - * characters for VT100 terminals. This means it will not work on - * non-VT100 compliant terminals, namely Windows' cmd.exe, but should - * work on anything unix-y. */ - fputs("\x1b[2J\x1b[H", stdout); - return 0; -} diff --git a/toolbox/dmesg.c b/toolbox/dmesg.c deleted file mode 100644 index 9c73b00..0000000 --- a/toolbox/dmesg.c +++ /dev/null @@ -1,58 +0,0 @@ -#include <stdlib.h> -#include <unistd.h> -#include <stdio.h> -#include <errno.h> -#include <sys/klog.h> -#include <string.h> - -#define FALLBACK_KLOG_BUF_SHIFT 17 /* CONFIG_LOG_BUF_SHIFT from our kernel */ -#define FALLBACK_KLOG_BUF_LEN (1 << FALLBACK_KLOG_BUF_SHIFT) - -int dmesg_main(int argc, char **argv) -{ - char *buffer; - char *p; - ssize_t ret; - int n, op, klog_buf_len; - - klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0); - - if (klog_buf_len <= 0) { - klog_buf_len = FALLBACK_KLOG_BUF_LEN; - } - - buffer = (char *)malloc(klog_buf_len + 1); - - if (!buffer) { - perror("malloc"); - return EXIT_FAILURE; - } - - p = buffer; - - if((argc == 2) && (!strcmp(argv[1],"-c"))) { - op = KLOG_READ_CLEAR; - } else { - op = KLOG_READ_ALL; - } - - n = klogctl(op, buffer, klog_buf_len); - if (n < 0) { - perror("klogctl"); - return EXIT_FAILURE; - } - buffer[n] = '\0'; - - while((ret = write(STDOUT_FILENO, p, n))) { - if (ret == -1) { - if (errno == EINTR) - continue; - perror("write"); - return EXIT_FAILURE; - } - p += ret; - n -= ret; - } - - return 0; -} diff --git a/toolbox/exists.c b/toolbox/exists.c deleted file mode 100644 index e348668..0000000 --- a/toolbox/exists.c +++ /dev/null @@ -1,16 +0,0 @@ -#include <sys/types.h> -#include <sys/stat.h> -#include <unistd.h> - -int exists_main(int argc, char *argv[]) -{ - struct stat s; - - if(argc < 2) return 1; - - if(stat(argv[1], &s)) { - return 1; - } else { - return 0; - } -} diff --git a/toolbox/insmod.c b/toolbox/insmod.c deleted file mode 100644 index d252433..0000000 --- a/toolbox/insmod.c +++ /dev/null @@ -1,97 +0,0 @@ -#include <stdio.h> -#include <string.h> -#include <fcntl.h> -#include <unistd.h> -#include <malloc.h> -#include <errno.h> -#include <sys/param.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <unistd.h> - -extern int init_module(void *, unsigned long, const char *); - -static void *read_file(const char *filename, ssize_t *_size) -{ - int ret, fd; - struct stat sb; - ssize_t size; - void *buffer = NULL; - - /* open the file */ - fd = open(filename, O_RDONLY); - if (fd < 0) - return NULL; - - /* find out how big it is */ - if (fstat(fd, &sb) < 0) - goto bail; - size = sb.st_size; - - /* allocate memory for it to be read into */ - buffer = malloc(size); - if (!buffer) - goto bail; - - /* slurp it into our buffer */ - ret = read(fd, buffer, size); - if (ret != size) - goto bail; - - /* let the caller know how big it is */ - *_size = size; - -bail: - close(fd); - return buffer; -} - -int insmod_main(int argc, char **argv) -{ - void *file; - ssize_t size = 0; - char opts[1024]; - int ret; - - /* make sure we've got an argument */ - if (argc < 2) { - fprintf(stderr, "usage: insmod <module.o>\n"); - return -1; - } - - /* read the file into memory */ - file = read_file(argv[1], &size); - if (!file) { - fprintf(stderr, "insmod: can't open '%s'\n", argv[1]); - return -1; - } - - opts[0] = '\0'; - if (argc > 2) { - int i, len; - char *end = opts + sizeof(opts) - 1; - char *ptr = opts; - - for (i = 2; (i < argc) && (ptr < end); i++) { - len = MIN(strlen(argv[i]), (size_t)(end - ptr)); - memcpy(ptr, argv[i], len); - ptr += len; - *ptr++ = ' '; - } - *(ptr - 1) = '\0'; - } - - /* pass it to the kernel */ - ret = init_module(file, size, opts); - if (ret != 0) { - fprintf(stderr, - "insmod: init_module '%s' failed (%s)\n", - argv[1], strerror(errno)); - } - - /* free the file buffer */ - free(file); - - return ret; -} - diff --git a/toolbox/lsmod.c b/toolbox/lsmod.c deleted file mode 100644 index 8b55ee6..0000000 --- a/toolbox/lsmod.c +++ /dev/null @@ -1,10 +0,0 @@ -#include <stdio.h> - -extern int cat_main(int argc, char **argv); - -int lsmod_main(int argc, char **argv) -{ - char *cat_argv[] = { "cat", "/proc/modules", NULL }; - return cat_main(2, cat_argv); -} - diff --git a/toolbox/lsusb.c b/toolbox/lsusb.c deleted file mode 100644 index 236e74b..0000000 --- a/toolbox/lsusb.c +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (C) 2010 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 <endian.h> -#include <errno.h> -#include <stdio.h> -#include <stdint.h> -#include <string.h> - -#include <usbhost/usbhost.h> - -static int verbose = 0; -static char str_buff[4096]; - -static const char *get_str(struct usb_device *dev, int id) -{ - char *str = usb_device_get_string(dev, id); - - if (id && str) { - strlcpy(str_buff, str, sizeof(str_buff)); - free(str); - } else { - snprintf(str_buff, sizeof(str_buff), "%02x", id); - } - - return str_buff; -} - - -static void lsusb_parse_device_descriptor(struct usb_device *dev, - struct usb_device_descriptor *desc) -{ - printf(" Device Descriptor\n"); - printf("\tbcdUSB: %04x\n", letoh16(desc->bcdUSB)); - printf("\tbDeviceClass: %02x\n", desc->bDeviceClass); - printf("\tbDeviceSubClass: %02x\n", desc->bDeviceSubClass); - printf("\tbDeviceProtocol: %02x\n", desc->bDeviceProtocol); - printf("\tbMaxPacketSize0: %02x\n", desc->bMaxPacketSize0); - printf("\tidVendor: %04x\n", letoh16(desc->idVendor)); - printf("\tidProduct: %04x\n", letoh16(desc->idProduct)); - printf("\tbcdDevice: %04x\n", letoh16(desc->bcdDevice)); - printf("\tiManufacturer: %s\n", get_str(dev, desc->iManufacturer)); - printf("\tiProduct: %s\n", get_str(dev, desc->iProduct)); - printf("\tiSerialNumber: %s\n", get_str(dev,desc->iSerialNumber)); - printf("\tbNumConfiguration: %02x\n", desc->bNumConfigurations); - printf("\n"); -} - -static void lsusb_parse_config_descriptor(struct usb_device *dev, - struct usb_config_descriptor *desc) -{ - printf(" Config Descriptor\n"); - printf("\twTotalLength: %04x\n", letoh16(desc->wTotalLength)); - printf("\tbNumInterfaces: %02x\n", desc->bNumInterfaces); - printf("\tbConfigurationValue: %02x\n", desc->bConfigurationValue); - printf("\tiConfiguration: %s\n", get_str(dev, desc->iConfiguration)); - printf("\tbmAttributes: %02x\n", desc->bmAttributes); - printf("\tbMaxPower: %d mA\n", desc->bMaxPower * 2); - printf("\n"); -} - -static void lsusb_parse_interface_descriptor(struct usb_device *dev, - struct usb_interface_descriptor *desc) -{ - printf(" Interface Descriptor\n"); - printf("\tbInterfaceNumber: %02x\n", desc->bInterfaceNumber); - printf("\tbAlternateSetting: %02x\n", desc->bAlternateSetting); - printf("\tbNumEndpoints: %02x\n", desc->bNumEndpoints); - printf("\tbInterfaceClass: %02x\n", desc->bInterfaceClass); - printf("\tbInterfaceSubClass: %02x\n", desc->bInterfaceSubClass); - printf("\tbInterfaceProtocol: %02x\n", desc->bInterfaceProtocol); - printf("\tiInterface: %s\n", get_str(dev, desc->iInterface)); - printf("\n"); -} - -static void lsusb_parse_endpoint_descriptor(struct usb_device *dev, - struct usb_endpoint_descriptor *desc) -{ - printf(" Endpoint Descriptor\n"); - printf("\tbEndpointAddress: %02x\n", desc->bEndpointAddress); - printf("\tbmAttributes: %02x\n", desc->bmAttributes); - printf("\twMaxPacketSize: %02x\n", letoh16(desc->wMaxPacketSize)); - printf("\tbInterval: %02x\n", desc->bInterval); - printf("\tbRefresh: %02x\n", desc->bRefresh); - printf("\tbSynchAddress: %02x\n", desc->bSynchAddress); - printf("\n"); -} - -static void lsusb_dump_descriptor(struct usb_device *dev, - struct usb_descriptor_header *desc) -{ - int i; - printf(" Descriptor type %02x\n", desc->bDescriptorType); - - for (i = 0; i < desc->bLength; i++ ) { - if ((i % 16) == 0) - printf("\t%02x:", i); - printf(" %02x", ((uint8_t *)desc)[i]); - if ((i % 16) == 15) - printf("\n"); - } - - if ((i % 16) != 0) - printf("\n"); - printf("\n"); -} - -static void lsusb_parse_descriptor(struct usb_device *dev, - struct usb_descriptor_header *desc) -{ - switch (desc->bDescriptorType) { - case USB_DT_DEVICE: - lsusb_parse_device_descriptor(dev, (struct usb_device_descriptor *) desc); - break; - - case USB_DT_CONFIG: - lsusb_parse_config_descriptor(dev, (struct usb_config_descriptor *) desc); - break; - - case USB_DT_INTERFACE: - lsusb_parse_interface_descriptor(dev, (struct usb_interface_descriptor *) desc); - break; - - case USB_DT_ENDPOINT: - lsusb_parse_endpoint_descriptor(dev, (struct usb_endpoint_descriptor *) desc); - break; - - default: - lsusb_dump_descriptor(dev, desc); - - break; - } -} - -static int lsusb_device_added(const char *dev_name, void *client_data) -{ - struct usb_device *dev = usb_device_open(dev_name); - - if (!dev) { - fprintf(stderr, "can't open device %s: %s\n", dev_name, strerror(errno)); - return 0; - } - - if (verbose) { - struct usb_descriptor_iter iter; - struct usb_descriptor_header *desc; - - printf("%s:\n", dev_name); - - usb_descriptor_iter_init(dev, &iter); - - while ((desc = usb_descriptor_iter_next(&iter)) != NULL) - lsusb_parse_descriptor(dev, desc); - - } else { - uint16_t vid, pid; - char *mfg_name, *product_name, *serial; - - vid = usb_device_get_vendor_id(dev); - pid = usb_device_get_product_id(dev); - mfg_name = usb_device_get_manufacturer_name(dev); - product_name = usb_device_get_product_name(dev); - serial = usb_device_get_serial(dev); - - printf("%s: %04x:%04x %s %s %s\n", dev_name, vid, pid, - mfg_name, product_name, serial); - - free(mfg_name); - free(product_name); - free(serial); - } - - usb_device_close(dev); - - return 0; -} - -static int lsusb_device_removed(const char *dev_name, void *client_data) -{ - return 0; -} - - -static int lsusb_discovery_done(void *client_data) -{ - return 1; -} - - - -int lsusb_main(int argc, char **argv) -{ - struct usb_host_context *ctx; - - if (argc == 2 && !strcmp(argv[1], "-v")) - verbose = 1; - - ctx = usb_host_init(); - if (!ctx) { - perror("usb_host_init:"); - return 1; - } - - usb_host_run(ctx, - lsusb_device_added, - lsusb_device_removed, - lsusb_discovery_done, - NULL); - - usb_host_cleanup(ctx); - - return 0; -} - diff --git a/toolbox/mkswap.c b/toolbox/mkswap.c deleted file mode 100644 index 0904152..0000000 --- a/toolbox/mkswap.c +++ /dev/null @@ -1,93 +0,0 @@ -#include <stdio.h> -#include <unistd.h> -#include <sys/swap.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h> - -/* XXX This needs to be obtained from kernel headers. See b/9336527 */ -struct linux_swap_header { - char bootbits[1024]; /* Space for disklabel etc. */ - uint32_t version; - uint32_t last_page; - uint32_t nr_badpages; - unsigned char sws_uuid[16]; - unsigned char sws_volume[16]; - uint32_t padding[117]; - uint32_t badpages[1]; -}; - -#define MAGIC_SWAP_HEADER "SWAPSPACE2" -#define MAGIC_SWAP_HEADER_LEN 10 -#define MIN_PAGES 10 - -int mkswap_main(int argc, char **argv) -{ - int err = 0; - int fd; - ssize_t len; - off_t swap_size; - int pagesize; - struct linux_swap_header sw_hdr; - - if (argc != 2) { - fprintf(stderr, "Usage: %s <filename>\n", argv[0]); - return -EINVAL; - } - - fd = open(argv[1], O_WRONLY); - if (fd < 0) { - err = errno; - fprintf(stderr, "Cannot open %s\n", argv[1]); - return err; - } - - pagesize = getpagesize(); - /* Determine the length of the swap file */ - swap_size = lseek(fd, 0, SEEK_END); - if (swap_size < MIN_PAGES * pagesize) { - fprintf(stderr, "Swap file needs to be at least %dkB\n", - (MIN_PAGES * pagesize) >> 10); - err = -ENOSPC; - goto err; - } - if (lseek(fd, 0, SEEK_SET)) { - err = errno; - fprintf(stderr, "Can't seek to the beginning of the file\n"); - goto err; - } - - memset(&sw_hdr, 0, sizeof(sw_hdr)); - sw_hdr.version = 1; - sw_hdr.last_page = (swap_size / pagesize) - 1; - - len = write(fd, &sw_hdr, sizeof(sw_hdr)); - if (len != sizeof(sw_hdr)) { - err = errno; - fprintf(stderr, "Failed to write swap header into %s\n", argv[1]); - goto err; - } - - /* Write the magic header */ - if (lseek(fd, pagesize - MAGIC_SWAP_HEADER_LEN, SEEK_SET) < 0) { - err = errno; - fprintf(stderr, "Failed to seek into %s\n", argv[1]); - goto err; - } - - len = write(fd, MAGIC_SWAP_HEADER, MAGIC_SWAP_HEADER_LEN); - if (len != MAGIC_SWAP_HEADER_LEN) { - err = errno; - fprintf(stderr, "Failed to write magic swap header into %s\n", argv[1]); - goto err; - } - - if (fsync(fd) < 0) { - err = errno; - fprintf(stderr, "Failed to sync %s\n", argv[1]); - goto err; - } -err: - close(fd); - return err; -} diff --git a/toolbox/nohup.c b/toolbox/nohup.c deleted file mode 100644 index 363999d..0000000 --- a/toolbox/nohup.c +++ /dev/null @@ -1,26 +0,0 @@ -#include <signal.h> -#include <stdio.h> -#include <stdlib.h> -#include <unistd.h> - -int nohup_main(int argc, char *argv[]) -{ - if (argc < 2) { - fprintf(stderr, "Usage: %s [-n] program args...\n", argv[0]); - return EXIT_FAILURE; - } - signal(SIGHUP, SIG_IGN); - argv++; - if (strcmp(argv[0], "-n") == 0) { - argv++; - signal(SIGINT, SIG_IGN); - signal(SIGSTOP, SIG_IGN); - signal(SIGTTIN, SIG_IGN); - signal(SIGTTOU, SIG_IGN); - signal(SIGQUIT, SIG_IGN); - signal(SIGTERM, SIG_IGN); - } - execvp(argv[0], argv); - perror(argv[0]); - return EXIT_FAILURE; -} diff --git a/toolbox/notify.c b/toolbox/notify.c index c983ed5..8ce346c 100644 --- a/toolbox/notify.c +++ b/toolbox/notify.c @@ -101,14 +101,17 @@ int notify_main(int argc, char *argv[]) else if(verbose >= 1) printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : ""); if(print_files && (event->mask & IN_MODIFY)) { - char filename[512]; + char* filename = file_names[event->wd + id_offset]; + char* alloc_buf = NULL; ssize_t read_len; char *display_name; int buflen; - strcpy(filename, file_names[event->wd + id_offset]); if(event->len) { - strcat(filename, "/"); - strcat(filename, event->name); + if(asprintf(&alloc_buf, "%s/%s", filename, event->name) < 0) { + fprintf(stderr, "asprintf failed, %s\n", strerror(errno)); + return 1; + } + filename = alloc_buf; } ffd = open(filename, O_RDONLY); display_name = (verbose >= 2 || event->len == 0) ? filename : event->name; @@ -132,6 +135,7 @@ int notify_main(int argc, char *argv[]) printf("%s: %s", display_name, buf); } close(ffd); + free(alloc_buf); } if(event_count && --event_count == 0) return 0; diff --git a/toolbox/readlink.c b/toolbox/readlink.c deleted file mode 100644 index d114e20..0000000 --- a/toolbox/readlink.c +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2013, 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. - * * Neither the name of Google, Inc. nor the names of its contributors - * may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * 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. - */ - -#include <limits.h> -#include <stdio.h> -#include <stdlib.h> -#include <unistd.h> - -static int skip_newline, quiet_errors, canonicalize; - -static void usage(char* name) { - fprintf(stderr, "Usage: %s [OPTION]... FILE\n", name); -} - -int readlink_main(int argc, char* argv[]) { - int c; - while ((c = getopt(argc, argv, "nfqs")) != -1) { - switch (c) { - case 'n': - skip_newline = 1; - break; - case 'f': - canonicalize = 1; - break; - case 'q': - case 's': - quiet_errors = 1; - break; - case '?': - default: - usage(argv[0]); - return EXIT_FAILURE; - } - } - int index = optind; - if (argc - index != 1) { - usage(argv[0]); - return EXIT_FAILURE; - } - - char name[PATH_MAX+1]; - if (canonicalize) { - if(!realpath(argv[optind], name)) { - if (!quiet_errors) { - perror("readlink"); - } - return EXIT_FAILURE; - } - } else { - ssize_t len = readlink(argv[1], name, PATH_MAX); - - if (len < 0) { - if (!quiet_errors) { - perror("readlink"); - } - return EXIT_FAILURE; - } - name[len] = '\0'; - } - - fputs(name, stdout); - if (!skip_newline) { - fputs("\n", stdout); - } - - return EXIT_SUCCESS; -} diff --git a/toolbox/readtty.c b/toolbox/readtty.c deleted file mode 100644 index 2b27548..0000000 --- a/toolbox/readtty.c +++ /dev/null @@ -1,183 +0,0 @@ -#include <ctype.h> -#include <stdio.h> -#include <stdlib.h> -#include <sys/mman.h> -#include <fcntl.h> -#include <string.h> -#include <termios.h> -#include <unistd.h> - -struct { - char key; - char *chars; -} map[] = { - { '1', "_ -1?!,.:;\"'<=>()_" }, - { '2', "Cabc2ABC" }, - { '3', "Fdef3DEF" }, - { '4', "Ighi4GHI" }, - { '5', "Ljkl5JKL" }, - { '6', "Omno6MNO" }, - { '7', "Spqrs7PQRS" }, - { '8', "Vtuv8TUV" }, - { '9', "Zwxyz9WXYZ" }, - { '0', "*+&0@/#*" }, -}; - -char next_char(char key, char current) -{ - int i; - char *next; - for(i = 0; i < sizeof(map) / sizeof(map[0]); i++) { - if(key == map[i].key) { - next = strchr(map[i].chars, current); - if(next && next[1]) - return next[1]; - return map[i].chars[1]; - } - } - return key; -} - -char prev_char(char key, char current) -{ - int i; - char *next; - for(i = 0; i < sizeof(map) / sizeof(map[0]); i++) { - if(key == map[i].key) { - next = strchr(map[i].chars+1, current); - if(next && next[-1]) - return next[-1]; - return map[i].chars[1]; - } - } - return key; -} - -int readtty_main(int argc, char *argv[]) -{ - int c; - //int flags; - char buf[1]; - int res; - struct termios ttyarg; - struct termios savedttyarg; - int nonblock = 0; - int timeout = 0; - int flush = 0; - int phone = 0; - char *accept = NULL; - char *rejectstring = NULL; - char last_char_in = 0; - char current_char = 0; - char *exit_string = NULL; - int exit_match = 0; - - do { - c = getopt(argc, argv, "nt:fa:r:pe:"); - if (c == EOF) - break; - switch (c) { - case 't': - timeout = atoi(optarg); - break; - case 'n': - nonblock = 1; - break; - case 'f': - flush = 1; - break; - case 'a': - accept = optarg; - break; - case 'r': - rejectstring = optarg; - break; - case 'p': - phone = 1; - break; - case 'e': - exit_string = optarg; - break; - case '?': - fprintf(stderr, "%s: invalid option -%c\n", - argv[0], optopt); - exit(1); - } - } while (1); - - if(flush) - tcflush(STDIN_FILENO, TCIFLUSH); - ioctl(STDIN_FILENO, TCGETS , &savedttyarg) ; /* set changed tty arguments */ - ttyarg = savedttyarg; - ttyarg.c_cc[VMIN] = (timeout > 0 || nonblock) ? 0 : 1; /* minimum of 0 chars */ - ttyarg.c_cc[VTIME] = timeout; /* wait max 15/10 sec */ - ttyarg.c_iflag = BRKINT | ICRNL; - ttyarg.c_lflag &= ~(ECHO | ICANON); - ioctl(STDIN_FILENO, TCSETS , &ttyarg); - - while (1) { - res = read(STDIN_FILENO, buf, 1); - if(res <= 0) { - if(phone) { - if(current_char) { - write(STDERR_FILENO, ¤t_char, 1); - write(STDOUT_FILENO, ¤t_char, 1); - if(exit_string && current_char == exit_string[exit_match]) { - exit_match++; - if(exit_string[exit_match] == '\0') - break; - } - else - exit_match = 0; - current_char = 0; - } - continue; - } - break; - } - if(accept && strchr(accept, buf[0]) == NULL) { - if(rejectstring) { - write(STDOUT_FILENO, rejectstring, strlen(rejectstring)); - break; - } - if(flush) - tcflush(STDIN_FILENO, TCIFLUSH); - continue; - } - if(phone) { - //if(!isprint(buf[0])) { - // fprintf(stderr, "got unprintable character 0x%x\n", buf[0]); - //} - if(buf[0] == '\0') { - if(current_char) { - current_char = prev_char(last_char_in, current_char); - write(STDERR_FILENO, ¤t_char, 1); - write(STDERR_FILENO, "\b", 1); - } - continue; - } - if(current_char && buf[0] != last_char_in) { - write(STDERR_FILENO, ¤t_char, 1); - write(STDOUT_FILENO, ¤t_char, 1); - if(exit_string && current_char == exit_string[exit_match]) { - exit_match++; - if(exit_string[exit_match] == '\0') - break; - } - else - exit_match = 0; - current_char = 0; - } - last_char_in = buf[0]; - current_char = next_char(last_char_in, current_char); - write(STDERR_FILENO, ¤t_char, 1); - write(STDERR_FILENO, "\b", 1); - continue; - } - write(STDOUT_FILENO, buf, 1); - break; - } - ioctl(STDIN_FILENO, TCSETS , &savedttyarg) ; /* set changed tty arguments */ - - return 0; -} diff --git a/toolbox/rmmod.c b/toolbox/rmmod.c deleted file mode 100644 index c7e0d6a..0000000 --- a/toolbox/rmmod.c +++ /dev/null @@ -1,53 +0,0 @@ -#include <stdio.h> -#include <string.h> -#include <fcntl.h> -#include <unistd.h> -#include <malloc.h> -#include <errno.h> -#include <asm/unistd.h> - -extern int delete_module(const char *, unsigned int); - -int rmmod_main(int argc, char **argv) -{ - int ret, i; - char *modname, *dot; - - /* make sure we've got an argument */ - if (argc < 2) { - fprintf(stderr, "usage: rmmod <module>\n"); - return -1; - } - - /* if given /foo/bar/blah.ko, make a weak attempt - * to convert to "blah", just for convenience - */ - modname = strrchr(argv[1], '/'); - if (!modname) - modname = argv[1]; - else modname++; - - dot = strchr(argv[1], '.'); - if (dot) - *dot = '\0'; - - /* Replace "-" with "_". This would keep rmmod - * compatible with module-init-tools version of - * rmmod - */ - for (i = 0; modname[i] != '\0'; i++) { - if (modname[i] == '-') - modname[i] = '_'; - } - - /* pass it to the kernel */ - ret = delete_module(modname, O_NONBLOCK | O_EXCL); - if (ret != 0) { - fprintf(stderr, "rmmod: delete_module '%s' failed (errno %d)\n", - modname, errno); - return -1; - } - - return 0; -} - diff --git a/toolbox/rotatefb.c b/toolbox/rotatefb.c deleted file mode 100644 index 2ff4127..0000000 --- a/toolbox/rotatefb.c +++ /dev/null @@ -1,71 +0,0 @@ -#include <ctype.h> -#include <stdio.h> -#include <stdlib.h> -#include <sys/mman.h> -#include <fcntl.h> -#include <string.h> -#include <termios.h> -#include <unistd.h> -#include <errno.h> -#include <linux/fb.h> - - -int rotatefb_main(int argc, char *argv[]) -{ - int c; - char *fbdev = "/dev/graphics/fb0"; - int rotation = 0; - int fd; - int res; - struct fb_var_screeninfo fbinfo; - - do { - c = getopt(argc, argv, "d:"); - if (c == EOF) - break; - switch (c) { - case 'd': - fbdev = optarg; - break; - case '?': - fprintf(stderr, "%s: invalid option -%c\n", - argv[0], optopt); - exit(1); - } - } while (1); - - if(optind + 1 != argc) { - fprintf(stderr, "%s: specify rotation\n", argv[0]); - exit(1); - } - rotation = atoi(argv[optind]); - - fd = open(fbdev, O_RDWR); - if(fd < 0) { - fprintf(stderr, "cannot open %s\n", fbdev); - return 1; - } - - res = ioctl(fd, FBIOGET_VSCREENINFO, &fbinfo); - if(res < 0) { - fprintf(stderr, "failed to get fbinfo: %s\n", strerror(errno)); - return 1; - } - if((fbinfo.rotate ^ rotation) & 1) { - unsigned int xres = fbinfo.yres; - fbinfo.yres = fbinfo.xres; - fbinfo.xres = xres; - fbinfo.xres_virtual = fbinfo.xres; - fbinfo.yres_virtual = fbinfo.yres * 2; - if(fbinfo.yoffset == xres) - fbinfo.yoffset = fbinfo.yres; - } - fbinfo.rotate = rotation; - res = ioctl(fd, FBIOPUT_VSCREENINFO, &fbinfo); - if(res < 0) { - fprintf(stderr, "failed to set fbinfo: %s\n", strerror(errno)); - return 1; - } - - return 0; -} diff --git a/toolbox/setkey.c b/toolbox/setkey.c deleted file mode 100644 index 1ff2774..0000000 --- a/toolbox/setkey.c +++ /dev/null @@ -1,89 +0,0 @@ -#include <stdio.h> -#include <stdlib.h> -#include <fcntl.h> -#include <string.h> -#include <linux/kd.h> -#include <linux/vt.h> -#include <errno.h> - -static void setkey_usage(char *argv[]) -{ - fprintf(stderr, "%s [-t <table>] [-k <index>] [-v value] [-r] [-h]\n" - " -t <table> Select table\n" - " -k <index> Select key\n" - " -v <value> Set entry\n" - " -r Read current entry\n" - " -h Print help\n", argv[0]); -} - -#define TTYDEV "/dev/tty0" - -int setkey_main(int argc, char *argv[]) -{ - int fd; - struct kbentry kbe; - int did_something = 0; - - kbe.kb_table = 0; - kbe.kb_index = -1; - kbe.kb_value = 0; - - fd = open(TTYDEV, O_RDWR | O_SYNC); - if (fd < 0) { - fprintf(stderr, "open %s: %s\n", TTYDEV, strerror(errno)); - return 1; - } - - do { - int c, ret; - - c = getopt(argc, argv, "t:k:v:hr"); - if (c == EOF) - break; - - switch (c) { - case 't': - kbe.kb_table = strtol(optarg, NULL, 0); - break; - case 'k': - kbe.kb_index = strtol(optarg, NULL, 0); - break; - case 'v': - kbe.kb_value = strtol(optarg, NULL, 0); - ret = ioctl(fd, KDSKBENT, &kbe); - if (ret < 0) { - fprintf(stderr, "KDSKBENT %d %d %d failed: %s\n", - kbe.kb_table, kbe.kb_index, kbe.kb_value, - strerror(errno)); - return 1; - } - did_something = 1; - break; - case 'r': - ret = ioctl(fd, KDGKBENT, &kbe); - if (ret < 0) { - fprintf(stderr, "KDGKBENT %d %d failed: %s\n", - kbe.kb_table, kbe.kb_index, strerror(errno)); - return 1; - } - printf("0x%x 0x%x 0x%x\n", - kbe.kb_table, kbe.kb_index, kbe.kb_value); - did_something = 1; - break; - case 'h': - setkey_usage(argv); - return 1; - case '?': - fprintf(stderr, "%s: invalid option -%c\n", - argv[0], optopt); - return 1; - } - } while (1); - - if(optind != argc || !did_something) { - setkey_usage(argv); - return 1; - } - - return 0; -} diff --git a/toolbox/swapoff.c b/toolbox/swapoff.c deleted file mode 100644 index d8f6a00..0000000 --- a/toolbox/swapoff.c +++ /dev/null @@ -1,20 +0,0 @@ -#include <stdio.h> -#include <unistd.h> -#include <sys/swap.h> - -int swapoff_main(int argc, char **argv) -{ - int err = 0; - - if (argc != 2) { - fprintf(stderr, "Usage: %s <filename>\n", argv[0]); - return -EINVAL; - } - - err = swapoff(argv[1]); - if (err) { - fprintf(stderr, "swapoff failed for %s\n", argv[1]); - } - - return err; -} diff --git a/toolbox/swapon.c b/toolbox/swapon.c deleted file mode 100644 index 150701a..0000000 --- a/toolbox/swapon.c +++ /dev/null @@ -1,66 +0,0 @@ -#include <stdio.h> -#include <stdlib.h> -#include <unistd.h> -#include <getopt.h> -#include <sys/swap.h> - -static void usage(char *name) -{ - fprintf(stderr, "Usage: %s [-p prio] <filename>\n" - " prio must be between 0 and %d\n", name, SWAP_FLAG_PRIO_MASK); -} - -static int parse_prio(char *prio_str) -{ - unsigned long p = strtoul(prio_str, NULL, 10); - - return (p > SWAP_FLAG_PRIO_MASK)? -1 : (int)p; -} - -int swapon_main(int argc, char **argv) -{ - int err = 0; - int flags = 0; - int prio; - - opterr = 0; - do { - int c = getopt(argc, argv, "hp:"); - if (c == -1) - break; - - switch (c) { - case 'p': - if (optarg != NULL) - prio = parse_prio(optarg); - else - prio = -1; - - if (prio < 0) { - usage(argv[0]); - return -EINVAL; - } - flags |= SWAP_FLAG_PREFER; - flags |= (prio << SWAP_FLAG_PRIO_SHIFT) & SWAP_FLAG_PRIO_MASK; - break; - case 'h': - usage(argv[0]); - return 0; - case '?': - fprintf(stderr, "unknown option: %c\n", optopt); - return -EINVAL; - } - } while (1); - - if (optind != argc - 1) { - usage(argv[0]); - return -EINVAL; - } - - err = swapon(argv[argc - 1], flags); - if (err) { - fprintf(stderr, "swapon failed for %s\n", argv[argc - 1]); - } - - return err; -} diff --git a/toolbox/syren.c b/toolbox/syren.c deleted file mode 100644 index 47c2460..0000000 --- a/toolbox/syren.c +++ /dev/null @@ -1,158 +0,0 @@ -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <unistd.h> -#include <fcntl.h> -#include <malloc.h> - -/* ioctl crap */ -#define SYREN_RD 101 -#define SYREN_WR 102 -#define SYREN_OLD_RD 108 -#define SYREN_OLD_WR 109 - -struct syren_io_args { - unsigned long page; - unsigned long addr; - unsigned long value; -}; - -typedef struct { - u_char page; - u_char addr; - const char *name; -} syren_reg; - -static syren_reg registers[] = { - { 0, 0x04, "TOGBR1" }, - { 0, 0x05, "TOGBR2" }, - { 0, 0x06, "VBDCTRL" }, - { 1, 0x07, "VBUCTRL" }, - { 1, 0x08, "VBCTRL" }, - { 1, 0x09, "PWDNRG" }, - { 1, 0x0a, "VBPOP" }, - { 1, 0x0b, "VBCTRL2" }, - { 1, 0x0f, "VAUDCTRL" }, - { 1, 0x10, "VAUSCTRL" }, - { 1, 0x11, "VAUOCTRL" }, - { 1, 0x12, "VAUDPLL" }, - { 1, 0x17, "VRPCSIMR" }, - { 0, 0, 0 } -}; - -static syren_reg *find_reg(const char *name) -{ - int i; - - for (i = 0; registers[i].name != 0; i++) { - if (!strcasecmp(registers[i].name, name)) - return ®isters[i]; - } - - return NULL; -} - -static int usage(void) -{ - fprintf(stderr, "usage: syren [r/w] [REGNAME | page:addr] (value)\n"); - return 1; -} - -int -syren_main(int argc, char **argv) -{ - int cmd = -1; - syren_reg *r; - struct syren_io_args sio; - char name[32]; - int fd; - - if (argc < 3) { - return usage(); - } - - switch(argv[1][0]) { - case 'r': - cmd = SYREN_RD; - break; - case 'w': - cmd = SYREN_WR; - break; - case 'R': - cmd = SYREN_OLD_RD; - break; - case 'W': - cmd = SYREN_OLD_WR; - break; - default: - return usage(); - } - - if (cmd == SYREN_WR || cmd == SYREN_OLD_WR) { - if (argc < 4) - return usage(); - sio.value = strtoul(argv[3], 0, 0); - } - - fd = open("/dev/eac", O_RDONLY); - if (fd < 0) { - fprintf(stderr, "can't open /dev/eac\n"); - return 1; - } - - if (strcasecmp(argv[2], "all") == 0) { - int i; - if (cmd != SYREN_RD && cmd != SYREN_OLD_RD) { - fprintf(stderr, "can only read all registers\n"); - return 1; - } - - for (i = 0; registers[i].name; i++) { - sio.page = registers[i].page; - sio.addr = registers[i].addr; - if (ioctl(fd, cmd, &sio) < 0) { - fprintf(stderr, "%s: error\n", registers[i].name); - } else { - fprintf(stderr, "%s: %04x\n", registers[i].name, sio.value); - } - } - - close(fd); - return 0; - } - - r = find_reg(argv[2]); - if (r == NULL) { - if(strlen(argv[2]) >= sizeof(name)){ - fprintf(stderr, "REGNAME too long\n"); - return 0; - } - strlcpy(name, argv[2], sizeof(name)); - char *addr_str = strchr(argv[2], ':'); - if (addr_str == NULL) - return usage(); - *addr_str++ = 0; - sio.page = strtoul(argv[2], 0, 0); - sio.addr = strtoul(addr_str, 0, 0); - } else { - strlcpy(name, r->name, sizeof(name)); - sio.page = r->page; - sio.addr = r->addr; - } - - if (ioctl(fd, cmd, &sio) < 0) { - fprintf(stderr, "ioctl(%d) failed\n", cmd); - return 1; - } - - if (cmd == SYREN_RD || cmd == SYREN_OLD_RD) { - printf("%s: %04x\n", name, sio.value); - } else { - printf("wrote %04x to %s\n", sio.value, name); - } - - close(fd); - - return 0; -} - diff --git a/toolbox/upstream-freebsd/usr.bin/false/false.c b/toolbox/upstream-freebsd/usr.bin/false/false.c deleted file mode 100644 index 99948bc..0000000 --- a/toolbox/upstream-freebsd/usr.bin/false/false.c +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 1988, 1993 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 lint -static const char copyright[] = -"@(#) Copyright (c) 1988, 1993\n\ - The Regents of the University of California. All rights reserved.\n"; -#endif /* not lint */ - -#ifndef lint -static const char sccsid[] = "@(#)false.c 8.1 (Berkeley) 6/6/93"; -#endif /* not lint */ -#include <sys/cdefs.h> -__FBSDID("$FreeBSD$"); - -int -main(void) -{ - return 1; -} diff --git a/toolbox/upstream-freebsd/usr.bin/true/true.c b/toolbox/upstream-freebsd/usr.bin/true/true.c deleted file mode 100644 index a557f58..0000000 --- a/toolbox/upstream-freebsd/usr.bin/true/true.c +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 1988, 1993 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. - * - * $FreeBSD$ - */ - -#ifndef lint -static const char copyright[] = -"@(#) Copyright (c) 1988, 1993\n\ - The Regents of the University of California. All rights reserved.\n"; -#endif /* not lint */ - -#ifndef lint -static const char sccsid[] = "@(#)true.c 8.1 (Berkeley) 6/9/93"; -#endif /* not lint */ - -int -main(void) -{ - return 0; -} diff --git a/toolbox/upstream-netbsd/bin/kill/kill.c b/toolbox/upstream-netbsd/bin/kill/kill.c deleted file mode 100644 index 0592577..0000000 --- a/toolbox/upstream-netbsd/bin/kill/kill.c +++ /dev/null @@ -1,253 +0,0 @@ -/* $NetBSD: kill.c,v 1.27 2011/08/29 14:51:18 joerg Exp $ */ - -/* - * Copyright (c) 1988, 1993, 1994 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. - */ - -#include <sys/cdefs.h> -#if !defined(lint) && !defined(SHELL) -__COPYRIGHT("@(#) Copyright (c) 1988, 1993, 1994\ - The Regents of the University of California. All rights reserved."); -#endif /* not lint */ - -#ifndef lint -#if 0 -static char sccsid[] = "@(#)kill.c 8.4 (Berkeley) 4/28/95"; -#else -__RCSID("$NetBSD: kill.c,v 1.27 2011/08/29 14:51:18 joerg Exp $"); -#endif -#endif /* not lint */ - -#include <ctype.h> -#include <err.h> -#include <errno.h> -#include <signal.h> -#include <stdio.h> -#include <stdlib.h> -#include <limits.h> -#include <inttypes.h> -#include <string.h> -#include <termios.h> -#include <unistd.h> -#include <locale.h> -#include <sys/ioctl.h> - -#ifdef SHELL /* sh (aka ash) builtin */ -int killcmd(int, char *argv[]); -#define main killcmd -#include "../../bin/sh/bltin/bltin.h" -#endif /* SHELL */ - -__dead static void nosig(char *); -static void printsignals(FILE *); -static int signame_to_signum(char *); -__dead static void usage(void); - -int -main(int argc, char *argv[]) -{ - int errors; - intmax_t numsig, pid; - char *ep; - - setprogname(argv[0]); - setlocale(LC_ALL, ""); - if (argc < 2) - usage(); - - numsig = SIGTERM; - - argc--, argv++; - if (strcmp(*argv, "-l") == 0) { - argc--, argv++; - if (argc > 1) - usage(); - if (argc == 1) { - if (isdigit((unsigned char)**argv) == 0) - usage(); - numsig = strtoimax(*argv, &ep, 10); - /* check for correctly parsed number */ - if (*ep != '\0' || numsig == INTMAX_MIN || numsig == INTMAX_MAX) { - errx(EXIT_FAILURE, "illegal signal number: %s", - *argv); - /* NOTREACHED */ - } - if (numsig >= 128) - numsig -= 128; - /* and whether it fits into signals range */ - if (numsig <= 0 || numsig >= NSIG) - nosig(*argv); - printf("%s\n", sys_signame[(int) numsig]); - exit(0); - } - printsignals(stdout); - exit(0); - } - - if (!strcmp(*argv, "-s")) { - argc--, argv++; - if (argc < 1) { - warnx("option requires an argument -- s"); - usage(); - } - if (strcmp(*argv, "0")) { - if ((numsig = signame_to_signum(*argv)) < 0) - nosig(*argv); - } else - numsig = 0; - argc--, argv++; - } else if (**argv == '-') { - char *sn = *argv + 1; - if (isalpha((unsigned char)*sn)) { - if ((numsig = signame_to_signum(sn)) < 0) - nosig(sn); - } else if (isdigit((unsigned char)*sn)) { - numsig = strtoimax(sn, &ep, 10); - /* check for correctly parsed number */ - if (*ep || numsig == INTMAX_MIN || numsig == INTMAX_MAX ) { - errx(EXIT_FAILURE, "illegal signal number: %s", - sn); - /* NOTREACHED */ - } - /* and whether it fits into signals range */ - if (numsig < 0 || numsig >= NSIG) - nosig(sn); - } else - nosig(sn); - argc--, argv++; - } - - if (argc == 0) - usage(); - - for (errors = 0; argc; argc--, argv++) { -#ifdef SHELL - extern int getjobpgrp(const char *); - if (*argv[0] == '%') { - pid = getjobpgrp(*argv); - if (pid == 0) { - warnx("illegal job id: %s", *argv); - errors = 1; - continue; - } - } else -#endif - { - pid = strtoimax(*argv, &ep, 10); - /* make sure the pid is a number and fits into pid_t */ - if (!**argv || *ep || pid == INTMAX_MIN || - pid == INTMAX_MAX || pid != (pid_t) pid) { - - warnx("illegal process id: %s", *argv); - errors = 1; - continue; - } - } - if (kill((pid_t) pid, (int) numsig) == -1) { - warn("%s", *argv); - errors = 1; - } -#ifdef SHELL - /* Wakeup the process if it was suspended, so it can - exit without an explicit 'fg'. */ - if (numsig == SIGTERM || numsig == SIGHUP) - kill((pid_t) pid, SIGCONT); -#endif - } - - exit(errors); - /* NOTREACHED */ -} - -static int -signame_to_signum(char *sig) -{ - int n; - - if (strncasecmp(sig, "sig", 3) == 0) - sig += 3; - for (n = 1; n < NSIG; n++) { - if (!strcasecmp(sys_signame[n], sig)) - return (n); - } - return (-1); -} - -static void -nosig(char *name) -{ - - warnx("unknown signal %s; valid signals:", name); - printsignals(stderr); - exit(1); - /* NOTREACHED */ -} - -static void -printsignals(FILE *fp) -{ - int sig; - int len, nl; - const char *name; - int termwidth = 80; - - if (isatty(fileno(fp))) { - struct winsize win; - if (ioctl(fileno(fp), TIOCGWINSZ, &win) == 0 && win.ws_col > 0) - termwidth = win.ws_col; - } - - for (len = 0, sig = 1; sig < NSIG; sig++) { - name = sys_signame[sig]; - nl = 1 + strlen(name); - - if (len + nl >= termwidth) { - fprintf(fp, "\n"); - len = 0; - } else - if (len != 0) - fprintf(fp, " "); - len += nl; - fprintf(fp, "%s", name); - } - if (len != 0) - fprintf(fp, "\n"); -} - -static void -usage(void) -{ - - fprintf(stderr, "usage: %s [-s signal_name] pid ...\n" - " %s -l [exit_status]\n" - " %s -signal_name pid ...\n" - " %s -signal_number pid ...\n", - getprogname(), getprogname(), getprogname(), getprogname()); - exit(1); - /* NOTREACHED */ -} diff --git a/toolbox/upstream-netbsd/bin/sleep/sleep.c b/toolbox/upstream-netbsd/bin/sleep/sleep.c deleted file mode 100644 index 4349af4..0000000 --- a/toolbox/upstream-netbsd/bin/sleep/sleep.c +++ /dev/null @@ -1,159 +0,0 @@ -/* $NetBSD: sleep.c,v 1.24 2011/08/29 14:51:19 joerg Exp $ */ - -/* - * Copyright (c) 1988, 1993, 1994 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. - */ - -#include <sys/cdefs.h> -#ifndef lint -__COPYRIGHT("@(#) Copyright (c) 1988, 1993, 1994\ - The Regents of the University of California. All rights reserved."); -#endif /* not lint */ - -#ifndef lint -#if 0 -static char sccsid[] = "@(#)sleep.c 8.3 (Berkeley) 4/2/94"; -#else -__RCSID("$NetBSD: sleep.c,v 1.24 2011/08/29 14:51:19 joerg Exp $"); -#endif -#endif /* not lint */ - -#include <ctype.h> -#include <err.h> -#include <locale.h> -#include <math.h> -#include <signal.h> -#include <stdio.h> -#include <stdlib.h> -#include <time.h> -#include <unistd.h> - -__dead static void alarmhandle(int); -__dead static void usage(void); - -static volatile sig_atomic_t report_requested; -static void -report_request(int signo __unused) -{ - - report_requested = 1; -} - -int -main(int argc, char *argv[]) -{ - char *arg, *temp; - double fval, ival, val; - struct timespec ntime; - time_t original; - int ch, fracflag, rv; - - setprogname(argv[0]); - (void)setlocale(LC_ALL, ""); - - (void)signal(SIGALRM, alarmhandle); - - while ((ch = getopt(argc, argv, "")) != -1) - switch(ch) { - default: - usage(); - } - argc -= optind; - argv += optind; - - if (argc != 1) - usage(); - - /* - * Okay, why not just use atof for everything? Why bother - * checking if there is a fraction in use? Because the old - * sleep handled the full range of integers, that's why, and a - * double can't handle a large long. This is fairly useless - * given how large a number a double can hold on most - * machines, but now we won't ever have trouble. If you want - * 1000000000.9 seconds of sleep, well, that's your - * problem. Why use an isdigit() check instead of checking for - * a period? Because doing it this way means locales will be - * handled transparently by the atof code. - */ - fracflag = 0; - arg = *argv; - for (temp = arg; *temp != '\0'; temp++) - if (!isdigit((unsigned char)*temp)) - fracflag++; - - if (fracflag) { - val = atof(arg); - if (val <= 0) - usage(); - ival = floor(val); - fval = (1000000000 * (val-ival)); - ntime.tv_sec = ival; - ntime.tv_nsec = fval; - } - else { - ntime.tv_sec = atol(arg); - if (ntime.tv_sec <= 0) - return EXIT_SUCCESS; - ntime.tv_nsec = 0; - } - - original = ntime.tv_sec; - signal(SIGINFO, report_request); - while ((rv = nanosleep(&ntime, &ntime)) != 0) { - if (report_requested) { - /* Reporting does not bother with nanoseconds. */ - warnx("about %d second(s) left out of the original %d", - (int)ntime.tv_sec, (int)original); - report_requested = 0; - } else - break; - } - - if (rv == -1) - err(EXIT_FAILURE, "nanosleep failed"); - - return EXIT_SUCCESS; - /* NOTREACHED */ -} - -static void -usage(void) -{ - (void)fprintf(stderr, "usage: %s seconds\n", getprogname()); - exit(EXIT_FAILURE); - /* NOTREACHED */ -} - -/* ARGSUSED */ -static void -alarmhandle(int i) -{ - _exit(EXIT_SUCCESS); - /* NOTREACHED */ -} diff --git a/toolbox/upstream-netbsd/bin/sync/sync.c b/toolbox/upstream-netbsd/bin/sync/sync.c deleted file mode 100644 index 2b9c367..0000000 --- a/toolbox/upstream-netbsd/bin/sync/sync.c +++ /dev/null @@ -1,59 +0,0 @@ -/* $NetBSD: sync.c,v 1.13 2008/07/20 00:52:40 lukem Exp $ */ - -/* - * Copyright (c) 1987, 1993 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. - */ - -#include <sys/cdefs.h> -#ifndef lint -__COPYRIGHT("@(#) Copyright (c) 1987, 1993\ - The Regents of the University of California. All rights reserved."); -#endif /* not lint */ - -#ifndef lint -#if 0 -static char sccsid[] = "@(#)sync.c 8.1 (Berkeley) 5/31/93"; -#else -__RCSID("$NetBSD: sync.c,v 1.13 2008/07/20 00:52:40 lukem Exp $"); -#endif -#endif /* not lint */ - -#include <stdlib.h> -#include <unistd.h> - -int main(int, char *[]); - -/* ARGSUSED */ -int -main(int argc, char *argv[]) -{ - setprogname(argv[0]); - sync(); - exit(0); - /* NOTREACHED */ -} diff --git a/toolbox/upstream-netbsd/usr.bin/printenv/printenv.c b/toolbox/upstream-netbsd/usr.bin/printenv/printenv.c deleted file mode 100644 index e15384f..0000000 --- a/toolbox/upstream-netbsd/usr.bin/printenv/printenv.c +++ /dev/null @@ -1,102 +0,0 @@ -/* $NetBSD: printenv.c,v 1.12 2011/09/06 18:26:55 joerg Exp $ */ - -/* - * Copyright (c) 1987, 1993 - * The Regents of the University of California. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. - */ - -#include <sys/cdefs.h> -#ifndef lint -__COPYRIGHT("@(#) Copyright (c) 1987, 1993\ - The Regents of the University of California. All rights reserved."); -#endif /* not lint */ - -#ifndef lint -/*static char sccsid[] = "from: @(#)printenv.c 8.2 (Berkeley) 5/4/95";*/ -__RCSID("$NetBSD: printenv.c,v 1.12 2011/09/06 18:26:55 joerg Exp $"); -#endif /* not lint */ - -#include <sys/types.h> - -#include <stdlib.h> -#include <stdio.h> -#include <string.h> -#include <unistd.h> -#include <err.h> - -__dead static void usage(void); - -/* - * printenv - * - * Bill Joy, UCB - * February, 1979 - */ -int -main(int argc, char *argv[]) -{ - extern char **environ; - char *cp, **ep; - size_t len; - int ch; - - while ((ch = getopt(argc, argv, "")) != -1) - switch(ch) { - case '?': - default: - usage(); - } - argc -= optind; - argv += optind; - - if (argc == 0) { - for (ep = environ; *ep; ep++) - (void)printf("%s\n", *ep); - exit(0); - } - if (argc != 1) - usage(); - if (strchr(*argv, '=') != NULL) - errx(1, "Invalid environment variable %s", *argv); - len = strlen(*argv); - for (ep = environ; *ep; ep++) - if (!memcmp(*ep, *argv, len)) { - cp = *ep + len; - if (!*cp || *cp == '=') { - (void)printf("%s\n", *cp ? cp + 1 : cp); - exit(0); - } - } - exit(1); -} - -static void -usage(void) -{ - (void)fprintf(stderr, "Usage: printenv [name]\n"); - exit(1); -} diff --git a/toolbox/vmstat.c b/toolbox/vmstat.c deleted file mode 100644 index 4086ed0..0000000 --- a/toolbox/vmstat.c +++ /dev/null @@ -1,247 +0,0 @@ -/* - * 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. - * * Neither the name of Google, Inc. nor the names of its contributors - * may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * 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. - */ - -#include <errno.h> -#include <stdio.h> -#include <stdlib.h> -#include <sys/param.h> -#include <unistd.h> - -struct state { - long procs_r; - long procs_b; - - long mem_free; - long mem_mapped; - long mem_anon; - long mem_slab; - - long sys_in; - long sys_cs; - long sys_flt; - - long cpu_us; - long cpu_ni; - long cpu_sy; - long cpu_id; - long cpu_wa; - long cpu_ir; - long cpu_si; -}; - -#define MAX_LINE 256 - -char line[MAX_LINE]; - -static void read_state(struct state *s); -static int read_meminfo(struct state *s); -static int read_stat(struct state *s); -static int read_vmstat(struct state *s); -static void print_header(void); -static void print_line(struct state *old, struct state *new); -static void usage(char *cmd); - -int vmstat_main(int argc, char *argv[]) { - struct state s[2]; - int iterations, delay, header_interval; - int toggle, count; - int i; - - iterations = -1; - delay = 1; - header_interval = 20; - - for (i = 1; i < argc; i++) { - if (!strcmp(argv[i], "-n")) { - if (i >= argc - 1) { - fprintf(stderr, "Option -n requires an argument.\n"); - exit(EXIT_FAILURE); - } - iterations = atoi(argv[++i]); - continue; - } - if (!strcmp(argv[i], "-d")) { - if (i >= argc - 1) { - fprintf(stderr, "Option -d requires an argument.\n"); - exit(EXIT_FAILURE); - } - delay = atoi(argv[++i]); - continue; - } - if (!strcmp(argv[i], "-r")) { - if (i >= argc - 1) { - fprintf(stderr, "Option -r requires an argument.\n"); - exit(EXIT_FAILURE); - } - header_interval = atoi(argv[++i]); - continue; - } - if (!strcmp(argv[i], "-h")) { - usage(argv[0]); - exit(EXIT_SUCCESS); - } - fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]); - usage(argv[0]); - exit(EXIT_FAILURE); - } - - toggle = 0; - count = 0; - - if (!header_interval) - print_header(); - read_state(&s[1 - toggle]); - while ((iterations < 0) || (iterations-- > 0)) { - sleep(delay); - read_state(&s[toggle]); - if (header_interval) { - if (count == 0) - print_header(); - count = (count + 1) % header_interval; - } - print_line(&s[1 - toggle], &s[toggle]); - toggle = 1 - toggle; - } - - return 0; -} - -static void read_state(struct state *s) { - int error; - - error = read_meminfo(s); - if (error) { - fprintf(stderr, "vmstat: could not read /proc/meminfo: %s\n", strerror(error)); - exit(EXIT_FAILURE); - } - - error = read_stat(s); - if (error) { - fprintf(stderr, "vmstat: could not read /proc/stat: %s\n", strerror(error)); - exit(EXIT_FAILURE); - } - - error = read_vmstat(s); - if (error) { - fprintf(stderr, "vmstat: could not read /proc/vmstat: %s\n", strerror(error)); - exit(EXIT_FAILURE); - } -} - -static int read_meminfo(struct state *s) { - FILE *f; - - f = fopen("/proc/meminfo", "r"); - if (!f) return errno; - - while (fgets(line, MAX_LINE, f)) { - sscanf(line, "MemFree: %ld kB", &s->mem_free); - sscanf(line, "AnonPages: %ld kB", &s->mem_anon); - sscanf(line, "Mapped: %ld kB", &s->mem_mapped); - sscanf(line, "Slab: %ld kB", &s->mem_slab); - } - - fclose(f); - - return 0; -} - -static int read_stat(struct state *s) { - FILE *f; - - f = fopen("/proc/stat", "r"); - if (!f) return errno; - - while (fgets(line, MAX_LINE, f)) { - if (!strncmp(line, "cpu ", 4)) { - sscanf(line, "cpu %ld %ld %ld %ld %ld %ld %ld", - &s->cpu_us, &s->cpu_ni, &s->cpu_sy, &s->cpu_id, &s->cpu_wa, - &s->cpu_ir, &s->cpu_si); - } - sscanf(line, "intr %ld", &s->sys_in); - sscanf(line, "ctxt %ld", &s->sys_cs); - sscanf(line, "procs_running %ld", &s->procs_r); - sscanf(line, "procs_blocked %ld", &s->procs_b); - } - - fclose(f); - - return 0; -} - -static int read_vmstat(struct state *s) { - FILE *f; - - f = fopen("/proc/vmstat", "r"); - if (!f) return errno; - - while (fgets(line, MAX_LINE, f)) { - sscanf(line, "pgmajfault %ld", &s->sys_flt); - } - - fclose(f); - - return 0; -} - -static void print_header(void) { - printf("%-5s %-27s %-14s %-17s\n", "procs", "memory", "system", "cpu"); - printf("%2s %2s %6s %6s %6s %6s %4s %4s %4s %2s %2s %2s %2s %2s %2s\n", "r", "b", "free", "mapped", "anon", "slab", "in", "cs", "flt", "us", "ni", "sy", "id", "wa", "ir"); -} - -/* Jiffies to percent conversion */ -#define JP(jif) ((jif) * 100 / (HZ)) -#define NORM(var) ((var) = (((var) > 99) ? (99) : (var))) - -static void print_line(struct state *old, struct state *new) { - int us, ni, sy, id, wa, ir; - us = JP(new->cpu_us - old->cpu_us); NORM(us); - ni = JP(new->cpu_ni - old->cpu_ni); NORM(ni); - sy = JP(new->cpu_sy - old->cpu_sy); NORM(sy); - id = JP(new->cpu_id - old->cpu_id); NORM(id); - wa = JP(new->cpu_wa - old->cpu_wa); NORM(wa); - ir = JP(new->cpu_ir - old->cpu_ir); NORM(ir); - printf("%2ld %2ld %6ld %6ld %6ld %6ld %4ld %4ld %4ld %2d %2d %2d %2d %2d %2d\n", - new->procs_r ? (new->procs_r - 1) : 0, new->procs_b, - new->mem_free, new->mem_mapped, new->mem_anon, new->mem_slab, - new->sys_in - old->sys_in, new->sys_cs - old->sys_cs, new->sys_flt - old->sys_flt, - us, ni, sy, id, wa, ir); -} - -static void usage(char *cmd) { - fprintf(stderr, "Usage: %s [ -h ] [ -n iterations ] [ -d delay ] [ -r header_repeat ]\n" - " -n iterations How many rows of data to print.\n" - " -d delay How long to sleep between rows.\n" - " -r header_repeat How many rows to print before repeating\n" - " the header. Zero means never repeat.\n" - " -h Displays this help screen.\n", - cmd); -} |