Project import
diff --git a/rootdev/Android.mk b/rootdev/Android.mk
new file mode 100644
index 0000000..0f53ed9
--- /dev/null
+++ b/rootdev/Android.mk
@@ -0,0 +1,39 @@
+# Copyright (C) 2015 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 := $(call my-dir)
+
+rootdev_CFLAGS := \
+ -D_BSD_SOURCE \
+ -D_FILE_OFFSET_BITS=64 \
+ -D_LARGEFILE_SOURCE \
+ -Wall -Werror -Wno-sign-compare \
+
+# Build the shared library.
+include $(CLEAR_VARS)
+LOCAL_MODULE := librootdev
+LOCAL_CFLAGS += $(rootdev_CFLAGS)
+LOCAL_CLANG := true
+LOCAL_SRC_FILES := rootdev.c
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)
+include $(BUILD_SHARED_LIBRARY)
+
+# Build the command line tool.
+include $(CLEAR_VARS)
+LOCAL_MODULE := rootdev
+LOCAL_CFLAGS += $(rootdev_CFLAGS)
+LOCAL_CLANG := true
+LOCAL_SHARED_LIBRARIES := librootdev
+LOCAL_SRC_FILES := main.c
+include $(BUILD_EXECUTABLE)
diff --git a/rootdev/MODULE_LICENSE_BSD b/rootdev/MODULE_LICENSE_BSD
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/rootdev/MODULE_LICENSE_BSD
diff --git a/rootdev/Makefile b/rootdev/Makefile
new file mode 100644
index 0000000..5e83c57
--- /dev/null
+++ b/rootdev/Makefile
@@ -0,0 +1,27 @@
+# Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+CFLAGS += -Wall -Werror
+
+# Support large files and major:minor numbers
+CPPFLAGS += -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE
+
+OUT = $(CURDIR)
+$(shell mkdir -p $(OUT))
+
+all: $(OUT)/rootdev $(OUT)/librootdev.so.1.0
+
+$(OUT)/rootdev: main.c $(OUT)/librootdev.so.1.0
+ $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $^ -o $@
+
+$(OUT)/librootdev.so.1.0: rootdev.c
+ $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -shared -fPIC \
+ -Wl,-soname,librootdev.so.1 $< -o $@
+ ln -s $(@F) $(OUT)/librootdev.so.1
+ ln -s $(@F) $(OUT)/librootdev.so
+
+clean:
+ rm -f $(OUT)/rootdev $(OUT)/librootdev.so*
+
+.PHONY: clean
diff --git a/rootdev/NOTICE b/rootdev/NOTICE
new file mode 100644
index 0000000..d251496
--- /dev/null
+++ b/rootdev/NOTICE
@@ -0,0 +1,27 @@
+// Copyright (c) 2010 The Chromium OS Authors. 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.
diff --git a/rootdev/README.chromium b/rootdev/README.chromium
new file mode 100644
index 0000000..6e4e903
--- /dev/null
+++ b/rootdev/README.chromium
@@ -0,0 +1,15 @@
+Chromium OS version of rootdev
+
+Inspired by git://git.debian.org/~lamont/util-linux.git / 717db2c8177203fe242ea35b31bc312abe9aa3c9
+
+Description: Performs operations to discover and annotate the root block device
+
+Prior to this commit, rootdev was derived from the above link. However, it has
+been rewritten in its entirety and licensed as per LICENSE.
+
+chromeos-rootdev:
+- Provides core functionality in a library: librootdev
+- Walks sysfs to discover the block devices
+- Supports resolving through to /sys/block/XXX/slaves/*/dev devices
+- Will test and, optionally, symlink to the /dev entry for standard devices.
+- Is testable.
diff --git a/rootdev/inherit-review-settings-ok b/rootdev/inherit-review-settings-ok
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/rootdev/inherit-review-settings-ok
diff --git a/rootdev/main.c b/rootdev/main.c
new file mode 100644
index 0000000..b2838eb
--- /dev/null
+++ b/rootdev/main.c
@@ -0,0 +1,158 @@
+/* Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ *
+ * Driver for using rootdev.c from the commandline
+ */
+#include <err.h>
+#include <errno.h>
+#include <getopt.h>
+#include <linux/limits.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "rootdev.h"
+
+static void print_help(const char *progname) {
+ fprintf(stderr,
+ "%s [OPTIONS] [PATH]\n"
+ "Outputs the containing device for the specified PATH.\n"
+ "With no arguments, '/' is assumed.\n"
+ "\n"
+ "Options:\n"
+ " -h\tthis message.\n"
+ "\n"
+ " -c\tcreate the /dev node if it cannot be found\n"
+ " -d\treturn the block device only if possible\n"
+ " -i\treturn path even if the node doesn't exist\n"
+ " -s\tif possible, return the first slave of the root device\n"
+ "\n"
+ " --block [path]\tset the path to block under the sys mount point\n"
+ " --dev [path]\tset the path to dev mount point\n"
+ " --major [num]\tset the major number of the rootdev\n"
+ " --minor [num]\tset the minor number of the rootdev\n",
+ progname);
+}
+
+static int flag_help = 0;
+static int flag_use_slave = 0;
+static int flag_strip_partition = 0;
+static int flag_ignore = 0;
+static int flag_create = 0;
+static int flag_major = 0;
+static int flag_minor = 0;
+static const char *flag_path = "/";
+static char *flag_block_path = NULL;
+static char *flag_dev_path = NULL;
+
+static void parse_args(int argc, char **argv) {
+ while (1) {
+ int c;
+ int option_index = 0;
+ static const struct option long_options[] = {
+ {"c", no_argument, &flag_create, 1},
+ {"d", no_argument, &flag_strip_partition, 1},
+ {"h", no_argument, &flag_help, 1},
+ {"i", no_argument, &flag_ignore, 1},
+ {"s", no_argument, &flag_use_slave, 1},
+ /* Long arguments for testing. */
+ {"block", required_argument, NULL, 'b'},
+ {"dev", required_argument, NULL, 'd'},
+ {"major", required_argument, NULL, 'M'},
+ {"minor", required_argument, NULL, 'm'},
+ {0, 0, 0, 0}
+ };
+ c = getopt_long_only(argc, argv, "", long_options, &option_index);
+
+ if (c == -1)
+ break;
+
+ if (c == '?') {
+ flag_help = 1;
+ break;
+ }
+
+ switch (c) {
+ case 'b':
+ flag_block_path = optarg;
+ break;
+ case 'd':
+ flag_dev_path = optarg;
+ break;
+ case 'M':
+ flag_major = atoi(optarg);
+ break;
+ case 'm':
+ flag_minor = atoi(optarg);
+ break;
+ }
+
+ }
+
+ if (flag_create && flag_strip_partition) {
+ flag_help = 1;
+ warnx("-c and -d are incompatible at present.");
+ return;
+ }
+
+ if (optind < argc) {
+ flag_path = argv[optind++];
+ }
+
+ if (optind < argc) {
+ fprintf(stderr, "Too many free arguments: %d\n", argc - optind);
+ flag_help = 1;
+ }
+}
+
+int main(int argc, char **argv) {
+ struct stat path_stat;
+ char path[PATH_MAX];
+ int ret;
+ dev_t root_dev;
+ parse_args(argc, argv);
+
+ if (flag_help) {
+ print_help(argv[0]);
+ return 1;
+ }
+
+ if (flag_major || flag_minor) {
+ root_dev = makedev(flag_major, flag_minor);
+ } else {
+ /* Yields the containing dev_t in st_dev. */
+ if (stat(flag_path, &path_stat) != 0)
+ err(1, "Cannot stat(%s)", flag_path);
+ root_dev = path_stat.st_dev;
+ }
+
+ path[0] = '\0';
+ ret = rootdev_wrapper(path, sizeof(path),
+ flag_use_slave,
+ flag_strip_partition,
+ &root_dev,
+ flag_block_path,
+ flag_dev_path);
+
+ if (ret == 1 && flag_create) {
+ /* TODO(wad) add flag_force to allow replacement */
+ ret = 0;
+ if (mknod(path, S_IFBLK | S_IRUSR | S_IWUSR, root_dev) && errno != EEXIST) {
+ warn("failed to create %s", path);
+ ret = 1;
+ }
+ }
+
+ if (flag_ignore && ret > 0)
+ ret = 0;
+
+ if (path[0] != '\0')
+ printf("%s\n", path);
+
+ return ret;
+}
diff --git a/rootdev/rootdev.c b/rootdev/rootdev.c
new file mode 100644
index 0000000..e4c6d55
--- /dev/null
+++ b/rootdev/rootdev.c
@@ -0,0 +1,429 @@
+/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ *
+ * Implements root device discovery via sysfs with optional bells and whistles.
+ */
+
+#include "rootdev.h"
+
+#include <ctype.h>
+#include <dirent.h>
+#include <err.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+/*
+ * Limit prevents endless looping to find slave.
+ * We currently have at most 2 levels, this allows
+ * for future growth.
+ */
+#define MAX_SLAVE_DEPTH 8
+
+static const char *kDefaultSearchPath = "/sys/block";
+static const char *kDefaultDevPath = "/dev/block";
+
+/* Encode the root device structuring here for Chromium OS */
+static const char kActiveRoot[] = "/dev/ACTIVE_ROOT";
+static const char kRootDev[] = "/dev/ROOT";
+static const char kRootA[] = "/dev/ROOT0";
+static const char kRootB[] = "/dev/ROOT1";
+
+struct part_config {
+ const char *name;
+ int offset;
+};
+
+#define CHROMEOS_PRIMARY_PARTITION 3
+static const struct part_config kPrimaryPart[] = { { kRootA, 0 },
+ { kRootDev, -3 },
+ { kRootB, 2 } };
+#define CHROMEOS_SECONDARY_PARTITION 5
+static const struct part_config kSecondaryPart[] = { { kRootB, 0 },
+ { kRootDev, -5 },
+ { kRootA, -2 } };
+
+/* The number of entries in a part_config so we could add RootC easily. */
+static const int kPartitionEntries = 3;
+
+/* Converts a file of %u:%u -> dev_t. */
+static dev_t devt_from_file(const char *file) {
+ char candidate[10]; /* TODO(wad) system-provided constant? */
+ ssize_t bytes = 0;
+ unsigned int major_num = 0;
+ unsigned int minor_num = 0;
+ dev_t dev = 0;
+ int fd = -1;
+
+ /* Never hang. Either get the data or return 0. */
+ fd = open(file, O_NONBLOCK | O_RDONLY);
+ if (fd < 0)
+ return 0;
+ bytes = read(fd, candidate, sizeof(candidate));
+ close(fd);
+
+ /* 0:0 should be considered the minimum size. */
+ if (bytes < 3)
+ return 0;
+ candidate[bytes] = 0;
+ if (sscanf(candidate, "%u:%u", &major_num, &minor_num) == 2) {
+ /* candidate's size artificially limits the size of the converted
+ * %u to safely convert to a signed int. */
+ dev = makedev(major_num, minor_num);
+ }
+ return dev;
+}
+
+/* Walks sysfs and recurses into any directory/link that represents
+ * a block device to find sub-devices (partitions) for dev.
+ * If dev == 0, the name fo the first device in the directory will be returned.
+ * Returns the device's name in "name" */
+static int match_sysfs_device(char *name, size_t name_len,
+ const char *basedir, dev_t *dev, int depth) {
+ int found = -1;
+ size_t basedir_len;
+ DIR *dirp = NULL;
+ struct dirent *entry = NULL;
+ struct dirent *next = NULL;
+ char *working_path = NULL;
+ long working_path_size = 0;
+
+ if (!name || !name_len || !basedir || !dev) {
+ warnx("match_sysfs_device: invalid arguments supplied");
+ return -1;
+ }
+ basedir_len = strlen(basedir);
+ if (!basedir_len) {
+ warnx("match_sysfs_device: basedir must not be empty");
+ return -1;
+ }
+
+ errno = 0;
+ dirp = opendir(basedir);
+ if (!dirp) {
+ /* Don't complain if the directory doesn't exist. */
+ if (errno != ENOENT)
+ warn("match_sysfs_device:opendir(%s)", basedir);
+ return found;
+ }
+
+ /* Grab a platform appropriate path to work with.
+ * Ideally, this won't vary under sys/block. */
+ working_path_size = pathconf(basedir, _PC_NAME_MAX) + 1;
+ /* Fallback to PATH_MAX on any pathconf error. */
+ if (working_path_size < 0)
+ working_path_size = PATH_MAX;
+
+ working_path = malloc(working_path_size);
+ if (!working_path) {
+ warn("malloc(dirent)");
+ closedir(dirp);
+ return found;
+ }
+
+ /* Allocate a properly sized entry. */
+ entry = malloc(offsetof(struct dirent, d_name) + working_path_size);
+ if (!entry) {
+ warn("malloc(dirent)");
+ free(working_path);
+ closedir(dirp);
+ return found;
+ }
+
+ while (readdir_r(dirp, entry, &next) == 0 && next) {
+ size_t candidate_len = strlen(entry->d_name);
+ size_t path_len = 0;
+ dev_t found_devt = 0;
+ /* Ignore the usual */
+ if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
+ continue;
+ /* TODO(wad) determine how to best bubble up this case. */
+ if (candidate_len > name_len)
+ continue;
+ /* Only traverse directories or symlinks (to directories ideally) */
+ switch (entry->d_type) {
+ case DT_UNKNOWN:
+ case DT_DIR:
+ case DT_LNK:
+ break;
+ default:
+ continue;
+ }
+ /* Determine path to block device number */
+ path_len = snprintf(working_path, working_path_size, "%s/%s/dev",
+ basedir, entry->d_name);
+ /* Ignore if truncation occurs. */
+ if (path_len != candidate_len + basedir_len + 5)
+ continue;
+
+ found_devt = devt_from_file(working_path);
+ /* *dev == 0 is a wildcard. */
+ if (!*dev || found_devt == *dev) {
+ snprintf(name, name_len, "%s", entry->d_name);
+ *dev = found_devt;
+ found = 1;
+ break;
+ }
+
+ /* Prevent infinite recursion on symlink loops by limiting depth. */
+ if (depth > 5)
+ break;
+
+ /* Recurse one level for devices that may have a matching partition. */
+ if (major(found_devt) == major(*dev) && minor(*dev) > minor(found_devt)) {
+ sprintf(working_path, "%s/%s", basedir, entry->d_name);
+ found = match_sysfs_device(name, name_len, working_path, dev, depth + 1);
+ if (found > 0)
+ break;
+ }
+ }
+
+ free(working_path);
+ free(entry);
+ closedir(dirp);
+ return found;
+}
+
+const char *rootdev_get_partition(const char *dst, size_t len) {
+ const char *end = dst + strnlen(dst, len);
+ const char *part = end - 1;
+ if (!len)
+ return NULL;
+
+ if (!isdigit(*part--))
+ return NULL;
+
+ while (part > dst && isdigit(*part)) part--;
+ part++;
+
+ if (part >= end)
+ return NULL;
+
+ return part;
+}
+
+void rootdev_strip_partition(char *dst, size_t len) {
+ char *part = (char *)rootdev_get_partition(dst, len);
+ if (!part)
+ return;
+ /* For devices that end with a digit, the kernel uses a 'p'
+ * as a separator. E.g., mmcblk1p2. */
+ if (*(part - 1) == 'p')
+ part--;
+ *part = '\0';
+}
+
+int rootdev_symlink_active(const char *path) {
+ int ret = 0;
+ /* Don't overwrite an existing link. */
+ errno = 0;
+ if ((symlink(path, kActiveRoot)) && errno != EEXIST) {
+ warn("failed to symlink %s -> %s", kActiveRoot, path);
+ ret = -1;
+ }
+ return ret;
+}
+
+int rootdev_get_device(char *dst, size_t size, dev_t dev,
+ const char *search) {
+ struct stat active_root_statbuf;
+
+ if (search == NULL)
+ search = kDefaultSearchPath;
+
+ /* Check if the -s symlink exists. */
+ if ((stat(kActiveRoot, &active_root_statbuf) == 0) &&
+ active_root_statbuf.st_rdev == dev) {
+ /* Note, if the link is not fully qualified, this won't be
+ * either. */
+ ssize_t len = readlink(kActiveRoot, dst, PATH_MAX);
+ if (len > 0) {
+ dst[len] = 0;
+ return 0;
+ }
+ /* If readlink fails or is empty, fall through */
+ }
+
+ snprintf(dst, size, "%s", search);
+ if (match_sysfs_device(dst, size, dst, &dev, 0) <= 0) {
+ fprintf (stderr, "unable to find match\n");
+ return 1;
+ }
+
+ return 0;
+}
+
+/*
+ * rootdev_get_device_slave returns results in slave which
+ * may be the original device or the name of the slave.
+ *
+ * Because slave and device may point to the same data,
+ * must be careful how they are handled because slave
+ * is modified (can't use snprintf).
+ */
+void rootdev_get_device_slave(char *slave, size_t size, dev_t *dev,
+ const char *device, const char *search) {
+ char dst[PATH_MAX];
+ int len = 0;
+ int i;
+
+ if (search == NULL)
+ search = kDefaultSearchPath;
+
+ /*
+ * With stacked device mappers, we have to chain through all the levels
+ * and find the last device. For example, verity can be stacked on bootcache
+ * that is stacked on a disk partition.
+ */
+ if (slave != device)
+ strncpy(slave, device, size);
+ slave[size - 1] = '\0';
+ for (i = 0; i < MAX_SLAVE_DEPTH; i++) {
+ len = snprintf(dst, sizeof(dst), "%s/%s/slaves", search, slave);
+ if (len != strlen(device) + strlen(search) + 8) {
+ warnx("rootdev_get_device_slave: device name too long");
+ return;
+ }
+ *dev = 0;
+ if (match_sysfs_device(slave, size, dst, dev, 0) <= 0) {
+ return;
+ }
+ }
+ warnx("slave depth greater than %d at %s", i, slave);
+}
+
+int rootdev_create_devices(const char *name, dev_t dev, bool symlink) {
+ int ret = 0;
+ unsigned int major_num = major(dev);
+ unsigned int minor_num = minor(dev);
+ int i;
+ const struct part_config *config;
+ const char *part_s = rootdev_get_partition(name, strlen(name));
+
+ if (part_s == NULL) {
+ warnx("create_devices: unable to determine partition");
+ return -1;
+ }
+
+ switch (atoi(part_s)) {
+ case CHROMEOS_PRIMARY_PARTITION:
+ config = kPrimaryPart;
+ break;
+ case CHROMEOS_SECONDARY_PARTITION:
+ config = kSecondaryPart;
+ break;
+ default:
+ warnx("create_devices: unable to determine partition: %s",
+ part_s);
+ return -1;
+ }
+
+ for (i = 0; i < kPartitionEntries; ++i) {
+ dev = makedev(major_num, minor_num + config[i].offset);
+ errno = 0;
+ if (mknod(config[i].name,
+ S_IFBLK | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH,
+ dev) && errno != EEXIST) {
+ warn("failed to create %s", config[i].name);
+ return -1;
+ }
+ }
+
+ if (symlink)
+ ret = rootdev_symlink_active(config[0].name);
+ return ret;
+}
+
+int rootdev_get_path(char *path, size_t size, const char *device,
+ const char *dev_path) {
+ int path_len;
+
+ if (!dev_path)
+ dev_path = kDefaultDevPath;
+
+ if (!path || !size || !device)
+ return -1;
+
+ path_len = snprintf(path, size, "%s/%s", dev_path, device);
+ if (path_len != strlen(dev_path) + 1 + strlen(device))
+ return -1;
+
+ // TODO(bsimonnet): We should check that |path| exists and is the right
+ // device. We don't do this currently as OEMs can add custom SELinux rules
+ // which may prevent us from accessing this.
+ // See b/24267261.
+
+ return 0;
+}
+
+int rootdev_wrapper(char *path, size_t size,
+ bool full, bool strip,
+ dev_t *dev,
+ const char *search, const char *dev_path) {
+ int res = 0;
+ char devname[PATH_MAX];
+ if (!search)
+ search = kDefaultSearchPath;
+ if (!dev_path)
+ dev_path = kDefaultDevPath;
+ if (!dev)
+ return -1;
+
+ res = rootdev_get_device(devname, sizeof(devname), *dev, search);
+ if (res != 0)
+ return res;
+
+ if (full)
+ rootdev_get_device_slave(devname, sizeof(devname), dev, devname,
+ search);
+
+ /* TODO(wad) we should really just track the block dev, partition number, and
+ * dev path. When we rewrite this, we can track all the sysfs info
+ * in the class. */
+ if (strip) {
+ /* When we strip the partition, we don't want get_path to return non-zero
+ * because of dev mismatch. Passing in 0 tells it to not test. */
+ *dev = 0;
+ rootdev_strip_partition(devname, size);
+ }
+
+ res = rootdev_get_path(path, size, devname, dev_path);
+
+ return res;
+}
+
+int rootdev(char *path, size_t size, bool full, bool strip) {
+ struct stat root_statbuf;
+ dev_t _root_dev, *root_dev = &_root_dev;
+
+ /* Yields the containing dev_t in st_dev. */
+ if (stat("/data", &root_statbuf) != 0)
+ return -1;
+
+ /* Some ABIs (like mips o32) are broken and the st_dev field isn't actually
+ * a dev_t. In that case, pass a pointer to a local dev_t who we took care
+ * of truncating the value into. On sane arches, gcc can optimize this to
+ * the same code, so should only be a penalty when the ABI is broken. */
+ if (sizeof(root_statbuf.st_dev) == sizeof(*root_dev)) {
+ /* Cast is OK since we verified size here. */
+ root_dev = (dev_t *)&root_statbuf.st_dev;
+ } else {
+ *root_dev = root_statbuf.st_dev;
+ }
+
+ return rootdev_wrapper(path,
+ size,
+ full,
+ strip,
+ root_dev,
+ NULL, /* default /sys dir */
+ NULL); /* default /dev dir */
+}
diff --git a/rootdev/rootdev.h b/rootdev/rootdev.h
new file mode 100644
index 0000000..aacfaf0
--- /dev/null
+++ b/rootdev/rootdev.h
@@ -0,0 +1,100 @@
+/* Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ *
+ * Interface for root device discovery via sysfs with optional
+ * bells and whistles.
+ */
+#ifndef ROOTDEV_ROOTDEV_H_
+#define ROOTDEV_ROOTDEV_H_
+
+#include <stdbool.h>
+#include <sys/types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * rootdev: returns the path to the root device in @path
+ * @path: pre-allocated char array the result will be written to
+ * @size: size of @path
+ * @full: whether to try to do full resolution. E.g., device-mapper
+ * @strip: whether to remove the partition # or not.
+ *
+ * Returns 0 on success, non-zero on error.
+ */
+int rootdev(char *path, size_t size, bool full, bool strip);
+
+/* All interface below this point will most definitely be C specific. If
+ * we rewrite this as a C++ class, only the above generic interface should
+ * still be provided.
+ */
+
+/**
+ * rootdev_wrapper: rootdev equivalent with paths can be substituted.
+ */
+int rootdev_wrapper(char *path, size_t size,
+ bool full, bool strip,
+ dev_t *dev,
+ const char *search, const char *dev_path);
+/**
+ * rootdev_get_device: finds the /dev path for @dev
+ * @dst: destination char array
+ * @size: size of @dst
+ * @dev: dev_t specifying the known root device
+ * @search: path to search under. NULL for default.
+ *
+ * Returns 0 on success, non-zero on error.
+ *
+ * The name of the devices is placed in @dst. It will not
+ * be qualified with /dev/ by default.
+ */
+int rootdev_get_device(char *dst, size_t size, dev_t dev,
+ const char *search);
+
+/**
+ * rootdev_get_device_slave: returns the first device under @device/slaves
+ * @slave: destination char array for storing the result
+ * @size: size of @slave
+ * @dev: pointer to a dev_t to populate
+ * @device: name of the device to probe, like "sdb"
+ * @search: path to search under. NULL for default.
+ *
+ * It is safe for @device == @slave.
+ */
+void rootdev_get_device_slave(char *slave, size_t size, dev_t *dev,
+ const char *device, const char *search);
+
+/**
+ * rootdev_get_path: converts a device name to a path in the device tree
+ * @path: char array to store the path
+ * @size: size of @devpath
+ * @device: name of the device
+ * @dev_path: path to dev tree. NULL for default (/dev)
+ *
+ * A @dev of 0 is ignored.
+ *
+ * @path is populated for all return codes.
+ * Returns 0 on success and non-zero on error:
+ * -1 on unexpected errors (@path may be invalid)
+ *
+ * Nb, this function does NOT search /dev for a match. It performs a normal
+ * string concatenation.
+ * We can't check if the device actually exists as vendors may create an
+ * SELinux context we don't know about for it (in which case, this function
+ * would always fail).
+ */
+int rootdev_get_path(char *path, size_t size, const char *device,
+ const char *dev_path);
+
+const char *rootdev_get_partition(const char *dst, size_t len);
+void rootdev_strip_partition(char *dst, size_t len);
+int rootdev_symlink_active(const char *path);
+int rootdev_create_devices(const char *name, dev_t dev, bool symlink);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* ROOTDEV_ROOTDEV_H_ */
diff --git a/rootdev/rootdev_test.sh b/rootdev/rootdev_test.sh
new file mode 100755
index 0000000..d236b2b
--- /dev/null
+++ b/rootdev/rootdev_test.sh
@@ -0,0 +1,292 @@
+#!/bin/bash
+# Copyright 2010 The Chromium OS Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+#
+# Simple functional test harness for rootdev
+# TODO(wad) rootdev should be rewritten in C++ and gmocked.
+
+set -u
+
+warn () {
+ echo "WARN: $@" 1>&2
+}
+
+error () {
+ echo "ERROR: $@" 1>&2
+ exit 1
+}
+
+PASS_COUNT=0
+pass () {
+ echo "PASS:$1" 1>&2
+ PASS_COUNT=$((PASS_COUNT + 1))
+ return 0
+}
+
+FAIL_COUNT=0
+fail () {
+ echo "FAIL:$1" 1>&2
+ FAIL_COUNT=$((FAIL_COUNT + 1))
+ return 0
+}
+
+WORKDIR=
+cleanup () {
+ if [ -n "$WORKDIR" ]; then
+ rm -rf "$WORKDIR"
+ fi
+ trap - EXIT
+}
+
+setup () {
+ WORKDIR=$(mktemp -d rootdev_test.XXXXXXX)
+ if [ ! -d "$WORKDIR" ]; then
+ error "Failed to create temporary work dir"
+ fi
+ trap cleanup EXIT
+}
+
+run_test () {
+ setup
+ echo "RUN:$1" 1>&2
+ eval $1
+ ret=$?
+ cleanup
+ if [ $ret -eq 0 ]; then
+ pass $1
+ else
+ fail $1
+ fi
+}
+
+expect () {
+ cond="$1"
+ eval test $1
+ if [ $? -ne 0 ]; then
+ warn "expect: $1"
+ return 1
+ fi
+ return 0
+}
+
+ROOTDEV=${1:-./rootdev}
+if [[ ! -e ${ROOTDEV} ]]; then
+ error "could not find rootdev '${ROOTDEV}'"
+fi
+
+if [ "${USER:-}" != "root" ]; then
+ error "Must be run as root to use mknod (${USER:-})"
+fi
+
+t00_bad_sys_dir () {
+ out=$("${ROOTDEV}" --block $WORKDIR 2>/dev/null)
+ expect "$? -ne 0" || return 1
+ expect "-z '$out'" || return 1
+}
+run_test t00_bad_sys_dir
+
+h00_setup_sda_tree() {
+ local block=$1
+ local dev=$2
+ mkdir -p $block
+ mkdir -p $dev
+ mkdir -p $block/sda/sda1
+ mkdir -p $block/sda/sda2
+ echo "10:0" > $block/sda/dev
+ echo "10:1" > $block/sda/sda1/dev
+ echo "10:2" > $block/sda/sda2/dev
+ mknod $dev/sda1 b 10 1
+ mknod $dev/sda2 b 10 2
+ mknod $dev/sda b 10 0
+}
+
+t01_sys_dev_match () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h00_setup_sda_tree $block $dev
+
+ out=$("${ROOTDEV}" --dev $dev --block $block --major 10 --minor 1 2>/dev/null)
+ expect "$? -eq 0" || return 1
+ expect "'$dev/sda1' = '$out'" || return 1
+}
+run_test t01_sys_dev_match
+
+t02_sys_dev_match_block () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h00_setup_sda_tree $block $dev
+
+ out=$("${ROOTDEV}" --dev $dev --block $block --major 10 --minor 0 2>/dev/null)
+ expect "$? -eq 0" || return 1
+ expect "'$dev/sda' = '$out'" || return 1
+}
+run_test t02_sys_dev_match_block
+
+t03_sys_dev_match_block_no_dev () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h00_setup_sda_tree $block $dev
+ rm $dev/sda
+
+ out=$("${ROOTDEV}" --dev $dev --block $block --major 10 --minor 0 2>/dev/null)
+ expect "$? -eq 1" || return 1
+ expect "'$dev/sda' = '$out'" || return 1
+}
+run_test t03_sys_dev_match_block_no_dev
+
+t04_sys_dev_match_block_no_dev_ignore () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h00_setup_sda_tree $block $dev
+ rm $dev/sda
+
+ out=$("${ROOTDEV}" -i --dev $dev --block $block --major 10 --minor 0 2>/dev/null)
+ expect "$? -eq 0" || return 1
+ expect "'$dev/sda' = '$out'" || return 1
+}
+run_test t04_sys_dev_match_block_no_dev_ignore
+
+
+h01_setup_dm_tree() {
+ local block=$1
+ local dev=$2
+ mkdir -p $block
+ mkdir -p $dev
+ mkdir -p $block/dm-0
+ mkdir -p $block/dm-0/slaves/sda1
+ echo "254:0" > $block/dm-0/dev
+ echo "10:1" > $block/dm-0/slaves/sda1/dev
+ mknod $dev/dm-0 b 254 0
+}
+
+t05_match_dm () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h00_setup_sda_tree $block $dev
+ h01_setup_dm_tree $block $dev
+
+ out=$("${ROOTDEV}" --dev $dev --block $block --major 254 --minor 0 \
+ 2>/dev/null)
+ expect "$? -eq 0" || return 1
+ expect "'$dev/dm-0' = '$out'" || return 1
+}
+run_test t05_match_dm
+
+t06_match_dm_slave () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h00_setup_sda_tree $block $dev
+ h01_setup_dm_tree $block $dev
+
+ out=$("${ROOTDEV}" -s --dev $dev --block $block --major 254 --minor 0 \
+ 2>/dev/null)
+ expect "$? -eq 0" || return 1
+ expect "'$dev/sda1' = '$out'" || return 1
+}
+run_test t06_match_dm_slave
+
+t07_safe_fail_on_no_slave () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h00_setup_sda_tree $block $dev
+ h01_setup_dm_tree $block $dev
+
+ out=$("${ROOTDEV}" -s --dev $dev --block $block --major 10 --minor 1 \
+ 2>/dev/null)
+ expect "$? -eq 0" || return 1
+ expect "'$dev/sda1' = '$out'" || return 1
+}
+run_test t07_safe_fail_on_no_slave
+
+t08_safe_fail_on_no_slave_dev () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h00_setup_sda_tree $block $dev
+ h01_setup_dm_tree $block $dev
+ # If the matching dev node is missing, an error code will be returned
+ # but the path will still represent the slave.
+ rm $dev/sda1
+
+ out=$("${ROOTDEV}" -s --dev $dev --block $block --major 254 --minor 0 \
+ 2>/dev/null)
+ expect "$? -eq 1" || return 1
+ expect "'$dev/sda1' = '$out'" || return 1
+}
+run_test t08_safe_fail_on_no_slave_dev
+
+t09_safe_fail_on_no_slave_dev_ignore () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h00_setup_sda_tree $block $dev
+ h01_setup_dm_tree $block $dev
+ # If the matching dev node is missing, an error code will be returned
+ # but the path will still represent the slave.
+ rm $dev/sda1
+
+ out=$("${ROOTDEV}" -i -s --dev $dev --block $block --major 254 --minor 0 \
+ 2>/dev/null)
+ expect "$? -eq 0" || return 1
+ expect "'$dev/sda1' = '$out'" || return 1
+}
+run_test t09_safe_fail_on_no_slave_dev_ignore
+
+h02_setup_mmc_tree() {
+ local block=$1
+ local dev=$2
+ mkdir -p $block
+ mkdir -p $dev
+ mkdir -p $block/mmcblk0/mmcblk0p1
+ mkdir -p $block/mmcblk0/mmcblk0p2
+ echo "11:0" > $block/mmcblk0/dev
+ echo "11:1" > $block/mmcblk0/mmcblk0p1/dev
+ echo "11:2" > $block/mmcblk0/mmcblk0p2/dev
+ mknod $dev/mmcblk0 b 11 0
+ mknod $dev/mmcblk0p1 b 11 1
+ mknod $dev/mmcblk0p2 b 11 2
+}
+
+t10_mmcdev () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h02_setup_mmc_tree $block $dev
+ out=$("${ROOTDEV}" --dev $dev --block $block --major 11 --minor 2 \
+ 2>/dev/null)
+ expect "$? -eq 0" || return 1
+ expect "'$dev/mmcblk0p2' = '$out'" || return 1
+}
+run_test t10_mmcdev
+
+t11_mmcdev_strip () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h02_setup_mmc_tree $block $dev
+ out=$("${ROOTDEV}" -d --dev $dev --block $block --major 11 --minor 2 \
+ 2>/dev/null)
+ expect "$? -eq 0" || return 1
+ expect "'$dev/mmcblk0' = '$out'" || return 1
+}
+run_test t11_mmcdev_strip
+
+t12_sda_strip () {
+ local block=$WORKDIR/sys/block
+ local dev=$WORKDIR/dev
+ h00_setup_sda_tree $block $dev
+ out=$("${ROOTDEV}" -d --dev $dev --block $block --major 10 --minor 2 \
+ 2>/dev/null)
+ expect "$? -eq 0" || return 1
+ expect "'$dev/sda' = '$out'" || return 1
+}
+run_test t12_sda_strip
+
+# TODO(wad) add node creation tests
+
+TEST_COUNT=$((PASS_COUNT + FAIL_COUNT))
+
+echo "----"
+echo "Test passed: $PASS_COUNT / $TEST_COUNT"
+echo "Test failed: $FAIL_COUNT / $TEST_COUNT"
+
+if [ $FAIL_COUNT -ne 0 ]; then
+ exit 1
+fi