From e9f9bb4afabaf39a6f34f9ab3e895139bb74bf25 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Thu, 1 Jun 2017 16:08:51 -0700 Subject: [PATCH 01/53] Initial commit of the plasma store. Contributors: Philipp Moritz, Robert Nishihara, Richard Shin, Stephanie Wang, Alexey Tumanov, Ion Stoica @ RISElab, UC Berkeley (2017) [from https://github.com/ray-project/ray/commit/b94b4a35e04d8d2c0af4420518a4e9a94c1c9b9f] --- cpp/src/plasma/CMakeLists.txt | 106 + cpp/src/plasma/eviction_policy.cc | 95 + cpp/src/plasma/eviction_policy.h | 128 + cpp/src/plasma/fling.cc | 76 + cpp/src/plasma/fling.h | 43 + cpp/src/plasma/logging.h | 147 + cpp/src/plasma/malloc.cc | 168 + cpp/src/plasma/malloc.h | 9 + cpp/src/plasma/plasma.cc | 53 + cpp/src/plasma/plasma.h | 187 + cpp/src/plasma/plasma_client.cc | 624 ++ cpp/src/plasma/plasma_client.h | 335 ++ cpp/src/plasma/plasma_common.cc | 67 + cpp/src/plasma/plasma_common.h | 46 + cpp/src/plasma/plasma_events.cc | 74 + cpp/src/plasma/plasma_events.h | 85 + cpp/src/plasma/plasma_extension.cc | 463 ++ cpp/src/plasma/plasma_extension.h | 24 + cpp/src/plasma/plasma_io.cc | 220 + cpp/src/plasma/plasma_io.h | 38 + cpp/src/plasma/plasma_protocol.cc | 577 ++ cpp/src/plasma/plasma_protocol.h | 194 + cpp/src/plasma/plasma_store.cc | 689 +++ cpp/src/plasma/plasma_store.h | 154 + cpp/src/plasma/status.cc | 90 + cpp/src/plasma/status.h | 226 + cpp/src/plasma/test/client_tests.cc | 331 ++ cpp/src/plasma/test/run_tests.sh | 44 + cpp/src/plasma/test/run_valgrind.sh | 10 + cpp/src/plasma/test/serialization_tests.cc | 439 ++ cpp/src/plasma/thirdparty/ae/ae.c | 465 ++ cpp/src/plasma/thirdparty/ae/ae.h | 123 + cpp/src/plasma/thirdparty/ae/ae_epoll.c | 135 + cpp/src/plasma/thirdparty/ae/ae_evport.c | 320 + cpp/src/plasma/thirdparty/ae/ae_kqueue.c | 138 + cpp/src/plasma/thirdparty/ae/ae_select.c | 106 + cpp/src/plasma/thirdparty/ae/config.h | 54 + cpp/src/plasma/thirdparty/ae/zmalloc.h | 16 + cpp/src/plasma/thirdparty/dlmalloc.c | 6281 ++++++++++++++++++++ cpp/src/plasma/thirdparty/xxhash.cc | 889 +++ cpp/src/plasma/thirdparty/xxhash.h | 293 + 41 files changed, 14562 insertions(+) create mode 100644 cpp/src/plasma/CMakeLists.txt create mode 100644 cpp/src/plasma/eviction_policy.cc create mode 100644 cpp/src/plasma/eviction_policy.h create mode 100644 cpp/src/plasma/fling.cc create mode 100644 cpp/src/plasma/fling.h create mode 100644 cpp/src/plasma/logging.h create mode 100644 cpp/src/plasma/malloc.cc create mode 100644 cpp/src/plasma/malloc.h create mode 100644 cpp/src/plasma/plasma.cc create mode 100644 cpp/src/plasma/plasma.h create mode 100644 cpp/src/plasma/plasma_client.cc create mode 100644 cpp/src/plasma/plasma_client.h create mode 100644 cpp/src/plasma/plasma_common.cc create mode 100644 cpp/src/plasma/plasma_common.h create mode 100644 cpp/src/plasma/plasma_events.cc create mode 100644 cpp/src/plasma/plasma_events.h create mode 100644 cpp/src/plasma/plasma_extension.cc create mode 100644 cpp/src/plasma/plasma_extension.h create mode 100644 cpp/src/plasma/plasma_io.cc create mode 100644 cpp/src/plasma/plasma_io.h create mode 100644 cpp/src/plasma/plasma_protocol.cc create mode 100644 cpp/src/plasma/plasma_protocol.h create mode 100644 cpp/src/plasma/plasma_store.cc create mode 100644 cpp/src/plasma/plasma_store.h create mode 100644 cpp/src/plasma/status.cc create mode 100644 cpp/src/plasma/status.h create mode 100644 cpp/src/plasma/test/client_tests.cc create mode 100644 cpp/src/plasma/test/run_tests.sh create mode 100644 cpp/src/plasma/test/run_valgrind.sh create mode 100644 cpp/src/plasma/test/serialization_tests.cc create mode 100644 cpp/src/plasma/thirdparty/ae/ae.c create mode 100644 cpp/src/plasma/thirdparty/ae/ae.h create mode 100644 cpp/src/plasma/thirdparty/ae/ae_epoll.c create mode 100644 cpp/src/plasma/thirdparty/ae/ae_evport.c create mode 100644 cpp/src/plasma/thirdparty/ae/ae_kqueue.c create mode 100644 cpp/src/plasma/thirdparty/ae/ae_select.c create mode 100644 cpp/src/plasma/thirdparty/ae/config.h create mode 100644 cpp/src/plasma/thirdparty/ae/zmalloc.h create mode 100644 cpp/src/plasma/thirdparty/dlmalloc.c create mode 100644 cpp/src/plasma/thirdparty/xxhash.cc create mode 100644 cpp/src/plasma/thirdparty/xxhash.h diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt new file mode 100644 index 00000000000..a138c081e22 --- /dev/null +++ b/cpp/src/plasma/CMakeLists.txt @@ -0,0 +1,106 @@ +cmake_minimum_required(VERSION 2.8) + +project(plasma) + +# Recursively include common +include(${CMAKE_CURRENT_LIST_DIR}/../common/cmake/Common.cmake) + +if(APPLE) + SET(CMAKE_SHARED_LIBRARY_SUFFIX ".so") +endif(APPLE) + +include_directories("${PYTHON_INCLUDE_DIRS}" thirdparty) + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --std=c99 -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200809L -march=native -mtune=native -O3") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++11 -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200809L -march=native -mtune=native -O3") + +# Compile flatbuffers + +set(PLASMA_FBS_SRC "${CMAKE_CURRENT_LIST_DIR}/format/plasma.fbs") +set(OUTPUT_DIR ${CMAKE_CURRENT_LIST_DIR}/format/) + +set(PLASMA_FBS_OUTPUT_FILES + "${OUTPUT_DIR}/plasma_generated.h") + +add_custom_command( + OUTPUT ${PLASMA_FBS_OUTPUT_FILES} + COMMAND ${FLATBUFFERS_COMPILER} -c -o ${OUTPUT_DIR} ${PLASMA_FBS_SRC} + DEPENDS ${PLASMA_FBS_SRC} + COMMENT "Running flatc compiler on ${PLASMA_FBS_SRC}" + VERBATIM) + +add_custom_target(gen_plasma_fbs DEPENDS ${PLASMA_FBS_OUTPUT_FILES}) + +add_dependencies(gen_plasma_fbs flatbuffers_ep) + +if(UNIX AND NOT APPLE) + link_libraries(rt) +endif() + +include_directories("${CMAKE_CURRENT_LIST_DIR}/") +include_directories("${CMAKE_CURRENT_LIST_DIR}/../") + +add_library(plasma SHARED + plasma.cc + plasma_extension.cc + plasma_protocol.cc + plasma_client.cc + thirdparty/xxhash.c + fling.c) + +add_dependencies(plasma gen_plasma_fbs) + +if(APPLE) + target_link_libraries(plasma plasma_lib "-undefined dynamic_lookup" -Wl,-force_load,${FLATBUFFERS_STATIC_LIB} ${PYTHON_LIBRARIES} ${FLATBUFFERS_STATIC_LIB} -lpthread) +else(APPLE) + target_link_libraries(plasma plasma_lib -Wl,--whole-archive ${FLATBUFFERS_STATIC_LIB} -Wl,--no-whole-archive ${PYTHON_LIBRARIES} ${FLATBUFFERS_STATIC_LIB} -lpthread) +endif(APPLE) + +include_directories("${FLATBUFFERS_INCLUDE_DIR}") + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") + +set_source_files_properties(thirdparty/dlmalloc.c PROPERTIES COMPILE_FLAGS -Wno-all) + +add_library(plasma_lib STATIC + plasma_client.cc + plasma.cc + plasma_common.cc + plasma_io.cc + plasma_protocol.cc + status.cc + fling.c + thirdparty/xxhash.c) + +target_link_libraries(plasma_lib ${FLATBUFFERS_STATIC_LIB} -lpthread) +add_dependencies(plasma_lib gen_plasma_fbs) + +add_executable(plasma_store + plasma_store.cc + thirdparty/ae/ae.c + plasma.cc + plasma_events.cc + plasma_protocol.cc + eviction_policy.cc + fling.c + malloc.cc) + +add_dependencies(plasma_store hiredis gen_plasma_fbs) + +target_link_libraries(plasma_store plasma_lib ${FLATBUFFERS_STATIC_LIB}) + +add_dependencies(plasma protocol_fbs) + +add_executable(plasma_manager + plasma_manager.cc) + +target_link_libraries(plasma_manager common plasma_lib ${FLATBUFFERS_STATIC_LIB}) + +add_library(plasma_client SHARED plasma_client.cc) +target_link_libraries(plasma_client ${FLATBUFFERS_STATIC_LIB}) + +target_link_libraries(plasma_client plasma_lib ${FLATBUFFERS_STATIC_LIB}) + +define_test(client_tests plasma_lib) +define_test(manager_tests plasma_lib plasma_manager.cc) +define_test(serialization_tests plasma_lib) diff --git a/cpp/src/plasma/eviction_policy.cc b/cpp/src/plasma/eviction_policy.cc new file mode 100644 index 00000000000..135c63ad0d4 --- /dev/null +++ b/cpp/src/plasma/eviction_policy.cc @@ -0,0 +1,95 @@ +#include "eviction_policy.h" + +void LRUCache::add(const ObjectID &key, int64_t size) { + auto it = item_map_.find(key); + ARROW_CHECK(it == item_map_.end()); + /* Note that it is important to use a list so the iterators stay valid. */ + item_list_.emplace_front(key, size); + item_map_.emplace(key, item_list_.begin()); +} + +void LRUCache::remove(const ObjectID &key) { + auto it = item_map_.find(key); + ARROW_CHECK(it != item_map_.end()); + item_list_.erase(it->second); + item_map_.erase(it); +} + +int64_t LRUCache::choose_objects_to_evict( + int64_t num_bytes_required, + std::vector &objects_to_evict) { + int64_t bytes_evicted = 0; + auto it = item_list_.end(); + while (bytes_evicted < num_bytes_required && it != item_list_.begin()) { + it--; + objects_to_evict.push_back(it->first); + bytes_evicted += it->second; + } + return bytes_evicted; +} + +EvictionPolicy::EvictionPolicy(PlasmaStoreInfo *store_info) + : memory_used_(0), store_info_(store_info) {} + +int64_t EvictionPolicy::choose_objects_to_evict( + int64_t num_bytes_required, + std::vector &objects_to_evict) { + int64_t bytes_evicted = + cache_.choose_objects_to_evict(num_bytes_required, objects_to_evict); + /* Update the LRU cache. */ + for (auto &object_id : objects_to_evict) { + cache_.remove(object_id); + } + /* Update the number of bytes used. */ + memory_used_ -= bytes_evicted; + return bytes_evicted; +} + +void EvictionPolicy::object_created(ObjectID object_id) { + auto entry = store_info_->objects[object_id].get(); + cache_.add(object_id, entry->info.data_size + entry->info.metadata_size); +} + +bool EvictionPolicy::require_space(int64_t size, + std::vector &objects_to_evict) { + /* Check if there is enough space to create the object. */ + int64_t required_space = memory_used_ + size - store_info_->memory_capacity; + int64_t num_bytes_evicted; + if (required_space > 0) { + /* Try to free up at least as much space as we need right now but ideally + * up to 20% of the total capacity. */ + int64_t space_to_free = std::max(size, store_info_->memory_capacity / 5); + ARROW_LOG(DEBUG) + << "not enough space to create this object, so evicting objects"; + /* Choose some objects to evict, and update the return pointers. */ + num_bytes_evicted = + choose_objects_to_evict(space_to_free, objects_to_evict); + ARROW_LOG(INFO) + << "There is not enough space to create this object, so evicting " + << objects_to_evict.size() << " objects to free up " + << num_bytes_evicted << " bytes."; + } else { + num_bytes_evicted = 0; + } + if (num_bytes_evicted >= required_space) { + /* We only increment the space used if there is enough space to create the + * object. */ + memory_used_ += size; + } + return num_bytes_evicted >= required_space; +} + +void EvictionPolicy::begin_object_access( + ObjectID object_id, + std::vector &objects_to_evict) { + /* If the object is in the LRU cache, remove it. */ + cache_.remove(object_id); +} + +void EvictionPolicy::end_object_access( + ObjectID object_id, + std::vector &objects_to_evict) { + auto entry = store_info_->objects[object_id].get(); + /* Add the object to the LRU cache.*/ + cache_.add(object_id, entry->info.data_size + entry->info.metadata_size); +} diff --git a/cpp/src/plasma/eviction_policy.h b/cpp/src/plasma/eviction_policy.h new file mode 100644 index 00000000000..fd3861db467 --- /dev/null +++ b/cpp/src/plasma/eviction_policy.h @@ -0,0 +1,128 @@ +#ifndef EVICTION_POLICY_H +#define EVICTION_POLICY_H + +#include +#include + +#include "plasma_common.h" +#include "plasma.h" + +/* ==== The eviction policy ==== + * + * This file contains declaration for all functions and data structures that + * need to be provided if you want to implement a new eviction algorithm for the + * Plasma store. + */ + +class LRUCache { + private: + /** A doubly-linked list containing the items in the cache and + * their sizes in LRU order. */ + typedef std::list> ItemList; + ItemList item_list_; + /** A hash table mapping the object ID of an object in the cache to its + * location in the doubly linked list item_list_. */ + std::unordered_map item_map_; + + public: + LRUCache(){}; + + void add(const ObjectID &key, int64_t size); + + void remove(const ObjectID &key); + + int64_t choose_objects_to_evict(int64_t num_bytes_required, + std::vector &objects_to_evict); +}; + +/** The eviction policy. */ +class EvictionPolicy { + public: + /** + * Construct an eviction policy. + * + * @param store_info Information about the Plasma store that is exposed + * to the eviction policy. + */ + EvictionPolicy(PlasmaStoreInfo *store_info); + + /** + * This method will be called whenever an object is first created in order to + * add it to the LRU cache. This is done so that the first time, the Plasma + * store calls begin_object_access, we can remove the object from the LRU + * cache. + * + * @param object_id The object ID of the object that was created. + * @return Void. + */ + void object_created(ObjectID object_id); + + /** + * This method will be called when the Plasma store needs more space, perhaps + * to create a new object. If the required amount of space cannot be freed up, + * then a fatal error will be thrown. When this method is called, the eviction + * policy will assume that the objects chosen to be evicted will in fact be + * evicted from the Plasma store by the caller. + * + * @param size The size in bytes of the new object, including both data and + * metadata. + * @param objects_to_evict The object IDs that were chosen for eviction will + * be stored into this vector. + * @return True if enough space can be freed and false otherwise. + */ + bool require_space(int64_t size, std::vector &objects_to_evict); + + /** + * This method will be called whenever an unused object in the Plasma store + * starts to be used. When this method is called, the eviction policy will + * assume that the objects chosen to be evicted will in fact be evicted from + * the Plasma store by the caller. + * + * @param object_id The ID of the object that is now being used. + * @param objects_to_evict The object IDs that were chosen for eviction will + * be stored into this vector. + * @return Void. + */ + void begin_object_access(ObjectID object_id, + std::vector &objects_to_evict); + + /** + * This method will be called whenever an object in the Plasma store that was + * being used is no longer being used. When this method is called, the + * eviction policy will assume that the objects chosen to be evicted will in + * fact be evicted from the Plasma store by the caller. + * + * @param object_id The ID of the object that is no longer being used. + * @param objects_to_evict The object IDs that were chosen for eviction will + * be stored into this vector. + * @return Void. + */ + void end_object_access(ObjectID object_id, + std::vector &objects_to_evict); + + /** + * Choose some objects to evict from the Plasma store. When this method is + * called, the eviction policy will assume that the objects chosen to be + * evicted will in fact be evicted from the Plasma store by the caller. + * + * @note This method is not part of the API. It is exposed in the header file + * only for testing. + * + * @param num_bytes_required The number of bytes of space to try to free up. + * @param objects_to_evict The object IDs that were chosen for eviction will + * be stored into this vector. + * @return The total number of bytes of space chosen to be evicted. + */ + int64_t choose_objects_to_evict(int64_t num_bytes_required, + std::vector &objects_to_evict); + + private: + /** Pointer to the plasma store info. */ + PlasmaStoreInfo *store_info_; + /** The amount of memory (in bytes) currently being used. */ + int64_t memory_used_; + /** Datastructure for the LRU cache. */ + LRUCache cache_; +}; + +#endif /* EVICTION_POLICY_H */ diff --git a/cpp/src/plasma/fling.cc b/cpp/src/plasma/fling.cc new file mode 100644 index 00000000000..379b896b543 --- /dev/null +++ b/cpp/src/plasma/fling.cc @@ -0,0 +1,76 @@ +#include "fling.h" + +#include + +void init_msg(struct msghdr *msg, + struct iovec *iov, + char *buf, + size_t buf_len) { + iov->iov_base = buf; + iov->iov_len = 1; + + msg->msg_iov = iov; + msg->msg_iovlen = 1; + msg->msg_control = buf; + msg->msg_controllen = buf_len; + msg->msg_name = NULL; + msg->msg_namelen = 0; +} + +int send_fd(int conn, int fd) { + struct msghdr msg; + struct iovec iov; + char buf[CMSG_SPACE(sizeof(int))]; + memset(&buf, 0, CMSG_SPACE(sizeof(int))); + + init_msg(&msg, &iov, buf, sizeof(buf)); + + struct cmsghdr *header = CMSG_FIRSTHDR(&msg); + header->cmsg_level = SOL_SOCKET; + header->cmsg_type = SCM_RIGHTS; + header->cmsg_len = CMSG_LEN(sizeof(int)); + *(int *) CMSG_DATA(header) = fd; + + /* Send file descriptor. */ + return sendmsg(conn, &msg, 0); +} + +int recv_fd(int conn) { + struct msghdr msg; + struct iovec iov; + char buf[CMSG_SPACE(sizeof(int))]; + init_msg(&msg, &iov, buf, sizeof(buf)); + + if (recvmsg(conn, &msg, 0) == -1) + return -1; + + int found_fd = -1; + int oh_noes = 0; + for (struct cmsghdr *header = CMSG_FIRSTHDR(&msg); header != NULL; + header = CMSG_NXTHDR(&msg, header)) + if (header->cmsg_level == SOL_SOCKET && header->cmsg_type == SCM_RIGHTS) { + int count = + (header->cmsg_len - (CMSG_DATA(header) - (unsigned char *) header)) / + sizeof(int); + for (int i = 0; i < count; ++i) { + int fd = ((int *) CMSG_DATA(header))[i]; + if (found_fd == -1) { + found_fd = fd; + } else { + close(fd); + oh_noes = 1; + } + } + } + + /* The sender sent us more than one file descriptor. We've closed + * them all to prevent fd leaks but notify the caller that we got + * a bad message. */ + if (oh_noes) { + close(found_fd); + errno = EBADMSG; + return -1; + } + + return found_fd; +} diff --git a/cpp/src/plasma/fling.h b/cpp/src/plasma/fling.h new file mode 100644 index 00000000000..efc41d801e8 --- /dev/null +++ b/cpp/src/plasma/fling.h @@ -0,0 +1,43 @@ +/* FLING: Exchanging file descriptors over sockets + * + * This is a little library for sending file descriptors over a socket + * between processes. The reason for doing that (as opposed to using + * filenames to share the files) is so (a) no files remain in the + * filesystem after all the processes terminate, (b) to make sure that + * there are no name collisions and (c) to be able to control who has + * access to the data. + * + * Most of the code is from https://github.com/sharvil/flingfd */ + +#include +#include +#include +#include +#include + +/* This is neccessary for Mac OS X, see http://www.apuebook.com/faqs2e.html + * (10). */ +#if !defined(CMSG_SPACE) && !defined(CMSG_LEN) +#define CMSG_SPACE(len) \ + (__DARWIN_ALIGN32(sizeof(struct cmsghdr)) + __DARWIN_ALIGN32(len)) +#define CMSG_LEN(len) (__DARWIN_ALIGN32(sizeof(struct cmsghdr)) + (len)) +#endif + +void init_msg(struct msghdr *msg, struct iovec *iov, char *buf, size_t buf_len); + +/** + * Send a file descriptor over a unix domain socket. + * + * @param conn Unix domain socket to send the file descriptor over. + * @param fd File descriptor to send over. + * @return Status code which is < 0 on failure. + */ +int send_fd(int conn, int fd); + +/** + * Receive a file descriptor over a unix domain socket. + * + * @param conn Unix domain socket to receive the file descriptor from. + * @return File descriptor or a value < 0 on failure. + */ +int recv_fd(int conn); diff --git a/cpp/src/plasma/logging.h b/cpp/src/plasma/logging.h new file mode 100644 index 00000000000..917d18140dd --- /dev/null +++ b/cpp/src/plasma/logging.h @@ -0,0 +1,147 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#ifndef ARROW_UTIL_LOGGING_H +#define ARROW_UTIL_LOGGING_H + +#include +#include + +namespace arrow { + +// Stubbed versions of macros defined in glog/logging.h, intended for +// environments where glog headers aren't available. +// +// Add more as needed. + +// Log levels. LOG ignores them, so their values are abitrary. + +#define ARROW_DEBUG (-1) +#define ARROW_INFO 0 +#define ARROW_WARNING 1 +#define ARROW_ERROR 2 +#define ARROW_FATAL 3 + +#define ARROW_LOG_INTERNAL(level) ::arrow::internal::CerrLog(level) +#define ARROW_LOG(level) ARROW_LOG_INTERNAL(ARROW_##level) + +#define ARROW_CHECK(condition) \ + (condition) ? 0 : ::arrow::internal::FatalLog(ARROW_FATAL) \ + << __FILE__ << __LINE__ \ + << " Check failed: " #condition " " + +#ifdef NDEBUG +#define ARROW_DFATAL ARROW_WARNING + +#define DCHECK(condition) \ + while (false) \ + ::arrow::internal::NullLog() +#define DCHECK_EQ(val1, val2) \ + while (false) \ + ::arrow::internal::NullLog() +#define DCHECK_NE(val1, val2) \ + while (false) \ + ::arrow::internal::NullLog() +#define DCHECK_LE(val1, val2) \ + while (false) \ + ::arrow::internal::NullLog() +#define DCHECK_LT(val1, val2) \ + while (false) \ + ::arrow::internal::NullLog() +#define DCHECK_GE(val1, val2) \ + while (false) \ + ::arrow::internal::NullLog() +#define DCHECK_GT(val1, val2) \ + while (false) \ + ::arrow::internal::NullLog() + +#else +#define ARROW_DFATAL ARROW_FATAL + +#define DCHECK(condition) ARROW_CHECK(condition) +#define DCHECK_EQ(val1, val2) ARROW_CHECK((val1) == (val2)) +#define DCHECK_NE(val1, val2) ARROW_CHECK((val1) != (val2)) +#define DCHECK_LE(val1, val2) ARROW_CHECK((val1) <= (val2)) +#define DCHECK_LT(val1, val2) ARROW_CHECK((val1) < (val2)) +#define DCHECK_GE(val1, val2) ARROW_CHECK((val1) >= (val2)) +#define DCHECK_GT(val1, val2) ARROW_CHECK((val1) > (val2)) + +#endif // NDEBUG + +namespace internal { + +class NullLog { + public: + template + NullLog &operator<<(const T &t) { + return *this; + } +}; + +class CerrLog { + public: + CerrLog(int severity) // NOLINT(runtime/explicit) + : severity_(severity), + has_logged_(false) {} + + virtual ~CerrLog() { + if (has_logged_) { + std::cerr << std::endl; + } + if (severity_ == ARROW_FATAL) { + std::exit(1); + } + } + + template + CerrLog &operator<<(const T &t) { + // TODO(pcm): Print this if in debug mode, but not if in valgrind + // mode + if (severity_ == ARROW_DEBUG) { + return *this; + } + + has_logged_ = true; + std::cerr << t; + return *this; + } + + protected: + const int severity_; + bool has_logged_; +}; + +// Clang-tidy isn't smart enough to determine that DCHECK using CerrLog doesn't +// return so we create a new class to give it a hint. +class FatalLog : public CerrLog { + public: + explicit FatalLog(int /* severity */) // NOLINT + : CerrLog(ARROW_FATAL){} // NOLINT + + [[noreturn]] ~FatalLog() { + if (has_logged_) { + std::cerr << std::endl; + } + std::exit(1); + } +}; + +} // namespace internal + +} // namespace arrow + +#endif // ARROW_UTIL_LOGGING_H diff --git a/cpp/src/plasma/malloc.cc b/cpp/src/plasma/malloc.cc new file mode 100644 index 00000000000..e8399649a98 --- /dev/null +++ b/cpp/src/plasma/malloc.cc @@ -0,0 +1,168 @@ +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "common.h" + +extern "C" { +void *fake_mmap(size_t); +int fake_munmap(void *, size_t); + +#define MMAP(s) fake_mmap(s) +#define MUNMAP(a, s) fake_munmap(a, s) +#define DIRECT_MMAP(s) fake_mmap(s) +#define DIRECT_MUNMAP(a, s) fake_munmap(a, s) +#define USE_DL_PREFIX +#define HAVE_MORECORE 0 +#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T +#define DEFAULT_GRANULARITY ((size_t) 128U * 1024U) + +#include "thirdparty/dlmalloc.c" + +#undef MMAP +#undef MUNMAP +#undef DIRECT_MMAP +#undef DIRECT_MUNMAP +#undef USE_DL_PREFIX +#undef HAVE_MORECORE +#undef DEFAULT_GRANULARITY +} + +struct mmap_record { + int fd; + int64_t size; +}; + +namespace { + +/** Hashtable that contains one entry per segment that we got from the OS + * via mmap. Associates the address of that segment with its file descriptor + * and size. */ +std::unordered_map mmap_records; + +} /* namespace */ + +constexpr int GRANULARITY_MULTIPLIER = 2; + +static void *pointer_advance(void *p, ptrdiff_t n) { + return (unsigned char *) p + n; +} + +static void *pointer_retreat(void *p, ptrdiff_t n) { + return (unsigned char *) p - n; +} + +static ptrdiff_t pointer_distance(void const *pfrom, void const *pto) { + return (unsigned char const *) pto - (unsigned char const *) pfrom; +} + +/* Create a buffer. This is creating a temporary file and then + * immediately unlinking it so we do not leave traces in the system. */ +int create_buffer(int64_t size) { + int fd; +#ifdef _WIN32 + if (!CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, + (DWORD)((uint64_t) size >> (CHAR_BIT * sizeof(DWORD))), + (DWORD)(uint64_t) size, NULL)) { + fd = -1; + } +#else +#ifdef __linux__ + constexpr char file_template[] = "/dev/shm/plasmaXXXXXX"; +#else + constexpr char file_template[] = "/tmp/plasmaXXXXXX"; +#endif + char file_name[32]; + strncpy(file_name, file_template, 32); + fd = mkstemp(file_name); + if (fd < 0) + return -1; + FILE *file = fdopen(fd, "a+"); + if (!file) { + close(fd); + return -1; + } + if (unlink(file_name) != 0) { + LOG_ERROR("unlink error"); + return -1; + } + if (ftruncate(fd, (off_t) size) != 0) { + LOG_ERROR("ftruncate error"); + return -1; + } +#endif + return fd; +} + +void *fake_mmap(size_t size) { + /* Add sizeof(size_t) so that the returned pointer is deliberately not + * page-aligned. This ensures that the segments of memory returned by + * fake_mmap are never contiguous. */ + size += sizeof(size_t); + + int fd = create_buffer(size); + CHECKM(fd >= 0, "Failed to create buffer during mmap"); + void *pointer = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (pointer == MAP_FAILED) { + return pointer; + } + + /* Increase dlmalloc's allocation granularity directly. */ + mparams.granularity *= GRANULARITY_MULTIPLIER; + + mmap_record &record = mmap_records[pointer]; + record.fd = fd; + record.size = size; + + /* We lie to dlmalloc about where mapped memory actually lives. */ + pointer = pointer_advance(pointer, sizeof(size_t)); + LOG_DEBUG("%p = fake_mmap(%lu)", pointer, size); + return pointer; +} + +int fake_munmap(void *addr, size_t size) { + LOG_DEBUG("fake_munmap(%p, %lu)", addr, size); + addr = pointer_retreat(addr, sizeof(size_t)); + size += sizeof(size_t); + + auto entry = mmap_records.find(addr); + + if (entry == mmap_records.end() || entry->second.size != size) { + /* Reject requests to munmap that don't directly match previous + * calls to mmap, to prevent dlmalloc from trimming. */ + return -1; + } + + int r = munmap(addr, size); + if (r == 0) { + close(entry->second.fd); + } + + mmap_records.erase(entry); + return r; +} + +void get_malloc_mapinfo(void *addr, + int *fd, + int64_t *map_size, + ptrdiff_t *offset) { + /* TODO(rshin): Implement a more efficient search through mmap_records. */ + for (const auto &entry : mmap_records) { + if (addr >= entry.first && + addr < pointer_advance(entry.first, entry.second.size)) { + *fd = entry.second.fd; + *map_size = entry.second.size; + *offset = pointer_distance(entry.first, addr); + return; + } + } + *fd = -1; + *map_size = 0; + *offset = 0; +} diff --git a/cpp/src/plasma/malloc.h b/cpp/src/plasma/malloc.h new file mode 100644 index 00000000000..9fc1f48bb9e --- /dev/null +++ b/cpp/src/plasma/malloc.h @@ -0,0 +1,9 @@ +#ifndef MALLOC_H +#define MALLOC_H + +void get_malloc_mapinfo(void *addr, + int *fd, + int64_t *map_length, + ptrdiff_t *offset); + +#endif /* MALLOC_H */ diff --git a/cpp/src/plasma/plasma.cc b/cpp/src/plasma/plasma.cc new file mode 100644 index 00000000000..6273d3bbc8c --- /dev/null +++ b/cpp/src/plasma/plasma.cc @@ -0,0 +1,53 @@ +#include "plasma_common.h" +#include "plasma.h" + +#include "io.h" +#include +#include +#include + +#include "plasma_protocol.h" + +int warn_if_sigpipe(int status, int client_sock) { + if (status >= 0) { + return 0; + } + if (errno == EPIPE || errno == EBADF || errno == ECONNRESET) { + ARROW_LOG(WARNING) + << "Received SIGPIPE, BAD FILE DESCRIPTOR, or ECONNRESET when " + "sending a message to client on fd " + << client_sock << ". The client on the other end may " + "have hung up."; + return errno; + } + ARROW_LOG(FATAL) << "Failed to write message to client on fd " << client_sock + << "."; +} + +/** + * This will create a new ObjectInfo buffer. The first sizeof(int64_t) bytes + * of this buffer are the length of the remaining message and the + * remaining message is a serialized version of the object info. + * + * @param object_info The object info to be serialized + * @return The object info buffer. It is the caller's responsibility to free + * this buffer with "free" after it has been used. + */ +uint8_t *create_object_info_buffer(ObjectInfoT *object_info) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreateObjectInfo(fbb, object_info); + fbb.Finish(message); + uint8_t *notification = (uint8_t *) malloc(sizeof(int64_t) + fbb.GetSize()); + *((int64_t *) notification) = fbb.GetSize(); + memcpy(notification + sizeof(int64_t), fbb.GetBufferPointer(), fbb.GetSize()); + return notification; +} + +ObjectTableEntry *get_object_table_entry(PlasmaStoreInfo *store_info, + ObjectID object_id) { + auto it = store_info->objects.find(object_id); + if (it == store_info->objects.end()) { + return NULL; + } + return it->second.get(); +} diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h new file mode 100644 index 00000000000..4cd3f46dd3b --- /dev/null +++ b/cpp/src/plasma/plasma.h @@ -0,0 +1,187 @@ +#ifndef PLASMA_H +#define PLASMA_H + +#include +#include +#include +#include +#include +#include +#include /* pid_t */ + +extern "C" { +#include "sha256.h" +} + +#include +#include + +#include "format/common_generated.h" +#include "logging.h" +#include "status.h" + +#include + +#define HANDLE_SIGPIPE(s, fd_) \ + do { \ + Status _s = (s); \ + if (!_s.ok()) { \ + if (errno == EPIPE || errno == EBADF || errno == ECONNRESET) { \ + ARROW_LOG(WARNING) \ + << "Received SIGPIPE, BAD FILE DESCRIPTOR, or ECONNRESET when " \ + "sending a message to client on fd " \ + << fd_ << ". " \ + "The client on the other end may have hung up."; \ + } else { \ + return _s; \ + } \ + } \ + } while (0); + +/** Allocation granularity used in plasma for object allocation. */ +#define BLOCK_SIZE 64 + +// Size of object hash digests. +constexpr int64_t kDigestSize = SHA256_BLOCK_SIZE; + +struct Client; + +/** + * Object request data structure. Used in the plasma_wait_for_objects() + * argument. + */ +typedef struct { + /** The ID of the requested object. If ID_NIL request any object. */ + ObjectID object_id; + /** Request associated to the object. It can take one of the following values: + * - PLASMA_QUERY_LOCAL: return if or when the object is available in the + * local Plasma Store. + * - PLASMA_QUERY_ANYWHERE: return if or when the object is available in + * the system (i.e., either in the local or a remote Plasma Store). */ + int type; + /** Object status. Same as the status returned by plasma_status() function + * call. This is filled in by plasma_wait_for_objects1(): + * - ObjectStatus_Local: object is ready at the local Plasma Store. + * - ObjectStatus_Remote: object is ready at a remote Plasma Store. + * - ObjectStatus_Nonexistent: object does not exist in the system. + * - PLASMA_CLIENT_IN_TRANSFER, if the object is currently being scheduled + * for being transferred or it is transferring. */ + int status; +} ObjectRequest; + +/** Mapping from object IDs to type and status of the request. */ +typedef std::unordered_map + ObjectRequestMap; + +/* Handle to access memory mapped file and map it into client address space. */ +typedef struct { + /** The file descriptor of the memory mapped file in the store. It is used as + * a unique identifier of the file in the client to look up the corresponding + * file descriptor on the client's side. */ + int store_fd; + /** The size in bytes of the memory mapped file. */ + int64_t mmap_size; +} object_handle; + +typedef struct { + /** Handle for memory mapped file the object is stored in. */ + object_handle handle; + /** The offset in bytes in the memory mapped file of the data. */ + ptrdiff_t data_offset; + /** The offset in bytes in the memory mapped file of the metadata. */ + ptrdiff_t metadata_offset; + /** The size in bytes of the data. */ + int64_t data_size; + /** The size in bytes of the metadata. */ + int64_t metadata_size; +} PlasmaObject; + +typedef enum { + /** Object was created but not sealed in the local Plasma Store. */ + PLASMA_CREATED = 1, + /** Object is sealed and stored in the local Plasma Store. */ + PLASMA_SEALED +} object_state; + +typedef enum { + /** The object was not found. */ + OBJECT_NOT_FOUND = 0, + /** The object was found. */ + OBJECT_FOUND = 1 +} object_status; + +typedef enum { + /** Query for object in the local plasma store. */ + PLASMA_QUERY_LOCAL = 1, + /** Query for object in the local plasma store or in a remote plasma store. */ + PLASMA_QUERY_ANYWHERE +} object_request_type; + +/** This type is used by the Plasma store. It is here because it is exposed to + * the eviction policy. */ +struct ObjectTableEntry { + /** Object id of this object. */ + ObjectID object_id; + /** Object info like size, creation time and owner. */ + ObjectInfoT info; + /** Memory mapped file containing the object. */ + int fd; + /** Size of the underlying map. */ + int64_t map_size; + /** Offset from the base of the mmap. */ + ptrdiff_t offset; + /** Pointer to the object data. Needed to free the object. */ + uint8_t *pointer; + /** Set of clients currently using this object. */ + std::unordered_set clients; + /** The state of the object, e.g., whether it is open or sealed. */ + object_state state; + /** The digest of the object. Used to see if two objects are the same. */ + unsigned char digest[kDigestSize]; +}; + +/** The plasma store information that is exposed to the eviction policy. */ +struct PlasmaStoreInfo { + /** Objects that are in the Plasma store. */ + std::unordered_map, + UniqueIDHasher> + objects; + /** The amount of memory (in bytes) that we allow to be allocated in the + * store. */ + int64_t memory_capacity; +}; + +/** + * Get an entry from the object table and return NULL if the object_id + * is not present. + * + * @param store_info The PlasmaStoreInfo that contains the object table. + * @param object_id The object_id of the entry we are looking for. + * @return The entry associated with the object_id or NULL if the object_id + * is not present. + */ +ObjectTableEntry *get_object_table_entry(PlasmaStoreInfo *store_info, + ObjectID object_id); + +/** + * Print a warning if the status is less than zero. This should be used to check + * the success of messages sent to plasma clients. We print a warning instead of + * failing because the plasma clients are allowed to die. This is used to handle + * situations where the store writes to a client file descriptor, and the client + * may already have disconnected. If we have processed the disconnection and + * closed the file descriptor, we should get a BAD FILE DESCRIPTOR error. If we + * have not, then we should get a SIGPIPE. If we write to a TCP socket that + * isn't connected yet, then we should get an ECONNRESET. + * + * @param status The status to check. If it is less less than zero, we will + * print a warning. + * @param client_sock The client socket. This is just used to print some extra + * information. + * @return The errno set. + */ +int warn_if_sigpipe(int status, int client_sock); + +uint8_t *create_object_info_buffer(ObjectInfoT *object_info); + +#endif /* PLASMA_H */ diff --git a/cpp/src/plasma/plasma_client.cc b/cpp/src/plasma/plasma_client.cc new file mode 100644 index 00000000000..c811b418b6f --- /dev/null +++ b/cpp/src/plasma/plasma_client.cc @@ -0,0 +1,624 @@ +// PLASMA CLIENT: Client library for using the plasma store and manager + +#ifdef _WIN32 +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "plasma_common.h" +#include "plasma.h" +#include "plasma_io.h" +#include "plasma_protocol.h" +#include "plasma_client.h" + +#include +#include + +extern "C" { +#include "sha256.h" +#include "fling.h" + +#define XXH_STATIC_LINKING_ONLY +#include "xxhash.h" + +#define XXH64_DEFAULT_SEED 0 +} + +// Number of threads used for memcopy and hash computations. +constexpr int64_t kThreadPoolSize = 8; +constexpr int64_t kBytesInMB = 1 << 20; +static std::vector threadpool_(kThreadPoolSize); + +struct ClientMmapTableEntry { + /// The result of mmap for this file descriptor. + uint8_t *pointer; + /// The length of the memory-mapped file. + size_t length; + /// The number of objects in this memory-mapped file that are currently being + /// used by the client. When this count reaches zeros, we unmap the file. + int count; +}; + +struct ObjectInUseEntry { + /// A count of the number of times this client has called PlasmaClient::Create + /// or + /// PlasmaClient::Get on this object ID minus the number of calls to + /// PlasmaClient::Release. + /// When this count reaches zero, we remove the entry from the ObjectsInUse + /// and decrement a count in the relevant ClientMmapTableEntry. + int count; + /// Cached information to read the object. + PlasmaObject object; + /// A flag representing whether the object has been sealed. + bool is_sealed; +}; + +// If the file descriptor fd has been mmapped in this client process before, +// return the pointer that was returned by mmap, otherwise mmap it and store the +// pointer in a hash table. +uint8_t *lookup_or_mmap(PlasmaClient *conn, + int fd, + int store_fd_val, + int64_t map_size) { + auto entry = conn->mmap_table.find(store_fd_val); + if (entry != conn->mmap_table.end()) { + close(fd); + return entry->second->pointer; + } else { + uint8_t *result = (uint8_t *) mmap(NULL, map_size, PROT_READ | PROT_WRITE, + MAP_SHARED, fd, 0); + if (result == MAP_FAILED) { + ARROW_LOG(FATAL) << "mmap failed"; + } + close(fd); + ClientMmapTableEntry *entry = new ClientMmapTableEntry(); + entry->pointer = result; + entry->length = map_size; + entry->count = 0; + conn->mmap_table[store_fd_val] = entry; + return result; + } +} + +// Get a pointer to a file that we know has been memory mapped in this client +// process before. +uint8_t *lookup_mmapped_file(PlasmaClient *conn, int store_fd_val) { + auto entry = conn->mmap_table.find(store_fd_val); + ARROW_CHECK(entry != conn->mmap_table.end()); + return entry->second->pointer; +} + +void increment_object_count(PlasmaClient *conn, + ObjectID object_id, + PlasmaObject *object, + bool is_sealed) { + // Increment the count of the object to track the fact that it is being used. + // The corresponding decrement should happen in PlasmaClient::Release. + auto elem = conn->objects_in_use.find(object_id); + ObjectInUseEntry *object_entry; + if (elem == conn->objects_in_use.end()) { + // Add this object ID to the hash table of object IDs in use. The + // corresponding call to free happens in PlasmaClient::Release. + object_entry = new ObjectInUseEntry(); + object_entry->object = *object; + object_entry->count = 0; + object_entry->is_sealed = is_sealed; + conn->objects_in_use[object_id] = object_entry; + // Increment the count of the number of objects in the memory-mapped file + // that are being used. The corresponding decrement should happen in + // PlasmaClient::Release. + auto entry = conn->mmap_table.find(object->handle.store_fd); + ARROW_CHECK(entry != conn->mmap_table.end()); + ARROW_CHECK(entry->second->count >= 0); + // Update the in_use_object_bytes. + conn->in_use_object_bytes += + (object_entry->object.data_size + object_entry->object.metadata_size); + entry->second->count += 1; + } else { + object_entry = elem->second; + ARROW_CHECK(object_entry->count > 0); + } + // Increment the count of the number of instances of this object that are + // being used by this client. The corresponding decrement should happen in + // PlasmaClient::Release. + object_entry->count += 1; +} + +Status PlasmaClient::Create(ObjectID object_id, + int64_t data_size, + uint8_t *metadata, + int64_t metadata_size, + uint8_t **data) { + ARROW_LOG(DEBUG) << "called plasma_create on conn " << store_conn + << " with size " << data_size << " and metadata size " + << metadata_size; + RETURN_NOT_OK( + SendCreateRequest(store_conn, object_id, data_size, metadata_size)); + std::vector buffer; + RETURN_NOT_OK( + PlasmaReceive(store_conn, MessageType_PlasmaCreateReply, buffer)); + ObjectID id; + PlasmaObject object; + RETURN_NOT_OK(ReadCreateReply(buffer.data(), &id, &object)); + // If the CreateReply included an error, then the store will not send a file + // descriptor. + int fd = recv_fd(store_conn); + ARROW_CHECK(fd >= 0) << "recv not successful"; + ARROW_CHECK(object.data_size == data_size); + ARROW_CHECK(object.metadata_size == metadata_size); + // The metadata should come right after the data. + ARROW_CHECK(object.metadata_offset == object.data_offset + data_size); + *data = lookup_or_mmap(this, fd, object.handle.store_fd, + object.handle.mmap_size) + + object.data_offset; + // If plasma_create is being called from a transfer, then we will not copy the + // metadata here. The metadata will be written along with the data streamed + // from the transfer. + if (metadata != NULL) { + // Copy the metadata to the buffer. + memcpy(*data + object.data_size, metadata, metadata_size); + } + // Increment the count of the number of instances of this object that this + // client is using. A call to PlasmaClient::Release is required to decrement + // this + // count. Cache the reference to the object. + increment_object_count(this, object_id, &object, false); + // We increment the count a second time (and the corresponding decrement will + // happen in a PlasmaClient::Release call in plasma_seal) so even if the + // buffer + // returned by PlasmaClient::Dreate goes out of scope, the object does not get + // released before the call to PlasmaClient::Seal happens. + increment_object_count(this, object_id, &object, false); + return Status::OK(); +} + +Status PlasmaClient::Get(ObjectID object_ids[], + int64_t num_objects, + int64_t timeout_ms, + ObjectBuffer object_buffers[]) { + // Fill out the info for the objects that are already in use locally. + bool all_present = true; + for (int i = 0; i < num_objects; ++i) { + auto object_entry = objects_in_use.find(object_ids[i]); + if (object_entry == objects_in_use.end()) { + // This object is not currently in use by this client, so we need to send + // a request to the store. + all_present = false; + // Make a note to ourselves that the object is not present. + object_buffers[i].data_size = -1; + } else { + // NOTE: If the object is still unsealed, we will deadlock, since we must + // have been the one who created it. + ARROW_CHECK(object_entry->second->is_sealed) + << "Plasma client called get on an unsealed object that it created"; + PlasmaObject *object = &object_entry->second->object; + object_buffers[i].data = + lookup_mmapped_file(this, object->handle.store_fd); + object_buffers[i].data = object_buffers[i].data + object->data_offset; + object_buffers[i].data_size = object->data_size; + object_buffers[i].metadata = object_buffers[i].data + object->data_size; + object_buffers[i].metadata_size = object->metadata_size; + // Increment the count of the number of instances of this object that this + // client is using. A call to PlasmaClient::Release is required to + // decrement this + // count. Cache the reference to the object. + increment_object_count(this, object_ids[i], object, true); + } + } + + if (all_present) { + return Status::OK(); + } + + // If we get here, then the objects aren't all currently in use by this + // client, so we need to send a request to the plasma store. + RETURN_NOT_OK( + SendGetRequest(store_conn, object_ids, num_objects, timeout_ms)); + std::vector buffer; + RETURN_NOT_OK(PlasmaReceive(store_conn, MessageType_PlasmaGetReply, buffer)); + std::vector received_object_ids(num_objects); + std::vector object_data(num_objects); + PlasmaObject *object; + RETURN_NOT_OK(ReadGetReply(buffer.data(), received_object_ids.data(), + object_data.data(), num_objects)); + + for (int i = 0; i < num_objects; ++i) { + DCHECK(received_object_ids[i] == object_ids[i]); + object = &object_data[i]; + if (object_buffers[i].data_size != -1) { + // If the object was already in use by the client, then the store should + // have returned it. + DCHECK(object->data_size != -1); + // We won't use this file descriptor, but the store sent us one, so we + // need to receive it and then close it right away so we don't leak file + // descriptors. + int fd = recv_fd(store_conn); + close(fd); + ARROW_CHECK(fd >= 0); + // We've already filled out the information for this object, so we can + // just continue. + continue; + } + // If we are here, the object was not currently in use, so we need to + // process the reply from the object store. + if (object->data_size != -1) { + // The object was retrieved. The user will be responsible for releasing + // this object. + int fd = recv_fd(store_conn); + ARROW_CHECK(fd >= 0); + object_buffers[i].data = lookup_or_mmap(this, fd, object->handle.store_fd, + object->handle.mmap_size); + // Finish filling out the return values. + object_buffers[i].data = object_buffers[i].data + object->data_offset; + object_buffers[i].data_size = object->data_size; + object_buffers[i].metadata = object_buffers[i].data + object->data_size; + object_buffers[i].metadata_size = object->metadata_size; + // Increment the count of the number of instances of this object that this + // client is using. A call to PlasmaClient::Release is required to + // decrement this + // count. Cache the reference to the object. + increment_object_count(this, received_object_ids[i], object, true); + } else { + // The object was not retrieved. Make sure we already put a -1 here to + // indicate that the object was not retrieved. The caller is not + // responsible for releasing this object. + DCHECK(object_buffers[i].data_size == -1); + object_buffers[i].data_size = -1; + } + } + return Status::OK(); +} + +/// This is a helper method for implementing plasma_release. We maintain a +/// buffer +/// of release calls and only perform them once the buffer becomes full (as +/// judged by the aggregate sizes of the objects). There may be multiple release +/// calls for the same object ID in the buffer. In this case, the first release +/// calls will not do anything. The client will only send a message to the store +/// releasing the object when the client is truly done with the object. +/// +/// @param conn The plasma connection. +/// @param object_id The object ID to attempt to release. +Status PlasmaClient::PerformRelease(ObjectID object_id) { + // Decrement the count of the number of instances of this object that are + // being used by this client. The corresponding increment should have happened + // in PlasmaClient::Get. + auto object_entry = objects_in_use.find(object_id); + ARROW_CHECK(object_entry != objects_in_use.end()); + object_entry->second->count -= 1; + ARROW_CHECK(object_entry->second->count >= 0); + // Check if the client is no longer using this object. + if (object_entry->second->count == 0) { + // Decrement the count of the number of objects in this memory-mapped file + // that the client is using. The corresponding increment should have + // happened in plasma_get. + int fd = object_entry->second->object.handle.store_fd; + auto entry = mmap_table.find(fd); + ARROW_CHECK(entry != mmap_table.end()); + entry->second->count -= 1; + ARROW_CHECK(entry->second->count >= 0); + // If none are being used then unmap the file. + if (entry->second->count == 0) { + munmap(entry->second->pointer, entry->second->length); + // Remove the corresponding entry from the hash table. + delete entry->second; + mmap_table.erase(fd); + } + // Tell the store that the client no longer needs the object. + RETURN_NOT_OK(SendReleaseRequest(store_conn, object_id)); + // Update the in_use_object_bytes. + in_use_object_bytes -= (object_entry->second->object.data_size + + object_entry->second->object.metadata_size); + DCHECK(in_use_object_bytes >= 0); + // Remove the entry from the hash table of objects currently in use. + delete object_entry->second; + objects_in_use.erase(object_id); + } + return Status::OK(); +} + +Status PlasmaClient::Release(ObjectID object_id) { + // Add the new object to the release history. + release_history.push_front(object_id); + // If there are too many bytes in use by the client or if there are too many + // pending release calls, and there are at least some pending release calls in + // the release_history list, then release some objects. + while ((in_use_object_bytes > + std::min(kL3CacheSizeBytes, store_capacity / 100) || + release_history.size() > config.release_delay) && + release_history.size() > 0) { + // Perform a release for the object ID for the first pending release. + RETURN_NOT_OK(PerformRelease(release_history.back())); + // Remove the last entry from the release history. + release_history.pop_back(); + } + return Status::OK(); +} + +// This method is used to query whether the plasma store contains an object. +Status PlasmaClient::Contains(ObjectID object_id, int *has_object) { + // Check if we already have a reference to the object. + if (objects_in_use.count(object_id) > 0) { + *has_object = 1; + } else { + // If we don't already have a reference to the object, check with the store + // to see if we have the object. + RETURN_NOT_OK(SendContainsRequest(store_conn, object_id)); + std::vector buffer; + RETURN_NOT_OK( + PlasmaReceive(store_conn, MessageType_PlasmaContainsReply, buffer)); + ObjectID object_id2; + RETURN_NOT_OK(ReadContainsReply(buffer.data(), &object_id2, has_object)); + } + return Status::OK(); +} + +static void compute_block_hash(const unsigned char *data, + int64_t nbytes, + uint64_t *hash) { + XXH64_state_t hash_state; + XXH64_reset(&hash_state, XXH64_DEFAULT_SEED); + XXH64_update(&hash_state, data, nbytes); + *hash = XXH64_digest(&hash_state); +} + +static inline bool compute_object_hash_parallel(XXH64_state_t *hash_state, + const unsigned char *data, + int64_t nbytes) { + // Note that this function will likely be faster if the address of data is + // aligned on a 64-byte boundary. + const uint64_t num_threads = kThreadPoolSize; + uint64_t threadhash[num_threads + 1]; + const uint64_t data_address = reinterpret_cast(data); + const uint64_t num_blocks = nbytes / BLOCK_SIZE; + const uint64_t chunk_size = (num_blocks / num_threads) * BLOCK_SIZE; + const uint64_t right_address = data_address + chunk_size * num_threads; + const uint64_t suffix = (data_address + nbytes) - right_address; + // Now the data layout is | k * num_threads * block_size | suffix | == + // | num_threads * chunk_size | suffix |, where chunk_size = k * block_size. + // Each thread gets a "chunk" of k blocks, except the suffix thread. + + for (int i = 0; i < num_threads; i++) { + threadpool_[i] = + std::thread(compute_block_hash, + reinterpret_cast(data_address) + i * chunk_size, + chunk_size, &threadhash[i]); + } + compute_block_hash(reinterpret_cast(right_address), suffix, + &threadhash[num_threads]); + + // Join the threads. + for (auto &t : threadpool_) { + if (t.joinable()) { + t.join(); + } + } + + XXH64_update(hash_state, (unsigned char *) threadhash, sizeof(threadhash)); + return true; +} + +static uint64_t compute_object_hash(const ObjectBuffer &obj_buffer) { + XXH64_state_t hash_state; + XXH64_reset(&hash_state, XXH64_DEFAULT_SEED); + if (obj_buffer.data_size >= kBytesInMB) { + compute_object_hash_parallel(&hash_state, (unsigned char *) obj_buffer.data, + obj_buffer.data_size); + } else { + XXH64_update(&hash_state, (unsigned char *) obj_buffer.data, + obj_buffer.data_size); + } + XXH64_update(&hash_state, (unsigned char *) obj_buffer.metadata, + obj_buffer.metadata_size); + return XXH64_digest(&hash_state); +} + +bool plasma_compute_object_hash(PlasmaClient *conn, + ObjectID obj_id, + unsigned char *digest) { + // Get the plasma object data. We pass in a timeout of 0 to indicate that + // the operation should timeout immediately. + ObjectBuffer obj_buffer; + ObjectID obj_id_array[1] = {obj_id}; + uint64_t hash; + + ARROW_CHECK_OK(conn->Get(obj_id_array, 1, 0, &obj_buffer)); + // If the object was not retrieved, return false. + if (obj_buffer.data_size == -1) { + return false; + } + // Compute the hash. + hash = compute_object_hash(obj_buffer); + memcpy(digest, &hash, sizeof(hash)); + // Release the plasma object. + ARROW_CHECK_OK(conn->Release(obj_id)); + return true; +} + +Status PlasmaClient::Seal(ObjectID object_id) { + // Make sure this client has a reference to the object before sending the + // request to Plasma. + auto object_entry = objects_in_use.find(object_id); + ARROW_CHECK(object_entry != objects_in_use.end()) + << "Plasma client called seal an object without a reference to it"; + ARROW_CHECK(!object_entry->second->is_sealed) + << "Plasma client called seal an already sealed object"; + object_entry->second->is_sealed = true; + /// Send the seal request to Plasma. + static unsigned char digest[kDigestSize]; + ARROW_CHECK(plasma_compute_object_hash(this, object_id, &digest[0])); + RETURN_NOT_OK(SendSealRequest(store_conn, object_id, &digest[0])); + // We call PlasmaClient::Release to decrement the number of instances of this + // object + // that are currently being used by this client. The corresponding increment + // happened in plasma_create and was used to ensure that the object was not + // released before the call to PlasmaClient::Seal. + return Release(object_id); +} + +Status PlasmaClient::Delete(ObjectID object_id) { + // TODO(rkn): In the future, we can use this method to give hints to the + // eviction policy about when an object will no longer be needed. + return Status::NotImplemented("PlasmaClient::Delete is not implemented."); +} + +Status PlasmaClient::Evict(int64_t num_bytes, int64_t &num_bytes_evicted) { + // Send a request to the store to evict objects. + RETURN_NOT_OK(SendEvictRequest(store_conn, num_bytes)); + // Wait for a response with the number of bytes actually evicted. + std::vector buffer; + int64_t type; + RETURN_NOT_OK(ReadMessage(store_conn, &type, buffer)); + return ReadEvictReply(buffer.data(), num_bytes_evicted); +} + +Status PlasmaClient::Subscribe(int &fd) { + int sock[2]; + // Create a non-blocking socket pair. This will only be used to send + // notifications from the Plasma store to the client. + socketpair(AF_UNIX, SOCK_STREAM, 0, sock); + // Make the socket non-blocking. + int flags = fcntl(sock[1], F_GETFL, 0); + ARROW_CHECK(fcntl(sock[1], F_SETFL, flags | O_NONBLOCK) == 0); + // Tell the Plasma store about the subscription. + RETURN_NOT_OK(SendSubscribeRequest(store_conn)); + // Send the file descriptor that the Plasma store should use to push + // notifications about sealed objects to this client. + ARROW_CHECK(send_fd(store_conn, sock[1]) >= 0); + close(sock[1]); + // Return the file descriptor that the client should use to read notifications + // about sealed objects. + fd = sock[0]; + return Status::OK(); +} + +Status PlasmaClient::Connect(const std::string &store_socket_name, + const std::string &manager_socket_name, + int release_delay) { + store_conn = connect_ipc_sock_retry(store_socket_name, -1, -1); + if (manager_socket_name != "") { + manager_conn = connect_ipc_sock_retry(manager_socket_name, -1, -1); + } else { + manager_conn = -1; + } + config.release_delay = release_delay; + in_use_object_bytes = 0; + // Send a ConnectRequest to the store to get its memory capacity. + RETURN_NOT_OK(SendConnectRequest(store_conn)); + std::vector buffer; + RETURN_NOT_OK( + PlasmaReceive(store_conn, MessageType_PlasmaConnectReply, buffer)); + RETURN_NOT_OK(ReadConnectReply(buffer.data(), &store_capacity)); + return Status::OK(); +} + +Status PlasmaClient::Disconnect() { + // NOTE: We purposefully do not finish sending release calls for objects in + // use, so that we don't duplicate PlasmaClient::Release calls (when handling + // a + // SIGTERM, for example). + for (auto &entry : objects_in_use) { + delete entry.second; + } + for (auto &entry : mmap_table) { + delete entry.second; + } + // Close the connections to Plasma. The Plasma store will release the objects + // that were in use by us when handling the SIGPIPE. + close(store_conn); + if (manager_conn >= 0) { + close(manager_conn); + } + return Status::OK(); +} + +bool plasma_manager_is_connected(PlasmaClient *conn) { + return conn->manager_conn >= 0; +} + +#define h_addr h_addr_list[0] + +Status PlasmaClient::Transfer(const char *address, + int port, + ObjectID object_id) { + return SendDataRequest(manager_conn, object_id, address, port); +} + +Status PlasmaClient::Fetch(int num_object_ids, ObjectID object_ids[]) { + ARROW_CHECK(manager_conn >= 0); + return SendFetchRequest(manager_conn, object_ids, num_object_ids); +} + +int get_manager_fd(PlasmaClient *conn) { + return conn->manager_conn; +} + +Status PlasmaClient::Info(ObjectID object_id, int *object_status) { + ARROW_CHECK(manager_conn >= 0); + + RETURN_NOT_OK(SendStatusRequest(manager_conn, &object_id, 1)); + std::vector buffer; + RETURN_NOT_OK( + PlasmaReceive(manager_conn, MessageType_PlasmaStatusReply, buffer)); + return ReadStatusReply(buffer.data(), &object_id, object_status, 1); +} + +Status PlasmaClient::Wait(int num_object_requests, + ObjectRequest object_requests[], + int num_ready_objects, + uint64_t timeout_ms, + int &num_objects_ready) { + ARROW_CHECK(manager_conn >= 0); + ARROW_CHECK(num_object_requests > 0); + ARROW_CHECK(num_ready_objects > 0); + ARROW_CHECK(num_ready_objects <= num_object_requests); + + for (int i = 0; i < num_object_requests; ++i) { + ARROW_CHECK(object_requests[i].type == PLASMA_QUERY_LOCAL || + object_requests[i].type == PLASMA_QUERY_ANYWHERE); + } + + RETURN_NOT_OK(SendWaitRequest(manager_conn, object_requests, + num_object_requests, num_ready_objects, + timeout_ms)); + std::vector buffer; + RETURN_NOT_OK( + PlasmaReceive(manager_conn, MessageType_PlasmaWaitReply, buffer)); + RETURN_NOT_OK( + ReadWaitReply(buffer.data(), object_requests, &num_ready_objects)); + + num_objects_ready = 0; + for (int i = 0; i < num_object_requests; ++i) { + int type = object_requests[i].type; + int status = object_requests[i].status; + switch (type) { + case PLASMA_QUERY_LOCAL: + if (status == ObjectStatus_Local) { + num_objects_ready += 1; + } + break; + case PLASMA_QUERY_ANYWHERE: + if (status == ObjectStatus_Local || status == ObjectStatus_Remote) { + num_objects_ready += 1; + } else { + ARROW_CHECK(status == ObjectStatus_Nonexistent); + } + break; + default: + ARROW_LOG(FATAL) << "This code should be unreachable."; + } + } + return Status::OK(); +} diff --git a/cpp/src/plasma/plasma_client.h b/cpp/src/plasma/plasma_client.h new file mode 100644 index 00000000000..cd03840412f --- /dev/null +++ b/cpp/src/plasma/plasma_client.h @@ -0,0 +1,335 @@ +#ifndef PLASMA_CLIENT_H +#define PLASMA_CLIENT_H + +#include +#include + +#include + +#include "plasma.h" + +using arrow::Status; + +#define PLASMA_DEFAULT_RELEASE_DELAY 64 + +// Use 100MB as an overestimate of the L3 cache size. +constexpr int64_t kL3CacheSizeBytes = 100000000; + +/// Object buffer data structure. +struct ObjectBuffer { + /// The size in bytes of the data object. + int64_t data_size; + /// The address of the data object. + uint8_t *data; + /// The metadata size in bytes. + int64_t metadata_size; + /// The address of the metadata. + uint8_t *metadata; +}; + +/// Configuration options for the plasma client. +struct PlasmaClientConfig { + /// Number of release calls we wait until the object is actually released. + /// This allows us to avoid invalidating the cpu cache on workers if objects + /// are reused accross tasks. + int release_delay; +}; + +struct ClientMmapTableEntry; +struct ObjectInUseEntry; + +class PlasmaClient { + public: + /// Connect to the local plasma store and plasma manager. Return + /// the resulting connection. + /// + /// @param store_socket_name The name of the UNIX domain socket to use to + /// connect to the Plasma store. + /// @param manager_socket_name The name of the UNIX domain socket to use to + /// connect to the local Plasma manager. If this is NULL, then this + /// function will not connect to a manager. + /// @param release_delay Number of released objects that are kept around + /// and not evicted to avoid too many munmaps. + /// @return The return status. + Status Connect(const std::string &store_socket_name, + const std::string &manager_socket_name, + int release_delay); + + /// Create an object in the Plasma Store. Any metadata for this object must be + /// be passed in when the object is created. + /// + /// @param object_id The ID to use for the newly created object. + /// @param data_size The size in bytes of the space to be allocated for this + /// object's + /// data (this does not include space used for metadata). + /// @param metadata The object's metadata. If there is no metadata, this + /// pointer + /// should be NULL. + /// @param metadata_size The size in bytes of the metadata. If there is no + /// metadata, this should be 0. + /// @param data The address of the newly created object will be written here. + /// @return The return status. + Status Create(ObjectID object_id, + int64_t data_size, + uint8_t *metadata, + int64_t metadata_size, + uint8_t **data); + + /// Get some objects from the Plasma Store. This function will block until the + /// objects have all been created and sealed in the Plasma Store or the + /// timeout + /// expires. The caller is responsible for releasing any retrieved objects, + /// but + /// the caller should not release objects that were not retrieved. + /// + /// @param object_ids The IDs of the objects to get. + /// @param num_object_ids The number of object IDs to get. + /// @param timeout_ms The amount of time in milliseconds to wait before this + /// request times out. If this value is -1, then no timeout is set. + /// @param object_buffers An array where the results will be stored. If the + /// data + /// size field is -1, then the object was not retrieved. + /// @return The return status. + Status Get(ObjectID object_ids[], + int64_t num_objects, + int64_t timeout_ms, + ObjectBuffer object_buffers[]); + + /// Tell Plasma that the client no longer needs the object. This should be + /// called + /// after Get when the client is done with the object. After this call, + /// the address returned by Get is no longer valid. This should be called + /// once for each call to Get (with the same object ID). + /// + /// @param object_id The ID of the object that is no longer needed. + /// @return The return status. + Status Release(ObjectID object_id); + + /// Check if the object store contains a particular object and the object has + /// been sealed. The result will be stored in has_object. + /// + /// @todo: We may want to indicate if the object has been created but not + /// sealed. + /// + /// @param object_id The ID of the object whose presence we are checking. + /// @param has_object The function will write 1 at this address if the object + /// is + /// present and 0 if it is not present. + /// @return The return status. + Status Contains(ObjectID object_id, int *has_object); + + /// Seal an object in the object store. The object will be immutable after + /// this + /// call. + /// + /// @param object_id The ID of the object to seal. + /// @return The return status. + Status Seal(ObjectID object_id); + + /// Delete an object from the object store. This currently assumes that the + /// object is present and has been sealed. + /// + /// @todo We may want to allow the deletion of objects that are not present or + /// haven't been sealed. + /// + /// @param object_id The ID of the object to delete. + /// @return The return status. + Status Delete(ObjectID object_id); + + /// Delete objects until we have freed up num_bytes bytes or there are no more + /// released objects that can be deleted. + /// + /// @param num_bytes The number of bytes to try to free up. + /// @param num_bytes_evicted Out parameter for total number of bytes of space + /// retrieved. + /// @return The return status. + Status Evict(int64_t num_bytes, int64_t &num_bytes_evicted); + + /// Subscribe to notifications when objects are sealed in the object store. + /// Whenever an object is sealed, a message will be written to the client + /// socket + /// that is returned by this method. + /// + /// @param fd Out parameter for the file descriptor the client should use to + /// read notifications + /// from the object store about sealed objects. + /// @return The return status. + Status Subscribe(int &fd); + + /// Disconnect from the local plasma instance, including the local store and + /// manager. + /// + /// @return The return status. + Status Disconnect(); + + /// Attempt to initiate the transfer of some objects from remote Plasma + /// Stores. + /// This method does not guarantee that the fetched objects will arrive + /// locally. + /// + /// For an object that is available in the local Plasma Store, this method + /// will + /// not do anything. For an object that is not available locally, it will + /// check + /// if the object are already being fetched. If so, it will not do anything. + /// If + /// not, it will query the object table for a list of Plasma Managers that + /// have + /// the object. The object table will return a non-empty list, and this Plasma + /// Manager will attempt to initiate transfers from one of those Plasma + /// Managers. + /// + /// This function is non-blocking. + /// + /// This method is idempotent in the sense that it is ok to call it multiple + /// times. + /// + /// @param num_object_ids The number of object IDs fetch is being called on. + /// @param object_ids The IDs of the objects that fetch is being called on. + /// @return The return status. + Status Fetch(int num_object_ids, ObjectID object_ids[]); + + /// Wait for (1) a specified number of objects to be available (sealed) in the + /// local Plasma Store or in a remote Plasma Store, or (2) for a timeout to + /// expire. This is a blocking call. + /// + /// @param num_object_requests Size of the object_requests array. + /// @param object_requests Object event array. Each element contains a request + /// for a particular object_id. The type of request is specified in the + /// "type" field. + /// - A PLASMA_QUERY_LOCAL request is satisfied when object_id becomes + /// available in the local Plasma Store. In this case, this function + /// sets the "status" field to ObjectStatus_Local. Note, if the + /// status + /// is not ObjectStatus_Local, it will be ObjectStatus_Nonexistent, + /// but it may exist elsewhere in the system. + /// - A PLASMA_QUERY_ANYWHERE request is satisfied when object_id + /// becomes + /// available either at the local Plasma Store or on a remote Plasma + /// Store. In this case, the functions sets the "status" field to + /// ObjectStatus_Local or ObjectStatus_Remote. + /// @param num_ready_objects The number of requests in object_requests array + /// that + /// must be satisfied before the function returns, unless it timeouts. + /// The num_ready_objects should be no larger than num_object_requests. + /// @param timeout_ms Timeout value in milliseconds. If this timeout expires + /// before min_num_ready_objects of requests are satisfied, the + /// function + /// returns. + /// @param num_objects_ready Out parameter for number of satisfied requests in + /// the object_requests list. If the returned number is less than + /// min_num_ready_objects this means that timeout expired. + /// @return The return status. + Status Wait(int num_object_requests, + ObjectRequest object_requests[], + int num_ready_objects, + uint64_t timeout_ms, + int &num_objects_ready); + + /// Transfer local object to a different plasma manager. + /// + /// @param conn The object containing the connection state. + /// @param addr IP address of the plasma manager we are transfering to. + /// @param port Port of the plasma manager we are transfering to. + /// @object_id ObjectID of the object we are transfering. + /// @return The return status. + Status Transfer(const char *addr, int port, ObjectID object_id); + + /// Return the status of a given object. This method may query the object + /// table. + /// + /// @param conn The object containing the connection state. + /// @param object_id The ID of the object whose status we query. + /// @param object_status Out parameter for object status. Can take the + /// following values. + /// - PLASMA_CLIENT_LOCAL, if object is stored in the local Plasma + /// Store. + /// has been already scheduled by the Plasma Manager. + /// - PLASMA_CLIENT_TRANSFER, if the object is either currently being + /// transferred or just scheduled. + /// - PLASMA_CLIENT_REMOTE, if the object is stored at a remote + /// Plasma Store. + /// - PLASMA_CLIENT_DOES_NOT_EXIST, if the object doesn’t exist in the + /// system. + /// @return The return status. + Status Info(ObjectID object_id, int *object_status); + + // private: + + Status PerformRelease(ObjectID object_id); + + /// File descriptor of the Unix domain socket that connects to the store. + int store_conn; + /// File descriptor of the Unix domain socket that connects to the manager. + int manager_conn; + /// File descriptor of the Unix domain socket on which client receives event + /// notifications for the objects it subscribes for when these objects are + /// sealed either locally or remotely. + int manager_conn_subscribe; + /// Table of dlmalloc buffer files that have been memory mapped so far. This + /// is a hash table mapping a file descriptor to a struct containing the + /// address of the corresponding memory-mapped file. + std::unordered_map mmap_table; + /// A hash table of the object IDs that are currently being used by this + /// client. + std::unordered_map + objects_in_use; + /// Object IDs of the last few release calls. This is a deque and + /// is used to delay releasing objects to see if they can be reused by + /// subsequent tasks so we do not unneccessarily invalidate cpu caches. + /// TODO(pcm): replace this with a proper lru cache using the size of the L3 + /// cache. + std::deque release_history; + /// The number of bytes in the combined objects that are held in the release + /// history doubly-linked list. If this is too large then the client starts + /// releasing objects. + int64_t in_use_object_bytes; + /// Configuration options for the plasma client. + PlasmaClientConfig config; + /// The amount of memory available to the Plasma store. The client needs this + /// information to make sure that it does not delay in releasing so much + /// memory that the store is unable to evict enough objects to free up space. + int64_t store_capacity; +}; + +/// Return true if the plasma manager is connected. +/// +/// @param conn The connection to the local plasma store and plasma manager. +/// @return True if the plasma manager is connected and false otherwise. +bool plasma_manager_is_connected(PlasmaClient *conn); + +/// Compute the hash of an object in the object store. +/// +/// @param conn The object containing the connection state. +/// @param object_id The ID of the object we want to hash. +/// @param digest A pointer at which to return the hash digest of the object. +/// The pointer must have at least DIGEST_SIZE bytes allocated. +/// @return A boolean representing whether the hash operation succeeded. +bool plasma_compute_object_hash(PlasmaClient *conn, + ObjectID object_id, + unsigned char *digest); + +/** + * Get the file descriptor for the socket connection to the plasma manager. + * + * @param conn The plasma connection. + * @return The file descriptor for the manager connection. If there is no + * connection to the manager, this is -1. + */ +int get_manager_fd(PlasmaClient *conn); + +/** + * Return the information associated to a given object. + * + * @param conn The object containing the connection state. + * @param object_id The ID of the object whose info the client queries. + * @param object_info The object's infirmation. + * @return PLASMA_CLIENT_LOCAL, if the object is in the local Plasma Store. + * PLASMA_CLIENT_NOT_LOCAL, if not. In this case, the caller needs to + * ignore data, metadata_size, and metadata fields. + */ +// int plasma_info(PlasmaConnection *conn, +// ObjectID object_id, +// ObjectInfo *object_info); + +#endif /* PLASMA_CLIENT_H */ diff --git a/cpp/src/plasma/plasma_common.cc b/cpp/src/plasma/plasma_common.cc new file mode 100644 index 00000000000..d09be2d3516 --- /dev/null +++ b/cpp/src/plasma/plasma_common.cc @@ -0,0 +1,67 @@ +#include "plasma_common.h" + +#include + +#include "format/plasma_generated.h" + +using arrow::Status; + +UniqueID UniqueID::from_random() { + UniqueID id; + uint8_t *data = id.mutable_data(); + std::random_device engine; + for (int i = 0; i < kUniqueIDSize; i++) { + data[i] = engine(); + } + return id; +} + +UniqueID UniqueID::from_binary(const std::string &binary) { + UniqueID id; + std::memcpy(&id, binary.data(), sizeof(id)); + return id; +} + +const uint8_t *UniqueID::data() const { + return id_; +} + +uint8_t *UniqueID::mutable_data() { + return id_; +} + +std::string UniqueID::binary() const { + return std::string(reinterpret_cast(id_), kUniqueIDSize); +} + +std::string UniqueID::hex() const { + constexpr char hex[] = "0123456789abcdef"; + std::string result; + for (int i = 0; i < sizeof(UniqueID); i++) { + unsigned int val = id_[i]; + result.push_back(hex[val >> 4]); + result.push_back(hex[val & 0xf]); + } + return result; +} + +bool UniqueID::operator==(const UniqueID &rhs) const { + return std::memcmp(data(), rhs.data(), kUniqueIDSize) == 0; +} + +Status plasma_error_status(int plasma_error) { + switch (plasma_error) { + case PlasmaError_OK: + return Status::OK(); + case PlasmaError_ObjectExists: + return Status::PlasmaObjectExists( + "object already exists in the plasma store"); + case PlasmaError_ObjectNonexistent: + return Status::PlasmaObjectNonexistent( + "object does not exist in the plasma store"); + case PlasmaError_OutOfMemory: + return Status::PlasmaStoreFull("object does not fit in the plasma store"); + default: + ARROW_LOG(FATAL) << "unknown plasma error code " << plasma_error; + } +} diff --git a/cpp/src/plasma/plasma_common.h b/cpp/src/plasma/plasma_common.h new file mode 100644 index 00000000000..a46940d3c67 --- /dev/null +++ b/cpp/src/plasma/plasma_common.h @@ -0,0 +1,46 @@ +#ifndef PLASMA_COMMON_H +#define PLASMA_COMMON_H + +#include +#include +// TODO(pcm): Convert getopt and sscanf in the store to use more idiomatic C++ +// and get rid of the next three lines: +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS +#endif + +#include "logging.h" +#include "status.h" + +constexpr int64_t kUniqueIDSize = 20; + +class UniqueID { + public: + static UniqueID from_random(); + static UniqueID from_binary(const std::string &binary); + bool operator==(const UniqueID &rhs) const; + const uint8_t *data() const; + uint8_t *mutable_data(); + std::string binary() const; + std::string hex() const; + + private: + uint8_t id_[kUniqueIDSize]; +}; + +static_assert(std::is_pod::value, "UniqueID must be plain old data"); + +struct UniqueIDHasher { + /* ObjectID hashing function. */ + size_t operator()(const UniqueID &id) const { + size_t result; + std::memcpy(&result, id.data(), sizeof(size_t)); + return result; + } +}; + +typedef UniqueID ObjectID; + +arrow::Status plasma_error_status(int plasma_error); + +#endif // PLASMA_COMMON_H diff --git a/cpp/src/plasma/plasma_events.cc b/cpp/src/plasma/plasma_events.cc new file mode 100644 index 00000000000..883b745d530 --- /dev/null +++ b/cpp/src/plasma/plasma_events.cc @@ -0,0 +1,74 @@ +#include "plasma_events.h" + +#include + +void EventLoop::file_event_callback(aeEventLoop *loop, + int fd, + void *context, + int events) { + FileCallback *callback = reinterpret_cast(context); + (*callback)(events); +} + +int EventLoop::timer_event_callback(aeEventLoop *loop, + long long timer_id, + void *context) { + TimerCallback *callback = reinterpret_cast(context); + return (*callback)(timer_id); +} + +constexpr int kInitialEventLoopSize = 1024; + +EventLoop::EventLoop() { + loop_ = aeCreateEventLoop(kInitialEventLoopSize); +} + +bool EventLoop::add_file_event(int fd, int events, FileCallback callback) { + if (file_callbacks_.find(fd) != file_callbacks_.end()) { + return false; + } + auto data = std::unique_ptr(new FileCallback(callback)); + void *context = reinterpret_cast(data.get()); + // Try to add the file descriptor. + int err = aeCreateFileEvent(loop_, fd, events, EventLoop::file_event_callback, + context); + // If it cannot be added, increase the size of the event loop. + if (err == AE_ERR && errno == ERANGE) { + err = aeResizeSetSize(loop_, 3 * aeGetSetSize(loop_) / 2); + if (err != AE_OK) { + return false; + } + err = aeCreateFileEvent(loop_, fd, events, EventLoop::file_event_callback, + context); + } + // In any case, test if there were errors. + if (err == AE_OK) { + file_callbacks_.emplace(fd, std::move(data)); + return true; + } + return false; +} + +void EventLoop::remove_file_event(int fd) { + aeDeleteFileEvent(loop_, fd, AE_READABLE | AE_WRITABLE); + file_callbacks_.erase(fd); +} + +void EventLoop::run() { + aeMain(loop_); +} + +int64_t EventLoop::add_timer(int64_t timeout, TimerCallback callback) { + auto data = std::unique_ptr(new TimerCallback(callback)); + void *context = reinterpret_cast(data.get()); + int64_t timer_id = aeCreateTimeEvent( + loop_, timeout, EventLoop::timer_event_callback, context, NULL); + timer_callbacks_.emplace(timer_id, std::move(data)); + return timer_id; +} + +int EventLoop::remove_timer(int64_t timer_id) { + int err = aeDeleteTimeEvent(loop_, timer_id); + timer_callbacks_.erase(timer_id); + return err; +} diff --git a/cpp/src/plasma/plasma_events.h b/cpp/src/plasma/plasma_events.h new file mode 100644 index 00000000000..c94025f96d8 --- /dev/null +++ b/cpp/src/plasma/plasma_events.h @@ -0,0 +1,85 @@ +#ifndef PLASMA_EVENTS +#define PLASMA_EVENTS + +#include +#include +#include + +extern "C" { +#include "ae/ae.h" +} + +/// Constant specifying that the timer is done and it will be removed. +constexpr int kEventLoopTimerDone = AE_NOMORE; + +/// Read event on the file descriptor. +constexpr int kEventLoopRead = AE_READABLE; + +/// Write event on the file descriptor. +constexpr int kEventLoopWrite = AE_WRITABLE; + +class EventLoop { + public: + // Signature of the handler that will be called when there is a new event + // on the file descriptor that this handler has been registered for. + // + // The arguments are the event flags (read or write). + typedef std::function FileCallback; + + // This handler will be called when a timer times out. The timer id is + // passed as an argument. The return is the number of milliseconds the timer + // shall be reset to or kEventLoopTimerDone if the timer shall not be + // triggered again. + typedef std::function TimerCallback; + + EventLoop(); + + /// Add a new file event handler to the event loop. + /// + /// @param fd The file descriptor we are listening to. + /// @param events The flags for events we are listening to (read or write). + /// @param callback The callback that will be called when the event happens. + /// @return Returns true if the event handler was added successfully. + bool add_file_event(int fd, int events, FileCallback callback); + + /// Remove a file event handler from the event loop. + /// + /// @param fd The file descriptor of the event handler. + /// @return Void. + void remove_file_event(int fd); + + /// Register a handler that will be called after a time slice of + /// "timeout" milliseconds. + /// + /// @param timeout The timeout in milliseconds. + /// @param callback The callback for the timeout. + /// @return The ID of the newly created timer. + int64_t add_timer(int64_t timeout, TimerCallback callback); + + /// Remove a timer handler from the event loop. + /// + /// @param timer_id The ID of the timer that is to be removed. + /// @return The ae.c error code. TODO(pcm): needs to be standardized + int remove_timer(int64_t timer_id); + + /// Run the event loop. + /// + /// @return Void. + void run(); + + private: + static void file_event_callback(aeEventLoop *loop, + int fd, + void *context, + int events); + + static int timer_event_callback(aeEventLoop *loop, + long long timer_id, + void *context); + + aeEventLoop *loop_; + std::unordered_map> file_callbacks_; + std::unordered_map> timer_callbacks_; +}; + +#endif // PLASMA_EVENTS diff --git a/cpp/src/plasma/plasma_extension.cc b/cpp/src/plasma/plasma_extension.cc new file mode 100644 index 00000000000..58d45ec3cb6 --- /dev/null +++ b/cpp/src/plasma/plasma_extension.cc @@ -0,0 +1,463 @@ +#include +#include "bytesobject.h" + +#include "plasma_io.h" +#include "plasma_common.h" +#include "plasma_protocol.h" +#include "plasma_client.h" + +PyObject *PlasmaOutOfMemoryError; +PyObject *PlasmaObjectExistsError; + +#include "plasma_extension.h" + +PyObject *PyPlasma_connect(PyObject *self, PyObject *args) { + const char *store_socket_name; + const char *manager_socket_name; + int release_delay; + if (!PyArg_ParseTuple(args, "ssi", &store_socket_name, &manager_socket_name, + &release_delay)) { + return NULL; + } + PlasmaClient *client = new PlasmaClient(); + ARROW_CHECK_OK( + client->Connect(store_socket_name, manager_socket_name, release_delay)); + + return PyCapsule_New(client, "plasma", NULL); +} + +PyObject *PyPlasma_disconnect(PyObject *self, PyObject *args) { + PyObject *client_capsule; + if (!PyArg_ParseTuple(args, "O", &client_capsule)) { + return NULL; + } + PlasmaClient *client; + ARROW_CHECK(PyObjectToPlasmaClient(client_capsule, &client)); + ARROW_CHECK_OK(client->Disconnect()); + /* We use the context of the connection capsule to indicate if the connection + * is still active (if the context is NULL) or if it is closed (if the context + * is (void*) 0x1). This is neccessary because the primary pointer of the + * capsule cannot be NULL. */ + PyCapsule_SetContext(client_capsule, (void *) 0x1); + Py_RETURN_NONE; +} + +PyObject *PyPlasma_create(PyObject *self, PyObject *args) { + PlasmaClient *client; + ObjectID object_id; + long long size; + PyObject *metadata; + if (!PyArg_ParseTuple(args, "O&O&LO", PyObjectToPlasmaClient, &client, + PyStringToUniqueID, &object_id, &size, &metadata)) { + return NULL; + } + if (!PyByteArray_Check(metadata)) { + PyErr_SetString(PyExc_TypeError, "metadata must be a bytearray"); + return NULL; + } + uint8_t *data; + Status s = client->Create(object_id, size, + (uint8_t *) PyByteArray_AsString(metadata), + PyByteArray_Size(metadata), &data); + if (s.IsPlasmaObjectExists()) { + PyErr_SetString(PlasmaObjectExistsError, + "An object with this ID already exists in the plasma " + "store."); + return NULL; + } + if (s.IsPlasmaStoreFull()) { + PyErr_SetString(PlasmaOutOfMemoryError, + "The plasma store ran out of memory and could not create " + "this object."); + return NULL; + } + ARROW_CHECK(s.ok()); + +#if PY_MAJOR_VERSION >= 3 + return PyMemoryView_FromMemory((char *) data, (Py_ssize_t) size, PyBUF_WRITE); +#else + return PyBuffer_FromReadWriteMemory((void *) data, (Py_ssize_t) size); +#endif +} + +PyObject *PyPlasma_hash(PyObject *self, PyObject *args) { + PlasmaClient *client; + ObjectID object_id; + if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, + PyStringToUniqueID, &object_id)) { + return NULL; + } + unsigned char digest[kDigestSize]; + bool success = plasma_compute_object_hash(client, object_id, digest); + if (success) { + PyObject *digest_string = + PyBytes_FromStringAndSize((char *) digest, kDigestSize); + return digest_string; + } else { + Py_RETURN_NONE; + } +} + +PyObject *PyPlasma_seal(PyObject *self, PyObject *args) { + PlasmaClient *client; + ObjectID object_id; + if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, + PyStringToUniqueID, &object_id)) { + return NULL; + } + ARROW_CHECK_OK(client->Seal(object_id)); + Py_RETURN_NONE; +} + +PyObject *PyPlasma_release(PyObject *self, PyObject *args) { + PlasmaClient *client; + ObjectID object_id; + if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, + PyStringToUniqueID, &object_id)) { + return NULL; + } + ARROW_CHECK_OK(client->Release(object_id)); + Py_RETURN_NONE; +} + +PyObject *PyPlasma_get(PyObject *self, PyObject *args) { + PlasmaClient *client; + PyObject *object_id_list; + long long timeout_ms; + if (!PyArg_ParseTuple(args, "O&OL", PyObjectToPlasmaClient, &client, + &object_id_list, &timeout_ms)) { + return NULL; + } + + Py_ssize_t num_object_ids = PyList_Size(object_id_list); + ObjectID *object_ids = (ObjectID *) malloc(sizeof(ObjectID) * num_object_ids); + ObjectBuffer *object_buffers = + (ObjectBuffer *) malloc(sizeof(ObjectBuffer) * num_object_ids); + + for (int i = 0; i < num_object_ids; ++i) { + PyStringToUniqueID(PyList_GetItem(object_id_list, i), &object_ids[i]); + } + + Py_BEGIN_ALLOW_THREADS; + ARROW_CHECK_OK( + client->Get(object_ids, num_object_ids, timeout_ms, object_buffers)); + Py_END_ALLOW_THREADS; + free(object_ids); + + PyObject *returns = PyList_New(num_object_ids); + for (int i = 0; i < num_object_ids; ++i) { + if (object_buffers[i].data_size != -1) { + /* The object was retrieved, so return the object. */ + PyObject *t = PyTuple_New(2); +#if PY_MAJOR_VERSION >= 3 + PyTuple_SetItem( + t, 0, PyMemoryView_FromMemory( + (char *) object_buffers[i].data, + (Py_ssize_t) object_buffers[i].data_size, PyBUF_READ)); + PyTuple_SetItem( + t, 1, PyMemoryView_FromMemory( + (char *) object_buffers[i].metadata, + (Py_ssize_t) object_buffers[i].metadata_size, PyBUF_READ)); +#else + PyTuple_SetItem( + t, 0, PyBuffer_FromMemory((void *) object_buffers[i].data, + (Py_ssize_t) object_buffers[i].data_size)); + PyTuple_SetItem(t, 1, PyBuffer_FromMemory( + (void *) object_buffers[i].metadata, + (Py_ssize_t) object_buffers[i].metadata_size)); +#endif + PyList_SetItem(returns, i, t); + } else { + /* The object was not retrieved, so just add None to the list of return + * values. */ + Py_XINCREF(Py_None); + PyList_SetItem(returns, i, Py_None); + } + } + free(object_buffers); + return returns; +} + +PyObject *PyPlasma_contains(PyObject *self, PyObject *args) { + PlasmaClient *client; + ObjectID object_id; + if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, + PyStringToUniqueID, &object_id)) { + return NULL; + } + int has_object; + ARROW_CHECK_OK(client->Contains(object_id, &has_object)); + + if (has_object) + Py_RETURN_TRUE; + else + Py_RETURN_FALSE; +} + +PyObject *PyPlasma_fetch(PyObject *self, PyObject *args) { + PlasmaClient *client; + PyObject *object_id_list; + if (!PyArg_ParseTuple(args, "O&O", PyObjectToPlasmaClient, &client, + &object_id_list)) { + return NULL; + } + if (!plasma_manager_is_connected(client)) { + PyErr_SetString(PyExc_RuntimeError, "Not connected to the plasma manager"); + return NULL; + } + Py_ssize_t n = PyList_Size(object_id_list); + ObjectID *object_ids = (ObjectID *) malloc(sizeof(ObjectID) * n); + for (int i = 0; i < n; ++i) { + PyStringToUniqueID(PyList_GetItem(object_id_list, i), &object_ids[i]); + } + ARROW_CHECK_OK(client->Fetch((int) n, object_ids)); + free(object_ids); + Py_RETURN_NONE; +} + +PyObject *PyPlasma_wait(PyObject *self, PyObject *args) { + PlasmaClient *client; + PyObject *object_id_list; + long long timeout; + int num_returns; + if (!PyArg_ParseTuple(args, "O&OLi", PyObjectToPlasmaClient, &client, + &object_id_list, &timeout, &num_returns)) { + return NULL; + } + Py_ssize_t n = PyList_Size(object_id_list); + + if (!plasma_manager_is_connected(client)) { + PyErr_SetString(PyExc_RuntimeError, "Not connected to the plasma manager"); + return NULL; + } + if (num_returns < 0) { + PyErr_SetString(PyExc_RuntimeError, + "The argument num_returns cannot be less than zero."); + return NULL; + } + if (num_returns > n) { + PyErr_SetString( + PyExc_RuntimeError, + "The argument num_returns cannot be greater than len(object_ids)"); + return NULL; + } + int64_t threshold = 1 << 30; + if (timeout > threshold) { + PyErr_SetString(PyExc_RuntimeError, + "The argument timeout cannot be greater than 2 ** 30."); + return NULL; + } + + ObjectRequest *object_requests = + (ObjectRequest *) malloc(sizeof(ObjectRequest) * n); + for (int i = 0; i < n; ++i) { + ARROW_CHECK(PyStringToUniqueID(PyList_GetItem(object_id_list, i), + &object_requests[i].object_id) == 1); + object_requests[i].type = PLASMA_QUERY_ANYWHERE; + } + /* Drop the global interpreter lock while we are waiting, so other threads can + * run. */ + int num_return_objects; + Py_BEGIN_ALLOW_THREADS; + ARROW_CHECK_OK(client->Wait((int) n, object_requests, num_returns, + (uint64_t) timeout, num_return_objects)); + Py_END_ALLOW_THREADS; + + int num_to_return = std::min(num_return_objects, num_returns); + PyObject *ready_ids = PyList_New(num_to_return); + PyObject *waiting_ids = PySet_New(object_id_list); + int num_returned = 0; + for (int i = 0; i < n; ++i) { + if (num_returned == num_to_return) { + break; + } + if (object_requests[i].status == ObjectStatus_Local || + object_requests[i].status == ObjectStatus_Remote) { + PyObject *ready = + PyBytes_FromStringAndSize((char *) &object_requests[i].object_id, + sizeof(object_requests[i].object_id)); + PyList_SetItem(ready_ids, num_returned, ready); + PySet_Discard(waiting_ids, ready); + num_returned += 1; + } else { + ARROW_CHECK(object_requests[i].status == ObjectStatus_Nonexistent); + } + } + ARROW_CHECK(num_returned == num_to_return); + /* Return both the ready IDs and the remaining IDs. */ + PyObject *t = PyTuple_New(2); + PyTuple_SetItem(t, 0, ready_ids); + PyTuple_SetItem(t, 1, waiting_ids); + return t; +} + +PyObject *PyPlasma_evict(PyObject *self, PyObject *args) { + PlasmaClient *client; + long long num_bytes; + if (!PyArg_ParseTuple(args, "O&L", PyObjectToPlasmaClient, &client, + &num_bytes)) { + return NULL; + } + int64_t evicted_bytes; + ARROW_CHECK_OK(client->Evict((int64_t) num_bytes, evicted_bytes)); + return PyLong_FromLong((long) evicted_bytes); +} + +PyObject *PyPlasma_delete(PyObject *self, PyObject *args) { + PlasmaClient *client; + ObjectID object_id; + if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, + PyStringToUniqueID, &object_id)) { + return NULL; + } + ARROW_CHECK_OK(client->Delete(object_id)); + Py_RETURN_NONE; +} + +PyObject *PyPlasma_transfer(PyObject *self, PyObject *args) { + PlasmaClient *client; + ObjectID object_id; + const char *addr; + int port; + if (!PyArg_ParseTuple(args, "O&O&si", PyObjectToPlasmaClient, &client, + PyStringToUniqueID, &object_id, &addr, &port)) { + return NULL; + } + + if (!plasma_manager_is_connected(client)) { + PyErr_SetString(PyExc_RuntimeError, "Not connected to the plasma manager"); + return NULL; + } + + ARROW_CHECK_OK(client->Transfer(addr, port, object_id)); + Py_RETURN_NONE; +} + +PyObject *PyPlasma_subscribe(PyObject *self, PyObject *args) { + PlasmaClient *client; + if (!PyArg_ParseTuple(args, "O&", PyObjectToPlasmaClient, &client)) { + return NULL; + } + + int sock; + ARROW_CHECK_OK(client->Subscribe(sock)); + return PyLong_FromLong(sock); +} + +PyObject *PyPlasma_receive_notification(PyObject *self, PyObject *args) { + int plasma_sock; + + if (!PyArg_ParseTuple(args, "i", &plasma_sock)) { + return NULL; + } + /* Receive object notification from the plasma connection socket. If the + * object was added, return a tuple of its fields: ObjectID, data_size, + * metadata_size. If the object was deleted, data_size and metadata_size will + * be set to -1. */ + uint8_t *notification = read_message_async(plasma_sock); + if (notification == NULL) { + PyErr_SetString(PyExc_RuntimeError, + "Failed to read object notification from Plasma socket"); + return NULL; + } + auto object_info = flatbuffers::GetRoot(notification); + /* Construct a tuple from object_info and return. */ + PyObject *t = PyTuple_New(3); + PyTuple_SetItem(t, 0, + PyBytes_FromStringAndSize(object_info->object_id()->data(), + object_info->object_id()->size())); + if (object_info->is_deletion()) { + PyTuple_SetItem(t, 1, PyLong_FromLong(-1)); + PyTuple_SetItem(t, 2, PyLong_FromLong(-1)); + } else { + PyTuple_SetItem(t, 1, PyLong_FromLong(object_info->data_size())); + PyTuple_SetItem(t, 2, PyLong_FromLong(object_info->metadata_size())); + } + + free(notification); + return t; +} + +static PyMethodDef plasma_methods[] = { + {"connect", PyPlasma_connect, METH_VARARGS, "Connect to plasma."}, + {"disconnect", PyPlasma_disconnect, METH_VARARGS, + "Disconnect from plasma."}, + {"create", PyPlasma_create, METH_VARARGS, "Create a new plasma object."}, + {"hash", PyPlasma_hash, METH_VARARGS, + "Compute the hash of a plasma object."}, + {"seal", PyPlasma_seal, METH_VARARGS, "Seal a plasma object."}, + {"get", PyPlasma_get, METH_VARARGS, "Get a plasma object."}, + {"contains", PyPlasma_contains, METH_VARARGS, + "Does the plasma store contain this plasma object?"}, + {"fetch", PyPlasma_fetch, METH_VARARGS, + "Fetch the object from another plasma manager instance."}, + {"wait", PyPlasma_wait, METH_VARARGS, + "Wait until num_returns objects in object_ids are ready."}, + {"evict", PyPlasma_evict, METH_VARARGS, + "Evict some objects until we recover some number of bytes."}, + {"release", PyPlasma_release, METH_VARARGS, "Release the plasma object."}, + {"delete", PyPlasma_delete, METH_VARARGS, "Delete a plasma object."}, + {"transfer", PyPlasma_transfer, METH_VARARGS, + "Transfer object to another plasma manager."}, + {"subscribe", PyPlasma_subscribe, METH_VARARGS, + "Subscribe to the plasma notification socket."}, + {"receive_notification", PyPlasma_receive_notification, METH_VARARGS, + "Receive next notification from plasma notification socket."}, + {NULL} /* Sentinel */ +}; + +#if PY_MAJOR_VERSION >= 3 +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "libplasma", /* m_name */ + "A Python client library for plasma.", /* m_doc */ + 0, /* m_size */ + plasma_methods, /* m_methods */ + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL, /* m_free */ +}; +#endif + +#if PY_MAJOR_VERSION >= 3 +#define INITERROR return NULL +#else +#define INITERROR return +#endif + +#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ +#define PyMODINIT_FUNC void +#endif + +#if PY_MAJOR_VERSION >= 3 +#define MOD_INIT(name) PyMODINIT_FUNC PyInit_##name(void) +#else +#define MOD_INIT(name) PyMODINIT_FUNC init##name(void) +#endif + +MOD_INIT(libplasma) { +#if PY_MAJOR_VERSION >= 3 + PyObject *m = PyModule_Create(&moduledef); +#else + PyObject *m = Py_InitModule3("libplasma", plasma_methods, + "A Python client library for plasma."); +#endif + + /* Create a custom exception for when an object ID is reused. */ + char plasma_object_exists_error[] = "plasma_object_exists.error"; + PlasmaObjectExistsError = + PyErr_NewException(plasma_object_exists_error, NULL, NULL); + Py_INCREF(PlasmaObjectExistsError); + PyModule_AddObject(m, "plasma_object_exists_error", PlasmaObjectExistsError); + /* Create a custom exception for when the plasma store is out of memory. */ + char plasma_out_of_memory_error[] = "plasma_out_of_memory.error"; + PlasmaOutOfMemoryError = + PyErr_NewException(plasma_out_of_memory_error, NULL, NULL); + Py_INCREF(PlasmaOutOfMemoryError); + PyModule_AddObject(m, "plasma_out_of_memory_error", PlasmaOutOfMemoryError); + +#if PY_MAJOR_VERSION >= 3 + return m; +#endif +} diff --git a/cpp/src/plasma/plasma_extension.h b/cpp/src/plasma/plasma_extension.h new file mode 100644 index 00000000000..6c7bf595456 --- /dev/null +++ b/cpp/src/plasma/plasma_extension.h @@ -0,0 +1,24 @@ +#ifndef PLASMA_EXTENSION_H +#define PLASMA_EXTENSION_H + +static int PyObjectToPlasmaClient(PyObject *object, PlasmaClient **client) { + if (PyCapsule_IsValid(object, "plasma")) { + *client = (PlasmaClient *) PyCapsule_GetPointer(object, "plasma"); + return 1; + } else { + PyErr_SetString(PyExc_TypeError, "must be a 'plasma' capsule"); + return 0; + } +} + +int PyStringToUniqueID(PyObject *object, ObjectID *object_id) { + if (PyBytes_Check(object)) { + memcpy(object_id, PyBytes_AsString(object), sizeof(ObjectID)); + return 1; + } else { + PyErr_SetString(PyExc_TypeError, "must be a 20 character string"); + return 0; + } +} + +#endif /* PLASMA_EXTENSION_H */ diff --git a/cpp/src/plasma/plasma_io.cc b/cpp/src/plasma/plasma_io.cc new file mode 100644 index 00000000000..7bad98518cb --- /dev/null +++ b/cpp/src/plasma/plasma_io.cc @@ -0,0 +1,220 @@ +#include "plasma_io.h" +#include "plasma_common.h" + +using arrow::Status; + +/* Number of times we try binding to a socket. */ +#define NUM_BIND_ATTEMPTS 5 +#define BIND_TIMEOUT_MS 100 + +/* Number of times we try connecting to a socket. */ +#define NUM_CONNECT_ATTEMPTS 50 +#define CONNECT_TIMEOUT_MS 100 + +Status WriteBytes(int fd, uint8_t *cursor, size_t length) { + ssize_t nbytes = 0; + size_t bytesleft = length; + size_t offset = 0; + while (bytesleft > 0) { + /* While we haven't written the whole message, write to the file descriptor, + * advance the cursor, and decrease the amount left to write. */ + nbytes = write(fd, cursor + offset, bytesleft); + if (nbytes < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { + continue; + } + return Status::IOError(std::string(strerror(errno))); + } else if (nbytes == 0) { + return Status::IOError("Encountered unexpected EOF"); + } + ARROW_CHECK(nbytes > 0); + bytesleft -= nbytes; + offset += nbytes; + } + + return Status::OK(); +} + +Status WriteMessage(int fd, int64_t type, int64_t length, uint8_t *bytes) { + int64_t version = PLASMA_PROTOCOL_VERSION; + RETURN_NOT_OK( + WriteBytes(fd, reinterpret_cast(&version), sizeof(version))); + RETURN_NOT_OK( + WriteBytes(fd, reinterpret_cast(&type), sizeof(type))); + RETURN_NOT_OK( + WriteBytes(fd, reinterpret_cast(&length), sizeof(length))); + return WriteBytes(fd, bytes, length * sizeof(char)); +} + +Status ReadBytes(int fd, uint8_t *cursor, size_t length) { + ssize_t nbytes = 0; + /* Termination condition: EOF or read 'length' bytes total. */ + size_t bytesleft = length; + size_t offset = 0; + while (bytesleft > 0) { + nbytes = read(fd, cursor + offset, bytesleft); + if (nbytes < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { + continue; + } + return Status::IOError(std::string(strerror(errno))); + } else if (0 == nbytes) { + return Status::IOError("Encountered unexpected EOF"); + } + ARROW_CHECK(nbytes > 0); + bytesleft -= nbytes; + offset += nbytes; + } + + return Status::OK(); +} + +Status ReadMessage(int fd, int64_t *type, std::vector &buffer) { + int64_t version; + RETURN_NOT_OK_ELSE( + ReadBytes(fd, reinterpret_cast(&version), sizeof(version)), + *type = DISCONNECT_CLIENT); + ARROW_CHECK(version == PLASMA_PROTOCOL_VERSION) << "version = " << version; + int64_t length; + RETURN_NOT_OK_ELSE( + ReadBytes(fd, reinterpret_cast(type), sizeof(*type)), + *type = DISCONNECT_CLIENT); + RETURN_NOT_OK_ELSE( + ReadBytes(fd, reinterpret_cast(&length), sizeof(length)), + *type = DISCONNECT_CLIENT); + if (length > buffer.size()) { + buffer.resize(length); + } + RETURN_NOT_OK_ELSE(ReadBytes(fd, buffer.data(), length), + *type = DISCONNECT_CLIENT); + return Status::OK(); +} + +int bind_ipc_sock(const std::string &pathname, bool shall_listen) { + struct sockaddr_un socket_address; + int socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (socket_fd < 0) { + ARROW_LOG(ERROR) << "socket() failed for pathname " << pathname; + return -1; + } + /* Tell the system to allow the port to be reused. */ + int on = 1; + if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, + sizeof(on)) < 0) { + ARROW_LOG(ERROR) << "setsockopt failed for pathname " << pathname; + close(socket_fd); + return -1; + } + + unlink(pathname.c_str()); + memset(&socket_address, 0, sizeof(socket_address)); + socket_address.sun_family = AF_UNIX; + if (pathname.size() + 1 > sizeof(socket_address.sun_path)) { + ARROW_LOG(ERROR) << "Socket pathname is too long."; + close(socket_fd); + return -1; + } + strncpy(socket_address.sun_path, pathname.c_str(), pathname.size() + 1); + + if (bind(socket_fd, (struct sockaddr *) &socket_address, + sizeof(socket_address)) != 0) { + ARROW_LOG(ERROR) << "Bind failed for pathname " << pathname; + close(socket_fd); + return -1; + } + if (shall_listen && listen(socket_fd, 5) == -1) { + ARROW_LOG(ERROR) << "Could not listen to socket " << pathname; + close(socket_fd); + return -1; + } + return socket_fd; +} + +int connect_ipc_sock_retry(const std::string &pathname, + int num_retries, + int64_t timeout) { + /* Pick the default values if the user did not specify. */ + if (num_retries < 0) { + num_retries = NUM_CONNECT_ATTEMPTS; + } + if (timeout < 0) { + timeout = CONNECT_TIMEOUT_MS; + } + + int fd = -1; + for (int num_attempts = 0; num_attempts < num_retries; ++num_attempts) { + fd = connect_ipc_sock(pathname); + if (fd >= 0) { + break; + } + if (num_attempts == 0) { + ARROW_LOG(ERROR) << "Connection to socket failed for pathname " + << pathname; + } + /* Sleep for timeout milliseconds. */ + usleep(timeout * 1000); + } + /* If we could not connect to the socket, exit. */ + if (fd == -1) { + ARROW_LOG(FATAL) << "Could not connect to socket " << pathname; + } + return fd; +} + +int connect_ipc_sock(const std::string &pathname) { + struct sockaddr_un socket_address; + int socket_fd; + + socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (socket_fd < 0) { + ARROW_LOG(ERROR) << "socket() failed for pathname " << pathname; + return -1; + } + + memset(&socket_address, 0, sizeof(socket_address)); + socket_address.sun_family = AF_UNIX; + if (pathname.size() + 1 > sizeof(socket_address.sun_path)) { + ARROW_LOG(ERROR) << "Socket pathname is too long."; + return -1; + } + strncpy(socket_address.sun_path, pathname.c_str(), pathname.size() + 1); + + if (connect(socket_fd, (struct sockaddr *) &socket_address, + sizeof(socket_address)) != 0) { + close(socket_fd); + return -1; + } + + return socket_fd; +} + +int AcceptClient(int socket_fd) { + int client_fd = accept(socket_fd, NULL, NULL); + if (client_fd < 0) { + ARROW_LOG(ERROR) << "Error reading from socket."; + return -1; + } + return client_fd; +} + +uint8_t *read_message_async(int sock) { + int64_t size; + Status s = ReadBytes(sock, (uint8_t *) &size, sizeof(int64_t)); + if (!s.ok()) { + /* The other side has closed the socket. */ + ARROW_LOG(DEBUG) + << "Socket has been closed, or some other error has occurred."; + close(sock); + return NULL; + } + uint8_t *message = (uint8_t *) malloc(size); + s = ReadBytes(sock, message, size); + if (!s.ok()) { + /* The other side has closed the socket. */ + ARROW_LOG(DEBUG) + << "Socket has been closed, or some other error has occurred."; + close(sock); + return NULL; + } + return message; +} diff --git a/cpp/src/plasma/plasma_io.h b/cpp/src/plasma/plasma_io.h new file mode 100644 index 00000000000..5127633947a --- /dev/null +++ b/cpp/src/plasma/plasma_io.h @@ -0,0 +1,38 @@ +#include +#include +#include +#include + +#include +#include + +#include "status.h" + +// TODO(pcm): Replace our own custom message header (message type, +// message length, plasma protocol verion) with one that is serialized +// using flatbuffers. +#define PLASMA_PROTOCOL_VERSION 0x0000000000000000 +#define DISCONNECT_CLIENT 0 + +arrow::Status WriteBytes(int fd, uint8_t *cursor, size_t length); + +arrow::Status WriteMessage(int fd, + int64_t type, + int64_t length, + uint8_t *bytes); + +arrow::Status ReadBytes(int fd, uint8_t *cursor, size_t length); + +arrow::Status ReadMessage(int fd, int64_t *type, std::vector &buffer); + +int bind_ipc_sock(const std::string &pathname, bool shall_listen); + +int connect_ipc_sock(const std::string &pathname); + +int connect_ipc_sock_retry(const std::string &pathname, + int num_retries, + int64_t timeout); + +int AcceptClient(int socket_fd); + +uint8_t *read_message_async(int sock); diff --git a/cpp/src/plasma/plasma_protocol.cc b/cpp/src/plasma/plasma_protocol.cc new file mode 100644 index 00000000000..134d09e8099 --- /dev/null +++ b/cpp/src/plasma/plasma_protocol.cc @@ -0,0 +1,577 @@ +#include "flatbuffers/flatbuffers.h" +#include "format/plasma_generated.h" + +#include "plasma_common.h" +#include "plasma_protocol.h" +#include "plasma_io.h" + +flatbuffers::Offset< + flatbuffers::Vector>> +to_flatbuffer(flatbuffers::FlatBufferBuilder &fbb, + ObjectID object_ids[], + int64_t num_objects) { + std::vector> results; + for (size_t i = 0; i < num_objects; i++) { + results.push_back(fbb.CreateString(object_ids[i].binary())); + } + return fbb.CreateVector(results); +} + +Status PlasmaReceive(int sock, + int64_t message_type, + std::vector &buffer) { + int64_t type; + RETURN_NOT_OK(ReadMessage(sock, &type, buffer)); + ARROW_CHECK(type == message_type) << "type = " << type + << ", message_type = " << message_type; + return Status::OK(); +} + +/* Create messages. */ + +Status SendCreateRequest(int sock, + ObjectID object_id, + int64_t data_size, + int64_t metadata_size) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaCreateRequest( + fbb, fbb.CreateString(object_id.binary()), data_size, metadata_size); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaCreateRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadCreateRequest(uint8_t *data, + ObjectID *object_id, + int64_t *data_size, + int64_t *metadata_size) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *data_size = message->data_size(); + *metadata_size = message->metadata_size(); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return Status::OK(); +} + +Status SendCreateReply(int sock, + ObjectID object_id, + PlasmaObject *object, + int error_code) { + flatbuffers::FlatBufferBuilder fbb; + PlasmaObjectSpec plasma_object( + object->handle.store_fd, object->handle.mmap_size, object->data_offset, + object->data_size, object->metadata_offset, object->metadata_size); + auto message = + CreatePlasmaCreateReply(fbb, fbb.CreateString(object_id.binary()), + &plasma_object, (PlasmaError) error_code); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaCreateReply, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadCreateReply(uint8_t *data, + ObjectID *object_id, + PlasmaObject *object) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *object_id = ObjectID::from_binary(message->object_id()->str()); + object->handle.store_fd = message->plasma_object()->segment_index(); + object->handle.mmap_size = message->plasma_object()->mmap_size(); + object->data_offset = message->plasma_object()->data_offset(); + object->data_size = message->plasma_object()->data_size(); + object->metadata_offset = message->plasma_object()->metadata_offset(); + object->metadata_size = message->plasma_object()->metadata_size(); + return plasma_error_status(message->error()); +} + +/* Seal messages. */ + +Status SendSealRequest(int sock, ObjectID object_id, unsigned char *digest) { + flatbuffers::FlatBufferBuilder fbb; + auto digest_string = fbb.CreateString((char *) digest, kDigestSize); + auto message = CreatePlasmaSealRequest( + fbb, fbb.CreateString(object_id.binary()), digest_string); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaSealRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadSealRequest(uint8_t *data, + ObjectID *object_id, + unsigned char *digest) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *object_id = ObjectID::from_binary(message->object_id()->str()); + ARROW_CHECK(message->digest()->size() == kDigestSize); + memcpy(digest, message->digest()->data(), kDigestSize); + return Status::OK(); +} + +Status SendSealReply(int sock, ObjectID object_id, int error) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaSealReply( + fbb, fbb.CreateString(object_id.binary()), (PlasmaError) error); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaSealReply, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadSealReply(uint8_t *data, ObjectID *object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return plasma_error_status(message->error()); +} + +/* Release messages. */ + +Status SendReleaseRequest(int sock, ObjectID object_id) { + flatbuffers::FlatBufferBuilder fbb; + auto message = + CreatePlasmaSealRequest(fbb, fbb.CreateString(object_id.binary())); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaReleaseRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadReleaseRequest(uint8_t *data, ObjectID *object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return Status::OK(); +} + +Status SendReleaseReply(int sock, ObjectID object_id, int error) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaReleaseReply( + fbb, fbb.CreateString(object_id.binary()), (PlasmaError) error); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaReleaseReply, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadReleaseReply(uint8_t *data, ObjectID *object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return plasma_error_status(message->error()); +} + +/* Delete messages. */ + +Status SendDeleteRequest(int sock, ObjectID object_id) { + flatbuffers::FlatBufferBuilder fbb; + auto message = + CreatePlasmaDeleteRequest(fbb, fbb.CreateString(object_id.binary())); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaDeleteRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadDeleteRequest(uint8_t *data, ObjectID *object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return Status::OK(); +} + +Status SendDeleteReply(int sock, ObjectID object_id, int error) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaDeleteReply( + fbb, fbb.CreateString(object_id.binary()), (PlasmaError) error); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaDeleteReply, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadDeleteReply(uint8_t *data, ObjectID *object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return plasma_error_status(message->error()); +} + +/* Satus messages. */ + +Status SendStatusRequest(int sock, ObjectID object_ids[], int64_t num_objects) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaStatusRequest( + fbb, to_flatbuffer(fbb, object_ids, num_objects)); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaStatusRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadStatusRequest(uint8_t *data, + ObjectID object_ids[], + int64_t num_objects) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + for (int64_t i = 0; i < num_objects; ++i) { + object_ids[i] = ObjectID::from_binary(message->object_ids()->Get(i)->str()); + } + return Status::OK(); +} + +Status SendStatusReply(int sock, + ObjectID object_ids[], + int object_status[], + int64_t num_objects) { + flatbuffers::FlatBufferBuilder fbb; + auto message = + CreatePlasmaStatusReply(fbb, to_flatbuffer(fbb, object_ids, num_objects), + fbb.CreateVector(object_status, num_objects)); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaStatusReply, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +int64_t ReadStatusReply_num_objects(uint8_t *data) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + return message->object_ids()->size(); +} + +Status ReadStatusReply(uint8_t *data, + ObjectID object_ids[], + int object_status[], + int64_t num_objects) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + for (int64_t i = 0; i < num_objects; ++i) { + object_ids[i] = ObjectID::from_binary(message->object_ids()->Get(i)->str()); + } + for (int64_t i = 0; i < num_objects; ++i) { + object_status[i] = message->status()->data()[i]; + } + return Status::OK(); +} + +/* Contains messages. */ + +Status SendContainsRequest(int sock, ObjectID object_id) { + flatbuffers::FlatBufferBuilder fbb; + auto message = + CreatePlasmaContainsRequest(fbb, fbb.CreateString(object_id.binary())); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaContainsRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadContainsRequest(uint8_t *data, ObjectID *object_id) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *object_id = ObjectID::from_binary(message->object_id()->str()); + return Status::OK(); +} + +Status SendContainsReply(int sock, ObjectID object_id, int has_object) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaContainsReply( + fbb, fbb.CreateString(object_id.binary()), has_object); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaContainsReply, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadContainsReply(uint8_t *data, ObjectID *object_id, int *has_object) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *object_id = ObjectID::from_binary(message->object_id()->str()); + *has_object = message->has_object(); + return Status::OK(); +} + +/* Connect messages. */ + +Status SendConnectRequest(int sock) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaConnectRequest(fbb); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaConnectRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadConnectRequest(uint8_t *data) { + return Status::OK(); +} + +Status SendConnectReply(int sock, int64_t memory_capacity) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaConnectReply(fbb, memory_capacity); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaConnectReply, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadConnectReply(uint8_t *data, int64_t *memory_capacity) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *memory_capacity = message->memory_capacity(); + return Status::OK(); +} + +/* Evict messages. */ + +Status SendEvictRequest(int sock, int64_t num_bytes) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaEvictRequest(fbb, num_bytes); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaEvictRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadEvictRequest(uint8_t *data, int64_t *num_bytes) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *num_bytes = message->num_bytes(); + return Status::OK(); +} + +Status SendEvictReply(int sock, int64_t num_bytes) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaEvictReply(fbb, num_bytes); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaEvictReply, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadEvictReply(uint8_t *data, int64_t &num_bytes) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + num_bytes = message->num_bytes(); + return Status::OK(); +} + +/* Get messages. */ + +Status SendGetRequest(int sock, + ObjectID object_ids[], + int64_t num_objects, + int64_t timeout_ms) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaGetRequest( + fbb, to_flatbuffer(fbb, object_ids, num_objects), timeout_ms); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaGetRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadGetRequest(uint8_t *data, + std::vector &object_ids, + int64_t *timeout_ms) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + for (int64_t i = 0; i < message->object_ids()->size(); ++i) { + auto object_id = message->object_ids()->Get(i)->str(); + object_ids.push_back(ObjectID::from_binary(object_id)); + } + *timeout_ms = message->timeout_ms(); + return Status::OK(); +} + +Status SendGetReply( + int sock, + ObjectID object_ids[], + std::unordered_map &plasma_objects, + int64_t num_objects) { + flatbuffers::FlatBufferBuilder fbb; + std::vector objects; + + for (int i = 0; i < num_objects; ++i) { + const PlasmaObject &object = plasma_objects[object_ids[i]]; + objects.push_back(PlasmaObjectSpec( + object.handle.store_fd, object.handle.mmap_size, object.data_offset, + object.data_size, object.metadata_offset, object.metadata_size)); + } + auto message = CreatePlasmaGetReply( + fbb, to_flatbuffer(fbb, object_ids, num_objects), + fbb.CreateVectorOfStructs(objects.data(), num_objects)); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaGetReply, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadGetReply(uint8_t *data, + ObjectID object_ids[], + PlasmaObject plasma_objects[], + int64_t num_objects) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + for (int64_t i = 0; i < num_objects; ++i) { + object_ids[i] = ObjectID::from_binary(message->object_ids()->Get(i)->str()); + } + for (int64_t i = 0; i < num_objects; ++i) { + const PlasmaObjectSpec *object = message->plasma_objects()->Get(i); + plasma_objects[i].handle.store_fd = object->segment_index(); + plasma_objects[i].handle.mmap_size = object->mmap_size(); + plasma_objects[i].data_offset = object->data_offset(); + plasma_objects[i].data_size = object->data_size(); + plasma_objects[i].metadata_offset = object->metadata_offset(); + plasma_objects[i].metadata_size = object->metadata_size(); + } + return Status::OK(); +} + +/* Fetch messages. */ + +Status SendFetchRequest(int sock, ObjectID object_ids[], int64_t num_objects) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaFetchRequest( + fbb, to_flatbuffer(fbb, object_ids, num_objects)); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaFetchRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadFetchRequest(uint8_t *data, std::vector &object_ids) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + for (int64_t i = 0; i < message->object_ids()->size(); ++i) { + object_ids.push_back( + ObjectID::from_binary(message->object_ids()->Get(i)->str())); + } + return Status::OK(); +} + +/* Wait messages. */ + +Status SendWaitRequest(int sock, + ObjectRequest object_requests[], + int num_requests, + int num_ready_objects, + int64_t timeout_ms) { + flatbuffers::FlatBufferBuilder fbb; + + std::vector> object_request_specs; + for (int i = 0; i < num_requests; i++) { + object_request_specs.push_back(CreateObjectRequestSpec( + fbb, fbb.CreateString(object_requests[i].object_id.binary()), + object_requests[i].type)); + } + + auto message = + CreatePlasmaWaitRequest(fbb, fbb.CreateVector(object_request_specs), + num_ready_objects, timeout_ms); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaWaitRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadWaitRequest(uint8_t *data, + ObjectRequestMap &object_requests, + int64_t *timeout_ms, + int *num_ready_objects) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *num_ready_objects = message->num_ready_objects(); + *timeout_ms = message->timeout(); + + for (int i = 0; i < message->object_requests()->size(); i++) { + ObjectID object_id = ObjectID::from_binary( + message->object_requests()->Get(i)->object_id()->str()); + ObjectRequest object_request({object_id, + message->object_requests()->Get(i)->type(), + ObjectStatus_Nonexistent}); + object_requests[object_id] = object_request; + } + return Status::OK(); +} + +Status SendWaitReply(int sock, + const ObjectRequestMap &object_requests, + int num_ready_objects) { + flatbuffers::FlatBufferBuilder fbb; + + std::vector> object_replies; + for (const auto &entry : object_requests) { + const auto &object_request = entry.second; + object_replies.push_back(CreateObjectReply( + fbb, fbb.CreateString(object_request.object_id.binary()), + object_request.status)); + } + + auto message = CreatePlasmaWaitReply( + fbb, fbb.CreateVector(object_replies.data(), num_ready_objects), + num_ready_objects); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaWaitReply, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadWaitReply(uint8_t *data, + ObjectRequest object_requests[], + int *num_ready_objects) { + DCHECK(data); + + auto message = flatbuffers::GetRoot(data); + *num_ready_objects = message->num_ready_objects(); + for (int i = 0; i < *num_ready_objects; i++) { + object_requests[i].object_id = ObjectID::from_binary( + message->object_requests()->Get(i)->object_id()->str()); + object_requests[i].status = message->object_requests()->Get(i)->status(); + } + return Status::OK(); +} + +/* Subscribe messages. */ + +Status SendSubscribeRequest(int sock) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaSubscribeRequest(fbb); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaSubscribeRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +/* Data messages. */ + +Status SendDataRequest(int sock, + ObjectID object_id, + const char *address, + int port) { + flatbuffers::FlatBufferBuilder fbb; + auto addr = fbb.CreateString((char *) address, strlen(address)); + auto message = CreatePlasmaDataRequest( + fbb, fbb.CreateString(object_id.binary()), addr, port); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaDataRequest, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadDataRequest(uint8_t *data, + ObjectID *object_id, + char **address, + int *port) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + DCHECK(message->object_id()->size() == sizeof(ObjectID)); + *object_id = ObjectID::from_binary(message->object_id()->str()); + *address = strdup(message->address()->c_str()); + *port = message->port(); + return Status::OK(); +} + +Status SendDataReply(int sock, + ObjectID object_id, + int64_t object_size, + int64_t metadata_size) { + flatbuffers::FlatBufferBuilder fbb; + auto message = CreatePlasmaDataReply( + fbb, fbb.CreateString(object_id.binary()), object_size, metadata_size); + fbb.Finish(message); + return WriteMessage(sock, MessageType_PlasmaDataReply, fbb.GetSize(), + fbb.GetBufferPointer()); +} + +Status ReadDataReply(uint8_t *data, + ObjectID *object_id, + int64_t *object_size, + int64_t *metadata_size) { + DCHECK(data); + auto message = flatbuffers::GetRoot(data); + *object_id = ObjectID::from_binary(message->object_id()->str()); + *object_size = (int64_t) message->object_size(); + *metadata_size = (int64_t) message->metadata_size(); + return Status::OK(); +} diff --git a/cpp/src/plasma/plasma_protocol.h b/cpp/src/plasma/plasma_protocol.h new file mode 100644 index 00000000000..3d525282b8b --- /dev/null +++ b/cpp/src/plasma/plasma_protocol.h @@ -0,0 +1,194 @@ +#ifndef PLASMA_PROTOCOL_H +#define PLASMA_PROTOCOL_H + +#include "status.h" +#include "format/plasma_generated.h" +#include "plasma.h" + +using arrow::Status; + +/* Plasma receive message. */ + +Status PlasmaReceive(int sock, + int64_t message_type, + std::vector &buffer); + +/* Plasma Create message functions. */ + +Status SendCreateRequest(int sock, + ObjectID object_id, + int64_t data_size, + int64_t metadata_size); + +Status ReadCreateRequest(uint8_t *data, + ObjectID *object_id, + int64_t *data_size, + int64_t *metadata_size); + +Status SendCreateReply(int sock, + ObjectID object_id, + PlasmaObject *object, + int error); + +Status ReadCreateReply(uint8_t *data, + ObjectID *object_id, + PlasmaObject *object); + +/* Plasma Seal message functions. */ + +Status SendSealRequest(int sock, ObjectID object_id, unsigned char *digest); + +Status ReadSealRequest(uint8_t *data, + ObjectID *object_id, + unsigned char *digest); + +Status SendSealReply(int sock, ObjectID object_id, int error); + +Status ReadSealReply(uint8_t *data, ObjectID *object_id); + +/* Plasma Get message functions. */ + +Status SendGetRequest(int sock, + ObjectID object_ids[], + int64_t num_objects, + int64_t timeout_ms); + +Status ReadGetRequest(uint8_t *data, + std::vector &object_ids, + int64_t *timeout_ms); + +Status SendGetReply( + int sock, + ObjectID object_ids[], + std::unordered_map &plasma_objects, + int64_t num_objects); + +Status ReadGetReply(uint8_t *data, + ObjectID object_ids[], + PlasmaObject plasma_objects[], + int64_t num_objects); + +/* Plasma Release message functions. */ + +Status SendReleaseRequest(int sock, ObjectID object_id); + +Status ReadReleaseRequest(uint8_t *data, ObjectID *object_id); + +Status SendReleaseReply(int sock, ObjectID object_id, int error); + +Status ReadReleaseReply(uint8_t *data, ObjectID *object_id); + +/* Plasma Delete message functions. */ + +Status SendDeleteRequest(int sock, ObjectID object_id); + +Status ReadDeleteRequest(uint8_t *data, ObjectID *object_id); + +Status SendDeleteReply(int sock, ObjectID object_id, int error); + +Status ReadDeleteReply(uint8_t *data, ObjectID *object_id); + +/* Satus messages. */ + +Status SendStatusRequest(int sock, ObjectID object_ids[], int64_t num_objects); + +Status ReadStatusRequest(uint8_t *data, + ObjectID object_ids[], + int64_t num_objects); + +Status SendStatusReply(int sock, + ObjectID object_ids[], + int object_status[], + int64_t num_objects); + +int64_t ReadStatusReply_num_objects(uint8_t *data); + +Status ReadStatusReply(uint8_t *data, + ObjectID object_ids[], + int object_status[], + int64_t num_objects); + +/* Plasma Constains message functions. */ + +Status SendContainsRequest(int sock, ObjectID object_id); + +Status ReadContainsRequest(uint8_t *data, ObjectID *object_id); + +Status SendContainsReply(int sock, ObjectID object_id, int has_object); + +Status ReadContainsReply(uint8_t *data, ObjectID *object_id, int *has_object); + +/* Plasma Connect message functions. */ + +Status SendConnectRequest(int sock); + +Status ReadConnectRequest(uint8_t *data); + +Status SendConnectReply(int sock, int64_t memory_capacity); + +Status ReadConnectReply(uint8_t *data, int64_t *memory_capacity); + +/* Plasma Evict message functions (no reply so far). */ + +Status SendEvictRequest(int sock, int64_t num_bytes); + +Status ReadEvictRequest(uint8_t *data, int64_t *num_bytes); + +Status SendEvictReply(int sock, int64_t num_bytes); + +Status ReadEvictReply(uint8_t *data, int64_t &num_bytes); + +/* Plasma Fetch Remote message functions. */ + +Status SendFetchRequest(int sock, ObjectID object_ids[], int64_t num_objects); + +Status ReadFetchRequest(uint8_t *data, std::vector &object_ids); + +/* Plasma Wait message functions. */ + +Status SendWaitRequest(int sock, + ObjectRequest object_requests[], + int num_requests, + int num_ready_objects, + int64_t timeout_ms); + +Status ReadWaitRequest(uint8_t *data, + ObjectRequestMap &object_requests, + int64_t *timeout_ms, + int *num_ready_objects); + +Status SendWaitReply(int sock, + const ObjectRequestMap &object_requests, + int num_ready_objects); + +Status ReadWaitReply(uint8_t *data, + ObjectRequest object_requests[], + int *num_ready_objects); + +/* Plasma Subscribe message functions. */ + +Status SendSubscribeRequest(int sock); + +/* Data messages. */ + +Status SendDataRequest(int sock, + ObjectID object_id, + const char *address, + int port); + +Status ReadDataRequest(uint8_t *data, + ObjectID *object_id, + char **address, + int *port); + +Status SendDataReply(int sock, + ObjectID object_id, + int64_t object_size, + int64_t metadata_size); + +Status ReadDataReply(uint8_t *data, + ObjectID *object_id, + int64_t *object_size, + int64_t *metadata_size); + +#endif /* PLASMA_PROTOCOL */ diff --git a/cpp/src/plasma/plasma_store.cc b/cpp/src/plasma/plasma_store.cc new file mode 100644 index 00000000000..9fa4ea44634 --- /dev/null +++ b/cpp/src/plasma/plasma_store.cc @@ -0,0 +1,689 @@ +// PLASMA STORE: This is a simple object store server process +// +// It accepts incoming client connections on a unix domain socket +// (name passed in via the -s option of the executable) and uses a +// single thread to serve the clients. Each client establishes a +// connection and can create objects, wait for objects and seal +// objects through that connection. +// +// It keeps a hash table that maps object_ids (which are 20 byte long, +// just enough to store and SHA1 hash) to memory mapped files. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "plasma_common.h" +#include "plasma_store.h" +#include "format/common_generated.h" +#include "plasma_io.h" +#include "malloc.h" + +extern "C" { +#include "fling.h" +void *dlmalloc(size_t); +void *dlmemalign(size_t alignment, size_t bytes); +void dlfree(void *); +size_t dlmalloc_set_footprint_limit(size_t bytes); +} + +struct GetRequest { + GetRequest(Client *client, const std::vector &object_ids); + + /// The client that called get. + Client *client; + /// The ID of the timer that will time out and cause this wait to return to + /// the client if it hasn't already returned. + int64_t timer; + /// The object IDs involved in this request. This is used in the reply. + std::vector object_ids; + /// The object information for the objects in this request. This is used in + /// the reply. + std::unordered_map objects; + /// The minimum number of objects to wait for in this request. + int64_t num_objects_to_wait_for; + /// The number of object requests in this wait request that are already + /// satisfied. + int64_t num_satisfied; +}; + +GetRequest::GetRequest(Client *client, const std::vector &object_ids) + : client(client), + timer(-1), + object_ids(object_ids.begin(), object_ids.end()), + objects(object_ids.size()), + num_satisfied(0) { + std::unordered_set unique_ids(object_ids.begin(), + object_ids.end()); + num_objects_to_wait_for = unique_ids.size(); +} + +Client::Client(int fd) : fd(fd) {} + +PlasmaStore::PlasmaStore(EventLoop *loop, int64_t system_memory) + : loop_(loop), eviction_policy_(&store_info_) { + store_info_.memory_capacity = system_memory; +} + +PlasmaStore::~PlasmaStore() { + for (const auto &element : pending_notifications_) { + auto object_notifications = element.second.object_notifications; + for (int i = 0; i < object_notifications.size(); ++i) { + uint8_t *notification = (uint8_t *) object_notifications.at(i); + uint8_t *data = notification; + free(data); + } + } +} + +// If this client is not already using the object, add the client to the +// object's list of clients, otherwise do nothing. +void PlasmaStore::add_client_to_object_clients(ObjectTableEntry *entry, + Client *client) { + // Check if this client is already using the object. + if (entry->clients.find(client) != entry->clients.end()) { + return; + } + // If there are no other clients using this object, notify the eviction policy + // that the object is being used. + if (entry->clients.size() == 0) { + // Tell the eviction policy that this object is being used. + std::vector objects_to_evict; + eviction_policy_.begin_object_access(entry->object_id, objects_to_evict); + delete_objects(objects_to_evict); + } + // Add the client pointer to the list of clients using this object. + entry->clients.insert(client); +} + +// Create a new object buffer in the hash table. +int PlasmaStore::create_object(ObjectID object_id, + int64_t data_size, + int64_t metadata_size, + Client *client, + PlasmaObject *result) { + ARROW_LOG(DEBUG) << "creating object " << object_id.hex(); + if (store_info_.objects.count(object_id) != 0) { + // There is already an object with the same ID in the Plasma Store, so + // ignore this requst. + return PlasmaError_ObjectExists; + } + // Try to evict objects until there is enough space. + uint8_t *pointer; + do { + // Allocate space for the new object. We use dlmemalign instead of dlmalloc + // in order to align the allocated region to a 64-byte boundary. This is not + // strictly necessary, but it is an optimization that could speed up the + // computation of a hash of the data (see compute_object_hash_parallel in + // plasma_client.cc). Note that even though this pointer is 64-byte aligned, + // it is not guaranteed that the corresponding pointer in the client will be + // 64-byte aligned, but in practice it often will be. + pointer = (uint8_t *) dlmemalign(BLOCK_SIZE, data_size + metadata_size); + if (pointer == NULL) { + // Tell the eviction policy how much space we need to create this object. + std::vector objects_to_evict; + bool success = eviction_policy_.require_space(data_size + metadata_size, + objects_to_evict); + delete_objects(objects_to_evict); + // Return an error to the client if not enough space could be freed to + // create the object. + if (!success) { + return PlasmaError_OutOfMemory; + } + } + } while (pointer == NULL); + int fd; + int64_t map_size; + ptrdiff_t offset; + get_malloc_mapinfo(pointer, &fd, &map_size, &offset); + assert(fd != -1); + + auto entry = std::unique_ptr(new ObjectTableEntry()); + entry->object_id = object_id; + entry->info.object_id = object_id.binary(); + entry->info.data_size = data_size; + entry->info.metadata_size = metadata_size; + entry->pointer = pointer; + // TODO(pcm): Set the other fields. + entry->fd = fd; + entry->map_size = map_size; + entry->offset = offset; + entry->state = PLASMA_CREATED; + + store_info_.objects[object_id] = std::move(entry); + result->handle.store_fd = fd; + result->handle.mmap_size = map_size; + result->data_offset = offset; + result->metadata_offset = offset + data_size; + result->data_size = data_size; + result->metadata_size = metadata_size; + // Notify the eviction policy that this object was created. This must be done + // immediately before the call to add_client_to_object_clients so that the + // eviction policy does not have an opportunity to evict the object. + eviction_policy_.object_created(object_id); + // Record that this client is using this object. + add_client_to_object_clients(store_info_.objects[object_id].get(), client); + return PlasmaError_OK; +} + +void PlasmaObject_init(PlasmaObject *object, ObjectTableEntry *entry) { + DCHECK(object != NULL); + DCHECK(entry != NULL); + DCHECK(entry->state == PLASMA_SEALED); + object->handle.store_fd = entry->fd; + object->handle.mmap_size = entry->map_size; + object->data_offset = entry->offset; + object->metadata_offset = entry->offset + entry->info.data_size; + object->data_size = entry->info.data_size; + object->metadata_size = entry->info.metadata_size; +} + +void PlasmaStore::return_from_get(GetRequest *get_req) { + // Send the get reply to the client. + Status s = SendGetReply(get_req->client->fd, &get_req->object_ids[0], + get_req->objects, get_req->object_ids.size()); + warn_if_sigpipe(s.ok() ? 0 : -1, get_req->client->fd); + // If we successfully sent the get reply message to the client, then also send + // the file descriptors. + if (s.ok()) { + // Send all of the file descriptors for the present objects. + for (const auto &object_id : get_req->object_ids) { + PlasmaObject &object = get_req->objects[object_id]; + // We use the data size to indicate whether the object is present or not. + if (object.data_size != -1) { + int error_code = send_fd(get_req->client->fd, object.handle.store_fd); + // If we failed to send the file descriptor, loop until we have sent it + // successfully. TODO(rkn): This is problematic for two reasons. First + // of all, sending the file descriptor should just succeed without any + // errors, but sometimes I see a "Message too long" error number. + // Second, looping like this allows a client to potentially block the + // plasma store event loop which should never happen. + while (error_code < 0) { + if (errno == EMSGSIZE) { + ARROW_LOG(WARNING) << "Failed to send file descriptor, retrying."; + error_code = send_fd(get_req->client->fd, object.handle.store_fd); + continue; + } + warn_if_sigpipe(error_code, get_req->client->fd); + break; + } + } + } + } + + // Remove the get request from each of the relevant object_get_requests hash + // tables if it is present there. It should only be present there if the get + // request timed out. + for (ObjectID &object_id : get_req->object_ids) { + auto &get_requests = object_get_requests_[object_id]; + // Erase get_req from the vector. + auto it = std::find(get_requests.begin(), get_requests.end(), get_req); + if (it != get_requests.end()) { + get_requests.erase(it); + } + } + // Remove the get request. + if (get_req->timer != -1) { + ARROW_CHECK(loop_->remove_timer(get_req->timer) == AE_OK); + } + delete get_req; +} + +void PlasmaStore::update_object_get_requests(ObjectID object_id) { + std::vector &get_requests = object_get_requests_[object_id]; + int index = 0; + int num_requests = get_requests.size(); + for (int i = 0; i < num_requests; ++i) { + GetRequest *get_req = get_requests[index]; + auto entry = get_object_table_entry(&store_info_, object_id); + ARROW_CHECK(entry != NULL); + + PlasmaObject_init(&get_req->objects[object_id], entry); + get_req->num_satisfied += 1; + // Record the fact that this client will be using this object and will + // be responsible for releasing this object. + add_client_to_object_clients(entry, get_req->client); + + // If this get request is done, reply to the client. + if (get_req->num_satisfied == get_req->num_objects_to_wait_for) { + return_from_get(get_req); + } else { + // The call to return_from_get will remove the current element in the + // array, so we only increment the counter in the else branch. + index += 1; + } + } + + DCHECK(index == get_requests.size()); + // Remove the array of get requests for this object, since no one should be + // waiting for this object anymore. + object_get_requests_.erase(object_id); +} + +void PlasmaStore::process_get_request(Client *client, + const std::vector &object_ids, + uint64_t timeout_ms) { + // Create a get request for this object. + GetRequest *get_req = new GetRequest(client, object_ids); + + for (auto object_id : object_ids) { + // Check if this object is already present locally. If so, record that the + // object is being used and mark it as accounted for. + auto entry = get_object_table_entry(&store_info_, object_id); + if (entry && entry->state == PLASMA_SEALED) { + // Update the get request to take into account the present object. + PlasmaObject_init(&get_req->objects[object_id], entry); + get_req->num_satisfied += 1; + // If necessary, record that this client is using this object. In the case + // where entry == NULL, this will be called from seal_object. + add_client_to_object_clients(entry, client); + } else { + // Add a placeholder plasma object to the get request to indicate that the + // object is not present. This will be parsed by the client. We set the + // data size to -1 to indicate that the object is not present. + get_req->objects[object_id].data_size = -1; + // Add the get request to the relevant data structures. + object_get_requests_[object_id].push_back(get_req); + } + } + + // If all of the objects are present already or if the timeout is 0, return to + // the client. + if (get_req->num_satisfied == get_req->num_objects_to_wait_for || + timeout_ms == 0) { + return_from_get(get_req); + } else if (timeout_ms != -1) { + // Set a timer that will cause the get request to return to the client. Note + // that a timeout of -1 is used to indicate that no timer should be set. + get_req->timer = + loop_->add_timer(timeout_ms, [this, get_req](int64_t timer_id) { + return_from_get(get_req); + return kEventLoopTimerDone; + }); + } +} + +int PlasmaStore::remove_client_from_object_clients(ObjectTableEntry *entry, + Client *client) { + auto it = entry->clients.find(client); + if (it != entry->clients.end()) { + entry->clients.erase(it); + // If no more clients are using this object, notify the eviction policy + // that the object is no longer being used. + if (entry->clients.size() == 0) { + // Tell the eviction policy that this object is no longer being used. + std::vector objects_to_evict; + eviction_policy_.end_object_access(entry->object_id, objects_to_evict); + delete_objects(objects_to_evict); + } + // Return 1 to indicate that the client was removed. + return 1; + } else { + // Return 0 to indicate that the client was not removed. + return 0; + } +} + +void PlasmaStore::release_object(ObjectID object_id, Client *client) { + auto entry = get_object_table_entry(&store_info_, object_id); + ARROW_CHECK(entry != NULL); + // Remove the client from the object's array of clients. + ARROW_CHECK(remove_client_from_object_clients(entry, client) == 1); +} + +// Check if an object is present. +int PlasmaStore::contains_object(ObjectID object_id) { + auto entry = get_object_table_entry(&store_info_, object_id); + return entry && (entry->state == PLASMA_SEALED) ? OBJECT_FOUND + : OBJECT_NOT_FOUND; +} + +// Seal an object that has been created in the hash table. +void PlasmaStore::seal_object(ObjectID object_id, unsigned char digest[]) { + ARROW_LOG(DEBUG) << "sealing object " << object_id.hex(); + auto entry = get_object_table_entry(&store_info_, object_id); + ARROW_CHECK(entry != NULL); + ARROW_CHECK(entry->state == PLASMA_CREATED); + // Set the state of object to SEALED. + entry->state = PLASMA_SEALED; + // Set the object digest. + entry->info.digest = std::string((char *) &digest[0], kDigestSize); + // Inform all subscribers that a new object has been sealed. + push_notification(&entry->info); + + // Update all get requests that involve this object. + update_object_get_requests(object_id); +} + +void PlasmaStore::delete_objects(const std::vector &object_ids) { + for (const auto &object_id : object_ids) { + ARROW_LOG(DEBUG) << "deleting object " << object_id.hex(); + auto entry = get_object_table_entry(&store_info_, object_id); + // TODO(rkn): This should probably not fail, but should instead throw an + // error. Maybe we should also support deleting objects that have been + // created but not sealed. + ARROW_CHECK(entry != NULL) + << "To delete an object it must be in the object table."; + ARROW_CHECK(entry->state == PLASMA_SEALED) + << "To delete an object it must have been sealed."; + ARROW_CHECK(entry->clients.size() == 0) + << "To delete an object, there must be no clients currently using it."; + dlfree(entry->pointer); + store_info_.objects.erase(object_id); + // Inform all subscribers that the object has been deleted. + ObjectInfoT notification; + notification.object_id = object_id.binary(); + notification.is_deletion = true; + push_notification(¬ification); + } +} + +void PlasmaStore::connect_client(int listener_sock) { + int client_fd = AcceptClient(listener_sock); + // This is freed in disconnect_client. + Client *client = new Client(client_fd); + // Add a callback to handle events on this socket. + // TODO(pcm): Check return value. + loop_->add_file_event(client_fd, kEventLoopRead, [this, client](int events) { + process_message(client); + }); + ARROW_LOG(DEBUG) << "New connection with fd " << client_fd; +} + +void PlasmaStore::disconnect_client(Client *client) { + ARROW_CHECK(client != NULL); + ARROW_CHECK(client->fd > 0); + loop_->remove_file_event(client->fd); + // Close the socket. + close(client->fd); + ARROW_LOG(INFO) << "Disconnecting client on fd " << client->fd; + // If this client was using any objects, remove it from the appropriate + // lists. + for (const auto &entry : store_info_.objects) { + remove_client_from_object_clients(entry.second.get(), client); + } + // Note, the store may still attempt to send a message to the disconnected + // client (for example, when an object ID that the client was waiting for + // is ready). In these cases, the attempt to send the message will fail, but + // the store should just ignore the failure. + delete client; +} + +/// Send notifications about sealed objects to the subscribers. This is called +/// in seal_object. If the socket's send buffer is full, the notification will +/// be +/// buffered, and this will be called again when the send buffer has room. +/// +/// @param client The client to send the notification to. +/// @return Void. +void PlasmaStore::send_notifications(int client_fd) { + auto it = pending_notifications_.find(client_fd); + + int num_processed = 0; + bool closed = false; + // Loop over the array of pending notifications and send as many of them as + // possible. + for (int i = 0; i < it->second.object_notifications.size(); ++i) { + uint8_t *notification = (uint8_t *) it->second.object_notifications.at(i); + // Decode the length, which is the first bytes of the message. + int64_t size = *((int64_t *) notification); + + // Attempt to send a notification about this object ID. + int nbytes = send(client_fd, notification, sizeof(int64_t) + size, 0); + if (nbytes >= 0) { + ARROW_CHECK(nbytes == sizeof(int64_t) + size); + } else if (nbytes == -1 && + (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) { + ARROW_LOG(DEBUG) + << "The socket's send buffer is full, so we are caching this " + "notification and will send it later."; + // Add a callback to the event loop to send queued notifications whenever + // there is room in the socket's send buffer. Callbacks can be added + // more than once here and will be overwritten. The callback is removed + // at the end of the method. + // TODO(pcm): Introduce status codes and check in case the file descriptor + // is added twice. + loop_->add_file_event( + client_fd, kEventLoopWrite, + [this, client_fd](int events) { send_notifications(client_fd); }); + break; + } else { + ARROW_LOG(WARNING) << "Failed to send notification to client on fd " + << client_fd; + if (errno == EPIPE) { + closed = true; + break; + } + } + num_processed += 1; + // The corresponding malloc happened in create_object_info_buffer + // within push_notification. + free(notification); + } + // Remove the sent notifications from the array. + it->second.object_notifications.erase( + it->second.object_notifications.begin(), + it->second.object_notifications.begin() + num_processed); + + // Stop sending notifications if the pipe was broken. + if (closed) { + close(client_fd); + pending_notifications_.erase(client_fd); + } + + // If we have sent all notifications, remove the fd from the event loop. + if (it->second.object_notifications.empty()) { + loop_->remove_file_event(client_fd); + } +} + +void PlasmaStore::push_notification(ObjectInfoT *object_info) { + for (auto &element : pending_notifications_) { + uint8_t *notification = create_object_info_buffer(object_info); + element.second.object_notifications.push_back(notification); + send_notifications(element.first); + // The notification gets freed in send_notifications when the notification + // is sent over the socket. + } +} + +// Subscribe to notifications about sealed objects. +void PlasmaStore::subscribe_to_updates(Client *client) { + ARROW_LOG(DEBUG) << "subscribing to updates on fd " << client->fd; + // TODO(rkn): The store could block here if the client doesn't send a file + // descriptor. + int fd = recv_fd(client->fd); + if (fd < 0) { + // This may mean that the client died before sending the file descriptor. + ARROW_LOG(WARNING) << "Failed to receive file descriptor from client on fd " + << client->fd << "."; + return; + } + + // Create a new array to buffer notifications that can't be sent to the + // subscriber yet because the socket send buffer is full. TODO(rkn): the queue + // never gets freed. + NotificationQueue &queue = pending_notifications_[fd]; + + // Push notifications to the new subscriber about existing objects. + for (const auto &entry : store_info_.objects) { + push_notification(&entry.second->info); + } + send_notifications(fd); +} + +Status PlasmaStore::process_message(Client *client) { + int64_t type; + Status s = ReadMessage(client->fd, &type, input_buffer_); + ARROW_CHECK(s.ok() || s.IsIOError()); + + uint8_t *input = input_buffer_.data(); + ObjectID object_id; + PlasmaObject object; + // TODO(pcm): Get rid of the following. + memset(&object, 0, sizeof(object)); + + // Process the different types of requests. + switch (type) { + case MessageType_PlasmaCreateRequest: { + int64_t data_size; + int64_t metadata_size; + RETURN_NOT_OK( + ReadCreateRequest(input, &object_id, &data_size, &metadata_size)); + int error_code = + create_object(object_id, data_size, metadata_size, client, &object); + HANDLE_SIGPIPE(SendCreateReply(client->fd, object_id, &object, error_code), + client->fd); + if (error_code == PlasmaError_OK) { + warn_if_sigpipe(send_fd(client->fd, object.handle.store_fd), client->fd); + } + } break; + case MessageType_PlasmaGetRequest: { + std::vector object_ids_to_get; + int64_t timeout_ms; + RETURN_NOT_OK(ReadGetRequest(input, object_ids_to_get, &timeout_ms)); + process_get_request(client, object_ids_to_get, timeout_ms); + } break; + case MessageType_PlasmaReleaseRequest: + RETURN_NOT_OK(ReadReleaseRequest(input, &object_id)); + release_object(object_id, client); + break; + case MessageType_PlasmaContainsRequest: + RETURN_NOT_OK(ReadContainsRequest(input, &object_id)); + if (contains_object(object_id) == OBJECT_FOUND) { + HANDLE_SIGPIPE(SendContainsReply(client->fd, object_id, 1), client->fd); + } else { + HANDLE_SIGPIPE(SendContainsReply(client->fd, object_id, 0), client->fd); + } + break; + case MessageType_PlasmaSealRequest: { + unsigned char digest[kDigestSize]; + RETURN_NOT_OK(ReadSealRequest(input, &object_id, &digest[0])); + seal_object(object_id, &digest[0]); + } break; + case MessageType_PlasmaEvictRequest: { + // This code path should only be used for testing. + int64_t num_bytes; + RETURN_NOT_OK(ReadEvictRequest(input, &num_bytes)); + std::vector objects_to_evict; + int64_t num_bytes_evicted = + eviction_policy_.choose_objects_to_evict(num_bytes, objects_to_evict); + delete_objects(objects_to_evict); + HANDLE_SIGPIPE(SendEvictReply(client->fd, num_bytes_evicted), client->fd); + } break; + case MessageType_PlasmaSubscribeRequest: + subscribe_to_updates(client); + break; + case MessageType_PlasmaConnectRequest: { + HANDLE_SIGPIPE(SendConnectReply(client->fd, store_info_.memory_capacity), + client->fd); + } break; + case DISCONNECT_CLIENT: + ARROW_LOG(DEBUG) << "Disconnecting client on fd " << client->fd; + disconnect_client(client); + break; + default: + // This code should be unreachable. + ARROW_CHECK(0); + } + return Status::OK(); +} + +// Report "success" to valgrind. +void signal_handler(int signal) { + if (signal == SIGTERM) { + exit(0); + } +} + +void start_server(char *socket_name, int64_t system_memory) { + // Ignore SIGPIPE signals. If we don't do this, then when we attempt to write + // to a client that has already died, the store could die. + signal(SIGPIPE, SIG_IGN); + // Create the event loop. + EventLoop loop; + PlasmaStore store(&loop, system_memory); + int socket = bind_ipc_sock(socket_name, true); + ARROW_CHECK(socket >= 0); + // TODO(pcm): Check return value. + loop.add_file_event(socket, kEventLoopRead, [&store, socket](int events) { + store.connect_client(socket); + }); + loop.run(); +} + +int main(int argc, char *argv[]) { + signal(SIGTERM, signal_handler); + char *socket_name = NULL; + int64_t system_memory = -1; + int c; + while ((c = getopt(argc, argv, "s:m:")) != -1) { + switch (c) { + case 's': + socket_name = optarg; + break; + case 'm': { + char extra; + int scanned = sscanf(optarg, "%" SCNd64 "%c", &system_memory, &extra); + ARROW_CHECK(scanned == 1); + ARROW_LOG(INFO) << "Allowing the Plasma store to use up to " + << ((double) system_memory) / 1000000000 + << "GB of memory."; + break; + } + default: + exit(-1); + } + } + if (!socket_name) { + ARROW_LOG(FATAL) + << "please specify socket for incoming connections with -s switch"; + } + if (system_memory == -1) { + ARROW_LOG(FATAL) + << "please specify the amount of system memory with -m switch"; + } +#ifdef __linux__ + // On Linux, check that the amount of memory available in /dev/shm is large + // enough to accommodate the request. If it isn't, then fail. + int shm_fd = open("/dev/shm", O_RDONLY); + struct statvfs shm_vfs_stats; + fstatvfs(shm_fd, &shm_vfs_stats); + // The value shm_vfs_stats.f_bsize is the block size, and the value + // shm_vfs_stats.f_bavail is the number of available blocks. + int64_t shm_mem_avail = shm_vfs_stats.f_bsize * shm_vfs_stats.f_bavail; + close(shm_fd); + if (system_memory > shm_mem_avail) { + ARROW_LOG(FATAL) + << "System memory request exceeds memory available in /dev/shm. The " + "request is for " + << system_memory << " bytes, and the amount available is " + << shm_mem_avail + << " bytes. You may be able to free up space by deleting files in " + "/dev/shm. If you are inside a Docker container, you may need to " + "pass " + "an argument with the flag '--shm-size' to 'docker run'."; + } +#endif + // Make it so dlmalloc fails if we try to request more memory than is + // available. + dlmalloc_set_footprint_limit((size_t) system_memory); + ARROW_LOG(DEBUG) << "starting server listening on " << socket_name; + start_server(socket_name, system_memory); +} diff --git a/cpp/src/plasma/plasma_store.h b/cpp/src/plasma/plasma_store.h new file mode 100644 index 00000000000..c63fb43b6fb --- /dev/null +++ b/cpp/src/plasma/plasma_store.h @@ -0,0 +1,154 @@ +#ifndef PLASMA_STORE_H +#define PLASMA_STORE_H + +#include "eviction_policy.h" +#include "plasma.h" +#include "plasma_common.h" +#include "plasma_events.h" +#include "plasma_protocol.h" + +class GetRequest; + +struct NotificationQueue { + /// The object notifications for clients. We notify the client about the + /// objects in the order that the objects were sealed or deleted. + std::deque object_notifications; +}; + +/// Contains all information that is associated with a Plasma store client. +struct Client { + Client(int fd); + + /// The file descriptor used to communicate with the client. + int fd; +}; + +class PlasmaStore { + public: + PlasmaStore(EventLoop *loop, int64_t system_memory); + + ~PlasmaStore(); + + /// Create a new object. The client must do a call to release_object to tell + /// the store when it is done with the object. + /// + /// @param object_id Object ID of the object to be created. + /// @param data_size Size in bytes of the object to be created. + /// @param metadata_size Size in bytes of the object metadata. + /// @return One of the following error codes: + /// - PlasmaError_OK, if the object was created successfully. + /// - PlasmaError_ObjectExists, if an object with this ID is already + /// present in the store. In this case, the client should not call + /// plasma_release. + /// - PlasmaError_OutOfMemory, if the store is out of memory and + /// cannot create the object. In this case, the client should not call + /// plasma_release. + int create_object(ObjectID object_id, + int64_t data_size, + int64_t metadata_size, + Client *client, + PlasmaObject *result); + + /// Delete objects that have been created in the hash table. This should only + /// be called on objects that are returned by the eviction policy to evict. + /// + /// @param object_ids Object IDs of the objects to be deleted. + /// @return Void. + void delete_objects(const std::vector &object_ids); + + /// Process a get request from a client. This method assumes that we will + /// eventually have these objects sealed. If one of the objects has not yet + /// been sealed, the client that requested the object will be notified when it + /// is sealed. + /// + /// For each object, the client must do a call to release_object to tell the + /// store when it is done with the object. + /// + /// @param client The client making this request. + /// @param object_ids Object IDs of the objects to be gotten. + /// @param timeout_ms The timeout for the get request in milliseconds. + /// @return Void. + void process_get_request(Client *client, + const std::vector &object_ids, + uint64_t timeout_ms); + + /// Seal an object. The object is now immutable and can be accessed with get. + /// + /// @param object_id Object ID of the object to be sealed. + /// @param digest The digest of the object. This is used to tell if two + /// objects + /// with the same object ID are the same. + /// @return Void. + void seal_object(ObjectID object_id, unsigned char digest[]); + + /// Check if the plasma store contains an object: + /// + /// @param object_id Object ID that will be checked. + /// @return OBJECT_FOUND if the object is in the store, OBJECT_NOT_FOUND if + /// not + int contains_object(ObjectID object_id); + + /// Record the fact that a particular client is no longer using an object. + /// + /// @param object_id The object ID of the object that is being released. + /// @param client The client making this request. + /// @param Void. + void release_object(ObjectID object_id, Client *client); + + /// Subscribe a file descriptor to updates about new sealed objects. + /// + /// @param client The client making this request. + /// @return Void. + void subscribe_to_updates(Client *client); + + /// Connect a new client to the PlasmaStore. + /// + /// @param listener_sock The socket that is listening to incoming connections. + /// @return Void. + void connect_client(int listener_sock); + + /// Disconnect a client from the PlasmaStore. + /// + /// @param client The client that is disconnected. + /// @return Void. + void disconnect_client(Client *client); + + void send_notifications(int client_fd); + + Status process_message(Client *client); + + private: + void push_notification(ObjectInfoT *object_notification); + + void add_client_to_object_clients(ObjectTableEntry *entry, Client *client); + + void return_from_get(GetRequest *get_req); + + void update_object_get_requests(ObjectID object_id); + + int remove_client_from_object_clients(ObjectTableEntry *entry, + Client *client); + + /// Event loop of the plasma store. + EventLoop *loop_; + /// The plasma store information, including the object tables, that is exposed + /// to the eviction policy. + PlasmaStoreInfo store_info_; + /// The state that is managed by the eviction policy. + EvictionPolicy eviction_policy_; + /// Input buffer. This is allocated only once to avoid mallocs for every + /// call to process_message. + std::vector input_buffer_; + /// A hash table mapping object IDs to a vector of the get requests that are + /// waiting for the object to arrive. + std::unordered_map, UniqueIDHasher> + object_get_requests_; + /// The pending notifications that have not been sent to subscribers because + /// the socket send buffers were full. This is a hash table from client file + /// descriptor to an array of object_ids to send to that client. + /// TODO(pcm): Consider putting this into the Client data structure and + /// reorganize the code slightly. + std::unordered_map pending_notifications_; +}; + +#endif // PLASMA_STORE_H diff --git a/cpp/src/plasma/status.cc b/cpp/src/plasma/status.cc new file mode 100644 index 00000000000..11082d6cd9d --- /dev/null +++ b/cpp/src/plasma/status.cc @@ -0,0 +1,90 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// A Status encapsulates the result of an operation. It may indicate success, +// or it may indicate an error with an associated error message. +// +// Multiple threads can invoke const methods on a Status without +// external synchronization, but if any of the threads may call a +// non-const method, all threads accessing the same Status must use +// external synchronization. + +#include "status.h" + +#include + +namespace arrow { + +Status::Status(StatusCode code, const std::string &msg, int16_t posix_code) { + assert(code != StatusCode::OK); + const uint32_t size = static_cast(msg.size()); + char *result = new char[size + 7]; + memcpy(result, &size, sizeof(size)); + result[4] = static_cast(code); + memcpy(result + 5, &posix_code, sizeof(posix_code)); + memcpy(result + 7, msg.c_str(), msg.size()); + state_ = result; +} + +const char *Status::CopyState(const char *state) { + uint32_t size; + memcpy(&size, state, sizeof(size)); + char *result = new char[size + 7]; + memcpy(result, state, size + 7); + return result; +} + +std::string Status::CodeAsString() const { + if (state_ == NULL) { + return "OK"; + } + + const char *type; + switch (code()) { + case StatusCode::OK: + type = "OK"; + break; + case StatusCode::OutOfMemory: + type = "Out of memory"; + break; + case StatusCode::KeyError: + type = "Key error"; + break; + case StatusCode::TypeError: + type = "Type error"; + break; + case StatusCode::Invalid: + type = "Invalid"; + break; + case StatusCode::IOError: + type = "IOError"; + break; + case StatusCode::UnknownError: + type = "Unknown error"; + break; + case StatusCode::NotImplemented: + type = "NotImplemented"; + break; + default: + type = "Unknown"; + break; + } + return std::string(type); +} + +std::string Status::ToString() const { + std::string result(CodeAsString()); + if (state_ == NULL) { + return result; + } + + result.append(": "); + + uint32_t length; + memcpy(&length, state_, sizeof(length)); + result.append(reinterpret_cast(state_ + 7), length); + return result; +} + +} // namespace arrow diff --git a/cpp/src/plasma/status.h b/cpp/src/plasma/status.h new file mode 100644 index 00000000000..30d3a1e2f82 --- /dev/null +++ b/cpp/src/plasma/status.h @@ -0,0 +1,226 @@ +// Copyright (c) 2011 The LevelDB Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. See the AUTHORS file for names of contributors. +// +// A Status encapsulates the result of an operation. It may indicate success, +// or it may indicate an error with an associated error message. +// +// Multiple threads can invoke const methods on a Status without +// external synchronization, but if any of the threads may call a +// non-const method, all threads accessing the same Status must use +// external synchronization. + +// Adapted from Kudu github.com/cloudera/kudu + +#ifndef ARROW_STATUS_H_ +#define ARROW_STATUS_H_ + +#include +#include +#include + +// Return the given status if it is not OK. +#define ARROW_RETURN_NOT_OK(s) \ + do { \ + ::arrow::Status _s = (s); \ + if (!_s.ok()) { \ + return _s; \ + } \ + } while (0); + +// Return the given status if it is not OK, but first clone it and +// prepend the given message. +#define ARROW_RETURN_NOT_OK_PREPEND(s, msg) \ + do { \ + ::arrow::Status _s = (s); \ + if (::gutil::PREDICT_FALSE(!_s.ok())) \ + return _s.CloneAndPrepend(msg); \ + } while (0); + +// Return 'to_return' if 'to_call' returns a bad status. +// The substitution for 'to_return' may reference the variable +// 's' for the bad status. +#define ARROW_RETURN_NOT_OK_RET(to_call, to_return) \ + do { \ + ::arrow::Status s = (to_call); \ + if (::gutil::PREDICT_FALSE(!s.ok())) \ + return (to_return); \ + } while (0); + +// If 'to_call' returns a bad status, CHECK immediately with a logged message +// of 'msg' followed by the status. +#define ARROW_CHECK_OK_PREPEND(to_call, msg) \ + do { \ + ::arrow::Status _s = (to_call); \ + ARROW_CHECK(_s.ok()) << (msg) << ": " << _s.ToString(); \ + } while (0); + +// If the status is bad, CHECK immediately, appending the status to the +// logged message. +#define ARROW_CHECK_OK(s) ARROW_CHECK_OK_PREPEND(s, "Bad status") + +namespace arrow { + +#define RETURN_NOT_OK(s) \ + do { \ + Status _s = (s); \ + if (!_s.ok()) { \ + return _s; \ + } \ + } while (0); + +#define RETURN_NOT_OK_ELSE(s, else_) \ + do { \ + Status _s = (s); \ + if (!_s.ok()) { \ + else_; \ + return _s; \ + } \ + } while (0); + +enum class StatusCode : char { + OK = 0, + OutOfMemory = 1, + KeyError = 2, + TypeError = 3, + Invalid = 4, + IOError = 5, + UnknownError = 9, + NotImplemented = 10, + PlasmaObjectExists = 20, + PlasmaObjectNonexistent = 21, + PlasmaStoreFull = 22 +}; + +class Status { + public: + // Create a success status. + Status() : state_(NULL) {} + ~Status() { delete[] state_; } + + Status(StatusCode code, const std::string &msg) : Status(code, msg, -1) {} + + // Copy the specified status. + Status(const Status &s); + void operator=(const Status &s); + + // Return a success status. + static Status OK() { return Status(); } + + // Return error status of an appropriate type. + static Status OutOfMemory(const std::string &msg, int16_t posix_code = -1) { + return Status(StatusCode::OutOfMemory, msg, posix_code); + } + + static Status KeyError(const std::string &msg) { + return Status(StatusCode::KeyError, msg, -1); + } + + static Status TypeError(const std::string &msg) { + return Status(StatusCode::TypeError, msg, -1); + } + + static Status UnknownError(const std::string &msg) { + return Status(StatusCode::UnknownError, msg, -1); + } + + static Status NotImplemented(const std::string &msg) { + return Status(StatusCode::NotImplemented, msg, -1); + } + + static Status Invalid(const std::string &msg) { + return Status(StatusCode::Invalid, msg, -1); + } + + static Status IOError(const std::string &msg) { + return Status(StatusCode::IOError, msg, -1); + } + + static Status PlasmaObjectExists(const std::string &msg) { + return Status(StatusCode::PlasmaObjectExists, msg, -1); + } + + static Status PlasmaObjectNonexistent(const std::string &msg) { + return Status(StatusCode::PlasmaObjectNonexistent, msg, -1); + } + + static Status PlasmaStoreFull(const std::string &msg) { + return Status(StatusCode::PlasmaStoreFull, msg, -1); + } + + // Returns true iff the status indicates success. + bool ok() const { return (state_ == NULL); } + + bool IsOutOfMemory() const { return code() == StatusCode::OutOfMemory; } + bool IsKeyError() const { return code() == StatusCode::KeyError; } + bool IsInvalid() const { return code() == StatusCode::Invalid; } + bool IsIOError() const { return code() == StatusCode::IOError; } + bool IsTypeError() const { return code() == StatusCode::TypeError; } + bool IsUnknownError() const { return code() == StatusCode::UnknownError; } + bool IsNotImplemented() const { return code() == StatusCode::NotImplemented; } + // An object with this object ID already exists in the plasma store. + bool IsPlasmaObjectExists() const { + return code() == StatusCode::PlasmaObjectExists; + } + // An object was requested that doesn't exist in the plasma store. + bool IsPlasmaObjectNonexistent() const { + return code() == StatusCode::PlasmaObjectNonexistent; + } + // An object is too large to fit into the plasma store. + bool IsPlasmaStoreFull() const { + return code() == StatusCode::PlasmaStoreFull; + } + + // Return a string representation of this status suitable for printing. + // Returns the string "OK" for success. + std::string ToString() const; + + // Return a string representation of the status code, without the message + // text or posix code information. + std::string CodeAsString() const; + + // Get the POSIX code associated with this Status, or -1 if there is none. + int16_t posix_code() const; + + StatusCode code() const { + return ((state_ == NULL) ? StatusCode::OK + : static_cast(state_[4])); + } + + std::string message() const { + uint32_t length; + memcpy(&length, state_, sizeof(length)); + std::string msg; + msg.append((state_ + 7), length); + return msg; + } + + private: + // OK status has a NULL state_. Otherwise, state_ is a new[] array + // of the following form: + // state_[0..3] == length of message + // state_[4] == code + // state_[5..6] == posix_code + // state_[7..] == message + const char *state_; + + Status(StatusCode code, const std::string &msg, int16_t posix_code); + static const char *CopyState(const char *s); +}; + +inline Status::Status(const Status &s) { + state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_); +} + +inline void Status::operator=(const Status &s) { + // The following condition catches both aliasing (when this == &s), + // and the common case where both s and *this are ok. + if (state_ != s.state_) { + delete[] state_; + state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_); + } +} + +} // namespace arrow + +#endif // ARROW_STATUS_H_ diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc new file mode 100644 index 00000000000..f255734cb96 --- /dev/null +++ b/cpp/src/plasma/test/client_tests.cc @@ -0,0 +1,331 @@ +#include "greatest.h" + +#include +#include +#include + +#include "plasma_common.h" +#include "plasma.h" +#include "plasma_protocol.h" +#include "plasma_client.h" + +SUITE(plasma_client_tests); + +TEST plasma_status_tests(void) { + PlasmaClient client1; + ARROW_CHECK_OK(client1.Connect("/tmp/store1", "/tmp/manager1", + PLASMA_DEFAULT_RELEASE_DELAY)); + PlasmaClient client2; + ARROW_CHECK_OK(client2.Connect("/tmp/store2", "/tmp/manager2", + PLASMA_DEFAULT_RELEASE_DELAY)); + ObjectID oid1 = ObjectID::from_random(); + + /* Test for object non-existence. */ + int status; + ARROW_CHECK_OK(client1.Info(oid1, &status)); + ASSERT(status == ObjectStatus_Nonexistent); + + /* Test for the object being in local Plasma store. */ + /* First create object. */ + int64_t data_size = 100; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + uint8_t *data; + ARROW_CHECK_OK( + client1.Create(oid1, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client1.Seal(oid1)); + /* Sleep to avoid race condition of Plasma Manager waiting for notification. + */ + sleep(1); + ARROW_CHECK_OK(client1.Info(oid1, &status)); + ASSERT(status == ObjectStatus_Local); + + /* Test for object being remote. */ + ARROW_CHECK_OK(client2.Info(oid1, &status)); + ASSERT(status == ObjectStatus_Remote); + + ARROW_CHECK_OK(client1.Disconnect()); + ARROW_CHECK_OK(client2.Disconnect()); + + PASS(); +} + +TEST plasma_fetch_tests(void) { + PlasmaClient client1; + ARROW_CHECK_OK(client1.Connect("/tmp/store1", "/tmp/manager1", + PLASMA_DEFAULT_RELEASE_DELAY)); + PlasmaClient client2; + ARROW_CHECK_OK(client2.Connect("/tmp/store2", "/tmp/manager2", + PLASMA_DEFAULT_RELEASE_DELAY)); + ObjectID oid1 = ObjectID::from_random(); + + /* Test for object non-existence. */ + int status; + + /* No object in the system */ + ARROW_CHECK_OK(client1.Info(oid1, &status)); + ASSERT(status == ObjectStatus_Nonexistent); + + /* Test for the object being in local Plasma store. */ + /* First create object. */ + int64_t data_size = 100; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + uint8_t *data; + ARROW_CHECK_OK( + client1.Create(oid1, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client1.Seal(oid1)); + + /* Object with ID oid1 has been just inserted. On the next fetch we might + * either find the object or not, depending on whether the Plasma Manager has + * received the notification from the Plasma Store or not. */ + ObjectID oid_array1[1] = {oid1}; + ARROW_CHECK_OK(client1.Fetch(1, oid_array1)); + ARROW_CHECK_OK(client1.Info(oid1, &status)); + ASSERT((status == ObjectStatus_Local) || + (status == ObjectStatus_Nonexistent)); + + /* Sleep to make sure Plasma Manager got the notification. */ + sleep(1); + ARROW_CHECK_OK(client1.Info(oid1, &status)); + ASSERT(status == ObjectStatus_Local); + + /* Test for object being remote. */ + ARROW_CHECK_OK(client2.Info(oid1, &status)); + ASSERT(status == ObjectStatus_Remote); + + /* Sleep to make sure the object has been fetched and it is now stored in the + * local Plasma Store. */ + ARROW_CHECK_OK(client2.Fetch(1, oid_array1)); + sleep(1); + ARROW_CHECK_OK(client2.Info(oid1, &status)); + ASSERT(status == ObjectStatus_Local); + + sleep(1); + ARROW_CHECK_OK(client1.Disconnect()); + ARROW_CHECK_OK(client2.Disconnect()); + + PASS(); +} + +void init_data_123(uint8_t *data, uint64_t size, uint8_t base) { + for (int i = 0; i < size; i++) { + data[i] = base + i; + } +} + +bool is_equal_data_123(uint8_t *data1, uint8_t *data2, uint64_t size) { + for (int i = 0; i < size; i++) { + if (data1[i] != data2[i]) { + return false; + }; + } + return true; +} + +TEST plasma_nonblocking_get_tests(void) { + PlasmaClient client; + ARROW_CHECK_OK(client.Connect("/tmp/store1", "/tmp/manager1", + PLASMA_DEFAULT_RELEASE_DELAY)); + ObjectID oid = ObjectID::from_random(); + ObjectID oid_array[1] = {oid}; + ObjectBuffer obj_buffer; + + /* Test for object non-existence. */ + ARROW_CHECK_OK(client.Get(oid_array, 1, 0, &obj_buffer)); + ASSERT(obj_buffer.data_size == -1); + + /* Test for the object being in local Plasma store. */ + /* First create object. */ + int64_t data_size = 4; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + uint8_t *data; + ARROW_CHECK_OK(client.Create(oid, data_size, metadata, metadata_size, &data)); + init_data_123(data, data_size, 0); + ARROW_CHECK_OK(client.Seal(oid)); + + sleep(1); + ARROW_CHECK_OK(client.Get(oid_array, 1, 0, &obj_buffer)); + ASSERT(is_equal_data_123(data, obj_buffer.data, data_size) == true); + + sleep(1); + ARROW_CHECK_OK(client.Disconnect()); + + PASS(); +} + +TEST plasma_wait_for_objects_tests(void) { + PlasmaClient client1; + ARROW_CHECK_OK(client1.Connect("/tmp/store1", "/tmp/manager1", + PLASMA_DEFAULT_RELEASE_DELAY)); + PlasmaClient client2; + ARROW_CHECK_OK(client2.Connect("/tmp/store2", "/tmp/manager2", + PLASMA_DEFAULT_RELEASE_DELAY)); + ObjectID oid1 = ObjectID::from_random(); + ObjectID oid2 = ObjectID::from_random(); +#define NUM_OBJ_REQUEST 2 +#define WAIT_TIMEOUT_MS 1000 + ObjectRequest obj_requests[NUM_OBJ_REQUEST]; + + obj_requests[0].object_id = oid1; + obj_requests[0].type = PLASMA_QUERY_ANYWHERE; + obj_requests[1].object_id = oid2; + obj_requests[1].type = PLASMA_QUERY_ANYWHERE; + + struct timeval start, end; + gettimeofday(&start, NULL); + int n; + ARROW_CHECK_OK(client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, + WAIT_TIMEOUT_MS, n)); + ASSERT(n == 0); + gettimeofday(&end, NULL); + float diff_ms = (end.tv_sec - start.tv_sec); + diff_ms = (((diff_ms * 1000000.) + end.tv_usec) - (start.tv_usec)) / 1000.; + /* Reduce threshold by 10% to make sure we pass consistently. */ + ASSERT(diff_ms > WAIT_TIMEOUT_MS * 0.9); + + /* Create and insert an object in plasma_conn1. */ + int64_t data_size = 4; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + uint8_t *data; + ARROW_CHECK_OK( + client1.Create(oid1, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client1.Seal(oid1)); + + ARROW_CHECK_OK(client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, + WAIT_TIMEOUT_MS, n)); + ASSERT(n == 1); + + /* Create and insert an object in client2. */ + ARROW_CHECK_OK( + client2.Create(oid2, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client2.Seal(oid2)); + + ARROW_CHECK_OK(client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, + WAIT_TIMEOUT_MS, n)); + ASSERT(n == 2); + + ARROW_CHECK_OK(client2.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, + WAIT_TIMEOUT_MS, n)); + ASSERT(n == 2); + + obj_requests[0].type = PLASMA_QUERY_LOCAL; + obj_requests[1].type = PLASMA_QUERY_LOCAL; + ARROW_CHECK_OK(client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, + WAIT_TIMEOUT_MS, n)); + ASSERT(n == 1); + + ARROW_CHECK_OK(client2.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, + WAIT_TIMEOUT_MS, n)); + ASSERT(n == 1); + + ARROW_CHECK_OK(client1.Disconnect()); + ARROW_CHECK_OK(client2.Disconnect()); + + PASS(); +} + +TEST plasma_get_tests(void) { + PlasmaClient client1, client2; + ARROW_CHECK_OK(client1.Connect("/tmp/store1", "/tmp/manager1", + PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK(client2.Connect("/tmp/store2", "/tmp/manager2", + PLASMA_DEFAULT_RELEASE_DELAY)); + ObjectID oid1 = ObjectID::from_random(); + ObjectID oid2 = ObjectID::from_random(); + ObjectBuffer obj_buffer; + + ObjectID oid_array1[1] = {oid1}; + ObjectID oid_array2[1] = {oid2}; + + int64_t data_size = 4; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + uint8_t *data; + ARROW_CHECK_OK( + client1.Create(oid1, data_size, metadata, metadata_size, &data)); + init_data_123(data, data_size, 1); + ARROW_CHECK_OK(client1.Seal(oid1)); + + ARROW_CHECK_OK(client1.Get(oid_array1, 1, -1, &obj_buffer)); + ASSERT(data[0] == obj_buffer.data[0]); + + ARROW_CHECK_OK( + client2.Create(oid2, data_size, metadata, metadata_size, &data)); + init_data_123(data, data_size, 2); + ARROW_CHECK_OK(client2.Seal(oid2)); + + ARROW_CHECK_OK(client1.Fetch(1, oid_array2)); + ARROW_CHECK_OK(client1.Get(oid_array2, 1, -1, &obj_buffer)); + ASSERT(data[0] == obj_buffer.data[0]); + + sleep(1); + ARROW_CHECK_OK(client1.Disconnect()); + ARROW_CHECK_OK(client2.Disconnect()); + + PASS(); +} + +TEST plasma_get_multiple_tests(void) { + PlasmaClient client1, client2; + ARROW_CHECK_OK(client1.Connect("/tmp/store1", "/tmp/manager1", + PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK(client2.Connect("/tmp/store2", "/tmp/manager2", + PLASMA_DEFAULT_RELEASE_DELAY)); + ObjectID oid1 = ObjectID::from_random(); + ObjectID oid2 = ObjectID::from_random(); + ObjectID obj_ids[NUM_OBJ_REQUEST]; + ObjectBuffer obj_buffer[NUM_OBJ_REQUEST]; + int obj1_first = 1, obj2_first = 2; + + obj_ids[0] = oid1; + obj_ids[1] = oid2; + + int64_t data_size = 4; + uint8_t metadata[] = {5}; + int64_t metadata_size = sizeof(metadata); + uint8_t *data; + ARROW_CHECK_OK( + client1.Create(oid1, data_size, metadata, metadata_size, &data)); + init_data_123(data, data_size, obj1_first); + ARROW_CHECK_OK(client1.Seal(oid1)); + + /* This only waits for oid1. */ + ARROW_CHECK_OK(client1.Get(obj_ids, 1, -1, obj_buffer)); + ASSERT(data[0] == obj_buffer[0].data[0]); + + ARROW_CHECK_OK( + client2.Create(oid2, data_size, metadata, metadata_size, &data)); + init_data_123(data, data_size, obj2_first); + ARROW_CHECK_OK(client2.Seal(oid2)); + + ARROW_CHECK_OK(client1.Fetch(2, obj_ids)); + ARROW_CHECK_OK(client1.Get(obj_ids, 2, -1, obj_buffer)); + ASSERT(obj1_first == obj_buffer[0].data[0]); + ASSERT(obj2_first == obj_buffer[1].data[0]); + + sleep(1); + ARROW_CHECK_OK(client1.Disconnect()); + ARROW_CHECK_OK(client2.Disconnect()); + + PASS(); +} + +SUITE(plasma_client_tests) { + RUN_TEST(plasma_status_tests); + RUN_TEST(plasma_fetch_tests); + RUN_TEST(plasma_nonblocking_get_tests); + RUN_TEST(plasma_wait_for_objects_tests); + RUN_TEST(plasma_get_tests); + RUN_TEST(plasma_get_multiple_tests); +} + +GREATEST_MAIN_DEFS(); + +int main(int argc, char **argv) { + GREATEST_MAIN_BEGIN(); + RUN_SUITE(plasma_client_tests); + GREATEST_MAIN_END(); +} diff --git a/cpp/src/plasma/test/run_tests.sh b/cpp/src/plasma/test/run_tests.sh new file mode 100644 index 00000000000..82f8ff9944d --- /dev/null +++ b/cpp/src/plasma/test/run_tests.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash + +# Cause the script to exit if a single command fails. +set -e + +./src/plasma/plasma_store -s /tmp/plasma_store_socket_1 -m 0 & +sleep 1 +./src/plasma/manager_tests +killall plasma_store +./src/plasma/serialization_tests + +# Start the Redis shards. +./src/common/thirdparty/redis/src/redis-server --loglevel warning --loadmodule ./src/common/redis_module/libray_redis_module.so --port 6379 & +redis_pid1=$! +./src/common/thirdparty/redis/src/redis-server --loglevel warning --loadmodule ./src/common/redis_module/libray_redis_module.so --port 6380 & +redis_pid2=$! +sleep 1 + +# Flush the redis server +./src/common/thirdparty/redis/src/redis-cli flushall +# Register the shard location with the primary shard. +./src/common/thirdparty/redis/src/redis-cli set NumRedisShards 1 +./src/common/thirdparty/redis/src/redis-cli rpush RedisShards 127.0.0.1:6380 +sleep 1 +./src/plasma/plasma_store -s /tmp/store1 -m 1000000000 & +plasma1_pid=$! +./src/plasma/plasma_manager -m /tmp/manager1 -s /tmp/store1 -h 127.0.0.1 -p 11111 -r 127.0.0.1:6379 & +plasma2_pid=$! +./src/plasma/plasma_store -s /tmp/store2 -m 1000000000 & +plasma3_pid=$! +./src/plasma/plasma_manager -m /tmp/manager2 -s /tmp/store2 -h 127.0.0.1 -p 22222 -r 127.0.0.1:6379 & +plasma4_pid=$! +sleep 1 + +./src/plasma/client_tests + +kill $plasma4_pid +kill $plasma3_pid +kill $plasma2_pid +kill $plasma1_pid +kill $redis_pid1 +wait $redis_pid1 +kill $redis_pid2 +wait $redis_pid2 diff --git a/cpp/src/plasma/test/run_valgrind.sh b/cpp/src/plasma/test/run_valgrind.sh new file mode 100644 index 00000000000..74531e72161 --- /dev/null +++ b/cpp/src/plasma/test/run_valgrind.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +# Cause the script to exit if a single command fails. +set -e + +./src/plasma/plasma_store -s /tmp/plasma_store_socket_1 -m 0 & +sleep 1 +valgrind --leak-check=full --error-exitcode=1 ./src/plasma/manager_tests +killall plasma_store +valgrind --leak-check=full --error-exitcode=1 ./src/plasma/serialization_tests diff --git a/cpp/src/plasma/test/serialization_tests.cc b/cpp/src/plasma/test/serialization_tests.cc new file mode 100644 index 00000000000..b3909453544 --- /dev/null +++ b/cpp/src/plasma/test/serialization_tests.cc @@ -0,0 +1,439 @@ +#include "greatest.h" + +#include +#include + +#include "plasma_common.h" +#include "plasma.h" +#include "plasma_io.h" +#include "plasma_protocol.h" + +SUITE(plasma_serialization_tests); + +/** + * Create a temporary file. Needs to be closed by the caller. + * + * @return File descriptor of the file. + */ +int create_temp_file(void) { + static char temp[] = "/tmp/tempfileXXXXXX"; + char file_name[32]; + strncpy(file_name, temp, 32); + return mkstemp(file_name); +} + +/** + * Seek to the beginning of a file and read a message from it. + * + * @param fd File descriptor of the file. + * @param message type Message type that we expect in the file. + * + * @return Pointer to the content of the message. Needs to be freed by the + * caller. + */ +std::vector read_message_from_file(int fd, int message_type) { + /* Go to the beginning of the file. */ + lseek(fd, 0, SEEK_SET); + int64_t type; + std::vector data; + ARROW_CHECK_OK(ReadMessage(fd, &type, data)); + ARROW_CHECK(type == message_type); + return data; +} + +PlasmaObject random_plasma_object(void) { + int random = rand(); + PlasmaObject object; + memset(&object, 0, sizeof(object)); + object.handle.store_fd = random + 7; + object.handle.mmap_size = random + 42; + object.data_offset = random + 1; + object.metadata_offset = random + 2; + object.data_size = random + 3; + object.metadata_size = random + 4; + return object; +} + +TEST plasma_create_request_test(void) { + int fd = create_temp_file(); + ObjectID object_id1 = ObjectID::from_random(); + int64_t data_size1 = 42; + int64_t metadata_size1 = 11; + ARROW_CHECK_OK(SendCreateRequest(fd, object_id1, data_size1, metadata_size1)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaCreateRequest); + ObjectID object_id2; + int64_t data_size2; + int64_t metadata_size2; + ARROW_CHECK_OK(ReadCreateRequest(data.data(), &object_id2, &data_size2, + &metadata_size2)); + ASSERT_EQ(data_size1, data_size2); + ASSERT_EQ(metadata_size1, metadata_size2); + ASSERT(object_id1 == object_id2); + close(fd); + PASS(); +} + +TEST plasma_create_reply_test(void) { + int fd = create_temp_file(); + ObjectID object_id1 = ObjectID::from_random(); + PlasmaObject object1 = random_plasma_object(); + ARROW_CHECK_OK(SendCreateReply(fd, object_id1, &object1, 0)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaCreateReply); + ObjectID object_id2; + PlasmaObject object2; + memset(&object2, 0, sizeof(object2)); + ARROW_CHECK_OK(ReadCreateReply(data.data(), &object_id2, &object2)); + ASSERT(object_id1 == object_id2); + ASSERT(memcmp(&object1, &object2, sizeof(object1)) == 0); + close(fd); + PASS(); +} + +TEST plasma_seal_request_test(void) { + int fd = create_temp_file(); + ObjectID object_id1 = ObjectID::from_random(); + unsigned char digest1[kDigestSize]; + memset(&digest1[0], 7, kDigestSize); + ARROW_CHECK_OK(SendSealRequest(fd, object_id1, &digest1[0])); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaSealRequest); + ObjectID object_id2; + unsigned char digest2[kDigestSize]; + ARROW_CHECK_OK(ReadSealRequest(data.data(), &object_id2, &digest2[0])); + ASSERT(object_id1 == object_id2); + ASSERT(memcmp(&digest1[0], &digest2[0], kDigestSize) == 0); + close(fd); + PASS(); +} + +TEST plasma_seal_reply_test(void) { + int fd = create_temp_file(); + ObjectID object_id1 = ObjectID::from_random(); + ARROW_CHECK_OK(SendSealReply(fd, object_id1, PlasmaError_ObjectExists)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaSealReply); + ObjectID object_id2; + Status s = ReadSealReply(data.data(), &object_id2); + ASSERT(object_id1 == object_id2); + ASSERT(s.IsPlasmaObjectExists()); + close(fd); + PASS(); +} + +TEST plasma_get_request_test(void) { + int fd = create_temp_file(); + ObjectID object_ids[2]; + object_ids[0] = ObjectID::from_random(); + object_ids[1] = ObjectID::from_random(); + int64_t timeout_ms = 1234; + ARROW_CHECK_OK(SendGetRequest(fd, object_ids, 2, timeout_ms)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaGetRequest); + std::vector object_ids_return; + int64_t timeout_ms_return; + ARROW_CHECK_OK( + ReadGetRequest(data.data(), object_ids_return, &timeout_ms_return)); + ASSERT(object_ids[0] == object_ids_return[0]); + ASSERT(object_ids[1] == object_ids_return[1]); + ASSERT(timeout_ms == timeout_ms_return); + close(fd); + PASS(); +} + +TEST plasma_get_reply_test(void) { + int fd = create_temp_file(); + ObjectID object_ids[2]; + object_ids[0] = ObjectID::from_random(); + object_ids[1] = ObjectID::from_random(); + std::unordered_map plasma_objects; + plasma_objects[object_ids[0]] = random_plasma_object(); + plasma_objects[object_ids[1]] = random_plasma_object(); + ARROW_CHECK_OK(SendGetReply(fd, object_ids, plasma_objects, 2)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaGetReply); + ObjectID object_ids_return[2]; + PlasmaObject plasma_objects_return[2]; + memset(&plasma_objects_return, 0, sizeof(plasma_objects_return)); + ARROW_CHECK_OK(ReadGetReply(data.data(), object_ids_return, + &plasma_objects_return[0], 2)); + ASSERT(object_ids[0] == object_ids_return[0]); + ASSERT(object_ids[1] == object_ids_return[1]); + ASSERT(memcmp(&plasma_objects[object_ids[0]], &plasma_objects_return[0], + sizeof(PlasmaObject)) == 0); + ASSERT(memcmp(&plasma_objects[object_ids[1]], &plasma_objects_return[1], + sizeof(PlasmaObject)) == 0); + close(fd); + PASS(); +} + +TEST plasma_release_request_test(void) { + int fd = create_temp_file(); + ObjectID object_id1 = ObjectID::from_random(); + ARROW_CHECK_OK(SendReleaseRequest(fd, object_id1)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaReleaseRequest); + ObjectID object_id2; + ARROW_CHECK_OK(ReadReleaseRequest(data.data(), &object_id2)); + ASSERT(object_id1 == object_id2); + close(fd); + PASS(); +} + +TEST plasma_release_reply_test(void) { + int fd = create_temp_file(); + ObjectID object_id1 = ObjectID::from_random(); + ARROW_CHECK_OK(SendReleaseReply(fd, object_id1, PlasmaError_ObjectExists)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaReleaseReply); + ObjectID object_id2; + Status s = ReadReleaseReply(data.data(), &object_id2); + ASSERT(object_id1 == object_id2); + ASSERT(s.IsPlasmaObjectExists()); + close(fd); + PASS(); +} + +TEST plasma_delete_request_test(void) { + int fd = create_temp_file(); + ObjectID object_id1 = ObjectID::from_random(); + ARROW_CHECK_OK(SendDeleteRequest(fd, object_id1)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaDeleteRequest); + ObjectID object_id2; + ARROW_CHECK_OK(ReadDeleteRequest(data.data(), &object_id2)); + ASSERT(object_id1 == object_id2); + close(fd); + PASS(); +} + +TEST plasma_delete_reply_test(void) { + int fd = create_temp_file(); + ObjectID object_id1 = ObjectID::from_random(); + int error1 = PlasmaError_ObjectExists; + ARROW_CHECK_OK(SendDeleteReply(fd, object_id1, error1)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaDeleteReply); + ObjectID object_id2; + Status s = ReadDeleteReply(data.data(), &object_id2); + ASSERT(object_id1 == object_id2); + ASSERT(s.IsPlasmaObjectExists()); + close(fd); + PASS(); +} + +TEST plasma_status_request_test(void) { + int fd = create_temp_file(); + int64_t num_objects = 2; + ObjectID object_ids[num_objects]; + object_ids[0] = ObjectID::from_random(); + object_ids[1] = ObjectID::from_random(); + ARROW_CHECK_OK(SendStatusRequest(fd, object_ids, num_objects)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaStatusRequest); + ObjectID object_ids_read[num_objects]; + ARROW_CHECK_OK(ReadStatusRequest(data.data(), object_ids_read, num_objects)); + ASSERT(object_ids[0] == object_ids_read[0]); + ASSERT(object_ids[1] == object_ids_read[1]); + close(fd); + PASS(); +} + +TEST plasma_status_reply_test(void) { + int fd = create_temp_file(); + ObjectID object_ids[2]; + object_ids[0] = ObjectID::from_random(); + object_ids[1] = ObjectID::from_random(); + int object_statuses[2] = {42, 43}; + ARROW_CHECK_OK(SendStatusReply(fd, object_ids, object_statuses, 2)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaStatusReply); + int64_t num_objects = ReadStatusReply_num_objects(data.data()); + ObjectID object_ids_read[num_objects]; + int object_statuses_read[num_objects]; + ARROW_CHECK_OK(ReadStatusReply(data.data(), object_ids_read, + object_statuses_read, num_objects)); + ASSERT(object_ids[0] == object_ids_read[0]); + ASSERT(object_ids[1] == object_ids_read[1]); + ASSERT_EQ(object_statuses[0], object_statuses_read[0]); + ASSERT_EQ(object_statuses[1], object_statuses_read[1]); + close(fd); + PASS(); +} + +TEST plasma_evict_request_test(void) { + int fd = create_temp_file(); + int64_t num_bytes = 111; + ARROW_CHECK_OK(SendEvictRequest(fd, num_bytes)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaEvictRequest); + int64_t num_bytes_received; + ARROW_CHECK_OK(ReadEvictRequest(data.data(), &num_bytes_received)); + ASSERT_EQ(num_bytes, num_bytes_received); + close(fd); + PASS(); +} + +TEST plasma_evict_reply_test(void) { + int fd = create_temp_file(); + int64_t num_bytes = 111; + ARROW_CHECK_OK(SendEvictReply(fd, num_bytes)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaEvictReply); + int64_t num_bytes_received; + ARROW_CHECK_OK(ReadEvictReply(data.data(), num_bytes_received)); + ASSERT_EQ(num_bytes, num_bytes_received); + close(fd); + PASS(); +} + +TEST plasma_fetch_request_test(void) { + int fd = create_temp_file(); + ObjectID object_ids[2]; + object_ids[0] = ObjectID::from_random(); + object_ids[1] = ObjectID::from_random(); + ARROW_CHECK_OK(SendFetchRequest(fd, object_ids, 2)); + std::vector data = + read_message_from_file(fd, MessageType_PlasmaFetchRequest); + std::vector object_ids_read; + ARROW_CHECK_OK(ReadFetchRequest(data.data(), object_ids_read)); + ASSERT(object_ids[0] == object_ids_read[0]); + ASSERT(object_ids[1] == object_ids_read[1]); + close(fd); + PASS(); +} + +TEST plasma_wait_request_test(void) { + int fd = create_temp_file(); + const int num_objects_in = 2; + ObjectRequest object_requests_in[num_objects_in] = { + ObjectRequest({ObjectID::from_random(), PLASMA_QUERY_ANYWHERE, 0}), + ObjectRequest({ObjectID::from_random(), PLASMA_QUERY_LOCAL, 0})}; + const int num_ready_objects_in = 1; + int64_t timeout_ms = 1000; + + ARROW_CHECK_OK(SendWaitRequest(fd, &object_requests_in[0], num_objects_in, + num_ready_objects_in, timeout_ms)); + /* Read message back. */ + std::vector data = + read_message_from_file(fd, MessageType_PlasmaWaitRequest); + int num_ready_objects_out; + int64_t timeout_ms_read; + ObjectRequestMap object_requests_out; + ARROW_CHECK_OK(ReadWaitRequest(data.data(), object_requests_out, + &timeout_ms_read, &num_ready_objects_out)); + ASSERT_EQ(num_objects_in, object_requests_out.size()); + ASSERT_EQ(num_ready_objects_out, num_ready_objects_in); + for (int i = 0; i < num_objects_in; i++) { + const ObjectID &object_id = object_requests_in[i].object_id; + ASSERT_EQ(1, object_requests_out.count(object_id)); + const auto &entry = object_requests_out.find(object_id); + ASSERT(entry != object_requests_out.end()); + ASSERT(entry->second.object_id == object_requests_in[i].object_id); + ASSERT_EQ(entry->second.type, object_requests_in[i].type); + } + close(fd); + PASS(); +} + +TEST plasma_wait_reply_test(void) { + int fd = create_temp_file(); + const int num_objects_in = 2; + /* Create a map with two ObjectRequests in it. */ + ObjectRequestMap objects_in(num_objects_in); + ObjectID id1 = ObjectID::from_random(); + objects_in[id1] = ObjectRequest({id1, 0, ObjectStatus_Local}); + ObjectID id2 = ObjectID::from_random(); + objects_in[id2] = ObjectRequest({id2, 0, ObjectStatus_Nonexistent}); + + ARROW_CHECK_OK(SendWaitReply(fd, objects_in, num_objects_in)); + /* Read message back. */ + std::vector data = + read_message_from_file(fd, MessageType_PlasmaWaitReply); + ObjectRequest objects_out[2]; + int num_objects_out; + ARROW_CHECK_OK(ReadWaitReply(data.data(), &objects_out[0], &num_objects_out)); + ASSERT(num_objects_in == num_objects_out); + for (int i = 0; i < num_objects_out; i++) { + /* Each object request must appear exactly once. */ + ASSERT(1 == objects_in.count(objects_out[i].object_id)); + const auto &entry = objects_in.find(objects_out[i].object_id); + ASSERT(entry != objects_in.end()); + ASSERT(entry->second.object_id == objects_out[i].object_id); + ASSERT(entry->second.status == objects_out[i].status); + } + close(fd); + PASS(); +} + +TEST plasma_data_request_test(void) { + int fd = create_temp_file(); + ObjectID object_id1 = ObjectID::from_random(); + const char *address1 = "address1"; + int port1 = 12345; + ARROW_CHECK_OK(SendDataRequest(fd, object_id1, address1, port1)); + /* Reading message back. */ + std::vector data = + read_message_from_file(fd, MessageType_PlasmaDataRequest); + ObjectID object_id2; + char *address2; + int port2; + ARROW_CHECK_OK(ReadDataRequest(data.data(), &object_id2, &address2, &port2)); + ASSERT(object_id1 == object_id2); + ASSERT(strcmp(address1, address2) == 0); + ASSERT(port1 == port2); + free(address2); + close(fd); + PASS(); +} + +TEST plasma_data_reply_test(void) { + int fd = create_temp_file(); + ObjectID object_id1 = ObjectID::from_random(); + int64_t object_size1 = 146; + int64_t metadata_size1 = 198; + ARROW_CHECK_OK(SendDataReply(fd, object_id1, object_size1, metadata_size1)); + /* Reading message back. */ + std::vector data = + read_message_from_file(fd, MessageType_PlasmaDataReply); + ObjectID object_id2; + int64_t object_size2; + int64_t metadata_size2; + ARROW_CHECK_OK( + ReadDataReply(data.data(), &object_id2, &object_size2, &metadata_size2)); + ASSERT(object_id1 == object_id2); + ASSERT(object_size1 == object_size2); + ASSERT(metadata_size1 == metadata_size2); + PASS(); +} + +SUITE(plasma_serialization_tests) { + RUN_TEST(plasma_create_request_test); + RUN_TEST(plasma_create_reply_test); + RUN_TEST(plasma_seal_request_test); + RUN_TEST(plasma_seal_reply_test); + RUN_TEST(plasma_get_request_test); + RUN_TEST(plasma_get_reply_test); + RUN_TEST(plasma_release_request_test); + RUN_TEST(plasma_release_reply_test); + RUN_TEST(plasma_delete_request_test); + RUN_TEST(plasma_delete_reply_test); + RUN_TEST(plasma_status_request_test); + RUN_TEST(plasma_status_reply_test); + RUN_TEST(plasma_evict_request_test); + RUN_TEST(plasma_evict_reply_test); + RUN_TEST(plasma_fetch_request_test); + RUN_TEST(plasma_wait_request_test); + RUN_TEST(plasma_wait_reply_test); + RUN_TEST(plasma_data_request_test); + RUN_TEST(plasma_data_reply_test); +} + +GREATEST_MAIN_DEFS(); + +int main(int argc, char **argv) { + GREATEST_MAIN_BEGIN(); + RUN_SUITE(plasma_serialization_tests); + GREATEST_MAIN_END(); +} diff --git a/cpp/src/plasma/thirdparty/ae/ae.c b/cpp/src/plasma/thirdparty/ae/ae.c new file mode 100644 index 00000000000..e66808a8146 --- /dev/null +++ b/cpp/src/plasma/thirdparty/ae/ae.c @@ -0,0 +1,465 @@ +/* A simple event-driven programming library. Originally I wrote this code + * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated + * it in form of a library for easy reuse. + * + * Copyright (c) 2006-2010, Salvatore Sanfilippo + * 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 Redis 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ae.h" +#include "zmalloc.h" +#include "config.h" + +/* Include the best multiplexing layer supported by this system. + * The following should be ordered by performances, descending. */ +#ifdef HAVE_EVPORT +#include "ae_evport.c" +#else + #ifdef HAVE_EPOLL + #include "ae_epoll.c" + #else + #ifdef HAVE_KQUEUE + #include "ae_kqueue.c" + #else + #include "ae_select.c" + #endif + #endif +#endif + +aeEventLoop *aeCreateEventLoop(int setsize) { + aeEventLoop *eventLoop; + int i; + + if ((eventLoop = zmalloc(sizeof(*eventLoop))) == NULL) goto err; + eventLoop->events = zmalloc(sizeof(aeFileEvent)*setsize); + eventLoop->fired = zmalloc(sizeof(aeFiredEvent)*setsize); + if (eventLoop->events == NULL || eventLoop->fired == NULL) goto err; + eventLoop->setsize = setsize; + eventLoop->lastTime = time(NULL); + eventLoop->timeEventHead = NULL; + eventLoop->timeEventNextId = 0; + eventLoop->stop = 0; + eventLoop->maxfd = -1; + eventLoop->beforesleep = NULL; + if (aeApiCreate(eventLoop) == -1) goto err; + /* Events with mask == AE_NONE are not set. So let's initialize the + * vector with it. */ + for (i = 0; i < setsize; i++) + eventLoop->events[i].mask = AE_NONE; + return eventLoop; + +err: + if (eventLoop) { + zfree(eventLoop->events); + zfree(eventLoop->fired); + zfree(eventLoop); + } + return NULL; +} + +/* Return the current set size. */ +int aeGetSetSize(aeEventLoop *eventLoop) { + return eventLoop->setsize; +} + +/* Resize the maximum set size of the event loop. + * If the requested set size is smaller than the current set size, but + * there is already a file descriptor in use that is >= the requested + * set size minus one, AE_ERR is returned and the operation is not + * performed at all. + * + * Otherwise AE_OK is returned and the operation is successful. */ +int aeResizeSetSize(aeEventLoop *eventLoop, int setsize) { + int i; + + if (setsize == eventLoop->setsize) return AE_OK; + if (eventLoop->maxfd >= setsize) return AE_ERR; + if (aeApiResize(eventLoop,setsize) == -1) return AE_ERR; + + eventLoop->events = zrealloc(eventLoop->events,sizeof(aeFileEvent)*setsize); + eventLoop->fired = zrealloc(eventLoop->fired,sizeof(aeFiredEvent)*setsize); + eventLoop->setsize = setsize; + + /* Make sure that if we created new slots, they are initialized with + * an AE_NONE mask. */ + for (i = eventLoop->maxfd+1; i < setsize; i++) + eventLoop->events[i].mask = AE_NONE; + return AE_OK; +} + +void aeDeleteEventLoop(aeEventLoop *eventLoop) { + aeApiFree(eventLoop); + zfree(eventLoop->events); + zfree(eventLoop->fired); + zfree(eventLoop); +} + +void aeStop(aeEventLoop *eventLoop) { + eventLoop->stop = 1; +} + +int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask, + aeFileProc *proc, void *clientData) +{ + if (fd >= eventLoop->setsize) { + errno = ERANGE; + return AE_ERR; + } + aeFileEvent *fe = &eventLoop->events[fd]; + + if (aeApiAddEvent(eventLoop, fd, mask) == -1) + return AE_ERR; + fe->mask |= mask; + if (mask & AE_READABLE) fe->rfileProc = proc; + if (mask & AE_WRITABLE) fe->wfileProc = proc; + fe->clientData = clientData; + if (fd > eventLoop->maxfd) + eventLoop->maxfd = fd; + return AE_OK; +} + +void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask) +{ + if (fd >= eventLoop->setsize) return; + aeFileEvent *fe = &eventLoop->events[fd]; + if (fe->mask == AE_NONE) return; + + aeApiDelEvent(eventLoop, fd, mask); + fe->mask = fe->mask & (~mask); + if (fd == eventLoop->maxfd && fe->mask == AE_NONE) { + /* Update the max fd */ + int j; + + for (j = eventLoop->maxfd-1; j >= 0; j--) + if (eventLoop->events[j].mask != AE_NONE) break; + eventLoop->maxfd = j; + } +} + +int aeGetFileEvents(aeEventLoop *eventLoop, int fd) { + if (fd >= eventLoop->setsize) return 0; + aeFileEvent *fe = &eventLoop->events[fd]; + + return fe->mask; +} + +static void aeGetTime(long *seconds, long *milliseconds) +{ + struct timeval tv; + + gettimeofday(&tv, NULL); + *seconds = tv.tv_sec; + *milliseconds = tv.tv_usec/1000; +} + +static void aeAddMillisecondsToNow(long long milliseconds, long *sec, long *ms) { + long cur_sec, cur_ms, when_sec, when_ms; + + aeGetTime(&cur_sec, &cur_ms); + when_sec = cur_sec + milliseconds/1000; + when_ms = cur_ms + milliseconds%1000; + if (when_ms >= 1000) { + when_sec ++; + when_ms -= 1000; + } + *sec = when_sec; + *ms = when_ms; +} + +long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds, + aeTimeProc *proc, void *clientData, + aeEventFinalizerProc *finalizerProc) +{ + long long id = eventLoop->timeEventNextId++; + aeTimeEvent *te; + + te = zmalloc(sizeof(*te)); + if (te == NULL) return AE_ERR; + te->id = id; + aeAddMillisecondsToNow(milliseconds,&te->when_sec,&te->when_ms); + te->timeProc = proc; + te->finalizerProc = finalizerProc; + te->clientData = clientData; + te->next = eventLoop->timeEventHead; + eventLoop->timeEventHead = te; + return id; +} + +int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id) +{ + aeTimeEvent *te = eventLoop->timeEventHead; + while(te) { + if (te->id == id) { + te->id = AE_DELETED_EVENT_ID; + return AE_OK; + } + te = te->next; + } + return AE_ERR; /* NO event with the specified ID found */ +} + +/* Search the first timer to fire. + * This operation is useful to know how many time the select can be + * put in sleep without to delay any event. + * If there are no timers NULL is returned. + * + * Note that's O(N) since time events are unsorted. + * Possible optimizations (not needed by Redis so far, but...): + * 1) Insert the event in order, so that the nearest is just the head. + * Much better but still insertion or deletion of timers is O(N). + * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)). + */ +static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop) +{ + aeTimeEvent *te = eventLoop->timeEventHead; + aeTimeEvent *nearest = NULL; + + while(te) { + if (!nearest || te->when_sec < nearest->when_sec || + (te->when_sec == nearest->when_sec && + te->when_ms < nearest->when_ms)) + nearest = te; + te = te->next; + } + return nearest; +} + +/* Process time events */ +static int processTimeEvents(aeEventLoop *eventLoop) { + int processed = 0; + aeTimeEvent *te, *prev; + long long maxId; + time_t now = time(NULL); + + /* If the system clock is moved to the future, and then set back to the + * right value, time events may be delayed in a random way. Often this + * means that scheduled operations will not be performed soon enough. + * + * Here we try to detect system clock skews, and force all the time + * events to be processed ASAP when this happens: the idea is that + * processing events earlier is less dangerous than delaying them + * indefinitely, and practice suggests it is. */ + if (now < eventLoop->lastTime) { + te = eventLoop->timeEventHead; + while(te) { + te->when_sec = 0; + te = te->next; + } + } + eventLoop->lastTime = now; + + prev = NULL; + te = eventLoop->timeEventHead; + maxId = eventLoop->timeEventNextId-1; + while(te) { + long now_sec, now_ms; + long long id; + + /* Remove events scheduled for deletion. */ + if (te->id == AE_DELETED_EVENT_ID) { + aeTimeEvent *next = te->next; + if (prev == NULL) + eventLoop->timeEventHead = te->next; + else + prev->next = te->next; + if (te->finalizerProc) + te->finalizerProc(eventLoop, te->clientData); + zfree(te); + te = next; + continue; + } + + /* Make sure we don't process time events created by time events in + * this iteration. Note that this check is currently useless: we always + * add new timers on the head, however if we change the implementation + * detail, this check may be useful again: we keep it here for future + * defense. */ + if (te->id > maxId) { + te = te->next; + continue; + } + aeGetTime(&now_sec, &now_ms); + if (now_sec > te->when_sec || + (now_sec == te->when_sec && now_ms >= te->when_ms)) + { + int retval; + + id = te->id; + retval = te->timeProc(eventLoop, id, te->clientData); + processed++; + if (retval != AE_NOMORE) { + aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms); + } else { + te->id = AE_DELETED_EVENT_ID; + } + } + prev = te; + te = te->next; + } + return processed; +} + +/* Process every pending time event, then every pending file event + * (that may be registered by time event callbacks just processed). + * Without special flags the function sleeps until some file event + * fires, or when the next time event occurs (if any). + * + * If flags is 0, the function does nothing and returns. + * if flags has AE_ALL_EVENTS set, all the kind of events are processed. + * if flags has AE_FILE_EVENTS set, file events are processed. + * if flags has AE_TIME_EVENTS set, time events are processed. + * if flags has AE_DONT_WAIT set the function returns ASAP until all + * the events that's possible to process without to wait are processed. + * + * The function returns the number of events processed. */ +int aeProcessEvents(aeEventLoop *eventLoop, int flags) +{ + int processed = 0, numevents; + + /* Nothing to do? return ASAP */ + if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0; + + /* Note that we want call select() even if there are no + * file events to process as long as we want to process time + * events, in order to sleep until the next time event is ready + * to fire. */ + if (eventLoop->maxfd != -1 || + ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) { + int j; + aeTimeEvent *shortest = NULL; + struct timeval tv, *tvp; + + if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT)) + shortest = aeSearchNearestTimer(eventLoop); + if (shortest) { + long now_sec, now_ms; + + aeGetTime(&now_sec, &now_ms); + tvp = &tv; + + /* How many milliseconds we need to wait for the next + * time event to fire? */ + long long ms = + (shortest->when_sec - now_sec)*1000 + + shortest->when_ms - now_ms; + + if (ms > 0) { + tvp->tv_sec = ms/1000; + tvp->tv_usec = (ms % 1000)*1000; + } else { + tvp->tv_sec = 0; + tvp->tv_usec = 0; + } + } else { + /* If we have to check for events but need to return + * ASAP because of AE_DONT_WAIT we need to set the timeout + * to zero */ + if (flags & AE_DONT_WAIT) { + tv.tv_sec = tv.tv_usec = 0; + tvp = &tv; + } else { + /* Otherwise we can block */ + tvp = NULL; /* wait forever */ + } + } + + numevents = aeApiPoll(eventLoop, tvp); + for (j = 0; j < numevents; j++) { + aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd]; + int mask = eventLoop->fired[j].mask; + int fd = eventLoop->fired[j].fd; + int rfired = 0; + + /* note the fe->mask & mask & ... code: maybe an already processed + * event removed an element that fired and we still didn't + * processed, so we check if the event is still valid. */ + if (fe->mask & mask & AE_READABLE) { + rfired = 1; + fe->rfileProc(eventLoop,fd,fe->clientData,mask); + } + if (fe->mask & mask & AE_WRITABLE) { + if (!rfired || fe->wfileProc != fe->rfileProc) + fe->wfileProc(eventLoop,fd,fe->clientData,mask); + } + processed++; + } + } + /* Check time events */ + if (flags & AE_TIME_EVENTS) + processed += processTimeEvents(eventLoop); + + return processed; /* return the number of processed file/time events */ +} + +/* Wait for milliseconds until the given file descriptor becomes + * writable/readable/exception */ +int aeWait(int fd, int mask, long long milliseconds) { + struct pollfd pfd; + int retmask = 0, retval; + + memset(&pfd, 0, sizeof(pfd)); + pfd.fd = fd; + if (mask & AE_READABLE) pfd.events |= POLLIN; + if (mask & AE_WRITABLE) pfd.events |= POLLOUT; + + if ((retval = poll(&pfd, 1, milliseconds))== 1) { + if (pfd.revents & POLLIN) retmask |= AE_READABLE; + if (pfd.revents & POLLOUT) retmask |= AE_WRITABLE; + if (pfd.revents & POLLERR) retmask |= AE_WRITABLE; + if (pfd.revents & POLLHUP) retmask |= AE_WRITABLE; + return retmask; + } else { + return retval; + } +} + +void aeMain(aeEventLoop *eventLoop) { + eventLoop->stop = 0; + while (!eventLoop->stop) { + if (eventLoop->beforesleep != NULL) + eventLoop->beforesleep(eventLoop); + aeProcessEvents(eventLoop, AE_ALL_EVENTS); + } +} + +char *aeGetApiName(void) { + return aeApiName(); +} + +void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep) { + eventLoop->beforesleep = beforesleep; +} diff --git a/cpp/src/plasma/thirdparty/ae/ae.h b/cpp/src/plasma/thirdparty/ae/ae.h new file mode 100644 index 00000000000..827c4c9e4e5 --- /dev/null +++ b/cpp/src/plasma/thirdparty/ae/ae.h @@ -0,0 +1,123 @@ +/* A simple event-driven programming library. Originally I wrote this code + * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated + * it in form of a library for easy reuse. + * + * Copyright (c) 2006-2012, Salvatore Sanfilippo + * 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 Redis 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. + */ + +#ifndef __AE_H__ +#define __AE_H__ + +#include + +#define AE_OK 0 +#define AE_ERR -1 + +#define AE_NONE 0 +#define AE_READABLE 1 +#define AE_WRITABLE 2 + +#define AE_FILE_EVENTS 1 +#define AE_TIME_EVENTS 2 +#define AE_ALL_EVENTS (AE_FILE_EVENTS|AE_TIME_EVENTS) +#define AE_DONT_WAIT 4 + +#define AE_NOMORE -1 +#define AE_DELETED_EVENT_ID -1 + +/* Macros */ +#define AE_NOTUSED(V) ((void) V) + +struct aeEventLoop; + +/* Types and data structures */ +typedef void aeFileProc(struct aeEventLoop *eventLoop, int fd, void *clientData, int mask); +typedef int aeTimeProc(struct aeEventLoop *eventLoop, long long id, void *clientData); +typedef void aeEventFinalizerProc(struct aeEventLoop *eventLoop, void *clientData); +typedef void aeBeforeSleepProc(struct aeEventLoop *eventLoop); + +/* File event structure */ +typedef struct aeFileEvent { + int mask; /* one of AE_(READABLE|WRITABLE) */ + aeFileProc *rfileProc; + aeFileProc *wfileProc; + void *clientData; +} aeFileEvent; + +/* Time event structure */ +typedef struct aeTimeEvent { + long long id; /* time event identifier. */ + long when_sec; /* seconds */ + long when_ms; /* milliseconds */ + aeTimeProc *timeProc; + aeEventFinalizerProc *finalizerProc; + void *clientData; + struct aeTimeEvent *next; +} aeTimeEvent; + +/* A fired event */ +typedef struct aeFiredEvent { + int fd; + int mask; +} aeFiredEvent; + +/* State of an event based program */ +typedef struct aeEventLoop { + int maxfd; /* highest file descriptor currently registered */ + int setsize; /* max number of file descriptors tracked */ + long long timeEventNextId; + time_t lastTime; /* Used to detect system clock skew */ + aeFileEvent *events; /* Registered events */ + aeFiredEvent *fired; /* Fired events */ + aeTimeEvent *timeEventHead; + int stop; + void *apidata; /* This is used for polling API specific data */ + aeBeforeSleepProc *beforesleep; +} aeEventLoop; + +/* Prototypes */ +aeEventLoop *aeCreateEventLoop(int setsize); +void aeDeleteEventLoop(aeEventLoop *eventLoop); +void aeStop(aeEventLoop *eventLoop); +int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask, + aeFileProc *proc, void *clientData); +void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask); +int aeGetFileEvents(aeEventLoop *eventLoop, int fd); +long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds, + aeTimeProc *proc, void *clientData, + aeEventFinalizerProc *finalizerProc); +int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id); +int aeProcessEvents(aeEventLoop *eventLoop, int flags); +int aeWait(int fd, int mask, long long milliseconds); +void aeMain(aeEventLoop *eventLoop); +char *aeGetApiName(void); +void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep); +int aeGetSetSize(aeEventLoop *eventLoop); +int aeResizeSetSize(aeEventLoop *eventLoop, int setsize); + +#endif diff --git a/cpp/src/plasma/thirdparty/ae/ae_epoll.c b/cpp/src/plasma/thirdparty/ae/ae_epoll.c new file mode 100644 index 00000000000..410aac70dc5 --- /dev/null +++ b/cpp/src/plasma/thirdparty/ae/ae_epoll.c @@ -0,0 +1,135 @@ +/* Linux epoll(2) based ae.c module + * + * Copyright (c) 2009-2012, Salvatore Sanfilippo + * 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 Redis 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 + +typedef struct aeApiState { + int epfd; + struct epoll_event *events; +} aeApiState; + +static int aeApiCreate(aeEventLoop *eventLoop) { + aeApiState *state = zmalloc(sizeof(aeApiState)); + + if (!state) return -1; + state->events = zmalloc(sizeof(struct epoll_event)*eventLoop->setsize); + if (!state->events) { + zfree(state); + return -1; + } + state->epfd = epoll_create(1024); /* 1024 is just a hint for the kernel */ + if (state->epfd == -1) { + zfree(state->events); + zfree(state); + return -1; + } + eventLoop->apidata = state; + return 0; +} + +static int aeApiResize(aeEventLoop *eventLoop, int setsize) { + aeApiState *state = eventLoop->apidata; + + state->events = zrealloc(state->events, sizeof(struct epoll_event)*setsize); + return 0; +} + +static void aeApiFree(aeEventLoop *eventLoop) { + aeApiState *state = eventLoop->apidata; + + close(state->epfd); + zfree(state->events); + zfree(state); +} + +static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + struct epoll_event ee = {0}; /* avoid valgrind warning */ + /* If the fd was already monitored for some event, we need a MOD + * operation. Otherwise we need an ADD operation. */ + int op = eventLoop->events[fd].mask == AE_NONE ? + EPOLL_CTL_ADD : EPOLL_CTL_MOD; + + ee.events = 0; + mask |= eventLoop->events[fd].mask; /* Merge old events */ + if (mask & AE_READABLE) ee.events |= EPOLLIN; + if (mask & AE_WRITABLE) ee.events |= EPOLLOUT; + ee.data.fd = fd; + if (epoll_ctl(state->epfd,op,fd,&ee) == -1) return -1; + return 0; +} + +static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int delmask) { + aeApiState *state = eventLoop->apidata; + struct epoll_event ee = {0}; /* avoid valgrind warning */ + int mask = eventLoop->events[fd].mask & (~delmask); + + ee.events = 0; + if (mask & AE_READABLE) ee.events |= EPOLLIN; + if (mask & AE_WRITABLE) ee.events |= EPOLLOUT; + ee.data.fd = fd; + if (mask != AE_NONE) { + epoll_ctl(state->epfd,EPOLL_CTL_MOD,fd,&ee); + } else { + /* Note, Kernel < 2.6.9 requires a non null event pointer even for + * EPOLL_CTL_DEL. */ + epoll_ctl(state->epfd,EPOLL_CTL_DEL,fd,&ee); + } +} + +static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { + aeApiState *state = eventLoop->apidata; + int retval, numevents = 0; + + retval = epoll_wait(state->epfd,state->events,eventLoop->setsize, + tvp ? (tvp->tv_sec*1000 + tvp->tv_usec/1000) : -1); + if (retval > 0) { + int j; + + numevents = retval; + for (j = 0; j < numevents; j++) { + int mask = 0; + struct epoll_event *e = state->events+j; + + if (e->events & EPOLLIN) mask |= AE_READABLE; + if (e->events & EPOLLOUT) mask |= AE_WRITABLE; + if (e->events & EPOLLERR) mask |= AE_WRITABLE; + if (e->events & EPOLLHUP) mask |= AE_WRITABLE; + eventLoop->fired[j].fd = e->data.fd; + eventLoop->fired[j].mask = mask; + } + } + return numevents; +} + +static char *aeApiName(void) { + return "epoll"; +} diff --git a/cpp/src/plasma/thirdparty/ae/ae_evport.c b/cpp/src/plasma/thirdparty/ae/ae_evport.c new file mode 100644 index 00000000000..5c317becb6f --- /dev/null +++ b/cpp/src/plasma/thirdparty/ae/ae_evport.c @@ -0,0 +1,320 @@ +/* ae.c module for illumos event ports. + * + * Copyright (c) 2012, Joyent, Inc. 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 Redis 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 +#include +#include +#include + +#include +#include + +#include + +static int evport_debug = 0; + +/* + * This file implements the ae API using event ports, present on Solaris-based + * systems since Solaris 10. Using the event port interface, we associate file + * descriptors with the port. Each association also includes the set of poll(2) + * events that the consumer is interested in (e.g., POLLIN and POLLOUT). + * + * There's one tricky piece to this implementation: when we return events via + * aeApiPoll, the corresponding file descriptors become dissociated from the + * port. This is necessary because poll events are level-triggered, so if the + * fd didn't become dissociated, it would immediately fire another event since + * the underlying state hasn't changed yet. We must re-associate the file + * descriptor, but only after we know that our caller has actually read from it. + * The ae API does not tell us exactly when that happens, but we do know that + * it must happen by the time aeApiPoll is called again. Our solution is to + * keep track of the last fds returned by aeApiPoll and re-associate them next + * time aeApiPoll is invoked. + * + * To summarize, in this module, each fd association is EITHER (a) represented + * only via the in-kernel association OR (b) represented by pending_fds and + * pending_masks. (b) is only true for the last fds we returned from aeApiPoll, + * and only until we enter aeApiPoll again (at which point we restore the + * in-kernel association). + */ +#define MAX_EVENT_BATCHSZ 512 + +typedef struct aeApiState { + int portfd; /* event port */ + int npending; /* # of pending fds */ + int pending_fds[MAX_EVENT_BATCHSZ]; /* pending fds */ + int pending_masks[MAX_EVENT_BATCHSZ]; /* pending fds' masks */ +} aeApiState; + +static int aeApiCreate(aeEventLoop *eventLoop) { + int i; + aeApiState *state = zmalloc(sizeof(aeApiState)); + if (!state) return -1; + + state->portfd = port_create(); + if (state->portfd == -1) { + zfree(state); + return -1; + } + + state->npending = 0; + + for (i = 0; i < MAX_EVENT_BATCHSZ; i++) { + state->pending_fds[i] = -1; + state->pending_masks[i] = AE_NONE; + } + + eventLoop->apidata = state; + return 0; +} + +static int aeApiResize(aeEventLoop *eventLoop, int setsize) { + /* Nothing to resize here. */ + return 0; +} + +static void aeApiFree(aeEventLoop *eventLoop) { + aeApiState *state = eventLoop->apidata; + + close(state->portfd); + zfree(state); +} + +static int aeApiLookupPending(aeApiState *state, int fd) { + int i; + + for (i = 0; i < state->npending; i++) { + if (state->pending_fds[i] == fd) + return (i); + } + + return (-1); +} + +/* + * Helper function to invoke port_associate for the given fd and mask. + */ +static int aeApiAssociate(const char *where, int portfd, int fd, int mask) { + int events = 0; + int rv, err; + + if (mask & AE_READABLE) + events |= POLLIN; + if (mask & AE_WRITABLE) + events |= POLLOUT; + + if (evport_debug) + fprintf(stderr, "%s: port_associate(%d, 0x%x) = ", where, fd, events); + + rv = port_associate(portfd, PORT_SOURCE_FD, fd, events, + (void *)(uintptr_t)mask); + err = errno; + + if (evport_debug) + fprintf(stderr, "%d (%s)\n", rv, rv == 0 ? "no error" : strerror(err)); + + if (rv == -1) { + fprintf(stderr, "%s: port_associate: %s\n", where, strerror(err)); + + if (err == EAGAIN) + fprintf(stderr, "aeApiAssociate: event port limit exceeded."); + } + + return rv; +} + +static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + int fullmask, pfd; + + if (evport_debug) + fprintf(stderr, "aeApiAddEvent: fd %d mask 0x%x\n", fd, mask); + + /* + * Since port_associate's "events" argument replaces any existing events, we + * must be sure to include whatever events are already associated when + * we call port_associate() again. + */ + fullmask = mask | eventLoop->events[fd].mask; + pfd = aeApiLookupPending(state, fd); + + if (pfd != -1) { + /* + * This fd was recently returned from aeApiPoll. It should be safe to + * assume that the consumer has processed that poll event, but we play + * it safer by simply updating pending_mask. The fd will be + * re-associated as usual when aeApiPoll is called again. + */ + if (evport_debug) + fprintf(stderr, "aeApiAddEvent: adding to pending fd %d\n", fd); + state->pending_masks[pfd] |= fullmask; + return 0; + } + + return (aeApiAssociate("aeApiAddEvent", state->portfd, fd, fullmask)); +} + +static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + int fullmask, pfd; + + if (evport_debug) + fprintf(stderr, "del fd %d mask 0x%x\n", fd, mask); + + pfd = aeApiLookupPending(state, fd); + + if (pfd != -1) { + if (evport_debug) + fprintf(stderr, "deleting event from pending fd %d\n", fd); + + /* + * This fd was just returned from aeApiPoll, so it's not currently + * associated with the port. All we need to do is update + * pending_mask appropriately. + */ + state->pending_masks[pfd] &= ~mask; + + if (state->pending_masks[pfd] == AE_NONE) + state->pending_fds[pfd] = -1; + + return; + } + + /* + * The fd is currently associated with the port. Like with the add case + * above, we must look at the full mask for the file descriptor before + * updating that association. We don't have a good way of knowing what the + * events are without looking into the eventLoop state directly. We rely on + * the fact that our caller has already updated the mask in the eventLoop. + */ + + fullmask = eventLoop->events[fd].mask; + if (fullmask == AE_NONE) { + /* + * We're removing *all* events, so use port_dissociate to remove the + * association completely. Failure here indicates a bug. + */ + if (evport_debug) + fprintf(stderr, "aeApiDelEvent: port_dissociate(%d)\n", fd); + + if (port_dissociate(state->portfd, PORT_SOURCE_FD, fd) != 0) { + perror("aeApiDelEvent: port_dissociate"); + abort(); /* will not return */ + } + } else if (aeApiAssociate("aeApiDelEvent", state->portfd, fd, + fullmask) != 0) { + /* + * ENOMEM is a potentially transient condition, but the kernel won't + * generally return it unless things are really bad. EAGAIN indicates + * we've reached an resource limit, for which it doesn't make sense to + * retry (counter-intuitively). All other errors indicate a bug. In any + * of these cases, the best we can do is to abort. + */ + abort(); /* will not return */ + } +} + +static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { + aeApiState *state = eventLoop->apidata; + struct timespec timeout, *tsp; + int mask, i; + uint_t nevents; + port_event_t event[MAX_EVENT_BATCHSZ]; + + /* + * If we've returned fd events before, we must re-associate them with the + * port now, before calling port_get(). See the block comment at the top of + * this file for an explanation of why. + */ + for (i = 0; i < state->npending; i++) { + if (state->pending_fds[i] == -1) + /* This fd has since been deleted. */ + continue; + + if (aeApiAssociate("aeApiPoll", state->portfd, + state->pending_fds[i], state->pending_masks[i]) != 0) { + /* See aeApiDelEvent for why this case is fatal. */ + abort(); + } + + state->pending_masks[i] = AE_NONE; + state->pending_fds[i] = -1; + } + + state->npending = 0; + + if (tvp != NULL) { + timeout.tv_sec = tvp->tv_sec; + timeout.tv_nsec = tvp->tv_usec * 1000; + tsp = &timeout; + } else { + tsp = NULL; + } + + /* + * port_getn can return with errno == ETIME having returned some events (!). + * So if we get ETIME, we check nevents, too. + */ + nevents = 1; + if (port_getn(state->portfd, event, MAX_EVENT_BATCHSZ, &nevents, + tsp) == -1 && (errno != ETIME || nevents == 0)) { + if (errno == ETIME || errno == EINTR) + return 0; + + /* Any other error indicates a bug. */ + perror("aeApiPoll: port_get"); + abort(); + } + + state->npending = nevents; + + for (i = 0; i < nevents; i++) { + mask = 0; + if (event[i].portev_events & POLLIN) + mask |= AE_READABLE; + if (event[i].portev_events & POLLOUT) + mask |= AE_WRITABLE; + + eventLoop->fired[i].fd = event[i].portev_object; + eventLoop->fired[i].mask = mask; + + if (evport_debug) + fprintf(stderr, "aeApiPoll: fd %d mask 0x%x\n", + (int)event[i].portev_object, mask); + + state->pending_fds[i] = event[i].portev_object; + state->pending_masks[i] = (uintptr_t)event[i].portev_user; + } + + return nevents; +} + +static char *aeApiName(void) { + return "evport"; +} diff --git a/cpp/src/plasma/thirdparty/ae/ae_kqueue.c b/cpp/src/plasma/thirdparty/ae/ae_kqueue.c new file mode 100644 index 00000000000..6796f4ceb59 --- /dev/null +++ b/cpp/src/plasma/thirdparty/ae/ae_kqueue.c @@ -0,0 +1,138 @@ +/* Kqueue(2)-based ae.c module + * + * Copyright (C) 2009 Harish Mallipeddi - harish.mallipeddi@gmail.com + * 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 Redis 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 +#include +#include + +typedef struct aeApiState { + int kqfd; + struct kevent *events; +} aeApiState; + +static int aeApiCreate(aeEventLoop *eventLoop) { + aeApiState *state = zmalloc(sizeof(aeApiState)); + + if (!state) return -1; + state->events = zmalloc(sizeof(struct kevent)*eventLoop->setsize); + if (!state->events) { + zfree(state); + return -1; + } + state->kqfd = kqueue(); + if (state->kqfd == -1) { + zfree(state->events); + zfree(state); + return -1; + } + eventLoop->apidata = state; + return 0; +} + +static int aeApiResize(aeEventLoop *eventLoop, int setsize) { + aeApiState *state = eventLoop->apidata; + + state->events = zrealloc(state->events, sizeof(struct kevent)*setsize); + return 0; +} + +static void aeApiFree(aeEventLoop *eventLoop) { + aeApiState *state = eventLoop->apidata; + + close(state->kqfd); + zfree(state->events); + zfree(state); +} + +static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + struct kevent ke; + + if (mask & AE_READABLE) { + EV_SET(&ke, fd, EVFILT_READ, EV_ADD, 0, 0, NULL); + if (kevent(state->kqfd, &ke, 1, NULL, 0, NULL) == -1) return -1; + } + if (mask & AE_WRITABLE) { + EV_SET(&ke, fd, EVFILT_WRITE, EV_ADD, 0, 0, NULL); + if (kevent(state->kqfd, &ke, 1, NULL, 0, NULL) == -1) return -1; + } + return 0; +} + +static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + struct kevent ke; + + if (mask & AE_READABLE) { + EV_SET(&ke, fd, EVFILT_READ, EV_DELETE, 0, 0, NULL); + kevent(state->kqfd, &ke, 1, NULL, 0, NULL); + } + if (mask & AE_WRITABLE) { + EV_SET(&ke, fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL); + kevent(state->kqfd, &ke, 1, NULL, 0, NULL); + } +} + +static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { + aeApiState *state = eventLoop->apidata; + int retval, numevents = 0; + + if (tvp != NULL) { + struct timespec timeout; + timeout.tv_sec = tvp->tv_sec; + timeout.tv_nsec = tvp->tv_usec * 1000; + retval = kevent(state->kqfd, NULL, 0, state->events, eventLoop->setsize, + &timeout); + } else { + retval = kevent(state->kqfd, NULL, 0, state->events, eventLoop->setsize, + NULL); + } + + if (retval > 0) { + int j; + + numevents = retval; + for(j = 0; j < numevents; j++) { + int mask = 0; + struct kevent *e = state->events+j; + + if (e->filter == EVFILT_READ) mask |= AE_READABLE; + if (e->filter == EVFILT_WRITE) mask |= AE_WRITABLE; + eventLoop->fired[j].fd = e->ident; + eventLoop->fired[j].mask = mask; + } + } + return numevents; +} + +static char *aeApiName(void) { + return "kqueue"; +} diff --git a/cpp/src/plasma/thirdparty/ae/ae_select.c b/cpp/src/plasma/thirdparty/ae/ae_select.c new file mode 100644 index 00000000000..c039a8ea312 --- /dev/null +++ b/cpp/src/plasma/thirdparty/ae/ae_select.c @@ -0,0 +1,106 @@ +/* Select()-based ae.c module. + * + * Copyright (c) 2009-2012, Salvatore Sanfilippo + * 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 Redis 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 +#include + +typedef struct aeApiState { + fd_set rfds, wfds; + /* We need to have a copy of the fd sets as it's not safe to reuse + * FD sets after select(). */ + fd_set _rfds, _wfds; +} aeApiState; + +static int aeApiCreate(aeEventLoop *eventLoop) { + aeApiState *state = zmalloc(sizeof(aeApiState)); + + if (!state) return -1; + FD_ZERO(&state->rfds); + FD_ZERO(&state->wfds); + eventLoop->apidata = state; + return 0; +} + +static int aeApiResize(aeEventLoop *eventLoop, int setsize) { + /* Just ensure we have enough room in the fd_set type. */ + if (setsize >= FD_SETSIZE) return -1; + return 0; +} + +static void aeApiFree(aeEventLoop *eventLoop) { + zfree(eventLoop->apidata); +} + +static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + + if (mask & AE_READABLE) FD_SET(fd,&state->rfds); + if (mask & AE_WRITABLE) FD_SET(fd,&state->wfds); + return 0; +} + +static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int mask) { + aeApiState *state = eventLoop->apidata; + + if (mask & AE_READABLE) FD_CLR(fd,&state->rfds); + if (mask & AE_WRITABLE) FD_CLR(fd,&state->wfds); +} + +static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) { + aeApiState *state = eventLoop->apidata; + int retval, j, numevents = 0; + + memcpy(&state->_rfds,&state->rfds,sizeof(fd_set)); + memcpy(&state->_wfds,&state->wfds,sizeof(fd_set)); + + retval = select(eventLoop->maxfd+1, + &state->_rfds,&state->_wfds,NULL,tvp); + if (retval > 0) { + for (j = 0; j <= eventLoop->maxfd; j++) { + int mask = 0; + aeFileEvent *fe = &eventLoop->events[j]; + + if (fe->mask == AE_NONE) continue; + if (fe->mask & AE_READABLE && FD_ISSET(j,&state->_rfds)) + mask |= AE_READABLE; + if (fe->mask & AE_WRITABLE && FD_ISSET(j,&state->_wfds)) + mask |= AE_WRITABLE; + eventLoop->fired[numevents].fd = j; + eventLoop->fired[numevents].mask = mask; + numevents++; + } + } + return numevents; +} + +static char *aeApiName(void) { + return "select"; +} diff --git a/cpp/src/plasma/thirdparty/ae/config.h b/cpp/src/plasma/thirdparty/ae/config.h new file mode 100644 index 00000000000..4f8e1ea1bc3 --- /dev/null +++ b/cpp/src/plasma/thirdparty/ae/config.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2009-2012, Salvatore Sanfilippo + * 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 Redis 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. + */ + +#ifndef __CONFIG_H +#define __CONFIG_H + +#ifdef __APPLE__ +#include +#endif + +/* Test for polling API */ +#ifdef __linux__ +#define HAVE_EPOLL 1 +#endif + +#if (defined(__APPLE__) && defined(MAC_OS_X_VERSION_10_6)) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined (__NetBSD__) +#define HAVE_KQUEUE 1 +#endif + +#ifdef __sun +#include +#ifdef _DTRACE_VERSION +#define HAVE_EVPORT 1 +#endif +#endif + + +#endif diff --git a/cpp/src/plasma/thirdparty/ae/zmalloc.h b/cpp/src/plasma/thirdparty/ae/zmalloc.h new file mode 100644 index 00000000000..54c8a69cb2e --- /dev/null +++ b/cpp/src/plasma/thirdparty/ae/zmalloc.h @@ -0,0 +1,16 @@ +#ifndef _ZMALLOC_H +#define _ZMALLOC_H + +#ifndef zmalloc +#define zmalloc malloc +#endif + +#ifndef zfree +#define zfree free +#endif + +#ifndef zrealloc +#define zrealloc realloc +#endif + +#endif /* _ZMALLOC_H */ diff --git a/cpp/src/plasma/thirdparty/dlmalloc.c b/cpp/src/plasma/thirdparty/dlmalloc.c new file mode 100644 index 00000000000..84ccbd28fc4 --- /dev/null +++ b/cpp/src/plasma/thirdparty/dlmalloc.c @@ -0,0 +1,6281 @@ +/* + This is a version (aka dlmalloc) of malloc/free/realloc written by + Doug Lea and released to the public domain, as explained at + http://creativecommons.org/publicdomain/zero/1.0/ Send questions, + comments, complaints, performance data, etc to dl@cs.oswego.edu + +* Version 2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea + Note: There may be an updated version of this malloc obtainable at + ftp://gee.cs.oswego.edu/pub/misc/malloc.c + Check before installing! + +* Quickstart + + This library is all in one file to simplify the most common usage: + ftp it, compile it (-O3), and link it into another program. All of + the compile-time options default to reasonable values for use on + most platforms. You might later want to step through various + compile-time and dynamic tuning options. + + For convenience, an include file for code using this malloc is at: + ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.6.h + You don't really need this .h file unless you call functions not + defined in your system include files. The .h file contains only the + excerpts from this file needed for using this malloc on ANSI C/C++ + systems, so long as you haven't changed compile-time options about + naming and tuning parameters. If you do, then you can create your + own malloc.h that does include all settings by cutting at the point + indicated below. Note that you may already by default be using a C + library containing a malloc that is based on some version of this + malloc (for example in linux). You might still want to use the one + in this file to customize settings or to avoid overheads associated + with library versions. + +* Vital statistics: + + Supported pointer/size_t representation: 4 or 8 bytes + size_t MUST be an unsigned type of the same width as + pointers. (If you are using an ancient system that declares + size_t as a signed type, or need it to be a different width + than pointers, you can use a previous release of this malloc + (e.g. 2.7.2) supporting these.) + + Alignment: 8 bytes (minimum) + This suffices for nearly all current machines and C compilers. + However, you can define MALLOC_ALIGNMENT to be wider than this + if necessary (up to 128bytes), at the expense of using more space. + + Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes) + 8 or 16 bytes (if 8byte sizes) + Each malloced chunk has a hidden word of overhead holding size + and status information, and additional cross-check word + if FOOTERS is defined. + + Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead) + 8-byte ptrs: 32 bytes (including overhead) + + Even a request for zero bytes (i.e., malloc(0)) returns a + pointer to something of the minimum allocatable size. + The maximum overhead wastage (i.e., number of extra bytes + allocated than were requested in malloc) is less than or equal + to the minimum size, except for requests >= mmap_threshold that + are serviced via mmap(), where the worst case wastage is about + 32 bytes plus the remainder from a system page (the minimal + mmap unit); typically 4096 or 8192 bytes. + + Security: static-safe; optionally more or less + The "security" of malloc refers to the ability of malicious + code to accentuate the effects of errors (for example, freeing + space that is not currently malloc'ed or overwriting past the + ends of chunks) in code that calls malloc. This malloc + guarantees not to modify any memory locations below the base of + heap, i.e., static variables, even in the presence of usage + errors. The routines additionally detect most improper frees + and reallocs. All this holds as long as the static bookkeeping + for malloc itself is not corrupted by some other means. This + is only one aspect of security -- these checks do not, and + cannot, detect all possible programming errors. + + If FOOTERS is defined nonzero, then each allocated chunk + carries an additional check word to verify that it was malloced + from its space. These check words are the same within each + execution of a program using malloc, but differ across + executions, so externally crafted fake chunks cannot be + freed. This improves security by rejecting frees/reallocs that + could corrupt heap memory, in addition to the checks preventing + writes to statics that are always on. This may further improve + security at the expense of time and space overhead. (Note that + FOOTERS may also be worth using with MSPACES.) + + By default detected errors cause the program to abort (calling + "abort()"). You can override this to instead proceed past + errors by defining PROCEED_ON_ERROR. In this case, a bad free + has no effect, and a malloc that encounters a bad address + caused by user overwrites will ignore the bad address by + dropping pointers and indices to all known memory. This may + be appropriate for programs that should continue if at all + possible in the face of programming errors, although they may + run out of memory because dropped memory is never reclaimed. + + If you don't like either of these options, you can define + CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything + else. And if if you are sure that your program using malloc has + no errors or vulnerabilities, you can define INSECURE to 1, + which might (or might not) provide a small performance improvement. + + It is also possible to limit the maximum total allocatable + space, using malloc_set_footprint_limit. This is not + designed as a security feature in itself (calls to set limits + are not screened or privileged), but may be useful as one + aspect of a secure implementation. + + Thread-safety: NOT thread-safe unless USE_LOCKS defined non-zero + When USE_LOCKS is defined, each public call to malloc, free, + etc is surrounded with a lock. By default, this uses a plain + pthread mutex, win32 critical section, or a spin-lock if if + available for the platform and not disabled by setting + USE_SPIN_LOCKS=0. However, if USE_RECURSIVE_LOCKS is defined, + recursive versions are used instead (which are not required for + base functionality but may be needed in layered extensions). + Using a global lock is not especially fast, and can be a major + bottleneck. It is designed only to provide minimal protection + in concurrent environments, and to provide a basis for + extensions. If you are using malloc in a concurrent program, + consider instead using nedmalloc + (http://www.nedprod.com/programs/portable/nedmalloc/) or + ptmalloc (See http://www.malloc.de), which are derived from + versions of this malloc. + + System requirements: Any combination of MORECORE and/or MMAP/MUNMAP + This malloc can use unix sbrk or any emulation (invoked using + the CALL_MORECORE macro) and/or mmap/munmap or any emulation + (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system + memory. On most unix systems, it tends to work best if both + MORECORE and MMAP are enabled. On Win32, it uses emulations + based on VirtualAlloc. It also uses common C library functions + like memset. + + Compliance: I believe it is compliant with the Single Unix Specification + (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably + others as well. + +* Overview of algorithms + + This is not the fastest, most space-conserving, most portable, or + most tunable malloc ever written. However it is among the fastest + while also being among the most space-conserving, portable and + tunable. Consistent balance across these factors results in a good + general-purpose allocator for malloc-intensive programs. + + In most ways, this malloc is a best-fit allocator. Generally, it + chooses the best-fitting existing chunk for a request, with ties + broken in approximately least-recently-used order. (This strategy + normally maintains low fragmentation.) However, for requests less + than 256bytes, it deviates from best-fit when there is not an + exactly fitting available chunk by preferring to use space adjacent + to that used for the previous small request, as well as by breaking + ties in approximately most-recently-used order. (These enhance + locality of series of small allocations.) And for very large requests + (>= 256Kb by default), it relies on system memory mapping + facilities, if supported. (This helps avoid carrying around and + possibly fragmenting memory used only for large chunks.) + + All operations (except malloc_stats and mallinfo) have execution + times that are bounded by a constant factor of the number of bits in + a size_t, not counting any clearing in calloc or copying in realloc, + or actions surrounding MORECORE and MMAP that have times + proportional to the number of non-contiguous regions returned by + system allocation routines, which is often just 1. In real-time + applications, you can optionally suppress segment traversals using + NO_SEGMENT_TRAVERSAL, which assures bounded execution even when + system allocators return non-contiguous spaces, at the typical + expense of carrying around more memory and increased fragmentation. + + The implementation is not very modular and seriously overuses + macros. Perhaps someday all C compilers will do as good a job + inlining modular code as can now be done by brute-force expansion, + but now, enough of them seem not to. + + Some compilers issue a lot of warnings about code that is + dead/unreachable only on some platforms, and also about intentional + uses of negation on unsigned types. All known cases of each can be + ignored. + + For a longer but out of date high-level description, see + http://gee.cs.oswego.edu/dl/html/malloc.html + +* MSPACES + If MSPACES is defined, then in addition to malloc, free, etc., + this file also defines mspace_malloc, mspace_free, etc. These + are versions of malloc routines that take an "mspace" argument + obtained using create_mspace, to control all internal bookkeeping. + If ONLY_MSPACES is defined, only these versions are compiled. + So if you would like to use this allocator for only some allocations, + and your system malloc for others, you can compile with + ONLY_MSPACES and then do something like... + static mspace mymspace = create_mspace(0,0); // for example + #define mymalloc(bytes) mspace_malloc(mymspace, bytes) + + (Note: If you only need one instance of an mspace, you can instead + use "USE_DL_PREFIX" to relabel the global malloc.) + + You can similarly create thread-local allocators by storing + mspaces as thread-locals. For example: + static __thread mspace tlms = 0; + void* tlmalloc(size_t bytes) { + if (tlms == 0) tlms = create_mspace(0, 0); + return mspace_malloc(tlms, bytes); + } + void tlfree(void* mem) { mspace_free(tlms, mem); } + + Unless FOOTERS is defined, each mspace is completely independent. + You cannot allocate from one and free to another (although + conformance is only weakly checked, so usage errors are not always + caught). If FOOTERS is defined, then each chunk carries around a tag + indicating its originating mspace, and frees are directed to their + originating spaces. Normally, this requires use of locks. + + ------------------------- Compile-time options --------------------------- + +Be careful in setting #define values for numerical constants of type +size_t. On some systems, literal values are not automatically extended +to size_t precision unless they are explicitly casted. You can also +use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below. + +WIN32 default: defined if _WIN32 defined + Defining WIN32 sets up defaults for MS environment and compilers. + Otherwise defaults are for unix. Beware that there seem to be some + cases where this malloc might not be a pure drop-in replacement for + Win32 malloc: Random-looking failures from Win32 GDI API's (eg; + SetDIBits()) may be due to bugs in some video driver implementations + when pixel buffers are malloc()ed, and the region spans more than + one VirtualAlloc()ed region. Because dlmalloc uses a small (64Kb) + default granularity, pixel buffers may straddle virtual allocation + regions more often than when using the Microsoft allocator. You can + avoid this by using VirtualAlloc() and VirtualFree() for all pixel + buffers rather than using malloc(). If this is not possible, + recompile this malloc with a larger DEFAULT_GRANULARITY. Note: + in cases where MSC and gcc (cygwin) are known to differ on WIN32, + conditions use _MSC_VER to distinguish them. + +DLMALLOC_EXPORT default: extern + Defines how public APIs are declared. If you want to export via a + Windows DLL, you might define this as + #define DLMALLOC_EXPORT extern __declspec(dllexport) + If you want a POSIX ELF shared object, you might use + #define DLMALLOC_EXPORT extern __attribute__((visibility("default"))) + +MALLOC_ALIGNMENT default: (size_t)(2 * sizeof(void *)) + Controls the minimum alignment for malloc'ed chunks. It must be a + power of two and at least 8, even on machines for which smaller + alignments would suffice. It may be defined as larger than this + though. Note however that code and data structures are optimized for + the case of 8-byte alignment. + +MSPACES default: 0 (false) + If true, compile in support for independent allocation spaces. + This is only supported if HAVE_MMAP is true. + +ONLY_MSPACES default: 0 (false) + If true, only compile in mspace versions, not regular versions. + +USE_LOCKS default: 0 (false) + Causes each call to each public routine to be surrounded with + pthread or WIN32 mutex lock/unlock. (If set true, this can be + overridden on a per-mspace basis for mspace versions.) If set to a + non-zero value other than 1, locks are used, but their + implementation is left out, so lock functions must be supplied manually, + as described below. + +USE_SPIN_LOCKS default: 1 iff USE_LOCKS and spin locks available + If true, uses custom spin locks for locking. This is currently + supported only gcc >= 4.1, older gccs on x86 platforms, and recent + MS compilers. Otherwise, posix locks or win32 critical sections are + used. + +USE_RECURSIVE_LOCKS default: not defined + If defined nonzero, uses recursive (aka reentrant) locks, otherwise + uses plain mutexes. This is not required for malloc proper, but may + be needed for layered allocators such as nedmalloc. + +LOCK_AT_FORK default: not defined + If defined nonzero, performs pthread_atfork upon initialization + to initialize child lock while holding parent lock. The implementation + assumes that pthread locks (not custom locks) are being used. In other + cases, you may need to customize the implementation. + +FOOTERS default: 0 + If true, provide extra checking and dispatching by placing + information in the footers of allocated chunks. This adds + space and time overhead. + +INSECURE default: 0 + If true, omit checks for usage errors and heap space overwrites. + +USE_DL_PREFIX default: NOT defined + Causes compiler to prefix all public routines with the string 'dl'. + This can be useful when you only want to use this malloc in one part + of a program, using your regular system malloc elsewhere. + +MALLOC_INSPECT_ALL default: NOT defined + If defined, compiles malloc_inspect_all and mspace_inspect_all, that + perform traversal of all heap space. Unless access to these + functions is otherwise restricted, you probably do not want to + include them in secure implementations. + +ABORT default: defined as abort() + Defines how to abort on failed checks. On most systems, a failed + check cannot die with an "assert" or even print an informative + message, because the underlying print routines in turn call malloc, + which will fail again. Generally, the best policy is to simply call + abort(). It's not very useful to do more than this because many + errors due to overwriting will show up as address faults (null, odd + addresses etc) rather than malloc-triggered checks, so will also + abort. Also, most compilers know that abort() does not return, so + can better optimize code conditionally calling it. + +PROCEED_ON_ERROR default: defined as 0 (false) + Controls whether detected bad addresses cause them to bypassed + rather than aborting. If set, detected bad arguments to free and + realloc are ignored. And all bookkeeping information is zeroed out + upon a detected overwrite of freed heap space, thus losing the + ability to ever return it from malloc again, but enabling the + application to proceed. If PROCEED_ON_ERROR is defined, the + static variable malloc_corruption_error_count is compiled in + and can be examined to see if errors have occurred. This option + generates slower code than the default abort policy. + +DEBUG default: NOT defined + The DEBUG setting is mainly intended for people trying to modify + this code or diagnose problems when porting to new platforms. + However, it may also be able to better isolate user errors than just + using runtime checks. The assertions in the check routines spell + out in more detail the assumptions and invariants underlying the + algorithms. The checking is fairly extensive, and will slow down + execution noticeably. Calling malloc_stats or mallinfo with DEBUG + set will attempt to check every non-mmapped allocated and free chunk + in the course of computing the summaries. + +ABORT_ON_ASSERT_FAILURE default: defined as 1 (true) + Debugging assertion failures can be nearly impossible if your + version of the assert macro causes malloc to be called, which will + lead to a cascade of further failures, blowing the runtime stack. + ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(), + which will usually make debugging easier. + +MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32 + The action to take before "return 0" when malloc fails to be able to + return memory because there is none available. + +HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES + True if this system supports sbrk or an emulation of it. + +MORECORE default: sbrk + The name of the sbrk-style system routine to call to obtain more + memory. See below for guidance on writing custom MORECORE + functions. The type of the argument to sbrk/MORECORE varies across + systems. It cannot be size_t, because it supports negative + arguments, so it is normally the signed type of the same width as + size_t (sometimes declared as "intptr_t"). It doesn't much matter + though. Internally, we only call it with arguments less than half + the max value of a size_t, which should work across all reasonable + possibilities, although sometimes generating compiler warnings. + +MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE + If true, take advantage of fact that consecutive calls to MORECORE + with positive arguments always return contiguous increasing + addresses. This is true of unix sbrk. It does not hurt too much to + set it true anyway, since malloc copes with non-contiguities. + Setting it false when definitely non-contiguous saves time + and possibly wasted space it would take to discover this though. + +MORECORE_CANNOT_TRIM default: NOT defined + True if MORECORE cannot release space back to the system when given + negative arguments. This is generally necessary only if you are + using a hand-crafted MORECORE function that cannot handle negative + arguments. + +NO_SEGMENT_TRAVERSAL default: 0 + If non-zero, suppresses traversals of memory segments + returned by either MORECORE or CALL_MMAP. This disables + merging of segments that are contiguous, and selectively + releasing them to the OS if unused, but bounds execution times. + +HAVE_MMAP default: 1 (true) + True if this system supports mmap or an emulation of it. If so, and + HAVE_MORECORE is not true, MMAP is used for all system + allocation. If set and HAVE_MORECORE is true as well, MMAP is + primarily used to directly allocate very large blocks. It is also + used as a backup strategy in cases where MORECORE fails to provide + space from system. Note: A single call to MUNMAP is assumed to be + able to unmap memory that may have be allocated using multiple calls + to MMAP, so long as they are adjacent. + +HAVE_MREMAP default: 1 on linux, else 0 + If true realloc() uses mremap() to re-allocate large blocks and + extend or shrink allocation spaces. + +MMAP_CLEARS default: 1 except on WINCE. + True if mmap clears memory so calloc doesn't need to. This is true + for standard unix mmap using /dev/zero and on WIN32 except for WINCE. + +USE_BUILTIN_FFS default: 0 (i.e., not used) + Causes malloc to use the builtin ffs() function to compute indices. + Some compilers may recognize and intrinsify ffs to be faster than the + supplied C version. Also, the case of x86 using gcc is special-cased + to an asm instruction, so is already as fast as it can be, and so + this setting has no effect. Similarly for Win32 under recent MS compilers. + (On most x86s, the asm version is only slightly faster than the C version.) + +malloc_getpagesize default: derive from system includes, or 4096. + The system page size. To the extent possible, this malloc manages + memory from the system in page-size units. This may be (and + usually is) a function rather than a constant. This is ignored + if WIN32, where page size is determined using getSystemInfo during + initialization. + +USE_DEV_RANDOM default: 0 (i.e., not used) + Causes malloc to use /dev/random to initialize secure magic seed for + stamping footers. Otherwise, the current time is used. + +NO_MALLINFO default: 0 + If defined, don't compile "mallinfo". This can be a simple way + of dealing with mismatches between system declarations and + those in this file. + +MALLINFO_FIELD_TYPE default: size_t + The type of the fields in the mallinfo struct. This was originally + defined as "int" in SVID etc, but is more usefully defined as + size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set + +NO_MALLOC_STATS default: 0 + If defined, don't compile "malloc_stats". This avoids calls to + fprintf and bringing in stdio dependencies you might not want. + +REALLOC_ZERO_BYTES_FREES default: not defined + This should be set if a call to realloc with zero bytes should + be the same as a call to free. Some people think it should. Otherwise, + since this malloc returns a unique pointer for malloc(0), so does + realloc(p, 0). + +LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H +LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H +LACKS_STDLIB_H LACKS_SCHED_H LACKS_TIME_H default: NOT defined unless on WIN32 + Define these if your system does not have these header files. + You might need to manually insert some of the declarations they provide. + +DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS, + system_info.dwAllocationGranularity in WIN32, + otherwise 64K. + Also settable using mallopt(M_GRANULARITY, x) + The unit for allocating and deallocating memory from the system. On + most systems with contiguous MORECORE, there is no reason to + make this more than a page. However, systems with MMAP tend to + either require or encourage larger granularities. You can increase + this value to prevent system allocation functions to be called so + often, especially if they are slow. The value must be at least one + page and must be a power of two. Setting to 0 causes initialization + to either page size or win32 region size. (Note: In previous + versions of malloc, the equivalent of this option was called + "TOP_PAD") + +DEFAULT_TRIM_THRESHOLD default: 2MB + Also settable using mallopt(M_TRIM_THRESHOLD, x) + The maximum amount of unused top-most memory to keep before + releasing via malloc_trim in free(). Automatic trimming is mainly + useful in long-lived programs using contiguous MORECORE. Because + trimming via sbrk can be slow on some systems, and can sometimes be + wasteful (in cases where programs immediately afterward allocate + more large chunks) the value should be high enough so that your + overall system performance would improve by releasing this much + memory. As a rough guide, you might set to a value close to the + average size of a process (program) running on your system. + Releasing this much memory would allow such a process to run in + memory. Generally, it is worth tuning trim thresholds when a + program undergoes phases where several large chunks are allocated + and released in ways that can reuse each other's storage, perhaps + mixed with phases where there are no such chunks at all. The trim + value must be greater than page size to have any useful effect. To + disable trimming completely, you can set to MAX_SIZE_T. Note that the trick + some people use of mallocing a huge space and then freeing it at + program startup, in an attempt to reserve system memory, doesn't + have the intended effect under automatic trimming, since that memory + will immediately be returned to the system. + +DEFAULT_MMAP_THRESHOLD default: 256K + Also settable using mallopt(M_MMAP_THRESHOLD, x) + The request size threshold for using MMAP to directly service a + request. Requests of at least this size that cannot be allocated + using already-existing space will be serviced via mmap. (If enough + normal freed space already exists it is used instead.) Using mmap + segregates relatively large chunks of memory so that they can be + individually obtained and released from the host system. A request + serviced through mmap is never reused by any other request (at least + not directly; the system may just so happen to remap successive + requests to the same locations). Segregating space in this way has + the benefits that: Mmapped space can always be individually released + back to the system, which helps keep the system level memory demands + of a long-lived program low. Also, mapped memory doesn't become + `locked' between other chunks, as can happen with normally allocated + chunks, which means that even trimming via malloc_trim would not + release them. However, it has the disadvantage that the space + cannot be reclaimed, consolidated, and then used to service later + requests, as happens with normal chunks. The advantages of mmap + nearly always outweigh disadvantages for "large" chunks, but the + value of "large" may vary across systems. The default is an + empirically derived value that works well in most systems. You can + disable mmap by setting to MAX_SIZE_T. + +MAX_RELEASE_CHECK_RATE default: 4095 unless not HAVE_MMAP + The number of consolidated frees between checks to release + unused segments when freeing. When using non-contiguous segments, + especially with multiple mspaces, checking only for topmost space + doesn't always suffice to trigger trimming. To compensate for this, + free() will, with a period of MAX_RELEASE_CHECK_RATE (or the + current number of segments, if greater) try to release unused + segments to the OS when freeing chunks that result in + consolidation. The best value for this parameter is a compromise + between slowing down frees with relatively costly checks that + rarely trigger versus holding on to unused memory. To effectively + disable, set to MAX_SIZE_T. This may lead to a very slight speed + improvement at the expense of carrying around more memory. +*/ + +/* Version identifier to allow people to support multiple versions */ +#ifndef DLMALLOC_VERSION +#define DLMALLOC_VERSION 20806 +#endif /* DLMALLOC_VERSION */ + +#ifndef DLMALLOC_EXPORT +#define DLMALLOC_EXPORT extern +#endif + +#ifndef WIN32 +#ifdef _WIN32 +#define WIN32 1 +#endif /* _WIN32 */ +#ifdef _WIN32_WCE +#define LACKS_FCNTL_H +#define WIN32 1 +#endif /* _WIN32_WCE */ +#endif /* WIN32 */ +#ifdef WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#include +#define HAVE_MMAP 1 +#define HAVE_MORECORE 0 +#define LACKS_UNISTD_H +#define LACKS_SYS_PARAM_H +#define LACKS_SYS_MMAN_H +#define LACKS_STRING_H +#define LACKS_STRINGS_H +#define LACKS_SYS_TYPES_H +#define LACKS_ERRNO_H +#define LACKS_SCHED_H +#ifndef MALLOC_FAILURE_ACTION +#define MALLOC_FAILURE_ACTION +#endif /* MALLOC_FAILURE_ACTION */ +#ifndef MMAP_CLEARS +#ifdef _WIN32_WCE /* WINCE reportedly does not clear */ +#define MMAP_CLEARS 0 +#else +#define MMAP_CLEARS 1 +#endif /* _WIN32_WCE */ +#endif /*MMAP_CLEARS */ +#endif /* WIN32 */ + +#if defined(DARWIN) || defined(_DARWIN) +/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */ +#ifndef HAVE_MORECORE +#define HAVE_MORECORE 0 +#define HAVE_MMAP 1 +/* OSX allocators provide 16 byte alignment */ +#ifndef MALLOC_ALIGNMENT +#define MALLOC_ALIGNMENT ((size_t)16U) +#endif +#endif /* HAVE_MORECORE */ +#endif /* DARWIN */ + +#ifndef LACKS_SYS_TYPES_H +#include /* For size_t */ +#endif /* LACKS_SYS_TYPES_H */ + +/* The maximum possible size_t value has all bits set */ +#define MAX_SIZE_T (~(size_t)0) + +#ifndef USE_LOCKS /* ensure true if spin or recursive locks set */ +#define USE_LOCKS ((defined(USE_SPIN_LOCKS) && USE_SPIN_LOCKS != 0) || \ + (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0)) +#endif /* USE_LOCKS */ + +#if USE_LOCKS /* Spin locks for gcc >= 4.1, older gcc on x86, MSC >= 1310 */ +#if ((defined(__GNUC__) && \ + ((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \ + defined(__i386__) || defined(__x86_64__))) || \ + (defined(_MSC_VER) && _MSC_VER>=1310)) +#ifndef USE_SPIN_LOCKS +#define USE_SPIN_LOCKS 1 +#endif /* USE_SPIN_LOCKS */ +#elif USE_SPIN_LOCKS +#error "USE_SPIN_LOCKS defined without implementation" +#endif /* ... locks available... */ +#elif !defined(USE_SPIN_LOCKS) +#define USE_SPIN_LOCKS 0 +#endif /* USE_LOCKS */ + +#ifndef ONLY_MSPACES +#define ONLY_MSPACES 0 +#endif /* ONLY_MSPACES */ +#ifndef MSPACES +#if ONLY_MSPACES +#define MSPACES 1 +#else /* ONLY_MSPACES */ +#define MSPACES 0 +#endif /* ONLY_MSPACES */ +#endif /* MSPACES */ +#ifndef MALLOC_ALIGNMENT +#define MALLOC_ALIGNMENT ((size_t)(2 * sizeof(void *))) +#endif /* MALLOC_ALIGNMENT */ +#ifndef FOOTERS +#define FOOTERS 0 +#endif /* FOOTERS */ +#ifndef ABORT +#define ABORT abort() +#endif /* ABORT */ +#ifndef ABORT_ON_ASSERT_FAILURE +#define ABORT_ON_ASSERT_FAILURE 1 +#endif /* ABORT_ON_ASSERT_FAILURE */ +#ifndef PROCEED_ON_ERROR +#define PROCEED_ON_ERROR 0 +#endif /* PROCEED_ON_ERROR */ + +#ifndef INSECURE +#define INSECURE 0 +#endif /* INSECURE */ +#ifndef MALLOC_INSPECT_ALL +#define MALLOC_INSPECT_ALL 0 +#endif /* MALLOC_INSPECT_ALL */ +#ifndef HAVE_MMAP +#define HAVE_MMAP 1 +#endif /* HAVE_MMAP */ +#ifndef MMAP_CLEARS +#define MMAP_CLEARS 1 +#endif /* MMAP_CLEARS */ +#ifndef HAVE_MREMAP +#ifdef linux +#define HAVE_MREMAP 1 +#define _GNU_SOURCE /* Turns on mremap() definition */ +#else /* linux */ +#define HAVE_MREMAP 0 +#endif /* linux */ +#endif /* HAVE_MREMAP */ +#ifndef MALLOC_FAILURE_ACTION +#define MALLOC_FAILURE_ACTION errno = ENOMEM; +#endif /* MALLOC_FAILURE_ACTION */ +#ifndef HAVE_MORECORE +#if ONLY_MSPACES +#define HAVE_MORECORE 0 +#else /* ONLY_MSPACES */ +#define HAVE_MORECORE 1 +#endif /* ONLY_MSPACES */ +#endif /* HAVE_MORECORE */ +#if !HAVE_MORECORE +#define MORECORE_CONTIGUOUS 0 +#else /* !HAVE_MORECORE */ +#define MORECORE_DEFAULT sbrk +#ifndef MORECORE_CONTIGUOUS +#define MORECORE_CONTIGUOUS 1 +#endif /* MORECORE_CONTIGUOUS */ +#endif /* HAVE_MORECORE */ +#ifndef DEFAULT_GRANULARITY +#if (MORECORE_CONTIGUOUS || defined(WIN32)) +#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */ +#else /* MORECORE_CONTIGUOUS */ +#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U) +#endif /* MORECORE_CONTIGUOUS */ +#endif /* DEFAULT_GRANULARITY */ +#ifndef DEFAULT_TRIM_THRESHOLD +#ifndef MORECORE_CANNOT_TRIM +#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U) +#else /* MORECORE_CANNOT_TRIM */ +#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T +#endif /* MORECORE_CANNOT_TRIM */ +#endif /* DEFAULT_TRIM_THRESHOLD */ +#ifndef DEFAULT_MMAP_THRESHOLD +#if HAVE_MMAP +#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U) +#else /* HAVE_MMAP */ +#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T +#endif /* HAVE_MMAP */ +#endif /* DEFAULT_MMAP_THRESHOLD */ +#ifndef MAX_RELEASE_CHECK_RATE +#if HAVE_MMAP +#define MAX_RELEASE_CHECK_RATE 4095 +#else +#define MAX_RELEASE_CHECK_RATE MAX_SIZE_T +#endif /* HAVE_MMAP */ +#endif /* MAX_RELEASE_CHECK_RATE */ +#ifndef USE_BUILTIN_FFS +#define USE_BUILTIN_FFS 0 +#endif /* USE_BUILTIN_FFS */ +#ifndef USE_DEV_RANDOM +#define USE_DEV_RANDOM 0 +#endif /* USE_DEV_RANDOM */ +#ifndef NO_MALLINFO +#define NO_MALLINFO 0 +#endif /* NO_MALLINFO */ +#ifndef MALLINFO_FIELD_TYPE +#define MALLINFO_FIELD_TYPE size_t +#endif /* MALLINFO_FIELD_TYPE */ +#ifndef NO_MALLOC_STATS +#define NO_MALLOC_STATS 0 +#endif /* NO_MALLOC_STATS */ +#ifndef NO_SEGMENT_TRAVERSAL +#define NO_SEGMENT_TRAVERSAL 0 +#endif /* NO_SEGMENT_TRAVERSAL */ + +/* + mallopt tuning options. SVID/XPG defines four standard parameter + numbers for mallopt, normally defined in malloc.h. None of these + are used in this malloc, so setting them has no effect. But this + malloc does support the following options. +*/ + +#define M_TRIM_THRESHOLD (-1) +#define M_GRANULARITY (-2) +#define M_MMAP_THRESHOLD (-3) + +/* ------------------------ Mallinfo declarations ------------------------ */ + +#if !NO_MALLINFO +/* + This version of malloc supports the standard SVID/XPG mallinfo + routine that returns a struct containing usage properties and + statistics. It should work on any system that has a + /usr/include/malloc.h defining struct mallinfo. The main + declaration needed is the mallinfo struct that is returned (by-copy) + by mallinfo(). The malloinfo struct contains a bunch of fields that + are not even meaningful in this version of malloc. These fields are + are instead filled by mallinfo() with other numbers that might be of + interest. + + HAVE_USR_INCLUDE_MALLOC_H should be set if you have a + /usr/include/malloc.h file that includes a declaration of struct + mallinfo. If so, it is included; else a compliant version is + declared below. These must be precisely the same for mallinfo() to + work. The original SVID version of this struct, defined on most + systems with mallinfo, declares all fields as ints. But some others + define as unsigned long. If your system defines the fields using a + type of different width than listed here, you MUST #include your + system version and #define HAVE_USR_INCLUDE_MALLOC_H. +*/ + +/* #define HAVE_USR_INCLUDE_MALLOC_H */ + +#ifdef HAVE_USR_INCLUDE_MALLOC_H +#include "/usr/include/malloc.h" +#else /* HAVE_USR_INCLUDE_MALLOC_H */ +#ifndef STRUCT_MALLINFO_DECLARED +/* HP-UX (and others?) redefines mallinfo unless _STRUCT_MALLINFO is defined */ +#define _STRUCT_MALLINFO +#define STRUCT_MALLINFO_DECLARED 1 +struct mallinfo { + MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ + MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ + MALLINFO_FIELD_TYPE smblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ + MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ + MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ + MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ + MALLINFO_FIELD_TYPE fordblks; /* total free space */ + MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ +}; +#endif /* STRUCT_MALLINFO_DECLARED */ +#endif /* HAVE_USR_INCLUDE_MALLOC_H */ +#endif /* NO_MALLINFO */ + +/* + Try to persuade compilers to inline. The most critical functions for + inlining are defined as macros, so these aren't used for them. +*/ + +#ifndef FORCEINLINE + #if defined(__GNUC__) +#define FORCEINLINE __inline __attribute__ ((always_inline)) + #elif defined(_MSC_VER) + #define FORCEINLINE __forceinline + #endif +#endif +#ifndef NOINLINE + #if defined(__GNUC__) + #define NOINLINE __attribute__ ((noinline)) + #elif defined(_MSC_VER) + #define NOINLINE __declspec(noinline) + #else + #define NOINLINE + #endif +#endif + +#ifdef __cplusplus +extern "C" { +#ifndef FORCEINLINE + #define FORCEINLINE inline +#endif +#endif /* __cplusplus */ +#ifndef FORCEINLINE + #define FORCEINLINE +#endif + +#if !ONLY_MSPACES + +/* ------------------- Declarations of public routines ------------------- */ + +#ifndef USE_DL_PREFIX +#define dlcalloc calloc +#define dlfree free +#define dlmalloc malloc +#define dlmemalign memalign +#define dlposix_memalign posix_memalign +#define dlrealloc realloc +#define dlrealloc_in_place realloc_in_place +#define dlvalloc valloc +#define dlpvalloc pvalloc +#define dlmallinfo mallinfo +#define dlmallopt mallopt +#define dlmalloc_trim malloc_trim +#define dlmalloc_stats malloc_stats +#define dlmalloc_usable_size malloc_usable_size +#define dlmalloc_footprint malloc_footprint +#define dlmalloc_max_footprint malloc_max_footprint +#define dlmalloc_footprint_limit malloc_footprint_limit +#define dlmalloc_set_footprint_limit malloc_set_footprint_limit +#define dlmalloc_inspect_all malloc_inspect_all +#define dlindependent_calloc independent_calloc +#define dlindependent_comalloc independent_comalloc +#define dlbulk_free bulk_free +#endif /* USE_DL_PREFIX */ + +/* + malloc(size_t n) + Returns a pointer to a newly allocated chunk of at least n bytes, or + null if no space is available, in which case errno is set to ENOMEM + on ANSI C systems. + + If n is zero, malloc returns a minimum-sized chunk. (The minimum + size is 16 bytes on most 32bit systems, and 32 bytes on 64bit + systems.) Note that size_t is an unsigned type, so calls with + arguments that would be negative if signed are interpreted as + requests for huge amounts of space, which will often fail. The + maximum supported value of n differs across systems, but is in all + cases less than the maximum representable value of a size_t. +*/ +DLMALLOC_EXPORT void* dlmalloc(size_t); + +/* + free(void* p) + Releases the chunk of memory pointed to by p, that had been previously + allocated using malloc or a related routine such as realloc. + It has no effect if p is null. If p was not malloced or already + freed, free(p) will by default cause the current program to abort. +*/ +DLMALLOC_EXPORT void dlfree(void*); + +/* + calloc(size_t n_elements, size_t element_size); + Returns a pointer to n_elements * element_size bytes, with all locations + set to zero. +*/ +DLMALLOC_EXPORT void* dlcalloc(size_t, size_t); + +/* + realloc(void* p, size_t n) + Returns a pointer to a chunk of size n that contains the same data + as does chunk p up to the minimum of (n, p's size) bytes, or null + if no space is available. + + The returned pointer may or may not be the same as p. The algorithm + prefers extending p in most cases when possible, otherwise it + employs the equivalent of a malloc-copy-free sequence. + + If p is null, realloc is equivalent to malloc. + + If space is not available, realloc returns null, errno is set (if on + ANSI) and p is NOT freed. + + if n is for fewer bytes than already held by p, the newly unused + space is lopped off and freed if possible. realloc with a size + argument of zero (re)allocates a minimum-sized chunk. + + The old unix realloc convention of allowing the last-free'd chunk + to be used as an argument to realloc is not supported. +*/ +DLMALLOC_EXPORT void* dlrealloc(void*, size_t); + +/* + realloc_in_place(void* p, size_t n) + Resizes the space allocated for p to size n, only if this can be + done without moving p (i.e., only if there is adjacent space + available if n is greater than p's current allocated size, or n is + less than or equal to p's size). This may be used instead of plain + realloc if an alternative allocation strategy is needed upon failure + to expand space; for example, reallocation of a buffer that must be + memory-aligned or cleared. You can use realloc_in_place to trigger + these alternatives only when needed. + + Returns p if successful; otherwise null. +*/ +DLMALLOC_EXPORT void* dlrealloc_in_place(void*, size_t); + +/* + memalign(size_t alignment, size_t n); + Returns a pointer to a newly allocated chunk of n bytes, aligned + in accord with the alignment argument. + + The alignment argument should be a power of two. If the argument is + not a power of two, the nearest greater power is used. + 8-byte alignment is guaranteed by normal malloc calls, so don't + bother calling memalign with an argument of 8 or less. + + Overreliance on memalign is a sure way to fragment space. +*/ +DLMALLOC_EXPORT void* dlmemalign(size_t, size_t); + +/* + int posix_memalign(void** pp, size_t alignment, size_t n); + Allocates a chunk of n bytes, aligned in accord with the alignment + argument. Differs from memalign only in that it (1) assigns the + allocated memory to *pp rather than returning it, (2) fails and + returns EINVAL if the alignment is not a power of two (3) fails and + returns ENOMEM if memory cannot be allocated. +*/ +DLMALLOC_EXPORT int dlposix_memalign(void**, size_t, size_t); + +/* + valloc(size_t n); + Equivalent to memalign(pagesize, n), where pagesize is the page + size of the system. If the pagesize is unknown, 4096 is used. +*/ +DLMALLOC_EXPORT void* dlvalloc(size_t); + +/* + mallopt(int parameter_number, int parameter_value) + Sets tunable parameters The format is to provide a + (parameter-number, parameter-value) pair. mallopt then sets the + corresponding parameter to the argument value if it can (i.e., so + long as the value is meaningful), and returns 1 if successful else + 0. To workaround the fact that mallopt is specified to use int, + not size_t parameters, the value -1 is specially treated as the + maximum unsigned size_t value. + + SVID/XPG/ANSI defines four standard param numbers for mallopt, + normally defined in malloc.h. None of these are use in this malloc, + so setting them has no effect. But this malloc also supports other + options in mallopt. See below for details. Briefly, supported + parameters are as follows (listed defaults are for "typical" + configurations). + + Symbol param # default allowed param values + M_TRIM_THRESHOLD -1 2*1024*1024 any (-1 disables) + M_GRANULARITY -2 page size any power of 2 >= page size + M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support) +*/ +DLMALLOC_EXPORT int dlmallopt(int, int); + +/* + malloc_footprint(); + Returns the number of bytes obtained from the system. The total + number of bytes allocated by malloc, realloc etc., is less than this + value. Unlike mallinfo, this function returns only a precomputed + result, so can be called frequently to monitor memory consumption. + Even if locks are otherwise defined, this function does not use them, + so results might not be up to date. +*/ +DLMALLOC_EXPORT size_t dlmalloc_footprint(void); + +/* + malloc_max_footprint(); + Returns the maximum number of bytes obtained from the system. This + value will be greater than current footprint if deallocated space + has been reclaimed by the system. The peak number of bytes allocated + by malloc, realloc etc., is less than this value. Unlike mallinfo, + this function returns only a precomputed result, so can be called + frequently to monitor memory consumption. Even if locks are + otherwise defined, this function does not use them, so results might + not be up to date. +*/ +DLMALLOC_EXPORT size_t dlmalloc_max_footprint(void); + +/* + malloc_footprint_limit(); + Returns the number of bytes that the heap is allowed to obtain from + the system, returning the last value returned by + malloc_set_footprint_limit, or the maximum size_t value if + never set. The returned value reflects a permission. There is no + guarantee that this number of bytes can actually be obtained from + the system. +*/ +DLMALLOC_EXPORT size_t dlmalloc_footprint_limit(); + +/* + malloc_set_footprint_limit(); + Sets the maximum number of bytes to obtain from the system, causing + failure returns from malloc and related functions upon attempts to + exceed this value. The argument value may be subject to page + rounding to an enforceable limit; this actual value is returned. + Using an argument of the maximum possible size_t effectively + disables checks. If the argument is less than or equal to the + current malloc_footprint, then all future allocations that require + additional system memory will fail. However, invocation cannot + retroactively deallocate existing used memory. +*/ +DLMALLOC_EXPORT size_t dlmalloc_set_footprint_limit(size_t bytes); + +#if MALLOC_INSPECT_ALL +/* + malloc_inspect_all(void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg); + Traverses the heap and calls the given handler for each managed + region, skipping all bytes that are (or may be) used for bookkeeping + purposes. Traversal does not include include chunks that have been + directly memory mapped. Each reported region begins at the start + address, and continues up to but not including the end address. The + first used_bytes of the region contain allocated data. If + used_bytes is zero, the region is unallocated. The handler is + invoked with the given callback argument. If locks are defined, they + are held during the entire traversal. It is a bad idea to invoke + other malloc functions from within the handler. + + For example, to count the number of in-use chunks with size greater + than 1000, you could write: + static int count = 0; + void count_chunks(void* start, void* end, size_t used, void* arg) { + if (used >= 1000) ++count; + } + then: + malloc_inspect_all(count_chunks, NULL); + + malloc_inspect_all is compiled only if MALLOC_INSPECT_ALL is defined. +*/ +DLMALLOC_EXPORT void dlmalloc_inspect_all(void(*handler)(void*, void *, size_t, void*), + void* arg); + +#endif /* MALLOC_INSPECT_ALL */ + +#if !NO_MALLINFO +/* + mallinfo() + Returns (by copy) a struct containing various summary statistics: + + arena: current total non-mmapped bytes allocated from system + ordblks: the number of free chunks + smblks: always zero. + hblks: current number of mmapped regions + hblkhd: total bytes held in mmapped regions + usmblks: the maximum total allocated space. This will be greater + than current total if trimming has occurred. + fsmblks: always zero + uordblks: current total allocated space (normal or mmapped) + fordblks: total free space + keepcost: the maximum number of bytes that could ideally be released + back to system via malloc_trim. ("ideally" means that + it ignores page restrictions etc.) + + Because these fields are ints, but internal bookkeeping may + be kept as longs, the reported values may wrap around zero and + thus be inaccurate. +*/ +DLMALLOC_EXPORT struct mallinfo dlmallinfo(void); +#endif /* NO_MALLINFO */ + +/* + independent_calloc(size_t n_elements, size_t element_size, void* chunks[]); + + independent_calloc is similar to calloc, but instead of returning a + single cleared space, it returns an array of pointers to n_elements + independent elements that can hold contents of size elem_size, each + of which starts out cleared, and can be independently freed, + realloc'ed etc. The elements are guaranteed to be adjacently + allocated (this is not guaranteed to occur with multiple callocs or + mallocs), which may also improve cache locality in some + applications. + + The "chunks" argument is optional (i.e., may be null, which is + probably the most typical usage). If it is null, the returned array + is itself dynamically allocated and should also be freed when it is + no longer needed. Otherwise, the chunks array must be of at least + n_elements in length. It is filled in with the pointers to the + chunks. + + In either case, independent_calloc returns this pointer array, or + null if the allocation failed. If n_elements is zero and "chunks" + is null, it returns a chunk representing an array with zero elements + (which should be freed if not wanted). + + Each element must be freed when it is no longer needed. This can be + done all at once using bulk_free. + + independent_calloc simplifies and speeds up implementations of many + kinds of pools. It may also be useful when constructing large data + structures that initially have a fixed number of fixed-sized nodes, + but the number is not known at compile time, and some of the nodes + may later need to be freed. For example: + + struct Node { int item; struct Node* next; }; + + struct Node* build_list() { + struct Node** pool; + int n = read_number_of_nodes_needed(); + if (n <= 0) return 0; + pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0); + if (pool == 0) die(); + // organize into a linked list... + struct Node* first = pool[0]; + for (i = 0; i < n-1; ++i) + pool[i]->next = pool[i+1]; + free(pool); // Can now free the array (or not, if it is needed later) + return first; + } +*/ +DLMALLOC_EXPORT void** dlindependent_calloc(size_t, size_t, void**); + +/* + independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); + + independent_comalloc allocates, all at once, a set of n_elements + chunks with sizes indicated in the "sizes" array. It returns + an array of pointers to these elements, each of which can be + independently freed, realloc'ed etc. The elements are guaranteed to + be adjacently allocated (this is not guaranteed to occur with + multiple callocs or mallocs), which may also improve cache locality + in some applications. + + The "chunks" argument is optional (i.e., may be null). If it is null + the returned array is itself dynamically allocated and should also + be freed when it is no longer needed. Otherwise, the chunks array + must be of at least n_elements in length. It is filled in with the + pointers to the chunks. + + In either case, independent_comalloc returns this pointer array, or + null if the allocation failed. If n_elements is zero and chunks is + null, it returns a chunk representing an array with zero elements + (which should be freed if not wanted). + + Each element must be freed when it is no longer needed. This can be + done all at once using bulk_free. + + independent_comallac differs from independent_calloc in that each + element may have a different size, and also that it does not + automatically clear elements. + + independent_comalloc can be used to speed up allocation in cases + where several structs or objects must always be allocated at the + same time. For example: + + struct Head { ... } + struct Foot { ... } + + void send_message(char* msg) { + int msglen = strlen(msg); + size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) }; + void* chunks[3]; + if (independent_comalloc(3, sizes, chunks) == 0) + die(); + struct Head* head = (struct Head*)(chunks[0]); + char* body = (char*)(chunks[1]); + struct Foot* foot = (struct Foot*)(chunks[2]); + // ... + } + + In general though, independent_comalloc is worth using only for + larger values of n_elements. For small values, you probably won't + detect enough difference from series of malloc calls to bother. + + Overuse of independent_comalloc can increase overall memory usage, + since it cannot reuse existing noncontiguous small chunks that + might be available for some of the elements. +*/ +DLMALLOC_EXPORT void** dlindependent_comalloc(size_t, size_t*, void**); + +/* + bulk_free(void* array[], size_t n_elements) + Frees and clears (sets to null) each non-null pointer in the given + array. This is likely to be faster than freeing them one-by-one. + If footers are used, pointers that have been allocated in different + mspaces are not freed or cleared, and the count of all such pointers + is returned. For large arrays of pointers with poor locality, it + may be worthwhile to sort this array before calling bulk_free. +*/ +DLMALLOC_EXPORT size_t dlbulk_free(void**, size_t n_elements); + +/* + pvalloc(size_t n); + Equivalent to valloc(minimum-page-that-holds(n)), that is, + round up n to nearest pagesize. + */ +DLMALLOC_EXPORT void* dlpvalloc(size_t); + +/* + malloc_trim(size_t pad); + + If possible, gives memory back to the system (via negative arguments + to sbrk) if there is unused memory at the `high' end of the malloc + pool or in unused MMAP segments. You can call this after freeing + large blocks of memory to potentially reduce the system-level memory + requirements of a program. However, it cannot guarantee to reduce + memory. Under some allocation patterns, some large free blocks of + memory will be locked between two used chunks, so they cannot be + given back to the system. + + The `pad' argument to malloc_trim represents the amount of free + trailing space to leave untrimmed. If this argument is zero, only + the minimum amount of memory to maintain internal data structures + will be left. Non-zero arguments can be supplied to maintain enough + trailing space to service future expected allocations without having + to re-obtain memory from the system. + + Malloc_trim returns 1 if it actually released any memory, else 0. +*/ +DLMALLOC_EXPORT int dlmalloc_trim(size_t); + +/* + malloc_stats(); + Prints on stderr the amount of space obtained from the system (both + via sbrk and mmap), the maximum amount (which may be more than + current if malloc_trim and/or munmap got called), and the current + number of bytes allocated via malloc (or realloc, etc) but not yet + freed. Note that this is the number of bytes allocated, not the + number requested. It will be larger than the number requested + because of alignment and bookkeeping overhead. Because it includes + alignment wastage as being in use, this figure may be greater than + zero even when no user-level chunks are allocated. + + The reported current and maximum system memory can be inaccurate if + a program makes other calls to system memory allocation functions + (normally sbrk) outside of malloc. + + malloc_stats prints only the most commonly interesting statistics. + More information can be obtained by calling mallinfo. +*/ +DLMALLOC_EXPORT void dlmalloc_stats(void); + +/* + malloc_usable_size(void* p); + + Returns the number of bytes you can actually use in + an allocated chunk, which may be more than you requested (although + often not) due to alignment and minimum size constraints. + You can use this many bytes without worrying about + overwriting other allocated objects. This is not a particularly great + programming practice. malloc_usable_size can be more useful in + debugging and assertions, for example: + + p = malloc(n); + assert(malloc_usable_size(p) >= 256); +*/ +size_t dlmalloc_usable_size(void*); + +#endif /* ONLY_MSPACES */ + +#if MSPACES + +/* + mspace is an opaque type representing an independent + region of space that supports mspace_malloc, etc. +*/ +typedef void* mspace; + +/* + create_mspace creates and returns a new independent space with the + given initial capacity, or, if 0, the default granularity size. It + returns null if there is no system memory available to create the + space. If argument locked is non-zero, the space uses a separate + lock to control access. The capacity of the space will grow + dynamically as needed to service mspace_malloc requests. You can + control the sizes of incremental increases of this space by + compiling with a different DEFAULT_GRANULARITY or dynamically + setting with mallopt(M_GRANULARITY, value). +*/ +DLMALLOC_EXPORT mspace create_mspace(size_t capacity, int locked); + +/* + destroy_mspace destroys the given space, and attempts to return all + of its memory back to the system, returning the total number of + bytes freed. After destruction, the results of access to all memory + used by the space become undefined. +*/ +DLMALLOC_EXPORT size_t destroy_mspace(mspace msp); + +/* + create_mspace_with_base uses the memory supplied as the initial base + of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this + space is used for bookkeeping, so the capacity must be at least this + large. (Otherwise 0 is returned.) When this initial space is + exhausted, additional memory will be obtained from the system. + Destroying this space will deallocate all additionally allocated + space (if possible) but not the initial base. +*/ +DLMALLOC_EXPORT mspace create_mspace_with_base(void* base, size_t capacity, int locked); + +/* + mspace_track_large_chunks controls whether requests for large chunks + are allocated in their own untracked mmapped regions, separate from + others in this mspace. By default large chunks are not tracked, + which reduces fragmentation. However, such chunks are not + necessarily released to the system upon destroy_mspace. Enabling + tracking by setting to true may increase fragmentation, but avoids + leakage when relying on destroy_mspace to release all memory + allocated using this space. The function returns the previous + setting. +*/ +DLMALLOC_EXPORT int mspace_track_large_chunks(mspace msp, int enable); + + +/* + mspace_malloc behaves as malloc, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_malloc(mspace msp, size_t bytes); + +/* + mspace_free behaves as free, but operates within + the given space. + + If compiled with FOOTERS==1, mspace_free is not actually needed. + free may be called instead of mspace_free because freed chunks from + any space are handled by their originating spaces. +*/ +DLMALLOC_EXPORT void mspace_free(mspace msp, void* mem); + +/* + mspace_realloc behaves as realloc, but operates within + the given space. + + If compiled with FOOTERS==1, mspace_realloc is not actually + needed. realloc may be called instead of mspace_realloc because + realloced chunks from any space are handled by their originating + spaces. +*/ +DLMALLOC_EXPORT void* mspace_realloc(mspace msp, void* mem, size_t newsize); + +/* + mspace_calloc behaves as calloc, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); + +/* + mspace_memalign behaves as memalign, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_memalign(mspace msp, size_t alignment, size_t bytes); + +/* + mspace_independent_calloc behaves as independent_calloc, but + operates within the given space. +*/ +DLMALLOC_EXPORT void** mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void* chunks[]); + +/* + mspace_independent_comalloc behaves as independent_comalloc, but + operates within the given space. +*/ +DLMALLOC_EXPORT void** mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void* chunks[]); + +/* + mspace_footprint() returns the number of bytes obtained from the + system for this space. +*/ +DLMALLOC_EXPORT size_t mspace_footprint(mspace msp); + +/* + mspace_max_footprint() returns the peak number of bytes obtained from the + system for this space. +*/ +DLMALLOC_EXPORT size_t mspace_max_footprint(mspace msp); + + +#if !NO_MALLINFO +/* + mspace_mallinfo behaves as mallinfo, but reports properties of + the given space. +*/ +DLMALLOC_EXPORT struct mallinfo mspace_mallinfo(mspace msp); +#endif /* NO_MALLINFO */ + +/* + malloc_usable_size(void* p) behaves the same as malloc_usable_size; +*/ +DLMALLOC_EXPORT size_t mspace_usable_size(const void* mem); + +/* + mspace_malloc_stats behaves as malloc_stats, but reports + properties of the given space. +*/ +DLMALLOC_EXPORT void mspace_malloc_stats(mspace msp); + +/* + mspace_trim behaves as malloc_trim, but + operates within the given space. +*/ +DLMALLOC_EXPORT int mspace_trim(mspace msp, size_t pad); + +/* + An alias for mallopt. +*/ +DLMALLOC_EXPORT int mspace_mallopt(int, int); + +#endif /* MSPACES */ + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif /* __cplusplus */ + +/* + ======================================================================== + To make a fully customizable malloc.h header file, cut everything + above this line, put into file malloc.h, edit to suit, and #include it + on the next line, as well as in programs that use this malloc. + ======================================================================== +*/ + +/* #include "malloc.h" */ + +/*------------------------------ internal #includes ---------------------- */ + +#ifdef _MSC_VER +#pragma warning( disable : 4146 ) /* no "unsigned" warnings */ +#endif /* _MSC_VER */ +#if !NO_MALLOC_STATS +#include /* for printing in malloc_stats */ +#endif /* NO_MALLOC_STATS */ +#ifndef LACKS_ERRNO_H +#include /* for MALLOC_FAILURE_ACTION */ +#endif /* LACKS_ERRNO_H */ +#ifdef DEBUG +#if ABORT_ON_ASSERT_FAILURE +#undef assert +#define assert(x) if(!(x)) ABORT +#else /* ABORT_ON_ASSERT_FAILURE */ +#include +#endif /* ABORT_ON_ASSERT_FAILURE */ +#else /* DEBUG */ +#ifndef assert +#define assert(x) +#endif +#define DEBUG 0 +#endif /* DEBUG */ +#if !defined(WIN32) && !defined(LACKS_TIME_H) +#include /* for magic initialization */ +#endif /* WIN32 */ +#ifndef LACKS_STDLIB_H +#include /* for abort() */ +#endif /* LACKS_STDLIB_H */ +#ifndef LACKS_STRING_H +#include /* for memset etc */ +#endif /* LACKS_STRING_H */ +#if USE_BUILTIN_FFS +#ifndef LACKS_STRINGS_H +#include /* for ffs */ +#endif /* LACKS_STRINGS_H */ +#endif /* USE_BUILTIN_FFS */ +#if HAVE_MMAP +#ifndef LACKS_SYS_MMAN_H +/* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */ +#if (defined(linux) && !defined(__USE_GNU)) +#define __USE_GNU 1 +#include /* for mmap */ +#undef __USE_GNU +#else +#include /* for mmap */ +#endif /* linux */ +#endif /* LACKS_SYS_MMAN_H */ +#ifndef LACKS_FCNTL_H +#include +#endif /* LACKS_FCNTL_H */ +#endif /* HAVE_MMAP */ +#ifndef LACKS_UNISTD_H +#include /* for sbrk, sysconf */ +#else /* LACKS_UNISTD_H */ +#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) +extern void* sbrk(ptrdiff_t); +#endif /* FreeBSD etc */ +#endif /* LACKS_UNISTD_H */ + +/* Declarations for locking */ +#if USE_LOCKS +#ifndef WIN32 +#if defined (__SVR4) && defined (__sun) /* solaris */ +#include +#elif !defined(LACKS_SCHED_H) +#include +#endif /* solaris or LACKS_SCHED_H */ +#if (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0) || !USE_SPIN_LOCKS +#include +#endif /* USE_RECURSIVE_LOCKS ... */ +#elif defined(_MSC_VER) +#ifndef _M_AMD64 +/* These are already defined on AMD64 builds */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ +LONG __cdecl _InterlockedCompareExchange(LONG volatile *Dest, LONG Exchange, LONG Comp); +LONG __cdecl _InterlockedExchange(LONG volatile *Target, LONG Value); +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* _M_AMD64 */ +#pragma intrinsic (_InterlockedCompareExchange) +#pragma intrinsic (_InterlockedExchange) +#define interlockedcompareexchange _InterlockedCompareExchange +#define interlockedexchange _InterlockedExchange +#elif defined(WIN32) && defined(__GNUC__) +#define interlockedcompareexchange(a, b, c) __sync_val_compare_and_swap(a, c, b) +#define interlockedexchange __sync_lock_test_and_set +#endif /* Win32 */ +#else /* USE_LOCKS */ +#endif /* USE_LOCKS */ + +#ifndef LOCK_AT_FORK +#define LOCK_AT_FORK 0 +#endif + +/* Declarations for bit scanning on win32 */ +#if defined(_MSC_VER) && _MSC_VER>=1300 +#ifndef BitScanForward /* Try to avoid pulling in WinNT.h */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ +unsigned char _BitScanForward(unsigned long *index, unsigned long mask); +unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#define BitScanForward _BitScanForward +#define BitScanReverse _BitScanReverse +#pragma intrinsic(_BitScanForward) +#pragma intrinsic(_BitScanReverse) +#endif /* BitScanForward */ +#endif /* defined(_MSC_VER) && _MSC_VER>=1300 */ + +#ifndef WIN32 +#ifndef malloc_getpagesize +# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ +# ifndef _SC_PAGE_SIZE +# define _SC_PAGE_SIZE _SC_PAGESIZE +# endif +# endif +# ifdef _SC_PAGE_SIZE +# define malloc_getpagesize sysconf(_SC_PAGE_SIZE) +# else +# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE) + extern size_t getpagesize(); +# define malloc_getpagesize getpagesize() +# else +# ifdef WIN32 /* use supplied emulation of getpagesize */ +# define malloc_getpagesize getpagesize() +# else +# ifndef LACKS_SYS_PARAM_H +# include +# endif +# ifdef EXEC_PAGESIZE +# define malloc_getpagesize EXEC_PAGESIZE +# else +# ifdef NBPG +# ifndef CLSIZE +# define malloc_getpagesize NBPG +# else +# define malloc_getpagesize (NBPG * CLSIZE) +# endif +# else +# ifdef NBPC +# define malloc_getpagesize NBPC +# else +# ifdef PAGESIZE +# define malloc_getpagesize PAGESIZE +# else /* just guess */ +# define malloc_getpagesize ((size_t)4096U) +# endif +# endif +# endif +# endif +# endif +# endif +# endif +#endif +#endif + +/* ------------------- size_t and alignment properties -------------------- */ + +/* The byte and bit size of a size_t */ +#define SIZE_T_SIZE (sizeof(size_t)) +#define SIZE_T_BITSIZE (sizeof(size_t) << 3) + +/* Some constants coerced to size_t */ +/* Annoying but necessary to avoid errors on some platforms */ +#define SIZE_T_ZERO ((size_t)0) +#define SIZE_T_ONE ((size_t)1) +#define SIZE_T_TWO ((size_t)2) +#define SIZE_T_FOUR ((size_t)4) +#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1) +#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2) +#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES) +#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U) + +/* The bit mask value corresponding to MALLOC_ALIGNMENT */ +#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE) + +/* True if address a has acceptable alignment */ +#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0) + +/* the number of bytes to offset an address to align it */ +#define align_offset(A)\ + ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\ + ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK)) + +/* -------------------------- MMAP preliminaries ------------------------- */ + +/* + If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and + checks to fail so compiler optimizer can delete code rather than + using so many "#if"s. +*/ + + +/* MORECORE and MMAP must return MFAIL on failure */ +#define MFAIL ((void*)(MAX_SIZE_T)) +#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */ + +#if HAVE_MMAP + +#ifndef WIN32 +#define MUNMAP_DEFAULT(a, s) munmap((a), (s)) +#define MMAP_PROT (PROT_READ|PROT_WRITE) +#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) +#define MAP_ANONYMOUS MAP_ANON +#endif /* MAP_ANON */ +#ifdef MAP_ANONYMOUS +#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS) +#define MMAP_DEFAULT(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0) +#else /* MAP_ANONYMOUS */ +/* + Nearly all versions of mmap support MAP_ANONYMOUS, so the following + is unlikely to be needed, but is supplied just in case. +*/ +#define MMAP_FLAGS (MAP_PRIVATE) +static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ +#define MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \ + (dev_zero_fd = open("/dev/zero", O_RDWR), \ + mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \ + mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) +#endif /* MAP_ANONYMOUS */ + +#define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s) + +#else /* WIN32 */ + +/* Win32 MMAP via VirtualAlloc */ +static FORCEINLINE void* win32mmap(size_t size) { + void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); + return (ptr != 0)? ptr: MFAIL; +} + +/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ +static FORCEINLINE void* win32direct_mmap(size_t size) { + void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, + PAGE_READWRITE); + return (ptr != 0)? ptr: MFAIL; +} + +/* This function supports releasing coalesed segments */ +static FORCEINLINE int win32munmap(void* ptr, size_t size) { + MEMORY_BASIC_INFORMATION minfo; + char* cptr = (char*)ptr; + while (size) { + if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) + return -1; + if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || + minfo.State != MEM_COMMIT || minfo.RegionSize > size) + return -1; + if (VirtualFree(cptr, 0, MEM_RELEASE) == 0) + return -1; + cptr += minfo.RegionSize; + size -= minfo.RegionSize; + } + return 0; +} + +#define MMAP_DEFAULT(s) win32mmap(s) +#define MUNMAP_DEFAULT(a, s) win32munmap((a), (s)) +#define DIRECT_MMAP_DEFAULT(s) win32direct_mmap(s) +#endif /* WIN32 */ +#endif /* HAVE_MMAP */ + +#if HAVE_MREMAP +#ifndef WIN32 +#define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv)) +#endif /* WIN32 */ +#endif /* HAVE_MREMAP */ + +/** + * Define CALL_MORECORE + */ +#if HAVE_MORECORE + #ifdef MORECORE + #define CALL_MORECORE(S) MORECORE(S) + #else /* MORECORE */ + #define CALL_MORECORE(S) MORECORE_DEFAULT(S) + #endif /* MORECORE */ +#else /* HAVE_MORECORE */ + #define CALL_MORECORE(S) MFAIL +#endif /* HAVE_MORECORE */ + +/** + * Define CALL_MMAP/CALL_MUNMAP/CALL_DIRECT_MMAP + */ +#if HAVE_MMAP + #define USE_MMAP_BIT (SIZE_T_ONE) + + #ifdef MMAP + #define CALL_MMAP(s) MMAP(s) + #else /* MMAP */ + #define CALL_MMAP(s) MMAP_DEFAULT(s) + #endif /* MMAP */ + #ifdef MUNMAP + #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) + #else /* MUNMAP */ + #define CALL_MUNMAP(a, s) MUNMAP_DEFAULT((a), (s)) + #endif /* MUNMAP */ + #ifdef DIRECT_MMAP + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) + #else /* DIRECT_MMAP */ + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s) + #endif /* DIRECT_MMAP */ +#else /* HAVE_MMAP */ + #define USE_MMAP_BIT (SIZE_T_ZERO) + + #define MMAP(s) MFAIL + #define MUNMAP(a, s) (-1) + #define DIRECT_MMAP(s) MFAIL + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) + #define CALL_MMAP(s) MMAP(s) + #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) +#endif /* HAVE_MMAP */ + +/** + * Define CALL_MREMAP + */ +#if HAVE_MMAP && HAVE_MREMAP + #ifdef MREMAP + #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv)) + #else /* MREMAP */ + #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv)) + #endif /* MREMAP */ +#else /* HAVE_MMAP && HAVE_MREMAP */ + #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL +#endif /* HAVE_MMAP && HAVE_MREMAP */ + +/* mstate bit set if continguous morecore disabled or failed */ +#define USE_NONCONTIGUOUS_BIT (4U) + +/* segment bit set in create_mspace_with_base */ +#define EXTERN_BIT (8U) + + +/* --------------------------- Lock preliminaries ------------------------ */ + +/* + When locks are defined, there is one global lock, plus + one per-mspace lock. + + The global lock_ensures that mparams.magic and other unique + mparams values are initialized only once. It also protects + sequences of calls to MORECORE. In many cases sys_alloc requires + two calls, that should not be interleaved with calls by other + threads. This does not protect against direct calls to MORECORE + by other threads not using this lock, so there is still code to + cope the best we can on interference. + + Per-mspace locks surround calls to malloc, free, etc. + By default, locks are simple non-reentrant mutexes. + + Because lock-protected regions generally have bounded times, it is + OK to use the supplied simple spinlocks. Spinlocks are likely to + improve performance for lightly contended applications, but worsen + performance under heavy contention. + + If USE_LOCKS is > 1, the definitions of lock routines here are + bypassed, in which case you will need to define the type MLOCK_T, + and at least INITIAL_LOCK, DESTROY_LOCK, ACQUIRE_LOCK, RELEASE_LOCK + and TRY_LOCK. You must also declare a + static MLOCK_T malloc_global_mutex = { initialization values };. + +*/ + +#if !USE_LOCKS +#define USE_LOCK_BIT (0U) +#define INITIAL_LOCK(l) (0) +#define DESTROY_LOCK(l) (0) +#define ACQUIRE_MALLOC_GLOBAL_LOCK() +#define RELEASE_MALLOC_GLOBAL_LOCK() + +#else +#if USE_LOCKS > 1 +/* ----------------------- User-defined locks ------------------------ */ +/* Define your own lock implementation here */ +/* #define INITIAL_LOCK(lk) ... */ +/* #define DESTROY_LOCK(lk) ... */ +/* #define ACQUIRE_LOCK(lk) ... */ +/* #define RELEASE_LOCK(lk) ... */ +/* #define TRY_LOCK(lk) ... */ +/* static MLOCK_T malloc_global_mutex = ... */ + +#elif USE_SPIN_LOCKS + +/* First, define CAS_LOCK and CLEAR_LOCK on ints */ +/* Note CAS_LOCK defined to return 0 on success */ + +#if defined(__GNUC__)&& (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) +#define CAS_LOCK(sl) __sync_lock_test_and_set(sl, 1) +#define CLEAR_LOCK(sl) __sync_lock_release(sl) + +#elif (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))) +/* Custom spin locks for older gcc on x86 */ +static FORCEINLINE int x86_cas_lock(int *sl) { + int ret; + int val = 1; + int cmp = 0; + __asm__ __volatile__ ("lock; cmpxchgl %1, %2" + : "=a" (ret) + : "r" (val), "m" (*(sl)), "0"(cmp) + : "memory", "cc"); + return ret; +} + +static FORCEINLINE void x86_clear_lock(int* sl) { + assert(*sl != 0); + int prev = 0; + int ret; + __asm__ __volatile__ ("lock; xchgl %0, %1" + : "=r" (ret) + : "m" (*(sl)), "0"(prev) + : "memory"); +} + +#define CAS_LOCK(sl) x86_cas_lock(sl) +#define CLEAR_LOCK(sl) x86_clear_lock(sl) + +#else /* Win32 MSC */ +#define CAS_LOCK(sl) interlockedexchange(sl, (LONG)1) +#define CLEAR_LOCK(sl) interlockedexchange (sl, (LONG)0) + +#endif /* ... gcc spins locks ... */ + +/* How to yield for a spin lock */ +#define SPINS_PER_YIELD 63 +#if defined(_MSC_VER) +#define SLEEP_EX_DURATION 50 /* delay for yield/sleep */ +#define SPIN_LOCK_YIELD SleepEx(SLEEP_EX_DURATION, FALSE) +#elif defined (__SVR4) && defined (__sun) /* solaris */ +#define SPIN_LOCK_YIELD thr_yield(); +#elif !defined(LACKS_SCHED_H) +#define SPIN_LOCK_YIELD sched_yield(); +#else +#define SPIN_LOCK_YIELD +#endif /* ... yield ... */ + +#if !defined(USE_RECURSIVE_LOCKS) || USE_RECURSIVE_LOCKS == 0 +/* Plain spin locks use single word (embedded in malloc_states) */ +static int spin_acquire_lock(int *sl) { + int spins = 0; + while (*(volatile int *)sl != 0 || CAS_LOCK(sl)) { + if ((++spins & SPINS_PER_YIELD) == 0) { + SPIN_LOCK_YIELD; + } + } + return 0; +} + +#define MLOCK_T int +#define TRY_LOCK(sl) !CAS_LOCK(sl) +#define RELEASE_LOCK(sl) CLEAR_LOCK(sl) +#define ACQUIRE_LOCK(sl) (CAS_LOCK(sl)? spin_acquire_lock(sl) : 0) +#define INITIAL_LOCK(sl) (*sl = 0) +#define DESTROY_LOCK(sl) (0) +static MLOCK_T malloc_global_mutex = 0; + +#else /* USE_RECURSIVE_LOCKS */ +/* types for lock owners */ +#ifdef WIN32 +#define THREAD_ID_T DWORD +#define CURRENT_THREAD GetCurrentThreadId() +#define EQ_OWNER(X,Y) ((X) == (Y)) +#else +/* + Note: the following assume that pthread_t is a type that can be + initialized to (casted) zero. If this is not the case, you will need to + somehow redefine these or not use spin locks. +*/ +#define THREAD_ID_T pthread_t +#define CURRENT_THREAD pthread_self() +#define EQ_OWNER(X,Y) pthread_equal(X, Y) +#endif + +struct malloc_recursive_lock { + int sl; + unsigned int c; + THREAD_ID_T threadid; +}; + +#define MLOCK_T struct malloc_recursive_lock +static MLOCK_T malloc_global_mutex = { 0, 0, (THREAD_ID_T)0}; + +static FORCEINLINE void recursive_release_lock(MLOCK_T *lk) { + assert(lk->sl != 0); + if (--lk->c == 0) { + CLEAR_LOCK(&lk->sl); + } +} + +static FORCEINLINE int recursive_acquire_lock(MLOCK_T *lk) { + THREAD_ID_T mythreadid = CURRENT_THREAD; + int spins = 0; + for (;;) { + if (*((volatile int *)(&lk->sl)) == 0) { + if (!CAS_LOCK(&lk->sl)) { + lk->threadid = mythreadid; + lk->c = 1; + return 0; + } + } + else if (EQ_OWNER(lk->threadid, mythreadid)) { + ++lk->c; + return 0; + } + if ((++spins & SPINS_PER_YIELD) == 0) { + SPIN_LOCK_YIELD; + } + } +} + +static FORCEINLINE int recursive_try_lock(MLOCK_T *lk) { + THREAD_ID_T mythreadid = CURRENT_THREAD; + if (*((volatile int *)(&lk->sl)) == 0) { + if (!CAS_LOCK(&lk->sl)) { + lk->threadid = mythreadid; + lk->c = 1; + return 1; + } + } + else if (EQ_OWNER(lk->threadid, mythreadid)) { + ++lk->c; + return 1; + } + return 0; +} + +#define RELEASE_LOCK(lk) recursive_release_lock(lk) +#define TRY_LOCK(lk) recursive_try_lock(lk) +#define ACQUIRE_LOCK(lk) recursive_acquire_lock(lk) +#define INITIAL_LOCK(lk) ((lk)->threadid = (THREAD_ID_T)0, (lk)->sl = 0, (lk)->c = 0) +#define DESTROY_LOCK(lk) (0) +#endif /* USE_RECURSIVE_LOCKS */ + +#elif defined(WIN32) /* Win32 critical sections */ +#define MLOCK_T CRITICAL_SECTION +#define ACQUIRE_LOCK(lk) (EnterCriticalSection(lk), 0) +#define RELEASE_LOCK(lk) LeaveCriticalSection(lk) +#define TRY_LOCK(lk) TryEnterCriticalSection(lk) +#define INITIAL_LOCK(lk) (!InitializeCriticalSectionAndSpinCount((lk), 0x80000000|4000)) +#define DESTROY_LOCK(lk) (DeleteCriticalSection(lk), 0) +#define NEED_GLOBAL_LOCK_INIT + +static MLOCK_T malloc_global_mutex; +static volatile LONG malloc_global_mutex_status; + +/* Use spin loop to initialize global lock */ +static void init_malloc_global_mutex() { + for (;;) { + long stat = malloc_global_mutex_status; + if (stat > 0) + return; + /* transition to < 0 while initializing, then to > 0) */ + if (stat == 0 && + interlockedcompareexchange(&malloc_global_mutex_status, (LONG)-1, (LONG)0) == 0) { + InitializeCriticalSection(&malloc_global_mutex); + interlockedexchange(&malloc_global_mutex_status, (LONG)1); + return; + } + SleepEx(0, FALSE); + } +} + +#else /* pthreads-based locks */ +#define MLOCK_T pthread_mutex_t +#define ACQUIRE_LOCK(lk) pthread_mutex_lock(lk) +#define RELEASE_LOCK(lk) pthread_mutex_unlock(lk) +#define TRY_LOCK(lk) (!pthread_mutex_trylock(lk)) +#define INITIAL_LOCK(lk) pthread_init_lock(lk) +#define DESTROY_LOCK(lk) pthread_mutex_destroy(lk) + +#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 && defined(linux) && !defined(PTHREAD_MUTEX_RECURSIVE) +/* Cope with old-style linux recursive lock initialization by adding */ +/* skipped internal declaration from pthread.h */ +extern int pthread_mutexattr_setkind_np __P ((pthread_mutexattr_t *__attr, + int __kind)); +#define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP +#define pthread_mutexattr_settype(x,y) pthread_mutexattr_setkind_np(x,y) +#endif /* USE_RECURSIVE_LOCKS ... */ + +static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER; + +static int pthread_init_lock (MLOCK_T *lk) { + pthread_mutexattr_t attr; + if (pthread_mutexattr_init(&attr)) return 1; +#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 + if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1; +#endif + if (pthread_mutex_init(lk, &attr)) return 1; + if (pthread_mutexattr_destroy(&attr)) return 1; + return 0; +} + +#endif /* ... lock types ... */ + +/* Common code for all lock types */ +#define USE_LOCK_BIT (2U) + +#ifndef ACQUIRE_MALLOC_GLOBAL_LOCK +#define ACQUIRE_MALLOC_GLOBAL_LOCK() ACQUIRE_LOCK(&malloc_global_mutex); +#endif + +#ifndef RELEASE_MALLOC_GLOBAL_LOCK +#define RELEASE_MALLOC_GLOBAL_LOCK() RELEASE_LOCK(&malloc_global_mutex); +#endif + +#endif /* USE_LOCKS */ + +/* ----------------------- Chunk representations ------------------------ */ + +/* + (The following includes lightly edited explanations by Colin Plumb.) + + The malloc_chunk declaration below is misleading (but accurate and + necessary). It declares a "view" into memory allowing access to + necessary fields at known offsets from a given base. + + Chunks of memory are maintained using a `boundary tag' method as + originally described by Knuth. (See the paper by Paul Wilson + ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such + techniques.) Sizes of free chunks are stored both in the front of + each chunk and at the end. This makes consolidating fragmented + chunks into bigger chunks fast. The head fields also hold bits + representing whether chunks are free or in use. + + Here are some pictures to make it clearer. They are "exploded" to + show that the state of a chunk can be thought of as extending from + the high 31 bits of the head field of its header through the + prev_foot and PINUSE_BIT bit of the following chunk header. + + A chunk that's in use looks like: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk (if P = 0) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| + | Size of this chunk 1| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | | + +- -+ + | | + +- -+ + | : + +- size - sizeof(size_t) available payload bytes -+ + : | + chunk-> +- -+ + | | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1| + | Size of next chunk (may or may not be in use) | +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + And if it's free, it looks like this: + + chunk-> +- -+ + | User payload (must be in use, or we would have merged!) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| + | Size of this chunk 0| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Next pointer | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Prev pointer | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | : + +- size - sizeof(struct chunk) unused bytes -+ + : | + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of this chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0| + | Size of next chunk (must be in use, or we would have merged)| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | : + +- User payload -+ + : | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |0| + +-+ + Note that since we always merge adjacent free chunks, the chunks + adjacent to a free chunk must be in use. + + Given a pointer to a chunk (which can be derived trivially from the + payload pointer) we can, in O(1) time, find out whether the adjacent + chunks are free, and if so, unlink them from the lists that they + are on and merge them with the current chunk. + + Chunks always begin on even word boundaries, so the mem portion + (which is returned to the user) is also on an even word boundary, and + thus at least double-word aligned. + + The P (PINUSE_BIT) bit, stored in the unused low-order bit of the + chunk size (which is always a multiple of two words), is an in-use + bit for the *previous* chunk. If that bit is *clear*, then the + word before the current chunk size contains the previous chunk + size, and can be used to find the front of the previous chunk. + The very first chunk allocated always has this bit set, preventing + access to non-existent (or non-owned) memory. If pinuse is set for + any given chunk, then you CANNOT determine the size of the + previous chunk, and might even get a memory addressing fault when + trying to do so. + + The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of + the chunk size redundantly records whether the current chunk is + inuse (unless the chunk is mmapped). This redundancy enables usage + checks within free and realloc, and reduces indirection when freeing + and consolidating chunks. + + Each freshly allocated chunk must have both cinuse and pinuse set. + That is, each allocated chunk borders either a previously allocated + and still in-use chunk, or the base of its memory arena. This is + ensured by making all allocations from the `lowest' part of any + found chunk. Further, no free chunk physically borders another one, + so each free chunk is known to be preceded and followed by either + inuse chunks or the ends of memory. + + Note that the `foot' of the current chunk is actually represented + as the prev_foot of the NEXT chunk. This makes it easier to + deal with alignments etc but can be very confusing when trying + to extend or adapt this code. + + The exceptions to all this are + + 1. The special chunk `top' is the top-most available chunk (i.e., + the one bordering the end of available memory). It is treated + specially. Top is never included in any bin, is used only if + no other chunk is available, and is released back to the + system if it is very large (see M_TRIM_THRESHOLD). In effect, + the top chunk is treated as larger (and thus less well + fitting) than any other available chunk. The top chunk + doesn't update its trailing size field since there is no next + contiguous chunk that would have to index off it. However, + space is still allocated for it (TOP_FOOT_SIZE) to enable + separation or merging when space is extended. + + 3. Chunks allocated via mmap, have both cinuse and pinuse bits + cleared in their head fields. Because they are allocated + one-by-one, each must carry its own prev_foot field, which is + also used to hold the offset this chunk has within its mmapped + region, which is needed to preserve alignment. Each mmapped + chunk is trailed by the first two fields of a fake next-chunk + for sake of usage checks. + +*/ + +struct malloc_chunk { + size_t prev_foot; /* Size of previous chunk (if free). */ + size_t head; /* Size and inuse bits. */ + struct malloc_chunk* fd; /* double links -- used only if free. */ + struct malloc_chunk* bk; +}; + +typedef struct malloc_chunk mchunk; +typedef struct malloc_chunk* mchunkptr; +typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */ +typedef unsigned int bindex_t; /* Described below */ +typedef unsigned int binmap_t; /* Described below */ +typedef unsigned int flag_t; /* The type of various bit flag sets */ + +/* ------------------- Chunks sizes and alignments ----------------------- */ + +#define MCHUNK_SIZE (sizeof(mchunk)) + +#if FOOTERS +#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) +#else /* FOOTERS */ +#define CHUNK_OVERHEAD (SIZE_T_SIZE) +#endif /* FOOTERS */ + +/* MMapped chunks need a second word of overhead ... */ +#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) +/* ... and additional padding for fake next-chunk at foot */ +#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES) + +/* The smallest size we can malloc is an aligned minimal chunk */ +#define MIN_CHUNK_SIZE\ + ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) + +/* conversion from malloc headers to user pointers, and back */ +#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES)) +#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES)) +/* chunk associated with aligned address A */ +#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A))) + +/* Bounds on request (not chunk) sizes. */ +#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2) +#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE) + +/* pad request bytes into a usable size */ +#define pad_request(req) \ + (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) + +/* pad request, checking for minimum (but not maximum) */ +#define request2size(req) \ + (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req)) + + +/* ------------------ Operations on head and foot fields ----------------- */ + +/* + The head field of a chunk is or'ed with PINUSE_BIT when previous + adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in + use, unless mmapped, in which case both bits are cleared. + + FLAG4_BIT is not used by this malloc, but might be useful in extensions. +*/ + +#define PINUSE_BIT (SIZE_T_ONE) +#define CINUSE_BIT (SIZE_T_TWO) +#define FLAG4_BIT (SIZE_T_FOUR) +#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT) +#define FLAG_BITS (PINUSE_BIT|CINUSE_BIT|FLAG4_BIT) + +/* Head value for fenceposts */ +#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE) + +/* extraction of fields from head words */ +#define cinuse(p) ((p)->head & CINUSE_BIT) +#define pinuse(p) ((p)->head & PINUSE_BIT) +#define flag4inuse(p) ((p)->head & FLAG4_BIT) +#define is_inuse(p) (((p)->head & INUSE_BITS) != PINUSE_BIT) +#define is_mmapped(p) (((p)->head & INUSE_BITS) == 0) + +#define chunksize(p) ((p)->head & ~(FLAG_BITS)) + +#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT) +#define set_flag4(p) ((p)->head |= FLAG4_BIT) +#define clear_flag4(p) ((p)->head &= ~FLAG4_BIT) + +/* Treat space at ptr +/- offset as a chunk */ +#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s))) +#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s))) + +/* Ptr to next or previous physical malloc_chunk. */ +#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~FLAG_BITS))) +#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) )) + +/* extract next chunk's pinuse bit */ +#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT) + +/* Get/set size at footer */ +#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot) +#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s)) + +/* Set size, pinuse bit, and foot */ +#define set_size_and_pinuse_of_free_chunk(p, s)\ + ((p)->head = (s|PINUSE_BIT), set_foot(p, s)) + +/* Set size, pinuse bit, foot, and clear next pinuse */ +#define set_free_with_pinuse(p, s, n)\ + (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s)) + +/* Get the internal overhead associated with chunk p */ +#define overhead_for(p)\ + (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD) + +/* Return true if malloced space is not necessarily cleared */ +#if MMAP_CLEARS +#define calloc_must_clear(p) (!is_mmapped(p)) +#else /* MMAP_CLEARS */ +#define calloc_must_clear(p) (1) +#endif /* MMAP_CLEARS */ + +/* ---------------------- Overlaid data structures ----------------------- */ + +/* + When chunks are not in use, they are treated as nodes of either + lists or trees. + + "Small" chunks are stored in circular doubly-linked lists, and look + like this: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `head:' | Size of chunk, in bytes |P| + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Forward pointer to next chunk in list | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Back pointer to previous chunk in list | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Unused space (may be 0 bytes long) . + . . + . | +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `foot:' | Size of chunk, in bytes | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Larger chunks are kept in a form of bitwise digital trees (aka + tries) keyed on chunksizes. Because malloc_tree_chunks are only for + free chunks greater than 256 bytes, their size doesn't impose any + constraints on user chunk sizes. Each node looks like: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `head:' | Size of chunk, in bytes |P| + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Forward pointer to next chunk of same size | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Back pointer to previous chunk of same size | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to left child (child[0]) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to right child (child[1]) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to parent | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | bin index of this chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Unused space . + . | +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `foot:' | Size of chunk, in bytes | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Each tree holding treenodes is a tree of unique chunk sizes. Chunks + of the same size are arranged in a circularly-linked list, with only + the oldest chunk (the next to be used, in our FIFO ordering) + actually in the tree. (Tree members are distinguished by a non-null + parent pointer.) If a chunk with the same size an an existing node + is inserted, it is linked off the existing node using pointers that + work in the same way as fd/bk pointers of small chunks. + + Each tree contains a power of 2 sized range of chunk sizes (the + smallest is 0x100 <= x < 0x180), which is is divided in half at each + tree level, with the chunks in the smaller half of the range (0x100 + <= x < 0x140 for the top nose) in the left subtree and the larger + half (0x140 <= x < 0x180) in the right subtree. This is, of course, + done by inspecting individual bits. + + Using these rules, each node's left subtree contains all smaller + sizes than its right subtree. However, the node at the root of each + subtree has no particular ordering relationship to either. (The + dividing line between the subtree sizes is based on trie relation.) + If we remove the last chunk of a given size from the interior of the + tree, we need to replace it with a leaf node. The tree ordering + rules permit a node to be replaced by any leaf below it. + + The smallest chunk in a tree (a common operation in a best-fit + allocator) can be found by walking a path to the leftmost leaf in + the tree. Unlike a usual binary tree, where we follow left child + pointers until we reach a null, here we follow the right child + pointer any time the left one is null, until we reach a leaf with + both child pointers null. The smallest chunk in the tree will be + somewhere along that path. + + The worst case number of steps to add, find, or remove a node is + bounded by the number of bits differentiating chunks within + bins. Under current bin calculations, this ranges from 6 up to 21 + (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case + is of course much better. +*/ + +struct malloc_tree_chunk { + /* The first four fields must be compatible with malloc_chunk */ + size_t prev_foot; + size_t head; + struct malloc_tree_chunk* fd; + struct malloc_tree_chunk* bk; + + struct malloc_tree_chunk* child[2]; + struct malloc_tree_chunk* parent; + bindex_t index; +}; + +typedef struct malloc_tree_chunk tchunk; +typedef struct malloc_tree_chunk* tchunkptr; +typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */ + +/* A little helper macro for trees */ +#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1]) + +/* ----------------------------- Segments -------------------------------- */ + +/* + Each malloc space may include non-contiguous segments, held in a + list headed by an embedded malloc_segment record representing the + top-most space. Segments also include flags holding properties of + the space. Large chunks that are directly allocated by mmap are not + included in this list. They are instead independently created and + destroyed without otherwise keeping track of them. + + Segment management mainly comes into play for spaces allocated by + MMAP. Any call to MMAP might or might not return memory that is + adjacent to an existing segment. MORECORE normally contiguously + extends the current space, so this space is almost always adjacent, + which is simpler and faster to deal with. (This is why MORECORE is + used preferentially to MMAP when both are available -- see + sys_alloc.) When allocating using MMAP, we don't use any of the + hinting mechanisms (inconsistently) supported in various + implementations of unix mmap, or distinguish reserving from + committing memory. Instead, we just ask for space, and exploit + contiguity when we get it. It is probably possible to do + better than this on some systems, but no general scheme seems + to be significantly better. + + Management entails a simpler variant of the consolidation scheme + used for chunks to reduce fragmentation -- new adjacent memory is + normally prepended or appended to an existing segment. However, + there are limitations compared to chunk consolidation that mostly + reflect the fact that segment processing is relatively infrequent + (occurring only when getting memory from system) and that we + don't expect to have huge numbers of segments: + + * Segments are not indexed, so traversal requires linear scans. (It + would be possible to index these, but is not worth the extra + overhead and complexity for most programs on most platforms.) + * New segments are only appended to old ones when holding top-most + memory; if they cannot be prepended to others, they are held in + different segments. + + Except for the top-most segment of an mstate, each segment record + is kept at the tail of its segment. Segments are added by pushing + segment records onto the list headed by &mstate.seg for the + containing mstate. + + Segment flags control allocation/merge/deallocation policies: + * If EXTERN_BIT set, then we did not allocate this segment, + and so should not try to deallocate or merge with others. + (This currently holds only for the initial segment passed + into create_mspace_with_base.) + * If USE_MMAP_BIT set, the segment may be merged with + other surrounding mmapped segments and trimmed/de-allocated + using munmap. + * If neither bit is set, then the segment was obtained using + MORECORE so can be merged with surrounding MORECORE'd segments + and deallocated/trimmed using MORECORE with negative arguments. +*/ + +struct malloc_segment { + char* base; /* base address */ + size_t size; /* allocated size */ + struct malloc_segment* next; /* ptr to next segment */ + flag_t sflags; /* mmap and extern flag */ +}; + +#define is_mmapped_segment(S) ((S)->sflags & USE_MMAP_BIT) +#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT) + +typedef struct malloc_segment msegment; +typedef struct malloc_segment* msegmentptr; + +/* ---------------------------- malloc_state ----------------------------- */ + +/* + A malloc_state holds all of the bookkeeping for a space. + The main fields are: + + Top + The topmost chunk of the currently active segment. Its size is + cached in topsize. The actual size of topmost space is + topsize+TOP_FOOT_SIZE, which includes space reserved for adding + fenceposts and segment records if necessary when getting more + space from the system. The size at which to autotrim top is + cached from mparams in trim_check, except that it is disabled if + an autotrim fails. + + Designated victim (dv) + This is the preferred chunk for servicing small requests that + don't have exact fits. It is normally the chunk split off most + recently to service another small request. Its size is cached in + dvsize. The link fields of this chunk are not maintained since it + is not kept in a bin. + + SmallBins + An array of bin headers for free chunks. These bins hold chunks + with sizes less than MIN_LARGE_SIZE bytes. Each bin contains + chunks of all the same size, spaced 8 bytes apart. To simplify + use in double-linked lists, each bin header acts as a malloc_chunk + pointing to the real first node, if it exists (else pointing to + itself). This avoids special-casing for headers. But to avoid + waste, we allocate only the fd/bk pointers of bins, and then use + repositioning tricks to treat these as the fields of a chunk. + + TreeBins + Treebins are pointers to the roots of trees holding a range of + sizes. There are 2 equally spaced treebins for each power of two + from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything + larger. + + Bin maps + There is one bit map for small bins ("smallmap") and one for + treebins ("treemap). Each bin sets its bit when non-empty, and + clears the bit when empty. Bit operations are then used to avoid + bin-by-bin searching -- nearly all "search" is done without ever + looking at bins that won't be selected. The bit maps + conservatively use 32 bits per map word, even if on 64bit system. + For a good description of some of the bit-based techniques used + here, see Henry S. Warren Jr's book "Hacker's Delight" (and + supplement at http://hackersdelight.org/). Many of these are + intended to reduce the branchiness of paths through malloc etc, as + well as to reduce the number of memory locations read or written. + + Segments + A list of segments headed by an embedded malloc_segment record + representing the initial space. + + Address check support + The least_addr field is the least address ever obtained from + MORECORE or MMAP. Attempted frees and reallocs of any address less + than this are trapped (unless INSECURE is defined). + + Magic tag + A cross-check field that should always hold same value as mparams.magic. + + Max allowed footprint + The maximum allowed bytes to allocate from system (zero means no limit) + + Flags + Bits recording whether to use MMAP, locks, or contiguous MORECORE + + Statistics + Each space keeps track of current and maximum system memory + obtained via MORECORE or MMAP. + + Trim support + Fields holding the amount of unused topmost memory that should trigger + trimming, and a counter to force periodic scanning to release unused + non-topmost segments. + + Locking + If USE_LOCKS is defined, the "mutex" lock is acquired and released + around every public call using this mspace. + + Extension support + A void* pointer and a size_t field that can be used to help implement + extensions to this malloc. +*/ + +/* Bin types, widths and sizes */ +#define NSMALLBINS (32U) +#define NTREEBINS (32U) +#define SMALLBIN_SHIFT (3U) +#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT) +#define TREEBIN_SHIFT (8U) +#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT) +#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE) +#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD) + +struct malloc_state { + binmap_t smallmap; + binmap_t treemap; + size_t dvsize; + size_t topsize; + char* least_addr; + mchunkptr dv; + mchunkptr top; + size_t trim_check; + size_t release_checks; + size_t magic; + mchunkptr smallbins[(NSMALLBINS+1)*2]; + tbinptr treebins[NTREEBINS]; + size_t footprint; + size_t max_footprint; + size_t footprint_limit; /* zero means no limit */ + flag_t mflags; +#if USE_LOCKS + MLOCK_T mutex; /* locate lock among fields that rarely change */ +#endif /* USE_LOCKS */ + msegment seg; + void* extp; /* Unused but available for extensions */ + size_t exts; +}; + +typedef struct malloc_state* mstate; + +/* ------------- Global malloc_state and malloc_params ------------------- */ + +/* + malloc_params holds global properties, including those that can be + dynamically set using mallopt. There is a single instance, mparams, + initialized in init_mparams. Note that the non-zeroness of "magic" + also serves as an initialization flag. +*/ + +struct malloc_params { + size_t magic; + size_t page_size; + size_t granularity; + size_t mmap_threshold; + size_t trim_threshold; + flag_t default_mflags; +}; + +static struct malloc_params mparams; + +/* Ensure mparams initialized */ +#define ensure_initialization() (void)(mparams.magic != 0 || init_mparams()) + +#if !ONLY_MSPACES + +/* The global malloc_state used for all non-"mspace" calls */ +static struct malloc_state _gm_; +#define gm (&_gm_) +#define is_global(M) ((M) == &_gm_) + +#endif /* !ONLY_MSPACES */ + +#define is_initialized(M) ((M)->top != 0) + +/* -------------------------- system alloc setup ------------------------- */ + +/* Operations on mflags */ + +#define use_lock(M) ((M)->mflags & USE_LOCK_BIT) +#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT) +#if USE_LOCKS +#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT) +#else +#define disable_lock(M) +#endif + +#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT) +#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT) +#if HAVE_MMAP +#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT) +#else +#define disable_mmap(M) +#endif + +#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT) +#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT) + +#define set_lock(M,L)\ + ((M)->mflags = (L)?\ + ((M)->mflags | USE_LOCK_BIT) :\ + ((M)->mflags & ~USE_LOCK_BIT)) + +/* page-align a size */ +#define page_align(S)\ + (((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE)) + +/* granularity-align a size */ +#define granularity_align(S)\ + (((S) + (mparams.granularity - SIZE_T_ONE))\ + & ~(mparams.granularity - SIZE_T_ONE)) + + +/* For mmap, use granularity alignment on windows, else page-align */ +#ifdef WIN32 +#define mmap_align(S) granularity_align(S) +#else +#define mmap_align(S) page_align(S) +#endif + +/* For sys_alloc, enough padding to ensure can malloc request on success */ +#define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT) + +#define is_page_aligned(S)\ + (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0) +#define is_granularity_aligned(S)\ + (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0) + +/* True if segment S holds address A */ +#define segment_holds(S, A)\ + ((char*)(A) >= S->base && (char*)(A) < S->base + S->size) + +/* Return segment holding given address */ +static msegmentptr segment_holding(mstate m, char* addr) { + msegmentptr sp = &m->seg; + for (;;) { + if (addr >= sp->base && addr < sp->base + sp->size) + return sp; + if ((sp = sp->next) == 0) + return 0; + } +} + +/* Return true if segment contains a segment link */ +static int has_segment_link(mstate m, msegmentptr ss) { + msegmentptr sp = &m->seg; + for (;;) { + if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size) + return 1; + if ((sp = sp->next) == 0) + return 0; + } +} + +#ifndef MORECORE_CANNOT_TRIM +#define should_trim(M,s) ((s) > (M)->trim_check) +#else /* MORECORE_CANNOT_TRIM */ +#define should_trim(M,s) (0) +#endif /* MORECORE_CANNOT_TRIM */ + +/* + TOP_FOOT_SIZE is padding at the end of a segment, including space + that may be needed to place segment records and fenceposts when new + noncontiguous segments are added. +*/ +#define TOP_FOOT_SIZE\ + (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE) + + +/* ------------------------------- Hooks -------------------------------- */ + +/* + PREACTION should be defined to return 0 on success, and nonzero on + failure. If you are not using locking, you can redefine these to do + anything you like. +*/ + +#if USE_LOCKS +#define PREACTION(M) ((use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0) +#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); } +#else /* USE_LOCKS */ + +#ifndef PREACTION +#define PREACTION(M) (0) +#endif /* PREACTION */ + +#ifndef POSTACTION +#define POSTACTION(M) +#endif /* POSTACTION */ + +#endif /* USE_LOCKS */ + +/* + CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses. + USAGE_ERROR_ACTION is triggered on detected bad frees and + reallocs. The argument p is an address that might have triggered the + fault. It is ignored by the two predefined actions, but might be + useful in custom actions that try to help diagnose errors. +*/ + +#if PROCEED_ON_ERROR + +/* A count of the number of corruption errors causing resets */ +int malloc_corruption_error_count; + +/* default corruption action */ +static void reset_on_error(mstate m); + +#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m) +#define USAGE_ERROR_ACTION(m, p) + +#else /* PROCEED_ON_ERROR */ + +#ifndef CORRUPTION_ERROR_ACTION +#define CORRUPTION_ERROR_ACTION(m) ABORT +#endif /* CORRUPTION_ERROR_ACTION */ + +#ifndef USAGE_ERROR_ACTION +#define USAGE_ERROR_ACTION(m,p) ABORT +#endif /* USAGE_ERROR_ACTION */ + +#endif /* PROCEED_ON_ERROR */ + + +/* -------------------------- Debugging setup ---------------------------- */ + +#if ! DEBUG + +#define check_free_chunk(M,P) +#define check_inuse_chunk(M,P) +#define check_malloced_chunk(M,P,N) +#define check_mmapped_chunk(M,P) +#define check_malloc_state(M) +#define check_top_chunk(M,P) + +#else /* DEBUG */ +#define check_free_chunk(M,P) do_check_free_chunk(M,P) +#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P) +#define check_top_chunk(M,P) do_check_top_chunk(M,P) +#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N) +#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P) +#define check_malloc_state(M) do_check_malloc_state(M) + +static void do_check_any_chunk(mstate m, mchunkptr p); +static void do_check_top_chunk(mstate m, mchunkptr p); +static void do_check_mmapped_chunk(mstate m, mchunkptr p); +static void do_check_inuse_chunk(mstate m, mchunkptr p); +static void do_check_free_chunk(mstate m, mchunkptr p); +static void do_check_malloced_chunk(mstate m, void* mem, size_t s); +static void do_check_tree(mstate m, tchunkptr t); +static void do_check_treebin(mstate m, bindex_t i); +static void do_check_smallbin(mstate m, bindex_t i); +static void do_check_malloc_state(mstate m); +static int bin_find(mstate m, mchunkptr x); +static size_t traverse_and_check(mstate m); +#endif /* DEBUG */ + +/* ---------------------------- Indexing Bins ---------------------------- */ + +#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS) +#define small_index(s) (bindex_t)((s) >> SMALLBIN_SHIFT) +#define small_index2size(i) ((i) << SMALLBIN_SHIFT) +#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE)) + +/* addressing by index. See above about smallbin repositioning */ +#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1]))) +#define treebin_at(M,i) (&((M)->treebins[i])) + +/* assign tree index for size S to variable I. Use x86 asm if possible */ +#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +#define compute_tree_index(S, I)\ +{\ + unsigned int X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K = (unsigned) sizeof(X)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clz(X); \ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#elif defined (__INTEL_COMPILER) +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K = _bit_scan_reverse (X); \ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#elif defined(_MSC_VER) && _MSC_VER>=1300 +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K;\ + _BitScanReverse((DWORD *) &K, (DWORD) X);\ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#else /* GNUC */ +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int Y = (unsigned int)X;\ + unsigned int N = ((Y - 0x100) >> 16) & 8;\ + unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\ + N += K;\ + N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\ + K = 14 - N + ((Y <<= K) >> 15);\ + I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\ + }\ +} +#endif /* GNUC */ + +/* Bit representing maximum resolved size in a treebin at i */ +#define bit_for_tree_index(i) \ + (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2) + +/* Shift placing maximum resolved bit in a treebin at i as sign bit */ +#define leftshift_for_tree_index(i) \ + ((i == NTREEBINS-1)? 0 : \ + ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2))) + +/* The size of the smallest chunk held in bin with index i */ +#define minsize_for_tree_index(i) \ + ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \ + (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1))) + + +/* ------------------------ Operations on bin maps ----------------------- */ + +/* bit corresponding to given index */ +#define idx2bit(i) ((binmap_t)(1) << (i)) + +/* Mark/Clear bits with given index */ +#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i)) +#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i)) +#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i)) + +#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i)) +#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i)) +#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i)) + +/* isolate the least set bit of a bitmap */ +#define least_bit(x) ((x) & -(x)) + +/* mask with all bits to left of least bit of x on */ +#define left_bits(x) ((x<<1) | -(x<<1)) + +/* mask with all bits to left of or equal to least bit of x on */ +#define same_or_left_bits(x) ((x) | -(x)) + +/* index corresponding to given bit. Use x86 asm if possible */ + +#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + J = __builtin_ctz(X); \ + I = (bindex_t)J;\ +} + +#elif defined (__INTEL_COMPILER) +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + J = _bit_scan_forward (X); \ + I = (bindex_t)J;\ +} + +#elif defined(_MSC_VER) && _MSC_VER>=1300 +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + _BitScanForward((DWORD *) &J, X);\ + I = (bindex_t)J;\ +} + +#elif USE_BUILTIN_FFS +#define compute_bit2idx(X, I) I = ffs(X)-1 + +#else +#define compute_bit2idx(X, I)\ +{\ + unsigned int Y = X - 1;\ + unsigned int K = Y >> (16-4) & 16;\ + unsigned int N = K; Y >>= K;\ + N += K = Y >> (8-3) & 8; Y >>= K;\ + N += K = Y >> (4-2) & 4; Y >>= K;\ + N += K = Y >> (2-1) & 2; Y >>= K;\ + N += K = Y >> (1-0) & 1; Y >>= K;\ + I = (bindex_t)(N + Y);\ +} +#endif /* GNUC */ + + +/* ----------------------- Runtime Check Support ------------------------- */ + +/* + For security, the main invariant is that malloc/free/etc never + writes to a static address other than malloc_state, unless static + malloc_state itself has been corrupted, which cannot occur via + malloc (because of these checks). In essence this means that we + believe all pointers, sizes, maps etc held in malloc_state, but + check all of those linked or offsetted from other embedded data + structures. These checks are interspersed with main code in a way + that tends to minimize their run-time cost. + + When FOOTERS is defined, in addition to range checking, we also + verify footer fields of inuse chunks, which can be used guarantee + that the mstate controlling malloc/free is intact. This is a + streamlined version of the approach described by William Robertson + et al in "Run-time Detection of Heap-based Overflows" LISA'03 + http://www.usenix.org/events/lisa03/tech/robertson.html The footer + of an inuse chunk holds the xor of its mstate and a random seed, + that is checked upon calls to free() and realloc(). This is + (probabalistically) unguessable from outside the program, but can be + computed by any code successfully malloc'ing any chunk, so does not + itself provide protection against code that has already broken + security through some other means. Unlike Robertson et al, we + always dynamically check addresses of all offset chunks (previous, + next, etc). This turns out to be cheaper than relying on hashes. +*/ + +#if !INSECURE +/* Check if address a is at least as high as any from MORECORE or MMAP */ +#define ok_address(M, a) ((char*)(a) >= (M)->least_addr) +/* Check if address of next chunk n is higher than base chunk p */ +#define ok_next(p, n) ((char*)(p) < (char*)(n)) +/* Check if p has inuse status */ +#define ok_inuse(p) is_inuse(p) +/* Check if p has its pinuse bit on */ +#define ok_pinuse(p) pinuse(p) + +#else /* !INSECURE */ +#define ok_address(M, a) (1) +#define ok_next(b, n) (1) +#define ok_inuse(p) (1) +#define ok_pinuse(p) (1) +#endif /* !INSECURE */ + +#if (FOOTERS && !INSECURE) +/* Check if (alleged) mstate m has expected magic field */ +#define ok_magic(M) ((M)->magic == mparams.magic) +#else /* (FOOTERS && !INSECURE) */ +#define ok_magic(M) (1) +#endif /* (FOOTERS && !INSECURE) */ + +/* In gcc, use __builtin_expect to minimize impact of checks */ +#if !INSECURE +#if defined(__GNUC__) && __GNUC__ >= 3 +#define RTCHECK(e) __builtin_expect(e, 1) +#else /* GNUC */ +#define RTCHECK(e) (e) +#endif /* GNUC */ +#else /* !INSECURE */ +#define RTCHECK(e) (1) +#endif /* !INSECURE */ + +/* macros to set up inuse chunks with or without footers */ + +#if !FOOTERS + +#define mark_inuse_foot(M,p,s) + +/* Macros for setting head/foot of non-mmapped chunks */ + +/* Set cinuse bit and pinuse bit of next chunk */ +#define set_inuse(M,p,s)\ + ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ + ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) + +/* Set cinuse and pinuse of this chunk and pinuse of next chunk */ +#define set_inuse_and_pinuse(M,p,s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) + +/* Set size, cinuse and pinuse bit of this chunk */ +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT)) + +#else /* FOOTERS */ + +/* Set foot of inuse chunk to be xor of mstate and seed */ +#define mark_inuse_foot(M,p,s)\ + (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic)) + +#define get_mstate_for(p)\ + ((mstate)(((mchunkptr)((char*)(p) +\ + (chunksize(p))))->prev_foot ^ mparams.magic)) + +#define set_inuse(M,p,s)\ + ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ + (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \ + mark_inuse_foot(M,p,s)) + +#define set_inuse_and_pinuse(M,p,s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\ + mark_inuse_foot(M,p,s)) + +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + mark_inuse_foot(M, p, s)) + +#endif /* !FOOTERS */ + +/* ---------------------------- setting mparams -------------------------- */ + +#if LOCK_AT_FORK +static void pre_fork(void) { ACQUIRE_LOCK(&(gm)->mutex); } +static void post_fork_parent(void) { RELEASE_LOCK(&(gm)->mutex); } +static void post_fork_child(void) { INITIAL_LOCK(&(gm)->mutex); } +#endif /* LOCK_AT_FORK */ + +/* Initialize mparams */ +static int init_mparams(void) { +#ifdef NEED_GLOBAL_LOCK_INIT + if (malloc_global_mutex_status <= 0) + init_malloc_global_mutex(); +#endif + + ACQUIRE_MALLOC_GLOBAL_LOCK(); + if (mparams.magic == 0) { + size_t magic; + size_t psize; + size_t gsize; + +#ifndef WIN32 + psize = malloc_getpagesize; + gsize = ((DEFAULT_GRANULARITY != 0)? DEFAULT_GRANULARITY : psize); +#else /* WIN32 */ + { + SYSTEM_INFO system_info; + GetSystemInfo(&system_info); + psize = system_info.dwPageSize; + gsize = ((DEFAULT_GRANULARITY != 0)? + DEFAULT_GRANULARITY : system_info.dwAllocationGranularity); + } +#endif /* WIN32 */ + + /* Sanity-check configuration: + size_t must be unsigned and as wide as pointer type. + ints must be at least 4 bytes. + alignment must be at least 8. + Alignment, min chunk size, and page size must all be powers of 2. + */ + if ((sizeof(size_t) != sizeof(char*)) || + (MAX_SIZE_T < MIN_CHUNK_SIZE) || + (sizeof(int) < 4) || + (MALLOC_ALIGNMENT < (size_t)8U) || + ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) || + ((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) || + ((gsize & (gsize-SIZE_T_ONE)) != 0) || + ((psize & (psize-SIZE_T_ONE)) != 0)) + ABORT; + mparams.granularity = gsize; + mparams.page_size = psize; + mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD; + mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD; +#if MORECORE_CONTIGUOUS + mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT; +#else /* MORECORE_CONTIGUOUS */ + mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT; +#endif /* MORECORE_CONTIGUOUS */ + +#if !ONLY_MSPACES + /* Set up lock for main malloc area */ + gm->mflags = mparams.default_mflags; + (void)INITIAL_LOCK(&gm->mutex); +#endif +#if LOCK_AT_FORK + pthread_atfork(&pre_fork, &post_fork_parent, &post_fork_child); +#endif + + { +#if USE_DEV_RANDOM + int fd; + unsigned char buf[sizeof(size_t)]; + /* Try to use /dev/urandom, else fall back on using time */ + if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 && + read(fd, buf, sizeof(buf)) == sizeof(buf)) { + magic = *((size_t *) buf); + close(fd); + } + else +#endif /* USE_DEV_RANDOM */ +#ifdef WIN32 + magic = (size_t)(GetTickCount() ^ (size_t)0x55555555U); +#elif defined(LACKS_TIME_H) + magic = (size_t)&magic ^ (size_t)0x55555555U; +#else + magic = (size_t)(time(0) ^ (size_t)0x55555555U); +#endif + magic |= (size_t)8U; /* ensure nonzero */ + magic &= ~(size_t)7U; /* improve chances of fault for bad values */ + /* Until memory modes commonly available, use volatile-write */ + (*(volatile size_t *)(&(mparams.magic))) = magic; + } + } + + RELEASE_MALLOC_GLOBAL_LOCK(); + return 1; +} + +/* support for mallopt */ +static int change_mparam(int param_number, int value) { + size_t val; + ensure_initialization(); + val = (value == -1)? MAX_SIZE_T : (size_t)value; + switch(param_number) { + case M_TRIM_THRESHOLD: + mparams.trim_threshold = val; + return 1; + case M_GRANULARITY: + if (val >= mparams.page_size && ((val & (val-1)) == 0)) { + mparams.granularity = val; + return 1; + } + else + return 0; + case M_MMAP_THRESHOLD: + mparams.mmap_threshold = val; + return 1; + default: + return 0; + } +} + +#if DEBUG +/* ------------------------- Debugging Support --------------------------- */ + +/* Check properties of any chunk, whether free, inuse, mmapped etc */ +static void do_check_any_chunk(mstate m, mchunkptr p) { + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); +} + +/* Check properties of top chunk */ +static void do_check_top_chunk(mstate m, mchunkptr p) { + msegmentptr sp = segment_holding(m, (char*)p); + size_t sz = p->head & ~INUSE_BITS; /* third-lowest bit can be set! */ + assert(sp != 0); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(sz == m->topsize); + assert(sz > 0); + assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE); + assert(pinuse(p)); + assert(!pinuse(chunk_plus_offset(p, sz))); +} + +/* Check properties of (inuse) mmapped chunks */ +static void do_check_mmapped_chunk(mstate m, mchunkptr p) { + size_t sz = chunksize(p); + size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD); + assert(is_mmapped(p)); + assert(use_mmap(m)); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(!is_small(sz)); + assert((len & (mparams.page_size-SIZE_T_ONE)) == 0); + assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD); + assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0); +} + +/* Check properties of inuse chunks */ +static void do_check_inuse_chunk(mstate m, mchunkptr p) { + do_check_any_chunk(m, p); + assert(is_inuse(p)); + assert(next_pinuse(p)); + /* If not pinuse and not mmapped, previous chunk has OK offset */ + assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p); + if (is_mmapped(p)) + do_check_mmapped_chunk(m, p); +} + +/* Check properties of free chunks */ +static void do_check_free_chunk(mstate m, mchunkptr p) { + size_t sz = chunksize(p); + mchunkptr next = chunk_plus_offset(p, sz); + do_check_any_chunk(m, p); + assert(!is_inuse(p)); + assert(!next_pinuse(p)); + assert (!is_mmapped(p)); + if (p != m->dv && p != m->top) { + if (sz >= MIN_CHUNK_SIZE) { + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(is_aligned(chunk2mem(p))); + assert(next->prev_foot == sz); + assert(pinuse(p)); + assert (next == m->top || is_inuse(next)); + assert(p->fd->bk == p); + assert(p->bk->fd == p); + } + else /* markers are always of size SIZE_T_SIZE */ + assert(sz == SIZE_T_SIZE); + } +} + +/* Check properties of malloced chunks at the point they are malloced */ +static void do_check_malloced_chunk(mstate m, void* mem, size_t s) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + size_t sz = p->head & ~INUSE_BITS; + do_check_inuse_chunk(m, p); + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(sz >= MIN_CHUNK_SIZE); + assert(sz >= s); + /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */ + assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE)); + } +} + +/* Check a tree and its subtrees. */ +static void do_check_tree(mstate m, tchunkptr t) { + tchunkptr head = 0; + tchunkptr u = t; + bindex_t tindex = t->index; + size_t tsize = chunksize(t); + bindex_t idx; + compute_tree_index(tsize, idx); + assert(tindex == idx); + assert(tsize >= MIN_LARGE_SIZE); + assert(tsize >= minsize_for_tree_index(idx)); + assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1)))); + + do { /* traverse through chain of same-sized nodes */ + do_check_any_chunk(m, ((mchunkptr)u)); + assert(u->index == tindex); + assert(chunksize(u) == tsize); + assert(!is_inuse(u)); + assert(!next_pinuse(u)); + assert(u->fd->bk == u); + assert(u->bk->fd == u); + if (u->parent == 0) { + assert(u->child[0] == 0); + assert(u->child[1] == 0); + } + else { + assert(head == 0); /* only one node on chain has parent */ + head = u; + assert(u->parent != u); + assert (u->parent->child[0] == u || + u->parent->child[1] == u || + *((tbinptr*)(u->parent)) == u); + if (u->child[0] != 0) { + assert(u->child[0]->parent == u); + assert(u->child[0] != u); + do_check_tree(m, u->child[0]); + } + if (u->child[1] != 0) { + assert(u->child[1]->parent == u); + assert(u->child[1] != u); + do_check_tree(m, u->child[1]); + } + if (u->child[0] != 0 && u->child[1] != 0) { + assert(chunksize(u->child[0]) < chunksize(u->child[1])); + } + } + u = u->fd; + } while (u != t); + assert(head != 0); +} + +/* Check all the chunks in a treebin. */ +static void do_check_treebin(mstate m, bindex_t i) { + tbinptr* tb = treebin_at(m, i); + tchunkptr t = *tb; + int empty = (m->treemap & (1U << i)) == 0; + if (t == 0) + assert(empty); + if (!empty) + do_check_tree(m, t); +} + +/* Check all the chunks in a smallbin. */ +static void do_check_smallbin(mstate m, bindex_t i) { + sbinptr b = smallbin_at(m, i); + mchunkptr p = b->bk; + unsigned int empty = (m->smallmap & (1U << i)) == 0; + if (p == b) + assert(empty); + if (!empty) { + for (; p != b; p = p->bk) { + size_t size = chunksize(p); + mchunkptr q; + /* each chunk claims to be free */ + do_check_free_chunk(m, p); + /* chunk belongs in bin */ + assert(small_index(size) == i); + assert(p->bk == b || chunksize(p->bk) == chunksize(p)); + /* chunk is followed by an inuse chunk */ + q = next_chunk(p); + if (q->head != FENCEPOST_HEAD) + do_check_inuse_chunk(m, q); + } + } +} + +/* Find x in a bin. Used in other check functions. */ +static int bin_find(mstate m, mchunkptr x) { + size_t size = chunksize(x); + if (is_small(size)) { + bindex_t sidx = small_index(size); + sbinptr b = smallbin_at(m, sidx); + if (smallmap_is_marked(m, sidx)) { + mchunkptr p = b; + do { + if (p == x) + return 1; + } while ((p = p->fd) != b); + } + } + else { + bindex_t tidx; + compute_tree_index(size, tidx); + if (treemap_is_marked(m, tidx)) { + tchunkptr t = *treebin_at(m, tidx); + size_t sizebits = size << leftshift_for_tree_index(tidx); + while (t != 0 && chunksize(t) != size) { + t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; + sizebits <<= 1; + } + if (t != 0) { + tchunkptr u = t; + do { + if (u == (tchunkptr)x) + return 1; + } while ((u = u->fd) != t); + } + } + } + return 0; +} + +/* Traverse each chunk and check it; return total */ +static size_t traverse_and_check(mstate m) { + size_t sum = 0; + if (is_initialized(m)) { + msegmentptr s = &m->seg; + sum += m->topsize + TOP_FOOT_SIZE; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + mchunkptr lastq = 0; + assert(pinuse(q)); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + sum += chunksize(q); + if (is_inuse(q)) { + assert(!bin_find(m, q)); + do_check_inuse_chunk(m, q); + } + else { + assert(q == m->dv || bin_find(m, q)); + assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */ + do_check_free_chunk(m, q); + } + lastq = q; + q = next_chunk(q); + } + s = s->next; + } + } + return sum; +} + + +/* Check all properties of malloc_state. */ +static void do_check_malloc_state(mstate m) { + bindex_t i; + size_t total; + /* check bins */ + for (i = 0; i < NSMALLBINS; ++i) + do_check_smallbin(m, i); + for (i = 0; i < NTREEBINS; ++i) + do_check_treebin(m, i); + + if (m->dvsize != 0) { /* check dv chunk */ + do_check_any_chunk(m, m->dv); + assert(m->dvsize == chunksize(m->dv)); + assert(m->dvsize >= MIN_CHUNK_SIZE); + assert(bin_find(m, m->dv) == 0); + } + + if (m->top != 0) { /* check top chunk */ + do_check_top_chunk(m, m->top); + /*assert(m->topsize == chunksize(m->top)); redundant */ + assert(m->topsize > 0); + assert(bin_find(m, m->top) == 0); + } + + total = traverse_and_check(m); + assert(total <= m->footprint); + assert(m->footprint <= m->max_footprint); +} +#endif /* DEBUG */ + +/* ----------------------------- statistics ------------------------------ */ + +#if !NO_MALLINFO +static struct mallinfo internal_mallinfo(mstate m) { + struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + ensure_initialization(); + if (!PREACTION(m)) { + check_malloc_state(m); + if (is_initialized(m)) { + size_t nfree = SIZE_T_ONE; /* top always free */ + size_t mfree = m->topsize + TOP_FOOT_SIZE; + size_t sum = mfree; + msegmentptr s = &m->seg; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + size_t sz = chunksize(q); + sum += sz; + if (!is_inuse(q)) { + mfree += sz; + ++nfree; + } + q = next_chunk(q); + } + s = s->next; + } + + nm.arena = sum; + nm.ordblks = nfree; + nm.hblkhd = m->footprint - sum; + nm.usmblks = m->max_footprint; + nm.uordblks = m->footprint - mfree; + nm.fordblks = mfree; + nm.keepcost = m->topsize; + } + + POSTACTION(m); + } + return nm; +} +#endif /* !NO_MALLINFO */ + +#if !NO_MALLOC_STATS +static void internal_malloc_stats(mstate m) { + ensure_initialization(); + if (!PREACTION(m)) { + size_t maxfp = 0; + size_t fp = 0; + size_t used = 0; + check_malloc_state(m); + if (is_initialized(m)) { + msegmentptr s = &m->seg; + maxfp = m->max_footprint; + fp = m->footprint; + used = fp - (m->topsize + TOP_FOOT_SIZE); + + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + if (!is_inuse(q)) + used -= chunksize(q); + q = next_chunk(q); + } + s = s->next; + } + } + POSTACTION(m); /* drop lock */ + fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp)); + fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp)); + fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used)); + } +} +#endif /* NO_MALLOC_STATS */ + +/* ----------------------- Operations on smallbins ----------------------- */ + +/* + Various forms of linking and unlinking are defined as macros. Even + the ones for trees, which are very long but have very short typical + paths. This is ugly but reduces reliance on inlining support of + compilers. +*/ + +/* Link a free chunk into a smallbin */ +#define insert_small_chunk(M, P, S) {\ + bindex_t I = small_index(S);\ + mchunkptr B = smallbin_at(M, I);\ + mchunkptr F = B;\ + assert(S >= MIN_CHUNK_SIZE);\ + if (!smallmap_is_marked(M, I))\ + mark_smallmap(M, I);\ + else if (RTCHECK(ok_address(M, B->fd)))\ + F = B->fd;\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + B->fd = P;\ + F->bk = P;\ + P->fd = F;\ + P->bk = B;\ +} + +/* Unlink a chunk from a smallbin */ +#define unlink_small_chunk(M, P, S) {\ + mchunkptr F = P->fd;\ + mchunkptr B = P->bk;\ + bindex_t I = small_index(S);\ + assert(P != B);\ + assert(P != F);\ + assert(chunksize(P) == small_index2size(I));\ + if (RTCHECK(F == smallbin_at(M,I) || (ok_address(M, F) && F->bk == P))) { \ + if (B == F) {\ + clear_smallmap(M, I);\ + }\ + else if (RTCHECK(B == smallbin_at(M,I) ||\ + (ok_address(M, B) && B->fd == P))) {\ + F->bk = B;\ + B->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ +} + +/* Unlink the first chunk from a smallbin */ +#define unlink_first_small_chunk(M, B, P, I) {\ + mchunkptr F = P->fd;\ + assert(P != B);\ + assert(P != F);\ + assert(chunksize(P) == small_index2size(I));\ + if (B == F) {\ + clear_smallmap(M, I);\ + }\ + else if (RTCHECK(ok_address(M, F) && F->bk == P)) {\ + F->bk = B;\ + B->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ +} + +/* Replace dv node, binning the old one */ +/* Used only when dvsize known to be small */ +#define replace_dv(M, P, S) {\ + size_t DVS = M->dvsize;\ + assert(is_small(DVS));\ + if (DVS != 0) {\ + mchunkptr DV = M->dv;\ + insert_small_chunk(M, DV, DVS);\ + }\ + M->dvsize = S;\ + M->dv = P;\ +} + +/* ------------------------- Operations on trees ------------------------- */ + +/* Insert chunk into tree */ +#define insert_large_chunk(M, X, S) {\ + tbinptr* H;\ + bindex_t I;\ + compute_tree_index(S, I);\ + H = treebin_at(M, I);\ + X->index = I;\ + X->child[0] = X->child[1] = 0;\ + if (!treemap_is_marked(M, I)) {\ + mark_treemap(M, I);\ + *H = X;\ + X->parent = (tchunkptr)H;\ + X->fd = X->bk = X;\ + }\ + else {\ + tchunkptr T = *H;\ + size_t K = S << leftshift_for_tree_index(I);\ + for (;;) {\ + if (chunksize(T) != S) {\ + tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\ + K <<= 1;\ + if (*C != 0)\ + T = *C;\ + else if (RTCHECK(ok_address(M, C))) {\ + *C = X;\ + X->parent = T;\ + X->fd = X->bk = X;\ + break;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + break;\ + }\ + }\ + else {\ + tchunkptr F = T->fd;\ + if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\ + T->fd = F->bk = X;\ + X->fd = F;\ + X->bk = T;\ + X->parent = 0;\ + break;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + break;\ + }\ + }\ + }\ + }\ +} + +/* + Unlink steps: + + 1. If x is a chained node, unlink it from its same-sized fd/bk links + and choose its bk node as its replacement. + 2. If x was the last node of its size, but not a leaf node, it must + be replaced with a leaf node (not merely one with an open left or + right), to make sure that lefts and rights of descendents + correspond properly to bit masks. We use the rightmost descendent + of x. We could use any other leaf, but this is easy to locate and + tends to counteract removal of leftmosts elsewhere, and so keeps + paths shorter than minimally guaranteed. This doesn't loop much + because on average a node in a tree is near the bottom. + 3. If x is the base of a chain (i.e., has parent links) relink + x's parent and children to x's replacement (or null if none). +*/ + +#define unlink_large_chunk(M, X) {\ + tchunkptr XP = X->parent;\ + tchunkptr R;\ + if (X->bk != X) {\ + tchunkptr F = X->fd;\ + R = X->bk;\ + if (RTCHECK(ok_address(M, F) && F->bk == X && R->fd == X)) {\ + F->bk = R;\ + R->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else {\ + tchunkptr* RP;\ + if (((R = *(RP = &(X->child[1]))) != 0) ||\ + ((R = *(RP = &(X->child[0]))) != 0)) {\ + tchunkptr* CP;\ + while ((*(CP = &(R->child[1])) != 0) ||\ + (*(CP = &(R->child[0])) != 0)) {\ + R = *(RP = CP);\ + }\ + if (RTCHECK(ok_address(M, RP)))\ + *RP = 0;\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + }\ + if (XP != 0) {\ + tbinptr* H = treebin_at(M, X->index);\ + if (X == *H) {\ + if ((*H = R) == 0) \ + clear_treemap(M, X->index);\ + }\ + else if (RTCHECK(ok_address(M, XP))) {\ + if (XP->child[0] == X) \ + XP->child[0] = R;\ + else \ + XP->child[1] = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + if (R != 0) {\ + if (RTCHECK(ok_address(M, R))) {\ + tchunkptr C0, C1;\ + R->parent = XP;\ + if ((C0 = X->child[0]) != 0) {\ + if (RTCHECK(ok_address(M, C0))) {\ + R->child[0] = C0;\ + C0->parent = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + if ((C1 = X->child[1]) != 0) {\ + if (RTCHECK(ok_address(M, C1))) {\ + R->child[1] = C1;\ + C1->parent = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ +} + +/* Relays to large vs small bin operations */ + +#define insert_chunk(M, P, S)\ + if (is_small(S)) insert_small_chunk(M, P, S)\ + else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); } + +#define unlink_chunk(M, P, S)\ + if (is_small(S)) unlink_small_chunk(M, P, S)\ + else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); } + + +/* Relays to internal calls to malloc/free from realloc, memalign etc */ + +#if ONLY_MSPACES +#define internal_malloc(m, b) mspace_malloc(m, b) +#define internal_free(m, mem) mspace_free(m,mem); +#else /* ONLY_MSPACES */ +#if MSPACES +#define internal_malloc(m, b)\ + ((m == gm)? dlmalloc(b) : mspace_malloc(m, b)) +#define internal_free(m, mem)\ + if (m == gm) dlfree(mem); else mspace_free(m,mem); +#else /* MSPACES */ +#define internal_malloc(m, b) dlmalloc(b) +#define internal_free(m, mem) dlfree(mem) +#endif /* MSPACES */ +#endif /* ONLY_MSPACES */ + +/* ----------------------- Direct-mmapping chunks ----------------------- */ + +/* + Directly mmapped chunks are set up with an offset to the start of + the mmapped region stored in the prev_foot field of the chunk. This + allows reconstruction of the required argument to MUNMAP when freed, + and also allows adjustment of the returned chunk to meet alignment + requirements (especially in memalign). +*/ + +/* Malloc using mmap */ +static void* mmap_alloc(mstate m, size_t nb) { + size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + if (m->footprint_limit != 0) { + size_t fp = m->footprint + mmsize; + if (fp <= m->footprint || fp > m->footprint_limit) + return 0; + } + if (mmsize > nb) { /* Check for wrap around 0 */ + char* mm = (char*)(CALL_DIRECT_MMAP(mmsize)); + if (mm != CMFAIL) { + size_t offset = align_offset(chunk2mem(mm)); + size_t psize = mmsize - offset - MMAP_FOOT_PAD; + mchunkptr p = (mchunkptr)(mm + offset); + p->prev_foot = offset; + p->head = psize; + mark_inuse_foot(m, p, psize); + chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0; + + if (m->least_addr == 0 || mm < m->least_addr) + m->least_addr = mm; + if ((m->footprint += mmsize) > m->max_footprint) + m->max_footprint = m->footprint; + assert(is_aligned(chunk2mem(p))); + check_mmapped_chunk(m, p); + return chunk2mem(p); + } + } + return 0; +} + +/* Realloc using mmap */ +static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb, int flags) { + size_t oldsize = chunksize(oldp); + (void)flags; /* placate people compiling -Wunused */ + if (is_small(nb)) /* Can't shrink mmap regions below small size */ + return 0; + /* Keep old chunk if big enough but not too big */ + if (oldsize >= nb + SIZE_T_SIZE && + (oldsize - nb) <= (mparams.granularity << 1)) + return oldp; + else { + size_t offset = oldp->prev_foot; + size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD; + size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + char* cp = (char*)CALL_MREMAP((char*)oldp - offset, + oldmmsize, newmmsize, flags); + if (cp != CMFAIL) { + mchunkptr newp = (mchunkptr)(cp + offset); + size_t psize = newmmsize - offset - MMAP_FOOT_PAD; + newp->head = psize; + mark_inuse_foot(m, newp, psize); + chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0; + + if (cp < m->least_addr) + m->least_addr = cp; + if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint) + m->max_footprint = m->footprint; + check_mmapped_chunk(m, newp); + return newp; + } + } + return 0; +} + + +/* -------------------------- mspace management -------------------------- */ + +/* Initialize top chunk and its size */ +static void init_top(mstate m, mchunkptr p, size_t psize) { + /* Ensure alignment */ + size_t offset = align_offset(chunk2mem(p)); + p = (mchunkptr)((char*)p + offset); + psize -= offset; + + m->top = p; + m->topsize = psize; + p->head = psize | PINUSE_BIT; + /* set size of fake trailing chunk holding overhead space only once */ + chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE; + m->trim_check = mparams.trim_threshold; /* reset on each update */ +} + +/* Initialize bins for a new mstate that is otherwise zeroed out */ +static void init_bins(mstate m) { + /* Establish circular links for smallbins */ + bindex_t i; + for (i = 0; i < NSMALLBINS; ++i) { + sbinptr bin = smallbin_at(m,i); + bin->fd = bin->bk = bin; + } +} + +#if PROCEED_ON_ERROR + +/* default corruption action */ +static void reset_on_error(mstate m) { + int i; + ++malloc_corruption_error_count; + /* Reinitialize fields to forget about all memory */ + m->smallmap = m->treemap = 0; + m->dvsize = m->topsize = 0; + m->seg.base = 0; + m->seg.size = 0; + m->seg.next = 0; + m->top = m->dv = 0; + for (i = 0; i < NTREEBINS; ++i) + *treebin_at(m, i) = 0; + init_bins(m); +} +#endif /* PROCEED_ON_ERROR */ + +/* Allocate chunk and prepend remainder with chunk in successor base. */ +static void* prepend_alloc(mstate m, char* newbase, char* oldbase, + size_t nb) { + mchunkptr p = align_as_chunk(newbase); + mchunkptr oldfirst = align_as_chunk(oldbase); + size_t psize = (char*)oldfirst - (char*)p; + mchunkptr q = chunk_plus_offset(p, nb); + size_t qsize = psize - nb; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + + assert((char*)oldfirst > (char*)q); + assert(pinuse(oldfirst)); + assert(qsize >= MIN_CHUNK_SIZE); + + /* consolidate remainder with first chunk of old base */ + if (oldfirst == m->top) { + size_t tsize = m->topsize += qsize; + m->top = q; + q->head = tsize | PINUSE_BIT; + check_top_chunk(m, q); + } + else if (oldfirst == m->dv) { + size_t dsize = m->dvsize += qsize; + m->dv = q; + set_size_and_pinuse_of_free_chunk(q, dsize); + } + else { + if (!is_inuse(oldfirst)) { + size_t nsize = chunksize(oldfirst); + unlink_chunk(m, oldfirst, nsize); + oldfirst = chunk_plus_offset(oldfirst, nsize); + qsize += nsize; + } + set_free_with_pinuse(q, qsize, oldfirst); + insert_chunk(m, q, qsize); + check_free_chunk(m, q); + } + + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); +} + +/* Add a segment to hold a new noncontiguous region */ +static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) { + /* Determine locations and sizes of segment, fenceposts, old top */ + char* old_top = (char*)m->top; + msegmentptr oldsp = segment_holding(m, old_top); + char* old_end = oldsp->base + oldsp->size; + size_t ssize = pad_request(sizeof(struct malloc_segment)); + char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + size_t offset = align_offset(chunk2mem(rawsp)); + char* asp = rawsp + offset; + char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp; + mchunkptr sp = (mchunkptr)csp; + msegmentptr ss = (msegmentptr)(chunk2mem(sp)); + mchunkptr tnext = chunk_plus_offset(sp, ssize); + mchunkptr p = tnext; + int nfences = 0; + + /* reset top to new space */ + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + + /* Set up segment record */ + assert(is_aligned(ss)); + set_size_and_pinuse_of_inuse_chunk(m, sp, ssize); + *ss = m->seg; /* Push current record */ + m->seg.base = tbase; + m->seg.size = tsize; + m->seg.sflags = mmapped; + m->seg.next = ss; + + /* Insert trailing fenceposts */ + for (;;) { + mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE); + p->head = FENCEPOST_HEAD; + ++nfences; + if ((char*)(&(nextp->head)) < old_end) + p = nextp; + else + break; + } + assert(nfences >= 2); + + /* Insert the rest of old top into a bin as an ordinary free chunk */ + if (csp != old_top) { + mchunkptr q = (mchunkptr)old_top; + size_t psize = csp - old_top; + mchunkptr tn = chunk_plus_offset(q, psize); + set_free_with_pinuse(q, psize, tn); + insert_chunk(m, q, psize); + } + + check_top_chunk(m, m->top); +} + +/* -------------------------- System allocation -------------------------- */ + +/* Get memory from system using MORECORE or MMAP */ +static void* sys_alloc(mstate m, size_t nb) { + char* tbase = CMFAIL; + size_t tsize = 0; + flag_t mmap_flag = 0; + size_t asize; /* allocation size */ + + ensure_initialization(); + + /* Directly map large chunks, but only if already initialized */ + if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) { + void* mem = mmap_alloc(m, nb); + if (mem != 0) + return mem; + } + + asize = granularity_align(nb + SYS_ALLOC_PADDING); + if (asize <= nb) + return 0; /* wraparound */ + if (m->footprint_limit != 0) { + size_t fp = m->footprint + asize; + if (fp <= m->footprint || fp > m->footprint_limit) + return 0; + } + + /* + Try getting memory in any of three ways (in most-preferred to + least-preferred order): + 1. A call to MORECORE that can normally contiguously extend memory. + (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or + or main space is mmapped or a previous contiguous call failed) + 2. A call to MMAP new space (disabled if not HAVE_MMAP). + Note that under the default settings, if MORECORE is unable to + fulfill a request, and HAVE_MMAP is true, then mmap is + used as a noncontiguous system allocator. This is a useful backup + strategy for systems with holes in address spaces -- in this case + sbrk cannot contiguously expand the heap, but mmap may be able to + find space. + 3. A call to MORECORE that cannot usually contiguously extend memory. + (disabled if not HAVE_MORECORE) + + In all cases, we need to request enough bytes from system to ensure + we can malloc nb bytes upon success, so pad with enough space for + top_foot, plus alignment-pad to make sure we don't lose bytes if + not on boundary, and round this up to a granularity unit. + */ + + if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) { + char* br = CMFAIL; + size_t ssize = asize; /* sbrk call size */ + msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top); + ACQUIRE_MALLOC_GLOBAL_LOCK(); + + if (ss == 0) { /* First time through or recovery */ + char* base = (char*)CALL_MORECORE(0); + if (base != CMFAIL) { + size_t fp; + /* Adjust to end on a page boundary */ + if (!is_page_aligned(base)) + ssize += (page_align((size_t)base) - (size_t)base); + fp = m->footprint + ssize; /* recheck limits */ + if (ssize > nb && ssize < HALF_MAX_SIZE_T && + (m->footprint_limit == 0 || + (fp > m->footprint && fp <= m->footprint_limit)) && + (br = (char*)(CALL_MORECORE(ssize))) == base) { + tbase = base; + tsize = ssize; + } + } + } + else { + /* Subtract out existing available top space from MORECORE request. */ + ssize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING); + /* Use mem here only if it did continuously extend old space */ + if (ssize < HALF_MAX_SIZE_T && + (br = (char*)(CALL_MORECORE(ssize))) == ss->base+ss->size) { + tbase = br; + tsize = ssize; + } + } + + if (tbase == CMFAIL) { /* Cope with partial failure */ + if (br != CMFAIL) { /* Try to use/extend the space we did get */ + if (ssize < HALF_MAX_SIZE_T && + ssize < nb + SYS_ALLOC_PADDING) { + size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - ssize); + if (esize < HALF_MAX_SIZE_T) { + char* end = (char*)CALL_MORECORE(esize); + if (end != CMFAIL) + ssize += esize; + else { /* Can't use; try to release */ + (void) CALL_MORECORE(-ssize); + br = CMFAIL; + } + } + } + } + if (br != CMFAIL) { /* Use the space we did get */ + tbase = br; + tsize = ssize; + } + else + disable_contiguous(m); /* Don't try contiguous path in the future */ + } + + RELEASE_MALLOC_GLOBAL_LOCK(); + } + + if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */ + char* mp = (char*)(CALL_MMAP(asize)); + if (mp != CMFAIL) { + tbase = mp; + tsize = asize; + mmap_flag = USE_MMAP_BIT; + } + } + + if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */ + if (asize < HALF_MAX_SIZE_T) { + char* br = CMFAIL; + char* end = CMFAIL; + ACQUIRE_MALLOC_GLOBAL_LOCK(); + br = (char*)(CALL_MORECORE(asize)); + end = (char*)(CALL_MORECORE(0)); + RELEASE_MALLOC_GLOBAL_LOCK(); + if (br != CMFAIL && end != CMFAIL && br < end) { + size_t ssize = end - br; + if (ssize > nb + TOP_FOOT_SIZE) { + tbase = br; + tsize = ssize; + } + } + } + } + + if (tbase != CMFAIL) { + + if ((m->footprint += tsize) > m->max_footprint) + m->max_footprint = m->footprint; + + if (!is_initialized(m)) { /* first-time initialization */ + if (m->least_addr == 0 || tbase < m->least_addr) + m->least_addr = tbase; + m->seg.base = tbase; + m->seg.size = tsize; + m->seg.sflags = mmap_flag; + m->magic = mparams.magic; + m->release_checks = MAX_RELEASE_CHECK_RATE; + init_bins(m); +#if !ONLY_MSPACES + if (is_global(m)) + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + else +#endif + { + /* Offset top by embedded malloc_state */ + mchunkptr mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE); + } + } + + else { + /* Try to merge with an existing segment */ + msegmentptr sp = &m->seg; + /* Only consider most recent segment if traversal suppressed */ + while (sp != 0 && tbase != sp->base + sp->size) + sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; + if (sp != 0 && + !is_extern_segment(sp) && + (sp->sflags & USE_MMAP_BIT) == mmap_flag && + segment_holds(sp, m->top)) { /* append */ + sp->size += tsize; + init_top(m, m->top, m->topsize + tsize); + } + else { + if (tbase < m->least_addr) + m->least_addr = tbase; + sp = &m->seg; + while (sp != 0 && sp->base != tbase + tsize) + sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; + if (sp != 0 && + !is_extern_segment(sp) && + (sp->sflags & USE_MMAP_BIT) == mmap_flag) { + char* oldbase = sp->base; + sp->base = tbase; + sp->size += tsize; + return prepend_alloc(m, tbase, oldbase, nb); + } + else + add_segment(m, tbase, tsize, mmap_flag); + } + } + + if (nb < m->topsize) { /* Allocate from new or extended top space */ + size_t rsize = m->topsize -= nb; + mchunkptr p = m->top; + mchunkptr r = m->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + check_top_chunk(m, m->top); + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); + } + } + + MALLOC_FAILURE_ACTION; + return 0; +} + +/* ----------------------- system deallocation -------------------------- */ + +/* Unmap and unlink any mmapped segments that don't contain used chunks */ +static size_t release_unused_segments(mstate m) { + size_t released = 0; + int nsegs = 0; + msegmentptr pred = &m->seg; + msegmentptr sp = pred->next; + while (sp != 0) { + char* base = sp->base; + size_t size = sp->size; + msegmentptr next = sp->next; + ++nsegs; + if (is_mmapped_segment(sp) && !is_extern_segment(sp)) { + mchunkptr p = align_as_chunk(base); + size_t psize = chunksize(p); + /* Can unmap if first chunk holds entire segment and not pinned */ + if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) { + tchunkptr tp = (tchunkptr)p; + assert(segment_holds(sp, (char*)sp)); + if (p == m->dv) { + m->dv = 0; + m->dvsize = 0; + } + else { + unlink_large_chunk(m, tp); + } + if (CALL_MUNMAP(base, size) == 0) { + released += size; + m->footprint -= size; + /* unlink obsoleted record */ + sp = pred; + sp->next = next; + } + else { /* back out if cannot unmap */ + insert_large_chunk(m, tp, psize); + } + } + } + if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */ + break; + pred = sp; + sp = next; + } + /* Reset check counter */ + m->release_checks = (((size_t) nsegs > (size_t) MAX_RELEASE_CHECK_RATE)? + (size_t) nsegs : (size_t) MAX_RELEASE_CHECK_RATE); + return released; +} + +static int sys_trim(mstate m, size_t pad) { + size_t released = 0; + ensure_initialization(); + if (pad < MAX_REQUEST && is_initialized(m)) { + pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ + + if (m->topsize > pad) { + /* Shrink top space in granularity-size units, keeping at least one */ + size_t unit = mparams.granularity; + size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit - + SIZE_T_ONE) * unit; + msegmentptr sp = segment_holding(m, (char*)m->top); + + if (!is_extern_segment(sp)) { + if (is_mmapped_segment(sp)) { + if (HAVE_MMAP && + sp->size >= extra && + !has_segment_link(m, sp)) { /* can't shrink if pinned */ + size_t newsize = sp->size - extra; + (void)newsize; /* placate people compiling -Wunused-variable */ + /* Prefer mremap, fall back to munmap */ + if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) || + (CALL_MUNMAP(sp->base + newsize, extra) == 0)) { + released = extra; + } + } + } + else if (HAVE_MORECORE) { + if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */ + extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit; + ACQUIRE_MALLOC_GLOBAL_LOCK(); + { + /* Make sure end of memory is where we last set it. */ + char* old_br = (char*)(CALL_MORECORE(0)); + if (old_br == sp->base + sp->size) { + char* rel_br = (char*)(CALL_MORECORE(-extra)); + char* new_br = (char*)(CALL_MORECORE(0)); + if (rel_br != CMFAIL && new_br < old_br) + released = old_br - new_br; + } + } + RELEASE_MALLOC_GLOBAL_LOCK(); + } + } + + if (released != 0) { + sp->size -= released; + m->footprint -= released; + init_top(m, m->top, m->topsize - released); + check_top_chunk(m, m->top); + } + } + + /* Unmap any unused mmapped segments */ + if (HAVE_MMAP) + released += release_unused_segments(m); + + /* On failure, disable autotrim to avoid repeated failed future calls */ + if (released == 0 && m->topsize > m->trim_check) + m->trim_check = MAX_SIZE_T; + } + + return (released != 0)? 1 : 0; +} + +/* Consolidate and bin a chunk. Differs from exported versions + of free mainly in that the chunk need not be marked as inuse. +*/ +static void dispose_chunk(mstate m, mchunkptr p, size_t psize) { + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + mchunkptr prev; + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + m->footprint -= psize; + return; + } + prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(m, prev))) { /* consolidate backward */ + if (p != m->dv) { + unlink_chunk(m, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + m->dvsize = psize; + set_free_with_pinuse(p, psize, next); + return; + } + } + else { + CORRUPTION_ERROR_ACTION(m); + return; + } + } + if (RTCHECK(ok_address(m, next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == m->top) { + size_t tsize = m->topsize += psize; + m->top = p; + p->head = tsize | PINUSE_BIT; + if (p == m->dv) { + m->dv = 0; + m->dvsize = 0; + } + return; + } + else if (next == m->dv) { + size_t dsize = m->dvsize += psize; + m->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + return; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(m, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == m->dv) { + m->dvsize = psize; + return; + } + } + } + else { + set_free_with_pinuse(p, psize, next); + } + insert_chunk(m, p, psize); + } + else { + CORRUPTION_ERROR_ACTION(m); + } +} + +/* ---------------------------- malloc --------------------------- */ + +/* allocate a large request from the best fitting chunk in a treebin */ +static void* tmalloc_large(mstate m, size_t nb) { + tchunkptr v = 0; + size_t rsize = -nb; /* Unsigned negation */ + tchunkptr t; + bindex_t idx; + compute_tree_index(nb, idx); + if ((t = *treebin_at(m, idx)) != 0) { + /* Traverse tree for this bin looking for node with size == nb */ + size_t sizebits = nb << leftshift_for_tree_index(idx); + tchunkptr rst = 0; /* The deepest untaken right subtree */ + for (;;) { + tchunkptr rt; + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + v = t; + if ((rsize = trem) == 0) + break; + } + rt = t->child[1]; + t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; + if (rt != 0 && rt != t) + rst = rt; + if (t == 0) { + t = rst; /* set t to least subtree holding sizes > nb */ + break; + } + sizebits <<= 1; + } + } + if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */ + binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; + if (leftbits != 0) { + bindex_t i; + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + t = *treebin_at(m, i); + } + } + + while (t != 0) { /* find smallest of tree or subtree */ + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } + t = leftmost_child(t); + } + + /* If dv is a better fit, return 0 so malloc will use it */ + if (v != 0 && rsize < (size_t)(m->dvsize - nb)) { + if (RTCHECK(ok_address(m, v))) { /* split */ + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + insert_chunk(m, r, rsize); + } + return chunk2mem(v); + } + } + CORRUPTION_ERROR_ACTION(m); + } + return 0; +} + +/* allocate a small request from the best fitting chunk in a treebin */ +static void* tmalloc_small(mstate m, size_t nb) { + tchunkptr t, v; + size_t rsize; + bindex_t i; + binmap_t leastbit = least_bit(m->treemap); + compute_bit2idx(leastbit, i); + v = t = *treebin_at(m, i); + rsize = chunksize(t) - nb; + + while ((t = leftmost_child(t)) != 0) { + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } + } + + if (RTCHECK(ok_address(m, v))) { + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(m, r, rsize); + } + return chunk2mem(v); + } + } + + CORRUPTION_ERROR_ACTION(m); + return 0; +} + +#if !ONLY_MSPACES + +void* dlmalloc(size_t bytes) { + /* + Basic algorithm: + If a small request (< 256 bytes minus per-chunk overhead): + 1. If one exists, use a remainderless chunk in associated smallbin. + (Remainderless means that there are too few excess bytes to + represent as a chunk.) + 2. If it is big enough, use the dv chunk, which is normally the + chunk adjacent to the one used for the most recent small request. + 3. If one exists, split the smallest available chunk in a bin, + saving remainder in dv. + 4. If it is big enough, use the top chunk. + 5. If available, get memory from system and use it + Otherwise, for a large request: + 1. Find the smallest available binned chunk that fits, and use it + if it is better fitting than dv chunk, splitting if necessary. + 2. If better fitting than any binned chunk, use the dv chunk. + 3. If it is big enough, use the top chunk. + 4. If request size >= mmap threshold, try to directly mmap this chunk. + 5. If available, get memory from system and use it + + The ugly goto's here ensure that postaction occurs along all paths. + */ + +#if USE_LOCKS + ensure_initialization(); /* initialize in sys_alloc if not using locks */ +#endif + + if (!PREACTION(gm)) { + void* mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = gm->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(gm, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(gm, b, p, idx); + set_inuse_and_pinuse(gm, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (nb > gm->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(gm, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(gm, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(gm, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(gm, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + } + else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + + if (nb <= gm->dvsize) { + size_t rsize = gm->dvsize - nb; + mchunkptr p = gm->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = gm->dv = chunk_plus_offset(p, nb); + gm->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + } + else { /* exhaust dv */ + size_t dvs = gm->dvsize; + gm->dvsize = 0; + gm->dv = 0; + set_inuse_and_pinuse(gm, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (nb < gm->topsize) { /* Split top */ + size_t rsize = gm->topsize -= nb; + mchunkptr p = gm->top; + mchunkptr r = gm->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + mem = chunk2mem(p); + check_top_chunk(gm, gm->top); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + mem = sys_alloc(gm, nb); + + postaction: + POSTACTION(gm); + return mem; + } + + return 0; +} + +/* ---------------------------- free --------------------------- */ + +void dlfree(void* mem) { + /* + Consolidate freed chunks with preceeding or succeeding bordering + free chunks, if they exist, and then place in a bin. Intermixed + with special cases for top, dv, mmapped chunks, and usage errors. + */ + + if (mem != 0) { + mchunkptr p = mem2chunk(mem); +#if FOOTERS + mstate fm = get_mstate_for(p); + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } +#else /* FOOTERS */ +#define fm gm +#endif /* FOOTERS */ + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } + else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } + else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } + else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } + else + set_free_with_pinuse(p, psize, next); + + if (is_small(psize)) { + insert_small_chunk(fm, p, psize); + check_free_chunk(fm, p); + } + else { + tchunkptr tp = (tchunkptr)p; + insert_large_chunk(fm, tp, psize); + check_free_chunk(fm, p); + if (--fm->release_checks == 0) + release_unused_segments(fm); + } + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } +#if !FOOTERS +#undef fm +#endif /* FOOTERS */ +} + +void* dlcalloc(size_t n_elements, size_t elem_size) { + void* mem; + size_t req = 0; + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t)0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = dlmalloc(req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; +} + +#endif /* !ONLY_MSPACES */ + +/* ------------ Internal support for realloc, memalign, etc -------------- */ + +/* Try to realloc; only in-place unless can_move true */ +static mchunkptr try_realloc_chunk(mstate m, mchunkptr p, size_t nb, + int can_move) { + mchunkptr newp = 0; + size_t oldsize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, oldsize); + if (RTCHECK(ok_address(m, p) && ok_inuse(p) && + ok_next(p, next) && ok_pinuse(next))) { + if (is_mmapped(p)) { + newp = mmap_resize(m, p, nb, can_move); + } + else if (oldsize >= nb) { /* already big enough */ + size_t rsize = oldsize - nb; + if (rsize >= MIN_CHUNK_SIZE) { /* split off remainder */ + mchunkptr r = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, r, rsize); + dispose_chunk(m, r, rsize); + } + newp = p; + } + else if (next == m->top) { /* extend into top */ + if (oldsize + m->topsize > nb) { + size_t newsize = oldsize + m->topsize; + size_t newtopsize = newsize - nb; + mchunkptr newtop = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + newtop->head = newtopsize |PINUSE_BIT; + m->top = newtop; + m->topsize = newtopsize; + newp = p; + } + } + else if (next == m->dv) { /* extend into dv */ + size_t dvs = m->dvsize; + if (oldsize + dvs >= nb) { + size_t dsize = oldsize + dvs - nb; + if (dsize >= MIN_CHUNK_SIZE) { + mchunkptr r = chunk_plus_offset(p, nb); + mchunkptr n = chunk_plus_offset(r, dsize); + set_inuse(m, p, nb); + set_size_and_pinuse_of_free_chunk(r, dsize); + clear_pinuse(n); + m->dvsize = dsize; + m->dv = r; + } + else { /* exhaust dv */ + size_t newsize = oldsize + dvs; + set_inuse(m, p, newsize); + m->dvsize = 0; + m->dv = 0; + } + newp = p; + } + } + else if (!cinuse(next)) { /* extend into next free chunk */ + size_t nextsize = chunksize(next); + if (oldsize + nextsize >= nb) { + size_t rsize = oldsize + nextsize - nb; + unlink_chunk(m, next, nextsize); + if (rsize < MIN_CHUNK_SIZE) { + size_t newsize = oldsize + nextsize; + set_inuse(m, p, newsize); + } + else { + mchunkptr r = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, r, rsize); + dispose_chunk(m, r, rsize); + } + newp = p; + } + } + } + else { + USAGE_ERROR_ACTION(m, chunk2mem(p)); + } + return newp; +} + +static void* internal_memalign(mstate m, size_t alignment, size_t bytes) { + void* mem = 0; + if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */ + alignment = MIN_CHUNK_SIZE; + if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */ + size_t a = MALLOC_ALIGNMENT << 1; + while (a < alignment) a <<= 1; + alignment = a; + } + if (bytes >= MAX_REQUEST - alignment) { + if (m != 0) { /* Test isn't needed but avoids compiler warning */ + MALLOC_FAILURE_ACTION; + } + } + else { + size_t nb = request2size(bytes); + size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; + mem = internal_malloc(m, req); + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (PREACTION(m)) + return 0; + if ((((size_t)(mem)) & (alignment - 1)) != 0) { /* misaligned */ + /* + Find an aligned spot inside chunk. Since we need to give + back leading space in a chunk of at least MIN_CHUNK_SIZE, if + the first calculation places us at a spot with less than + MIN_CHUNK_SIZE leader, we can move to the next aligned spot. + We've allocated enough total room so that this is always + possible. + */ + char* br = (char*)mem2chunk((size_t)(((size_t)((char*)mem + alignment - + SIZE_T_ONE)) & + -alignment)); + char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)? + br : br+alignment; + mchunkptr newp = (mchunkptr)pos; + size_t leadsize = pos - (char*)(p); + size_t newsize = chunksize(p) - leadsize; + + if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */ + newp->prev_foot = p->prev_foot + leadsize; + newp->head = newsize; + } + else { /* Otherwise, give back leader, use the rest */ + set_inuse(m, newp, newsize); + set_inuse(m, p, leadsize); + dispose_chunk(m, p, leadsize); + } + p = newp; + } + + /* Give back spare room at the end */ + if (!is_mmapped(p)) { + size_t size = chunksize(p); + if (size > nb + MIN_CHUNK_SIZE) { + size_t remainder_size = size - nb; + mchunkptr remainder = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, remainder, remainder_size); + dispose_chunk(m, remainder, remainder_size); + } + } + + mem = chunk2mem(p); + assert (chunksize(p) >= nb); + assert(((size_t)mem & (alignment - 1)) == 0); + check_inuse_chunk(m, p); + POSTACTION(m); + } + } + return mem; +} + +/* + Common support for independent_X routines, handling + all of the combinations that can result. + The opts arg has: + bit 0 set if all elements are same size (using sizes[0]) + bit 1 set if elements should be zeroed +*/ +static void** ialloc(mstate m, + size_t n_elements, + size_t* sizes, + int opts, + void* chunks[]) { + + size_t element_size; /* chunksize of each element, if all same */ + size_t contents_size; /* total size of elements */ + size_t array_size; /* request size of pointer array */ + void* mem; /* malloced aggregate space */ + mchunkptr p; /* corresponding chunk */ + size_t remainder_size; /* remaining bytes while splitting */ + void** marray; /* either "chunks" or malloced ptr array */ + mchunkptr array_chunk; /* chunk for malloced ptr array */ + flag_t was_enabled; /* to disable mmap */ + size_t size; + size_t i; + + ensure_initialization(); + /* compute array length, if needed */ + if (chunks != 0) { + if (n_elements == 0) + return chunks; /* nothing to do */ + marray = chunks; + array_size = 0; + } + else { + /* if empty req, must still return chunk representing empty array */ + if (n_elements == 0) + return (void**)internal_malloc(m, 0); + marray = 0; + array_size = request2size(n_elements * (sizeof(void*))); + } + + /* compute total element size */ + if (opts & 0x1) { /* all-same-size */ + element_size = request2size(*sizes); + contents_size = n_elements * element_size; + } + else { /* add up all the sizes */ + element_size = 0; + contents_size = 0; + for (i = 0; i != n_elements; ++i) + contents_size += request2size(sizes[i]); + } + + size = contents_size + array_size; + + /* + Allocate the aggregate chunk. First disable direct-mmapping so + malloc won't use it, since we would not be able to later + free/realloc space internal to a segregated mmap region. + */ + was_enabled = use_mmap(m); + disable_mmap(m); + mem = internal_malloc(m, size - CHUNK_OVERHEAD); + if (was_enabled) + enable_mmap(m); + if (mem == 0) + return 0; + + if (PREACTION(m)) return 0; + p = mem2chunk(mem); + remainder_size = chunksize(p); + + assert(!is_mmapped(p)); + + if (opts & 0x2) { /* optionally clear the elements */ + memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size); + } + + /* If not provided, allocate the pointer array as final part of chunk */ + if (marray == 0) { + size_t array_chunk_size; + array_chunk = chunk_plus_offset(p, contents_size); + array_chunk_size = remainder_size - contents_size; + marray = (void**) (chunk2mem(array_chunk)); + set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size); + remainder_size = contents_size; + } + + /* split out elements */ + for (i = 0; ; ++i) { + marray[i] = chunk2mem(p); + if (i != n_elements-1) { + if (element_size != 0) + size = element_size; + else + size = request2size(sizes[i]); + remainder_size -= size; + set_size_and_pinuse_of_inuse_chunk(m, p, size); + p = chunk_plus_offset(p, size); + } + else { /* the final element absorbs any overallocation slop */ + set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); + break; + } + } + +#if DEBUG + if (marray != chunks) { + /* final element must have exactly exhausted chunk */ + if (element_size != 0) { + assert(remainder_size == element_size); + } + else { + assert(remainder_size == request2size(sizes[i])); + } + check_inuse_chunk(m, mem2chunk(marray)); + } + for (i = 0; i != n_elements; ++i) + check_inuse_chunk(m, mem2chunk(marray[i])); + +#endif /* DEBUG */ + + POSTACTION(m); + return marray; +} + +/* Try to free all pointers in the given array. + Note: this could be made faster, by delaying consolidation, + at the price of disabling some user integrity checks, We + still optimize some consolidations by combining adjacent + chunks before freeing, which will occur often if allocated + with ialloc or the array is sorted. +*/ +static size_t internal_bulk_free(mstate m, void* array[], size_t nelem) { + size_t unfreed = 0; + if (!PREACTION(m)) { + void** a; + void** fence = &(array[nelem]); + for (a = array; a != fence; ++a) { + void* mem = *a; + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + size_t psize = chunksize(p); +#if FOOTERS + if (get_mstate_for(p) != m) { + ++unfreed; + continue; + } +#endif + check_inuse_chunk(m, p); + *a = 0; + if (RTCHECK(ok_address(m, p) && ok_inuse(p))) { + void ** b = a + 1; /* try to merge with next chunk */ + mchunkptr next = next_chunk(p); + if (b != fence && *b == chunk2mem(next)) { + size_t newsize = chunksize(next) + psize; + set_inuse(m, p, newsize); + *b = chunk2mem(p); + } + else + dispose_chunk(m, p, psize); + } + else { + CORRUPTION_ERROR_ACTION(m); + break; + } + } + } + if (should_trim(m, m->topsize)) + sys_trim(m, 0); + POSTACTION(m); + } + return unfreed; +} + +/* Traversal */ +#if MALLOC_INSPECT_ALL +static void internal_inspect_all(mstate m, + void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + if (is_initialized(m)) { + mchunkptr top = m->top; + msegmentptr s; + for (s = &m->seg; s != 0; s = s->next) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && q->head != FENCEPOST_HEAD) { + mchunkptr next = next_chunk(q); + size_t sz = chunksize(q); + size_t used; + void* start; + if (is_inuse(q)) { + used = sz - CHUNK_OVERHEAD; /* must not be mmapped */ + start = chunk2mem(q); + } + else { + used = 0; + if (is_small(sz)) { /* offset by possible bookkeeping */ + start = (void*)((char*)q + sizeof(struct malloc_chunk)); + } + else { + start = (void*)((char*)q + sizeof(struct malloc_tree_chunk)); + } + } + if (start < (void*)next) /* skip if all space is bookkeeping */ + handler(start, next, used, arg); + if (q == top) + break; + q = next; + } + } + } +} +#endif /* MALLOC_INSPECT_ALL */ + +/* ------------------ Exported realloc, memalign, etc -------------------- */ + +#if !ONLY_MSPACES + +void* dlrealloc(void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem == 0) { + mem = dlmalloc(bytes); + } + else if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } +#ifdef REALLOC_ZERO_BYTES_FREES + else if (bytes == 0) { + dlfree(oldmem); + } +#endif /* REALLOC_ZERO_BYTES_FREES */ + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = gm; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1); + POSTACTION(m); + if (newp != 0) { + check_inuse_chunk(m, newp); + mem = chunk2mem(newp); + } + else { + mem = internal_malloc(m, bytes); + if (mem != 0) { + size_t oc = chunksize(oldp) - overhead_for(oldp); + memcpy(mem, oldmem, (oc < bytes)? oc : bytes); + internal_free(m, oldmem); + } + } + } + } + return mem; +} + +void* dlrealloc_in_place(void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem != 0) { + if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = gm; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0); + POSTACTION(m); + if (newp == oldp) { + check_inuse_chunk(m, newp); + mem = oldmem; + } + } + } + } + return mem; +} + +void* dlmemalign(size_t alignment, size_t bytes) { + if (alignment <= MALLOC_ALIGNMENT) { + return dlmalloc(bytes); + } + return internal_memalign(gm, alignment, bytes); +} + +int dlposix_memalign(void** pp, size_t alignment, size_t bytes) { + void* mem = 0; + if (alignment == MALLOC_ALIGNMENT) + mem = dlmalloc(bytes); + else { + size_t d = alignment / sizeof(void*); + size_t r = alignment % sizeof(void*); + if (r != 0 || d == 0 || (d & (d-SIZE_T_ONE)) != 0) + return EINVAL; + else if (bytes <= MAX_REQUEST - alignment) { + if (alignment < MIN_CHUNK_SIZE) + alignment = MIN_CHUNK_SIZE; + mem = internal_memalign(gm, alignment, bytes); + } + } + if (mem == 0) + return ENOMEM; + else { + *pp = mem; + return 0; + } +} + +void* dlvalloc(size_t bytes) { + size_t pagesz; + ensure_initialization(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, bytes); +} + +void* dlpvalloc(size_t bytes) { + size_t pagesz; + ensure_initialization(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE)); +} + +void** dlindependent_calloc(size_t n_elements, size_t elem_size, + void* chunks[]) { + size_t sz = elem_size; /* serves as 1-element array */ + return ialloc(gm, n_elements, &sz, 3, chunks); +} + +void** dlindependent_comalloc(size_t n_elements, size_t sizes[], + void* chunks[]) { + return ialloc(gm, n_elements, sizes, 0, chunks); +} + +size_t dlbulk_free(void* array[], size_t nelem) { + return internal_bulk_free(gm, array, nelem); +} + +#if MALLOC_INSPECT_ALL +void dlmalloc_inspect_all(void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + ensure_initialization(); + if (!PREACTION(gm)) { + internal_inspect_all(gm, handler, arg); + POSTACTION(gm); + } +} +#endif /* MALLOC_INSPECT_ALL */ + +int dlmalloc_trim(size_t pad) { + int result = 0; + ensure_initialization(); + if (!PREACTION(gm)) { + result = sys_trim(gm, pad); + POSTACTION(gm); + } + return result; +} + +size_t dlmalloc_footprint(void) { + return gm->footprint; +} + +size_t dlmalloc_max_footprint(void) { + return gm->max_footprint; +} + +size_t dlmalloc_footprint_limit(void) { + size_t maf = gm->footprint_limit; + return maf == 0 ? MAX_SIZE_T : maf; +} + +size_t dlmalloc_set_footprint_limit(size_t bytes) { + ensure_initialization(); + size_t result; /* invert sense of 0 */ + if (bytes == 0) + result = granularity_align(1); /* Use minimal size */ + if (bytes == MAX_SIZE_T) + result = 0; /* disable */ + else + result = granularity_align(bytes); + return gm->footprint_limit = result; +} + +#if !NO_MALLINFO +struct mallinfo dlmallinfo(void) { + return internal_mallinfo(gm); +} +#endif /* NO_MALLINFO */ + +#if !NO_MALLOC_STATS +void dlmalloc_stats() { + internal_malloc_stats(gm); +} +#endif /* NO_MALLOC_STATS */ + +int dlmallopt(int param_number, int value) { + return change_mparam(param_number, value); +} + +size_t dlmalloc_usable_size(void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (is_inuse(p)) + return chunksize(p) - overhead_for(p); + } + return 0; +} + +#endif /* !ONLY_MSPACES */ + +/* ----------------------------- user mspaces ---------------------------- */ + +#if MSPACES + +static mstate init_user_mstate(char* tbase, size_t tsize) { + size_t msize = pad_request(sizeof(struct malloc_state)); + mchunkptr mn; + mchunkptr msp = align_as_chunk(tbase); + mstate m = (mstate)(chunk2mem(msp)); + memset(m, 0, msize); + (void)INITIAL_LOCK(&m->mutex); + msp->head = (msize|INUSE_BITS); + m->seg.base = m->least_addr = tbase; + m->seg.size = m->footprint = m->max_footprint = tsize; + m->magic = mparams.magic; + m->release_checks = MAX_RELEASE_CHECK_RATE; + m->mflags = mparams.default_mflags; + m->extp = 0; + m->exts = 0; + disable_contiguous(m); + init_bins(m); + mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE); + check_top_chunk(m, m->top); + return m; +} + +mspace create_mspace(size_t capacity, int locked) { + mstate m = 0; + size_t msize; + ensure_initialization(); + msize = pad_request(sizeof(struct malloc_state)); + if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { + size_t rs = ((capacity == 0)? mparams.granularity : + (capacity + TOP_FOOT_SIZE + msize)); + size_t tsize = granularity_align(rs); + char* tbase = (char*)(CALL_MMAP(tsize)); + if (tbase != CMFAIL) { + m = init_user_mstate(tbase, tsize); + m->seg.sflags = USE_MMAP_BIT; + set_lock(m, locked); + } + } + return (mspace)m; +} + +mspace create_mspace_with_base(void* base, size_t capacity, int locked) { + mstate m = 0; + size_t msize; + ensure_initialization(); + msize = pad_request(sizeof(struct malloc_state)); + if (capacity > msize + TOP_FOOT_SIZE && + capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { + m = init_user_mstate((char*)base, capacity); + m->seg.sflags = EXTERN_BIT; + set_lock(m, locked); + } + return (mspace)m; +} + +int mspace_track_large_chunks(mspace msp, int enable) { + int ret = 0; + mstate ms = (mstate)msp; + if (!PREACTION(ms)) { + if (!use_mmap(ms)) { + ret = 1; + } + if (!enable) { + enable_mmap(ms); + } else { + disable_mmap(ms); + } + POSTACTION(ms); + } + return ret; +} + +size_t destroy_mspace(mspace msp) { + size_t freed = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + msegmentptr sp = &ms->seg; + (void)DESTROY_LOCK(&ms->mutex); /* destroy before unmapped */ + while (sp != 0) { + char* base = sp->base; + size_t size = sp->size; + flag_t flag = sp->sflags; + (void)base; /* placate people compiling -Wunused-variable */ + sp = sp->next; + if ((flag & USE_MMAP_BIT) && !(flag & EXTERN_BIT) && + CALL_MUNMAP(base, size) == 0) + freed += size; + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return freed; +} + +/* + mspace versions of routines are near-clones of the global + versions. This is not so nice but better than the alternatives. +*/ + +void* mspace_malloc(mspace msp, size_t bytes) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (!PREACTION(ms)) { + void* mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = ms->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(ms, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(ms, b, p, idx); + set_inuse_and_pinuse(ms, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb > ms->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(ms, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(ms, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(ms, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(ms, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + } + else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + + if (nb <= ms->dvsize) { + size_t rsize = ms->dvsize - nb; + mchunkptr p = ms->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = ms->dv = chunk_plus_offset(p, nb); + ms->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + } + else { /* exhaust dv */ + size_t dvs = ms->dvsize; + ms->dvsize = 0; + ms->dv = 0; + set_inuse_and_pinuse(ms, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb < ms->topsize) { /* Split top */ + size_t rsize = ms->topsize -= nb; + mchunkptr p = ms->top; + mchunkptr r = ms->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + mem = chunk2mem(p); + check_top_chunk(ms, ms->top); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + mem = sys_alloc(ms, nb); + + postaction: + POSTACTION(ms); + return mem; + } + + return 0; +} + +void mspace_free(mspace msp, void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); +#if FOOTERS + mstate fm = get_mstate_for(p); + (void)msp; /* placate people compiling -Wunused */ +#else /* FOOTERS */ + mstate fm = (mstate)msp; +#endif /* FOOTERS */ + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } + else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } + else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } + else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } + else + set_free_with_pinuse(p, psize, next); + + if (is_small(psize)) { + insert_small_chunk(fm, p, psize); + check_free_chunk(fm, p); + } + else { + tchunkptr tp = (tchunkptr)p; + insert_large_chunk(fm, tp, psize); + check_free_chunk(fm, p); + if (--fm->release_checks == 0) + release_unused_segments(fm); + } + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } +} + +void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) { + void* mem; + size_t req = 0; + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t)0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = internal_malloc(ms, req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; +} + +void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem == 0) { + mem = mspace_malloc(msp, bytes); + } + else if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } +#ifdef REALLOC_ZERO_BYTES_FREES + else if (bytes == 0) { + mspace_free(msp, oldmem); + } +#endif /* REALLOC_ZERO_BYTES_FREES */ + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = (mstate)msp; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1); + POSTACTION(m); + if (newp != 0) { + check_inuse_chunk(m, newp); + mem = chunk2mem(newp); + } + else { + mem = mspace_malloc(m, bytes); + if (mem != 0) { + size_t oc = chunksize(oldp) - overhead_for(oldp); + memcpy(mem, oldmem, (oc < bytes)? oc : bytes); + mspace_free(m, oldmem); + } + } + } + } + return mem; +} + +void* mspace_realloc_in_place(mspace msp, void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem != 0) { + if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = (mstate)msp; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + (void)msp; /* placate people compiling -Wunused */ + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0); + POSTACTION(m); + if (newp == oldp) { + check_inuse_chunk(m, newp); + mem = oldmem; + } + } + } + } + return mem; +} + +void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (alignment <= MALLOC_ALIGNMENT) + return mspace_malloc(msp, bytes); + return internal_memalign(ms, alignment, bytes); +} + +void** mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void* chunks[]) { + size_t sz = elem_size; /* serves as 1-element array */ + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return ialloc(ms, n_elements, &sz, 3, chunks); +} + +void** mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void* chunks[]) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return ialloc(ms, n_elements, sizes, 0, chunks); +} + +size_t mspace_bulk_free(mspace msp, void* array[], size_t nelem) { + return internal_bulk_free((mstate)msp, array, nelem); +} + +#if MALLOC_INSPECT_ALL +void mspace_inspect_all(mspace msp, + void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (!PREACTION(ms)) { + internal_inspect_all(ms, handler, arg); + POSTACTION(ms); + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } +} +#endif /* MALLOC_INSPECT_ALL */ + +int mspace_trim(mspace msp, size_t pad) { + int result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (!PREACTION(ms)) { + result = sys_trim(ms, pad); + POSTACTION(ms); + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +#if !NO_MALLOC_STATS +void mspace_malloc_stats(mspace msp) { + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + internal_malloc_stats(ms); + } + else { + USAGE_ERROR_ACTION(ms,ms); + } +} +#endif /* NO_MALLOC_STATS */ + +size_t mspace_footprint(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + result = ms->footprint; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_max_footprint(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + result = ms->max_footprint; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_footprint_limit(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + size_t maf = ms->footprint_limit; + result = (maf == 0) ? MAX_SIZE_T : maf; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_set_footprint_limit(mspace msp, size_t bytes) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (bytes == 0) + result = granularity_align(1); /* Use minimal size */ + if (bytes == MAX_SIZE_T) + result = 0; /* disable */ + else + result = granularity_align(bytes); + ms->footprint_limit = result; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +#if !NO_MALLINFO +struct mallinfo mspace_mallinfo(mspace msp) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + } + return internal_mallinfo(ms); +} +#endif /* NO_MALLINFO */ + +size_t mspace_usable_size(const void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (is_inuse(p)) + return chunksize(p) - overhead_for(p); + } + return 0; +} + +int mspace_mallopt(int param_number, int value) { + return change_mparam(param_number, value); +} + +#endif /* MSPACES */ + + +/* -------------------- Alternative MORECORE functions ------------------- */ + +/* + Guidelines for creating a custom version of MORECORE: + + * For best performance, MORECORE should allocate in multiples of pagesize. + * MORECORE may allocate more memory than requested. (Or even less, + but this will usually result in a malloc failure.) + * MORECORE must not allocate memory when given argument zero, but + instead return one past the end address of memory from previous + nonzero call. + * For best performance, consecutive calls to MORECORE with positive + arguments should return increasing addresses, indicating that + space has been contiguously extended. + * Even though consecutive calls to MORECORE need not return contiguous + addresses, it must be OK for malloc'ed chunks to span multiple + regions in those cases where they do happen to be contiguous. + * MORECORE need not handle negative arguments -- it may instead + just return MFAIL when given negative arguments. + Negative arguments are always multiples of pagesize. MORECORE + must not misinterpret negative args as large positive unsigned + args. You can suppress all such calls from even occurring by defining + MORECORE_CANNOT_TRIM, + + As an example alternative MORECORE, here is a custom allocator + kindly contributed for pre-OSX macOS. It uses virtually but not + necessarily physically contiguous non-paged memory (locked in, + present and won't get swapped out). You can use it by uncommenting + this section, adding some #includes, and setting up the appropriate + defines above: + + #define MORECORE osMoreCore + + There is also a shutdown routine that should somehow be called for + cleanup upon program exit. + + #define MAX_POOL_ENTRIES 100 + #define MINIMUM_MORECORE_SIZE (64 * 1024U) + static int next_os_pool; + void *our_os_pools[MAX_POOL_ENTRIES]; + + void *osMoreCore(int size) + { + void *ptr = 0; + static void *sbrk_top = 0; + + if (size > 0) + { + if (size < MINIMUM_MORECORE_SIZE) + size = MINIMUM_MORECORE_SIZE; + if (CurrentExecutionLevel() == kTaskLevel) + ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0); + if (ptr == 0) + { + return (void *) MFAIL; + } + // save ptrs so they can be freed during cleanup + our_os_pools[next_os_pool] = ptr; + next_os_pool++; + ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK); + sbrk_top = (char *) ptr + size; + return ptr; + } + else if (size < 0) + { + // we don't currently support shrink behavior + return (void *) MFAIL; + } + else + { + return sbrk_top; + } + } + + // cleanup any allocated memory pools + // called as last thing before shutting down driver + + void osCleanupMem(void) + { + void **ptr; + + for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++) + if (*ptr) + { + PoolDeallocate(*ptr); + *ptr = 0; + } + } + +*/ + + +/* ----------------------------------------------------------------------- +History: + v2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea + * fix bad comparison in dlposix_memalign + * don't reuse adjusted asize in sys_alloc + * add LOCK_AT_FORK -- thanks to Kirill Artamonov for the suggestion + * reduce compiler warnings -- thanks to all who reported/suggested these + + v2.8.5 Sun May 22 10:26:02 2011 Doug Lea (dl at gee) + * Always perform unlink checks unless INSECURE + * Add posix_memalign. + * Improve realloc to expand in more cases; expose realloc_in_place. + Thanks to Peter Buhr for the suggestion. + * Add footprint_limit, inspect_all, bulk_free. Thanks + to Barry Hayes and others for the suggestions. + * Internal refactorings to avoid calls while holding locks + * Use non-reentrant locks by default. Thanks to Roland McGrath + for the suggestion. + * Small fixes to mspace_destroy, reset_on_error. + * Various configuration extensions/changes. Thanks + to all who contributed these. + + V2.8.4a Thu Apr 28 14:39:43 2011 (dl at gee.cs.oswego.edu) + * Update Creative Commons URL + + V2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee) + * Use zeros instead of prev foot for is_mmapped + * Add mspace_track_large_chunks; thanks to Jean Brouwers + * Fix set_inuse in internal_realloc; thanks to Jean Brouwers + * Fix insufficient sys_alloc padding when using 16byte alignment + * Fix bad error check in mspace_footprint + * Adaptations for ptmalloc; thanks to Wolfram Gloger. + * Reentrant spin locks; thanks to Earl Chew and others + * Win32 improvements; thanks to Niall Douglas and Earl Chew + * Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options + * Extension hook in malloc_state + * Various small adjustments to reduce warnings on some compilers + * Various configuration extensions/changes for more platforms. Thanks + to all who contributed these. + + V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee) + * Add max_footprint functions + * Ensure all appropriate literals are size_t + * Fix conditional compilation problem for some #define settings + * Avoid concatenating segments with the one provided + in create_mspace_with_base + * Rename some variables to avoid compiler shadowing warnings + * Use explicit lock initialization. + * Better handling of sbrk interference. + * Simplify and fix segment insertion, trimming and mspace_destroy + * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x + * Thanks especially to Dennis Flanagan for help on these. + + V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee) + * Fix memalign brace error. + + V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee) + * Fix improper #endif nesting in C++ + * Add explicit casts needed for C++ + + V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee) + * Use trees for large bins + * Support mspaces + * Use segments to unify sbrk-based and mmap-based system allocation, + removing need for emulation on most platforms without sbrk. + * Default safety checks + * Optional footer checks. Thanks to William Robertson for the idea. + * Internal code refactoring + * Incorporate suggestions and platform-specific changes. + Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas, + Aaron Bachmann, Emery Berger, and others. + * Speed up non-fastbin processing enough to remove fastbins. + * Remove useless cfree() to avoid conflicts with other apps. + * Remove internal memcpy, memset. Compilers handle builtins better. + * Remove some options that no one ever used and rename others. + + V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee) + * Fix malloc_state bitmap array misdeclaration + + V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee) + * Allow tuning of FIRST_SORTED_BIN_SIZE + * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte. + * Better detection and support for non-contiguousness of MORECORE. + Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger + * Bypass most of malloc if no frees. Thanks To Emery Berger. + * Fix freeing of old top non-contiguous chunk im sysmalloc. + * Raised default trim and map thresholds to 256K. + * Fix mmap-related #defines. Thanks to Lubos Lunak. + * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield. + * Branch-free bin calculation + * Default trim and mmap thresholds now 256K. + + V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee) + * Introduce independent_comalloc and independent_calloc. + Thanks to Michael Pachos for motivation and help. + * Make optional .h file available + * Allow > 2GB requests on 32bit systems. + * new WIN32 sbrk, mmap, munmap, lock code from . + Thanks also to Andreas Mueller , + and Anonymous. + * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for + helping test this.) + * memalign: check alignment arg + * realloc: don't try to shift chunks backwards, since this + leads to more fragmentation in some programs and doesn't + seem to help in any others. + * Collect all cases in malloc requiring system memory into sysmalloc + * Use mmap as backup to sbrk + * Place all internal state in malloc_state + * Introduce fastbins (although similar to 2.5.1) + * Many minor tunings and cosmetic improvements + * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK + * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS + Thanks to Tony E. Bennett and others. + * Include errno.h to support default failure action. + + V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee) + * return null for negative arguments + * Added Several WIN32 cleanups from Martin C. Fong + * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h' + (e.g. WIN32 platforms) + * Cleanup header file inclusion for WIN32 platforms + * Cleanup code to avoid Microsoft Visual C++ compiler complaints + * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing + memory allocation routines + * Set 'malloc_getpagesize' for WIN32 platforms (needs more work) + * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to + usage of 'assert' in non-WIN32 code + * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to + avoid infinite loop + * Always call 'fREe()' rather than 'free()' + + V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee) + * Fixed ordering problem with boundary-stamping + + V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee) + * Added pvalloc, as recommended by H.J. Liu + * Added 64bit pointer support mainly from Wolfram Gloger + * Added anonymously donated WIN32 sbrk emulation + * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen + * malloc_extend_top: fix mask error that caused wastage after + foreign sbrks + * Add linux mremap support code from HJ Liu + + V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee) + * Integrated most documentation with the code. + * Add support for mmap, with help from + Wolfram Gloger (Gloger@lrz.uni-muenchen.de). + * Use last_remainder in more cases. + * Pack bins using idea from colin@nyx10.cs.du.edu + * Use ordered bins instead of best-fit threshhold + * Eliminate block-local decls to simplify tracing and debugging. + * Support another case of realloc via move into top + * Fix error occuring when initial sbrk_base not word-aligned. + * Rely on page size for units instead of SBRK_UNIT to + avoid surprises about sbrk alignment conventions. + * Add mallinfo, mallopt. Thanks to Raymond Nijssen + (raymond@es.ele.tue.nl) for the suggestion. + * Add `pad' argument to malloc_trim and top_pad mallopt parameter. + * More precautions for cases where other routines call sbrk, + courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de). + * Added macros etc., allowing use in linux libc from + H.J. Lu (hjl@gnu.ai.mit.edu) + * Inverted this history list + + V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee) + * Re-tuned and fixed to behave more nicely with V2.6.0 changes. + * Removed all preallocation code since under current scheme + the work required to undo bad preallocations exceeds + the work saved in good cases for most test programs. + * No longer use return list or unconsolidated bins since + no scheme using them consistently outperforms those that don't + given above changes. + * Use best fit for very large chunks to prevent some worst-cases. + * Added some support for debugging + + V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee) + * Removed footers when chunks are in use. Thanks to + Paul Wilson (wilson@cs.texas.edu) for the suggestion. + + V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee) + * Added malloc_trim, with help from Wolfram Gloger + (wmglo@Dent.MED.Uni-Muenchen.DE). + + V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g) + + V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g) + * realloc: try to expand in both directions + * malloc: swap order of clean-bin strategy; + * realloc: only conditionally expand backwards + * Try not to scavenge used bins + * Use bin counts as a guide to preallocation + * Occasionally bin return list chunks in first scan + * Add a few optimizations from colin@nyx10.cs.du.edu + + V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g) + * faster bin computation & slightly different binning + * merged all consolidations to one part of malloc proper + (eliminating old malloc_find_space & malloc_clean_bin) + * Scan 2 returns chunks (not just 1) + * Propagate failure in realloc if malloc returns 0 + * Add stuff to allow compilation on non-ANSI compilers + from kpv@research.att.com + + V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu) + * removed potential for odd address access in prev_chunk + * removed dependency on getpagesize.h + * misc cosmetics and a bit more internal documentation + * anticosmetics: mangled names in macros to evade debugger strangeness + * tested on sparc, hp-700, dec-mips, rs6000 + with gcc & native cc (hp, dec only) allowing + Detlefs & Zorn comparison study (in SIGPLAN Notices.) + + Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu) + * Based loosely on libg++-1.2X malloc. (It retains some of the overall + structure of old version, but most details differ.) + +*/ diff --git a/cpp/src/plasma/thirdparty/xxhash.cc b/cpp/src/plasma/thirdparty/xxhash.cc new file mode 100644 index 00000000000..f74880b0de7 --- /dev/null +++ b/cpp/src/plasma/thirdparty/xxhash.cc @@ -0,0 +1,889 @@ +/* +* xxHash - Fast Hash algorithm +* Copyright (C) 2012-2016, Yann Collet +* +* BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are +* met: +* +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above +* copyright notice, this list of conditions and the following disclaimer +* in the documentation and/or other materials provided with the +* distribution. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +* You can contact the author at : +* - xxHash homepage: http://www.xxhash.com +* - xxHash source repository : https://github.com/Cyan4973/xxHash +*/ + + +/* ************************************* +* Tuning parameters +***************************************/ +/*!XXH_FORCE_MEMORY_ACCESS : + * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. + * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. + * The below switch allow to select different access method for improved performance. + * Method 0 (default) : use `memcpy()`. Safe and portable. + * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). + * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. + * Method 2 : direct access. This method doesn't depend on compiler but violate C standard. + * It can generate buggy code on targets which do not support unaligned memory accesses. + * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) + * See http://stackoverflow.com/a/32095106/646947 for details. + * Prefer these methods in priority order (0 > 1 > 2) + */ +#ifndef XXH_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */ +# if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) +# define XXH_FORCE_MEMORY_ACCESS 2 +# elif defined(__INTEL_COMPILER) || \ + (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) )) +# define XXH_FORCE_MEMORY_ACCESS 1 +# endif +#endif + +/*!XXH_ACCEPT_NULL_INPUT_POINTER : + * If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer. + * When this option is enabled, xxHash output for null input pointers will be the same as a null-length input. + * By default, this option is disabled. To enable it, uncomment below define : + */ +/* #define XXH_ACCEPT_NULL_INPUT_POINTER 1 */ + +/*!XXH_FORCE_NATIVE_FORMAT : + * By default, xxHash library provides endian-independent Hash values, based on little-endian convention. + * Results are therefore identical for little-endian and big-endian CPU. + * This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format. + * Should endian-independence be of no importance for your application, you may set the #define below to 1, + * to improve speed for Big-endian CPU. + * This option has no impact on Little_Endian CPU. + */ +#ifndef XXH_FORCE_NATIVE_FORMAT /* can be defined externally */ +# define XXH_FORCE_NATIVE_FORMAT 0 +#endif + +/*!XXH_FORCE_ALIGN_CHECK : + * This is a minor performance trick, only useful with lots of very small keys. + * It means : check for aligned/unaligned input. + * The check costs one initial branch per hash; set to 0 when the input data + * is guaranteed to be aligned. + */ +#ifndef XXH_FORCE_ALIGN_CHECK /* can be defined externally */ +# if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) +# define XXH_FORCE_ALIGN_CHECK 0 +# else +# define XXH_FORCE_ALIGN_CHECK 1 +# endif +#endif + + +/* ************************************* +* Includes & Memory related functions +***************************************/ +/*! Modify the local functions below should you wish to use some other memory routines +* for malloc(), free() */ +#include +static void* XXH_malloc(size_t s) { return malloc(s); } +static void XXH_free (void* p) { free(p); } +/*! and for memcpy() */ +#include +static void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcpy(dest,src,size); } + +#define XXH_STATIC_LINKING_ONLY +#include "xxhash.h" + + +/* ************************************* +* Compiler Specific Options +***************************************/ +#ifdef _MSC_VER /* Visual Studio */ +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +# define FORCE_INLINE static __forceinline +#else +# if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ +# ifdef __GNUC__ +# define FORCE_INLINE static inline __attribute__((always_inline)) +# else +# define FORCE_INLINE static inline +# endif +# else +# define FORCE_INLINE static +# endif /* __STDC_VERSION__ */ +#endif + + +/* ************************************* +* Basic Types +***************************************/ +#ifndef MEM_MODULE +# if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) +# include + typedef uint8_t BYTE; + typedef uint16_t U16; + typedef uint32_t U32; + typedef int32_t S32; +# else + typedef unsigned char BYTE; + typedef unsigned short U16; + typedef unsigned int U32; + typedef signed int S32; +# endif +#endif + +#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) + +/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */ +static U32 XXH_read32(const void* memPtr) { return *(const U32*) memPtr; } + +#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) + +/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ +/* currently only defined for gcc and icc */ +typedef union { U32 u32; } __attribute__((packed)) unalign; +static U32 XXH_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } + +#else + +/* portable and safe solution. Generally efficient. + * see : http://stackoverflow.com/a/32095106/646947 + */ +static U32 XXH_read32(const void* memPtr) +{ + U32 val; + memcpy(&val, memPtr, sizeof(val)); + return val; +} + +#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ + + +/* **************************************** +* Compiler-specific Functions and Macros +******************************************/ +#define XXH_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) + +/* Note : although _rotl exists for minGW (GCC under windows), performance seems poor */ +#if defined(_MSC_VER) +# define XXH_rotl32(x,r) _rotl(x,r) +# define XXH_rotl64(x,r) _rotl64(x,r) +#else +# define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r))) +# define XXH_rotl64(x,r) ((x << r) | (x >> (64 - r))) +#endif + +#if defined(_MSC_VER) /* Visual Studio */ +# define XXH_swap32 _byteswap_ulong +#elif XXH_GCC_VERSION >= 403 +# define XXH_swap32 __builtin_bswap32 +#else +static U32 XXH_swap32 (U32 x) +{ + return ((x << 24) & 0xff000000 ) | + ((x << 8) & 0x00ff0000 ) | + ((x >> 8) & 0x0000ff00 ) | + ((x >> 24) & 0x000000ff ); +} +#endif + + +/* ************************************* +* Architecture Macros +***************************************/ +typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess; + +/* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example on the compiler command line */ +#ifndef XXH_CPU_LITTLE_ENDIAN + static const int g_one = 1; +# define XXH_CPU_LITTLE_ENDIAN (*(const char*)(&g_one)) +#endif + + +/* *************************** +* Memory reads +*****************************/ +typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment; + +FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align) +{ + if (align==XXH_unaligned) + return endian==XXH_littleEndian ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr)); + else + return endian==XXH_littleEndian ? *(const U32*)ptr : XXH_swap32(*(const U32*)ptr); +} + +FORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianess endian) +{ + return XXH_readLE32_align(ptr, endian, XXH_unaligned); +} + +static U32 XXH_readBE32(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_swap32(XXH_read32(ptr)) : XXH_read32(ptr); +} + + +/* ************************************* +* Macros +***************************************/ +#define XXH_STATIC_ASSERT(c) { enum { XXH_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */ +XXH_PUBLIC_API unsigned XXH_versionNumber (void) { return XXH_VERSION_NUMBER; } + + +/* ******************************************************************* +* 32-bits hash functions +*********************************************************************/ +static const U32 PRIME32_1 = 2654435761U; +static const U32 PRIME32_2 = 2246822519U; +static const U32 PRIME32_3 = 3266489917U; +static const U32 PRIME32_4 = 668265263U; +static const U32 PRIME32_5 = 374761393U; + +static U32 XXH32_round(U32 seed, U32 input) +{ + seed += input * PRIME32_2; + seed = XXH_rotl32(seed, 13); + seed *= PRIME32_1; + return seed; +} + +FORCE_INLINE U32 XXH32_endian_align(const void* input, size_t len, U32 seed, XXH_endianess endian, XXH_alignment align) +{ + const BYTE* p = (const BYTE*)input; + const BYTE* bEnd = p + len; + U32 h32; +#define XXH_get32bits(p) XXH_readLE32_align(p, endian, align) + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (p==NULL) { + len=0; + bEnd=p=(const BYTE*)(size_t)16; + } +#endif + + if (len>=16) { + const BYTE* const limit = bEnd - 16; + U32 v1 = seed + PRIME32_1 + PRIME32_2; + U32 v2 = seed + PRIME32_2; + U32 v3 = seed + 0; + U32 v4 = seed - PRIME32_1; + + do { + v1 = XXH32_round(v1, XXH_get32bits(p)); p+=4; + v2 = XXH32_round(v2, XXH_get32bits(p)); p+=4; + v3 = XXH32_round(v3, XXH_get32bits(p)); p+=4; + v4 = XXH32_round(v4, XXH_get32bits(p)); p+=4; + } while (p<=limit); + + h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18); + } else { + h32 = seed + PRIME32_5; + } + + h32 += (U32) len; + + while (p+4<=bEnd) { + h32 += XXH_get32bits(p) * PRIME32_3; + h32 = XXH_rotl32(h32, 17) * PRIME32_4 ; + p+=4; + } + + while (p> 15; + h32 *= PRIME32_2; + h32 ^= h32 >> 13; + h32 *= PRIME32_3; + h32 ^= h32 >> 16; + + return h32; +} + + +XXH_PUBLIC_API unsigned int XXH32 (const void* input, size_t len, unsigned int seed) +{ +#if 0 + /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ + XXH32_state_t state; + XXH32_reset(&state, seed); + XXH32_update(&state, input, len); + return XXH32_digest(&state); +#else + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if (XXH_FORCE_ALIGN_CHECK) { + if ((((size_t)input) & 3) == 0) { /* Input is 4-bytes aligned, leverage the speed benefit */ + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); + else + return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); + } } + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); + else + return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); +#endif +} + + + +/*====== Hash streaming ======*/ + +XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void) +{ + return (XXH32_state_t*)XXH_malloc(sizeof(XXH32_state_t)); +} +XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr) +{ + XXH_free(statePtr); + return XXH_OK; +} + +XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dstState, const XXH32_state_t* srcState) +{ + memcpy(dstState, srcState, sizeof(*dstState)); +} + +XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, unsigned int seed) +{ + XXH32_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ + memset(&state, 0, sizeof(state)-4); /* do not write into reserved, for future removal */ + state.v1 = seed + PRIME32_1 + PRIME32_2; + state.v2 = seed + PRIME32_2; + state.v3 = seed + 0; + state.v4 = seed - PRIME32_1; + memcpy(statePtr, &state, sizeof(state)); + return XXH_OK; +} + + +FORCE_INLINE XXH_errorcode XXH32_update_endian (XXH32_state_t* state, const void* input, size_t len, XXH_endianess endian) +{ + const BYTE* p = (const BYTE*)input; + const BYTE* const bEnd = p + len; + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (input==NULL) return XXH_ERROR; +#endif + + state->total_len_32 += (unsigned)len; + state->large_len |= (len>=16) | (state->total_len_32>=16); + + if (state->memsize + len < 16) { /* fill in tmp buffer */ + XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, len); + state->memsize += (unsigned)len; + return XXH_OK; + } + + if (state->memsize) { /* some data left from previous update */ + XXH_memcpy((BYTE*)(state->mem32) + state->memsize, input, 16-state->memsize); + { const U32* p32 = state->mem32; + state->v1 = XXH32_round(state->v1, XXH_readLE32(p32, endian)); p32++; + state->v2 = XXH32_round(state->v2, XXH_readLE32(p32, endian)); p32++; + state->v3 = XXH32_round(state->v3, XXH_readLE32(p32, endian)); p32++; + state->v4 = XXH32_round(state->v4, XXH_readLE32(p32, endian)); p32++; + } + p += 16-state->memsize; + state->memsize = 0; + } + + if (p <= bEnd-16) { + const BYTE* const limit = bEnd - 16; + U32 v1 = state->v1; + U32 v2 = state->v2; + U32 v3 = state->v3; + U32 v4 = state->v4; + + do { + v1 = XXH32_round(v1, XXH_readLE32(p, endian)); p+=4; + v2 = XXH32_round(v2, XXH_readLE32(p, endian)); p+=4; + v3 = XXH32_round(v3, XXH_readLE32(p, endian)); p+=4; + v4 = XXH32_round(v4, XXH_readLE32(p, endian)); p+=4; + } while (p<=limit); + + state->v1 = v1; + state->v2 = v2; + state->v3 = v3; + state->v4 = v4; + } + + if (p < bEnd) { + XXH_memcpy(state->mem32, p, (size_t)(bEnd-p)); + state->memsize = (unsigned)(bEnd-p); + } + + return XXH_OK; +} + +XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_update_endian(state_in, input, len, XXH_littleEndian); + else + return XXH32_update_endian(state_in, input, len, XXH_bigEndian); +} + + + +FORCE_INLINE U32 XXH32_digest_endian (const XXH32_state_t* state, XXH_endianess endian) +{ + const BYTE * p = (const BYTE*)state->mem32; + const BYTE* const bEnd = (const BYTE*)(state->mem32) + state->memsize; + U32 h32; + + if (state->large_len) { + h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18); + } else { + h32 = state->v3 /* == seed */ + PRIME32_5; + } + + h32 += state->total_len_32; + + while (p+4<=bEnd) { + h32 += XXH_readLE32(p, endian) * PRIME32_3; + h32 = XXH_rotl32(h32, 17) * PRIME32_4; + p+=4; + } + + while (p> 15; + h32 *= PRIME32_2; + h32 ^= h32 >> 13; + h32 *= PRIME32_3; + h32 ^= h32 >> 16; + + return h32; +} + + +XXH_PUBLIC_API unsigned int XXH32_digest (const XXH32_state_t* state_in) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_digest_endian(state_in, XXH_littleEndian); + else + return XXH32_digest_endian(state_in, XXH_bigEndian); +} + + +/*====== Canonical representation ======*/ + +/*! Default XXH result types are basic unsigned 32 and 64 bits. +* The canonical representation follows human-readable write convention, aka big-endian (large digits first). +* These functions allow transformation of hash result into and from its canonical format. +* This way, hash values can be written into a file or buffer, and remain comparable across different systems and programs. +*/ + +XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash) +{ + XXH_STATIC_ASSERT(sizeof(XXH32_canonical_t) == sizeof(XXH32_hash_t)); + if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap32(hash); + memcpy(dst, &hash, sizeof(*dst)); +} + +XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src) +{ + return XXH_readBE32(src); +} + + +#ifndef XXH_NO_LONG_LONG + +/* ******************************************************************* +* 64-bits hash functions +*********************************************************************/ + +/*====== Memory access ======*/ + +#ifndef MEM_MODULE +# define MEM_MODULE +# if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) ) +# include + typedef uint64_t U64; +# else + typedef unsigned long long U64; /* if your compiler doesn't support unsigned long long, replace by another 64-bit type here. Note that xxhash.h will also need to be updated. */ +# endif +#endif + + +#if (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==2)) + +/* Force direct memory access. Only works on CPU which support unaligned memory access in hardware */ +static U64 XXH_read64(const void* memPtr) { return *(const U64*) memPtr; } + +#elif (defined(XXH_FORCE_MEMORY_ACCESS) && (XXH_FORCE_MEMORY_ACCESS==1)) + +/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ +/* currently only defined for gcc and icc */ +typedef union { U32 u32; U64 u64; } __attribute__((packed)) unalign64; +static U64 XXH_read64(const void* ptr) { return ((const unalign64*)ptr)->u64; } + +#else + +/* portable and safe solution. Generally efficient. + * see : http://stackoverflow.com/a/32095106/646947 + */ + +static U64 XXH_read64(const void* memPtr) +{ + U64 val; + memcpy(&val, memPtr, sizeof(val)); + return val; +} + +#endif /* XXH_FORCE_DIRECT_MEMORY_ACCESS */ + +#if defined(_MSC_VER) /* Visual Studio */ +# define XXH_swap64 _byteswap_uint64 +#elif XXH_GCC_VERSION >= 403 +# define XXH_swap64 __builtin_bswap64 +#else +static U64 XXH_swap64 (U64 x) +{ + return ((x << 56) & 0xff00000000000000ULL) | + ((x << 40) & 0x00ff000000000000ULL) | + ((x << 24) & 0x0000ff0000000000ULL) | + ((x << 8) & 0x000000ff00000000ULL) | + ((x >> 8) & 0x00000000ff000000ULL) | + ((x >> 24) & 0x0000000000ff0000ULL) | + ((x >> 40) & 0x000000000000ff00ULL) | + ((x >> 56) & 0x00000000000000ffULL); +} +#endif + +FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align) +{ + if (align==XXH_unaligned) + return endian==XXH_littleEndian ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr)); + else + return endian==XXH_littleEndian ? *(const U64*)ptr : XXH_swap64(*(const U64*)ptr); +} + +FORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianess endian) +{ + return XXH_readLE64_align(ptr, endian, XXH_unaligned); +} + +static U64 XXH_readBE64(const void* ptr) +{ + return XXH_CPU_LITTLE_ENDIAN ? XXH_swap64(XXH_read64(ptr)) : XXH_read64(ptr); +} + + +/*====== xxh64 ======*/ + +static const U64 PRIME64_1 = 11400714785074694791ULL; +static const U64 PRIME64_2 = 14029467366897019727ULL; +static const U64 PRIME64_3 = 1609587929392839161ULL; +static const U64 PRIME64_4 = 9650029242287828579ULL; +static const U64 PRIME64_5 = 2870177450012600261ULL; + +static U64 XXH64_round(U64 acc, U64 input) +{ + acc += input * PRIME64_2; + acc = XXH_rotl64(acc, 31); + acc *= PRIME64_1; + return acc; +} + +static U64 XXH64_mergeRound(U64 acc, U64 val) +{ + val = XXH64_round(0, val); + acc ^= val; + acc = acc * PRIME64_1 + PRIME64_4; + return acc; +} + +FORCE_INLINE U64 XXH64_endian_align(const void* input, size_t len, U64 seed, XXH_endianess endian, XXH_alignment align) +{ + const BYTE* p = (const BYTE*)input; + const BYTE* bEnd = p + len; + U64 h64; +#define XXH_get64bits(p) XXH_readLE64_align(p, endian, align) + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (p==NULL) { + len=0; + bEnd=p=(const BYTE*)(size_t)32; + } +#endif + + if (len>=32) { + const BYTE* const limit = bEnd - 32; + U64 v1 = seed + PRIME64_1 + PRIME64_2; + U64 v2 = seed + PRIME64_2; + U64 v3 = seed + 0; + U64 v4 = seed - PRIME64_1; + + do { + v1 = XXH64_round(v1, XXH_get64bits(p)); p+=8; + v2 = XXH64_round(v2, XXH_get64bits(p)); p+=8; + v3 = XXH64_round(v3, XXH_get64bits(p)); p+=8; + v4 = XXH64_round(v4, XXH_get64bits(p)); p+=8; + } while (p<=limit); + + h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); + h64 = XXH64_mergeRound(h64, v1); + h64 = XXH64_mergeRound(h64, v2); + h64 = XXH64_mergeRound(h64, v3); + h64 = XXH64_mergeRound(h64, v4); + + } else { + h64 = seed + PRIME64_5; + } + + h64 += (U64) len; + + while (p+8<=bEnd) { + U64 const k1 = XXH64_round(0, XXH_get64bits(p)); + h64 ^= k1; + h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4; + p+=8; + } + + if (p+4<=bEnd) { + h64 ^= (U64)(XXH_get32bits(p)) * PRIME64_1; + h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; + p+=4; + } + + while (p> 33; + h64 *= PRIME64_2; + h64 ^= h64 >> 29; + h64 *= PRIME64_3; + h64 ^= h64 >> 32; + + return h64; +} + + +XXH_PUBLIC_API unsigned long long XXH64 (const void* input, size_t len, unsigned long long seed) +{ +#if 0 + /* Simple version, good for code maintenance, but unfortunately slow for small inputs */ + XXH64_state_t state; + XXH64_reset(&state, seed); + XXH64_update(&state, input, len); + return XXH64_digest(&state); +#else + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if (XXH_FORCE_ALIGN_CHECK) { + if ((((size_t)input) & 7)==0) { /* Input is aligned, let's leverage the speed advantage */ + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); + else + return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); + } } + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH64_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); + else + return XXH64_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); +#endif +} + +/*====== Hash Streaming ======*/ + +XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void) +{ + return (XXH64_state_t*)XXH_malloc(sizeof(XXH64_state_t)); +} +XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr) +{ + XXH_free(statePtr); + return XXH_OK; +} + +XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dstState, const XXH64_state_t* srcState) +{ + memcpy(dstState, srcState, sizeof(*dstState)); +} + +XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, unsigned long long seed) +{ + XXH64_state_t state; /* using a local state to memcpy() in order to avoid strict-aliasing warnings */ + memset(&state, 0, sizeof(state)-8); /* do not write into reserved, for future removal */ + state.v1 = seed + PRIME64_1 + PRIME64_2; + state.v2 = seed + PRIME64_2; + state.v3 = seed + 0; + state.v4 = seed - PRIME64_1; + memcpy(statePtr, &state, sizeof(state)); + return XXH_OK; +} + +FORCE_INLINE XXH_errorcode XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianess endian) +{ + const BYTE* p = (const BYTE*)input; + const BYTE* const bEnd = p + len; + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (input==NULL) return XXH_ERROR; +#endif + + state->total_len += len; + + if (state->memsize + len < 32) { /* fill in tmp buffer */ + XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, len); + state->memsize += (U32)len; + return XXH_OK; + } + + if (state->memsize) { /* tmp buffer is full */ + XXH_memcpy(((BYTE*)state->mem64) + state->memsize, input, 32-state->memsize); + state->v1 = XXH64_round(state->v1, XXH_readLE64(state->mem64+0, endian)); + state->v2 = XXH64_round(state->v2, XXH_readLE64(state->mem64+1, endian)); + state->v3 = XXH64_round(state->v3, XXH_readLE64(state->mem64+2, endian)); + state->v4 = XXH64_round(state->v4, XXH_readLE64(state->mem64+3, endian)); + p += 32-state->memsize; + state->memsize = 0; + } + + if (p+32 <= bEnd) { + const BYTE* const limit = bEnd - 32; + U64 v1 = state->v1; + U64 v2 = state->v2; + U64 v3 = state->v3; + U64 v4 = state->v4; + + do { + v1 = XXH64_round(v1, XXH_readLE64(p, endian)); p+=8; + v2 = XXH64_round(v2, XXH_readLE64(p, endian)); p+=8; + v3 = XXH64_round(v3, XXH_readLE64(p, endian)); p+=8; + v4 = XXH64_round(v4, XXH_readLE64(p, endian)); p+=8; + } while (p<=limit); + + state->v1 = v1; + state->v2 = v2; + state->v3 = v3; + state->v4 = v4; + } + + if (p < bEnd) { + XXH_memcpy(state->mem64, p, (size_t)(bEnd-p)); + state->memsize = (unsigned)(bEnd-p); + } + + return XXH_OK; +} + +XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH64_update_endian(state_in, input, len, XXH_littleEndian); + else + return XXH64_update_endian(state_in, input, len, XXH_bigEndian); +} + +FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianess endian) +{ + const BYTE * p = (const BYTE*)state->mem64; + const BYTE* const bEnd = (const BYTE*)state->mem64 + state->memsize; + U64 h64; + + if (state->total_len >= 32) { + U64 const v1 = state->v1; + U64 const v2 = state->v2; + U64 const v3 = state->v3; + U64 const v4 = state->v4; + + h64 = XXH_rotl64(v1, 1) + XXH_rotl64(v2, 7) + XXH_rotl64(v3, 12) + XXH_rotl64(v4, 18); + h64 = XXH64_mergeRound(h64, v1); + h64 = XXH64_mergeRound(h64, v2); + h64 = XXH64_mergeRound(h64, v3); + h64 = XXH64_mergeRound(h64, v4); + } else { + h64 = state->v3 + PRIME64_5; + } + + h64 += (U64) state->total_len; + + while (p+8<=bEnd) { + U64 const k1 = XXH64_round(0, XXH_readLE64(p, endian)); + h64 ^= k1; + h64 = XXH_rotl64(h64,27) * PRIME64_1 + PRIME64_4; + p+=8; + } + + if (p+4<=bEnd) { + h64 ^= (U64)(XXH_readLE32(p, endian)) * PRIME64_1; + h64 = XXH_rotl64(h64, 23) * PRIME64_2 + PRIME64_3; + p+=4; + } + + while (p> 33; + h64 *= PRIME64_2; + h64 ^= h64 >> 29; + h64 *= PRIME64_3; + h64 ^= h64 >> 32; + + return h64; +} + +XXH_PUBLIC_API unsigned long long XXH64_digest (const XXH64_state_t* state_in) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH64_digest_endian(state_in, XXH_littleEndian); + else + return XXH64_digest_endian(state_in, XXH_bigEndian); +} + + +/*====== Canonical representation ======*/ + +XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash) +{ + XXH_STATIC_ASSERT(sizeof(XXH64_canonical_t) == sizeof(XXH64_hash_t)); + if (XXH_CPU_LITTLE_ENDIAN) hash = XXH_swap64(hash); + memcpy(dst, &hash, sizeof(*dst)); +} + +XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src) +{ + return XXH_readBE64(src); +} + +#endif /* XXH_NO_LONG_LONG */ diff --git a/cpp/src/plasma/thirdparty/xxhash.h b/cpp/src/plasma/thirdparty/xxhash.h new file mode 100644 index 00000000000..9d831e03b35 --- /dev/null +++ b/cpp/src/plasma/thirdparty/xxhash.h @@ -0,0 +1,293 @@ +/* + xxHash - Extremely Fast Hash algorithm + Header File + Copyright (C) 2012-2016, Yann Collet. + + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + You can contact the author at : + - xxHash source repository : https://github.com/Cyan4973/xxHash +*/ + +/* Notice extracted from xxHash homepage : + +xxHash is an extremely fast Hash algorithm, running at RAM speed limits. +It also successfully passes all tests from the SMHasher suite. + +Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz) + +Name Speed Q.Score Author +xxHash 5.4 GB/s 10 +CrapWow 3.2 GB/s 2 Andrew +MumurHash 3a 2.7 GB/s 10 Austin Appleby +SpookyHash 2.0 GB/s 10 Bob Jenkins +SBox 1.4 GB/s 9 Bret Mulvey +Lookup3 1.2 GB/s 9 Bob Jenkins +SuperFastHash 1.2 GB/s 1 Paul Hsieh +CityHash64 1.05 GB/s 10 Pike & Alakuijala +FNV 0.55 GB/s 5 Fowler, Noll, Vo +CRC32 0.43 GB/s 9 +MD5-32 0.33 GB/s 10 Ronald L. Rivest +SHA1-32 0.28 GB/s 10 + +Q.Score is a measure of quality of the hash function. +It depends on successfully passing SMHasher test set. +10 is a perfect score. + +A 64-bits version, named XXH64, is available since r35. +It offers much better speed, but for 64-bits applications only. +Name Speed on 64 bits Speed on 32 bits +XXH64 13.8 GB/s 1.9 GB/s +XXH32 6.8 GB/s 6.0 GB/s +*/ + +#ifndef XXHASH_H_5627135585666179 +#define XXHASH_H_5627135585666179 1 + +#if defined (__cplusplus) +extern "C" { +#endif + + +/* **************************** +* Definitions +******************************/ +#include /* size_t */ +typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode; + + +/* **************************** +* API modifier +******************************/ +/** XXH_PRIVATE_API +* This is useful to include xxhash functions in `static` mode +* in order to inline them, and remove their symbol from the public list. +* Methodology : +* #define XXH_PRIVATE_API +* #include "xxhash.h" +* `xxhash.c` is automatically included. +* It's not useful to compile and link it as a separate module. +*/ +#ifdef XXH_PRIVATE_API +# ifndef XXH_STATIC_LINKING_ONLY +# define XXH_STATIC_LINKING_ONLY +# endif +# if defined(__GNUC__) +# define XXH_PUBLIC_API static __inline __attribute__((unused)) +# elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define XXH_PUBLIC_API static inline +# elif defined(_MSC_VER) +# define XXH_PUBLIC_API static __inline +# else +# define XXH_PUBLIC_API static /* this version may generate warnings for unused static functions; disable the relevant warning */ +# endif +#else +# define XXH_PUBLIC_API /* do nothing */ +#endif /* XXH_PRIVATE_API */ + +/*!XXH_NAMESPACE, aka Namespace Emulation : + +If you want to include _and expose_ xxHash functions from within your own library, +but also want to avoid symbol collisions with other libraries which may also include xxHash, + +you can use XXH_NAMESPACE, to automatically prefix any public symbol from xxhash library +with the value of XXH_NAMESPACE (therefore, avoid NULL and numeric values). + +Note that no change is required within the calling program as long as it includes `xxhash.h` : +regular symbol name will be automatically translated by this header. +*/ +#ifdef XXH_NAMESPACE +# define XXH_CAT(A,B) A##B +# define XXH_NAME2(A,B) XXH_CAT(A,B) +# define XXH_versionNumber XXH_NAME2(XXH_NAMESPACE, XXH_versionNumber) +# define XXH32 XXH_NAME2(XXH_NAMESPACE, XXH32) +# define XXH32_createState XXH_NAME2(XXH_NAMESPACE, XXH32_createState) +# define XXH32_freeState XXH_NAME2(XXH_NAMESPACE, XXH32_freeState) +# define XXH32_reset XXH_NAME2(XXH_NAMESPACE, XXH32_reset) +# define XXH32_update XXH_NAME2(XXH_NAMESPACE, XXH32_update) +# define XXH32_digest XXH_NAME2(XXH_NAMESPACE, XXH32_digest) +# define XXH32_copyState XXH_NAME2(XXH_NAMESPACE, XXH32_copyState) +# define XXH32_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH32_canonicalFromHash) +# define XXH32_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH32_hashFromCanonical) +# define XXH64 XXH_NAME2(XXH_NAMESPACE, XXH64) +# define XXH64_createState XXH_NAME2(XXH_NAMESPACE, XXH64_createState) +# define XXH64_freeState XXH_NAME2(XXH_NAMESPACE, XXH64_freeState) +# define XXH64_reset XXH_NAME2(XXH_NAMESPACE, XXH64_reset) +# define XXH64_update XXH_NAME2(XXH_NAMESPACE, XXH64_update) +# define XXH64_digest XXH_NAME2(XXH_NAMESPACE, XXH64_digest) +# define XXH64_copyState XXH_NAME2(XXH_NAMESPACE, XXH64_copyState) +# define XXH64_canonicalFromHash XXH_NAME2(XXH_NAMESPACE, XXH64_canonicalFromHash) +# define XXH64_hashFromCanonical XXH_NAME2(XXH_NAMESPACE, XXH64_hashFromCanonical) +#endif + + +/* ************************************* +* Version +***************************************/ +#define XXH_VERSION_MAJOR 0 +#define XXH_VERSION_MINOR 6 +#define XXH_VERSION_RELEASE 2 +#define XXH_VERSION_NUMBER (XXH_VERSION_MAJOR *100*100 + XXH_VERSION_MINOR *100 + XXH_VERSION_RELEASE) +XXH_PUBLIC_API unsigned XXH_versionNumber (void); + + +/*-********************************************************************** +* 32-bits hash +************************************************************************/ +typedef unsigned int XXH32_hash_t; + +/*! XXH32() : + Calculate the 32-bits hash of sequence "length" bytes stored at memory address "input". + The memory between input & input+length must be valid (allocated and read-accessible). + "seed" can be used to alter the result predictably. + Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s */ +XXH_PUBLIC_API XXH32_hash_t XXH32 (const void* input, size_t length, unsigned int seed); + +/*====== Streaming ======*/ +typedef struct XXH32_state_s XXH32_state_t; /* incomplete type */ +XXH_PUBLIC_API XXH32_state_t* XXH32_createState(void); +XXH_PUBLIC_API XXH_errorcode XXH32_freeState(XXH32_state_t* statePtr); +XXH_PUBLIC_API void XXH32_copyState(XXH32_state_t* dst_state, const XXH32_state_t* src_state); + +XXH_PUBLIC_API XXH_errorcode XXH32_reset (XXH32_state_t* statePtr, unsigned int seed); +XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* statePtr, const void* input, size_t length); +XXH_PUBLIC_API XXH32_hash_t XXH32_digest (const XXH32_state_t* statePtr); + +/* +These functions generate the xxHash of an input provided in multiple segments. +Note that, for small input, they are slower than single-call functions, due to state management. +For small input, prefer `XXH32()` and `XXH64()` . + +XXH state must first be allocated, using XXH*_createState() . + +Start a new hash by initializing state with a seed, using XXH*_reset(). + +Then, feed the hash state by calling XXH*_update() as many times as necessary. +Obviously, input must be allocated and read accessible. +The function returns an error code, with 0 meaning OK, and any other value meaning there is an error. + +Finally, a hash value can be produced anytime, by using XXH*_digest(). +This function returns the nn-bits hash as an int or long long. + +It's still possible to continue inserting input into the hash state after a digest, +and generate some new hashes later on, by calling again XXH*_digest(). + +When done, free XXH state space if it was allocated dynamically. +*/ + +/*====== Canonical representation ======*/ + +typedef struct { unsigned char digest[4]; } XXH32_canonical_t; +XXH_PUBLIC_API void XXH32_canonicalFromHash(XXH32_canonical_t* dst, XXH32_hash_t hash); +XXH_PUBLIC_API XXH32_hash_t XXH32_hashFromCanonical(const XXH32_canonical_t* src); + +/* Default result type for XXH functions are primitive unsigned 32 and 64 bits. +* The canonical representation uses human-readable write convention, aka big-endian (large digits first). +* These functions allow transformation of hash result into and from its canonical format. +* This way, hash values can be written into a file / memory, and remain comparable on different systems and programs. +*/ + + +#ifndef XXH_NO_LONG_LONG +/*-********************************************************************** +* 64-bits hash +************************************************************************/ +typedef unsigned long long XXH64_hash_t; + +/*! XXH64() : + Calculate the 64-bits hash of sequence of length "len" stored at memory address "input". + "seed" can be used to alter the result predictably. + This function runs faster on 64-bits systems, but slower on 32-bits systems (see benchmark). +*/ +XXH_PUBLIC_API XXH64_hash_t XXH64 (const void* input, size_t length, unsigned long long seed); + +/*====== Streaming ======*/ +typedef struct XXH64_state_s XXH64_state_t; /* incomplete type */ +XXH_PUBLIC_API XXH64_state_t* XXH64_createState(void); +XXH_PUBLIC_API XXH_errorcode XXH64_freeState(XXH64_state_t* statePtr); +XXH_PUBLIC_API void XXH64_copyState(XXH64_state_t* dst_state, const XXH64_state_t* src_state); + +XXH_PUBLIC_API XXH_errorcode XXH64_reset (XXH64_state_t* statePtr, unsigned long long seed); +XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* statePtr, const void* input, size_t length); +XXH_PUBLIC_API XXH64_hash_t XXH64_digest (const XXH64_state_t* statePtr); + +/*====== Canonical representation ======*/ +typedef struct { unsigned char digest[8]; } XXH64_canonical_t; +XXH_PUBLIC_API void XXH64_canonicalFromHash(XXH64_canonical_t* dst, XXH64_hash_t hash); +XXH_PUBLIC_API XXH64_hash_t XXH64_hashFromCanonical(const XXH64_canonical_t* src); +#endif /* XXH_NO_LONG_LONG */ + + +#ifdef XXH_STATIC_LINKING_ONLY + +/* ================================================================================================ + This section contains definitions which are not guaranteed to remain stable. + They may change in future versions, becoming incompatible with a different version of the library. + They shall only be used with static linking. + Never use these definitions in association with dynamic linking ! +=================================================================================================== */ + +/* These definitions are only meant to make possible + static allocation of XXH state, on stack or in a struct for example. + Never use members directly. */ + +struct XXH32_state_s { + unsigned total_len_32; + unsigned large_len; + unsigned v1; + unsigned v2; + unsigned v3; + unsigned v4; + unsigned mem32[4]; /* buffer defined as U32 for alignment */ + unsigned memsize; + unsigned reserved; /* never read nor write, will be removed in a future version */ +}; /* typedef'd to XXH32_state_t */ + +#ifndef XXH_NO_LONG_LONG /* remove 64-bits support */ +struct XXH64_state_s { + unsigned long long total_len; + unsigned long long v1; + unsigned long long v2; + unsigned long long v3; + unsigned long long v4; + unsigned long long mem64[4]; /* buffer defined as U64 for alignment */ + unsigned memsize; + unsigned reserved[2]; /* never read nor write, will be removed in a future version */ +}; /* typedef'd to XXH64_state_t */ +#endif + +#ifdef XXH_PRIVATE_API +# include "xxhash.c" /* include xxhash function bodies as `static`, for inlining */ +#endif + +#endif /* XXH_STATIC_LINKING_ONLY */ + + +#if defined (__cplusplus) +} +#endif + +#endif /* XXHASH_H_5627135585666179 */ From 9ef7f412c5aa8338dbd0c41413e087a3527b0dcc Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Thu, 1 Jun 2017 16:57:26 -0700 Subject: [PATCH 02/53] make the plasma store compile --- cpp/CMakeLists.txt | 1 + cpp/src/arrow/status.h | 21 ++++++++++++++++++ cpp/src/arrow/util/logging.h | 1 + cpp/src/plasma/CMakeLists.txt | 38 ++++++++++++++++----------------- cpp/src/plasma/malloc.cc | 12 +++++------ cpp/src/plasma/plasma.cc | 1 - cpp/src/plasma/plasma.h | 6 +----- cpp/src/plasma/plasma_client.cc | 3 --- cpp/src/plasma/plasma_common.h | 4 ++-- cpp/src/plasma/plasma_store.cc | 4 ++-- 10 files changed, 52 insertions(+), 39 deletions(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index d5483f22802..1747d892e80 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -945,6 +945,7 @@ if(FLATBUFFERS_VENDORED) set(ARROW_DEPENDENCIES ${ARROW_DEPENDENCIES} flatbuffers_ep) endif() +add_subdirectory(src/plasma) add_subdirectory(src/arrow) add_subdirectory(src/arrow/io) if (ARROW_IPC) diff --git a/cpp/src/arrow/status.h b/cpp/src/arrow/status.h index 1688b967853..9f26d8975d6 100644 --- a/cpp/src/arrow/status.h +++ b/cpp/src/arrow/status.h @@ -83,6 +83,9 @@ enum class StatusCode : char { IOError = 5, UnknownError = 9, NotImplemented = 10, + PlasmaObjectExists = 20, + PlasmaObjectNonexistent = 21, + PlasmaStoreFull = 22 }; class ARROW_EXPORT Status { @@ -129,6 +132,18 @@ class ARROW_EXPORT Status { return Status(StatusCode::IOError, msg, -1); } + static Status PlasmaObjectExists(const std::string &msg) { + return Status(StatusCode::PlasmaObjectExists, msg, -1); + } + + static Status PlasmaObjectNonexistent(const std::string &msg) { + return Status(StatusCode::PlasmaObjectNonexistent, msg, -1); + } + + static Status PlasmaStoreFull(const std::string &msg) { + return Status(StatusCode::PlasmaStoreFull, msg, -1); + } + // Returns true iff the status indicates success. bool ok() const { return (state_ == NULL); } @@ -139,6 +154,12 @@ class ARROW_EXPORT Status { bool IsTypeError() const { return code() == StatusCode::TypeError; } bool IsUnknownError() const { return code() == StatusCode::UnknownError; } bool IsNotImplemented() const { return code() == StatusCode::NotImplemented; } + // An object with this object ID already exists in the plasma store. + bool IsPlasmaObjectExists() const { return code() == StatusCode::PlasmaObjectExists; } + // An object was requested that doesn't exist in the plasma store. + bool IsPlasmaObjectNonexistent() const { return code() == StatusCode::PlasmaObjectNonexistent; } + // An object is too large to fit into the plasma store. + bool IsPlasmaStoreFull() const { return code() == StatusCode::PlasmaStoreFull; } // Return a string representation of this status suitable for printing. // Returns the string "OK" for success. diff --git a/cpp/src/arrow/util/logging.h b/cpp/src/arrow/util/logging.h index 697d47c5410..8a929da0e02 100644 --- a/cpp/src/arrow/util/logging.h +++ b/cpp/src/arrow/util/logging.h @@ -30,6 +30,7 @@ namespace arrow { // Log levels. LOG ignores them, so their values are abitrary. +#define ARROW_DEBUG (-1) #define ARROW_INFO 0 #define ARROW_WARNING 1 #define ARROW_ERROR 2 diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index a138c081e22..e1dd1425056 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -2,8 +2,7 @@ cmake_minimum_required(VERSION 2.8) project(plasma) -# Recursively include common -include(${CMAKE_CURRENT_LIST_DIR}/../common/cmake/Common.cmake) +find_package(PythonLibsNew REQUIRED) if(APPLE) SET(CMAKE_SHARED_LIBRARY_SUFFIX ".so") @@ -11,20 +10,24 @@ endif(APPLE) include_directories("${PYTHON_INCLUDE_DIRS}" thirdparty) -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --std=c99 -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200809L -march=native -mtune=native -O3") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++11 -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200809L -march=native -mtune=native -O3") # Compile flatbuffers -set(PLASMA_FBS_SRC "${CMAKE_CURRENT_LIST_DIR}/format/plasma.fbs") +set(PLASMA_FBS_SRC "${CMAKE_CURRENT_LIST_DIR}/format/plasma.fbs" "${CMAKE_CURRENT_LIST_DIR}/format/common.fbs") set(OUTPUT_DIR ${CMAKE_CURRENT_LIST_DIR}/format/) set(PLASMA_FBS_OUTPUT_FILES + "${OUTPUT_DIR}/common_generated.h" "${OUTPUT_DIR}/plasma_generated.h") add_custom_command( OUTPUT ${PLASMA_FBS_OUTPUT_FILES} - COMMAND ${FLATBUFFERS_COMPILER} -c -o ${OUTPUT_DIR} ${PLASMA_FBS_SRC} + # The --gen-object-api flag generates a C++ class MessageT for each + # flatbuffers message Message, which can be used to store deserialized + # messages in data structures. This is currently used for ObjectInfo for + # example. + COMMAND ${FLATBUFFERS_COMPILER} -c -o ${OUTPUT_DIR} ${PLASMA_FBS_SRC} --gen-object-api DEPENDS ${PLASMA_FBS_SRC} COMMENT "Running flatc compiler on ${PLASMA_FBS_SRC}" VERBATIM) @@ -45,8 +48,8 @@ add_library(plasma SHARED plasma_extension.cc plasma_protocol.cc plasma_client.cc - thirdparty/xxhash.c - fling.c) + thirdparty/xxhash.cc + fling.cc) add_dependencies(plasma gen_plasma_fbs) @@ -68,9 +71,9 @@ add_library(plasma_lib STATIC plasma_common.cc plasma_io.cc plasma_protocol.cc - status.cc - fling.c - thirdparty/xxhash.c) + ../arrow/status.cc + fling.cc + thirdparty/xxhash.cc) target_link_libraries(plasma_lib ${FLATBUFFERS_STATIC_LIB} -lpthread) add_dependencies(plasma_lib gen_plasma_fbs) @@ -82,25 +85,20 @@ add_executable(plasma_store plasma_events.cc plasma_protocol.cc eviction_policy.cc - fling.c + fling.cc malloc.cc) -add_dependencies(plasma_store hiredis gen_plasma_fbs) +add_dependencies(plasma_store gen_plasma_fbs) target_link_libraries(plasma_store plasma_lib ${FLATBUFFERS_STATIC_LIB}) add_dependencies(plasma protocol_fbs) -add_executable(plasma_manager - plasma_manager.cc) - -target_link_libraries(plasma_manager common plasma_lib ${FLATBUFFERS_STATIC_LIB}) - add_library(plasma_client SHARED plasma_client.cc) target_link_libraries(plasma_client ${FLATBUFFERS_STATIC_LIB}) target_link_libraries(plasma_client plasma_lib ${FLATBUFFERS_STATIC_LIB}) -define_test(client_tests plasma_lib) -define_test(manager_tests plasma_lib plasma_manager.cc) -define_test(serialization_tests plasma_lib) +# define_test(client_tests plasma_lib) +# define_test(manager_tests plasma_lib plasma_manager.cc) +# define_test(serialization_tests plasma_lib) diff --git a/cpp/src/plasma/malloc.cc b/cpp/src/plasma/malloc.cc index e8399649a98..4fe3ee8b552 100644 --- a/cpp/src/plasma/malloc.cc +++ b/cpp/src/plasma/malloc.cc @@ -8,7 +8,7 @@ #include -#include "common.h" +#include "plasma_common.h" extern "C" { void *fake_mmap(size_t); @@ -89,11 +89,11 @@ int create_buffer(int64_t size) { return -1; } if (unlink(file_name) != 0) { - LOG_ERROR("unlink error"); + ARROW_LOG(FATAL) << "unlink error"; return -1; } if (ftruncate(fd, (off_t) size) != 0) { - LOG_ERROR("ftruncate error"); + ARROW_LOG(FATAL) << "ftruncate error"; return -1; } #endif @@ -107,7 +107,7 @@ void *fake_mmap(size_t size) { size += sizeof(size_t); int fd = create_buffer(size); - CHECKM(fd >= 0, "Failed to create buffer during mmap"); + ARROW_CHECK(fd >= 0) << "Failed to create buffer during mmap"; void *pointer = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (pointer == MAP_FAILED) { return pointer; @@ -122,12 +122,12 @@ void *fake_mmap(size_t size) { /* We lie to dlmalloc about where mapped memory actually lives. */ pointer = pointer_advance(pointer, sizeof(size_t)); - LOG_DEBUG("%p = fake_mmap(%lu)", pointer, size); + ARROW_LOG(DEBUG) << pointer << " = fake_mmap(" << size << ")"; return pointer; } int fake_munmap(void *addr, size_t size) { - LOG_DEBUG("fake_munmap(%p, %lu)", addr, size); + ARROW_LOG(DEBUG) << "fake_munmap(" << addr << ", " << size << ")"; addr = pointer_retreat(addr, sizeof(size_t)); size += sizeof(size_t); diff --git a/cpp/src/plasma/plasma.cc b/cpp/src/plasma/plasma.cc index 6273d3bbc8c..320d84e5f86 100644 --- a/cpp/src/plasma/plasma.cc +++ b/cpp/src/plasma/plasma.cc @@ -1,7 +1,6 @@ #include "plasma_common.h" #include "plasma.h" -#include "io.h" #include #include #include diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h index 4cd3f46dd3b..5fb4d2db921 100644 --- a/cpp/src/plasma/plasma.h +++ b/cpp/src/plasma/plasma.h @@ -9,10 +9,6 @@ #include #include /* pid_t */ -extern "C" { -#include "sha256.h" -} - #include #include @@ -42,7 +38,7 @@ extern "C" { #define BLOCK_SIZE 64 // Size of object hash digests. -constexpr int64_t kDigestSize = SHA256_BLOCK_SIZE; +constexpr int64_t kDigestSize = sizeof(uint64_t); struct Client; diff --git a/cpp/src/plasma/plasma_client.cc b/cpp/src/plasma/plasma_client.cc index c811b418b6f..1de0acb88fc 100644 --- a/cpp/src/plasma/plasma_client.cc +++ b/cpp/src/plasma/plasma_client.cc @@ -26,15 +26,12 @@ #include #include -extern "C" { -#include "sha256.h" #include "fling.h" #define XXH_STATIC_LINKING_ONLY #include "xxhash.h" #define XXH64_DEFAULT_SEED 0 -} // Number of threads used for memcopy and hash computations. constexpr int64_t kThreadPoolSize = 8; diff --git a/cpp/src/plasma/plasma_common.h b/cpp/src/plasma/plasma_common.h index a46940d3c67..8df0f750683 100644 --- a/cpp/src/plasma/plasma_common.h +++ b/cpp/src/plasma/plasma_common.h @@ -9,8 +9,8 @@ #define __STDC_FORMAT_MACROS #endif -#include "logging.h" -#include "status.h" +#include "arrow/util/logging.h" +#include "arrow/status.h" constexpr int64_t kUniqueIDSize = 20; diff --git a/cpp/src/plasma/plasma_store.cc b/cpp/src/plasma/plasma_store.cc index 9fa4ea44634..2a8bc269341 100644 --- a/cpp/src/plasma/plasma_store.cc +++ b/cpp/src/plasma/plasma_store.cc @@ -31,12 +31,12 @@ #include "plasma_common.h" #include "plasma_store.h" -#include "format/common_generated.h" #include "plasma_io.h" +#include "format/common_generated.h" +#include "fling.h" #include "malloc.h" extern "C" { -#include "fling.h" void *dlmalloc(size_t); void *dlmemalign(size_t alignment, size_t bytes); void dlfree(void *); From 51ab963098d71929757dca83c98edae2ffb38b8a Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Thu, 1 Jun 2017 18:00:23 -0700 Subject: [PATCH 03/53] fix compiler warnings --- cpp/src/plasma/eviction_policy.h | 4 ++-- cpp/src/plasma/plasma.cc | 1 + cpp/src/plasma/plasma_client.cc | 2 +- cpp/src/plasma/plasma_client.h | 2 +- cpp/src/plasma/plasma_common.cc | 3 ++- cpp/src/plasma/plasma_extension.cc | 7 ++----- cpp/src/plasma/plasma_extension.h | 4 ++++ cpp/src/plasma/plasma_io.cc | 2 +- cpp/src/plasma/plasma_protocol.cc | 4 ++-- cpp/src/plasma/plasma_store.cc | 13 +++++++------ cpp/src/plasma/plasma_store.h | 2 +- 11 files changed, 24 insertions(+), 20 deletions(-) diff --git a/cpp/src/plasma/eviction_policy.h b/cpp/src/plasma/eviction_policy.h index fd3861db467..22ea951d756 100644 --- a/cpp/src/plasma/eviction_policy.h +++ b/cpp/src/plasma/eviction_policy.h @@ -117,10 +117,10 @@ class EvictionPolicy { std::vector &objects_to_evict); private: - /** Pointer to the plasma store info. */ - PlasmaStoreInfo *store_info_; /** The amount of memory (in bytes) currently being used. */ int64_t memory_used_; + /** Pointer to the plasma store info. */ + PlasmaStoreInfo *store_info_; /** Datastructure for the LRU cache. */ LRUCache cache_; }; diff --git a/cpp/src/plasma/plasma.cc b/cpp/src/plasma/plasma.cc index 320d84e5f86..873e048cfde 100644 --- a/cpp/src/plasma/plasma.cc +++ b/cpp/src/plasma/plasma.cc @@ -21,6 +21,7 @@ int warn_if_sigpipe(int status, int client_sock) { } ARROW_LOG(FATAL) << "Failed to write message to client on fd " << client_sock << "."; + return -1; // This is never reached. } /** diff --git a/cpp/src/plasma/plasma_client.cc b/cpp/src/plasma/plasma_client.cc index 1de0acb88fc..a037507f965 100644 --- a/cpp/src/plasma/plasma_client.cc +++ b/cpp/src/plasma/plasma_client.cc @@ -376,7 +376,7 @@ static inline bool compute_object_hash_parallel(XXH64_state_t *hash_state, int64_t nbytes) { // Note that this function will likely be faster if the address of data is // aligned on a 64-byte boundary. - const uint64_t num_threads = kThreadPoolSize; + const int num_threads = kThreadPoolSize; uint64_t threadhash[num_threads + 1]; const uint64_t data_address = reinterpret_cast(data); const uint64_t num_blocks = nbytes / BLOCK_SIZE; diff --git a/cpp/src/plasma/plasma_client.h b/cpp/src/plasma/plasma_client.h index cd03840412f..ac026cf89ac 100644 --- a/cpp/src/plasma/plasma_client.h +++ b/cpp/src/plasma/plasma_client.h @@ -32,7 +32,7 @@ struct PlasmaClientConfig { /// Number of release calls we wait until the object is actually released. /// This allows us to avoid invalidating the cpu cache on workers if objects /// are reused accross tasks. - int release_delay; + size_t release_delay; }; struct ClientMmapTableEntry; diff --git a/cpp/src/plasma/plasma_common.cc b/cpp/src/plasma/plasma_common.cc index d09be2d3516..bac4ca89b9d 100644 --- a/cpp/src/plasma/plasma_common.cc +++ b/cpp/src/plasma/plasma_common.cc @@ -37,7 +37,7 @@ std::string UniqueID::binary() const { std::string UniqueID::hex() const { constexpr char hex[] = "0123456789abcdef"; std::string result; - for (int i = 0; i < sizeof(UniqueID); i++) { + for (int i = 0; i < kUniqueIDSize; i++) { unsigned int val = id_[i]; result.push_back(hex[val >> 4]); result.push_back(hex[val & 0xf]); @@ -64,4 +64,5 @@ Status plasma_error_status(int plasma_error) { default: ARROW_LOG(FATAL) << "unknown plasma error code " << plasma_error; } + return Status::OK(); } diff --git a/cpp/src/plasma/plasma_extension.cc b/cpp/src/plasma/plasma_extension.cc index 58d45ec3cb6..09dd4457675 100644 --- a/cpp/src/plasma/plasma_extension.cc +++ b/cpp/src/plasma/plasma_extension.cc @@ -1,16 +1,13 @@ -#include -#include "bytesobject.h" - #include "plasma_io.h" #include "plasma_common.h" #include "plasma_protocol.h" #include "plasma_client.h" +#include "plasma_extension.h" + PyObject *PlasmaOutOfMemoryError; PyObject *PlasmaObjectExistsError; -#include "plasma_extension.h" - PyObject *PyPlasma_connect(PyObject *self, PyObject *args) { const char *store_socket_name; const char *manager_socket_name; diff --git a/cpp/src/plasma/plasma_extension.h b/cpp/src/plasma/plasma_extension.h index 6c7bf595456..ee13d668663 100644 --- a/cpp/src/plasma/plasma_extension.h +++ b/cpp/src/plasma/plasma_extension.h @@ -1,6 +1,10 @@ #ifndef PLASMA_EXTENSION_H #define PLASMA_EXTENSION_H +#undef _XOPEN_SOURCE +#include +#include "bytesobject.h" + static int PyObjectToPlasmaClient(PyObject *object, PlasmaClient **client) { if (PyCapsule_IsValid(object, "plasma")) { *client = (PlasmaClient *) PyCapsule_GetPointer(object, "plasma"); diff --git a/cpp/src/plasma/plasma_io.cc b/cpp/src/plasma/plasma_io.cc index 7bad98518cb..4b88009c9b8 100644 --- a/cpp/src/plasma/plasma_io.cc +++ b/cpp/src/plasma/plasma_io.cc @@ -75,7 +75,7 @@ Status ReadMessage(int fd, int64_t *type, std::vector &buffer) { ReadBytes(fd, reinterpret_cast(&version), sizeof(version)), *type = DISCONNECT_CLIENT); ARROW_CHECK(version == PLASMA_PROTOCOL_VERSION) << "version = " << version; - int64_t length; + size_t length; RETURN_NOT_OK_ELSE( ReadBytes(fd, reinterpret_cast(type), sizeof(*type)), *type = DISCONNECT_CLIENT); diff --git a/cpp/src/plasma/plasma_protocol.cc b/cpp/src/plasma/plasma_protocol.cc index 134d09e8099..bbad0193ab7 100644 --- a/cpp/src/plasma/plasma_protocol.cc +++ b/cpp/src/plasma/plasma_protocol.cc @@ -11,7 +11,7 @@ to_flatbuffer(flatbuffers::FlatBufferBuilder &fbb, ObjectID object_ids[], int64_t num_objects) { std::vector> results; - for (size_t i = 0; i < num_objects; i++) { + for (int64_t i = 0; i < num_objects; i++) { results.push_back(fbb.CreateString(object_ids[i].binary())); } return fbb.CreateVector(results); @@ -467,7 +467,7 @@ Status ReadWaitRequest(uint8_t *data, *num_ready_objects = message->num_ready_objects(); *timeout_ms = message->timeout(); - for (int i = 0; i < message->object_requests()->size(); i++) { + for (size_t i = 0; i < message->object_requests()->size(); i++) { ObjectID object_id = ObjectID::from_binary( message->object_requests()->Get(i)->object_id()->str()); ObjectRequest object_request({object_id, diff --git a/cpp/src/plasma/plasma_store.cc b/cpp/src/plasma/plasma_store.cc index 2a8bc269341..d734fe6a028 100644 --- a/cpp/src/plasma/plasma_store.cc +++ b/cpp/src/plasma/plasma_store.cc @@ -84,7 +84,7 @@ PlasmaStore::PlasmaStore(EventLoop *loop, int64_t system_memory) PlasmaStore::~PlasmaStore() { for (const auto &element : pending_notifications_) { auto object_notifications = element.second.object_notifications; - for (int i = 0; i < object_notifications.size(); ++i) { + for (size_t i = 0; i < object_notifications.size(); ++i) { uint8_t *notification = (uint8_t *) object_notifications.at(i); uint8_t *data = notification; free(data); @@ -247,7 +247,7 @@ void PlasmaStore::return_from_get(GetRequest *get_req) { void PlasmaStore::update_object_get_requests(ObjectID object_id) { std::vector &get_requests = object_get_requests_[object_id]; - int index = 0; + size_t index = 0; int num_requests = get_requests.size(); for (int i = 0; i < num_requests; ++i) { GetRequest *get_req = get_requests[index]; @@ -278,7 +278,7 @@ void PlasmaStore::update_object_get_requests(ObjectID object_id) { void PlasmaStore::process_get_request(Client *client, const std::vector &object_ids, - uint64_t timeout_ms) { + int64_t timeout_ms) { // Create a get request for this object. GetRequest *get_req = new GetRequest(client, object_ids); @@ -439,7 +439,7 @@ void PlasmaStore::send_notifications(int client_fd) { bool closed = false; // Loop over the array of pending notifications and send as many of them as // possible. - for (int i = 0; i < it->second.object_notifications.size(); ++i) { + for (size_t i = 0; i < it->second.object_notifications.size(); ++i) { uint8_t *notification = (uint8_t *) it->second.object_notifications.at(i); // Decode the length, which is the first bytes of the message. int64_t size = *((int64_t *) notification); @@ -447,7 +447,7 @@ void PlasmaStore::send_notifications(int client_fd) { // Attempt to send a notification about this object ID. int nbytes = send(client_fd, notification, sizeof(int64_t) + size, 0); if (nbytes >= 0) { - ARROW_CHECK(nbytes == sizeof(int64_t) + size); + ARROW_CHECK(nbytes == static_cast(sizeof(int64_t)) + size); } else if (nbytes == -1 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) { ARROW_LOG(DEBUG) @@ -519,7 +519,8 @@ void PlasmaStore::subscribe_to_updates(Client *client) { // Create a new array to buffer notifications that can't be sent to the // subscriber yet because the socket send buffer is full. TODO(rkn): the queue // never gets freed. - NotificationQueue &queue = pending_notifications_[fd]; + // TODO(pcm): Is the following neccessary? + pending_notifications_[fd]; // Push notifications to the new subscriber about existing objects. for (const auto &entry : store_info_.objects) { diff --git a/cpp/src/plasma/plasma_store.h b/cpp/src/plasma/plasma_store.h index c63fb43b6fb..a0db660ac46 100644 --- a/cpp/src/plasma/plasma_store.h +++ b/cpp/src/plasma/plasma_store.h @@ -70,7 +70,7 @@ class PlasmaStore { /// @return Void. void process_get_request(Client *client, const std::vector &object_ids, - uint64_t timeout_ms); + int64_t timeout_ms); /// Seal an object. The object is now immutable and can be accessed with get. /// From 04c2edb3b091f1bcb2bf28cf2ecdb1902b05135c Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Thu, 1 Jun 2017 18:07:33 -0700 Subject: [PATCH 04/53] add missing file --- cpp/src/plasma/format/common.fbs | 17 ++ cpp/src/plasma/format/plasma.fbs | 274 +++++++++++++++++++++++++++++++ 2 files changed, 291 insertions(+) create mode 100644 cpp/src/plasma/format/common.fbs create mode 100644 cpp/src/plasma/format/plasma.fbs diff --git a/cpp/src/plasma/format/common.fbs b/cpp/src/plasma/format/common.fbs new file mode 100644 index 00000000000..5ed137969ba --- /dev/null +++ b/cpp/src/plasma/format/common.fbs @@ -0,0 +1,17 @@ +// Object information data structure. +table ObjectInfo { + // Object ID of this object. + object_id: string; + // Number of bytes the content of this object occupies in memory. + data_size: long; + // Number of bytes the metadata of this object occupies in memory. + metadata_size: long; + // Unix epoch of when this object was created. + create_time: long; + // How long creation of this object took. + construct_duration: long; + // Hash of the object content. + digest: string; + // Specifies if this object was deleted or added. + is_deletion: bool; +} \ No newline at end of file diff --git a/cpp/src/plasma/format/plasma.fbs b/cpp/src/plasma/format/plasma.fbs new file mode 100644 index 00000000000..19324089cdd --- /dev/null +++ b/cpp/src/plasma/format/plasma.fbs @@ -0,0 +1,274 @@ +// Plasma protocol specification + +enum MessageType:int { + // Create a new object. + PlasmaCreateRequest = 1, + PlasmaCreateReply, + // Seal an object. + PlasmaSealRequest, + PlasmaSealReply, + // Get an object that is stored on the local Plasma store. + PlasmaGetRequest, + PlasmaGetReply, + // Release an object. + PlasmaReleaseRequest, + PlasmaReleaseReply, + // Delete an object. + PlasmaDeleteRequest, + PlasmaDeleteReply, + // Get status of an object. + PlasmaStatusRequest, + PlasmaStatusReply, + // See if the store contains an object (will be deprecated). + PlasmaContainsRequest, + PlasmaContainsReply, + // Get information for a newly connecting client. + PlasmaConnectRequest, + PlasmaConnectReply, + // Make room for new objects in the plasma store. + PlasmaEvictRequest, + PlasmaEvictReply, + // Fetch objects from remote Plasma stores. + PlasmaFetchRequest, + // Wait for objects to be ready either from local or remote Plasma stores. + PlasmaWaitRequest, + PlasmaWaitReply, + // Subscribe to a list of objects or to all objects. + PlasmaSubscribeRequest, + // Unsubscribe. + PlasmaUnsubscribeRequest, + // Sending and receiving data. + // PlasmaDataRequest initiates sending the data, there will be one + // such message per data transfer. + PlasmaDataRequest, + // PlasmaDataReply contains the actual data and is sent back to the + // object store that requested the data. For each transfer, multiple + // reply messages get sent. Each one contains a fixed number of bytes. + PlasmaDataReply, + // Object notifications. + PlasmaNotification +} + +enum PlasmaError:int { + // Operation was successful. + OK, + // Trying to create an object that already exists. + ObjectExists, + // Trying to access an object that doesn't exist. + ObjectNonexistent, + // Trying to create an object but there isn't enough space in the store. + OutOfMemory +} + +// Plasma store messages + +struct PlasmaObjectSpec { + // Index of the memory segment (= memory mapped file) that + // this object is allocated in. + segment_index: int; + // Size in bytes of this segment (needed to call mmap). + mmap_size: ulong; + // The offset in bytes in the memory mapped file of the data. + data_offset: ulong; + // The size in bytes of the data. + data_size: ulong; + // The offset in bytes in the memory mapped file of the metadata. + metadata_offset: ulong; + // The size in bytes of the metadata. + metadata_size: ulong; +} + +table PlasmaCreateRequest { + // ID of the object to be created. + object_id: string; + // The size of the object's data in bytes. + data_size: ulong; + // The size of the object's metadata in bytes. + metadata_size: ulong; +} + +table PlasmaCreateReply { + // ID of the object that was created. + object_id: string; + // The object that is returned with this reply. + plasma_object: PlasmaObjectSpec; + // Error that occurred for this call. + error: PlasmaError; +} + +table PlasmaSealRequest { + // ID of the object to be sealed. + object_id: string; + // Hash of the object data. + digest: string; +} + +table PlasmaSealReply { + // ID of the object that was sealed. + object_id: string; + // Error code. + error: PlasmaError; +} + +table PlasmaGetRequest { + // IDs of the objects stored at local Plasma store we are getting. + object_ids: [string]; + // The number of milliseconds before the request should timeout. + timeout_ms: long; +} + +table PlasmaGetReply { + // IDs of the objects being returned. + // This number can be smaller than the number of requested + // objects if not all requested objects are stored and sealed + // in the local Plasma store. + object_ids: [string]; + // Plasma object information, in the same order as their IDs. + plasma_objects: [PlasmaObjectSpec]; + // The number of elements in both object_ids and plasma_objects arrays must agree. +} + +table PlasmaReleaseRequest { + // ID of the object to be released. + object_id: string; +} + +table PlasmaReleaseReply { + // ID of the object that was released. + object_id: string; + // Error code. + error: PlasmaError; +} + +table PlasmaDeleteRequest { + // ID of the object to be deleted. + object_id: string; +} + +table PlasmaDeleteReply { + // ID of the object that was deleted. + object_id: string; + // Error code. + error: PlasmaError; +} + +table PlasmaStatusRequest { + // IDs of the objects stored at local Plasma store we request the status of. + object_ids: [string]; +} + +enum ObjectStatus:int { + // Object is stored in the local Plasma Store. + Local = 1, + // Object is stored on a remote Plasma store, and it is not stored on the + // local Plasma Store. + Remote, + // Object is not stored in the system. + Nonexistent, + // Object is currently transferred from a remote Plasma store the the local + // Plasma Store. + Transfer +} + +table PlasmaStatusReply { + // IDs of the objects being returned. + object_ids: [string]; + // Status of the object. + status: [ObjectStatus]; +} + +// PlasmaContains is a subset of PlasmaStatus which does not +// involve the plasma manager, only the store. We should consider +// unifying them in the future and deprecating PlasmaContains. + +table PlasmaContainsRequest { + // ID of the object we are querying. + object_id: string; +} + +table PlasmaContainsReply { + // ID of the object we are querying. + object_id: string; + // 1 if the object is in the store and 0 otherwise. + has_object: int; +} + +// PlasmaConnect is used by a plasma client the first time it connects with the +// store. This is not really necessary, but is used to get some information +// about the store such as its memory capacity. + +table PlasmaConnectRequest { +} + +table PlasmaConnectReply { + // The memory capacity of the store. + memory_capacity: long; +} + +table PlasmaEvictRequest { + // Number of bytes that shall be freed. + num_bytes: ulong; +} + +table PlasmaEvictReply { + // Number of bytes that have been freed. + num_bytes: ulong; +} + +table PlasmaFetchRequest { + // IDs of objects to be gotten. + object_ids: [string]; +} + +table ObjectRequestSpec { + // ID of the object. + object_id: string; + // The type of the object. This specifies whether we + // will be waiting for an object store in the local or + // global Plasma store. + type: int; +} + +table PlasmaWaitRequest { + // Array of object requests whose status we are asking for. + object_requests: [ObjectRequestSpec]; + // Number of objects expected to be returned, if available. + num_ready_objects: int; + // timeout + timeout: long; +} + +table ObjectReply { + // ID of the object. + object_id: string; + // The object status. This specifies where the object is stored. + status: int; +} + +table PlasmaWaitReply { + // Array of object requests being returned. + object_requests: [ObjectReply]; + // Number of objects expected to be returned, if available. + num_ready_objects: int; +} + +table PlasmaSubscribeRequest { +} + +table PlasmaDataRequest { + // ID of the object that is requested. + object_id: string; + // The host address where the data shall be sent to. + address: string; + // The port of the manager the data shall be sent to. + port: int; +} + +table PlasmaDataReply { + // ID of the object that will be sent. + object_id: string; + // Size of the object data in bytes. + object_size: ulong; + // Size of the metadata in bytes. + metadata_size: ulong; +} From e649c2af2262431209a342c4175559b85c6ec780 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Thu, 1 Jun 2017 21:53:25 -0700 Subject: [PATCH 05/53] fix compilation --- cpp/CMakeLists.txt | 1 + cpp/src/plasma/CMakeLists.txt | 2 -- cpp/src/plasma/fling.cc | 9 +++++++-- cpp/src/plasma/plasma_common.cc | 2 +- cpp/src/plasma/plasma_io.cc | 2 +- cpp/src/plasma/plasma_protocol.cc | 18 ++++++++++-------- cpp/src/plasma/plasma_store.cc | 4 ++-- 7 files changed, 22 insertions(+), 16 deletions(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 1747d892e80..e4bc56d544e 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -694,6 +694,7 @@ if (ARROW_IPC) ExternalProject_Add(flatbuffers_ep URL "https://github.com/google/flatbuffers/archive/v${FLATBUFFERS_VERSION}.tar.gz" CMAKE_ARGS + "-DCMAKE_CXX_FLAGS=-fPIC" "-DCMAKE_INSTALL_PREFIX:PATH=${FLATBUFFERS_PREFIX}" "-DFLATBUFFERS_BUILD_TESTS=OFF") diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index e1dd1425056..2ab28ea5dcd 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -92,8 +92,6 @@ add_dependencies(plasma_store gen_plasma_fbs) target_link_libraries(plasma_store plasma_lib ${FLATBUFFERS_STATIC_LIB}) -add_dependencies(plasma protocol_fbs) - add_library(plasma_client SHARED plasma_client.cc) target_link_libraries(plasma_client ${FLATBUFFERS_STATIC_LIB}) diff --git a/cpp/src/plasma/fling.cc b/cpp/src/plasma/fling.cc index 379b896b543..9cf3ae4ee91 100644 --- a/cpp/src/plasma/fling.cc +++ b/cpp/src/plasma/fling.cc @@ -32,7 +32,12 @@ int send_fd(int conn, int fd) { *(int *) CMSG_DATA(header) = fd; /* Send file descriptor. */ - return sendmsg(conn, &msg, 0); + ssize_t r = sendmsg(conn, &msg, 0); + if (r >= 0) { + return 0; + } else { + return static_cast(r); + } } int recv_fd(int conn) { @@ -49,7 +54,7 @@ int recv_fd(int conn) { for (struct cmsghdr *header = CMSG_FIRSTHDR(&msg); header != NULL; header = CMSG_NXTHDR(&msg, header)) if (header->cmsg_level == SOL_SOCKET && header->cmsg_type == SCM_RIGHTS) { - int count = + ssize_t count = (header->cmsg_len - (CMSG_DATA(header) - (unsigned char *) header)) / sizeof(int); for (int i = 0; i < count; ++i) { diff --git a/cpp/src/plasma/plasma_common.cc b/cpp/src/plasma/plasma_common.cc index bac4ca89b9d..d80e6d3977d 100644 --- a/cpp/src/plasma/plasma_common.cc +++ b/cpp/src/plasma/plasma_common.cc @@ -11,7 +11,7 @@ UniqueID UniqueID::from_random() { uint8_t *data = id.mutable_data(); std::random_device engine; for (int i = 0; i < kUniqueIDSize; i++) { - data[i] = engine(); + data[i] = static_cast(engine()); } return id; } diff --git a/cpp/src/plasma/plasma_io.cc b/cpp/src/plasma/plasma_io.cc index 4b88009c9b8..07f3185a069 100644 --- a/cpp/src/plasma/plasma_io.cc +++ b/cpp/src/plasma/plasma_io.cc @@ -152,7 +152,7 @@ int connect_ipc_sock_retry(const std::string &pathname, << pathname; } /* Sleep for timeout milliseconds. */ - usleep(timeout * 1000); + usleep(static_cast(timeout * 1000)); } /* If we could not connect to the socket, exit. */ if (fd == -1) { diff --git a/cpp/src/plasma/plasma_protocol.cc b/cpp/src/plasma/plasma_protocol.cc index bbad0193ab7..24384a24be6 100644 --- a/cpp/src/plasma/plasma_protocol.cc +++ b/cpp/src/plasma/plasma_protocol.cc @@ -5,6 +5,8 @@ #include "plasma_protocol.h" #include "plasma_io.h" +using flatbuffers::uoffset_t; + flatbuffers::Offset< flatbuffers::Vector>> to_flatbuffer(flatbuffers::FlatBufferBuilder &fbb, @@ -207,7 +209,7 @@ Status ReadStatusRequest(uint8_t *data, int64_t num_objects) { DCHECK(data); auto message = flatbuffers::GetRoot(data); - for (int64_t i = 0; i < num_objects; ++i) { + for (uoffset_t i = 0; i < num_objects; ++i) { object_ids[i] = ObjectID::from_binary(message->object_ids()->Get(i)->str()); } return Status::OK(); @@ -238,10 +240,10 @@ Status ReadStatusReply(uint8_t *data, int64_t num_objects) { DCHECK(data); auto message = flatbuffers::GetRoot(data); - for (int64_t i = 0; i < num_objects; ++i) { + for (uoffset_t i = 0; i < num_objects; ++i) { object_ids[i] = ObjectID::from_binary(message->object_ids()->Get(i)->str()); } - for (int64_t i = 0; i < num_objects; ++i) { + for (uoffset_t i = 0; i < num_objects; ++i) { object_status[i] = message->status()->data()[i]; } return Status::OK(); @@ -362,7 +364,7 @@ Status ReadGetRequest(uint8_t *data, int64_t *timeout_ms) { DCHECK(data); auto message = flatbuffers::GetRoot(data); - for (int64_t i = 0; i < message->object_ids()->size(); ++i) { + for (uoffset_t i = 0; i < message->object_ids()->size(); ++i) { auto object_id = message->object_ids()->Get(i)->str(); object_ids.push_back(ObjectID::from_binary(object_id)); } @@ -398,10 +400,10 @@ Status ReadGetReply(uint8_t *data, int64_t num_objects) { DCHECK(data); auto message = flatbuffers::GetRoot(data); - for (int64_t i = 0; i < num_objects; ++i) { + for (uoffset_t i = 0; i < num_objects; ++i) { object_ids[i] = ObjectID::from_binary(message->object_ids()->Get(i)->str()); } - for (int64_t i = 0; i < num_objects; ++i) { + for (uoffset_t i = 0; i < num_objects; ++i) { const PlasmaObjectSpec *object = message->plasma_objects()->Get(i); plasma_objects[i].handle.store_fd = object->segment_index(); plasma_objects[i].handle.mmap_size = object->mmap_size(); @@ -427,7 +429,7 @@ Status SendFetchRequest(int sock, ObjectID object_ids[], int64_t num_objects) { Status ReadFetchRequest(uint8_t *data, std::vector &object_ids) { DCHECK(data); auto message = flatbuffers::GetRoot(data); - for (int64_t i = 0; i < message->object_ids()->size(); ++i) { + for (uoffset_t i = 0; i < message->object_ids()->size(); ++i) { object_ids.push_back( ObjectID::from_binary(message->object_ids()->Get(i)->str())); } @@ -467,7 +469,7 @@ Status ReadWaitRequest(uint8_t *data, *num_ready_objects = message->num_ready_objects(); *timeout_ms = message->timeout(); - for (size_t i = 0; i < message->object_requests()->size(); i++) { + for (uoffset_t i = 0; i < message->object_requests()->size(); i++) { ObjectID object_id = ObjectID::from_binary( message->object_requests()->Get(i)->object_id()->str()); ObjectRequest object_request({object_id, diff --git a/cpp/src/plasma/plasma_store.cc b/cpp/src/plasma/plasma_store.cc index d734fe6a028..15129b9c1e0 100644 --- a/cpp/src/plasma/plasma_store.cc +++ b/cpp/src/plasma/plasma_store.cc @@ -43,9 +43,9 @@ void dlfree(void *); size_t dlmalloc_set_footprint_limit(size_t bytes); } -struct GetRequest { +class GetRequest { + public: GetRequest(Client *client, const std::vector &object_ids); - /// The client that called get. Client *client; /// The ID of the timer that will time out and cause this wait to return to From cb3f3a38601ece4e021cea8e9e79cb2cdfe11b7e Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Fri, 2 Jun 2017 15:58:43 -0700 Subject: [PATCH 06/53] compile C files with CMAKE_C_FLAGS --- cpp/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index e4bc56d544e..937b4757070 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -186,7 +186,7 @@ endif() include(san-config) # For any C code, use the same flags. -set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS}") +# set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS}") # Code coverage if ("${ARROW_GENERATE_COVERAGE}") From 99537c94ebdb313c175bc0909ddcbf7f5b8f511e Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Fri, 2 Jun 2017 16:14:17 -0700 Subject: [PATCH 07/53] fix compiler warnings --- ci/travis_before_script_cpp.sh | 3 +-- cpp/src/plasma/plasma_store.cc | 8 ++++---- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/ci/travis_before_script_cpp.sh b/ci/travis_before_script_cpp.sh index 99087350689..1901c54fca7 100755 --- a/ci/travis_before_script_cpp.sh +++ b/ci/travis_before_script_cpp.sh @@ -26,12 +26,11 @@ source $TRAVIS_BUILD_DIR/ci/travis_env_common.sh if [ $only_library_mode == "no" ]; then # C++ toolchain export CPP_TOOLCHAIN=$TRAVIS_BUILD_DIR/cpp-toolchain - export FLATBUFFERS_HOME=$CPP_TOOLCHAIN export RAPIDJSON_HOME=$CPP_TOOLCHAIN # Set up C++ toolchain from conda-forge packages for faster builds source $TRAVIS_BUILD_DIR/ci/travis_install_conda.sh - conda create -y -q -p $CPP_TOOLCHAIN python=2.7 flatbuffers rapidjson + conda create -y -q -p $CPP_TOOLCHAIN python=2.7 rapidjson fi if [ $TRAVIS_OS_NAME == "osx" ]; then diff --git a/cpp/src/plasma/plasma_store.cc b/cpp/src/plasma/plasma_store.cc index 15129b9c1e0..854b64cbc23 100644 --- a/cpp/src/plasma/plasma_store.cc +++ b/cpp/src/plasma/plasma_store.cc @@ -248,8 +248,8 @@ void PlasmaStore::return_from_get(GetRequest *get_req) { void PlasmaStore::update_object_get_requests(ObjectID object_id) { std::vector &get_requests = object_get_requests_[object_id]; size_t index = 0; - int num_requests = get_requests.size(); - for (int i = 0; i < num_requests; ++i) { + size_t num_requests = get_requests.size(); + for (size_t i = 0; i < num_requests; ++i) { GetRequest *get_req = get_requests[index]; auto entry = get_object_table_entry(&store_info_, object_id); ARROW_CHECK(entry != NULL); @@ -445,9 +445,9 @@ void PlasmaStore::send_notifications(int client_fd) { int64_t size = *((int64_t *) notification); // Attempt to send a notification about this object ID. - int nbytes = send(client_fd, notification, sizeof(int64_t) + size, 0); + ssize_t nbytes = send(client_fd, notification, sizeof(int64_t) + size, 0); if (nbytes >= 0) { - ARROW_CHECK(nbytes == static_cast(sizeof(int64_t)) + size); + ARROW_CHECK(nbytes == static_cast(sizeof(int64_t)) + size); } else if (nbytes == -1 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) { ARROW_LOG(DEBUG) From 63729130d0f8ab59bb0261942f9299686e5c0964 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Fri, 2 Jun 2017 17:47:10 -0700 Subject: [PATCH 08/53] fix malloc? --- cpp/src/plasma/CMakeLists.txt | 2 ++ cpp/src/plasma/malloc.cc | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index 2ab28ea5dcd..61499bd2d01 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -78,6 +78,8 @@ add_library(plasma_lib STATIC target_link_libraries(plasma_lib ${FLATBUFFERS_STATIC_LIB} -lpthread) add_dependencies(plasma_lib gen_plasma_fbs) +set_source_files_properties(malloc.cc PROPERTIES COMPILE_FLAGS "-Wno-error=conversion") + add_executable(plasma_store plasma_store.cc thirdparty/ae/ae.c diff --git a/cpp/src/plasma/malloc.cc b/cpp/src/plasma/malloc.cc index 4fe3ee8b552..526f2e92de3 100644 --- a/cpp/src/plasma/malloc.cc +++ b/cpp/src/plasma/malloc.cc @@ -12,7 +12,7 @@ extern "C" { void *fake_mmap(size_t); -int fake_munmap(void *, size_t); +int fake_munmap(void *, int64_t); #define MMAP(s) fake_mmap(s) #define MUNMAP(a, s) fake_munmap(a, s) @@ -126,7 +126,7 @@ void *fake_mmap(size_t size) { return pointer; } -int fake_munmap(void *addr, size_t size) { +int fake_munmap(void *addr, int64_t size) { ARROW_LOG(DEBUG) << "fake_munmap(" << addr << ", " << size << ")"; addr = pointer_retreat(addr, sizeof(size_t)); size += sizeof(size_t); From c93034fb84ed254cb77c1b87d0362aa0b42d3199 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Fri, 2 Jun 2017 20:40:51 -0700 Subject: [PATCH 09/53] add Apache 2.0 headers --- cpp/src/plasma/CMakeLists.txt | 17 ++ cpp/src/plasma/eviction_policy.cc | 17 ++ cpp/src/plasma/eviction_policy.h | 17 ++ cpp/src/plasma/fling.cc | 17 ++ cpp/src/plasma/fling.h | 17 ++ cpp/src/plasma/format/common.fbs | 19 +- cpp/src/plasma/format/plasma.fbs | 17 ++ cpp/src/plasma/logging.h | 147 -------------- cpp/src/plasma/malloc.cc | 17 ++ cpp/src/plasma/malloc.h | 17 ++ cpp/src/plasma/plasma.cc | 17 ++ cpp/src/plasma/plasma.h | 17 ++ cpp/src/plasma/plasma_client.cc | 17 ++ cpp/src/plasma/plasma_client.h | 17 ++ cpp/src/plasma/plasma_common.cc | 17 ++ cpp/src/plasma/plasma_common.h | 17 ++ cpp/src/plasma/plasma_events.cc | 17 ++ cpp/src/plasma/plasma_events.h | 17 ++ cpp/src/plasma/plasma_extension.cc | 17 ++ cpp/src/plasma/plasma_extension.h | 17 ++ cpp/src/plasma/plasma_io.cc | 17 ++ cpp/src/plasma/plasma_io.h | 17 ++ cpp/src/plasma/plasma_protocol.cc | 17 ++ cpp/src/plasma/plasma_protocol.h | 17 ++ cpp/src/plasma/plasma_store.cc | 17 ++ cpp/src/plasma/plasma_store.h | 17 ++ cpp/src/plasma/status.cc | 90 -------- cpp/src/plasma/status.h | 226 --------------------- cpp/src/plasma/test/client_tests.cc | 17 ++ cpp/src/plasma/test/run_tests.sh | 17 ++ cpp/src/plasma/test/run_valgrind.sh | 17 ++ cpp/src/plasma/test/serialization_tests.cc | 17 ++ 32 files changed, 494 insertions(+), 464 deletions(-) delete mode 100644 cpp/src/plasma/logging.h delete mode 100644 cpp/src/plasma/status.cc delete mode 100644 cpp/src/plasma/status.h diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index 61499bd2d01..69ab0f092f3 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -1,3 +1,20 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + cmake_minimum_required(VERSION 2.8) project(plasma) diff --git a/cpp/src/plasma/eviction_policy.cc b/cpp/src/plasma/eviction_policy.cc index 135c63ad0d4..8ba30d30cbf 100644 --- a/cpp/src/plasma/eviction_policy.cc +++ b/cpp/src/plasma/eviction_policy.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include "eviction_policy.h" void LRUCache::add(const ObjectID &key, int64_t size) { diff --git a/cpp/src/plasma/eviction_policy.h b/cpp/src/plasma/eviction_policy.h index 22ea951d756..e80869eb3c1 100644 --- a/cpp/src/plasma/eviction_policy.h +++ b/cpp/src/plasma/eviction_policy.h @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #ifndef EVICTION_POLICY_H #define EVICTION_POLICY_H diff --git a/cpp/src/plasma/fling.cc b/cpp/src/plasma/fling.cc index 9cf3ae4ee91..b4cbad28f9d 100644 --- a/cpp/src/plasma/fling.cc +++ b/cpp/src/plasma/fling.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include "fling.h" #include diff --git a/cpp/src/plasma/fling.h b/cpp/src/plasma/fling.h index efc41d801e8..c676554be24 100644 --- a/cpp/src/plasma/fling.h +++ b/cpp/src/plasma/fling.h @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + /* FLING: Exchanging file descriptors over sockets * * This is a little library for sending file descriptors over a socket diff --git a/cpp/src/plasma/format/common.fbs b/cpp/src/plasma/format/common.fbs index 5ed137969ba..4d7d2852aec 100644 --- a/cpp/src/plasma/format/common.fbs +++ b/cpp/src/plasma/format/common.fbs @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + // Object information data structure. table ObjectInfo { // Object ID of this object. @@ -14,4 +31,4 @@ table ObjectInfo { digest: string; // Specifies if this object was deleted or added. is_deletion: bool; -} \ No newline at end of file +} diff --git a/cpp/src/plasma/format/plasma.fbs b/cpp/src/plasma/format/plasma.fbs index 19324089cdd..23782ade539 100644 --- a/cpp/src/plasma/format/plasma.fbs +++ b/cpp/src/plasma/format/plasma.fbs @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + // Plasma protocol specification enum MessageType:int { diff --git a/cpp/src/plasma/logging.h b/cpp/src/plasma/logging.h deleted file mode 100644 index 917d18140dd..00000000000 --- a/cpp/src/plasma/logging.h +++ /dev/null @@ -1,147 +0,0 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -#ifndef ARROW_UTIL_LOGGING_H -#define ARROW_UTIL_LOGGING_H - -#include -#include - -namespace arrow { - -// Stubbed versions of macros defined in glog/logging.h, intended for -// environments where glog headers aren't available. -// -// Add more as needed. - -// Log levels. LOG ignores them, so their values are abitrary. - -#define ARROW_DEBUG (-1) -#define ARROW_INFO 0 -#define ARROW_WARNING 1 -#define ARROW_ERROR 2 -#define ARROW_FATAL 3 - -#define ARROW_LOG_INTERNAL(level) ::arrow::internal::CerrLog(level) -#define ARROW_LOG(level) ARROW_LOG_INTERNAL(ARROW_##level) - -#define ARROW_CHECK(condition) \ - (condition) ? 0 : ::arrow::internal::FatalLog(ARROW_FATAL) \ - << __FILE__ << __LINE__ \ - << " Check failed: " #condition " " - -#ifdef NDEBUG -#define ARROW_DFATAL ARROW_WARNING - -#define DCHECK(condition) \ - while (false) \ - ::arrow::internal::NullLog() -#define DCHECK_EQ(val1, val2) \ - while (false) \ - ::arrow::internal::NullLog() -#define DCHECK_NE(val1, val2) \ - while (false) \ - ::arrow::internal::NullLog() -#define DCHECK_LE(val1, val2) \ - while (false) \ - ::arrow::internal::NullLog() -#define DCHECK_LT(val1, val2) \ - while (false) \ - ::arrow::internal::NullLog() -#define DCHECK_GE(val1, val2) \ - while (false) \ - ::arrow::internal::NullLog() -#define DCHECK_GT(val1, val2) \ - while (false) \ - ::arrow::internal::NullLog() - -#else -#define ARROW_DFATAL ARROW_FATAL - -#define DCHECK(condition) ARROW_CHECK(condition) -#define DCHECK_EQ(val1, val2) ARROW_CHECK((val1) == (val2)) -#define DCHECK_NE(val1, val2) ARROW_CHECK((val1) != (val2)) -#define DCHECK_LE(val1, val2) ARROW_CHECK((val1) <= (val2)) -#define DCHECK_LT(val1, val2) ARROW_CHECK((val1) < (val2)) -#define DCHECK_GE(val1, val2) ARROW_CHECK((val1) >= (val2)) -#define DCHECK_GT(val1, val2) ARROW_CHECK((val1) > (val2)) - -#endif // NDEBUG - -namespace internal { - -class NullLog { - public: - template - NullLog &operator<<(const T &t) { - return *this; - } -}; - -class CerrLog { - public: - CerrLog(int severity) // NOLINT(runtime/explicit) - : severity_(severity), - has_logged_(false) {} - - virtual ~CerrLog() { - if (has_logged_) { - std::cerr << std::endl; - } - if (severity_ == ARROW_FATAL) { - std::exit(1); - } - } - - template - CerrLog &operator<<(const T &t) { - // TODO(pcm): Print this if in debug mode, but not if in valgrind - // mode - if (severity_ == ARROW_DEBUG) { - return *this; - } - - has_logged_ = true; - std::cerr << t; - return *this; - } - - protected: - const int severity_; - bool has_logged_; -}; - -// Clang-tidy isn't smart enough to determine that DCHECK using CerrLog doesn't -// return so we create a new class to give it a hint. -class FatalLog : public CerrLog { - public: - explicit FatalLog(int /* severity */) // NOLINT - : CerrLog(ARROW_FATAL){} // NOLINT - - [[noreturn]] ~FatalLog() { - if (has_logged_) { - std::cerr << std::endl; - } - std::exit(1); - } -}; - -} // namespace internal - -} // namespace arrow - -#endif // ARROW_UTIL_LOGGING_H diff --git a/cpp/src/plasma/malloc.cc b/cpp/src/plasma/malloc.cc index 526f2e92de3..6052aac4f1c 100644 --- a/cpp/src/plasma/malloc.cc +++ b/cpp/src/plasma/malloc.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include #include #include diff --git a/cpp/src/plasma/malloc.h b/cpp/src/plasma/malloc.h index 9fc1f48bb9e..cbdbb6ba05e 100644 --- a/cpp/src/plasma/malloc.h +++ b/cpp/src/plasma/malloc.h @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #ifndef MALLOC_H #define MALLOC_H diff --git a/cpp/src/plasma/plasma.cc b/cpp/src/plasma/plasma.cc index 873e048cfde..f74ea12ca80 100644 --- a/cpp/src/plasma/plasma.cc +++ b/cpp/src/plasma/plasma.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include "plasma_common.h" #include "plasma.h" diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h index 5fb4d2db921..db5fc16e07a 100644 --- a/cpp/src/plasma/plasma.h +++ b/cpp/src/plasma/plasma.h @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #ifndef PLASMA_H #define PLASMA_H diff --git a/cpp/src/plasma/plasma_client.cc b/cpp/src/plasma/plasma_client.cc index a037507f965..58d40bbb882 100644 --- a/cpp/src/plasma/plasma_client.cc +++ b/cpp/src/plasma/plasma_client.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + // PLASMA CLIENT: Client library for using the plasma store and manager #ifdef _WIN32 diff --git a/cpp/src/plasma/plasma_client.h b/cpp/src/plasma/plasma_client.h index ac026cf89ac..5e0869cafa5 100644 --- a/cpp/src/plasma/plasma_client.h +++ b/cpp/src/plasma/plasma_client.h @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #ifndef PLASMA_CLIENT_H #define PLASMA_CLIENT_H diff --git a/cpp/src/plasma/plasma_common.cc b/cpp/src/plasma/plasma_common.cc index d80e6d3977d..fbdbced93b9 100644 --- a/cpp/src/plasma/plasma_common.cc +++ b/cpp/src/plasma/plasma_common.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include "plasma_common.h" #include diff --git a/cpp/src/plasma/plasma_common.h b/cpp/src/plasma/plasma_common.h index 8df0f750683..e7088f52485 100644 --- a/cpp/src/plasma/plasma_common.h +++ b/cpp/src/plasma/plasma_common.h @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #ifndef PLASMA_COMMON_H #define PLASMA_COMMON_H diff --git a/cpp/src/plasma/plasma_events.cc b/cpp/src/plasma/plasma_events.cc index 883b745d530..861e5dc6ebb 100644 --- a/cpp/src/plasma/plasma_events.cc +++ b/cpp/src/plasma/plasma_events.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include "plasma_events.h" #include diff --git a/cpp/src/plasma/plasma_events.h b/cpp/src/plasma/plasma_events.h index c94025f96d8..0f1986d5c1c 100644 --- a/cpp/src/plasma/plasma_events.h +++ b/cpp/src/plasma/plasma_events.h @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #ifndef PLASMA_EVENTS #define PLASMA_EVENTS diff --git a/cpp/src/plasma/plasma_extension.cc b/cpp/src/plasma/plasma_extension.cc index 09dd4457675..77f37592f91 100644 --- a/cpp/src/plasma/plasma_extension.cc +++ b/cpp/src/plasma/plasma_extension.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include "plasma_io.h" #include "plasma_common.h" #include "plasma_protocol.h" diff --git a/cpp/src/plasma/plasma_extension.h b/cpp/src/plasma/plasma_extension.h index ee13d668663..51fe5e59643 100644 --- a/cpp/src/plasma/plasma_extension.h +++ b/cpp/src/plasma/plasma_extension.h @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #ifndef PLASMA_EXTENSION_H #define PLASMA_EXTENSION_H diff --git a/cpp/src/plasma/plasma_io.cc b/cpp/src/plasma/plasma_io.cc index 07f3185a069..ecabfb57227 100644 --- a/cpp/src/plasma/plasma_io.cc +++ b/cpp/src/plasma/plasma_io.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include "plasma_io.h" #include "plasma_common.h" diff --git a/cpp/src/plasma/plasma_io.h b/cpp/src/plasma/plasma_io.h index 5127633947a..c22b062541f 100644 --- a/cpp/src/plasma/plasma_io.h +++ b/cpp/src/plasma/plasma_io.h @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include #include #include diff --git a/cpp/src/plasma/plasma_protocol.cc b/cpp/src/plasma/plasma_protocol.cc index 24384a24be6..de0f39249b2 100644 --- a/cpp/src/plasma/plasma_protocol.cc +++ b/cpp/src/plasma/plasma_protocol.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include "flatbuffers/flatbuffers.h" #include "format/plasma_generated.h" diff --git a/cpp/src/plasma/plasma_protocol.h b/cpp/src/plasma/plasma_protocol.h index 3d525282b8b..4257df3f6ad 100644 --- a/cpp/src/plasma/plasma_protocol.h +++ b/cpp/src/plasma/plasma_protocol.h @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #ifndef PLASMA_PROTOCOL_H #define PLASMA_PROTOCOL_H diff --git a/cpp/src/plasma/plasma_store.cc b/cpp/src/plasma/plasma_store.cc index 854b64cbc23..4136b7c7ead 100644 --- a/cpp/src/plasma/plasma_store.cc +++ b/cpp/src/plasma/plasma_store.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + // PLASMA STORE: This is a simple object store server process // // It accepts incoming client connections on a unix domain socket diff --git a/cpp/src/plasma/plasma_store.h b/cpp/src/plasma/plasma_store.h index a0db660ac46..777b83bf6bc 100644 --- a/cpp/src/plasma/plasma_store.h +++ b/cpp/src/plasma/plasma_store.h @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #ifndef PLASMA_STORE_H #define PLASMA_STORE_H diff --git a/cpp/src/plasma/status.cc b/cpp/src/plasma/status.cc deleted file mode 100644 index 11082d6cd9d..00000000000 --- a/cpp/src/plasma/status.cc +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) 2011 The LevelDB Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. See the AUTHORS file for names of contributors. -// -// A Status encapsulates the result of an operation. It may indicate success, -// or it may indicate an error with an associated error message. -// -// Multiple threads can invoke const methods on a Status without -// external synchronization, but if any of the threads may call a -// non-const method, all threads accessing the same Status must use -// external synchronization. - -#include "status.h" - -#include - -namespace arrow { - -Status::Status(StatusCode code, const std::string &msg, int16_t posix_code) { - assert(code != StatusCode::OK); - const uint32_t size = static_cast(msg.size()); - char *result = new char[size + 7]; - memcpy(result, &size, sizeof(size)); - result[4] = static_cast(code); - memcpy(result + 5, &posix_code, sizeof(posix_code)); - memcpy(result + 7, msg.c_str(), msg.size()); - state_ = result; -} - -const char *Status::CopyState(const char *state) { - uint32_t size; - memcpy(&size, state, sizeof(size)); - char *result = new char[size + 7]; - memcpy(result, state, size + 7); - return result; -} - -std::string Status::CodeAsString() const { - if (state_ == NULL) { - return "OK"; - } - - const char *type; - switch (code()) { - case StatusCode::OK: - type = "OK"; - break; - case StatusCode::OutOfMemory: - type = "Out of memory"; - break; - case StatusCode::KeyError: - type = "Key error"; - break; - case StatusCode::TypeError: - type = "Type error"; - break; - case StatusCode::Invalid: - type = "Invalid"; - break; - case StatusCode::IOError: - type = "IOError"; - break; - case StatusCode::UnknownError: - type = "Unknown error"; - break; - case StatusCode::NotImplemented: - type = "NotImplemented"; - break; - default: - type = "Unknown"; - break; - } - return std::string(type); -} - -std::string Status::ToString() const { - std::string result(CodeAsString()); - if (state_ == NULL) { - return result; - } - - result.append(": "); - - uint32_t length; - memcpy(&length, state_, sizeof(length)); - result.append(reinterpret_cast(state_ + 7), length); - return result; -} - -} // namespace arrow diff --git a/cpp/src/plasma/status.h b/cpp/src/plasma/status.h deleted file mode 100644 index 30d3a1e2f82..00000000000 --- a/cpp/src/plasma/status.h +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright (c) 2011 The LevelDB Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. See the AUTHORS file for names of contributors. -// -// A Status encapsulates the result of an operation. It may indicate success, -// or it may indicate an error with an associated error message. -// -// Multiple threads can invoke const methods on a Status without -// external synchronization, but if any of the threads may call a -// non-const method, all threads accessing the same Status must use -// external synchronization. - -// Adapted from Kudu github.com/cloudera/kudu - -#ifndef ARROW_STATUS_H_ -#define ARROW_STATUS_H_ - -#include -#include -#include - -// Return the given status if it is not OK. -#define ARROW_RETURN_NOT_OK(s) \ - do { \ - ::arrow::Status _s = (s); \ - if (!_s.ok()) { \ - return _s; \ - } \ - } while (0); - -// Return the given status if it is not OK, but first clone it and -// prepend the given message. -#define ARROW_RETURN_NOT_OK_PREPEND(s, msg) \ - do { \ - ::arrow::Status _s = (s); \ - if (::gutil::PREDICT_FALSE(!_s.ok())) \ - return _s.CloneAndPrepend(msg); \ - } while (0); - -// Return 'to_return' if 'to_call' returns a bad status. -// The substitution for 'to_return' may reference the variable -// 's' for the bad status. -#define ARROW_RETURN_NOT_OK_RET(to_call, to_return) \ - do { \ - ::arrow::Status s = (to_call); \ - if (::gutil::PREDICT_FALSE(!s.ok())) \ - return (to_return); \ - } while (0); - -// If 'to_call' returns a bad status, CHECK immediately with a logged message -// of 'msg' followed by the status. -#define ARROW_CHECK_OK_PREPEND(to_call, msg) \ - do { \ - ::arrow::Status _s = (to_call); \ - ARROW_CHECK(_s.ok()) << (msg) << ": " << _s.ToString(); \ - } while (0); - -// If the status is bad, CHECK immediately, appending the status to the -// logged message. -#define ARROW_CHECK_OK(s) ARROW_CHECK_OK_PREPEND(s, "Bad status") - -namespace arrow { - -#define RETURN_NOT_OK(s) \ - do { \ - Status _s = (s); \ - if (!_s.ok()) { \ - return _s; \ - } \ - } while (0); - -#define RETURN_NOT_OK_ELSE(s, else_) \ - do { \ - Status _s = (s); \ - if (!_s.ok()) { \ - else_; \ - return _s; \ - } \ - } while (0); - -enum class StatusCode : char { - OK = 0, - OutOfMemory = 1, - KeyError = 2, - TypeError = 3, - Invalid = 4, - IOError = 5, - UnknownError = 9, - NotImplemented = 10, - PlasmaObjectExists = 20, - PlasmaObjectNonexistent = 21, - PlasmaStoreFull = 22 -}; - -class Status { - public: - // Create a success status. - Status() : state_(NULL) {} - ~Status() { delete[] state_; } - - Status(StatusCode code, const std::string &msg) : Status(code, msg, -1) {} - - // Copy the specified status. - Status(const Status &s); - void operator=(const Status &s); - - // Return a success status. - static Status OK() { return Status(); } - - // Return error status of an appropriate type. - static Status OutOfMemory(const std::string &msg, int16_t posix_code = -1) { - return Status(StatusCode::OutOfMemory, msg, posix_code); - } - - static Status KeyError(const std::string &msg) { - return Status(StatusCode::KeyError, msg, -1); - } - - static Status TypeError(const std::string &msg) { - return Status(StatusCode::TypeError, msg, -1); - } - - static Status UnknownError(const std::string &msg) { - return Status(StatusCode::UnknownError, msg, -1); - } - - static Status NotImplemented(const std::string &msg) { - return Status(StatusCode::NotImplemented, msg, -1); - } - - static Status Invalid(const std::string &msg) { - return Status(StatusCode::Invalid, msg, -1); - } - - static Status IOError(const std::string &msg) { - return Status(StatusCode::IOError, msg, -1); - } - - static Status PlasmaObjectExists(const std::string &msg) { - return Status(StatusCode::PlasmaObjectExists, msg, -1); - } - - static Status PlasmaObjectNonexistent(const std::string &msg) { - return Status(StatusCode::PlasmaObjectNonexistent, msg, -1); - } - - static Status PlasmaStoreFull(const std::string &msg) { - return Status(StatusCode::PlasmaStoreFull, msg, -1); - } - - // Returns true iff the status indicates success. - bool ok() const { return (state_ == NULL); } - - bool IsOutOfMemory() const { return code() == StatusCode::OutOfMemory; } - bool IsKeyError() const { return code() == StatusCode::KeyError; } - bool IsInvalid() const { return code() == StatusCode::Invalid; } - bool IsIOError() const { return code() == StatusCode::IOError; } - bool IsTypeError() const { return code() == StatusCode::TypeError; } - bool IsUnknownError() const { return code() == StatusCode::UnknownError; } - bool IsNotImplemented() const { return code() == StatusCode::NotImplemented; } - // An object with this object ID already exists in the plasma store. - bool IsPlasmaObjectExists() const { - return code() == StatusCode::PlasmaObjectExists; - } - // An object was requested that doesn't exist in the plasma store. - bool IsPlasmaObjectNonexistent() const { - return code() == StatusCode::PlasmaObjectNonexistent; - } - // An object is too large to fit into the plasma store. - bool IsPlasmaStoreFull() const { - return code() == StatusCode::PlasmaStoreFull; - } - - // Return a string representation of this status suitable for printing. - // Returns the string "OK" for success. - std::string ToString() const; - - // Return a string representation of the status code, without the message - // text or posix code information. - std::string CodeAsString() const; - - // Get the POSIX code associated with this Status, or -1 if there is none. - int16_t posix_code() const; - - StatusCode code() const { - return ((state_ == NULL) ? StatusCode::OK - : static_cast(state_[4])); - } - - std::string message() const { - uint32_t length; - memcpy(&length, state_, sizeof(length)); - std::string msg; - msg.append((state_ + 7), length); - return msg; - } - - private: - // OK status has a NULL state_. Otherwise, state_ is a new[] array - // of the following form: - // state_[0..3] == length of message - // state_[4] == code - // state_[5..6] == posix_code - // state_[7..] == message - const char *state_; - - Status(StatusCode code, const std::string &msg, int16_t posix_code); - static const char *CopyState(const char *s); -}; - -inline Status::Status(const Status &s) { - state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_); -} - -inline void Status::operator=(const Status &s) { - // The following condition catches both aliasing (when this == &s), - // and the common case where both s and *this are ok. - if (state_ != s.state_) { - delete[] state_; - state_ = (s.state_ == NULL) ? NULL : CopyState(s.state_); - } -} - -} // namespace arrow - -#endif // ARROW_STATUS_H_ diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index f255734cb96..6a993be0509 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include "greatest.h" #include diff --git a/cpp/src/plasma/test/run_tests.sh b/cpp/src/plasma/test/run_tests.sh index 82f8ff9944d..958bd08398e 100644 --- a/cpp/src/plasma/test/run_tests.sh +++ b/cpp/src/plasma/test/run_tests.sh @@ -1,5 +1,22 @@ #!/usr/bin/env bash +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + # Cause the script to exit if a single command fails. set -e diff --git a/cpp/src/plasma/test/run_valgrind.sh b/cpp/src/plasma/test/run_valgrind.sh index 74531e72161..04721941286 100644 --- a/cpp/src/plasma/test/run_valgrind.sh +++ b/cpp/src/plasma/test/run_valgrind.sh @@ -1,5 +1,22 @@ #!/usr/bin/env bash +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + # Cause the script to exit if a single command fails. set -e diff --git a/cpp/src/plasma/test/serialization_tests.cc b/cpp/src/plasma/test/serialization_tests.cc index b3909453544..c3b2f3f7775 100644 --- a/cpp/src/plasma/test/serialization_tests.cc +++ b/cpp/src/plasma/test/serialization_tests.cc @@ -1,3 +1,20 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + #include "greatest.h" #include From 6cee1e253c5b74b3cc5b276e4a3553f7ce1ec967 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Fri, 2 Jun 2017 21:04:51 -0700 Subject: [PATCH 10/53] fix --- cpp/src/plasma/plasma.h | 4 ++-- cpp/src/plasma/plasma_io.h | 2 +- cpp/src/plasma/plasma_protocol.h | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h index db5fc16e07a..f12f44ff146 100644 --- a/cpp/src/plasma/plasma.h +++ b/cpp/src/plasma/plasma.h @@ -30,8 +30,8 @@ #include #include "format/common_generated.h" -#include "logging.h" -#include "status.h" +#include "arrow/util/logging.h" +#include "arrow/status.h" #include diff --git a/cpp/src/plasma/plasma_io.h b/cpp/src/plasma/plasma_io.h index c22b062541f..a8cbb7cdfb1 100644 --- a/cpp/src/plasma/plasma_io.h +++ b/cpp/src/plasma/plasma_io.h @@ -23,7 +23,7 @@ #include #include -#include "status.h" +#include "arrow/status.h" // TODO(pcm): Replace our own custom message header (message type, // message length, plasma protocol verion) with one that is serialized diff --git a/cpp/src/plasma/plasma_protocol.h b/cpp/src/plasma/plasma_protocol.h index 4257df3f6ad..f74b59a78be 100644 --- a/cpp/src/plasma/plasma_protocol.h +++ b/cpp/src/plasma/plasma_protocol.h @@ -18,7 +18,7 @@ #ifndef PLASMA_PROTOCOL_H #define PLASMA_PROTOCOL_H -#include "status.h" +#include "arrow/status.h" #include "format/plasma_generated.h" #include "plasma.h" From 99420e8f034010f03f289d0ca33d7493ca5ff07d Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Fri, 2 Jun 2017 21:51:36 -0700 Subject: [PATCH 11/53] add rat exceptions --- dev/release/run-rat.sh | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/dev/release/run-rat.sh b/dev/release/run-rat.sh index f225c66268a..757604f3859 100755 --- a/dev/release/run-rat.sh +++ b/dev/release/run-rat.sh @@ -59,6 +59,17 @@ $RAT $1 \ -e arrow-glib-sections.txt \ -e arrow-glib-overrides.txt \ -e gtk-doc.make \ + -e ae.c \ + -e ae.h \ + -e ae_epoll.c \ + -e ae_evport.c \ + -e ae_kqueue.c \ + -e ae_select.c \ + -e config.h \ + -e zmalloc.h \ + -e dlmalloc.c \ + -e xxhash.cc \ + -e xxhash.h \ -e "*.html" \ -e "*.sgml" \ -e "*.css" \ From 79ea0ca71db9a277f9c844d160328c5b9fa1b4b2 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sat, 3 Jun 2017 02:55:51 -0700 Subject: [PATCH 12/53] fix clang-tidy --- cpp/src/plasma/CMakeLists.txt | 24 +++++++++---------- .../plasma/{plasma_client.cc => client.cc} | 10 ++++---- cpp/src/plasma/{plasma_client.h => client.h} | 3 ++- .../plasma/{plasma_common.cc => common.cc} | 2 +- cpp/src/plasma/{plasma_common.h => common.h} | 0 .../plasma/{plasma_events.cc => events.cc} | 2 +- cpp/src/plasma/{plasma_events.h => events.h} | 0 cpp/src/plasma/eviction_policy.h | 10 ++++---- .../{plasma_extension.cc => extension.cc} | 10 ++++---- .../{plasma_extension.h => extension.h} | 2 +- cpp/src/plasma/{plasma_io.cc => io.cc} | 4 ++-- cpp/src/plasma/{plasma_io.h => io.h} | 0 cpp/src/plasma/malloc.cc | 2 +- cpp/src/plasma/plasma.cc | 7 +++--- .../{plasma_protocol.cc => protocol.cc} | 6 ++--- .../plasma/{plasma_protocol.h => protocol.h} | 4 +++- cpp/src/plasma/{plasma_store.cc => store.cc} | 6 ++--- cpp/src/plasma/{plasma_store.h => store.h} | 15 +++++++----- 18 files changed, 57 insertions(+), 50 deletions(-) rename cpp/src/plasma/{plasma_client.cc => client.cc} (99%) rename cpp/src/plasma/{plasma_client.h => client.h} (99%) rename cpp/src/plasma/{plasma_common.cc => common.cc} (98%) rename cpp/src/plasma/{plasma_common.h => common.h} (100%) rename cpp/src/plasma/{plasma_events.cc => events.cc} (99%) rename cpp/src/plasma/{plasma_events.h => events.h} (100%) rename cpp/src/plasma/{plasma_extension.cc => extension.cc} (99%) rename cpp/src/plasma/{plasma_extension.h => extension.h} (94%) rename cpp/src/plasma/{plasma_io.cc => io.cc} (99%) rename cpp/src/plasma/{plasma_io.h => io.h} (100%) rename cpp/src/plasma/{plasma_protocol.cc => protocol.cc} (99%) rename cpp/src/plasma/{plasma_protocol.h => protocol.h} (99%) rename cpp/src/plasma/{plasma_store.cc => store.cc} (99%) rename cpp/src/plasma/{plasma_store.h => store.h} (96%) diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index 69ab0f092f3..0e22b9e7fb4 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -25,7 +25,7 @@ if(APPLE) SET(CMAKE_SHARED_LIBRARY_SUFFIX ".so") endif(APPLE) -include_directories("${PYTHON_INCLUDE_DIRS}" thirdparty) +include_directories("${PYTHON_INCLUDE_DIRS}" thirdparty ..) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++11 -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200809L -march=native -mtune=native -O3") @@ -62,9 +62,9 @@ include_directories("${CMAKE_CURRENT_LIST_DIR}/../") add_library(plasma SHARED plasma.cc - plasma_extension.cc - plasma_protocol.cc - plasma_client.cc + extension.cc + protocol.cc + client.cc thirdparty/xxhash.cc fling.cc) @@ -83,11 +83,11 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") set_source_files_properties(thirdparty/dlmalloc.c PROPERTIES COMPILE_FLAGS -Wno-all) add_library(plasma_lib STATIC - plasma_client.cc + client.cc plasma.cc - plasma_common.cc - plasma_io.cc - plasma_protocol.cc + common.cc + io.cc + protocol.cc ../arrow/status.cc fling.cc thirdparty/xxhash.cc) @@ -98,11 +98,11 @@ add_dependencies(plasma_lib gen_plasma_fbs) set_source_files_properties(malloc.cc PROPERTIES COMPILE_FLAGS "-Wno-error=conversion") add_executable(plasma_store - plasma_store.cc + store.cc thirdparty/ae/ae.c plasma.cc - plasma_events.cc - plasma_protocol.cc + events.cc + protocol.cc eviction_policy.cc fling.cc malloc.cc) @@ -111,7 +111,7 @@ add_dependencies(plasma_store gen_plasma_fbs) target_link_libraries(plasma_store plasma_lib ${FLATBUFFERS_STATIC_LIB}) -add_library(plasma_client SHARED plasma_client.cc) +add_library(plasma_client SHARED client.cc) target_link_libraries(plasma_client ${FLATBUFFERS_STATIC_LIB}) target_link_libraries(plasma_client plasma_lib ${FLATBUFFERS_STATIC_LIB}) diff --git a/cpp/src/plasma/plasma_client.cc b/cpp/src/plasma/client.cc similarity index 99% rename from cpp/src/plasma/plasma_client.cc rename to cpp/src/plasma/client.cc index 58d40bbb882..e8e21e76286 100644 --- a/cpp/src/plasma/plasma_client.cc +++ b/cpp/src/plasma/client.cc @@ -34,11 +34,11 @@ #include #include -#include "plasma_common.h" -#include "plasma.h" -#include "plasma_io.h" -#include "plasma_protocol.h" -#include "plasma_client.h" +#include "plasma/common.h" +#include "plasma/plasma.h" +#include "plasma/io.h" +#include "plasma/protocol.h" +#include "plasma/client.h" #include #include diff --git a/cpp/src/plasma/plasma_client.h b/cpp/src/plasma/client.h similarity index 99% rename from cpp/src/plasma/plasma_client.h rename to cpp/src/plasma/client.h index 5e0869cafa5..41464c020ea 100644 --- a/cpp/src/plasma/plasma_client.h +++ b/cpp/src/plasma/client.h @@ -22,8 +22,9 @@ #include #include +#include -#include "plasma.h" +#include "plasma/plasma.h" using arrow::Status; diff --git a/cpp/src/plasma/plasma_common.cc b/cpp/src/plasma/common.cc similarity index 98% rename from cpp/src/plasma/plasma_common.cc rename to cpp/src/plasma/common.cc index fbdbced93b9..62a7e637167 100644 --- a/cpp/src/plasma/plasma_common.cc +++ b/cpp/src/plasma/common.cc @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -#include "plasma_common.h" +#include "plasma/common.h" #include diff --git a/cpp/src/plasma/plasma_common.h b/cpp/src/plasma/common.h similarity index 100% rename from cpp/src/plasma/plasma_common.h rename to cpp/src/plasma/common.h diff --git a/cpp/src/plasma/plasma_events.cc b/cpp/src/plasma/events.cc similarity index 99% rename from cpp/src/plasma/plasma_events.cc rename to cpp/src/plasma/events.cc index 861e5dc6ebb..564fff168ae 100644 --- a/cpp/src/plasma/plasma_events.cc +++ b/cpp/src/plasma/events.cc @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -#include "plasma_events.h" +#include "plasma/events.h" #include diff --git a/cpp/src/plasma/plasma_events.h b/cpp/src/plasma/events.h similarity index 100% rename from cpp/src/plasma/plasma_events.h rename to cpp/src/plasma/events.h diff --git a/cpp/src/plasma/eviction_policy.h b/cpp/src/plasma/eviction_policy.h index e80869eb3c1..896c3ea21ae 100644 --- a/cpp/src/plasma/eviction_policy.h +++ b/cpp/src/plasma/eviction_policy.h @@ -20,9 +20,11 @@ #include #include +#include +#include -#include "plasma_common.h" -#include "plasma.h" +#include "plasma/common.h" +#include "plasma/plasma.h" /* ==== The eviction policy ==== * @@ -42,7 +44,7 @@ class LRUCache { std::unordered_map item_map_; public: - LRUCache(){}; + LRUCache() {} void add(const ObjectID &key, int64_t size); @@ -61,7 +63,7 @@ class EvictionPolicy { * @param store_info Information about the Plasma store that is exposed * to the eviction policy. */ - EvictionPolicy(PlasmaStoreInfo *store_info); + explicit EvictionPolicy(PlasmaStoreInfo *store_info); /** * This method will be called whenever an object is first created in order to diff --git a/cpp/src/plasma/plasma_extension.cc b/cpp/src/plasma/extension.cc similarity index 99% rename from cpp/src/plasma/plasma_extension.cc rename to cpp/src/plasma/extension.cc index 77f37592f91..6934f9b5e04 100644 --- a/cpp/src/plasma/plasma_extension.cc +++ b/cpp/src/plasma/extension.cc @@ -15,12 +15,12 @@ // specific language governing permissions and limitations // under the License. -#include "plasma_io.h" -#include "plasma_common.h" -#include "plasma_protocol.h" -#include "plasma_client.h" +#include "plasma/io.h" +#include "plasma/common.h" +#include "plasma/protocol.h" +#include "plasma/client.h" -#include "plasma_extension.h" +#include "plasma/extension.h" PyObject *PlasmaOutOfMemoryError; PyObject *PlasmaObjectExistsError; diff --git a/cpp/src/plasma/plasma_extension.h b/cpp/src/plasma/extension.h similarity index 94% rename from cpp/src/plasma/plasma_extension.h rename to cpp/src/plasma/extension.h index 51fe5e59643..f75226773c3 100644 --- a/cpp/src/plasma/plasma_extension.h +++ b/cpp/src/plasma/extension.h @@ -24,7 +24,7 @@ static int PyObjectToPlasmaClient(PyObject *object, PlasmaClient **client) { if (PyCapsule_IsValid(object, "plasma")) { - *client = (PlasmaClient *) PyCapsule_GetPointer(object, "plasma"); + *client = reinterpret_cast(PyCapsule_GetPointer(object, "plasma")); return 1; } else { PyErr_SetString(PyExc_TypeError, "must be a 'plasma' capsule"); diff --git a/cpp/src/plasma/plasma_io.cc b/cpp/src/plasma/io.cc similarity index 99% rename from cpp/src/plasma/plasma_io.cc rename to cpp/src/plasma/io.cc index ecabfb57227..b9d1d380ffc 100644 --- a/cpp/src/plasma/plasma_io.cc +++ b/cpp/src/plasma/io.cc @@ -15,8 +15,8 @@ // specific language governing permissions and limitations // under the License. -#include "plasma_io.h" -#include "plasma_common.h" +#include "plasma/common.h" +#include "plasma/io.h" using arrow::Status; diff --git a/cpp/src/plasma/plasma_io.h b/cpp/src/plasma/io.h similarity index 100% rename from cpp/src/plasma/plasma_io.h rename to cpp/src/plasma/io.h diff --git a/cpp/src/plasma/malloc.cc b/cpp/src/plasma/malloc.cc index 6052aac4f1c..0d53ebc342d 100644 --- a/cpp/src/plasma/malloc.cc +++ b/cpp/src/plasma/malloc.cc @@ -25,7 +25,7 @@ #include -#include "plasma_common.h" +#include "plasma/common.h" extern "C" { void *fake_mmap(size_t); diff --git a/cpp/src/plasma/plasma.cc b/cpp/src/plasma/plasma.cc index f74ea12ca80..075d386cdd4 100644 --- a/cpp/src/plasma/plasma.cc +++ b/cpp/src/plasma/plasma.cc @@ -15,14 +15,13 @@ // specific language governing permissions and limitations // under the License. -#include "plasma_common.h" -#include "plasma.h" - #include #include #include -#include "plasma_protocol.h" +#include "plasma/common.h" +#include "plasma/plasma.h" +#include "plasma/protocol.h" int warn_if_sigpipe(int status, int client_sock) { if (status >= 0) { diff --git a/cpp/src/plasma/plasma_protocol.cc b/cpp/src/plasma/protocol.cc similarity index 99% rename from cpp/src/plasma/plasma_protocol.cc rename to cpp/src/plasma/protocol.cc index de0f39249b2..5246cf3d6eb 100644 --- a/cpp/src/plasma/plasma_protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -18,9 +18,9 @@ #include "flatbuffers/flatbuffers.h" #include "format/plasma_generated.h" -#include "plasma_common.h" -#include "plasma_protocol.h" -#include "plasma_io.h" +#include "plasma/common.h" +#include "plasma/protocol.h" +#include "plasma/io.h" using flatbuffers::uoffset_t; diff --git a/cpp/src/plasma/plasma_protocol.h b/cpp/src/plasma/protocol.h similarity index 99% rename from cpp/src/plasma/plasma_protocol.h rename to cpp/src/plasma/protocol.h index f74b59a78be..b4cf3eacab3 100644 --- a/cpp/src/plasma/plasma_protocol.h +++ b/cpp/src/plasma/protocol.h @@ -20,7 +20,9 @@ #include "arrow/status.h" #include "format/plasma_generated.h" -#include "plasma.h" +#include "plasma/plasma.h" + +#include using arrow::Status; diff --git a/cpp/src/plasma/plasma_store.cc b/cpp/src/plasma/store.cc similarity index 99% rename from cpp/src/plasma/plasma_store.cc rename to cpp/src/plasma/store.cc index 4136b7c7ead..8aada18f83e 100644 --- a/cpp/src/plasma/plasma_store.cc +++ b/cpp/src/plasma/store.cc @@ -46,9 +46,9 @@ #include #include -#include "plasma_common.h" -#include "plasma_store.h" -#include "plasma_io.h" +#include "plasma/common.h" +#include "plasma/store.h" +#include "plasma/io.h" #include "format/common_generated.h" #include "fling.h" #include "malloc.h" diff --git a/cpp/src/plasma/plasma_store.h b/cpp/src/plasma/store.h similarity index 96% rename from cpp/src/plasma/plasma_store.h rename to cpp/src/plasma/store.h index 777b83bf6bc..22b8b323a87 100644 --- a/cpp/src/plasma/plasma_store.h +++ b/cpp/src/plasma/store.h @@ -18,11 +18,14 @@ #ifndef PLASMA_STORE_H #define PLASMA_STORE_H -#include "eviction_policy.h" -#include "plasma.h" -#include "plasma_common.h" -#include "plasma_events.h" -#include "plasma_protocol.h" +#include +#include + +#include "plasma/eviction_policy.h" +#include "plasma/plasma.h" +#include "plasma/common.h" +#include "plasma/events.h" +#include "plasma/protocol.h" class GetRequest; @@ -34,7 +37,7 @@ struct NotificationQueue { /// Contains all information that is associated with a Plasma store client. struct Client { - Client(int fd); + explicit Client(int fd); /// The file descriptor used to communicate with the client. int fd; From 7f7e7e78a647320c6903710de591d8f35a57ede0 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sat, 3 Jun 2017 15:51:01 -0700 Subject: [PATCH 13/53] more linting --- cpp/CMakeLists.txt | 4 +++- cpp/src/plasma/client.cc | 14 +++++++------- cpp/src/plasma/eviction_policy.cc | 4 +++- cpp/src/plasma/fling.cc | 6 +++--- cpp/src/plasma/io.cc | 6 +++--- cpp/src/plasma/plasma.cc | 4 ++-- cpp/src/plasma/protocol.cc | 4 ++-- cpp/src/plasma/store.cc | 4 ++-- 8 files changed, 25 insertions(+), 21 deletions(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 937b4757070..37493c52324 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -862,7 +862,9 @@ if (UNIX) FOREACH(item ${LINT_FILES}) IF(NOT ((item MATCHES "_generated.h") OR - (item MATCHES "pyarrow_api.h"))) + (item MATCHES "pyarrow_api.h") OR + (item MATCHES "xxhash.h") OR + (item MATCHES "xxhash.cc"))) LIST(APPEND FILTERED_LINT_FILES ${item}) ENDIF() ENDFOREACH(item ${LINT_FILES}) diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index e8e21e76286..b071e9aab8b 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -40,13 +40,14 @@ #include "plasma/protocol.h" #include "plasma/client.h" +#include #include #include -#include "fling.h" +#include "plasma/fling.h" #define XXH_STATIC_LINKING_ONLY -#include "xxhash.h" +#include "thirdparty/xxhash.h" #define XXH64_DEFAULT_SEED 0 @@ -91,8 +92,7 @@ uint8_t *lookup_or_mmap(PlasmaClient *conn, close(fd); return entry->second->pointer; } else { - uint8_t *result = (uint8_t *) mmap(NULL, map_size, PROT_READ | PROT_WRITE, - MAP_SHARED, fd, 0); + uint8_t *result = reinterpret_cast(mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); if (result == MAP_FAILED) { ARROW_LOG(FATAL) << "mmap failed"; } @@ -254,7 +254,7 @@ Status PlasmaClient::Get(ObjectID object_ids[], if (object_buffers[i].data_size != -1) { // If the object was already in use by the client, then the store should // have returned it. - DCHECK(object->data_size != -1); + DCHECK_NE(object->data_size, -1); // We won't use this file descriptor, but the store sent us one, so we // need to receive it and then close it right away so we don't leak file // descriptors. @@ -288,7 +288,7 @@ Status PlasmaClient::Get(ObjectID object_ids[], // The object was not retrieved. Make sure we already put a -1 here to // indicate that the object was not retrieved. The caller is not // responsible for releasing this object. - DCHECK(object_buffers[i].data_size == -1); + DCHECK_EQ(object_buffers[i].data_size, -1); object_buffers[i].data_size = -1; } } @@ -335,7 +335,7 @@ Status PlasmaClient::PerformRelease(ObjectID object_id) { // Update the in_use_object_bytes. in_use_object_bytes -= (object_entry->second->object.data_size + object_entry->second->object.metadata_size); - DCHECK(in_use_object_bytes >= 0); + DCHECK_GE(in_use_object_bytes, 0); // Remove the entry from the hash table of objects currently in use. delete object_entry->second; objects_in_use.erase(object_id); diff --git a/cpp/src/plasma/eviction_policy.cc b/cpp/src/plasma/eviction_policy.cc index 8ba30d30cbf..453565665c6 100644 --- a/cpp/src/plasma/eviction_policy.cc +++ b/cpp/src/plasma/eviction_policy.cc @@ -15,7 +15,9 @@ // specific language governing permissions and limitations // under the License. -#include "eviction_policy.h" +#include "plasma/eviction_policy.h" + +#include void LRUCache::add(const ObjectID &key, int64_t size) { auto it = item_map_.find(key); diff --git a/cpp/src/plasma/fling.cc b/cpp/src/plasma/fling.cc index b4cbad28f9d..6246cc8f19c 100644 --- a/cpp/src/plasma/fling.cc +++ b/cpp/src/plasma/fling.cc @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -#include "fling.h" +#include "plasma/fling.h" #include @@ -46,7 +46,7 @@ int send_fd(int conn, int fd) { header->cmsg_level = SOL_SOCKET; header->cmsg_type = SCM_RIGHTS; header->cmsg_len = CMSG_LEN(sizeof(int)); - *(int *) CMSG_DATA(header) = fd; + *reinterpret_cast(CMSG_DATA(header)) = fd; /* Send file descriptor. */ ssize_t r = sendmsg(conn, &msg, 0); @@ -75,7 +75,7 @@ int recv_fd(int conn) { (header->cmsg_len - (CMSG_DATA(header) - (unsigned char *) header)) / sizeof(int); for (int i = 0; i < count; ++i) { - int fd = ((int *) CMSG_DATA(header))[i]; + int fd = (reinterpret_cast(CMSG_DATA(header)))[i]; if (found_fd == -1) { found_fd = fd; } else { diff --git a/cpp/src/plasma/io.cc b/cpp/src/plasma/io.cc index b9d1d380ffc..e404bce84ca 100644 --- a/cpp/src/plasma/io.cc +++ b/cpp/src/plasma/io.cc @@ -116,7 +116,7 @@ int bind_ipc_sock(const std::string &pathname, bool shall_listen) { } /* Tell the system to allow the port to be reused. */ int on = 1; - if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, + if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&on), sizeof(on)) < 0) { ARROW_LOG(ERROR) << "setsockopt failed for pathname " << pathname; close(socket_fd); @@ -216,7 +216,7 @@ int AcceptClient(int socket_fd) { uint8_t *read_message_async(int sock) { int64_t size; - Status s = ReadBytes(sock, (uint8_t *) &size, sizeof(int64_t)); + Status s = ReadBytes(sock, reinterpret_cast(&size), sizeof(int64_t)); if (!s.ok()) { /* The other side has closed the socket. */ ARROW_LOG(DEBUG) @@ -224,7 +224,7 @@ uint8_t *read_message_async(int sock) { close(sock); return NULL; } - uint8_t *message = (uint8_t *) malloc(size); + uint8_t *message = reinterpret_cast(malloc(size)); s = ReadBytes(sock, message, size); if (!s.ok()) { /* The other side has closed the socket. */ diff --git a/cpp/src/plasma/plasma.cc b/cpp/src/plasma/plasma.cc index 075d386cdd4..1c8ea4437b6 100644 --- a/cpp/src/plasma/plasma.cc +++ b/cpp/src/plasma/plasma.cc @@ -53,8 +53,8 @@ uint8_t *create_object_info_buffer(ObjectInfoT *object_info) { flatbuffers::FlatBufferBuilder fbb; auto message = CreateObjectInfo(fbb, object_info); fbb.Finish(message); - uint8_t *notification = (uint8_t *) malloc(sizeof(int64_t) + fbb.GetSize()); - *((int64_t *) notification) = fbb.GetSize(); + uint8_t *notification = reinterpret_cast(malloc(sizeof(int64_t) + fbb.GetSize())); + *(reinterpret_cast(notification)) = fbb.GetSize(); memcpy(notification + sizeof(int64_t), fbb.GetBufferPointer(), fbb.GetSize()); return notification; } diff --git a/cpp/src/plasma/protocol.cc b/cpp/src/plasma/protocol.cc index 5246cf3d6eb..dc0b8707d75 100644 --- a/cpp/src/plasma/protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -107,7 +107,7 @@ Status ReadCreateReply(uint8_t *data, Status SendSealRequest(int sock, ObjectID object_id, unsigned char *digest) { flatbuffers::FlatBufferBuilder fbb; - auto digest_string = fbb.CreateString((char *) digest, kDigestSize); + auto digest_string = fbb.CreateString(reinterpret_cast(digest), kDigestSize); auto message = CreatePlasmaSealRequest( fbb, fbb.CreateString(object_id.binary()), digest_string); fbb.Finish(message); @@ -550,7 +550,7 @@ Status SendDataRequest(int sock, const char *address, int port) { flatbuffers::FlatBufferBuilder fbb; - auto addr = fbb.CreateString((char *) address, strlen(address)); + auto addr = fbb.CreateString(address, strlen(address)); auto message = CreatePlasmaDataRequest( fbb, fbb.CreateString(object_id.binary()), addr, port); fbb.Finish(message); diff --git a/cpp/src/plasma/store.cc b/cpp/src/plasma/store.cc index 8aada18f83e..29bf5e88576 100644 --- a/cpp/src/plasma/store.cc +++ b/cpp/src/plasma/store.cc @@ -50,8 +50,8 @@ #include "plasma/store.h" #include "plasma/io.h" #include "format/common_generated.h" -#include "fling.h" -#include "malloc.h" +#include "plasma/fling.h" +#include "plasma/malloc.h" extern "C" { void *dlmalloc(size_t); From b1e0335a8227ce6997fd5151846057a009b4303f Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sat, 3 Jun 2017 16:58:32 -0700 Subject: [PATCH 14/53] fix linting --- cpp/CMakeLists.txt | 5 +- cpp/src/arrow/status.h | 12 ++- cpp/src/plasma/CMakeLists.txt | 1 + cpp/src/plasma/client.cc | 7 +- cpp/src/plasma/client.h | 4 +- cpp/src/plasma/events.cc | 2 +- cpp/src/plasma/events.h | 4 +- cpp/src/plasma/extension.cc | 90 +++++++++++----------- cpp/src/plasma/extension.h | 3 +- cpp/src/plasma/malloc.cc | 1 + cpp/src/plasma/plasma.cc | 4 +- cpp/src/plasma/protocol.cc | 2 +- cpp/src/plasma/protocol.h | 2 +- cpp/src/plasma/store.cc | 23 +++--- cpp/src/plasma/test/client_tests.cc | 12 +-- cpp/src/plasma/test/serialization_tests.cc | 13 ++-- 16 files changed, 100 insertions(+), 85 deletions(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 37493c52324..96b7138e3dd 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -864,7 +864,10 @@ if (UNIX) IF(NOT ((item MATCHES "_generated.h") OR (item MATCHES "pyarrow_api.h") OR (item MATCHES "xxhash.h") OR - (item MATCHES "xxhash.cc"))) + (item MATCHES "xxhash.cc") OR + (item MATCHES "config.h") OR + (item MATCHES "zmalloc.h") OR + (item MATCHES "ae.h"))) LIST(APPEND FILTERED_LINT_FILES ${item}) ENDIF() ENDFOREACH(item ${LINT_FILES}) diff --git a/cpp/src/arrow/status.h b/cpp/src/arrow/status.h index 9f26d8975d6..4ee221de23d 100644 --- a/cpp/src/arrow/status.h +++ b/cpp/src/arrow/status.h @@ -155,11 +155,17 @@ class ARROW_EXPORT Status { bool IsUnknownError() const { return code() == StatusCode::UnknownError; } bool IsNotImplemented() const { return code() == StatusCode::NotImplemented; } // An object with this object ID already exists in the plasma store. - bool IsPlasmaObjectExists() const { return code() == StatusCode::PlasmaObjectExists; } + bool IsPlasmaObjectExists() const { + return code() == StatusCode::PlasmaObjectExists; + } // An object was requested that doesn't exist in the plasma store. - bool IsPlasmaObjectNonexistent() const { return code() == StatusCode::PlasmaObjectNonexistent; } + bool IsPlasmaObjectNonexistent() const { + return code() == StatusCode::PlasmaObjectNonexistent; + } // An object is too large to fit into the plasma store. - bool IsPlasmaStoreFull() const { return code() == StatusCode::PlasmaStoreFull; } + bool IsPlasmaStoreFull() const { + return code() == StatusCode::PlasmaStoreFull; + } // Return a string representation of this status suitable for printing. // Returns the string "OK" for success. diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index 0e22b9e7fb4..9868db8d69f 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -81,6 +81,7 @@ include_directories("${FLATBUFFERS_INCLUDE_DIR}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") set_source_files_properties(thirdparty/dlmalloc.c PROPERTIES COMPILE_FLAGS -Wno-all) +set_source_files_properties(extension.cc PROPERTIES COMPILE_FLAGS -Wno-strict-aliasing) add_library(plasma_lib STATIC client.cc diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index b071e9aab8b..c585b411119 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -92,7 +92,8 @@ uint8_t *lookup_or_mmap(PlasmaClient *conn, close(fd); return entry->second->pointer; } else { - uint8_t *result = reinterpret_cast(mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); + uint8_t *result = reinterpret_cast( + mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); if (result == MAP_FAILED) { ARROW_LOG(FATAL) << "mmap failed"; } @@ -589,10 +590,10 @@ Status PlasmaClient::Info(ObjectID object_id, int *object_status) { return ReadStatusReply(buffer.data(), &object_id, object_status, 1); } -Status PlasmaClient::Wait(int num_object_requests, +Status PlasmaClient::Wait(int64_t num_object_requests, ObjectRequest object_requests[], int num_ready_objects, - uint64_t timeout_ms, + int64_t timeout_ms, int &num_objects_ready) { ARROW_CHECK(manager_conn >= 0); ARROW_CHECK(num_object_requests > 0); diff --git a/cpp/src/plasma/client.h b/cpp/src/plasma/client.h index 41464c020ea..6e4794210cd 100644 --- a/cpp/src/plasma/client.h +++ b/cpp/src/plasma/client.h @@ -238,10 +238,10 @@ class PlasmaClient { /// the object_requests list. If the returned number is less than /// min_num_ready_objects this means that timeout expired. /// @return The return status. - Status Wait(int num_object_requests, + Status Wait(int64_t num_object_requests, ObjectRequest object_requests[], int num_ready_objects, - uint64_t timeout_ms, + int64_t timeout_ms, int &num_objects_ready); /// Transfer local object to a different plasma manager. diff --git a/cpp/src/plasma/events.cc b/cpp/src/plasma/events.cc index 564fff168ae..0b33f2a5cf0 100644 --- a/cpp/src/plasma/events.cc +++ b/cpp/src/plasma/events.cc @@ -28,7 +28,7 @@ void EventLoop::file_event_callback(aeEventLoop *loop, } int EventLoop::timer_event_callback(aeEventLoop *loop, - long long timer_id, + TimerID timer_id, void *context) { TimerCallback *callback = reinterpret_cast(context); return (*callback)(timer_id); diff --git a/cpp/src/plasma/events.h b/cpp/src/plasma/events.h index 0f1986d5c1c..6baeed89b8d 100644 --- a/cpp/src/plasma/events.h +++ b/cpp/src/plasma/events.h @@ -35,6 +35,8 @@ constexpr int kEventLoopRead = AE_READABLE; /// Write event on the file descriptor. constexpr int kEventLoopWrite = AE_WRITABLE; +typedef long long TimerID; // NOLINT + class EventLoop { public: // Signature of the handler that will be called when there is a new event @@ -91,7 +93,7 @@ class EventLoop { int events); static int timer_event_callback(aeEventLoop *loop, - long long timer_id, + TimerID timer_id, void *context); aeEventLoop *loop_; diff --git a/cpp/src/plasma/extension.cc b/cpp/src/plasma/extension.cc index 6934f9b5e04..528c157847f 100644 --- a/cpp/src/plasma/extension.cc +++ b/cpp/src/plasma/extension.cc @@ -19,9 +19,11 @@ #include "plasma/common.h" #include "plasma/protocol.h" #include "plasma/client.h" - #include "plasma/extension.h" +#include +#include + PyObject *PlasmaOutOfMemoryError; PyObject *PlasmaObjectExistsError; @@ -52,16 +54,16 @@ PyObject *PyPlasma_disconnect(PyObject *self, PyObject *args) { * is still active (if the context is NULL) or if it is closed (if the context * is (void*) 0x1). This is neccessary because the primary pointer of the * capsule cannot be NULL. */ - PyCapsule_SetContext(client_capsule, (void *) 0x1); + PyCapsule_SetContext(client_capsule, reinterpret_cast(0x1)); Py_RETURN_NONE; } PyObject *PyPlasma_create(PyObject *self, PyObject *args) { PlasmaClient *client; ObjectID object_id; - long long size; + Py_ssize_t size; PyObject *metadata; - if (!PyArg_ParseTuple(args, "O&O&LO", PyObjectToPlasmaClient, &client, + if (!PyArg_ParseTuple(args, "O&O&nO", PyObjectToPlasmaClient, &client, PyStringToUniqueID, &object_id, &size, &metadata)) { return NULL; } @@ -71,7 +73,7 @@ PyObject *PyPlasma_create(PyObject *self, PyObject *args) { } uint8_t *data; Status s = client->Create(object_id, size, - (uint8_t *) PyByteArray_AsString(metadata), + reinterpret_cast(PyByteArray_AsString(metadata)), PyByteArray_Size(metadata), &data); if (s.IsPlasmaObjectExists()) { PyErr_SetString(PlasmaObjectExistsError, @@ -88,9 +90,9 @@ PyObject *PyPlasma_create(PyObject *self, PyObject *args) { ARROW_CHECK(s.ok()); #if PY_MAJOR_VERSION >= 3 - return PyMemoryView_FromMemory((char *) data, (Py_ssize_t) size, PyBUF_WRITE); + return PyMemoryView_FromMemory(reinterpret_cast(data), size, PyBUF_WRITE); #else - return PyBuffer_FromReadWriteMemory((void *) data, (Py_ssize_t) size); + return PyBuffer_FromReadWriteMemory(reinterpret_cast(data), size); #endif } @@ -105,7 +107,7 @@ PyObject *PyPlasma_hash(PyObject *self, PyObject *args) { bool success = plasma_compute_object_hash(client, object_id, digest); if (success) { PyObject *digest_string = - PyBytes_FromStringAndSize((char *) digest, kDigestSize); + PyBytes_FromStringAndSize(reinterpret_cast(digest), kDigestSize); return digest_string; } else { Py_RETURN_NONE; @@ -137,16 +139,15 @@ PyObject *PyPlasma_release(PyObject *self, PyObject *args) { PyObject *PyPlasma_get(PyObject *self, PyObject *args) { PlasmaClient *client; PyObject *object_id_list; - long long timeout_ms; - if (!PyArg_ParseTuple(args, "O&OL", PyObjectToPlasmaClient, &client, + Py_ssize_t timeout_ms; + if (!PyArg_ParseTuple(args, "O&On", PyObjectToPlasmaClient, &client, &object_id_list, &timeout_ms)) { return NULL; } Py_ssize_t num_object_ids = PyList_Size(object_id_list); - ObjectID *object_ids = (ObjectID *) malloc(sizeof(ObjectID) * num_object_ids); - ObjectBuffer *object_buffers = - (ObjectBuffer *) malloc(sizeof(ObjectBuffer) * num_object_ids); + ObjectID *object_ids = new ObjectID[num_object_ids]; + ObjectBuffer *object_buffers = new ObjectBuffer[num_object_ids]; for (int i = 0; i < num_object_ids; ++i) { PyStringToUniqueID(PyList_GetItem(object_id_list, i), &object_ids[i]); @@ -156,39 +157,35 @@ PyObject *PyPlasma_get(PyObject *self, PyObject *args) { ARROW_CHECK_OK( client->Get(object_ids, num_object_ids, timeout_ms, object_buffers)); Py_END_ALLOW_THREADS; - free(object_ids); + delete[] object_ids; PyObject *returns = PyList_New(num_object_ids); for (int i = 0; i < num_object_ids; ++i) { if (object_buffers[i].data_size != -1) { /* The object was retrieved, so return the object. */ PyObject *t = PyTuple_New(2); + Py_ssize_t data_size = static_cast(object_buffers[i].data_size); + Py_ssize_t metadata_size = static_cast(object_buffers[i].metadata_size); #if PY_MAJOR_VERSION >= 3 - PyTuple_SetItem( - t, 0, PyMemoryView_FromMemory( - (char *) object_buffers[i].data, - (Py_ssize_t) object_buffers[i].data_size, PyBUF_READ)); - PyTuple_SetItem( - t, 1, PyMemoryView_FromMemory( - (char *) object_buffers[i].metadata, - (Py_ssize_t) object_buffers[i].metadata_size, PyBUF_READ)); + char *data = reinterpret_cast(object_buffers[i].data); + char *metadata = reinterpret_cast(object_buffers[i].metadata); + PyTuple_SetItem(t, 0, PyMemoryView_FromMemory(data, data_size, PyBUF_READ)); + PyTuple_SetItem(t, 1, PyMemoryView_FromMemory(metadata, metadata_size, PyBUF_READ)); #else - PyTuple_SetItem( - t, 0, PyBuffer_FromMemory((void *) object_buffers[i].data, - (Py_ssize_t) object_buffers[i].data_size)); - PyTuple_SetItem(t, 1, PyBuffer_FromMemory( - (void *) object_buffers[i].metadata, - (Py_ssize_t) object_buffers[i].metadata_size)); + void *data = reinterpret_cast(object_buffers[i].data); + void *metadata = reinterpret_cast(object_buffers[i].metadata); + PyTuple_SetItem(t, 0, PyBuffer_FromMemory(data, data_size)); + PyTuple_SetItem(t, 1, PyBuffer_FromMemory(metadata, metadata_size)); #endif PyList_SetItem(returns, i, t); } else { /* The object was not retrieved, so just add None to the list of return * values. */ - Py_XINCREF(Py_None); + Py_INCREF(Py_None); PyList_SetItem(returns, i, Py_None); } } - free(object_buffers); + delete[] object_buffers; return returns; } @@ -220,21 +217,21 @@ PyObject *PyPlasma_fetch(PyObject *self, PyObject *args) { return NULL; } Py_ssize_t n = PyList_Size(object_id_list); - ObjectID *object_ids = (ObjectID *) malloc(sizeof(ObjectID) * n); + ObjectID *object_ids = new ObjectID[n]; for (int i = 0; i < n; ++i) { PyStringToUniqueID(PyList_GetItem(object_id_list, i), &object_ids[i]); } - ARROW_CHECK_OK(client->Fetch((int) n, object_ids)); - free(object_ids); + ARROW_CHECK_OK(client->Fetch(static_cast(n), object_ids)); + delete[] object_ids; Py_RETURN_NONE; } PyObject *PyPlasma_wait(PyObject *self, PyObject *args) { PlasmaClient *client; PyObject *object_id_list; - long long timeout; + Py_ssize_t timeout; int num_returns; - if (!PyArg_ParseTuple(args, "O&OLi", PyObjectToPlasmaClient, &client, + if (!PyArg_ParseTuple(args, "O&Oni", PyObjectToPlasmaClient, &client, &object_id_list, &timeout, &num_returns)) { return NULL; } @@ -262,8 +259,7 @@ PyObject *PyPlasma_wait(PyObject *self, PyObject *args) { return NULL; } - ObjectRequest *object_requests = - (ObjectRequest *) malloc(sizeof(ObjectRequest) * n); + std::vector object_requests(n); for (int i = 0; i < n; ++i) { ARROW_CHECK(PyStringToUniqueID(PyList_GetItem(object_id_list, i), &object_requests[i].object_id) == 1); @@ -273,8 +269,8 @@ PyObject *PyPlasma_wait(PyObject *self, PyObject *args) { * run. */ int num_return_objects; Py_BEGIN_ALLOW_THREADS; - ARROW_CHECK_OK(client->Wait((int) n, object_requests, num_returns, - (uint64_t) timeout, num_return_objects)); + ARROW_CHECK_OK(client->Wait(n, object_requests.data(), num_returns, + timeout, num_return_objects)); Py_END_ALLOW_THREADS; int num_to_return = std::min(num_return_objects, num_returns); @@ -287,9 +283,9 @@ PyObject *PyPlasma_wait(PyObject *self, PyObject *args) { } if (object_requests[i].status == ObjectStatus_Local || object_requests[i].status == ObjectStatus_Remote) { - PyObject *ready = - PyBytes_FromStringAndSize((char *) &object_requests[i].object_id, - sizeof(object_requests[i].object_id)); + PyObject *ready = PyBytes_FromStringAndSize( + reinterpret_cast(&object_requests[i].object_id), + sizeof(object_requests[i].object_id)); PyList_SetItem(ready_ids, num_returned, ready); PySet_Discard(waiting_ids, ready); num_returned += 1; @@ -307,14 +303,14 @@ PyObject *PyPlasma_wait(PyObject *self, PyObject *args) { PyObject *PyPlasma_evict(PyObject *self, PyObject *args) { PlasmaClient *client; - long long num_bytes; - if (!PyArg_ParseTuple(args, "O&L", PyObjectToPlasmaClient, &client, + Py_ssize_t num_bytes; + if (!PyArg_ParseTuple(args, "O&n", PyObjectToPlasmaClient, &client, &num_bytes)) { return NULL; } int64_t evicted_bytes; - ARROW_CHECK_OK(client->Evict((int64_t) num_bytes, evicted_bytes)); - return PyLong_FromLong((long) evicted_bytes); + ARROW_CHECK_OK(client->Evict(static_cast(num_bytes), evicted_bytes)); + return PyLong_FromSsize_t(static_cast(evicted_bytes)); } PyObject *PyPlasma_delete(PyObject *self, PyObject *args) { @@ -388,7 +384,7 @@ PyObject *PyPlasma_receive_notification(PyObject *self, PyObject *args) { PyTuple_SetItem(t, 2, PyLong_FromLong(object_info->metadata_size())); } - free(notification); + delete[] notification; return t; } diff --git a/cpp/src/plasma/extension.h b/cpp/src/plasma/extension.h index f75226773c3..b908833ed7f 100644 --- a/cpp/src/plasma/extension.h +++ b/cpp/src/plasma/extension.h @@ -19,8 +19,9 @@ #define PLASMA_EXTENSION_H #undef _XOPEN_SOURCE +#undef _POSIX_C_SOURCE #include -#include "bytesobject.h" +#include "bytesobject.h" // NOLINT static int PyObjectToPlasmaClient(PyObject *object, PlasmaClient **client) { if (PyCapsule_IsValid(object, "plasma")) { diff --git a/cpp/src/plasma/malloc.cc b/cpp/src/plasma/malloc.cc index 0d53ebc342d..25c51d043fa 100644 --- a/cpp/src/plasma/malloc.cc +++ b/cpp/src/plasma/malloc.cc @@ -26,6 +26,7 @@ #include #include "plasma/common.h" +#include "plasma/malloc.h" extern "C" { void *fake_mmap(size_t); diff --git a/cpp/src/plasma/plasma.cc b/cpp/src/plasma/plasma.cc index 1c8ea4437b6..43ac61cbb68 100644 --- a/cpp/src/plasma/plasma.cc +++ b/cpp/src/plasma/plasma.cc @@ -47,13 +47,13 @@ int warn_if_sigpipe(int status, int client_sock) { * * @param object_info The object info to be serialized * @return The object info buffer. It is the caller's responsibility to free - * this buffer with "free" after it has been used. + * this buffer with "delete" after it has been used. */ uint8_t *create_object_info_buffer(ObjectInfoT *object_info) { flatbuffers::FlatBufferBuilder fbb; auto message = CreateObjectInfo(fbb, object_info); fbb.Finish(message); - uint8_t *notification = reinterpret_cast(malloc(sizeof(int64_t) + fbb.GetSize())); + uint8_t *notification = new uint8_t[sizeof(int64_t) + fbb.GetSize()]; *(reinterpret_cast(notification)) = fbb.GetSize(); memcpy(notification + sizeof(int64_t), fbb.GetBufferPointer(), fbb.GetSize()); return notification; diff --git a/cpp/src/plasma/protocol.cc b/cpp/src/plasma/protocol.cc index dc0b8707d75..4e335bf11a0 100644 --- a/cpp/src/plasma/protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -457,7 +457,7 @@ Status ReadFetchRequest(uint8_t *data, std::vector &object_ids) { Status SendWaitRequest(int sock, ObjectRequest object_requests[], - int num_requests, + int64_t num_requests, int num_ready_objects, int64_t timeout_ms) { flatbuffers::FlatBufferBuilder fbb; diff --git a/cpp/src/plasma/protocol.h b/cpp/src/plasma/protocol.h index b4cf3eacab3..72b18c81da9 100644 --- a/cpp/src/plasma/protocol.h +++ b/cpp/src/plasma/protocol.h @@ -167,7 +167,7 @@ Status ReadFetchRequest(uint8_t *data, std::vector &object_ids); Status SendWaitRequest(int sock, ObjectRequest object_requests[], - int num_requests, + int64_t num_requests, int num_ready_objects, int64_t timeout_ms); diff --git a/cpp/src/plasma/store.cc b/cpp/src/plasma/store.cc index 29bf5e88576..918f39a56fd 100644 --- a/cpp/src/plasma/store.cc +++ b/cpp/src/plasma/store.cc @@ -42,6 +42,7 @@ #include #include +#include #include #include #include @@ -54,9 +55,9 @@ #include "plasma/malloc.h" extern "C" { -void *dlmalloc(size_t); +void *dlmalloc(size_t bytes); void *dlmemalign(size_t alignment, size_t bytes); -void dlfree(void *); +void dlfree(void * mem); size_t dlmalloc_set_footprint_limit(size_t bytes); } @@ -102,9 +103,9 @@ PlasmaStore::~PlasmaStore() { for (const auto &element : pending_notifications_) { auto object_notifications = element.second.object_notifications; for (size_t i = 0; i < object_notifications.size(); ++i) { - uint8_t *notification = (uint8_t *) object_notifications.at(i); + uint8_t *notification = reinterpret_cast(object_notifications.at(i)); uint8_t *data = notification; - free(data); + delete[] data; } } } @@ -151,7 +152,8 @@ int PlasmaStore::create_object(ObjectID object_id, // plasma_client.cc). Note that even though this pointer is 64-byte aligned, // it is not guaranteed that the corresponding pointer in the client will be // 64-byte aligned, but in practice it often will be. - pointer = (uint8_t *) dlmemalign(BLOCK_SIZE, data_size + metadata_size); + pointer = reinterpret_cast( + dlmemalign(BLOCK_SIZE, data_size + metadata_size)); if (pointer == NULL) { // Tell the eviction policy how much space we need to create this object. std::vector objects_to_evict; @@ -380,7 +382,7 @@ void PlasmaStore::seal_object(ObjectID object_id, unsigned char digest[]) { // Set the state of object to SEALED. entry->state = PLASMA_SEALED; // Set the object digest. - entry->info.digest = std::string((char *) &digest[0], kDigestSize); + entry->info.digest = std::string(reinterpret_cast(&digest[0]), kDigestSize); // Inform all subscribers that a new object has been sealed. push_notification(&entry->info); @@ -457,9 +459,10 @@ void PlasmaStore::send_notifications(int client_fd) { // Loop over the array of pending notifications and send as many of them as // possible. for (size_t i = 0; i < it->second.object_notifications.size(); ++i) { - uint8_t *notification = (uint8_t *) it->second.object_notifications.at(i); + uint8_t *notification = + reinterpret_cast(it->second.object_notifications.at(i)); // Decode the length, which is the first bytes of the message. - int64_t size = *((int64_t *) notification); + int64_t size = *(reinterpret_cast(notification)); // Attempt to send a notification about this object ID. ssize_t nbytes = send(client_fd, notification, sizeof(int64_t) + size, 0); @@ -491,7 +494,7 @@ void PlasmaStore::send_notifications(int client_fd) { num_processed += 1; // The corresponding malloc happened in create_object_info_buffer // within push_notification. - free(notification); + delete[] notification; } // Remove the sent notifications from the array. it->second.object_notifications.erase( @@ -661,7 +664,7 @@ int main(int argc, char *argv[]) { int scanned = sscanf(optarg, "%" SCNd64 "%c", &system_memory, &extra); ARROW_CHECK(scanned == 1); ARROW_LOG(INFO) << "Allowing the Plasma store to use up to " - << ((double) system_memory) / 1000000000 + << static_cast(system_memory) / 1000000000 << "GB of memory."; break; } diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index 6a993be0509..a172fd758c8 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -15,16 +15,16 @@ // specific language governing permissions and limitations // under the License. -#include "greatest.h" +#include "thirdparty/greatest.h" #include #include #include -#include "plasma_common.h" -#include "plasma.h" -#include "plasma_protocol.h" -#include "plasma_client.h" +#include "plasma/common.h" +#include "plasma/plasma.h" +#include "plasma/protocol.h" +#include "plasma/client.h" SUITE(plasma_client_tests); @@ -135,7 +135,7 @@ bool is_equal_data_123(uint8_t *data1, uint8_t *data2, uint64_t size) { for (int i = 0; i < size; i++) { if (data1[i] != data2[i]) { return false; - }; + } } return true; } diff --git a/cpp/src/plasma/test/serialization_tests.cc b/cpp/src/plasma/test/serialization_tests.cc index c3b2f3f7775..8b402d3ff55 100644 --- a/cpp/src/plasma/test/serialization_tests.cc +++ b/cpp/src/plasma/test/serialization_tests.cc @@ -15,15 +15,15 @@ // specific language governing permissions and limitations // under the License. -#include "greatest.h" +#include "thirdparty/greatest.h" #include #include -#include "plasma_common.h" -#include "plasma.h" -#include "plasma_io.h" -#include "plasma_protocol.h" +#include "plasma/common.h" +#include "plasma/plasma.h" +#include "plasma/io.h" +#include "plasma/protocol.h" SUITE(plasma_serialization_tests); @@ -59,7 +59,8 @@ std::vector read_message_from_file(int fd, int message_type) { } PlasmaObject random_plasma_object(void) { - int random = rand(); + unsigned int seed = time(NULL); + int random = rand_r(&seed); PlasmaObject object; memset(&object, 0, sizeof(object)); object.handle.store_fd = random + 7; From 74ecb19907db52ea68bcf980b3083760977fc4bb Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Wed, 7 Jun 2017 18:04:14 -0700 Subject: [PATCH 15/53] don't link against Python libraries --- cpp/src/plasma/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index 9868db8d69f..726a6ae7f2d 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -71,9 +71,9 @@ add_library(plasma SHARED add_dependencies(plasma gen_plasma_fbs) if(APPLE) - target_link_libraries(plasma plasma_lib "-undefined dynamic_lookup" -Wl,-force_load,${FLATBUFFERS_STATIC_LIB} ${PYTHON_LIBRARIES} ${FLATBUFFERS_STATIC_LIB} -lpthread) + target_link_libraries(plasma plasma_lib "-undefined dynamic_lookup" -Wl,-force_load,${FLATBUFFERS_STATIC_LIB} ${FLATBUFFERS_STATIC_LIB} -lpthread) else(APPLE) - target_link_libraries(plasma plasma_lib -Wl,--whole-archive ${FLATBUFFERS_STATIC_LIB} -Wl,--no-whole-archive ${PYTHON_LIBRARIES} ${FLATBUFFERS_STATIC_LIB} -lpthread) + target_link_libraries(plasma plasma_lib -Wl,--whole-archive ${FLATBUFFERS_STATIC_LIB} -Wl,--no-whole-archive ${FLATBUFFERS_STATIC_LIB} -lpthread) endif(APPLE) include_directories("${FLATBUFFERS_INCLUDE_DIR}") From e11b0e86ef1e4cea524383442aff06c588d75d60 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Wed, 7 Jun 2017 20:38:47 -0700 Subject: [PATCH 16/53] fix pthread --- ci/travis_before_script_cpp.sh | 2 +- cpp/src/plasma/CMakeLists.txt | 11 +++++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/ci/travis_before_script_cpp.sh b/ci/travis_before_script_cpp.sh index 1901c54fca7..a38a0dc1328 100755 --- a/ci/travis_before_script_cpp.sh +++ b/ci/travis_before_script_cpp.sh @@ -72,7 +72,7 @@ else $ARROW_CPP_DIR fi -make -j4 +make VERBOSE=1 -j4 make install popd diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index 726a6ae7f2d..b276e721b43 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -20,12 +20,15 @@ cmake_minimum_required(VERSION 2.8) project(plasma) find_package(PythonLibsNew REQUIRED) +find_package(Threads) + if(APPLE) SET(CMAKE_SHARED_LIBRARY_SUFFIX ".so") endif(APPLE) -include_directories("${PYTHON_INCLUDE_DIRS}" thirdparty ..) +include_directories(SYSTEM ${PYTHON_INCLUDE_DIRS}) +include_directories(thirdparty ..) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++11 -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200809L -march=native -mtune=native -O3") @@ -71,9 +74,9 @@ add_library(plasma SHARED add_dependencies(plasma gen_plasma_fbs) if(APPLE) - target_link_libraries(plasma plasma_lib "-undefined dynamic_lookup" -Wl,-force_load,${FLATBUFFERS_STATIC_LIB} ${FLATBUFFERS_STATIC_LIB} -lpthread) + target_link_libraries(plasma plasma_lib "-undefined dynamic_lookup" ${FLATBUFFERS_STATIC_LIB} ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT}) else(APPLE) - target_link_libraries(plasma plasma_lib -Wl,--whole-archive ${FLATBUFFERS_STATIC_LIB} -Wl,--no-whole-archive ${FLATBUFFERS_STATIC_LIB} -lpthread) + target_link_libraries(plasma plasma_lib -Wl,--whole-archive ${FLATBUFFERS_STATIC_LIB} -Wl,--no-whole-archive ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT}) endif(APPLE) include_directories("${FLATBUFFERS_INCLUDE_DIR}") @@ -93,7 +96,7 @@ add_library(plasma_lib STATIC fling.cc thirdparty/xxhash.cc) -target_link_libraries(plasma_lib ${FLATBUFFERS_STATIC_LIB} -lpthread) +target_link_libraries(plasma_lib ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT}) add_dependencies(plasma_lib gen_plasma_fbs) set_source_files_properties(malloc.cc PROPERTIES COMPILE_FLAGS "-Wno-error=conversion") From f936adb7b3f2a00ee282e3380abca361bb215f9f Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sun, 11 Jun 2017 14:54:34 -0700 Subject: [PATCH 17/53] build plasma python client only if python is available --- ci/travis_script_python.sh | 1 + cpp/src/plasma/CMakeLists.txt | 42 +++++++++++++++++------------------ 2 files changed, 22 insertions(+), 21 deletions(-) diff --git a/ci/travis_script_python.sh b/ci/travis_script_python.sh index 904db52a69a..2b2f98892a8 100755 --- a/ci/travis_script_python.sh +++ b/ci/travis_script_python.sh @@ -72,6 +72,7 @@ function build_arrow_libraries() { cmake -DARROW_BUILD_TESTS=off \ -DARROW_PYTHON=on \ + -DPLASMA_PYTHON=on \ -DCMAKE_INSTALL_PREFIX=$2 \ $CPP_DIR diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index b276e721b43..299713f64ad 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -22,13 +22,16 @@ project(plasma) find_package(PythonLibsNew REQUIRED) find_package(Threads) +option(PLASMA_PYTHON + "Build the Plasma Python extensions" + OFF) if(APPLE) SET(CMAKE_SHARED_LIBRARY_SUFFIX ".so") endif(APPLE) include_directories(SYSTEM ${PYTHON_INCLUDE_DIRS}) -include_directories(thirdparty ..) +include_directories("${FLATBUFFERS_INCLUDE_DIR}" "${CMAKE_CURRENT_LIST_DIR}/" "${CMAKE_CURRENT_LIST_DIR}/thirdparty/" "${CMAKE_CURRENT_LIST_DIR}/../") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++11 -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200809L -march=native -mtune=native -O3") @@ -60,26 +63,23 @@ if(UNIX AND NOT APPLE) link_libraries(rt) endif() -include_directories("${CMAKE_CURRENT_LIST_DIR}/") -include_directories("${CMAKE_CURRENT_LIST_DIR}/../") - -add_library(plasma SHARED - plasma.cc - extension.cc - protocol.cc - client.cc - thirdparty/xxhash.cc - fling.cc) - -add_dependencies(plasma gen_plasma_fbs) - -if(APPLE) - target_link_libraries(plasma plasma_lib "-undefined dynamic_lookup" ${FLATBUFFERS_STATIC_LIB} ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT}) -else(APPLE) - target_link_libraries(plasma plasma_lib -Wl,--whole-archive ${FLATBUFFERS_STATIC_LIB} -Wl,--no-whole-archive ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT}) -endif(APPLE) - -include_directories("${FLATBUFFERS_INCLUDE_DIR}") +if(PLASMA_PYTHON) + add_library(plasma SHARED + plasma.cc + extension.cc + protocol.cc + client.cc + thirdparty/xxhash.cc + fling.cc) + + add_dependencies(plasma gen_plasma_fbs) + + if(APPLE) + target_link_libraries(plasma plasma_lib "-undefined dynamic_lookup" ${FLATBUFFERS_STATIC_LIB} ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT}) + else(APPLE) + target_link_libraries(plasma plasma_lib -Wl,--whole-archive ${FLATBUFFERS_STATIC_LIB} -Wl,--no-whole-archive ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT}) + endif(APPLE) +endif() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") From d6e60d26c92c29533f62b816bf6321f04461c1d2 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sun, 11 Jun 2017 18:22:15 -0700 Subject: [PATCH 18/53] do not compile plasma on windows --- cpp/CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 96b7138e3dd..6eb02523395 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -951,7 +951,9 @@ if(FLATBUFFERS_VENDORED) set(ARROW_DEPENDENCIES ${ARROW_DEPENDENCIES} flatbuffers_ep) endif() -add_subdirectory(src/plasma) +if(NOT WIN32) + add_subdirectory(src/plasma) +endif() add_subdirectory(src/arrow) add_subdirectory(src/arrow/io) if (ARROW_IPC) From f40f85bdb85314bcaa38f104c9c040eb9f33b7bb Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Mon, 12 Jun 2017 16:36:28 -0700 Subject: [PATCH 19/53] add clang-format exceptions --- cpp/CMakeLists.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 6eb02523395..37a1647065e 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -895,7 +895,10 @@ if (${CLANG_FORMAT_FOUND}) sed -e '/windows_compatibility.h/g' | sed -e '/pyarrow_api.h/g' | sed -e '/config.h/g' | # python/config.h - sed -e '/platform.h/g'` # python/platform.h + sed -e '/platform.h/g' | # python/platform.h + sed -e '/ae.h/g' | + sed -e '/xxhash.cc/g' | + sed -e '/xxhash.h/g'` ) # runs clang format and exits with a non-zero exit code if any files need to be reformatted From ed680f97fa56338d7a00dff7087e83c38f1447b5 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Mon, 12 Jun 2017 16:40:51 -0700 Subject: [PATCH 20/53] reformat the code --- cpp/src/arrow/status.h | 14 +- cpp/src/arrow/util/logging.h | 7 +- cpp/src/plasma/client.cc | 230 +++++-------- cpp/src/plasma/client.h | 53 ++- cpp/src/plasma/common.cc | 34 +- cpp/src/plasma/common.h | 12 +- cpp/src/plasma/events.cc | 36 +- cpp/src/plasma/events.h | 13 +- cpp/src/plasma/eviction_policy.cc | 37 +- cpp/src/plasma/eviction_policy.h | 24 +- cpp/src/plasma/extension.cc | 265 +++++++-------- cpp/src/plasma/extension.h | 8 +- cpp/src/plasma/fling.cc | 19 +- cpp/src/plasma/fling.h | 9 +- cpp/src/plasma/io.cc | 94 ++---- cpp/src/plasma/io.h | 25 +- cpp/src/plasma/malloc.cc | 59 ++-- cpp/src/plasma/malloc.h | 5 +- cpp/src/plasma/plasma.cc | 34 +- cpp/src/plasma/plasma.h | 25 +- cpp/src/plasma/protocol.cc | 353 +++++++++----------- cpp/src/plasma/protocol.h | 147 +++----- cpp/src/plasma/store.cc | 371 ++++++++++----------- cpp/src/plasma/store.h | 43 ++- cpp/src/plasma/test/client_tests.cc | 121 +++---- cpp/src/plasma/test/serialization_tests.cc | 98 +++--- 26 files changed, 902 insertions(+), 1234 deletions(-) diff --git a/cpp/src/arrow/status.h b/cpp/src/arrow/status.h index 4ee221de23d..7e7f67ce628 100644 --- a/cpp/src/arrow/status.h +++ b/cpp/src/arrow/status.h @@ -132,15 +132,15 @@ class ARROW_EXPORT Status { return Status(StatusCode::IOError, msg, -1); } - static Status PlasmaObjectExists(const std::string &msg) { + static Status PlasmaObjectExists(const std::string& msg) { return Status(StatusCode::PlasmaObjectExists, msg, -1); } - static Status PlasmaObjectNonexistent(const std::string &msg) { + static Status PlasmaObjectNonexistent(const std::string& msg) { return Status(StatusCode::PlasmaObjectNonexistent, msg, -1); } - static Status PlasmaStoreFull(const std::string &msg) { + static Status PlasmaStoreFull(const std::string& msg) { return Status(StatusCode::PlasmaStoreFull, msg, -1); } @@ -155,17 +155,13 @@ class ARROW_EXPORT Status { bool IsUnknownError() const { return code() == StatusCode::UnknownError; } bool IsNotImplemented() const { return code() == StatusCode::NotImplemented; } // An object with this object ID already exists in the plasma store. - bool IsPlasmaObjectExists() const { - return code() == StatusCode::PlasmaObjectExists; - } + bool IsPlasmaObjectExists() const { return code() == StatusCode::PlasmaObjectExists; } // An object was requested that doesn't exist in the plasma store. bool IsPlasmaObjectNonexistent() const { return code() == StatusCode::PlasmaObjectNonexistent; } // An object is too large to fit into the plasma store. - bool IsPlasmaStoreFull() const { - return code() == StatusCode::PlasmaStoreFull; - } + bool IsPlasmaStoreFull() const { return code() == StatusCode::PlasmaStoreFull; } // Return a string representation of this status suitable for printing. // Returns the string "OK" for success. diff --git a/cpp/src/arrow/util/logging.h b/cpp/src/arrow/util/logging.h index 8a929da0e02..49f1699f136 100644 --- a/cpp/src/arrow/util/logging.h +++ b/cpp/src/arrow/util/logging.h @@ -39,10 +39,9 @@ namespace arrow { #define ARROW_LOG_INTERNAL(level) ::arrow::internal::CerrLog(level) #define ARROW_LOG(level) ARROW_LOG_INTERNAL(ARROW_##level) -#define ARROW_CHECK(condition) \ - (condition) ? 0 \ - : ::arrow::internal::FatalLog(ARROW_FATAL) \ - << __FILE__ << __LINE__ << " Check failed: " #condition " " +#define ARROW_CHECK(condition) \ + (condition) ? 0 : ::arrow::internal::FatalLog(ARROW_FATAL) \ + << __FILE__ << __LINE__ << " Check failed: " #condition " " #ifdef NDEBUG #define ARROW_DFATAL ARROW_WARNING diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index c585b411119..69dd826c25b 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -23,26 +23,26 @@ #include #include -#include +#include #include -#include -#include +#include +#include #include #include #include +#include #include -#include -#include +#include +#include "plasma/client.h" #include "plasma/common.h" -#include "plasma/plasma.h" #include "plasma/io.h" +#include "plasma/plasma.h" #include "plasma/protocol.h" -#include "plasma/client.h" #include -#include #include +#include #include "plasma/fling.h" @@ -58,7 +58,7 @@ static std::vector threadpool_(kThreadPoolSize); struct ClientMmapTableEntry { /// The result of mmap for this file descriptor. - uint8_t *pointer; + uint8_t* pointer; /// The length of the memory-mapped file. size_t length; /// The number of objects in this memory-mapped file that are currently being @@ -83,22 +83,17 @@ struct ObjectInUseEntry { // If the file descriptor fd has been mmapped in this client process before, // return the pointer that was returned by mmap, otherwise mmap it and store the // pointer in a hash table. -uint8_t *lookup_or_mmap(PlasmaClient *conn, - int fd, - int store_fd_val, - int64_t map_size) { +uint8_t* lookup_or_mmap(PlasmaClient* conn, int fd, int store_fd_val, int64_t map_size) { auto entry = conn->mmap_table.find(store_fd_val); if (entry != conn->mmap_table.end()) { close(fd); return entry->second->pointer; } else { - uint8_t *result = reinterpret_cast( - mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); - if (result == MAP_FAILED) { - ARROW_LOG(FATAL) << "mmap failed"; - } + uint8_t* result = reinterpret_cast( + mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); + if (result == MAP_FAILED) { ARROW_LOG(FATAL) << "mmap failed"; } close(fd); - ClientMmapTableEntry *entry = new ClientMmapTableEntry(); + ClientMmapTableEntry* entry = new ClientMmapTableEntry(); entry->pointer = result; entry->length = map_size; entry->count = 0; @@ -109,20 +104,18 @@ uint8_t *lookup_or_mmap(PlasmaClient *conn, // Get a pointer to a file that we know has been memory mapped in this client // process before. -uint8_t *lookup_mmapped_file(PlasmaClient *conn, int store_fd_val) { +uint8_t* lookup_mmapped_file(PlasmaClient* conn, int store_fd_val) { auto entry = conn->mmap_table.find(store_fd_val); ARROW_CHECK(entry != conn->mmap_table.end()); return entry->second->pointer; } -void increment_object_count(PlasmaClient *conn, - ObjectID object_id, - PlasmaObject *object, - bool is_sealed) { +void increment_object_count( + PlasmaClient* conn, ObjectID object_id, PlasmaObject* object, bool is_sealed) { // Increment the count of the object to track the fact that it is being used. // The corresponding decrement should happen in PlasmaClient::Release. auto elem = conn->objects_in_use.find(object_id); - ObjectInUseEntry *object_entry; + ObjectInUseEntry* object_entry; if (elem == conn->objects_in_use.end()) { // Add this object ID to the hash table of object IDs in use. The // corresponding call to free happens in PlasmaClient::Release. @@ -151,19 +144,13 @@ void increment_object_count(PlasmaClient *conn, object_entry->count += 1; } -Status PlasmaClient::Create(ObjectID object_id, - int64_t data_size, - uint8_t *metadata, - int64_t metadata_size, - uint8_t **data) { - ARROW_LOG(DEBUG) << "called plasma_create on conn " << store_conn - << " with size " << data_size << " and metadata size " - << metadata_size; - RETURN_NOT_OK( - SendCreateRequest(store_conn, object_id, data_size, metadata_size)); +Status PlasmaClient::Create(ObjectID object_id, int64_t data_size, uint8_t* metadata, + int64_t metadata_size, uint8_t** data) { + ARROW_LOG(DEBUG) << "called plasma_create on conn " << store_conn << " with size " + << data_size << " and metadata size " << metadata_size; + RETURN_NOT_OK(SendCreateRequest(store_conn, object_id, data_size, metadata_size)); std::vector buffer; - RETURN_NOT_OK( - PlasmaReceive(store_conn, MessageType_PlasmaCreateReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(store_conn, MessageType_PlasmaCreateReply, buffer)); ObjectID id; PlasmaObject object; RETURN_NOT_OK(ReadCreateReply(buffer.data(), &id, &object)); @@ -175,8 +162,7 @@ Status PlasmaClient::Create(ObjectID object_id, ARROW_CHECK(object.metadata_size == metadata_size); // The metadata should come right after the data. ARROW_CHECK(object.metadata_offset == object.data_offset + data_size); - *data = lookup_or_mmap(this, fd, object.handle.store_fd, - object.handle.mmap_size) + + *data = lookup_or_mmap(this, fd, object.handle.store_fd, object.handle.mmap_size) + object.data_offset; // If plasma_create is being called from a transfer, then we will not copy the // metadata here. The metadata will be written along with the data streamed @@ -199,10 +185,8 @@ Status PlasmaClient::Create(ObjectID object_id, return Status::OK(); } -Status PlasmaClient::Get(ObjectID object_ids[], - int64_t num_objects, - int64_t timeout_ms, - ObjectBuffer object_buffers[]) { +Status PlasmaClient::Get(ObjectID object_ids[], int64_t num_objects, int64_t timeout_ms, + ObjectBuffer object_buffers[]) { // Fill out the info for the objects that are already in use locally. bool all_present = true; for (int i = 0; i < num_objects; ++i) { @@ -218,9 +202,8 @@ Status PlasmaClient::Get(ObjectID object_ids[], // have been the one who created it. ARROW_CHECK(object_entry->second->is_sealed) << "Plasma client called get on an unsealed object that it created"; - PlasmaObject *object = &object_entry->second->object; - object_buffers[i].data = - lookup_mmapped_file(this, object->handle.store_fd); + PlasmaObject* object = &object_entry->second->object; + object_buffers[i].data = lookup_mmapped_file(this, object->handle.store_fd); object_buffers[i].data = object_buffers[i].data + object->data_offset; object_buffers[i].data_size = object->data_size; object_buffers[i].metadata = object_buffers[i].data + object->data_size; @@ -233,21 +216,18 @@ Status PlasmaClient::Get(ObjectID object_ids[], } } - if (all_present) { - return Status::OK(); - } + if (all_present) { return Status::OK(); } // If we get here, then the objects aren't all currently in use by this // client, so we need to send a request to the plasma store. - RETURN_NOT_OK( - SendGetRequest(store_conn, object_ids, num_objects, timeout_ms)); + RETURN_NOT_OK(SendGetRequest(store_conn, object_ids, num_objects, timeout_ms)); std::vector buffer; RETURN_NOT_OK(PlasmaReceive(store_conn, MessageType_PlasmaGetReply, buffer)); std::vector received_object_ids(num_objects); std::vector object_data(num_objects); - PlasmaObject *object; - RETURN_NOT_OK(ReadGetReply(buffer.data(), received_object_ids.data(), - object_data.data(), num_objects)); + PlasmaObject* object; + RETURN_NOT_OK(ReadGetReply( + buffer.data(), received_object_ids.data(), object_data.data(), num_objects)); for (int i = 0; i < num_objects; ++i) { DCHECK(received_object_ids[i] == object_ids[i]); @@ -273,8 +253,8 @@ Status PlasmaClient::Get(ObjectID object_ids[], // this object. int fd = recv_fd(store_conn); ARROW_CHECK(fd >= 0); - object_buffers[i].data = lookup_or_mmap(this, fd, object->handle.store_fd, - object->handle.mmap_size); + object_buffers[i].data = + lookup_or_mmap(this, fd, object->handle.store_fd, object->handle.mmap_size); // Finish filling out the return values. object_buffers[i].data = object_buffers[i].data + object->data_offset; object_buffers[i].data_size = object->data_size; @@ -350,9 +330,8 @@ Status PlasmaClient::Release(ObjectID object_id) { // If there are too many bytes in use by the client or if there are too many // pending release calls, and there are at least some pending release calls in // the release_history list, then release some objects. - while ((in_use_object_bytes > - std::min(kL3CacheSizeBytes, store_capacity / 100) || - release_history.size() > config.release_delay) && + while ((in_use_object_bytes > std::min(kL3CacheSizeBytes, store_capacity / 100) || + release_history.size() > config.release_delay) && release_history.size() > 0) { // Perform a release for the object ID for the first pending release. RETURN_NOT_OK(PerformRelease(release_history.back())); @@ -363,7 +342,7 @@ Status PlasmaClient::Release(ObjectID object_id) { } // This method is used to query whether the plasma store contains an object. -Status PlasmaClient::Contains(ObjectID object_id, int *has_object) { +Status PlasmaClient::Contains(ObjectID object_id, int* has_object) { // Check if we already have a reference to the object. if (objects_in_use.count(object_id) > 0) { *has_object = 1; @@ -372,26 +351,23 @@ Status PlasmaClient::Contains(ObjectID object_id, int *has_object) { // to see if we have the object. RETURN_NOT_OK(SendContainsRequest(store_conn, object_id)); std::vector buffer; - RETURN_NOT_OK( - PlasmaReceive(store_conn, MessageType_PlasmaContainsReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(store_conn, MessageType_PlasmaContainsReply, buffer)); ObjectID object_id2; RETURN_NOT_OK(ReadContainsReply(buffer.data(), &object_id2, has_object)); } return Status::OK(); } -static void compute_block_hash(const unsigned char *data, - int64_t nbytes, - uint64_t *hash) { +static void compute_block_hash( + const unsigned char* data, int64_t nbytes, uint64_t* hash) { XXH64_state_t hash_state; XXH64_reset(&hash_state, XXH64_DEFAULT_SEED); XXH64_update(&hash_state, data, nbytes); *hash = XXH64_digest(&hash_state); } -static inline bool compute_object_hash_parallel(XXH64_state_t *hash_state, - const unsigned char *data, - int64_t nbytes) { +static inline bool compute_object_hash_parallel( + XXH64_state_t* hash_state, const unsigned char* data, int64_t nbytes) { // Note that this function will likely be faster if the address of data is // aligned on a 64-byte boundary. const int num_threads = kThreadPoolSize; @@ -406,43 +382,38 @@ static inline bool compute_object_hash_parallel(XXH64_state_t *hash_state, // Each thread gets a "chunk" of k blocks, except the suffix thread. for (int i = 0; i < num_threads; i++) { - threadpool_[i] = - std::thread(compute_block_hash, - reinterpret_cast(data_address) + i * chunk_size, - chunk_size, &threadhash[i]); + threadpool_[i] = std::thread(compute_block_hash, + reinterpret_cast(data_address) + i * chunk_size, chunk_size, + &threadhash[i]); } - compute_block_hash(reinterpret_cast(right_address), suffix, - &threadhash[num_threads]); + compute_block_hash( + reinterpret_cast(right_address), suffix, &threadhash[num_threads]); // Join the threads. - for (auto &t : threadpool_) { - if (t.joinable()) { - t.join(); - } + for (auto& t : threadpool_) { + if (t.joinable()) { t.join(); } } - XXH64_update(hash_state, (unsigned char *) threadhash, sizeof(threadhash)); + XXH64_update(hash_state, (unsigned char*)threadhash, sizeof(threadhash)); return true; } -static uint64_t compute_object_hash(const ObjectBuffer &obj_buffer) { +static uint64_t compute_object_hash(const ObjectBuffer& obj_buffer) { XXH64_state_t hash_state; XXH64_reset(&hash_state, XXH64_DEFAULT_SEED); if (obj_buffer.data_size >= kBytesInMB) { - compute_object_hash_parallel(&hash_state, (unsigned char *) obj_buffer.data, - obj_buffer.data_size); + compute_object_hash_parallel( + &hash_state, (unsigned char*)obj_buffer.data, obj_buffer.data_size); } else { - XXH64_update(&hash_state, (unsigned char *) obj_buffer.data, - obj_buffer.data_size); + XXH64_update(&hash_state, (unsigned char*)obj_buffer.data, obj_buffer.data_size); } - XXH64_update(&hash_state, (unsigned char *) obj_buffer.metadata, - obj_buffer.metadata_size); + XXH64_update( + &hash_state, (unsigned char*)obj_buffer.metadata, obj_buffer.metadata_size); return XXH64_digest(&hash_state); } -bool plasma_compute_object_hash(PlasmaClient *conn, - ObjectID obj_id, - unsigned char *digest) { +bool plasma_compute_object_hash( + PlasmaClient* conn, ObjectID obj_id, unsigned char* digest) { // Get the plasma object data. We pass in a timeout of 0 to indicate that // the operation should timeout immediately. ObjectBuffer obj_buffer; @@ -451,9 +422,7 @@ bool plasma_compute_object_hash(PlasmaClient *conn, ARROW_CHECK_OK(conn->Get(obj_id_array, 1, 0, &obj_buffer)); // If the object was not retrieved, return false. - if (obj_buffer.data_size == -1) { - return false; - } + if (obj_buffer.data_size == -1) { return false; } // Compute the hash. hash = compute_object_hash(obj_buffer); memcpy(digest, &hash, sizeof(hash)); @@ -489,7 +458,7 @@ Status PlasmaClient::Delete(ObjectID object_id) { return Status::NotImplemented("PlasmaClient::Delete is not implemented."); } -Status PlasmaClient::Evict(int64_t num_bytes, int64_t &num_bytes_evicted) { +Status PlasmaClient::Evict(int64_t num_bytes, int64_t& num_bytes_evicted) { // Send a request to the store to evict objects. RETURN_NOT_OK(SendEvictRequest(store_conn, num_bytes)); // Wait for a response with the number of bytes actually evicted. @@ -499,7 +468,7 @@ Status PlasmaClient::Evict(int64_t num_bytes, int64_t &num_bytes_evicted) { return ReadEvictReply(buffer.data(), num_bytes_evicted); } -Status PlasmaClient::Subscribe(int &fd) { +Status PlasmaClient::Subscribe(int& fd) { int sock[2]; // Create a non-blocking socket pair. This will only be used to send // notifications from the Plasma store to the client. @@ -519,9 +488,8 @@ Status PlasmaClient::Subscribe(int &fd) { return Status::OK(); } -Status PlasmaClient::Connect(const std::string &store_socket_name, - const std::string &manager_socket_name, - int release_delay) { +Status PlasmaClient::Connect(const std::string& store_socket_name, + const std::string& manager_socket_name, int release_delay) { store_conn = connect_ipc_sock_retry(store_socket_name, -1, -1); if (manager_socket_name != "") { manager_conn = connect_ipc_sock_retry(manager_socket_name, -1, -1); @@ -533,8 +501,7 @@ Status PlasmaClient::Connect(const std::string &store_socket_name, // Send a ConnectRequest to the store to get its memory capacity. RETURN_NOT_OK(SendConnectRequest(store_conn)); std::vector buffer; - RETURN_NOT_OK( - PlasmaReceive(store_conn, MessageType_PlasmaConnectReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(store_conn, MessageType_PlasmaConnectReply, buffer)); RETURN_NOT_OK(ReadConnectReply(buffer.data(), &store_capacity)); return Status::OK(); } @@ -544,30 +511,26 @@ Status PlasmaClient::Disconnect() { // use, so that we don't duplicate PlasmaClient::Release calls (when handling // a // SIGTERM, for example). - for (auto &entry : objects_in_use) { + for (auto& entry : objects_in_use) { delete entry.second; } - for (auto &entry : mmap_table) { + for (auto& entry : mmap_table) { delete entry.second; } // Close the connections to Plasma. The Plasma store will release the objects // that were in use by us when handling the SIGPIPE. close(store_conn); - if (manager_conn >= 0) { - close(manager_conn); - } + if (manager_conn >= 0) { close(manager_conn); } return Status::OK(); } -bool plasma_manager_is_connected(PlasmaClient *conn) { +bool plasma_manager_is_connected(PlasmaClient* conn) { return conn->manager_conn >= 0; } #define h_addr h_addr_list[0] -Status PlasmaClient::Transfer(const char *address, - int port, - ObjectID object_id) { +Status PlasmaClient::Transfer(const char* address, int port, ObjectID object_id) { return SendDataRequest(manager_conn, object_id, address, port); } @@ -576,25 +539,21 @@ Status PlasmaClient::Fetch(int num_object_ids, ObjectID object_ids[]) { return SendFetchRequest(manager_conn, object_ids, num_object_ids); } -int get_manager_fd(PlasmaClient *conn) { +int get_manager_fd(PlasmaClient* conn) { return conn->manager_conn; } -Status PlasmaClient::Info(ObjectID object_id, int *object_status) { +Status PlasmaClient::Info(ObjectID object_id, int* object_status) { ARROW_CHECK(manager_conn >= 0); RETURN_NOT_OK(SendStatusRequest(manager_conn, &object_id, 1)); std::vector buffer; - RETURN_NOT_OK( - PlasmaReceive(manager_conn, MessageType_PlasmaStatusReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(manager_conn, MessageType_PlasmaStatusReply, buffer)); return ReadStatusReply(buffer.data(), &object_id, object_status, 1); } -Status PlasmaClient::Wait(int64_t num_object_requests, - ObjectRequest object_requests[], - int num_ready_objects, - int64_t timeout_ms, - int &num_objects_ready) { +Status PlasmaClient::Wait(int64_t num_object_requests, ObjectRequest object_requests[], + int num_ready_objects, int64_t timeout_ms, int& num_objects_ready) { ARROW_CHECK(manager_conn >= 0); ARROW_CHECK(num_object_requests > 0); ARROW_CHECK(num_ready_objects > 0); @@ -605,34 +564,29 @@ Status PlasmaClient::Wait(int64_t num_object_requests, object_requests[i].type == PLASMA_QUERY_ANYWHERE); } - RETURN_NOT_OK(SendWaitRequest(manager_conn, object_requests, - num_object_requests, num_ready_objects, - timeout_ms)); + RETURN_NOT_OK(SendWaitRequest( + manager_conn, object_requests, num_object_requests, num_ready_objects, timeout_ms)); std::vector buffer; - RETURN_NOT_OK( - PlasmaReceive(manager_conn, MessageType_PlasmaWaitReply, buffer)); - RETURN_NOT_OK( - ReadWaitReply(buffer.data(), object_requests, &num_ready_objects)); + RETURN_NOT_OK(PlasmaReceive(manager_conn, MessageType_PlasmaWaitReply, buffer)); + RETURN_NOT_OK(ReadWaitReply(buffer.data(), object_requests, &num_ready_objects)); num_objects_ready = 0; for (int i = 0; i < num_object_requests; ++i) { int type = object_requests[i].type; int status = object_requests[i].status; switch (type) { - case PLASMA_QUERY_LOCAL: - if (status == ObjectStatus_Local) { - num_objects_ready += 1; - } - break; - case PLASMA_QUERY_ANYWHERE: - if (status == ObjectStatus_Local || status == ObjectStatus_Remote) { - num_objects_ready += 1; - } else { - ARROW_CHECK(status == ObjectStatus_Nonexistent); - } - break; - default: - ARROW_LOG(FATAL) << "This code should be unreachable."; + case PLASMA_QUERY_LOCAL: + if (status == ObjectStatus_Local) { num_objects_ready += 1; } + break; + case PLASMA_QUERY_ANYWHERE: + if (status == ObjectStatus_Local || status == ObjectStatus_Remote) { + num_objects_ready += 1; + } else { + ARROW_CHECK(status == ObjectStatus_Nonexistent); + } + break; + default: + ARROW_LOG(FATAL) << "This code should be unreachable."; } } return Status::OK(); diff --git a/cpp/src/plasma/client.h b/cpp/src/plasma/client.h index 6e4794210cd..67cb62fc194 100644 --- a/cpp/src/plasma/client.h +++ b/cpp/src/plasma/client.h @@ -38,11 +38,11 @@ struct ObjectBuffer { /// The size in bytes of the data object. int64_t data_size; /// The address of the data object. - uint8_t *data; + uint8_t* data; /// The metadata size in bytes. int64_t metadata_size; /// The address of the metadata. - uint8_t *metadata; + uint8_t* metadata; }; /// Configuration options for the plasma client. @@ -69,9 +69,8 @@ class PlasmaClient { /// @param release_delay Number of released objects that are kept around /// and not evicted to avoid too many munmaps. /// @return The return status. - Status Connect(const std::string &store_socket_name, - const std::string &manager_socket_name, - int release_delay); + Status Connect(const std::string& store_socket_name, + const std::string& manager_socket_name, int release_delay); /// Create an object in the Plasma Store. Any metadata for this object must be /// be passed in when the object is created. @@ -87,11 +86,8 @@ class PlasmaClient { /// metadata, this should be 0. /// @param data The address of the newly created object will be written here. /// @return The return status. - Status Create(ObjectID object_id, - int64_t data_size, - uint8_t *metadata, - int64_t metadata_size, - uint8_t **data); + Status Create(ObjectID object_id, int64_t data_size, uint8_t* metadata, + int64_t metadata_size, uint8_t** data); /// Get some objects from the Plasma Store. This function will block until the /// objects have all been created and sealed in the Plasma Store or the @@ -108,10 +104,8 @@ class PlasmaClient { /// data /// size field is -1, then the object was not retrieved. /// @return The return status. - Status Get(ObjectID object_ids[], - int64_t num_objects, - int64_t timeout_ms, - ObjectBuffer object_buffers[]); + Status Get(ObjectID object_ids[], int64_t num_objects, int64_t timeout_ms, + ObjectBuffer object_buffers[]); /// Tell Plasma that the client no longer needs the object. This should be /// called @@ -134,7 +128,7 @@ class PlasmaClient { /// is /// present and 0 if it is not present. /// @return The return status. - Status Contains(ObjectID object_id, int *has_object); + Status Contains(ObjectID object_id, int* has_object); /// Seal an object in the object store. The object will be immutable after /// this @@ -161,7 +155,7 @@ class PlasmaClient { /// @param num_bytes_evicted Out parameter for total number of bytes of space /// retrieved. /// @return The return status. - Status Evict(int64_t num_bytes, int64_t &num_bytes_evicted); + Status Evict(int64_t num_bytes, int64_t& num_bytes_evicted); /// Subscribe to notifications when objects are sealed in the object store. /// Whenever an object is sealed, a message will be written to the client @@ -172,7 +166,7 @@ class PlasmaClient { /// read notifications /// from the object store about sealed objects. /// @return The return status. - Status Subscribe(int &fd); + Status Subscribe(int& fd); /// Disconnect from the local plasma instance, including the local store and /// manager. @@ -238,11 +232,8 @@ class PlasmaClient { /// the object_requests list. If the returned number is less than /// min_num_ready_objects this means that timeout expired. /// @return The return status. - Status Wait(int64_t num_object_requests, - ObjectRequest object_requests[], - int num_ready_objects, - int64_t timeout_ms, - int &num_objects_ready); + Status Wait(int64_t num_object_requests, ObjectRequest object_requests[], + int num_ready_objects, int64_t timeout_ms, int& num_objects_ready); /// Transfer local object to a different plasma manager. /// @@ -251,7 +242,7 @@ class PlasmaClient { /// @param port Port of the plasma manager we are transfering to. /// @object_id ObjectID of the object we are transfering. /// @return The return status. - Status Transfer(const char *addr, int port, ObjectID object_id); + Status Transfer(const char* addr, int port, ObjectID object_id); /// Return the status of a given object. This method may query the object /// table. @@ -270,7 +261,7 @@ class PlasmaClient { /// - PLASMA_CLIENT_DOES_NOT_EXIST, if the object doesn’t exist in the /// system. /// @return The return status. - Status Info(ObjectID object_id, int *object_status); + Status Info(ObjectID object_id, int* object_status); // private: @@ -287,11 +278,10 @@ class PlasmaClient { /// Table of dlmalloc buffer files that have been memory mapped so far. This /// is a hash table mapping a file descriptor to a struct containing the /// address of the corresponding memory-mapped file. - std::unordered_map mmap_table; + std::unordered_map mmap_table; /// A hash table of the object IDs that are currently being used by this /// client. - std::unordered_map - objects_in_use; + std::unordered_map objects_in_use; /// Object IDs of the last few release calls. This is a deque and /// is used to delay releasing objects to see if they can be reused by /// subsequent tasks so we do not unneccessarily invalidate cpu caches. @@ -314,7 +304,7 @@ class PlasmaClient { /// /// @param conn The connection to the local plasma store and plasma manager. /// @return True if the plasma manager is connected and false otherwise. -bool plasma_manager_is_connected(PlasmaClient *conn); +bool plasma_manager_is_connected(PlasmaClient* conn); /// Compute the hash of an object in the object store. /// @@ -323,9 +313,8 @@ bool plasma_manager_is_connected(PlasmaClient *conn); /// @param digest A pointer at which to return the hash digest of the object. /// The pointer must have at least DIGEST_SIZE bytes allocated. /// @return A boolean representing whether the hash operation succeeded. -bool plasma_compute_object_hash(PlasmaClient *conn, - ObjectID object_id, - unsigned char *digest); +bool plasma_compute_object_hash( + PlasmaClient* conn, ObjectID object_id, unsigned char* digest); /** * Get the file descriptor for the socket connection to the plasma manager. @@ -334,7 +323,7 @@ bool plasma_compute_object_hash(PlasmaClient *conn, * @return The file descriptor for the manager connection. If there is no * connection to the manager, this is -1. */ -int get_manager_fd(PlasmaClient *conn); +int get_manager_fd(PlasmaClient* conn); /** * Return the information associated to a given object. diff --git a/cpp/src/plasma/common.cc b/cpp/src/plasma/common.cc index 62a7e637167..a09a963fa47 100644 --- a/cpp/src/plasma/common.cc +++ b/cpp/src/plasma/common.cc @@ -25,7 +25,7 @@ using arrow::Status; UniqueID UniqueID::from_random() { UniqueID id; - uint8_t *data = id.mutable_data(); + uint8_t* data = id.mutable_data(); std::random_device engine; for (int i = 0; i < kUniqueIDSize; i++) { data[i] = static_cast(engine()); @@ -33,22 +33,22 @@ UniqueID UniqueID::from_random() { return id; } -UniqueID UniqueID::from_binary(const std::string &binary) { +UniqueID UniqueID::from_binary(const std::string& binary) { UniqueID id; std::memcpy(&id, binary.data(), sizeof(id)); return id; } -const uint8_t *UniqueID::data() const { +const uint8_t* UniqueID::data() const { return id_; } -uint8_t *UniqueID::mutable_data() { +uint8_t* UniqueID::mutable_data() { return id_; } std::string UniqueID::binary() const { - return std::string(reinterpret_cast(id_), kUniqueIDSize); + return std::string(reinterpret_cast(id_), kUniqueIDSize); } std::string UniqueID::hex() const { @@ -62,24 +62,22 @@ std::string UniqueID::hex() const { return result; } -bool UniqueID::operator==(const UniqueID &rhs) const { +bool UniqueID::operator==(const UniqueID& rhs) const { return std::memcmp(data(), rhs.data(), kUniqueIDSize) == 0; } Status plasma_error_status(int plasma_error) { switch (plasma_error) { - case PlasmaError_OK: - return Status::OK(); - case PlasmaError_ObjectExists: - return Status::PlasmaObjectExists( - "object already exists in the plasma store"); - case PlasmaError_ObjectNonexistent: - return Status::PlasmaObjectNonexistent( - "object does not exist in the plasma store"); - case PlasmaError_OutOfMemory: - return Status::PlasmaStoreFull("object does not fit in the plasma store"); - default: - ARROW_LOG(FATAL) << "unknown plasma error code " << plasma_error; + case PlasmaError_OK: + return Status::OK(); + case PlasmaError_ObjectExists: + return Status::PlasmaObjectExists("object already exists in the plasma store"); + case PlasmaError_ObjectNonexistent: + return Status::PlasmaObjectNonexistent("object does not exist in the plasma store"); + case PlasmaError_OutOfMemory: + return Status::PlasmaStoreFull("object does not fit in the plasma store"); + default: + ARROW_LOG(FATAL) << "unknown plasma error code " << plasma_error; } return Status::OK(); } diff --git a/cpp/src/plasma/common.h b/cpp/src/plasma/common.h index e7088f52485..61ed49359e7 100644 --- a/cpp/src/plasma/common.h +++ b/cpp/src/plasma/common.h @@ -26,18 +26,18 @@ #define __STDC_FORMAT_MACROS #endif -#include "arrow/util/logging.h" #include "arrow/status.h" +#include "arrow/util/logging.h" constexpr int64_t kUniqueIDSize = 20; class UniqueID { public: static UniqueID from_random(); - static UniqueID from_binary(const std::string &binary); - bool operator==(const UniqueID &rhs) const; - const uint8_t *data() const; - uint8_t *mutable_data(); + static UniqueID from_binary(const std::string& binary); + bool operator==(const UniqueID& rhs) const; + const uint8_t* data() const; + uint8_t* mutable_data(); std::string binary() const; std::string hex() const; @@ -49,7 +49,7 @@ static_assert(std::is_pod::value, "UniqueID must be plain old data"); struct UniqueIDHasher { /* ObjectID hashing function. */ - size_t operator()(const UniqueID &id) const { + size_t operator()(const UniqueID& id) const { size_t result; std::memcpy(&result, id.data(), sizeof(size_t)); return result; diff --git a/cpp/src/plasma/events.cc b/cpp/src/plasma/events.cc index 0b33f2a5cf0..264716ea456 100644 --- a/cpp/src/plasma/events.cc +++ b/cpp/src/plasma/events.cc @@ -19,18 +19,14 @@ #include -void EventLoop::file_event_callback(aeEventLoop *loop, - int fd, - void *context, - int events) { - FileCallback *callback = reinterpret_cast(context); +void EventLoop::file_event_callback( + aeEventLoop* loop, int fd, void* context, int events) { + FileCallback* callback = reinterpret_cast(context); (*callback)(events); } -int EventLoop::timer_event_callback(aeEventLoop *loop, - TimerID timer_id, - void *context) { - TimerCallback *callback = reinterpret_cast(context); +int EventLoop::timer_event_callback(aeEventLoop* loop, TimerID timer_id, void* context) { + TimerCallback* callback = reinterpret_cast(context); return (*callback)(timer_id); } @@ -41,22 +37,16 @@ EventLoop::EventLoop() { } bool EventLoop::add_file_event(int fd, int events, FileCallback callback) { - if (file_callbacks_.find(fd) != file_callbacks_.end()) { - return false; - } + if (file_callbacks_.find(fd) != file_callbacks_.end()) { return false; } auto data = std::unique_ptr(new FileCallback(callback)); - void *context = reinterpret_cast(data.get()); + void* context = reinterpret_cast(data.get()); // Try to add the file descriptor. - int err = aeCreateFileEvent(loop_, fd, events, EventLoop::file_event_callback, - context); + int err = aeCreateFileEvent(loop_, fd, events, EventLoop::file_event_callback, context); // If it cannot be added, increase the size of the event loop. if (err == AE_ERR && errno == ERANGE) { err = aeResizeSetSize(loop_, 3 * aeGetSetSize(loop_) / 2); - if (err != AE_OK) { - return false; - } - err = aeCreateFileEvent(loop_, fd, events, EventLoop::file_event_callback, - context); + if (err != AE_OK) { return false; } + err = aeCreateFileEvent(loop_, fd, events, EventLoop::file_event_callback, context); } // In any case, test if there were errors. if (err == AE_OK) { @@ -77,9 +67,9 @@ void EventLoop::run() { int64_t EventLoop::add_timer(int64_t timeout, TimerCallback callback) { auto data = std::unique_ptr(new TimerCallback(callback)); - void *context = reinterpret_cast(data.get()); - int64_t timer_id = aeCreateTimeEvent( - loop_, timeout, EventLoop::timer_event_callback, context, NULL); + void* context = reinterpret_cast(data.get()); + int64_t timer_id = + aeCreateTimeEvent(loop_, timeout, EventLoop::timer_event_callback, context, NULL); timer_callbacks_.emplace(timer_id, std::move(data)); return timer_id; } diff --git a/cpp/src/plasma/events.h b/cpp/src/plasma/events.h index 6baeed89b8d..df5c84ebd5e 100644 --- a/cpp/src/plasma/events.h +++ b/cpp/src/plasma/events.h @@ -35,7 +35,7 @@ constexpr int kEventLoopRead = AE_READABLE; /// Write event on the file descriptor. constexpr int kEventLoopWrite = AE_WRITABLE; -typedef long long TimerID; // NOLINT +typedef long long TimerID; // NOLINT class EventLoop { public: @@ -87,16 +87,11 @@ class EventLoop { void run(); private: - static void file_event_callback(aeEventLoop *loop, - int fd, - void *context, - int events); + static void file_event_callback(aeEventLoop* loop, int fd, void* context, int events); - static int timer_event_callback(aeEventLoop *loop, - TimerID timer_id, - void *context); + static int timer_event_callback(aeEventLoop* loop, TimerID timer_id, void* context); - aeEventLoop *loop_; + aeEventLoop* loop_; std::unordered_map> file_callbacks_; std::unordered_map> timer_callbacks_; }; diff --git a/cpp/src/plasma/eviction_policy.cc b/cpp/src/plasma/eviction_policy.cc index 453565665c6..5f184faa29e 100644 --- a/cpp/src/plasma/eviction_policy.cc +++ b/cpp/src/plasma/eviction_policy.cc @@ -19,7 +19,7 @@ #include -void LRUCache::add(const ObjectID &key, int64_t size) { +void LRUCache::add(const ObjectID& key, int64_t size) { auto it = item_map_.find(key); ARROW_CHECK(it == item_map_.end()); /* Note that it is important to use a list so the iterators stay valid. */ @@ -27,7 +27,7 @@ void LRUCache::add(const ObjectID &key, int64_t size) { item_map_.emplace(key, item_list_.begin()); } -void LRUCache::remove(const ObjectID &key) { +void LRUCache::remove(const ObjectID& key) { auto it = item_map_.find(key); ARROW_CHECK(it != item_map_.end()); item_list_.erase(it->second); @@ -35,8 +35,7 @@ void LRUCache::remove(const ObjectID &key) { } int64_t LRUCache::choose_objects_to_evict( - int64_t num_bytes_required, - std::vector &objects_to_evict) { + int64_t num_bytes_required, std::vector& objects_to_evict) { int64_t bytes_evicted = 0; auto it = item_list_.end(); while (bytes_evicted < num_bytes_required && it != item_list_.begin()) { @@ -47,16 +46,15 @@ int64_t LRUCache::choose_objects_to_evict( return bytes_evicted; } -EvictionPolicy::EvictionPolicy(PlasmaStoreInfo *store_info) +EvictionPolicy::EvictionPolicy(PlasmaStoreInfo* store_info) : memory_used_(0), store_info_(store_info) {} int64_t EvictionPolicy::choose_objects_to_evict( - int64_t num_bytes_required, - std::vector &objects_to_evict) { + int64_t num_bytes_required, std::vector& objects_to_evict) { int64_t bytes_evicted = cache_.choose_objects_to_evict(num_bytes_required, objects_to_evict); /* Update the LRU cache. */ - for (auto &object_id : objects_to_evict) { + for (auto& object_id : objects_to_evict) { cache_.remove(object_id); } /* Update the number of bytes used. */ @@ -69,8 +67,8 @@ void EvictionPolicy::object_created(ObjectID object_id) { cache_.add(object_id, entry->info.data_size + entry->info.metadata_size); } -bool EvictionPolicy::require_space(int64_t size, - std::vector &objects_to_evict) { +bool EvictionPolicy::require_space( + int64_t size, std::vector& objects_to_evict) { /* Check if there is enough space to create the object. */ int64_t required_space = memory_used_ + size - store_info_->memory_capacity; int64_t num_bytes_evicted; @@ -78,15 +76,12 @@ bool EvictionPolicy::require_space(int64_t size, /* Try to free up at least as much space as we need right now but ideally * up to 20% of the total capacity. */ int64_t space_to_free = std::max(size, store_info_->memory_capacity / 5); - ARROW_LOG(DEBUG) - << "not enough space to create this object, so evicting objects"; + ARROW_LOG(DEBUG) << "not enough space to create this object, so evicting objects"; /* Choose some objects to evict, and update the return pointers. */ - num_bytes_evicted = - choose_objects_to_evict(space_to_free, objects_to_evict); - ARROW_LOG(INFO) - << "There is not enough space to create this object, so evicting " - << objects_to_evict.size() << " objects to free up " - << num_bytes_evicted << " bytes."; + num_bytes_evicted = choose_objects_to_evict(space_to_free, objects_to_evict); + ARROW_LOG(INFO) << "There is not enough space to create this object, so evicting " + << objects_to_evict.size() << " objects to free up " + << num_bytes_evicted << " bytes."; } else { num_bytes_evicted = 0; } @@ -99,15 +94,13 @@ bool EvictionPolicy::require_space(int64_t size, } void EvictionPolicy::begin_object_access( - ObjectID object_id, - std::vector &objects_to_evict) { + ObjectID object_id, std::vector& objects_to_evict) { /* If the object is in the LRU cache, remove it. */ cache_.remove(object_id); } void EvictionPolicy::end_object_access( - ObjectID object_id, - std::vector &objects_to_evict) { + ObjectID object_id, std::vector& objects_to_evict) { auto entry = store_info_->objects[object_id].get(); /* Add the object to the LRU cache.*/ cache_.add(object_id, entry->info.data_size + entry->info.metadata_size); diff --git a/cpp/src/plasma/eviction_policy.h b/cpp/src/plasma/eviction_policy.h index 896c3ea21ae..51561a684e0 100644 --- a/cpp/src/plasma/eviction_policy.h +++ b/cpp/src/plasma/eviction_policy.h @@ -46,12 +46,12 @@ class LRUCache { public: LRUCache() {} - void add(const ObjectID &key, int64_t size); + void add(const ObjectID& key, int64_t size); - void remove(const ObjectID &key); + void remove(const ObjectID& key); - int64_t choose_objects_to_evict(int64_t num_bytes_required, - std::vector &objects_to_evict); + int64_t choose_objects_to_evict( + int64_t num_bytes_required, std::vector& objects_to_evict); }; /** The eviction policy. */ @@ -63,7 +63,7 @@ class EvictionPolicy { * @param store_info Information about the Plasma store that is exposed * to the eviction policy. */ - explicit EvictionPolicy(PlasmaStoreInfo *store_info); + explicit EvictionPolicy(PlasmaStoreInfo* store_info); /** * This method will be called whenever an object is first created in order to @@ -89,7 +89,7 @@ class EvictionPolicy { * be stored into this vector. * @return True if enough space can be freed and false otherwise. */ - bool require_space(int64_t size, std::vector &objects_to_evict); + bool require_space(int64_t size, std::vector& objects_to_evict); /** * This method will be called whenever an unused object in the Plasma store @@ -102,8 +102,7 @@ class EvictionPolicy { * be stored into this vector. * @return Void. */ - void begin_object_access(ObjectID object_id, - std::vector &objects_to_evict); + void begin_object_access(ObjectID object_id, std::vector& objects_to_evict); /** * This method will be called whenever an object in the Plasma store that was @@ -116,8 +115,7 @@ class EvictionPolicy { * be stored into this vector. * @return Void. */ - void end_object_access(ObjectID object_id, - std::vector &objects_to_evict); + void end_object_access(ObjectID object_id, std::vector& objects_to_evict); /** * Choose some objects to evict from the Plasma store. When this method is @@ -132,14 +130,14 @@ class EvictionPolicy { * be stored into this vector. * @return The total number of bytes of space chosen to be evicted. */ - int64_t choose_objects_to_evict(int64_t num_bytes_required, - std::vector &objects_to_evict); + int64_t choose_objects_to_evict( + int64_t num_bytes_required, std::vector& objects_to_evict); private: /** The amount of memory (in bytes) currently being used. */ int64_t memory_used_; /** Pointer to the plasma store info. */ - PlasmaStoreInfo *store_info_; + PlasmaStoreInfo* store_info_; /** Datastructure for the LRU cache. */ LRUCache cache_; }; diff --git a/cpp/src/plasma/extension.cc b/cpp/src/plasma/extension.cc index 528c157847f..11f3cd6f75a 100644 --- a/cpp/src/plasma/extension.cc +++ b/cpp/src/plasma/extension.cc @@ -15,165 +15,161 @@ // specific language governing permissions and limitations // under the License. -#include "plasma/io.h" +#include "plasma/extension.h" +#include "plasma/client.h" #include "plasma/common.h" +#include "plasma/io.h" #include "plasma/protocol.h" -#include "plasma/client.h" -#include "plasma/extension.h" #include #include -PyObject *PlasmaOutOfMemoryError; -PyObject *PlasmaObjectExistsError; +PyObject* PlasmaOutOfMemoryError; +PyObject* PlasmaObjectExistsError; -PyObject *PyPlasma_connect(PyObject *self, PyObject *args) { - const char *store_socket_name; - const char *manager_socket_name; +PyObject* PyPlasma_connect(PyObject* self, PyObject* args) { + const char* store_socket_name; + const char* manager_socket_name; int release_delay; - if (!PyArg_ParseTuple(args, "ssi", &store_socket_name, &manager_socket_name, - &release_delay)) { + if (!PyArg_ParseTuple( + args, "ssi", &store_socket_name, &manager_socket_name, &release_delay)) { return NULL; } - PlasmaClient *client = new PlasmaClient(); - ARROW_CHECK_OK( - client->Connect(store_socket_name, manager_socket_name, release_delay)); + PlasmaClient* client = new PlasmaClient(); + ARROW_CHECK_OK(client->Connect(store_socket_name, manager_socket_name, release_delay)); return PyCapsule_New(client, "plasma", NULL); } -PyObject *PyPlasma_disconnect(PyObject *self, PyObject *args) { - PyObject *client_capsule; - if (!PyArg_ParseTuple(args, "O", &client_capsule)) { - return NULL; - } - PlasmaClient *client; +PyObject* PyPlasma_disconnect(PyObject* self, PyObject* args) { + PyObject* client_capsule; + if (!PyArg_ParseTuple(args, "O", &client_capsule)) { return NULL; } + PlasmaClient* client; ARROW_CHECK(PyObjectToPlasmaClient(client_capsule, &client)); ARROW_CHECK_OK(client->Disconnect()); /* We use the context of the connection capsule to indicate if the connection * is still active (if the context is NULL) or if it is closed (if the context * is (void*) 0x1). This is neccessary because the primary pointer of the * capsule cannot be NULL. */ - PyCapsule_SetContext(client_capsule, reinterpret_cast(0x1)); + PyCapsule_SetContext(client_capsule, reinterpret_cast(0x1)); Py_RETURN_NONE; } -PyObject *PyPlasma_create(PyObject *self, PyObject *args) { - PlasmaClient *client; +PyObject* PyPlasma_create(PyObject* self, PyObject* args) { + PlasmaClient* client; ObjectID object_id; Py_ssize_t size; - PyObject *metadata; + PyObject* metadata; if (!PyArg_ParseTuple(args, "O&O&nO", PyObjectToPlasmaClient, &client, - PyStringToUniqueID, &object_id, &size, &metadata)) { + PyStringToUniqueID, &object_id, &size, &metadata)) { return NULL; } if (!PyByteArray_Check(metadata)) { PyErr_SetString(PyExc_TypeError, "metadata must be a bytearray"); return NULL; } - uint8_t *data; + uint8_t* data; Status s = client->Create(object_id, size, - reinterpret_cast(PyByteArray_AsString(metadata)), - PyByteArray_Size(metadata), &data); + reinterpret_cast(PyByteArray_AsString(metadata)), + PyByteArray_Size(metadata), &data); if (s.IsPlasmaObjectExists()) { PyErr_SetString(PlasmaObjectExistsError, - "An object with this ID already exists in the plasma " - "store."); + "An object with this ID already exists in the plasma " + "store."); return NULL; } if (s.IsPlasmaStoreFull()) { PyErr_SetString(PlasmaOutOfMemoryError, - "The plasma store ran out of memory and could not create " - "this object."); + "The plasma store ran out of memory and could not create " + "this object."); return NULL; } ARROW_CHECK(s.ok()); #if PY_MAJOR_VERSION >= 3 - return PyMemoryView_FromMemory(reinterpret_cast(data), size, PyBUF_WRITE); + return PyMemoryView_FromMemory(reinterpret_cast(data), size, PyBUF_WRITE); #else - return PyBuffer_FromReadWriteMemory(reinterpret_cast(data), size); + return PyBuffer_FromReadWriteMemory(reinterpret_cast(data), size); #endif } -PyObject *PyPlasma_hash(PyObject *self, PyObject *args) { - PlasmaClient *client; +PyObject* PyPlasma_hash(PyObject* self, PyObject* args) { + PlasmaClient* client; ObjectID object_id; - if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, - PyStringToUniqueID, &object_id)) { + if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, PyStringToUniqueID, + &object_id)) { return NULL; } unsigned char digest[kDigestSize]; bool success = plasma_compute_object_hash(client, object_id, digest); if (success) { - PyObject *digest_string = - PyBytes_FromStringAndSize(reinterpret_cast(digest), kDigestSize); + PyObject* digest_string = + PyBytes_FromStringAndSize(reinterpret_cast(digest), kDigestSize); return digest_string; } else { Py_RETURN_NONE; } } -PyObject *PyPlasma_seal(PyObject *self, PyObject *args) { - PlasmaClient *client; +PyObject* PyPlasma_seal(PyObject* self, PyObject* args) { + PlasmaClient* client; ObjectID object_id; - if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, - PyStringToUniqueID, &object_id)) { + if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, PyStringToUniqueID, + &object_id)) { return NULL; } ARROW_CHECK_OK(client->Seal(object_id)); Py_RETURN_NONE; } -PyObject *PyPlasma_release(PyObject *self, PyObject *args) { - PlasmaClient *client; +PyObject* PyPlasma_release(PyObject* self, PyObject* args) { + PlasmaClient* client; ObjectID object_id; - if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, - PyStringToUniqueID, &object_id)) { + if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, PyStringToUniqueID, + &object_id)) { return NULL; } ARROW_CHECK_OK(client->Release(object_id)); Py_RETURN_NONE; } -PyObject *PyPlasma_get(PyObject *self, PyObject *args) { - PlasmaClient *client; - PyObject *object_id_list; +PyObject* PyPlasma_get(PyObject* self, PyObject* args) { + PlasmaClient* client; + PyObject* object_id_list; Py_ssize_t timeout_ms; - if (!PyArg_ParseTuple(args, "O&On", PyObjectToPlasmaClient, &client, - &object_id_list, &timeout_ms)) { + if (!PyArg_ParseTuple( + args, "O&On", PyObjectToPlasmaClient, &client, &object_id_list, &timeout_ms)) { return NULL; } Py_ssize_t num_object_ids = PyList_Size(object_id_list); - ObjectID *object_ids = new ObjectID[num_object_ids]; - ObjectBuffer *object_buffers = new ObjectBuffer[num_object_ids]; + ObjectID* object_ids = new ObjectID[num_object_ids]; + ObjectBuffer* object_buffers = new ObjectBuffer[num_object_ids]; for (int i = 0; i < num_object_ids; ++i) { PyStringToUniqueID(PyList_GetItem(object_id_list, i), &object_ids[i]); } Py_BEGIN_ALLOW_THREADS; - ARROW_CHECK_OK( - client->Get(object_ids, num_object_ids, timeout_ms, object_buffers)); + ARROW_CHECK_OK(client->Get(object_ids, num_object_ids, timeout_ms, object_buffers)); Py_END_ALLOW_THREADS; delete[] object_ids; - PyObject *returns = PyList_New(num_object_ids); + PyObject* returns = PyList_New(num_object_ids); for (int i = 0; i < num_object_ids; ++i) { if (object_buffers[i].data_size != -1) { /* The object was retrieved, so return the object. */ - PyObject *t = PyTuple_New(2); + PyObject* t = PyTuple_New(2); Py_ssize_t data_size = static_cast(object_buffers[i].data_size); Py_ssize_t metadata_size = static_cast(object_buffers[i].metadata_size); #if PY_MAJOR_VERSION >= 3 - char *data = reinterpret_cast(object_buffers[i].data); - char *metadata = reinterpret_cast(object_buffers[i].metadata); + char* data = reinterpret_cast(object_buffers[i].data); + char* metadata = reinterpret_cast(object_buffers[i].metadata); PyTuple_SetItem(t, 0, PyMemoryView_FromMemory(data, data_size, PyBUF_READ)); PyTuple_SetItem(t, 1, PyMemoryView_FromMemory(metadata, metadata_size, PyBUF_READ)); #else - void *data = reinterpret_cast(object_buffers[i].data); - void *metadata = reinterpret_cast(object_buffers[i].metadata); + void* data = reinterpret_cast(object_buffers[i].data); + void* metadata = reinterpret_cast(object_buffers[i].metadata); PyTuple_SetItem(t, 0, PyBuffer_FromMemory(data, data_size)); PyTuple_SetItem(t, 1, PyBuffer_FromMemory(metadata, metadata_size)); #endif @@ -189,11 +185,11 @@ PyObject *PyPlasma_get(PyObject *self, PyObject *args) { return returns; } -PyObject *PyPlasma_contains(PyObject *self, PyObject *args) { - PlasmaClient *client; +PyObject* PyPlasma_contains(PyObject* self, PyObject* args) { + PlasmaClient* client; ObjectID object_id; - if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, - PyStringToUniqueID, &object_id)) { + if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, PyStringToUniqueID, + &object_id)) { return NULL; } int has_object; @@ -205,11 +201,10 @@ PyObject *PyPlasma_contains(PyObject *self, PyObject *args) { Py_RETURN_FALSE; } -PyObject *PyPlasma_fetch(PyObject *self, PyObject *args) { - PlasmaClient *client; - PyObject *object_id_list; - if (!PyArg_ParseTuple(args, "O&O", PyObjectToPlasmaClient, &client, - &object_id_list)) { +PyObject* PyPlasma_fetch(PyObject* self, PyObject* args) { + PlasmaClient* client; + PyObject* object_id_list; + if (!PyArg_ParseTuple(args, "O&O", PyObjectToPlasmaClient, &client, &object_id_list)) { return NULL; } if (!plasma_manager_is_connected(client)) { @@ -217,7 +212,7 @@ PyObject *PyPlasma_fetch(PyObject *self, PyObject *args) { return NULL; } Py_ssize_t n = PyList_Size(object_id_list); - ObjectID *object_ids = new ObjectID[n]; + ObjectID* object_ids = new ObjectID[n]; for (int i = 0; i < n; ++i) { PyStringToUniqueID(PyList_GetItem(object_id_list, i), &object_ids[i]); } @@ -226,13 +221,13 @@ PyObject *PyPlasma_fetch(PyObject *self, PyObject *args) { Py_RETURN_NONE; } -PyObject *PyPlasma_wait(PyObject *self, PyObject *args) { - PlasmaClient *client; - PyObject *object_id_list; +PyObject* PyPlasma_wait(PyObject* self, PyObject* args) { + PlasmaClient* client; + PyObject* object_id_list; Py_ssize_t timeout; int num_returns; - if (!PyArg_ParseTuple(args, "O&Oni", PyObjectToPlasmaClient, &client, - &object_id_list, &timeout, &num_returns)) { + if (!PyArg_ParseTuple(args, "O&Oni", PyObjectToPlasmaClient, &client, &object_id_list, + &timeout, &num_returns)) { return NULL; } Py_ssize_t n = PyList_Size(object_id_list); @@ -242,49 +237,46 @@ PyObject *PyPlasma_wait(PyObject *self, PyObject *args) { return NULL; } if (num_returns < 0) { - PyErr_SetString(PyExc_RuntimeError, - "The argument num_returns cannot be less than zero."); + PyErr_SetString( + PyExc_RuntimeError, "The argument num_returns cannot be less than zero."); return NULL; } if (num_returns > n) { - PyErr_SetString( - PyExc_RuntimeError, + PyErr_SetString(PyExc_RuntimeError, "The argument num_returns cannot be greater than len(object_ids)"); return NULL; } int64_t threshold = 1 << 30; if (timeout > threshold) { - PyErr_SetString(PyExc_RuntimeError, - "The argument timeout cannot be greater than 2 ** 30."); + PyErr_SetString( + PyExc_RuntimeError, "The argument timeout cannot be greater than 2 ** 30."); return NULL; } std::vector object_requests(n); for (int i = 0; i < n; ++i) { ARROW_CHECK(PyStringToUniqueID(PyList_GetItem(object_id_list, i), - &object_requests[i].object_id) == 1); + &object_requests[i].object_id) == 1); object_requests[i].type = PLASMA_QUERY_ANYWHERE; } /* Drop the global interpreter lock while we are waiting, so other threads can * run. */ int num_return_objects; Py_BEGIN_ALLOW_THREADS; - ARROW_CHECK_OK(client->Wait(n, object_requests.data(), num_returns, - timeout, num_return_objects)); + ARROW_CHECK_OK( + client->Wait(n, object_requests.data(), num_returns, timeout, num_return_objects)); Py_END_ALLOW_THREADS; int num_to_return = std::min(num_return_objects, num_returns); - PyObject *ready_ids = PyList_New(num_to_return); - PyObject *waiting_ids = PySet_New(object_id_list); + PyObject* ready_ids = PyList_New(num_to_return); + PyObject* waiting_ids = PySet_New(object_id_list); int num_returned = 0; for (int i = 0; i < n; ++i) { - if (num_returned == num_to_return) { - break; - } + if (num_returned == num_to_return) { break; } if (object_requests[i].status == ObjectStatus_Local || object_requests[i].status == ObjectStatus_Remote) { - PyObject *ready = PyBytes_FromStringAndSize( - reinterpret_cast(&object_requests[i].object_id), + PyObject* ready = PyBytes_FromStringAndSize( + reinterpret_cast(&object_requests[i].object_id), sizeof(object_requests[i].object_id)); PyList_SetItem(ready_ids, num_returned, ready); PySet_Discard(waiting_ids, ready); @@ -295,17 +287,16 @@ PyObject *PyPlasma_wait(PyObject *self, PyObject *args) { } ARROW_CHECK(num_returned == num_to_return); /* Return both the ready IDs and the remaining IDs. */ - PyObject *t = PyTuple_New(2); + PyObject* t = PyTuple_New(2); PyTuple_SetItem(t, 0, ready_ids); PyTuple_SetItem(t, 1, waiting_ids); return t; } -PyObject *PyPlasma_evict(PyObject *self, PyObject *args) { - PlasmaClient *client; +PyObject* PyPlasma_evict(PyObject* self, PyObject* args) { + PlasmaClient* client; Py_ssize_t num_bytes; - if (!PyArg_ParseTuple(args, "O&n", PyObjectToPlasmaClient, &client, - &num_bytes)) { + if (!PyArg_ParseTuple(args, "O&n", PyObjectToPlasmaClient, &client, &num_bytes)) { return NULL; } int64_t evicted_bytes; @@ -313,24 +304,24 @@ PyObject *PyPlasma_evict(PyObject *self, PyObject *args) { return PyLong_FromSsize_t(static_cast(evicted_bytes)); } -PyObject *PyPlasma_delete(PyObject *self, PyObject *args) { - PlasmaClient *client; +PyObject* PyPlasma_delete(PyObject* self, PyObject* args) { + PlasmaClient* client; ObjectID object_id; - if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, - PyStringToUniqueID, &object_id)) { + if (!PyArg_ParseTuple(args, "O&O&", PyObjectToPlasmaClient, &client, PyStringToUniqueID, + &object_id)) { return NULL; } ARROW_CHECK_OK(client->Delete(object_id)); Py_RETURN_NONE; } -PyObject *PyPlasma_transfer(PyObject *self, PyObject *args) { - PlasmaClient *client; +PyObject* PyPlasma_transfer(PyObject* self, PyObject* args) { + PlasmaClient* client; ObjectID object_id; - const char *addr; + const char* addr; int port; if (!PyArg_ParseTuple(args, "O&O&si", PyObjectToPlasmaClient, &client, - PyStringToUniqueID, &object_id, &addr, &port)) { + PyStringToUniqueID, &object_id, &addr, &port)) { return NULL; } @@ -343,39 +334,34 @@ PyObject *PyPlasma_transfer(PyObject *self, PyObject *args) { Py_RETURN_NONE; } -PyObject *PyPlasma_subscribe(PyObject *self, PyObject *args) { - PlasmaClient *client; - if (!PyArg_ParseTuple(args, "O&", PyObjectToPlasmaClient, &client)) { - return NULL; - } +PyObject* PyPlasma_subscribe(PyObject* self, PyObject* args) { + PlasmaClient* client; + if (!PyArg_ParseTuple(args, "O&", PyObjectToPlasmaClient, &client)) { return NULL; } int sock; ARROW_CHECK_OK(client->Subscribe(sock)); return PyLong_FromLong(sock); } -PyObject *PyPlasma_receive_notification(PyObject *self, PyObject *args) { +PyObject* PyPlasma_receive_notification(PyObject* self, PyObject* args) { int plasma_sock; - if (!PyArg_ParseTuple(args, "i", &plasma_sock)) { - return NULL; - } + if (!PyArg_ParseTuple(args, "i", &plasma_sock)) { return NULL; } /* Receive object notification from the plasma connection socket. If the * object was added, return a tuple of its fields: ObjectID, data_size, * metadata_size. If the object was deleted, data_size and metadata_size will * be set to -1. */ - uint8_t *notification = read_message_async(plasma_sock); + uint8_t* notification = read_message_async(plasma_sock); if (notification == NULL) { - PyErr_SetString(PyExc_RuntimeError, - "Failed to read object notification from Plasma socket"); + PyErr_SetString( + PyExc_RuntimeError, "Failed to read object notification from Plasma socket"); return NULL; } auto object_info = flatbuffers::GetRoot(notification); /* Construct a tuple from object_info and return. */ - PyObject *t = PyTuple_New(3); - PyTuple_SetItem(t, 0, - PyBytes_FromStringAndSize(object_info->object_id()->data(), - object_info->object_id()->size())); + PyObject* t = PyTuple_New(3); + PyTuple_SetItem(t, 0, PyBytes_FromStringAndSize(object_info->object_id()->data(), + object_info->object_id()->size())); if (object_info->is_deletion()) { PyTuple_SetItem(t, 1, PyLong_FromLong(-1)); PyTuple_SetItem(t, 2, PyLong_FromLong(-1)); @@ -390,36 +376,33 @@ PyObject *PyPlasma_receive_notification(PyObject *self, PyObject *args) { static PyMethodDef plasma_methods[] = { {"connect", PyPlasma_connect, METH_VARARGS, "Connect to plasma."}, - {"disconnect", PyPlasma_disconnect, METH_VARARGS, - "Disconnect from plasma."}, + {"disconnect", PyPlasma_disconnect, METH_VARARGS, "Disconnect from plasma."}, {"create", PyPlasma_create, METH_VARARGS, "Create a new plasma object."}, - {"hash", PyPlasma_hash, METH_VARARGS, - "Compute the hash of a plasma object."}, + {"hash", PyPlasma_hash, METH_VARARGS, "Compute the hash of a plasma object."}, {"seal", PyPlasma_seal, METH_VARARGS, "Seal a plasma object."}, {"get", PyPlasma_get, METH_VARARGS, "Get a plasma object."}, {"contains", PyPlasma_contains, METH_VARARGS, - "Does the plasma store contain this plasma object?"}, + "Does the plasma store contain this plasma object?"}, {"fetch", PyPlasma_fetch, METH_VARARGS, - "Fetch the object from another plasma manager instance."}, + "Fetch the object from another plasma manager instance."}, {"wait", PyPlasma_wait, METH_VARARGS, - "Wait until num_returns objects in object_ids are ready."}, + "Wait until num_returns objects in object_ids are ready."}, {"evict", PyPlasma_evict, METH_VARARGS, - "Evict some objects until we recover some number of bytes."}, + "Evict some objects until we recover some number of bytes."}, {"release", PyPlasma_release, METH_VARARGS, "Release the plasma object."}, {"delete", PyPlasma_delete, METH_VARARGS, "Delete a plasma object."}, {"transfer", PyPlasma_transfer, METH_VARARGS, - "Transfer object to another plasma manager."}, + "Transfer object to another plasma manager."}, {"subscribe", PyPlasma_subscribe, METH_VARARGS, - "Subscribe to the plasma notification socket."}, + "Subscribe to the plasma notification socket."}, {"receive_notification", PyPlasma_receive_notification, METH_VARARGS, - "Receive next notification from plasma notification socket."}, + "Receive next notification from plasma notification socket."}, {NULL} /* Sentinel */ }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = { - PyModuleDef_HEAD_INIT, - "libplasma", /* m_name */ + PyModuleDef_HEAD_INIT, "libplasma", /* m_name */ "A Python client library for plasma.", /* m_doc */ 0, /* m_size */ plasma_methods, /* m_methods */ @@ -448,22 +431,20 @@ static struct PyModuleDef moduledef = { MOD_INIT(libplasma) { #if PY_MAJOR_VERSION >= 3 - PyObject *m = PyModule_Create(&moduledef); + PyObject* m = PyModule_Create(&moduledef); #else - PyObject *m = Py_InitModule3("libplasma", plasma_methods, - "A Python client library for plasma."); + PyObject* m = + Py_InitModule3("libplasma", plasma_methods, "A Python client library for plasma."); #endif /* Create a custom exception for when an object ID is reused. */ char plasma_object_exists_error[] = "plasma_object_exists.error"; - PlasmaObjectExistsError = - PyErr_NewException(plasma_object_exists_error, NULL, NULL); + PlasmaObjectExistsError = PyErr_NewException(plasma_object_exists_error, NULL, NULL); Py_INCREF(PlasmaObjectExistsError); PyModule_AddObject(m, "plasma_object_exists_error", PlasmaObjectExistsError); /* Create a custom exception for when the plasma store is out of memory. */ char plasma_out_of_memory_error[] = "plasma_out_of_memory.error"; - PlasmaOutOfMemoryError = - PyErr_NewException(plasma_out_of_memory_error, NULL, NULL); + PlasmaOutOfMemoryError = PyErr_NewException(plasma_out_of_memory_error, NULL, NULL); Py_INCREF(PlasmaOutOfMemoryError); PyModule_AddObject(m, "plasma_out_of_memory_error", PlasmaOutOfMemoryError); diff --git a/cpp/src/plasma/extension.h b/cpp/src/plasma/extension.h index b908833ed7f..aa4c1fa1416 100644 --- a/cpp/src/plasma/extension.h +++ b/cpp/src/plasma/extension.h @@ -20,12 +20,12 @@ #undef _XOPEN_SOURCE #undef _POSIX_C_SOURCE +#include "bytesobject.h" // NOLINT #include -#include "bytesobject.h" // NOLINT -static int PyObjectToPlasmaClient(PyObject *object, PlasmaClient **client) { +static int PyObjectToPlasmaClient(PyObject* object, PlasmaClient** client) { if (PyCapsule_IsValid(object, "plasma")) { - *client = reinterpret_cast(PyCapsule_GetPointer(object, "plasma")); + *client = reinterpret_cast(PyCapsule_GetPointer(object, "plasma")); return 1; } else { PyErr_SetString(PyExc_TypeError, "must be a 'plasma' capsule"); @@ -33,7 +33,7 @@ static int PyObjectToPlasmaClient(PyObject *object, PlasmaClient **client) { } } -int PyStringToUniqueID(PyObject *object, ObjectID *object_id) { +int PyStringToUniqueID(PyObject* object, ObjectID* object_id) { if (PyBytes_Check(object)) { memcpy(object_id, PyBytes_AsString(object), sizeof(ObjectID)); return 1; diff --git a/cpp/src/plasma/fling.cc b/cpp/src/plasma/fling.cc index 6246cc8f19c..3ad5b611d0d 100644 --- a/cpp/src/plasma/fling.cc +++ b/cpp/src/plasma/fling.cc @@ -19,10 +19,7 @@ #include -void init_msg(struct msghdr *msg, - struct iovec *iov, - char *buf, - size_t buf_len) { +void init_msg(struct msghdr* msg, struct iovec* iov, char* buf, size_t buf_len) { iov->iov_base = buf; iov->iov_len = 1; @@ -42,11 +39,11 @@ int send_fd(int conn, int fd) { init_msg(&msg, &iov, buf, sizeof(buf)); - struct cmsghdr *header = CMSG_FIRSTHDR(&msg); + struct cmsghdr* header = CMSG_FIRSTHDR(&msg); header->cmsg_level = SOL_SOCKET; header->cmsg_type = SCM_RIGHTS; header->cmsg_len = CMSG_LEN(sizeof(int)); - *reinterpret_cast(CMSG_DATA(header)) = fd; + *reinterpret_cast(CMSG_DATA(header)) = fd; /* Send file descriptor. */ ssize_t r = sendmsg(conn, &msg, 0); @@ -63,19 +60,17 @@ int recv_fd(int conn) { char buf[CMSG_SPACE(sizeof(int))]; init_msg(&msg, &iov, buf, sizeof(buf)); - if (recvmsg(conn, &msg, 0) == -1) - return -1; + if (recvmsg(conn, &msg, 0) == -1) return -1; int found_fd = -1; int oh_noes = 0; - for (struct cmsghdr *header = CMSG_FIRSTHDR(&msg); header != NULL; + for (struct cmsghdr* header = CMSG_FIRSTHDR(&msg); header != NULL; header = CMSG_NXTHDR(&msg, header)) if (header->cmsg_level == SOL_SOCKET && header->cmsg_type == SCM_RIGHTS) { ssize_t count = - (header->cmsg_len - (CMSG_DATA(header) - (unsigned char *) header)) / - sizeof(int); + (header->cmsg_len - (CMSG_DATA(header) - (unsigned char*)header)) / sizeof(int); for (int i = 0; i < count; ++i) { - int fd = (reinterpret_cast(CMSG_DATA(header)))[i]; + int fd = (reinterpret_cast(CMSG_DATA(header)))[i]; if (found_fd == -1) { found_fd = fd; } else { diff --git a/cpp/src/plasma/fling.h b/cpp/src/plasma/fling.h index c676554be24..64da6821421 100644 --- a/cpp/src/plasma/fling.h +++ b/cpp/src/plasma/fling.h @@ -26,21 +26,20 @@ * * Most of the code is from https://github.com/sharvil/flingfd */ -#include #include -#include #include +#include #include +#include /* This is neccessary for Mac OS X, see http://www.apuebook.com/faqs2e.html * (10). */ #if !defined(CMSG_SPACE) && !defined(CMSG_LEN) -#define CMSG_SPACE(len) \ - (__DARWIN_ALIGN32(sizeof(struct cmsghdr)) + __DARWIN_ALIGN32(len)) +#define CMSG_SPACE(len) (__DARWIN_ALIGN32(sizeof(struct cmsghdr)) + __DARWIN_ALIGN32(len)) #define CMSG_LEN(len) (__DARWIN_ALIGN32(sizeof(struct cmsghdr)) + (len)) #endif -void init_msg(struct msghdr *msg, struct iovec *iov, char *buf, size_t buf_len); +void init_msg(struct msghdr* msg, struct iovec* iov, char* buf, size_t buf_len); /** * Send a file descriptor over a unix domain socket. diff --git a/cpp/src/plasma/io.cc b/cpp/src/plasma/io.cc index e404bce84ca..62340eb0bd1 100644 --- a/cpp/src/plasma/io.cc +++ b/cpp/src/plasma/io.cc @@ -15,8 +15,8 @@ // specific language governing permissions and limitations // under the License. -#include "plasma/common.h" #include "plasma/io.h" +#include "plasma/common.h" using arrow::Status; @@ -28,7 +28,7 @@ using arrow::Status; #define NUM_CONNECT_ATTEMPTS 50 #define CONNECT_TIMEOUT_MS 100 -Status WriteBytes(int fd, uint8_t *cursor, size_t length) { +Status WriteBytes(int fd, uint8_t* cursor, size_t length) { ssize_t nbytes = 0; size_t bytesleft = length; size_t offset = 0; @@ -37,9 +37,7 @@ Status WriteBytes(int fd, uint8_t *cursor, size_t length) { * advance the cursor, and decrease the amount left to write. */ nbytes = write(fd, cursor + offset, bytesleft); if (nbytes < 0) { - if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - continue; - } + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { continue; } return Status::IOError(std::string(strerror(errno))); } else if (nbytes == 0) { return Status::IOError("Encountered unexpected EOF"); @@ -52,18 +50,15 @@ Status WriteBytes(int fd, uint8_t *cursor, size_t length) { return Status::OK(); } -Status WriteMessage(int fd, int64_t type, int64_t length, uint8_t *bytes) { +Status WriteMessage(int fd, int64_t type, int64_t length, uint8_t* bytes) { int64_t version = PLASMA_PROTOCOL_VERSION; - RETURN_NOT_OK( - WriteBytes(fd, reinterpret_cast(&version), sizeof(version))); - RETURN_NOT_OK( - WriteBytes(fd, reinterpret_cast(&type), sizeof(type))); - RETURN_NOT_OK( - WriteBytes(fd, reinterpret_cast(&length), sizeof(length))); + RETURN_NOT_OK(WriteBytes(fd, reinterpret_cast(&version), sizeof(version))); + RETURN_NOT_OK(WriteBytes(fd, reinterpret_cast(&type), sizeof(type))); + RETURN_NOT_OK(WriteBytes(fd, reinterpret_cast(&length), sizeof(length))); return WriteBytes(fd, bytes, length * sizeof(char)); } -Status ReadBytes(int fd, uint8_t *cursor, size_t length) { +Status ReadBytes(int fd, uint8_t* cursor, size_t length) { ssize_t nbytes = 0; /* Termination condition: EOF or read 'length' bytes total. */ size_t bytesleft = length; @@ -71,9 +66,7 @@ Status ReadBytes(int fd, uint8_t *cursor, size_t length) { while (bytesleft > 0) { nbytes = read(fd, cursor + offset, bytesleft); if (nbytes < 0) { - if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - continue; - } + if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { continue; } return Status::IOError(std::string(strerror(errno))); } else if (0 == nbytes) { return Status::IOError("Encountered unexpected EOF"); @@ -86,28 +79,22 @@ Status ReadBytes(int fd, uint8_t *cursor, size_t length) { return Status::OK(); } -Status ReadMessage(int fd, int64_t *type, std::vector &buffer) { +Status ReadMessage(int fd, int64_t* type, std::vector& buffer) { int64_t version; - RETURN_NOT_OK_ELSE( - ReadBytes(fd, reinterpret_cast(&version), sizeof(version)), + RETURN_NOT_OK_ELSE(ReadBytes(fd, reinterpret_cast(&version), sizeof(version)), *type = DISCONNECT_CLIENT); ARROW_CHECK(version == PLASMA_PROTOCOL_VERSION) << "version = " << version; size_t length; - RETURN_NOT_OK_ELSE( - ReadBytes(fd, reinterpret_cast(type), sizeof(*type)), + RETURN_NOT_OK_ELSE(ReadBytes(fd, reinterpret_cast(type), sizeof(*type)), *type = DISCONNECT_CLIENT); - RETURN_NOT_OK_ELSE( - ReadBytes(fd, reinterpret_cast(&length), sizeof(length)), + RETURN_NOT_OK_ELSE(ReadBytes(fd, reinterpret_cast(&length), sizeof(length)), *type = DISCONNECT_CLIENT); - if (length > buffer.size()) { - buffer.resize(length); - } - RETURN_NOT_OK_ELSE(ReadBytes(fd, buffer.data(), length), - *type = DISCONNECT_CLIENT); + if (length > buffer.size()) { buffer.resize(length); } + RETURN_NOT_OK_ELSE(ReadBytes(fd, buffer.data(), length), *type = DISCONNECT_CLIENT); return Status::OK(); } -int bind_ipc_sock(const std::string &pathname, bool shall_listen) { +int bind_ipc_sock(const std::string& pathname, bool shall_listen) { struct sockaddr_un socket_address; int socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); if (socket_fd < 0) { @@ -116,8 +103,8 @@ int bind_ipc_sock(const std::string &pathname, bool shall_listen) { } /* Tell the system to allow the port to be reused. */ int on = 1; - if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&on), - sizeof(on)) < 0) { + if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&on), + sizeof(on)) < 0) { ARROW_LOG(ERROR) << "setsockopt failed for pathname " << pathname; close(socket_fd); return -1; @@ -133,8 +120,7 @@ int bind_ipc_sock(const std::string &pathname, bool shall_listen) { } strncpy(socket_address.sun_path, pathname.c_str(), pathname.size() + 1); - if (bind(socket_fd, (struct sockaddr *) &socket_address, - sizeof(socket_address)) != 0) { + if (bind(socket_fd, (struct sockaddr*)&socket_address, sizeof(socket_address)) != 0) { ARROW_LOG(ERROR) << "Bind failed for pathname " << pathname; close(socket_fd); return -1; @@ -147,38 +133,28 @@ int bind_ipc_sock(const std::string &pathname, bool shall_listen) { return socket_fd; } -int connect_ipc_sock_retry(const std::string &pathname, - int num_retries, - int64_t timeout) { +int connect_ipc_sock_retry( + const std::string& pathname, int num_retries, int64_t timeout) { /* Pick the default values if the user did not specify. */ - if (num_retries < 0) { - num_retries = NUM_CONNECT_ATTEMPTS; - } - if (timeout < 0) { - timeout = CONNECT_TIMEOUT_MS; - } + if (num_retries < 0) { num_retries = NUM_CONNECT_ATTEMPTS; } + if (timeout < 0) { timeout = CONNECT_TIMEOUT_MS; } int fd = -1; for (int num_attempts = 0; num_attempts < num_retries; ++num_attempts) { fd = connect_ipc_sock(pathname); - if (fd >= 0) { - break; - } + if (fd >= 0) { break; } if (num_attempts == 0) { - ARROW_LOG(ERROR) << "Connection to socket failed for pathname " - << pathname; + ARROW_LOG(ERROR) << "Connection to socket failed for pathname " << pathname; } /* Sleep for timeout milliseconds. */ usleep(static_cast(timeout * 1000)); } /* If we could not connect to the socket, exit. */ - if (fd == -1) { - ARROW_LOG(FATAL) << "Could not connect to socket " << pathname; - } + if (fd == -1) { ARROW_LOG(FATAL) << "Could not connect to socket " << pathname; } return fd; } -int connect_ipc_sock(const std::string &pathname) { +int connect_ipc_sock(const std::string& pathname) { struct sockaddr_un socket_address; int socket_fd; @@ -196,8 +172,8 @@ int connect_ipc_sock(const std::string &pathname) { } strncpy(socket_address.sun_path, pathname.c_str(), pathname.size() + 1); - if (connect(socket_fd, (struct sockaddr *) &socket_address, - sizeof(socket_address)) != 0) { + if (connect(socket_fd, (struct sockaddr*)&socket_address, sizeof(socket_address)) != + 0) { close(socket_fd); return -1; } @@ -214,22 +190,20 @@ int AcceptClient(int socket_fd) { return client_fd; } -uint8_t *read_message_async(int sock) { +uint8_t* read_message_async(int sock) { int64_t size; - Status s = ReadBytes(sock, reinterpret_cast(&size), sizeof(int64_t)); + Status s = ReadBytes(sock, reinterpret_cast(&size), sizeof(int64_t)); if (!s.ok()) { /* The other side has closed the socket. */ - ARROW_LOG(DEBUG) - << "Socket has been closed, or some other error has occurred."; + ARROW_LOG(DEBUG) << "Socket has been closed, or some other error has occurred."; close(sock); return NULL; } - uint8_t *message = reinterpret_cast(malloc(size)); + uint8_t* message = reinterpret_cast(malloc(size)); s = ReadBytes(sock, message, size); if (!s.ok()) { /* The other side has closed the socket. */ - ARROW_LOG(DEBUG) - << "Socket has been closed, or some other error has occurred."; + ARROW_LOG(DEBUG) << "Socket has been closed, or some other error has occurred."; close(sock); return NULL; } diff --git a/cpp/src/plasma/io.h b/cpp/src/plasma/io.h index a8cbb7cdfb1..453dd7349ce 100644 --- a/cpp/src/plasma/io.h +++ b/cpp/src/plasma/io.h @@ -16,12 +16,12 @@ // under the License. #include -#include #include #include +#include -#include #include +#include #include "arrow/status.h" @@ -31,25 +31,20 @@ #define PLASMA_PROTOCOL_VERSION 0x0000000000000000 #define DISCONNECT_CLIENT 0 -arrow::Status WriteBytes(int fd, uint8_t *cursor, size_t length); +arrow::Status WriteBytes(int fd, uint8_t* cursor, size_t length); -arrow::Status WriteMessage(int fd, - int64_t type, - int64_t length, - uint8_t *bytes); +arrow::Status WriteMessage(int fd, int64_t type, int64_t length, uint8_t* bytes); -arrow::Status ReadBytes(int fd, uint8_t *cursor, size_t length); +arrow::Status ReadBytes(int fd, uint8_t* cursor, size_t length); -arrow::Status ReadMessage(int fd, int64_t *type, std::vector &buffer); +arrow::Status ReadMessage(int fd, int64_t* type, std::vector& buffer); -int bind_ipc_sock(const std::string &pathname, bool shall_listen); +int bind_ipc_sock(const std::string& pathname, bool shall_listen); -int connect_ipc_sock(const std::string &pathname); +int connect_ipc_sock(const std::string& pathname); -int connect_ipc_sock_retry(const std::string &pathname, - int num_retries, - int64_t timeout); +int connect_ipc_sock_retry(const std::string& pathname, int num_retries, int64_t timeout); int AcceptClient(int socket_fd); -uint8_t *read_message_async(int sock); +uint8_t* read_message_async(int sock); diff --git a/cpp/src/plasma/malloc.cc b/cpp/src/plasma/malloc.cc index 25c51d043fa..317f9b3de4d 100644 --- a/cpp/src/plasma/malloc.cc +++ b/cpp/src/plasma/malloc.cc @@ -16,9 +16,9 @@ // under the License. #include -#include #include #include +#include #include #include #include @@ -29,8 +29,8 @@ #include "plasma/malloc.h" extern "C" { -void *fake_mmap(size_t); -int fake_munmap(void *, int64_t); +void* fake_mmap(size_t); +int fake_munmap(void*, int64_t); #define MMAP(s) fake_mmap(s) #define MUNMAP(a, s) fake_munmap(a, s) @@ -39,7 +39,7 @@ int fake_munmap(void *, int64_t); #define USE_DL_PREFIX #define HAVE_MORECORE 0 #define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T -#define DEFAULT_GRANULARITY ((size_t) 128U * 1024U) +#define DEFAULT_GRANULARITY ((size_t)128U * 1024U) #include "thirdparty/dlmalloc.c" @@ -62,22 +62,22 @@ namespace { /** Hashtable that contains one entry per segment that we got from the OS * via mmap. Associates the address of that segment with its file descriptor * and size. */ -std::unordered_map mmap_records; +std::unordered_map mmap_records; } /* namespace */ constexpr int GRANULARITY_MULTIPLIER = 2; -static void *pointer_advance(void *p, ptrdiff_t n) { - return (unsigned char *) p + n; +static void* pointer_advance(void* p, ptrdiff_t n) { + return (unsigned char*)p + n; } -static void *pointer_retreat(void *p, ptrdiff_t n) { - return (unsigned char *) p - n; +static void* pointer_retreat(void* p, ptrdiff_t n) { + return (unsigned char*)p - n; } -static ptrdiff_t pointer_distance(void const *pfrom, void const *pto) { - return (unsigned char const *) pto - (unsigned char const *) pfrom; +static ptrdiff_t pointer_distance(void const* pfrom, void const* pto) { + return (unsigned char const*)pto - (unsigned char const*)pfrom; } /* Create a buffer. This is creating a temporary file and then @@ -86,8 +86,8 @@ int create_buffer(int64_t size) { int fd; #ifdef _WIN32 if (!CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, - (DWORD)((uint64_t) size >> (CHAR_BIT * sizeof(DWORD))), - (DWORD)(uint64_t) size, NULL)) { + (DWORD)((uint64_t)size >> (CHAR_BIT * sizeof(DWORD))), (DWORD)(uint64_t)size, + NULL)) { fd = -1; } #else @@ -99,9 +99,8 @@ int create_buffer(int64_t size) { char file_name[32]; strncpy(file_name, file_template, 32); fd = mkstemp(file_name); - if (fd < 0) - return -1; - FILE *file = fdopen(fd, "a+"); + if (fd < 0) return -1; + FILE* file = fdopen(fd, "a+"); if (!file) { close(fd); return -1; @@ -110,7 +109,7 @@ int create_buffer(int64_t size) { ARROW_LOG(FATAL) << "unlink error"; return -1; } - if (ftruncate(fd, (off_t) size) != 0) { + if (ftruncate(fd, (off_t)size) != 0) { ARROW_LOG(FATAL) << "ftruncate error"; return -1; } @@ -118,7 +117,7 @@ int create_buffer(int64_t size) { return fd; } -void *fake_mmap(size_t size) { +void* fake_mmap(size_t size) { /* Add sizeof(size_t) so that the returned pointer is deliberately not * page-aligned. This ensures that the segments of memory returned by * fake_mmap are never contiguous. */ @@ -126,15 +125,13 @@ void *fake_mmap(size_t size) { int fd = create_buffer(size); ARROW_CHECK(fd >= 0) << "Failed to create buffer during mmap"; - void *pointer = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - if (pointer == MAP_FAILED) { - return pointer; - } + void* pointer = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (pointer == MAP_FAILED) { return pointer; } /* Increase dlmalloc's allocation granularity directly. */ mparams.granularity *= GRANULARITY_MULTIPLIER; - mmap_record &record = mmap_records[pointer]; + mmap_record& record = mmap_records[pointer]; record.fd = fd; record.size = size; @@ -144,7 +141,7 @@ void *fake_mmap(size_t size) { return pointer; } -int fake_munmap(void *addr, int64_t size) { +int fake_munmap(void* addr, int64_t size) { ARROW_LOG(DEBUG) << "fake_munmap(" << addr << ", " << size << ")"; addr = pointer_retreat(addr, sizeof(size_t)); size += sizeof(size_t); @@ -158,22 +155,16 @@ int fake_munmap(void *addr, int64_t size) { } int r = munmap(addr, size); - if (r == 0) { - close(entry->second.fd); - } + if (r == 0) { close(entry->second.fd); } mmap_records.erase(entry); return r; } -void get_malloc_mapinfo(void *addr, - int *fd, - int64_t *map_size, - ptrdiff_t *offset) { +void get_malloc_mapinfo(void* addr, int* fd, int64_t* map_size, ptrdiff_t* offset) { /* TODO(rshin): Implement a more efficient search through mmap_records. */ - for (const auto &entry : mmap_records) { - if (addr >= entry.first && - addr < pointer_advance(entry.first, entry.second.size)) { + for (const auto& entry : mmap_records) { + if (addr >= entry.first && addr < pointer_advance(entry.first, entry.second.size)) { *fd = entry.second.fd; *map_size = entry.second.size; *offset = pointer_distance(entry.first, addr); diff --git a/cpp/src/plasma/malloc.h b/cpp/src/plasma/malloc.h index cbdbb6ba05e..f89a4a9810e 100644 --- a/cpp/src/plasma/malloc.h +++ b/cpp/src/plasma/malloc.h @@ -18,9 +18,6 @@ #ifndef MALLOC_H #define MALLOC_H -void get_malloc_mapinfo(void *addr, - int *fd, - int64_t *map_length, - ptrdiff_t *offset); +void get_malloc_mapinfo(void* addr, int* fd, int64_t* map_length, ptrdiff_t* offset); #endif /* MALLOC_H */ diff --git a/cpp/src/plasma/plasma.cc b/cpp/src/plasma/plasma.cc index 43ac61cbb68..70e10983fed 100644 --- a/cpp/src/plasma/plasma.cc +++ b/cpp/src/plasma/plasma.cc @@ -15,8 +15,8 @@ // specific language governing permissions and limitations // under the License. -#include #include +#include #include #include "plasma/common.h" @@ -24,20 +24,16 @@ #include "plasma/protocol.h" int warn_if_sigpipe(int status, int client_sock) { - if (status >= 0) { - return 0; - } + if (status >= 0) { return 0; } if (errno == EPIPE || errno == EBADF || errno == ECONNRESET) { - ARROW_LOG(WARNING) - << "Received SIGPIPE, BAD FILE DESCRIPTOR, or ECONNRESET when " - "sending a message to client on fd " - << client_sock << ". The client on the other end may " - "have hung up."; + ARROW_LOG(WARNING) << "Received SIGPIPE, BAD FILE DESCRIPTOR, or ECONNRESET when " + "sending a message to client on fd " + << client_sock << ". The client on the other end may " + "have hung up."; return errno; } - ARROW_LOG(FATAL) << "Failed to write message to client on fd " << client_sock - << "."; - return -1; // This is never reached. + ARROW_LOG(FATAL) << "Failed to write message to client on fd " << client_sock << "."; + return -1; // This is never reached. } /** @@ -49,21 +45,19 @@ int warn_if_sigpipe(int status, int client_sock) { * @return The object info buffer. It is the caller's responsibility to free * this buffer with "delete" after it has been used. */ -uint8_t *create_object_info_buffer(ObjectInfoT *object_info) { +uint8_t* create_object_info_buffer(ObjectInfoT* object_info) { flatbuffers::FlatBufferBuilder fbb; auto message = CreateObjectInfo(fbb, object_info); fbb.Finish(message); - uint8_t *notification = new uint8_t[sizeof(int64_t) + fbb.GetSize()]; - *(reinterpret_cast(notification)) = fbb.GetSize(); + uint8_t* notification = new uint8_t[sizeof(int64_t) + fbb.GetSize()]; + *(reinterpret_cast(notification)) = fbb.GetSize(); memcpy(notification + sizeof(int64_t), fbb.GetBufferPointer(), fbb.GetSize()); return notification; } -ObjectTableEntry *get_object_table_entry(PlasmaStoreInfo *store_info, - ObjectID object_id) { +ObjectTableEntry* get_object_table_entry( + PlasmaStoreInfo* store_info, ObjectID object_id) { auto it = store_info->objects.find(object_id); - if (it == store_info->objects.end()) { - return NULL; - } + if (it == store_info->objects.end()) { return NULL; } return it->second.get(); } diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h index f12f44ff146..e898aed3375 100644 --- a/cpp/src/plasma/plasma.h +++ b/cpp/src/plasma/plasma.h @@ -18,20 +18,20 @@ #ifndef PLASMA_H #define PLASMA_H -#include -#include #include #include #include +#include +#include #include #include /* pid_t */ #include #include -#include "format/common_generated.h" -#include "arrow/util/logging.h" #include "arrow/status.h" +#include "arrow/util/logging.h" +#include "format/common_generated.h" #include @@ -83,8 +83,7 @@ typedef struct { } ObjectRequest; /** Mapping from object IDs to type and status of the request. */ -typedef std::unordered_map - ObjectRequestMap; +typedef std::unordered_map ObjectRequestMap; /* Handle to access memory mapped file and map it into client address space. */ typedef struct { @@ -144,9 +143,9 @@ struct ObjectTableEntry { /** Offset from the base of the mmap. */ ptrdiff_t offset; /** Pointer to the object data. Needed to free the object. */ - uint8_t *pointer; + uint8_t* pointer; /** Set of clients currently using this object. */ - std::unordered_set clients; + std::unordered_set clients; /** The state of the object, e.g., whether it is open or sealed. */ object_state state; /** The digest of the object. Used to see if two objects are the same. */ @@ -156,10 +155,7 @@ struct ObjectTableEntry { /** The plasma store information that is exposed to the eviction policy. */ struct PlasmaStoreInfo { /** Objects that are in the Plasma store. */ - std::unordered_map, - UniqueIDHasher> - objects; + std::unordered_map, UniqueIDHasher> objects; /** The amount of memory (in bytes) that we allow to be allocated in the * store. */ int64_t memory_capacity; @@ -174,8 +170,7 @@ struct PlasmaStoreInfo { * @return The entry associated with the object_id or NULL if the object_id * is not present. */ -ObjectTableEntry *get_object_table_entry(PlasmaStoreInfo *store_info, - ObjectID object_id); +ObjectTableEntry* get_object_table_entry(PlasmaStoreInfo* store_info, ObjectID object_id); /** * Print a warning if the status is less than zero. This should be used to check @@ -195,6 +190,6 @@ ObjectTableEntry *get_object_table_entry(PlasmaStoreInfo *store_info, */ int warn_if_sigpipe(int status, int client_sock); -uint8_t *create_object_info_buffer(ObjectInfoT *object_info); +uint8_t* create_object_info_buffer(ObjectInfoT* object_info); #endif /* PLASMA_H */ diff --git a/cpp/src/plasma/protocol.cc b/cpp/src/plasma/protocol.cc index 4e335bf11a0..7ffea2eca3b 100644 --- a/cpp/src/plasma/protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -19,16 +19,14 @@ #include "format/plasma_generated.h" #include "plasma/common.h" -#include "plasma/protocol.h" #include "plasma/io.h" +#include "plasma/protocol.h" using flatbuffers::uoffset_t; -flatbuffers::Offset< - flatbuffers::Vector>> -to_flatbuffer(flatbuffers::FlatBufferBuilder &fbb, - ObjectID object_ids[], - int64_t num_objects) { +flatbuffers::Offset>> +to_flatbuffer( + flatbuffers::FlatBufferBuilder& fbb, ObjectID object_ids[], int64_t num_objects) { std::vector> results; for (int64_t i = 0; i < num_objects; i++) { results.push_back(fbb.CreateString(object_ids[i].binary())); @@ -36,9 +34,7 @@ to_flatbuffer(flatbuffers::FlatBufferBuilder &fbb, return fbb.CreateVector(results); } -Status PlasmaReceive(int sock, - int64_t message_type, - std::vector &buffer) { +Status PlasmaReceive(int sock, int64_t message_type, std::vector& buffer) { int64_t type; RETURN_NOT_OK(ReadMessage(sock, &type, buffer)); ARROW_CHECK(type == message_type) << "type = " << type @@ -48,22 +44,18 @@ Status PlasmaReceive(int sock, /* Create messages. */ -Status SendCreateRequest(int sock, - ObjectID object_id, - int64_t data_size, - int64_t metadata_size) { +Status SendCreateRequest( + int sock, ObjectID object_id, int64_t data_size, int64_t metadata_size) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaCreateRequest( fbb, fbb.CreateString(object_id.binary()), data_size, metadata_size); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaCreateRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaCreateRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadCreateRequest(uint8_t *data, - ObjectID *object_id, - int64_t *data_size, - int64_t *metadata_size) { +Status ReadCreateRequest( + uint8_t* data, ObjectID* object_id, int64_t* data_size, int64_t* metadata_size) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *data_size = message->data_size(); @@ -72,25 +64,20 @@ Status ReadCreateRequest(uint8_t *data, return Status::OK(); } -Status SendCreateReply(int sock, - ObjectID object_id, - PlasmaObject *object, - int error_code) { +Status SendCreateReply( + int sock, ObjectID object_id, PlasmaObject* object, int error_code) { flatbuffers::FlatBufferBuilder fbb; - PlasmaObjectSpec plasma_object( - object->handle.store_fd, object->handle.mmap_size, object->data_offset, - object->data_size, object->metadata_offset, object->metadata_size); - auto message = - CreatePlasmaCreateReply(fbb, fbb.CreateString(object_id.binary()), - &plasma_object, (PlasmaError) error_code); + PlasmaObjectSpec plasma_object(object->handle.store_fd, object->handle.mmap_size, + object->data_offset, object->data_size, object->metadata_offset, + object->metadata_size); + auto message = CreatePlasmaCreateReply( + fbb, fbb.CreateString(object_id.binary()), &plasma_object, (PlasmaError)error_code); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaCreateReply, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaCreateReply, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadCreateReply(uint8_t *data, - ObjectID *object_id, - PlasmaObject *object) { +Status ReadCreateReply(uint8_t* data, ObjectID* object_id, PlasmaObject* object) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *object_id = ObjectID::from_binary(message->object_id()->str()); @@ -105,19 +92,17 @@ Status ReadCreateReply(uint8_t *data, /* Seal messages. */ -Status SendSealRequest(int sock, ObjectID object_id, unsigned char *digest) { +Status SendSealRequest(int sock, ObjectID object_id, unsigned char* digest) { flatbuffers::FlatBufferBuilder fbb; - auto digest_string = fbb.CreateString(reinterpret_cast(digest), kDigestSize); - auto message = CreatePlasmaSealRequest( - fbb, fbb.CreateString(object_id.binary()), digest_string); + auto digest_string = fbb.CreateString(reinterpret_cast(digest), kDigestSize); + auto message = + CreatePlasmaSealRequest(fbb, fbb.CreateString(object_id.binary()), digest_string); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaSealRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaSealRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadSealRequest(uint8_t *data, - ObjectID *object_id, - unsigned char *digest) { +Status ReadSealRequest(uint8_t* data, ObjectID* object_id, unsigned char* digest) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *object_id = ObjectID::from_binary(message->object_id()->str()); @@ -129,13 +114,13 @@ Status ReadSealRequest(uint8_t *data, Status SendSealReply(int sock, ObjectID object_id, int error) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaSealReply( - fbb, fbb.CreateString(object_id.binary()), (PlasmaError) error); + fbb, fbb.CreateString(object_id.binary()), (PlasmaError)error); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaSealReply, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaSealReply, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadSealReply(uint8_t *data, ObjectID *object_id) { +Status ReadSealReply(uint8_t* data, ObjectID* object_id) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *object_id = ObjectID::from_binary(message->object_id()->str()); @@ -146,14 +131,13 @@ Status ReadSealReply(uint8_t *data, ObjectID *object_id) { Status SendReleaseRequest(int sock, ObjectID object_id) { flatbuffers::FlatBufferBuilder fbb; - auto message = - CreatePlasmaSealRequest(fbb, fbb.CreateString(object_id.binary())); + auto message = CreatePlasmaSealRequest(fbb, fbb.CreateString(object_id.binary())); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaReleaseRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaReleaseRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadReleaseRequest(uint8_t *data, ObjectID *object_id) { +Status ReadReleaseRequest(uint8_t* data, ObjectID* object_id) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *object_id = ObjectID::from_binary(message->object_id()->str()); @@ -163,13 +147,13 @@ Status ReadReleaseRequest(uint8_t *data, ObjectID *object_id) { Status SendReleaseReply(int sock, ObjectID object_id, int error) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaReleaseReply( - fbb, fbb.CreateString(object_id.binary()), (PlasmaError) error); + fbb, fbb.CreateString(object_id.binary()), (PlasmaError)error); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaReleaseReply, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaReleaseReply, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadReleaseReply(uint8_t *data, ObjectID *object_id) { +Status ReadReleaseReply(uint8_t* data, ObjectID* object_id) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *object_id = ObjectID::from_binary(message->object_id()->str()); @@ -180,14 +164,13 @@ Status ReadReleaseReply(uint8_t *data, ObjectID *object_id) { Status SendDeleteRequest(int sock, ObjectID object_id) { flatbuffers::FlatBufferBuilder fbb; - auto message = - CreatePlasmaDeleteRequest(fbb, fbb.CreateString(object_id.binary())); + auto message = CreatePlasmaDeleteRequest(fbb, fbb.CreateString(object_id.binary())); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaDeleteRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaDeleteRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadDeleteRequest(uint8_t *data, ObjectID *object_id) { +Status ReadDeleteRequest(uint8_t* data, ObjectID* object_id) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *object_id = ObjectID::from_binary(message->object_id()->str()); @@ -197,13 +180,13 @@ Status ReadDeleteRequest(uint8_t *data, ObjectID *object_id) { Status SendDeleteReply(int sock, ObjectID object_id, int error) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaDeleteReply( - fbb, fbb.CreateString(object_id.binary()), (PlasmaError) error); + fbb, fbb.CreateString(object_id.binary()), (PlasmaError)error); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaDeleteReply, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaDeleteReply, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadDeleteReply(uint8_t *data, ObjectID *object_id) { +Status ReadDeleteReply(uint8_t* data, ObjectID* object_id) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *object_id = ObjectID::from_binary(message->object_id()->str()); @@ -214,16 +197,14 @@ Status ReadDeleteReply(uint8_t *data, ObjectID *object_id) { Status SendStatusRequest(int sock, ObjectID object_ids[], int64_t num_objects) { flatbuffers::FlatBufferBuilder fbb; - auto message = CreatePlasmaStatusRequest( - fbb, to_flatbuffer(fbb, object_ids, num_objects)); + auto message = + CreatePlasmaStatusRequest(fbb, to_flatbuffer(fbb, object_ids, num_objects)); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaStatusRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaStatusRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadStatusRequest(uint8_t *data, - ObjectID object_ids[], - int64_t num_objects) { +Status ReadStatusRequest(uint8_t* data, ObjectID object_ids[], int64_t num_objects) { DCHECK(data); auto message = flatbuffers::GetRoot(data); for (uoffset_t i = 0; i < num_objects; ++i) { @@ -232,29 +213,24 @@ Status ReadStatusRequest(uint8_t *data, return Status::OK(); } -Status SendStatusReply(int sock, - ObjectID object_ids[], - int object_status[], - int64_t num_objects) { +Status SendStatusReply( + int sock, ObjectID object_ids[], int object_status[], int64_t num_objects) { flatbuffers::FlatBufferBuilder fbb; - auto message = - CreatePlasmaStatusReply(fbb, to_flatbuffer(fbb, object_ids, num_objects), - fbb.CreateVector(object_status, num_objects)); + auto message = CreatePlasmaStatusReply(fbb, to_flatbuffer(fbb, object_ids, num_objects), + fbb.CreateVector(object_status, num_objects)); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaStatusReply, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaStatusReply, fbb.GetSize(), fbb.GetBufferPointer()); } -int64_t ReadStatusReply_num_objects(uint8_t *data) { +int64_t ReadStatusReply_num_objects(uint8_t* data) { DCHECK(data); auto message = flatbuffers::GetRoot(data); return message->object_ids()->size(); } -Status ReadStatusReply(uint8_t *data, - ObjectID object_ids[], - int object_status[], - int64_t num_objects) { +Status ReadStatusReply( + uint8_t* data, ObjectID object_ids[], int object_status[], int64_t num_objects) { DCHECK(data); auto message = flatbuffers::GetRoot(data); for (uoffset_t i = 0; i < num_objects; ++i) { @@ -270,14 +246,13 @@ Status ReadStatusReply(uint8_t *data, Status SendContainsRequest(int sock, ObjectID object_id) { flatbuffers::FlatBufferBuilder fbb; - auto message = - CreatePlasmaContainsRequest(fbb, fbb.CreateString(object_id.binary())); + auto message = CreatePlasmaContainsRequest(fbb, fbb.CreateString(object_id.binary())); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaContainsRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaContainsRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadContainsRequest(uint8_t *data, ObjectID *object_id) { +Status ReadContainsRequest(uint8_t* data, ObjectID* object_id) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *object_id = ObjectID::from_binary(message->object_id()->str()); @@ -286,14 +261,14 @@ Status ReadContainsRequest(uint8_t *data, ObjectID *object_id) { Status SendContainsReply(int sock, ObjectID object_id, int has_object) { flatbuffers::FlatBufferBuilder fbb; - auto message = CreatePlasmaContainsReply( - fbb, fbb.CreateString(object_id.binary()), has_object); + auto message = + CreatePlasmaContainsReply(fbb, fbb.CreateString(object_id.binary()), has_object); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaContainsReply, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaContainsReply, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadContainsReply(uint8_t *data, ObjectID *object_id, int *has_object) { +Status ReadContainsReply(uint8_t* data, ObjectID* object_id, int* has_object) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *object_id = ObjectID::from_binary(message->object_id()->str()); @@ -307,11 +282,11 @@ Status SendConnectRequest(int sock) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaConnectRequest(fbb); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaConnectRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaConnectRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadConnectRequest(uint8_t *data) { +Status ReadConnectRequest(uint8_t* data) { return Status::OK(); } @@ -319,11 +294,11 @@ Status SendConnectReply(int sock, int64_t memory_capacity) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaConnectReply(fbb, memory_capacity); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaConnectReply, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaConnectReply, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadConnectReply(uint8_t *data, int64_t *memory_capacity) { +Status ReadConnectReply(uint8_t* data, int64_t* memory_capacity) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *memory_capacity = message->memory_capacity(); @@ -336,11 +311,11 @@ Status SendEvictRequest(int sock, int64_t num_bytes) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaEvictRequest(fbb, num_bytes); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaEvictRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaEvictRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadEvictRequest(uint8_t *data, int64_t *num_bytes) { +Status ReadEvictRequest(uint8_t* data, int64_t* num_bytes) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *num_bytes = message->num_bytes(); @@ -351,11 +326,11 @@ Status SendEvictReply(int sock, int64_t num_bytes) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaEvictReply(fbb, num_bytes); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaEvictReply, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaEvictReply, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadEvictReply(uint8_t *data, int64_t &num_bytes) { +Status ReadEvictReply(uint8_t* data, int64_t& num_bytes) { DCHECK(data); auto message = flatbuffers::GetRoot(data); num_bytes = message->num_bytes(); @@ -364,21 +339,18 @@ Status ReadEvictReply(uint8_t *data, int64_t &num_bytes) { /* Get messages. */ -Status SendGetRequest(int sock, - ObjectID object_ids[], - int64_t num_objects, - int64_t timeout_ms) { +Status SendGetRequest( + int sock, ObjectID object_ids[], int64_t num_objects, int64_t timeout_ms) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaGetRequest( fbb, to_flatbuffer(fbb, object_ids, num_objects), timeout_ms); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaGetRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaGetRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadGetRequest(uint8_t *data, - std::vector &object_ids, - int64_t *timeout_ms) { +Status ReadGetRequest( + uint8_t* data, std::vector& object_ids, int64_t* timeout_ms) { DCHECK(data); auto message = flatbuffers::GetRoot(data); for (uoffset_t i = 0; i < message->object_ids()->size(); ++i) { @@ -389,39 +361,34 @@ Status ReadGetRequest(uint8_t *data, return Status::OK(); } -Status SendGetReply( - int sock, - ObjectID object_ids[], - std::unordered_map &plasma_objects, +Status SendGetReply(int sock, ObjectID object_ids[], + std::unordered_map& plasma_objects, int64_t num_objects) { flatbuffers::FlatBufferBuilder fbb; std::vector objects; for (int i = 0; i < num_objects; ++i) { - const PlasmaObject &object = plasma_objects[object_ids[i]]; - objects.push_back(PlasmaObjectSpec( - object.handle.store_fd, object.handle.mmap_size, object.data_offset, - object.data_size, object.metadata_offset, object.metadata_size)); + const PlasmaObject& object = plasma_objects[object_ids[i]]; + objects.push_back(PlasmaObjectSpec(object.handle.store_fd, object.handle.mmap_size, + object.data_offset, object.data_size, object.metadata_offset, + object.metadata_size)); } - auto message = CreatePlasmaGetReply( - fbb, to_flatbuffer(fbb, object_ids, num_objects), + auto message = CreatePlasmaGetReply(fbb, to_flatbuffer(fbb, object_ids, num_objects), fbb.CreateVectorOfStructs(objects.data(), num_objects)); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaGetReply, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaGetReply, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadGetReply(uint8_t *data, - ObjectID object_ids[], - PlasmaObject plasma_objects[], - int64_t num_objects) { +Status ReadGetReply(uint8_t* data, ObjectID object_ids[], PlasmaObject plasma_objects[], + int64_t num_objects) { DCHECK(data); auto message = flatbuffers::GetRoot(data); for (uoffset_t i = 0; i < num_objects; ++i) { object_ids[i] = ObjectID::from_binary(message->object_ids()->Get(i)->str()); } for (uoffset_t i = 0; i < num_objects; ++i) { - const PlasmaObjectSpec *object = message->plasma_objects()->Get(i); + const PlasmaObjectSpec* object = message->plasma_objects()->Get(i); plasma_objects[i].handle.store_fd = object->segment_index(); plasma_objects[i].handle.mmap_size = object->mmap_size(); plasma_objects[i].data_offset = object->data_offset(); @@ -436,98 +403,86 @@ Status ReadGetReply(uint8_t *data, Status SendFetchRequest(int sock, ObjectID object_ids[], int64_t num_objects) { flatbuffers::FlatBufferBuilder fbb; - auto message = CreatePlasmaFetchRequest( - fbb, to_flatbuffer(fbb, object_ids, num_objects)); + auto message = + CreatePlasmaFetchRequest(fbb, to_flatbuffer(fbb, object_ids, num_objects)); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaFetchRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaFetchRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadFetchRequest(uint8_t *data, std::vector &object_ids) { +Status ReadFetchRequest(uint8_t* data, std::vector& object_ids) { DCHECK(data); auto message = flatbuffers::GetRoot(data); for (uoffset_t i = 0; i < message->object_ids()->size(); ++i) { - object_ids.push_back( - ObjectID::from_binary(message->object_ids()->Get(i)->str())); + object_ids.push_back(ObjectID::from_binary(message->object_ids()->Get(i)->str())); } return Status::OK(); } /* Wait messages. */ -Status SendWaitRequest(int sock, - ObjectRequest object_requests[], - int64_t num_requests, - int num_ready_objects, - int64_t timeout_ms) { +Status SendWaitRequest(int sock, ObjectRequest object_requests[], int64_t num_requests, + int num_ready_objects, int64_t timeout_ms) { flatbuffers::FlatBufferBuilder fbb; std::vector> object_request_specs; for (int i = 0; i < num_requests; i++) { - object_request_specs.push_back(CreateObjectRequestSpec( - fbb, fbb.CreateString(object_requests[i].object_id.binary()), + object_request_specs.push_back(CreateObjectRequestSpec(fbb, + fbb.CreateString(object_requests[i].object_id.binary()), object_requests[i].type)); } - auto message = - CreatePlasmaWaitRequest(fbb, fbb.CreateVector(object_request_specs), - num_ready_objects, timeout_ms); + auto message = CreatePlasmaWaitRequest( + fbb, fbb.CreateVector(object_request_specs), num_ready_objects, timeout_ms); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaWaitRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaWaitRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadWaitRequest(uint8_t *data, - ObjectRequestMap &object_requests, - int64_t *timeout_ms, - int *num_ready_objects) { +Status ReadWaitRequest(uint8_t* data, ObjectRequestMap& object_requests, + int64_t* timeout_ms, int* num_ready_objects) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *num_ready_objects = message->num_ready_objects(); *timeout_ms = message->timeout(); for (uoffset_t i = 0; i < message->object_requests()->size(); i++) { - ObjectID object_id = ObjectID::from_binary( - message->object_requests()->Get(i)->object_id()->str()); - ObjectRequest object_request({object_id, - message->object_requests()->Get(i)->type(), - ObjectStatus_Nonexistent}); + ObjectID object_id = + ObjectID::from_binary(message->object_requests()->Get(i)->object_id()->str()); + ObjectRequest object_request({object_id, message->object_requests()->Get(i)->type(), + ObjectStatus_Nonexistent}); object_requests[object_id] = object_request; } return Status::OK(); } -Status SendWaitReply(int sock, - const ObjectRequestMap &object_requests, - int num_ready_objects) { +Status SendWaitReply( + int sock, const ObjectRequestMap& object_requests, int num_ready_objects) { flatbuffers::FlatBufferBuilder fbb; std::vector> object_replies; - for (const auto &entry : object_requests) { - const auto &object_request = entry.second; + for (const auto& entry : object_requests) { + const auto& object_request = entry.second; object_replies.push_back(CreateObjectReply( - fbb, fbb.CreateString(object_request.object_id.binary()), - object_request.status)); + fbb, fbb.CreateString(object_request.object_id.binary()), object_request.status)); } auto message = CreatePlasmaWaitReply( - fbb, fbb.CreateVector(object_replies.data(), num_ready_objects), - num_ready_objects); + fbb, fbb.CreateVector(object_replies.data(), num_ready_objects), num_ready_objects); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaWaitReply, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaWaitReply, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadWaitReply(uint8_t *data, - ObjectRequest object_requests[], - int *num_ready_objects) { +Status ReadWaitReply( + uint8_t* data, ObjectRequest object_requests[], int* num_ready_objects) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *num_ready_objects = message->num_ready_objects(); for (int i = 0; i < *num_ready_objects; i++) { - object_requests[i].object_id = ObjectID::from_binary( - message->object_requests()->Get(i)->object_id()->str()); + object_requests[i].object_id = + ObjectID::from_binary(message->object_requests()->Get(i)->object_id()->str()); object_requests[i].status = message->object_requests()->Get(i)->status(); } return Status::OK(); @@ -539,29 +494,23 @@ Status SendSubscribeRequest(int sock) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaSubscribeRequest(fbb); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaSubscribeRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaSubscribeRequest, fbb.GetSize(), fbb.GetBufferPointer()); } /* Data messages. */ -Status SendDataRequest(int sock, - ObjectID object_id, - const char *address, - int port) { +Status SendDataRequest(int sock, ObjectID object_id, const char* address, int port) { flatbuffers::FlatBufferBuilder fbb; auto addr = fbb.CreateString(address, strlen(address)); - auto message = CreatePlasmaDataRequest( - fbb, fbb.CreateString(object_id.binary()), addr, port); + auto message = + CreatePlasmaDataRequest(fbb, fbb.CreateString(object_id.binary()), addr, port); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaDataRequest, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaDataRequest, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadDataRequest(uint8_t *data, - ObjectID *object_id, - char **address, - int *port) { +Status ReadDataRequest(uint8_t* data, ObjectID* object_id, char** address, int* port) { DCHECK(data); auto message = flatbuffers::GetRoot(data); DCHECK(message->object_id()->size() == sizeof(ObjectID)); @@ -571,26 +520,22 @@ Status ReadDataRequest(uint8_t *data, return Status::OK(); } -Status SendDataReply(int sock, - ObjectID object_id, - int64_t object_size, - int64_t metadata_size) { +Status SendDataReply( + int sock, ObjectID object_id, int64_t object_size, int64_t metadata_size) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaDataReply( fbb, fbb.CreateString(object_id.binary()), object_size, metadata_size); fbb.Finish(message); - return WriteMessage(sock, MessageType_PlasmaDataReply, fbb.GetSize(), - fbb.GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaDataReply, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadDataReply(uint8_t *data, - ObjectID *object_id, - int64_t *object_size, - int64_t *metadata_size) { +Status ReadDataReply( + uint8_t* data, ObjectID* object_id, int64_t* object_size, int64_t* metadata_size) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *object_id = ObjectID::from_binary(message->object_id()->str()); - *object_size = (int64_t) message->object_size(); - *metadata_size = (int64_t) message->metadata_size(); + *object_size = (int64_t)message->object_size(); + *metadata_size = (int64_t)message->metadata_size(); return Status::OK(); } diff --git a/cpp/src/plasma/protocol.h b/cpp/src/plasma/protocol.h index 72b18c81da9..118ab7474c0 100644 --- a/cpp/src/plasma/protocol.h +++ b/cpp/src/plasma/protocol.h @@ -28,161 +28,128 @@ using arrow::Status; /* Plasma receive message. */ -Status PlasmaReceive(int sock, - int64_t message_type, - std::vector &buffer); +Status PlasmaReceive(int sock, int64_t message_type, std::vector& buffer); /* Plasma Create message functions. */ -Status SendCreateRequest(int sock, - ObjectID object_id, - int64_t data_size, - int64_t metadata_size); +Status SendCreateRequest( + int sock, ObjectID object_id, int64_t data_size, int64_t metadata_size); -Status ReadCreateRequest(uint8_t *data, - ObjectID *object_id, - int64_t *data_size, - int64_t *metadata_size); +Status ReadCreateRequest( + uint8_t* data, ObjectID* object_id, int64_t* data_size, int64_t* metadata_size); -Status SendCreateReply(int sock, - ObjectID object_id, - PlasmaObject *object, - int error); +Status SendCreateReply(int sock, ObjectID object_id, PlasmaObject* object, int error); -Status ReadCreateReply(uint8_t *data, - ObjectID *object_id, - PlasmaObject *object); +Status ReadCreateReply(uint8_t* data, ObjectID* object_id, PlasmaObject* object); /* Plasma Seal message functions. */ -Status SendSealRequest(int sock, ObjectID object_id, unsigned char *digest); +Status SendSealRequest(int sock, ObjectID object_id, unsigned char* digest); -Status ReadSealRequest(uint8_t *data, - ObjectID *object_id, - unsigned char *digest); +Status ReadSealRequest(uint8_t* data, ObjectID* object_id, unsigned char* digest); Status SendSealReply(int sock, ObjectID object_id, int error); -Status ReadSealReply(uint8_t *data, ObjectID *object_id); +Status ReadSealReply(uint8_t* data, ObjectID* object_id); /* Plasma Get message functions. */ -Status SendGetRequest(int sock, - ObjectID object_ids[], - int64_t num_objects, - int64_t timeout_ms); +Status SendGetRequest( + int sock, ObjectID object_ids[], int64_t num_objects, int64_t timeout_ms); -Status ReadGetRequest(uint8_t *data, - std::vector &object_ids, - int64_t *timeout_ms); +Status ReadGetRequest( + uint8_t* data, std::vector& object_ids, int64_t* timeout_ms); -Status SendGetReply( - int sock, - ObjectID object_ids[], - std::unordered_map &plasma_objects, +Status SendGetReply(int sock, ObjectID object_ids[], + std::unordered_map& plasma_objects, int64_t num_objects); -Status ReadGetReply(uint8_t *data, - ObjectID object_ids[], - PlasmaObject plasma_objects[], - int64_t num_objects); +Status ReadGetReply(uint8_t* data, ObjectID object_ids[], PlasmaObject plasma_objects[], + int64_t num_objects); /* Plasma Release message functions. */ Status SendReleaseRequest(int sock, ObjectID object_id); -Status ReadReleaseRequest(uint8_t *data, ObjectID *object_id); +Status ReadReleaseRequest(uint8_t* data, ObjectID* object_id); Status SendReleaseReply(int sock, ObjectID object_id, int error); -Status ReadReleaseReply(uint8_t *data, ObjectID *object_id); +Status ReadReleaseReply(uint8_t* data, ObjectID* object_id); /* Plasma Delete message functions. */ Status SendDeleteRequest(int sock, ObjectID object_id); -Status ReadDeleteRequest(uint8_t *data, ObjectID *object_id); +Status ReadDeleteRequest(uint8_t* data, ObjectID* object_id); Status SendDeleteReply(int sock, ObjectID object_id, int error); -Status ReadDeleteReply(uint8_t *data, ObjectID *object_id); +Status ReadDeleteReply(uint8_t* data, ObjectID* object_id); /* Satus messages. */ Status SendStatusRequest(int sock, ObjectID object_ids[], int64_t num_objects); -Status ReadStatusRequest(uint8_t *data, - ObjectID object_ids[], - int64_t num_objects); +Status ReadStatusRequest(uint8_t* data, ObjectID object_ids[], int64_t num_objects); -Status SendStatusReply(int sock, - ObjectID object_ids[], - int object_status[], - int64_t num_objects); +Status SendStatusReply( + int sock, ObjectID object_ids[], int object_status[], int64_t num_objects); -int64_t ReadStatusReply_num_objects(uint8_t *data); +int64_t ReadStatusReply_num_objects(uint8_t* data); -Status ReadStatusReply(uint8_t *data, - ObjectID object_ids[], - int object_status[], - int64_t num_objects); +Status ReadStatusReply( + uint8_t* data, ObjectID object_ids[], int object_status[], int64_t num_objects); /* Plasma Constains message functions. */ Status SendContainsRequest(int sock, ObjectID object_id); -Status ReadContainsRequest(uint8_t *data, ObjectID *object_id); +Status ReadContainsRequest(uint8_t* data, ObjectID* object_id); Status SendContainsReply(int sock, ObjectID object_id, int has_object); -Status ReadContainsReply(uint8_t *data, ObjectID *object_id, int *has_object); +Status ReadContainsReply(uint8_t* data, ObjectID* object_id, int* has_object); /* Plasma Connect message functions. */ Status SendConnectRequest(int sock); -Status ReadConnectRequest(uint8_t *data); +Status ReadConnectRequest(uint8_t* data); Status SendConnectReply(int sock, int64_t memory_capacity); -Status ReadConnectReply(uint8_t *data, int64_t *memory_capacity); +Status ReadConnectReply(uint8_t* data, int64_t* memory_capacity); /* Plasma Evict message functions (no reply so far). */ Status SendEvictRequest(int sock, int64_t num_bytes); -Status ReadEvictRequest(uint8_t *data, int64_t *num_bytes); +Status ReadEvictRequest(uint8_t* data, int64_t* num_bytes); Status SendEvictReply(int sock, int64_t num_bytes); -Status ReadEvictReply(uint8_t *data, int64_t &num_bytes); +Status ReadEvictReply(uint8_t* data, int64_t& num_bytes); /* Plasma Fetch Remote message functions. */ Status SendFetchRequest(int sock, ObjectID object_ids[], int64_t num_objects); -Status ReadFetchRequest(uint8_t *data, std::vector &object_ids); +Status ReadFetchRequest(uint8_t* data, std::vector& object_ids); /* Plasma Wait message functions. */ -Status SendWaitRequest(int sock, - ObjectRequest object_requests[], - int64_t num_requests, - int num_ready_objects, - int64_t timeout_ms); +Status SendWaitRequest(int sock, ObjectRequest object_requests[], int64_t num_requests, + int num_ready_objects, int64_t timeout_ms); -Status ReadWaitRequest(uint8_t *data, - ObjectRequestMap &object_requests, - int64_t *timeout_ms, - int *num_ready_objects); +Status ReadWaitRequest(uint8_t* data, ObjectRequestMap& object_requests, + int64_t* timeout_ms, int* num_ready_objects); -Status SendWaitReply(int sock, - const ObjectRequestMap &object_requests, - int num_ready_objects); +Status SendWaitReply( + int sock, const ObjectRequestMap& object_requests, int num_ready_objects); -Status ReadWaitReply(uint8_t *data, - ObjectRequest object_requests[], - int *num_ready_objects); +Status ReadWaitReply( + uint8_t* data, ObjectRequest object_requests[], int* num_ready_objects); /* Plasma Subscribe message functions. */ @@ -190,24 +157,14 @@ Status SendSubscribeRequest(int sock); /* Data messages. */ -Status SendDataRequest(int sock, - ObjectID object_id, - const char *address, - int port); - -Status ReadDataRequest(uint8_t *data, - ObjectID *object_id, - char **address, - int *port); - -Status SendDataReply(int sock, - ObjectID object_id, - int64_t object_size, - int64_t metadata_size); - -Status ReadDataReply(uint8_t *data, - ObjectID *object_id, - int64_t *object_size, - int64_t *metadata_size); +Status SendDataRequest(int sock, ObjectID object_id, const char* address, int port); + +Status ReadDataRequest(uint8_t* data, ObjectID* object_id, char** address, int* port); + +Status SendDataReply( + int sock, ObjectID object_id, int64_t object_size, int64_t metadata_size); + +Status ReadDataReply( + uint8_t* data, ObjectID* object_id, int64_t* object_size, int64_t* metadata_size); #endif /* PLASMA_PROTOCOL */ diff --git a/cpp/src/plasma/store.cc b/cpp/src/plasma/store.cc index 918f39a56fd..73fddc2f354 100644 --- a/cpp/src/plasma/store.cc +++ b/cpp/src/plasma/store.cc @@ -27,19 +27,19 @@ // just enough to store and SHA1 hash) to memory mapped files. #include +#include +#include +#include +#include #include #include -#include -#include +#include #include #include #include #include #include -#include -#include -#include -#include +#include #include #include @@ -47,25 +47,25 @@ #include #include -#include "plasma/common.h" -#include "plasma/store.h" -#include "plasma/io.h" #include "format/common_generated.h" +#include "plasma/common.h" #include "plasma/fling.h" +#include "plasma/io.h" #include "plasma/malloc.h" +#include "plasma/store.h" extern "C" { -void *dlmalloc(size_t bytes); -void *dlmemalign(size_t alignment, size_t bytes); -void dlfree(void * mem); +void* dlmalloc(size_t bytes); +void* dlmemalign(size_t alignment, size_t bytes); +void dlfree(void* mem); size_t dlmalloc_set_footprint_limit(size_t bytes); } class GetRequest { public: - GetRequest(Client *client, const std::vector &object_ids); + GetRequest(Client* client, const std::vector& object_ids); /// The client that called get. - Client *client; + Client* client; /// The ID of the timer that will time out and cause this wait to return to /// the client if it hasn't already returned. int64_t timer; @@ -81,30 +81,30 @@ class GetRequest { int64_t num_satisfied; }; -GetRequest::GetRequest(Client *client, const std::vector &object_ids) +GetRequest::GetRequest(Client* client, const std::vector& object_ids) : client(client), timer(-1), object_ids(object_ids.begin(), object_ids.end()), objects(object_ids.size()), num_satisfied(0) { - std::unordered_set unique_ids(object_ids.begin(), - object_ids.end()); + std::unordered_set unique_ids( + object_ids.begin(), object_ids.end()); num_objects_to_wait_for = unique_ids.size(); } Client::Client(int fd) : fd(fd) {} -PlasmaStore::PlasmaStore(EventLoop *loop, int64_t system_memory) +PlasmaStore::PlasmaStore(EventLoop* loop, int64_t system_memory) : loop_(loop), eviction_policy_(&store_info_) { store_info_.memory_capacity = system_memory; } PlasmaStore::~PlasmaStore() { - for (const auto &element : pending_notifications_) { + for (const auto& element : pending_notifications_) { auto object_notifications = element.second.object_notifications; for (size_t i = 0; i < object_notifications.size(); ++i) { - uint8_t *notification = reinterpret_cast(object_notifications.at(i)); - uint8_t *data = notification; + uint8_t* notification = reinterpret_cast(object_notifications.at(i)); + uint8_t* data = notification; delete[] data; } } @@ -112,12 +112,9 @@ PlasmaStore::~PlasmaStore() { // If this client is not already using the object, add the client to the // object's list of clients, otherwise do nothing. -void PlasmaStore::add_client_to_object_clients(ObjectTableEntry *entry, - Client *client) { +void PlasmaStore::add_client_to_object_clients(ObjectTableEntry* entry, Client* client) { // Check if this client is already using the object. - if (entry->clients.find(client) != entry->clients.end()) { - return; - } + if (entry->clients.find(client) != entry->clients.end()) { return; } // If there are no other clients using this object, notify the eviction policy // that the object is being used. if (entry->clients.size() == 0) { @@ -131,11 +128,8 @@ void PlasmaStore::add_client_to_object_clients(ObjectTableEntry *entry, } // Create a new object buffer in the hash table. -int PlasmaStore::create_object(ObjectID object_id, - int64_t data_size, - int64_t metadata_size, - Client *client, - PlasmaObject *result) { +int PlasmaStore::create_object(ObjectID object_id, int64_t data_size, + int64_t metadata_size, Client* client, PlasmaObject* result) { ARROW_LOG(DEBUG) << "creating object " << object_id.hex(); if (store_info_.objects.count(object_id) != 0) { // There is already an object with the same ID in the Plasma Store, so @@ -143,7 +137,7 @@ int PlasmaStore::create_object(ObjectID object_id, return PlasmaError_ObjectExists; } // Try to evict objects until there is enough space. - uint8_t *pointer; + uint8_t* pointer; do { // Allocate space for the new object. We use dlmemalign instead of dlmalloc // in order to align the allocated region to a 64-byte boundary. This is not @@ -152,19 +146,17 @@ int PlasmaStore::create_object(ObjectID object_id, // plasma_client.cc). Note that even though this pointer is 64-byte aligned, // it is not guaranteed that the corresponding pointer in the client will be // 64-byte aligned, but in practice it often will be. - pointer = reinterpret_cast( - dlmemalign(BLOCK_SIZE, data_size + metadata_size)); + pointer = + reinterpret_cast(dlmemalign(BLOCK_SIZE, data_size + metadata_size)); if (pointer == NULL) { // Tell the eviction policy how much space we need to create this object. std::vector objects_to_evict; - bool success = eviction_policy_.require_space(data_size + metadata_size, - objects_to_evict); + bool success = + eviction_policy_.require_space(data_size + metadata_size, objects_to_evict); delete_objects(objects_to_evict); // Return an error to the client if not enough space could be freed to // create the object. - if (!success) { - return PlasmaError_OutOfMemory; - } + if (!success) { return PlasmaError_OutOfMemory; } } } while (pointer == NULL); int fd; @@ -201,7 +193,7 @@ int PlasmaStore::create_object(ObjectID object_id, return PlasmaError_OK; } -void PlasmaObject_init(PlasmaObject *object, ObjectTableEntry *entry) { +void PlasmaObject_init(PlasmaObject* object, ObjectTableEntry* entry) { DCHECK(object != NULL); DCHECK(entry != NULL); DCHECK(entry->state == PLASMA_SEALED); @@ -213,17 +205,17 @@ void PlasmaObject_init(PlasmaObject *object, ObjectTableEntry *entry) { object->metadata_size = entry->info.metadata_size; } -void PlasmaStore::return_from_get(GetRequest *get_req) { +void PlasmaStore::return_from_get(GetRequest* get_req) { // Send the get reply to the client. - Status s = SendGetReply(get_req->client->fd, &get_req->object_ids[0], - get_req->objects, get_req->object_ids.size()); + Status s = SendGetReply(get_req->client->fd, &get_req->object_ids[0], get_req->objects, + get_req->object_ids.size()); warn_if_sigpipe(s.ok() ? 0 : -1, get_req->client->fd); // If we successfully sent the get reply message to the client, then also send // the file descriptors. if (s.ok()) { // Send all of the file descriptors for the present objects. - for (const auto &object_id : get_req->object_ids) { - PlasmaObject &object = get_req->objects[object_id]; + for (const auto& object_id : get_req->object_ids) { + PlasmaObject& object = get_req->objects[object_id]; // We use the data size to indicate whether the object is present or not. if (object.data_size != -1) { int error_code = send_fd(get_req->client->fd, object.handle.store_fd); @@ -249,27 +241,23 @@ void PlasmaStore::return_from_get(GetRequest *get_req) { // Remove the get request from each of the relevant object_get_requests hash // tables if it is present there. It should only be present there if the get // request timed out. - for (ObjectID &object_id : get_req->object_ids) { - auto &get_requests = object_get_requests_[object_id]; + for (ObjectID& object_id : get_req->object_ids) { + auto& get_requests = object_get_requests_[object_id]; // Erase get_req from the vector. auto it = std::find(get_requests.begin(), get_requests.end(), get_req); - if (it != get_requests.end()) { - get_requests.erase(it); - } + if (it != get_requests.end()) { get_requests.erase(it); } } // Remove the get request. - if (get_req->timer != -1) { - ARROW_CHECK(loop_->remove_timer(get_req->timer) == AE_OK); - } + if (get_req->timer != -1) { ARROW_CHECK(loop_->remove_timer(get_req->timer) == AE_OK); } delete get_req; } void PlasmaStore::update_object_get_requests(ObjectID object_id) { - std::vector &get_requests = object_get_requests_[object_id]; + std::vector& get_requests = object_get_requests_[object_id]; size_t index = 0; size_t num_requests = get_requests.size(); for (size_t i = 0; i < num_requests; ++i) { - GetRequest *get_req = get_requests[index]; + GetRequest* get_req = get_requests[index]; auto entry = get_object_table_entry(&store_info_, object_id); ARROW_CHECK(entry != NULL); @@ -295,11 +283,10 @@ void PlasmaStore::update_object_get_requests(ObjectID object_id) { object_get_requests_.erase(object_id); } -void PlasmaStore::process_get_request(Client *client, - const std::vector &object_ids, - int64_t timeout_ms) { +void PlasmaStore::process_get_request( + Client* client, const std::vector& object_ids, int64_t timeout_ms) { // Create a get request for this object. - GetRequest *get_req = new GetRequest(client, object_ids); + GetRequest* get_req = new GetRequest(client, object_ids); for (auto object_id : object_ids) { // Check if this object is already present locally. If so, record that the @@ -324,22 +311,20 @@ void PlasmaStore::process_get_request(Client *client, // If all of the objects are present already or if the timeout is 0, return to // the client. - if (get_req->num_satisfied == get_req->num_objects_to_wait_for || - timeout_ms == 0) { + if (get_req->num_satisfied == get_req->num_objects_to_wait_for || timeout_ms == 0) { return_from_get(get_req); } else if (timeout_ms != -1) { // Set a timer that will cause the get request to return to the client. Note // that a timeout of -1 is used to indicate that no timer should be set. - get_req->timer = - loop_->add_timer(timeout_ms, [this, get_req](int64_t timer_id) { - return_from_get(get_req); - return kEventLoopTimerDone; - }); + get_req->timer = loop_->add_timer(timeout_ms, [this, get_req](int64_t timer_id) { + return_from_get(get_req); + return kEventLoopTimerDone; + }); } } -int PlasmaStore::remove_client_from_object_clients(ObjectTableEntry *entry, - Client *client) { +int PlasmaStore::remove_client_from_object_clients( + ObjectTableEntry* entry, Client* client) { auto it = entry->clients.find(client); if (it != entry->clients.end()) { entry->clients.erase(it); @@ -359,7 +344,7 @@ int PlasmaStore::remove_client_from_object_clients(ObjectTableEntry *entry, } } -void PlasmaStore::release_object(ObjectID object_id, Client *client) { +void PlasmaStore::release_object(ObjectID object_id, Client* client) { auto entry = get_object_table_entry(&store_info_, object_id); ARROW_CHECK(entry != NULL); // Remove the client from the object's array of clients. @@ -369,8 +354,7 @@ void PlasmaStore::release_object(ObjectID object_id, Client *client) { // Check if an object is present. int PlasmaStore::contains_object(ObjectID object_id) { auto entry = get_object_table_entry(&store_info_, object_id); - return entry && (entry->state == PLASMA_SEALED) ? OBJECT_FOUND - : OBJECT_NOT_FOUND; + return entry && (entry->state == PLASMA_SEALED) ? OBJECT_FOUND : OBJECT_NOT_FOUND; } // Seal an object that has been created in the hash table. @@ -382,7 +366,7 @@ void PlasmaStore::seal_object(ObjectID object_id, unsigned char digest[]) { // Set the state of object to SEALED. entry->state = PLASMA_SEALED; // Set the object digest. - entry->info.digest = std::string(reinterpret_cast(&digest[0]), kDigestSize); + entry->info.digest = std::string(reinterpret_cast(&digest[0]), kDigestSize); // Inform all subscribers that a new object has been sealed. push_notification(&entry->info); @@ -390,15 +374,14 @@ void PlasmaStore::seal_object(ObjectID object_id, unsigned char digest[]) { update_object_get_requests(object_id); } -void PlasmaStore::delete_objects(const std::vector &object_ids) { - for (const auto &object_id : object_ids) { +void PlasmaStore::delete_objects(const std::vector& object_ids) { + for (const auto& object_id : object_ids) { ARROW_LOG(DEBUG) << "deleting object " << object_id.hex(); auto entry = get_object_table_entry(&store_info_, object_id); // TODO(rkn): This should probably not fail, but should instead throw an // error. Maybe we should also support deleting objects that have been // created but not sealed. - ARROW_CHECK(entry != NULL) - << "To delete an object it must be in the object table."; + ARROW_CHECK(entry != NULL) << "To delete an object it must be in the object table."; ARROW_CHECK(entry->state == PLASMA_SEALED) << "To delete an object it must have been sealed."; ARROW_CHECK(entry->clients.size() == 0) @@ -416,16 +399,15 @@ void PlasmaStore::delete_objects(const std::vector &object_ids) { void PlasmaStore::connect_client(int listener_sock) { int client_fd = AcceptClient(listener_sock); // This is freed in disconnect_client. - Client *client = new Client(client_fd); + Client* client = new Client(client_fd); // Add a callback to handle events on this socket. // TODO(pcm): Check return value. - loop_->add_file_event(client_fd, kEventLoopRead, [this, client](int events) { - process_message(client); - }); + loop_->add_file_event( + client_fd, kEventLoopRead, [this, client](int events) { process_message(client); }); ARROW_LOG(DEBUG) << "New connection with fd " << client_fd; } -void PlasmaStore::disconnect_client(Client *client) { +void PlasmaStore::disconnect_client(Client* client) { ARROW_CHECK(client != NULL); ARROW_CHECK(client->fd > 0); loop_->remove_file_event(client->fd); @@ -434,7 +416,7 @@ void PlasmaStore::disconnect_client(Client *client) { ARROW_LOG(INFO) << "Disconnecting client on fd " << client->fd; // If this client was using any objects, remove it from the appropriate // lists. - for (const auto &entry : store_info_.objects) { + for (const auto& entry : store_info_.objects) { remove_client_from_object_clients(entry.second.get(), client); } // Note, the store may still attempt to send a message to the disconnected @@ -459,10 +441,10 @@ void PlasmaStore::send_notifications(int client_fd) { // Loop over the array of pending notifications and send as many of them as // possible. for (size_t i = 0; i < it->second.object_notifications.size(); ++i) { - uint8_t *notification = - reinterpret_cast(it->second.object_notifications.at(i)); + uint8_t* notification = + reinterpret_cast(it->second.object_notifications.at(i)); // Decode the length, which is the first bytes of the message. - int64_t size = *(reinterpret_cast(notification)); + int64_t size = *(reinterpret_cast(notification)); // Attempt to send a notification about this object ID. ssize_t nbytes = send(client_fd, notification, sizeof(int64_t) + size, 0); @@ -470,22 +452,19 @@ void PlasmaStore::send_notifications(int client_fd) { ARROW_CHECK(nbytes == static_cast(sizeof(int64_t)) + size); } else if (nbytes == -1 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) { - ARROW_LOG(DEBUG) - << "The socket's send buffer is full, so we are caching this " - "notification and will send it later."; + ARROW_LOG(DEBUG) << "The socket's send buffer is full, so we are caching this " + "notification and will send it later."; // Add a callback to the event loop to send queued notifications whenever // there is room in the socket's send buffer. Callbacks can be added // more than once here and will be overwritten. The callback is removed // at the end of the method. // TODO(pcm): Introduce status codes and check in case the file descriptor // is added twice. - loop_->add_file_event( - client_fd, kEventLoopWrite, + loop_->add_file_event(client_fd, kEventLoopWrite, [this, client_fd](int events) { send_notifications(client_fd); }); break; } else { - ARROW_LOG(WARNING) << "Failed to send notification to client on fd " - << client_fd; + ARROW_LOG(WARNING) << "Failed to send notification to client on fd " << client_fd; if (errno == EPIPE) { closed = true; break; @@ -497,8 +476,7 @@ void PlasmaStore::send_notifications(int client_fd) { delete[] notification; } // Remove the sent notifications from the array. - it->second.object_notifications.erase( - it->second.object_notifications.begin(), + it->second.object_notifications.erase(it->second.object_notifications.begin(), it->second.object_notifications.begin() + num_processed); // Stop sending notifications if the pipe was broken. @@ -508,14 +486,12 @@ void PlasmaStore::send_notifications(int client_fd) { } // If we have sent all notifications, remove the fd from the event loop. - if (it->second.object_notifications.empty()) { - loop_->remove_file_event(client_fd); - } + if (it->second.object_notifications.empty()) { loop_->remove_file_event(client_fd); } } -void PlasmaStore::push_notification(ObjectInfoT *object_info) { - for (auto &element : pending_notifications_) { - uint8_t *notification = create_object_info_buffer(object_info); +void PlasmaStore::push_notification(ObjectInfoT* object_info) { + for (auto& element : pending_notifications_) { + uint8_t* notification = create_object_info_buffer(object_info); element.second.object_notifications.push_back(notification); send_notifications(element.first); // The notification gets freed in send_notifications when the notification @@ -524,7 +500,7 @@ void PlasmaStore::push_notification(ObjectInfoT *object_info) { } // Subscribe to notifications about sealed objects. -void PlasmaStore::subscribe_to_updates(Client *client) { +void PlasmaStore::subscribe_to_updates(Client* client) { ARROW_LOG(DEBUG) << "subscribing to updates on fd " << client->fd; // TODO(rkn): The store could block here if the client doesn't send a file // descriptor. @@ -543,18 +519,18 @@ void PlasmaStore::subscribe_to_updates(Client *client) { pending_notifications_[fd]; // Push notifications to the new subscriber about existing objects. - for (const auto &entry : store_info_.objects) { + for (const auto& entry : store_info_.objects) { push_notification(&entry.second->info); } send_notifications(fd); } -Status PlasmaStore::process_message(Client *client) { +Status PlasmaStore::process_message(Client* client) { int64_t type; Status s = ReadMessage(client->fd, &type, input_buffer_); ARROW_CHECK(s.ok() || s.IsIOError()); - uint8_t *input = input_buffer_.data(); + uint8_t* input = input_buffer_.data(); ObjectID object_id; PlasmaObject object; // TODO(pcm): Get rid of the following. @@ -562,78 +538,75 @@ Status PlasmaStore::process_message(Client *client) { // Process the different types of requests. switch (type) { - case MessageType_PlasmaCreateRequest: { - int64_t data_size; - int64_t metadata_size; - RETURN_NOT_OK( - ReadCreateRequest(input, &object_id, &data_size, &metadata_size)); - int error_code = - create_object(object_id, data_size, metadata_size, client, &object); - HANDLE_SIGPIPE(SendCreateReply(client->fd, object_id, &object, error_code), - client->fd); - if (error_code == PlasmaError_OK) { - warn_if_sigpipe(send_fd(client->fd, object.handle.store_fd), client->fd); - } - } break; - case MessageType_PlasmaGetRequest: { - std::vector object_ids_to_get; - int64_t timeout_ms; - RETURN_NOT_OK(ReadGetRequest(input, object_ids_to_get, &timeout_ms)); - process_get_request(client, object_ids_to_get, timeout_ms); - } break; - case MessageType_PlasmaReleaseRequest: - RETURN_NOT_OK(ReadReleaseRequest(input, &object_id)); - release_object(object_id, client); - break; - case MessageType_PlasmaContainsRequest: - RETURN_NOT_OK(ReadContainsRequest(input, &object_id)); - if (contains_object(object_id) == OBJECT_FOUND) { - HANDLE_SIGPIPE(SendContainsReply(client->fd, object_id, 1), client->fd); - } else { - HANDLE_SIGPIPE(SendContainsReply(client->fd, object_id, 0), client->fd); - } - break; - case MessageType_PlasmaSealRequest: { - unsigned char digest[kDigestSize]; - RETURN_NOT_OK(ReadSealRequest(input, &object_id, &digest[0])); - seal_object(object_id, &digest[0]); - } break; - case MessageType_PlasmaEvictRequest: { - // This code path should only be used for testing. - int64_t num_bytes; - RETURN_NOT_OK(ReadEvictRequest(input, &num_bytes)); - std::vector objects_to_evict; - int64_t num_bytes_evicted = - eviction_policy_.choose_objects_to_evict(num_bytes, objects_to_evict); - delete_objects(objects_to_evict); - HANDLE_SIGPIPE(SendEvictReply(client->fd, num_bytes_evicted), client->fd); - } break; - case MessageType_PlasmaSubscribeRequest: - subscribe_to_updates(client); - break; - case MessageType_PlasmaConnectRequest: { - HANDLE_SIGPIPE(SendConnectReply(client->fd, store_info_.memory_capacity), - client->fd); - } break; - case DISCONNECT_CLIENT: - ARROW_LOG(DEBUG) << "Disconnecting client on fd " << client->fd; - disconnect_client(client); - break; - default: - // This code should be unreachable. - ARROW_CHECK(0); + case MessageType_PlasmaCreateRequest: { + int64_t data_size; + int64_t metadata_size; + RETURN_NOT_OK(ReadCreateRequest(input, &object_id, &data_size, &metadata_size)); + int error_code = + create_object(object_id, data_size, metadata_size, client, &object); + HANDLE_SIGPIPE( + SendCreateReply(client->fd, object_id, &object, error_code), client->fd); + if (error_code == PlasmaError_OK) { + warn_if_sigpipe(send_fd(client->fd, object.handle.store_fd), client->fd); + } + } break; + case MessageType_PlasmaGetRequest: { + std::vector object_ids_to_get; + int64_t timeout_ms; + RETURN_NOT_OK(ReadGetRequest(input, object_ids_to_get, &timeout_ms)); + process_get_request(client, object_ids_to_get, timeout_ms); + } break; + case MessageType_PlasmaReleaseRequest: + RETURN_NOT_OK(ReadReleaseRequest(input, &object_id)); + release_object(object_id, client); + break; + case MessageType_PlasmaContainsRequest: + RETURN_NOT_OK(ReadContainsRequest(input, &object_id)); + if (contains_object(object_id) == OBJECT_FOUND) { + HANDLE_SIGPIPE(SendContainsReply(client->fd, object_id, 1), client->fd); + } else { + HANDLE_SIGPIPE(SendContainsReply(client->fd, object_id, 0), client->fd); + } + break; + case MessageType_PlasmaSealRequest: { + unsigned char digest[kDigestSize]; + RETURN_NOT_OK(ReadSealRequest(input, &object_id, &digest[0])); + seal_object(object_id, &digest[0]); + } break; + case MessageType_PlasmaEvictRequest: { + // This code path should only be used for testing. + int64_t num_bytes; + RETURN_NOT_OK(ReadEvictRequest(input, &num_bytes)); + std::vector objects_to_evict; + int64_t num_bytes_evicted = + eviction_policy_.choose_objects_to_evict(num_bytes, objects_to_evict); + delete_objects(objects_to_evict); + HANDLE_SIGPIPE(SendEvictReply(client->fd, num_bytes_evicted), client->fd); + } break; + case MessageType_PlasmaSubscribeRequest: + subscribe_to_updates(client); + break; + case MessageType_PlasmaConnectRequest: { + HANDLE_SIGPIPE( + SendConnectReply(client->fd, store_info_.memory_capacity), client->fd); + } break; + case DISCONNECT_CLIENT: + ARROW_LOG(DEBUG) << "Disconnecting client on fd " << client->fd; + disconnect_client(client); + break; + default: + // This code should be unreachable. + ARROW_CHECK(0); } return Status::OK(); } // Report "success" to valgrind. void signal_handler(int signal) { - if (signal == SIGTERM) { - exit(0); - } + if (signal == SIGTERM) { exit(0); } } -void start_server(char *socket_name, int64_t system_memory) { +void start_server(char* socket_name, int64_t system_memory) { // Ignore SIGPIPE signals. If we don't do this, then when we attempt to write // to a client that has already died, the store could die. signal(SIGPIPE, SIG_IGN); @@ -643,42 +616,39 @@ void start_server(char *socket_name, int64_t system_memory) { int socket = bind_ipc_sock(socket_name, true); ARROW_CHECK(socket >= 0); // TODO(pcm): Check return value. - loop.add_file_event(socket, kEventLoopRead, [&store, socket](int events) { - store.connect_client(socket); - }); + loop.add_file_event(socket, kEventLoopRead, + [&store, socket](int events) { store.connect_client(socket); }); loop.run(); } -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { signal(SIGTERM, signal_handler); - char *socket_name = NULL; + char* socket_name = NULL; int64_t system_memory = -1; int c; while ((c = getopt(argc, argv, "s:m:")) != -1) { switch (c) { - case 's': - socket_name = optarg; - break; - case 'm': { - char extra; - int scanned = sscanf(optarg, "%" SCNd64 "%c", &system_memory, &extra); - ARROW_CHECK(scanned == 1); - ARROW_LOG(INFO) << "Allowing the Plasma store to use up to " - << static_cast(system_memory) / 1000000000 - << "GB of memory."; - break; - } - default: - exit(-1); + case 's': + socket_name = optarg; + break; + case 'm': { + char extra; + int scanned = sscanf(optarg, "%" SCNd64 "%c", &system_memory, &extra); + ARROW_CHECK(scanned == 1); + ARROW_LOG(INFO) << "Allowing the Plasma store to use up to " + << static_cast(system_memory) / 1000000000 + << "GB of memory."; + break; + } + default: + exit(-1); } } if (!socket_name) { - ARROW_LOG(FATAL) - << "please specify socket for incoming connections with -s switch"; + ARROW_LOG(FATAL) << "please specify socket for incoming connections with -s switch"; } if (system_memory == -1) { - ARROW_LOG(FATAL) - << "please specify the amount of system memory with -m switch"; + ARROW_LOG(FATAL) << "please specify the amount of system memory with -m switch"; } #ifdef __linux__ // On Linux, check that the amount of memory available in /dev/shm is large @@ -691,20 +661,19 @@ int main(int argc, char *argv[]) { int64_t shm_mem_avail = shm_vfs_stats.f_bsize * shm_vfs_stats.f_bavail; close(shm_fd); if (system_memory > shm_mem_avail) { - ARROW_LOG(FATAL) - << "System memory request exceeds memory available in /dev/shm. The " - "request is for " - << system_memory << " bytes, and the amount available is " - << shm_mem_avail - << " bytes. You may be able to free up space by deleting files in " - "/dev/shm. If you are inside a Docker container, you may need to " - "pass " - "an argument with the flag '--shm-size' to 'docker run'."; + ARROW_LOG(FATAL) << "System memory request exceeds memory available in /dev/shm. The " + "request is for " + << system_memory << " bytes, and the amount available is " + << shm_mem_avail + << " bytes. You may be able to free up space by deleting files in " + "/dev/shm. If you are inside a Docker container, you may need to " + "pass " + "an argument with the flag '--shm-size' to 'docker run'."; } #endif // Make it so dlmalloc fails if we try to request more memory than is // available. - dlmalloc_set_footprint_limit((size_t) system_memory); + dlmalloc_set_footprint_limit((size_t)system_memory); ARROW_LOG(DEBUG) << "starting server listening on " << socket_name; start_server(socket_name, system_memory); } diff --git a/cpp/src/plasma/store.h b/cpp/src/plasma/store.h index 22b8b323a87..cc8dae7bb9d 100644 --- a/cpp/src/plasma/store.h +++ b/cpp/src/plasma/store.h @@ -21,10 +21,10 @@ #include #include -#include "plasma/eviction_policy.h" -#include "plasma/plasma.h" #include "plasma/common.h" #include "plasma/events.h" +#include "plasma/eviction_policy.h" +#include "plasma/plasma.h" #include "plasma/protocol.h" class GetRequest; @@ -32,7 +32,7 @@ class GetRequest; struct NotificationQueue { /// The object notifications for clients. We notify the client about the /// objects in the order that the objects were sealed or deleted. - std::deque object_notifications; + std::deque object_notifications; }; /// Contains all information that is associated with a Plasma store client. @@ -45,7 +45,7 @@ struct Client { class PlasmaStore { public: - PlasmaStore(EventLoop *loop, int64_t system_memory); + PlasmaStore(EventLoop* loop, int64_t system_memory); ~PlasmaStore(); @@ -63,18 +63,15 @@ class PlasmaStore { /// - PlasmaError_OutOfMemory, if the store is out of memory and /// cannot create the object. In this case, the client should not call /// plasma_release. - int create_object(ObjectID object_id, - int64_t data_size, - int64_t metadata_size, - Client *client, - PlasmaObject *result); + int create_object(ObjectID object_id, int64_t data_size, int64_t metadata_size, + Client* client, PlasmaObject* result); /// Delete objects that have been created in the hash table. This should only /// be called on objects that are returned by the eviction policy to evict. /// /// @param object_ids Object IDs of the objects to be deleted. /// @return Void. - void delete_objects(const std::vector &object_ids); + void delete_objects(const std::vector& object_ids); /// Process a get request from a client. This method assumes that we will /// eventually have these objects sealed. If one of the objects has not yet @@ -88,9 +85,8 @@ class PlasmaStore { /// @param object_ids Object IDs of the objects to be gotten. /// @param timeout_ms The timeout for the get request in milliseconds. /// @return Void. - void process_get_request(Client *client, - const std::vector &object_ids, - int64_t timeout_ms); + void process_get_request( + Client* client, const std::vector& object_ids, int64_t timeout_ms); /// Seal an object. The object is now immutable and can be accessed with get. /// @@ -113,13 +109,13 @@ class PlasmaStore { /// @param object_id The object ID of the object that is being released. /// @param client The client making this request. /// @param Void. - void release_object(ObjectID object_id, Client *client); + void release_object(ObjectID object_id, Client* client); /// Subscribe a file descriptor to updates about new sealed objects. /// /// @param client The client making this request. /// @return Void. - void subscribe_to_updates(Client *client); + void subscribe_to_updates(Client* client); /// Connect a new client to the PlasmaStore. /// @@ -131,26 +127,25 @@ class PlasmaStore { /// /// @param client The client that is disconnected. /// @return Void. - void disconnect_client(Client *client); + void disconnect_client(Client* client); void send_notifications(int client_fd); - Status process_message(Client *client); + Status process_message(Client* client); private: - void push_notification(ObjectInfoT *object_notification); + void push_notification(ObjectInfoT* object_notification); - void add_client_to_object_clients(ObjectTableEntry *entry, Client *client); + void add_client_to_object_clients(ObjectTableEntry* entry, Client* client); - void return_from_get(GetRequest *get_req); + void return_from_get(GetRequest* get_req); void update_object_get_requests(ObjectID object_id); - int remove_client_from_object_clients(ObjectTableEntry *entry, - Client *client); + int remove_client_from_object_clients(ObjectTableEntry* entry, Client* client); /// Event loop of the plasma store. - EventLoop *loop_; + EventLoop* loop_; /// The plasma store information, including the object tables, that is exposed /// to the eviction policy. PlasmaStoreInfo store_info_; @@ -161,7 +156,7 @@ class PlasmaStore { std::vector input_buffer_; /// A hash table mapping object IDs to a vector of the get requests that are /// waiting for the object to arrive. - std::unordered_map, UniqueIDHasher> + std::unordered_map, UniqueIDHasher> object_get_requests_; /// The pending notifications that have not been sent to subscribers because /// the socket send buffers were full. This is a hash table from client file diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index a172fd758c8..647f25a0d99 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -18,23 +18,23 @@ #include "thirdparty/greatest.h" #include -#include #include +#include +#include "plasma/client.h" #include "plasma/common.h" #include "plasma/plasma.h" #include "plasma/protocol.h" -#include "plasma/client.h" SUITE(plasma_client_tests); TEST plasma_status_tests(void) { PlasmaClient client1; - ARROW_CHECK_OK(client1.Connect("/tmp/store1", "/tmp/manager1", - PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK( + client1.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); PlasmaClient client2; - ARROW_CHECK_OK(client2.Connect("/tmp/store2", "/tmp/manager2", - PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK( + client2.Connect("/tmp/store2", "/tmp/manager2", PLASMA_DEFAULT_RELEASE_DELAY)); ObjectID oid1 = ObjectID::from_random(); /* Test for object non-existence. */ @@ -47,9 +47,8 @@ TEST plasma_status_tests(void) { int64_t data_size = 100; uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); - uint8_t *data; - ARROW_CHECK_OK( - client1.Create(oid1, data_size, metadata, metadata_size, &data)); + uint8_t* data; + ARROW_CHECK_OK(client1.Create(oid1, data_size, metadata, metadata_size, &data)); ARROW_CHECK_OK(client1.Seal(oid1)); /* Sleep to avoid race condition of Plasma Manager waiting for notification. */ @@ -69,11 +68,11 @@ TEST plasma_status_tests(void) { TEST plasma_fetch_tests(void) { PlasmaClient client1; - ARROW_CHECK_OK(client1.Connect("/tmp/store1", "/tmp/manager1", - PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK( + client1.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); PlasmaClient client2; - ARROW_CHECK_OK(client2.Connect("/tmp/store2", "/tmp/manager2", - PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK( + client2.Connect("/tmp/store2", "/tmp/manager2", PLASMA_DEFAULT_RELEASE_DELAY)); ObjectID oid1 = ObjectID::from_random(); /* Test for object non-existence. */ @@ -88,9 +87,8 @@ TEST plasma_fetch_tests(void) { int64_t data_size = 100; uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); - uint8_t *data; - ARROW_CHECK_OK( - client1.Create(oid1, data_size, metadata, metadata_size, &data)); + uint8_t* data; + ARROW_CHECK_OK(client1.Create(oid1, data_size, metadata, metadata_size, &data)); ARROW_CHECK_OK(client1.Seal(oid1)); /* Object with ID oid1 has been just inserted. On the next fetch we might @@ -99,8 +97,7 @@ TEST plasma_fetch_tests(void) { ObjectID oid_array1[1] = {oid1}; ARROW_CHECK_OK(client1.Fetch(1, oid_array1)); ARROW_CHECK_OK(client1.Info(oid1, &status)); - ASSERT((status == ObjectStatus_Local) || - (status == ObjectStatus_Nonexistent)); + ASSERT((status == ObjectStatus_Local) || (status == ObjectStatus_Nonexistent)); /* Sleep to make sure Plasma Manager got the notification. */ sleep(1); @@ -125,25 +122,23 @@ TEST plasma_fetch_tests(void) { PASS(); } -void init_data_123(uint8_t *data, uint64_t size, uint8_t base) { +void init_data_123(uint8_t* data, uint64_t size, uint8_t base) { for (int i = 0; i < size; i++) { data[i] = base + i; } } -bool is_equal_data_123(uint8_t *data1, uint8_t *data2, uint64_t size) { +bool is_equal_data_123(uint8_t* data1, uint8_t* data2, uint64_t size) { for (int i = 0; i < size; i++) { - if (data1[i] != data2[i]) { - return false; - } + if (data1[i] != data2[i]) { return false; } } return true; } TEST plasma_nonblocking_get_tests(void) { PlasmaClient client; - ARROW_CHECK_OK(client.Connect("/tmp/store1", "/tmp/manager1", - PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK( + client.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); ObjectID oid = ObjectID::from_random(); ObjectID oid_array[1] = {oid}; ObjectBuffer obj_buffer; @@ -157,7 +152,7 @@ TEST plasma_nonblocking_get_tests(void) { int64_t data_size = 4; uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); - uint8_t *data; + uint8_t* data; ARROW_CHECK_OK(client.Create(oid, data_size, metadata, metadata_size, &data)); init_data_123(data, data_size, 0); ARROW_CHECK_OK(client.Seal(oid)); @@ -174,11 +169,11 @@ TEST plasma_nonblocking_get_tests(void) { TEST plasma_wait_for_objects_tests(void) { PlasmaClient client1; - ARROW_CHECK_OK(client1.Connect("/tmp/store1", "/tmp/manager1", - PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK( + client1.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); PlasmaClient client2; - ARROW_CHECK_OK(client2.Connect("/tmp/store2", "/tmp/manager2", - PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK( + client2.Connect("/tmp/store2", "/tmp/manager2", PLASMA_DEFAULT_RELEASE_DELAY)); ObjectID oid1 = ObjectID::from_random(); ObjectID oid2 = ObjectID::from_random(); #define NUM_OBJ_REQUEST 2 @@ -193,8 +188,8 @@ TEST plasma_wait_for_objects_tests(void) { struct timeval start, end; gettimeofday(&start, NULL); int n; - ARROW_CHECK_OK(client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, - WAIT_TIMEOUT_MS, n)); + ARROW_CHECK_OK( + client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); ASSERT(n == 0); gettimeofday(&end, NULL); float diff_ms = (end.tv_sec - start.tv_sec); @@ -206,36 +201,34 @@ TEST plasma_wait_for_objects_tests(void) { int64_t data_size = 4; uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); - uint8_t *data; - ARROW_CHECK_OK( - client1.Create(oid1, data_size, metadata, metadata_size, &data)); + uint8_t* data; + ARROW_CHECK_OK(client1.Create(oid1, data_size, metadata, metadata_size, &data)); ARROW_CHECK_OK(client1.Seal(oid1)); - ARROW_CHECK_OK(client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, - WAIT_TIMEOUT_MS, n)); + ARROW_CHECK_OK( + client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); ASSERT(n == 1); /* Create and insert an object in client2. */ - ARROW_CHECK_OK( - client2.Create(oid2, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client2.Create(oid2, data_size, metadata, metadata_size, &data)); ARROW_CHECK_OK(client2.Seal(oid2)); - ARROW_CHECK_OK(client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, - WAIT_TIMEOUT_MS, n)); + ARROW_CHECK_OK( + client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); ASSERT(n == 2); - ARROW_CHECK_OK(client2.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, - WAIT_TIMEOUT_MS, n)); + ARROW_CHECK_OK( + client2.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); ASSERT(n == 2); obj_requests[0].type = PLASMA_QUERY_LOCAL; obj_requests[1].type = PLASMA_QUERY_LOCAL; - ARROW_CHECK_OK(client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, - WAIT_TIMEOUT_MS, n)); + ARROW_CHECK_OK( + client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); ASSERT(n == 1); - ARROW_CHECK_OK(client2.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, - WAIT_TIMEOUT_MS, n)); + ARROW_CHECK_OK( + client2.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); ASSERT(n == 1); ARROW_CHECK_OK(client1.Disconnect()); @@ -246,10 +239,10 @@ TEST plasma_wait_for_objects_tests(void) { TEST plasma_get_tests(void) { PlasmaClient client1, client2; - ARROW_CHECK_OK(client1.Connect("/tmp/store1", "/tmp/manager1", - PLASMA_DEFAULT_RELEASE_DELAY)); - ARROW_CHECK_OK(client2.Connect("/tmp/store2", "/tmp/manager2", - PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK( + client1.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK( + client2.Connect("/tmp/store2", "/tmp/manager2", PLASMA_DEFAULT_RELEASE_DELAY)); ObjectID oid1 = ObjectID::from_random(); ObjectID oid2 = ObjectID::from_random(); ObjectBuffer obj_buffer; @@ -260,17 +253,15 @@ TEST plasma_get_tests(void) { int64_t data_size = 4; uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); - uint8_t *data; - ARROW_CHECK_OK( - client1.Create(oid1, data_size, metadata, metadata_size, &data)); + uint8_t* data; + ARROW_CHECK_OK(client1.Create(oid1, data_size, metadata, metadata_size, &data)); init_data_123(data, data_size, 1); ARROW_CHECK_OK(client1.Seal(oid1)); ARROW_CHECK_OK(client1.Get(oid_array1, 1, -1, &obj_buffer)); ASSERT(data[0] == obj_buffer.data[0]); - ARROW_CHECK_OK( - client2.Create(oid2, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client2.Create(oid2, data_size, metadata, metadata_size, &data)); init_data_123(data, data_size, 2); ARROW_CHECK_OK(client2.Seal(oid2)); @@ -287,10 +278,10 @@ TEST plasma_get_tests(void) { TEST plasma_get_multiple_tests(void) { PlasmaClient client1, client2; - ARROW_CHECK_OK(client1.Connect("/tmp/store1", "/tmp/manager1", - PLASMA_DEFAULT_RELEASE_DELAY)); - ARROW_CHECK_OK(client2.Connect("/tmp/store2", "/tmp/manager2", - PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK( + client1.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); + ARROW_CHECK_OK( + client2.Connect("/tmp/store2", "/tmp/manager2", PLASMA_DEFAULT_RELEASE_DELAY)); ObjectID oid1 = ObjectID::from_random(); ObjectID oid2 = ObjectID::from_random(); ObjectID obj_ids[NUM_OBJ_REQUEST]; @@ -303,9 +294,8 @@ TEST plasma_get_multiple_tests(void) { int64_t data_size = 4; uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); - uint8_t *data; - ARROW_CHECK_OK( - client1.Create(oid1, data_size, metadata, metadata_size, &data)); + uint8_t* data; + ARROW_CHECK_OK(client1.Create(oid1, data_size, metadata, metadata_size, &data)); init_data_123(data, data_size, obj1_first); ARROW_CHECK_OK(client1.Seal(oid1)); @@ -313,8 +303,7 @@ TEST plasma_get_multiple_tests(void) { ARROW_CHECK_OK(client1.Get(obj_ids, 1, -1, obj_buffer)); ASSERT(data[0] == obj_buffer[0].data[0]); - ARROW_CHECK_OK( - client2.Create(oid2, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client2.Create(oid2, data_size, metadata, metadata_size, &data)); init_data_123(data, data_size, obj2_first); ARROW_CHECK_OK(client2.Seal(oid2)); @@ -341,7 +330,7 @@ SUITE(plasma_client_tests) { GREATEST_MAIN_DEFS(); -int main(int argc, char **argv) { +int main(int argc, char** argv) { GREATEST_MAIN_BEGIN(); RUN_SUITE(plasma_client_tests); GREATEST_MAIN_END(); diff --git a/cpp/src/plasma/test/serialization_tests.cc b/cpp/src/plasma/test/serialization_tests.cc index 8b402d3ff55..b594db8a60b 100644 --- a/cpp/src/plasma/test/serialization_tests.cc +++ b/cpp/src/plasma/test/serialization_tests.cc @@ -21,8 +21,8 @@ #include #include "plasma/common.h" -#include "plasma/plasma.h" #include "plasma/io.h" +#include "plasma/plasma.h" #include "plasma/protocol.h" SUITE(plasma_serialization_tests); @@ -78,13 +78,12 @@ TEST plasma_create_request_test(void) { int64_t data_size1 = 42; int64_t metadata_size1 = 11; ARROW_CHECK_OK(SendCreateRequest(fd, object_id1, data_size1, metadata_size1)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaCreateRequest); + std::vector data = read_message_from_file(fd, MessageType_PlasmaCreateRequest); ObjectID object_id2; int64_t data_size2; int64_t metadata_size2; - ARROW_CHECK_OK(ReadCreateRequest(data.data(), &object_id2, &data_size2, - &metadata_size2)); + ARROW_CHECK_OK( + ReadCreateRequest(data.data(), &object_id2, &data_size2, &metadata_size2)); ASSERT_EQ(data_size1, data_size2); ASSERT_EQ(metadata_size1, metadata_size2); ASSERT(object_id1 == object_id2); @@ -97,8 +96,7 @@ TEST plasma_create_reply_test(void) { ObjectID object_id1 = ObjectID::from_random(); PlasmaObject object1 = random_plasma_object(); ARROW_CHECK_OK(SendCreateReply(fd, object_id1, &object1, 0)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaCreateReply); + std::vector data = read_message_from_file(fd, MessageType_PlasmaCreateReply); ObjectID object_id2; PlasmaObject object2; memset(&object2, 0, sizeof(object2)); @@ -115,8 +113,7 @@ TEST plasma_seal_request_test(void) { unsigned char digest1[kDigestSize]; memset(&digest1[0], 7, kDigestSize); ARROW_CHECK_OK(SendSealRequest(fd, object_id1, &digest1[0])); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaSealRequest); + std::vector data = read_message_from_file(fd, MessageType_PlasmaSealRequest); ObjectID object_id2; unsigned char digest2[kDigestSize]; ARROW_CHECK_OK(ReadSealRequest(data.data(), &object_id2, &digest2[0])); @@ -130,8 +127,7 @@ TEST plasma_seal_reply_test(void) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); ARROW_CHECK_OK(SendSealReply(fd, object_id1, PlasmaError_ObjectExists)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaSealReply); + std::vector data = read_message_from_file(fd, MessageType_PlasmaSealReply); ObjectID object_id2; Status s = ReadSealReply(data.data(), &object_id2); ASSERT(object_id1 == object_id2); @@ -147,12 +143,10 @@ TEST plasma_get_request_test(void) { object_ids[1] = ObjectID::from_random(); int64_t timeout_ms = 1234; ARROW_CHECK_OK(SendGetRequest(fd, object_ids, 2, timeout_ms)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaGetRequest); + std::vector data = read_message_from_file(fd, MessageType_PlasmaGetRequest); std::vector object_ids_return; int64_t timeout_ms_return; - ARROW_CHECK_OK( - ReadGetRequest(data.data(), object_ids_return, &timeout_ms_return)); + ARROW_CHECK_OK(ReadGetRequest(data.data(), object_ids_return, &timeout_ms_return)); ASSERT(object_ids[0] == object_ids_return[0]); ASSERT(object_ids[1] == object_ids_return[1]); ASSERT(timeout_ms == timeout_ms_return); @@ -169,19 +163,18 @@ TEST plasma_get_reply_test(void) { plasma_objects[object_ids[0]] = random_plasma_object(); plasma_objects[object_ids[1]] = random_plasma_object(); ARROW_CHECK_OK(SendGetReply(fd, object_ids, plasma_objects, 2)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaGetReply); + std::vector data = read_message_from_file(fd, MessageType_PlasmaGetReply); ObjectID object_ids_return[2]; PlasmaObject plasma_objects_return[2]; memset(&plasma_objects_return, 0, sizeof(plasma_objects_return)); - ARROW_CHECK_OK(ReadGetReply(data.data(), object_ids_return, - &plasma_objects_return[0], 2)); + ARROW_CHECK_OK( + ReadGetReply(data.data(), object_ids_return, &plasma_objects_return[0], 2)); ASSERT(object_ids[0] == object_ids_return[0]); ASSERT(object_ids[1] == object_ids_return[1]); ASSERT(memcmp(&plasma_objects[object_ids[0]], &plasma_objects_return[0], - sizeof(PlasmaObject)) == 0); + sizeof(PlasmaObject)) == 0); ASSERT(memcmp(&plasma_objects[object_ids[1]], &plasma_objects_return[1], - sizeof(PlasmaObject)) == 0); + sizeof(PlasmaObject)) == 0); close(fd); PASS(); } @@ -203,8 +196,7 @@ TEST plasma_release_reply_test(void) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); ARROW_CHECK_OK(SendReleaseReply(fd, object_id1, PlasmaError_ObjectExists)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaReleaseReply); + std::vector data = read_message_from_file(fd, MessageType_PlasmaReleaseReply); ObjectID object_id2; Status s = ReadReleaseReply(data.data(), &object_id2); ASSERT(object_id1 == object_id2); @@ -217,8 +209,7 @@ TEST plasma_delete_request_test(void) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); ARROW_CHECK_OK(SendDeleteRequest(fd, object_id1)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaDeleteRequest); + std::vector data = read_message_from_file(fd, MessageType_PlasmaDeleteRequest); ObjectID object_id2; ARROW_CHECK_OK(ReadDeleteRequest(data.data(), &object_id2)); ASSERT(object_id1 == object_id2); @@ -231,8 +222,7 @@ TEST plasma_delete_reply_test(void) { ObjectID object_id1 = ObjectID::from_random(); int error1 = PlasmaError_ObjectExists; ARROW_CHECK_OK(SendDeleteReply(fd, object_id1, error1)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaDeleteReply); + std::vector data = read_message_from_file(fd, MessageType_PlasmaDeleteReply); ObjectID object_id2; Status s = ReadDeleteReply(data.data(), &object_id2); ASSERT(object_id1 == object_id2); @@ -248,8 +238,7 @@ TEST plasma_status_request_test(void) { object_ids[0] = ObjectID::from_random(); object_ids[1] = ObjectID::from_random(); ARROW_CHECK_OK(SendStatusRequest(fd, object_ids, num_objects)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaStatusRequest); + std::vector data = read_message_from_file(fd, MessageType_PlasmaStatusRequest); ObjectID object_ids_read[num_objects]; ARROW_CHECK_OK(ReadStatusRequest(data.data(), object_ids_read, num_objects)); ASSERT(object_ids[0] == object_ids_read[0]); @@ -265,13 +254,12 @@ TEST plasma_status_reply_test(void) { object_ids[1] = ObjectID::from_random(); int object_statuses[2] = {42, 43}; ARROW_CHECK_OK(SendStatusReply(fd, object_ids, object_statuses, 2)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaStatusReply); + std::vector data = read_message_from_file(fd, MessageType_PlasmaStatusReply); int64_t num_objects = ReadStatusReply_num_objects(data.data()); ObjectID object_ids_read[num_objects]; int object_statuses_read[num_objects]; - ARROW_CHECK_OK(ReadStatusReply(data.data(), object_ids_read, - object_statuses_read, num_objects)); + ARROW_CHECK_OK( + ReadStatusReply(data.data(), object_ids_read, object_statuses_read, num_objects)); ASSERT(object_ids[0] == object_ids_read[0]); ASSERT(object_ids[1] == object_ids_read[1]); ASSERT_EQ(object_statuses[0], object_statuses_read[0]); @@ -284,8 +272,7 @@ TEST plasma_evict_request_test(void) { int fd = create_temp_file(); int64_t num_bytes = 111; ARROW_CHECK_OK(SendEvictRequest(fd, num_bytes)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaEvictRequest); + std::vector data = read_message_from_file(fd, MessageType_PlasmaEvictRequest); int64_t num_bytes_received; ARROW_CHECK_OK(ReadEvictRequest(data.data(), &num_bytes_received)); ASSERT_EQ(num_bytes, num_bytes_received); @@ -297,8 +284,7 @@ TEST plasma_evict_reply_test(void) { int fd = create_temp_file(); int64_t num_bytes = 111; ARROW_CHECK_OK(SendEvictReply(fd, num_bytes)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaEvictReply); + std::vector data = read_message_from_file(fd, MessageType_PlasmaEvictReply); int64_t num_bytes_received; ARROW_CHECK_OK(ReadEvictReply(data.data(), num_bytes_received)); ASSERT_EQ(num_bytes, num_bytes_received); @@ -312,8 +298,7 @@ TEST plasma_fetch_request_test(void) { object_ids[0] = ObjectID::from_random(); object_ids[1] = ObjectID::from_random(); ARROW_CHECK_OK(SendFetchRequest(fd, object_ids, 2)); - std::vector data = - read_message_from_file(fd, MessageType_PlasmaFetchRequest); + std::vector data = read_message_from_file(fd, MessageType_PlasmaFetchRequest); std::vector object_ids_read; ARROW_CHECK_OK(ReadFetchRequest(data.data(), object_ids_read)); ASSERT(object_ids[0] == object_ids_read[0]); @@ -331,22 +316,21 @@ TEST plasma_wait_request_test(void) { const int num_ready_objects_in = 1; int64_t timeout_ms = 1000; - ARROW_CHECK_OK(SendWaitRequest(fd, &object_requests_in[0], num_objects_in, - num_ready_objects_in, timeout_ms)); + ARROW_CHECK_OK(SendWaitRequest( + fd, &object_requests_in[0], num_objects_in, num_ready_objects_in, timeout_ms)); /* Read message back. */ - std::vector data = - read_message_from_file(fd, MessageType_PlasmaWaitRequest); + std::vector data = read_message_from_file(fd, MessageType_PlasmaWaitRequest); int num_ready_objects_out; int64_t timeout_ms_read; ObjectRequestMap object_requests_out; - ARROW_CHECK_OK(ReadWaitRequest(data.data(), object_requests_out, - &timeout_ms_read, &num_ready_objects_out)); + ARROW_CHECK_OK(ReadWaitRequest( + data.data(), object_requests_out, &timeout_ms_read, &num_ready_objects_out)); ASSERT_EQ(num_objects_in, object_requests_out.size()); ASSERT_EQ(num_ready_objects_out, num_ready_objects_in); for (int i = 0; i < num_objects_in; i++) { - const ObjectID &object_id = object_requests_in[i].object_id; + const ObjectID& object_id = object_requests_in[i].object_id; ASSERT_EQ(1, object_requests_out.count(object_id)); - const auto &entry = object_requests_out.find(object_id); + const auto& entry = object_requests_out.find(object_id); ASSERT(entry != object_requests_out.end()); ASSERT(entry->second.object_id == object_requests_in[i].object_id); ASSERT_EQ(entry->second.type, object_requests_in[i].type); @@ -367,8 +351,7 @@ TEST plasma_wait_reply_test(void) { ARROW_CHECK_OK(SendWaitReply(fd, objects_in, num_objects_in)); /* Read message back. */ - std::vector data = - read_message_from_file(fd, MessageType_PlasmaWaitReply); + std::vector data = read_message_from_file(fd, MessageType_PlasmaWaitReply); ObjectRequest objects_out[2]; int num_objects_out; ARROW_CHECK_OK(ReadWaitReply(data.data(), &objects_out[0], &num_objects_out)); @@ -376,7 +359,7 @@ TEST plasma_wait_reply_test(void) { for (int i = 0; i < num_objects_out; i++) { /* Each object request must appear exactly once. */ ASSERT(1 == objects_in.count(objects_out[i].object_id)); - const auto &entry = objects_in.find(objects_out[i].object_id); + const auto& entry = objects_in.find(objects_out[i].object_id); ASSERT(entry != objects_in.end()); ASSERT(entry->second.object_id == objects_out[i].object_id); ASSERT(entry->second.status == objects_out[i].status); @@ -388,14 +371,13 @@ TEST plasma_wait_reply_test(void) { TEST plasma_data_request_test(void) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); - const char *address1 = "address1"; + const char* address1 = "address1"; int port1 = 12345; ARROW_CHECK_OK(SendDataRequest(fd, object_id1, address1, port1)); /* Reading message back. */ - std::vector data = - read_message_from_file(fd, MessageType_PlasmaDataRequest); + std::vector data = read_message_from_file(fd, MessageType_PlasmaDataRequest); ObjectID object_id2; - char *address2; + char* address2; int port2; ARROW_CHECK_OK(ReadDataRequest(data.data(), &object_id2, &address2, &port2)); ASSERT(object_id1 == object_id2); @@ -413,13 +395,11 @@ TEST plasma_data_reply_test(void) { int64_t metadata_size1 = 198; ARROW_CHECK_OK(SendDataReply(fd, object_id1, object_size1, metadata_size1)); /* Reading message back. */ - std::vector data = - read_message_from_file(fd, MessageType_PlasmaDataReply); + std::vector data = read_message_from_file(fd, MessageType_PlasmaDataReply); ObjectID object_id2; int64_t object_size2; int64_t metadata_size2; - ARROW_CHECK_OK( - ReadDataReply(data.data(), &object_id2, &object_size2, &metadata_size2)); + ARROW_CHECK_OK(ReadDataReply(data.data(), &object_id2, &object_size2, &metadata_size2)); ASSERT(object_id1 == object_id2); ASSERT(object_size1 == object_size2); ASSERT(metadata_size1 == metadata_size2); @@ -450,7 +430,7 @@ SUITE(plasma_serialization_tests) { GREATEST_MAIN_DEFS(); -int main(int argc, char **argv) { +int main(int argc, char** argv) { GREATEST_MAIN_BEGIN(); RUN_SUITE(plasma_serialization_tests); GREATEST_MAIN_END(); From b9a5a06e1c747fb95df6754c81fa4dbf32ffb735 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Mon, 12 Jun 2017 17:07:50 -0700 Subject: [PATCH 21/53] fix includes --- cpp/src/plasma/extension.h | 6 +++++- cpp/src/plasma/plasma.h | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/cpp/src/plasma/extension.h b/cpp/src/plasma/extension.h index aa4c1fa1416..28cf8f2c584 100644 --- a/cpp/src/plasma/extension.h +++ b/cpp/src/plasma/extension.h @@ -20,9 +20,13 @@ #undef _XOPEN_SOURCE #undef _POSIX_C_SOURCE -#include "bytesobject.h" // NOLINT #include +#include "bytesobject.h" // NOLINT + +#include "plasma/client.h" +#include "plasma/common.h" + static int PyObjectToPlasmaClient(PyObject* object, PlasmaClient** client) { if (PyCapsule_IsValid(object, "plasma")) { *client = reinterpret_cast(PyCapsule_GetPointer(object, "plasma")); diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h index e898aed3375..39ba2a3e679 100644 --- a/cpp/src/plasma/plasma.h +++ b/cpp/src/plasma/plasma.h @@ -32,6 +32,7 @@ #include "arrow/status.h" #include "arrow/util/logging.h" #include "format/common_generated.h" +#include "plasma/common.h" #include From 0b8593db5fdc66e9e5b152edcfd5f2e8cd677f00 Mon Sep 17 00:00:00 2001 From: Robert Nishihara Date: Tue, 13 Jun 2017 13:21:26 -0700 Subject: [PATCH 22/53] Port change from Ray. Change listen backlog size from 5 to 128. --- cpp/src/plasma/io.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/src/plasma/io.cc b/cpp/src/plasma/io.cc index 62340eb0bd1..213016d5d5a 100644 --- a/cpp/src/plasma/io.cc +++ b/cpp/src/plasma/io.cc @@ -125,7 +125,7 @@ int bind_ipc_sock(const std::string& pathname, bool shall_listen) { close(socket_fd); return -1; } - if (shall_listen && listen(socket_fd, 5) == -1) { + if (shall_listen && listen(socket_fd, 128) == -1) { ARROW_LOG(ERROR) << "Could not listen to socket " << pathname; close(socket_fd); return -1; From 9e5ae0e17130ccffea8acecbc43540a1a9b1b91a Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Wed, 14 Jun 2017 18:53:50 -0700 Subject: [PATCH 23/53] port serialization tests to gtest --- cpp/src/plasma/CMakeLists.txt | 3 +- cpp/src/plasma/test/serialization_tests.cc | 175 ++++++++------------- 2 files changed, 64 insertions(+), 114 deletions(-) diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index 299713f64ad..3a26caa759a 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -122,4 +122,5 @@ target_link_libraries(plasma_client plasma_lib ${FLATBUFFERS_STATIC_LIB}) # define_test(client_tests plasma_lib) # define_test(manager_tests plasma_lib plasma_manager.cc) -# define_test(serialization_tests plasma_lib) +ADD_ARROW_TEST(test/serialization_tests) +ARROW_TEST_LINK_LIBRARIES(test/serialization_tests plasma_lib) diff --git a/cpp/src/plasma/test/serialization_tests.cc b/cpp/src/plasma/test/serialization_tests.cc index b594db8a60b..663d8b03642 100644 --- a/cpp/src/plasma/test/serialization_tests.cc +++ b/cpp/src/plasma/test/serialization_tests.cc @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -#include "thirdparty/greatest.h" +#include "gtest/gtest.h" #include #include @@ -25,8 +25,6 @@ #include "plasma/plasma.h" #include "plasma/protocol.h" -SUITE(plasma_serialization_tests); - /** * Create a temporary file. Needs to be closed by the caller. * @@ -59,7 +57,7 @@ std::vector read_message_from_file(int fd, int message_type) { } PlasmaObject random_plasma_object(void) { - unsigned int seed = time(NULL); + unsigned int seed = static_cast(time(NULL)); int random = rand_r(&seed); PlasmaObject object; memset(&object, 0, sizeof(object)); @@ -72,7 +70,7 @@ PlasmaObject random_plasma_object(void) { return object; } -TEST plasma_create_request_test(void) { +TEST(PlasmaSerialization, CreateRequest) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); int64_t data_size1 = 42; @@ -86,12 +84,11 @@ TEST plasma_create_request_test(void) { ReadCreateRequest(data.data(), &object_id2, &data_size2, &metadata_size2)); ASSERT_EQ(data_size1, data_size2); ASSERT_EQ(metadata_size1, metadata_size2); - ASSERT(object_id1 == object_id2); + ASSERT_EQ(object_id1, object_id2); close(fd); - PASS(); } -TEST plasma_create_reply_test(void) { +TEST(PlasmaSerialization, CreateReply) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); PlasmaObject object1 = random_plasma_object(); @@ -101,13 +98,12 @@ TEST plasma_create_reply_test(void) { PlasmaObject object2; memset(&object2, 0, sizeof(object2)); ARROW_CHECK_OK(ReadCreateReply(data.data(), &object_id2, &object2)); - ASSERT(object_id1 == object_id2); - ASSERT(memcmp(&object1, &object2, sizeof(object1)) == 0); + ASSERT_EQ(object_id1, object_id2); + ASSERT_EQ(memcmp(&object1, &object2, sizeof(object1)), 0); close(fd); - PASS(); } -TEST plasma_seal_request_test(void) { +TEST(PlasmaSerialization, SealRequest) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); unsigned char digest1[kDigestSize]; @@ -117,26 +113,24 @@ TEST plasma_seal_request_test(void) { ObjectID object_id2; unsigned char digest2[kDigestSize]; ARROW_CHECK_OK(ReadSealRequest(data.data(), &object_id2, &digest2[0])); - ASSERT(object_id1 == object_id2); - ASSERT(memcmp(&digest1[0], &digest2[0], kDigestSize) == 0); + ASSERT_EQ(object_id1, object_id2); + ASSERT_EQ(memcmp(&digest1[0], &digest2[0], kDigestSize), 0); close(fd); - PASS(); } -TEST plasma_seal_reply_test(void) { +TEST(PlasmaSerialization, SealReply) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); ARROW_CHECK_OK(SendSealReply(fd, object_id1, PlasmaError_ObjectExists)); std::vector data = read_message_from_file(fd, MessageType_PlasmaSealReply); ObjectID object_id2; Status s = ReadSealReply(data.data(), &object_id2); - ASSERT(object_id1 == object_id2); - ASSERT(s.IsPlasmaObjectExists()); + ASSERT_EQ(object_id1, object_id2); + ASSERT_TRUE(s.IsPlasmaObjectExists()); close(fd); - PASS(); } -TEST plasma_get_request_test(void) { +TEST(PlasmaSerialization, GetRequest) { int fd = create_temp_file(); ObjectID object_ids[2]; object_ids[0] = ObjectID::from_random(); @@ -147,14 +141,13 @@ TEST plasma_get_request_test(void) { std::vector object_ids_return; int64_t timeout_ms_return; ARROW_CHECK_OK(ReadGetRequest(data.data(), object_ids_return, &timeout_ms_return)); - ASSERT(object_ids[0] == object_ids_return[0]); - ASSERT(object_ids[1] == object_ids_return[1]); - ASSERT(timeout_ms == timeout_ms_return); + ASSERT_EQ(object_ids[0], object_ids_return[0]); + ASSERT_EQ(object_ids[1], object_ids_return[1]); + ASSERT_EQ(timeout_ms, timeout_ms_return); close(fd); - PASS(); } -TEST plasma_get_reply_test(void) { +TEST(PlasmaSerialization, GetReply) { int fd = create_temp_file(); ObjectID object_ids[2]; object_ids[0] = ObjectID::from_random(); @@ -169,17 +162,16 @@ TEST plasma_get_reply_test(void) { memset(&plasma_objects_return, 0, sizeof(plasma_objects_return)); ARROW_CHECK_OK( ReadGetReply(data.data(), object_ids_return, &plasma_objects_return[0], 2)); - ASSERT(object_ids[0] == object_ids_return[0]); - ASSERT(object_ids[1] == object_ids_return[1]); - ASSERT(memcmp(&plasma_objects[object_ids[0]], &plasma_objects_return[0], - sizeof(PlasmaObject)) == 0); - ASSERT(memcmp(&plasma_objects[object_ids[1]], &plasma_objects_return[1], - sizeof(PlasmaObject)) == 0); + ASSERT_EQ(object_ids[0], object_ids_return[0]); + ASSERT_EQ(object_ids[1], object_ids_return[1]); + ASSERT_EQ(memcmp(&plasma_objects[object_ids[0]], &plasma_objects_return[0], + sizeof(PlasmaObject)), 0); + ASSERT_EQ(memcmp(&plasma_objects[object_ids[1]], &plasma_objects_return[1], + sizeof(PlasmaObject)), 0); close(fd); - PASS(); } -TEST plasma_release_request_test(void) { +TEST(PlasmaSerialization, ReleaseRequest) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); ARROW_CHECK_OK(SendReleaseRequest(fd, object_id1)); @@ -187,37 +179,34 @@ TEST plasma_release_request_test(void) { read_message_from_file(fd, MessageType_PlasmaReleaseRequest); ObjectID object_id2; ARROW_CHECK_OK(ReadReleaseRequest(data.data(), &object_id2)); - ASSERT(object_id1 == object_id2); + ASSERT_EQ(object_id1, object_id2); close(fd); - PASS(); } -TEST plasma_release_reply_test(void) { +TEST(PlasmaSerialization, ReleaseReply) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); ARROW_CHECK_OK(SendReleaseReply(fd, object_id1, PlasmaError_ObjectExists)); std::vector data = read_message_from_file(fd, MessageType_PlasmaReleaseReply); ObjectID object_id2; Status s = ReadReleaseReply(data.data(), &object_id2); - ASSERT(object_id1 == object_id2); - ASSERT(s.IsPlasmaObjectExists()); + ASSERT_EQ(object_id1, object_id2); + ASSERT_TRUE(s.IsPlasmaObjectExists()); close(fd); - PASS(); } -TEST plasma_delete_request_test(void) { +TEST(PlasmaSerialization, DeleteRequest) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); ARROW_CHECK_OK(SendDeleteRequest(fd, object_id1)); std::vector data = read_message_from_file(fd, MessageType_PlasmaDeleteRequest); ObjectID object_id2; ARROW_CHECK_OK(ReadDeleteRequest(data.data(), &object_id2)); - ASSERT(object_id1 == object_id2); + ASSERT_EQ(object_id1, object_id2); close(fd); - PASS(); } -TEST plasma_delete_reply_test(void) { +TEST(PlasmaSerialization, DeleteReply) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); int error1 = PlasmaError_ObjectExists; @@ -225,13 +214,12 @@ TEST plasma_delete_reply_test(void) { std::vector data = read_message_from_file(fd, MessageType_PlasmaDeleteReply); ObjectID object_id2; Status s = ReadDeleteReply(data.data(), &object_id2); - ASSERT(object_id1 == object_id2); - ASSERT(s.IsPlasmaObjectExists()); + ASSERT_EQ(object_id1, object_id2); + ASSERT_TRUE(s.IsPlasmaObjectExists()); close(fd); - PASS(); } -TEST plasma_status_request_test(void) { +TEST(PlasmaSerialization, StatusRequest) { int fd = create_temp_file(); int64_t num_objects = 2; ObjectID object_ids[num_objects]; @@ -241,13 +229,12 @@ TEST plasma_status_request_test(void) { std::vector data = read_message_from_file(fd, MessageType_PlasmaStatusRequest); ObjectID object_ids_read[num_objects]; ARROW_CHECK_OK(ReadStatusRequest(data.data(), object_ids_read, num_objects)); - ASSERT(object_ids[0] == object_ids_read[0]); - ASSERT(object_ids[1] == object_ids_read[1]); + ASSERT_EQ(object_ids[0], object_ids_read[0]); + ASSERT_EQ(object_ids[1], object_ids_read[1]); close(fd); - PASS(); } -TEST plasma_status_reply_test(void) { +TEST(PlasmaSerialization, StatusReply) { int fd = create_temp_file(); ObjectID object_ids[2]; object_ids[0] = ObjectID::from_random(); @@ -260,15 +247,14 @@ TEST plasma_status_reply_test(void) { int object_statuses_read[num_objects]; ARROW_CHECK_OK( ReadStatusReply(data.data(), object_ids_read, object_statuses_read, num_objects)); - ASSERT(object_ids[0] == object_ids_read[0]); - ASSERT(object_ids[1] == object_ids_read[1]); + ASSERT_EQ(object_ids[0], object_ids_read[0]); + ASSERT_EQ(object_ids[1], object_ids_read[1]); ASSERT_EQ(object_statuses[0], object_statuses_read[0]); ASSERT_EQ(object_statuses[1], object_statuses_read[1]); close(fd); - PASS(); } -TEST plasma_evict_request_test(void) { +TEST(PlasmaSerialization, EvictRequest) { int fd = create_temp_file(); int64_t num_bytes = 111; ARROW_CHECK_OK(SendEvictRequest(fd, num_bytes)); @@ -277,10 +263,9 @@ TEST plasma_evict_request_test(void) { ARROW_CHECK_OK(ReadEvictRequest(data.data(), &num_bytes_received)); ASSERT_EQ(num_bytes, num_bytes_received); close(fd); - PASS(); } -TEST plasma_evict_reply_test(void) { +TEST(PlasmaSerialization, EvictReply) { int fd = create_temp_file(); int64_t num_bytes = 111; ARROW_CHECK_OK(SendEvictReply(fd, num_bytes)); @@ -289,10 +274,9 @@ TEST plasma_evict_reply_test(void) { ARROW_CHECK_OK(ReadEvictReply(data.data(), num_bytes_received)); ASSERT_EQ(num_bytes, num_bytes_received); close(fd); - PASS(); } -TEST plasma_fetch_request_test(void) { +TEST(PlasmaSerialization, FetchRequest) { int fd = create_temp_file(); ObjectID object_ids[2]; object_ids[0] = ObjectID::from_random(); @@ -301,13 +285,12 @@ TEST plasma_fetch_request_test(void) { std::vector data = read_message_from_file(fd, MessageType_PlasmaFetchRequest); std::vector object_ids_read; ARROW_CHECK_OK(ReadFetchRequest(data.data(), object_ids_read)); - ASSERT(object_ids[0] == object_ids_read[0]); - ASSERT(object_ids[1] == object_ids_read[1]); + ASSERT_EQ(object_ids[0], object_ids_read[0]); + ASSERT_EQ(object_ids[1], object_ids_read[1]); close(fd); - PASS(); } -TEST plasma_wait_request_test(void) { +TEST(PlasmaSerialization, WaitRequest) { int fd = create_temp_file(); const int num_objects_in = 2; ObjectRequest object_requests_in[num_objects_in] = { @@ -331,15 +314,14 @@ TEST plasma_wait_request_test(void) { const ObjectID& object_id = object_requests_in[i].object_id; ASSERT_EQ(1, object_requests_out.count(object_id)); const auto& entry = object_requests_out.find(object_id); - ASSERT(entry != object_requests_out.end()); - ASSERT(entry->second.object_id == object_requests_in[i].object_id); + ASSERT_TRUE(entry != object_requests_out.end()); + ASSERT_EQ(entry->second.object_id, object_requests_in[i].object_id); ASSERT_EQ(entry->second.type, object_requests_in[i].type); } close(fd); - PASS(); } -TEST plasma_wait_reply_test(void) { +TEST(PlasmaSerialization, WaitReply) { int fd = create_temp_file(); const int num_objects_in = 2; /* Create a map with two ObjectRequests in it. */ @@ -355,20 +337,19 @@ TEST plasma_wait_reply_test(void) { ObjectRequest objects_out[2]; int num_objects_out; ARROW_CHECK_OK(ReadWaitReply(data.data(), &objects_out[0], &num_objects_out)); - ASSERT(num_objects_in == num_objects_out); + ASSERT_EQ(num_objects_in, num_objects_out); for (int i = 0; i < num_objects_out; i++) { /* Each object request must appear exactly once. */ - ASSERT(1 == objects_in.count(objects_out[i].object_id)); + ASSERT_EQ(objects_in.count(objects_out[i].object_id), 1); const auto& entry = objects_in.find(objects_out[i].object_id); - ASSERT(entry != objects_in.end()); - ASSERT(entry->second.object_id == objects_out[i].object_id); - ASSERT(entry->second.status == objects_out[i].status); + ASSERT_TRUE(entry != objects_in.end()); + ASSERT_EQ(entry->second.object_id, objects_out[i].object_id); + ASSERT_EQ(entry->second.status, objects_out[i].status); } close(fd); - PASS(); } -TEST plasma_data_request_test(void) { +TEST(PlasmaSerialization, DataRequest) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); const char* address1 = "address1"; @@ -380,15 +361,14 @@ TEST plasma_data_request_test(void) { char* address2; int port2; ARROW_CHECK_OK(ReadDataRequest(data.data(), &object_id2, &address2, &port2)); - ASSERT(object_id1 == object_id2); - ASSERT(strcmp(address1, address2) == 0); - ASSERT(port1 == port2); + ASSERT_EQ(object_id1, object_id2); + ASSERT_EQ(strcmp(address1, address2), 0); + ASSERT_EQ(port1, port2); free(address2); close(fd); - PASS(); } -TEST plasma_data_reply_test(void) { +TEST(PlasmaSerialization, DataReply) { int fd = create_temp_file(); ObjectID object_id1 = ObjectID::from_random(); int64_t object_size1 = 146; @@ -400,38 +380,7 @@ TEST plasma_data_reply_test(void) { int64_t object_size2; int64_t metadata_size2; ARROW_CHECK_OK(ReadDataReply(data.data(), &object_id2, &object_size2, &metadata_size2)); - ASSERT(object_id1 == object_id2); - ASSERT(object_size1 == object_size2); - ASSERT(metadata_size1 == metadata_size2); - PASS(); -} - -SUITE(plasma_serialization_tests) { - RUN_TEST(plasma_create_request_test); - RUN_TEST(plasma_create_reply_test); - RUN_TEST(plasma_seal_request_test); - RUN_TEST(plasma_seal_reply_test); - RUN_TEST(plasma_get_request_test); - RUN_TEST(plasma_get_reply_test); - RUN_TEST(plasma_release_request_test); - RUN_TEST(plasma_release_reply_test); - RUN_TEST(plasma_delete_request_test); - RUN_TEST(plasma_delete_reply_test); - RUN_TEST(plasma_status_request_test); - RUN_TEST(plasma_status_reply_test); - RUN_TEST(plasma_evict_request_test); - RUN_TEST(plasma_evict_reply_test); - RUN_TEST(plasma_fetch_request_test); - RUN_TEST(plasma_wait_request_test); - RUN_TEST(plasma_wait_reply_test); - RUN_TEST(plasma_data_request_test); - RUN_TEST(plasma_data_reply_test); -} - -GREATEST_MAIN_DEFS(); - -int main(int argc, char** argv) { - GREATEST_MAIN_BEGIN(); - RUN_SUITE(plasma_serialization_tests); - GREATEST_MAIN_END(); + ASSERT_EQ(object_id1, object_id2); + ASSERT_EQ(object_size1, object_size2); + ASSERT_EQ(metadata_size1, metadata_size2); } From 9c703c20de8d62c1c930eca418edf5fe446a5be9 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Thu, 15 Jun 2017 01:25:54 -0700 Subject: [PATCH 24/53] integrate client tests --- cpp/src/plasma/CMakeLists.txt | 2 + cpp/src/plasma/client.h | 2 +- cpp/src/plasma/test/client_tests.cc | 348 ++++++---------------------- 3 files changed, 75 insertions(+), 277 deletions(-) diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index 3a26caa759a..059759c3463 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -124,3 +124,5 @@ target_link_libraries(plasma_client plasma_lib ${FLATBUFFERS_STATIC_LIB}) # define_test(manager_tests plasma_lib plasma_manager.cc) ADD_ARROW_TEST(test/serialization_tests) ARROW_TEST_LINK_LIBRARIES(test/serialization_tests plasma_lib) +ADD_ARROW_TEST(test/client_tests) +ARROW_TEST_LINK_LIBRARIES(test/client_tests plasma_lib) diff --git a/cpp/src/plasma/client.h b/cpp/src/plasma/client.h index 67cb62fc194..b6b161afad4 100644 --- a/cpp/src/plasma/client.h +++ b/cpp/src/plasma/client.h @@ -64,7 +64,7 @@ class PlasmaClient { /// @param store_socket_name The name of the UNIX domain socket to use to /// connect to the Plasma store. /// @param manager_socket_name The name of the UNIX domain socket to use to - /// connect to the local Plasma manager. If this is NULL, then this + /// connect to the local Plasma manager. If this is "", then this /// function will not connect to a manager. /// @param release_delay Number of released objects that are kept around /// and not evicted to avoid too many munmaps. diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index 647f25a0d99..fad20eaf506 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -15,323 +15,119 @@ // specific language governing permissions and limitations // under the License. -#include "thirdparty/greatest.h" +#include "gtest/gtest.h" #include #include +#include #include +#include #include "plasma/client.h" #include "plasma/common.h" #include "plasma/plasma.h" #include "plasma/protocol.h" -SUITE(plasma_client_tests); - -TEST plasma_status_tests(void) { - PlasmaClient client1; - ARROW_CHECK_OK( - client1.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); - PlasmaClient client2; - ARROW_CHECK_OK( - client2.Connect("/tmp/store2", "/tmp/manager2", PLASMA_DEFAULT_RELEASE_DELAY)); - ObjectID oid1 = ObjectID::from_random(); - - /* Test for object non-existence. */ - int status; - ARROW_CHECK_OK(client1.Info(oid1, &status)); - ASSERT(status == ObjectStatus_Nonexistent); - - /* Test for the object being in local Plasma store. */ - /* First create object. */ - int64_t data_size = 100; - uint8_t metadata[] = {5}; - int64_t metadata_size = sizeof(metadata); - uint8_t* data; - ARROW_CHECK_OK(client1.Create(oid1, data_size, metadata, metadata_size, &data)); - ARROW_CHECK_OK(client1.Seal(oid1)); - /* Sleep to avoid race condition of Plasma Manager waiting for notification. - */ - sleep(1); - ARROW_CHECK_OK(client1.Info(oid1, &status)); - ASSERT(status == ObjectStatus_Local); - - /* Test for object being remote. */ - ARROW_CHECK_OK(client2.Info(oid1, &status)); - ASSERT(status == ObjectStatus_Remote); - - ARROW_CHECK_OK(client1.Disconnect()); - ARROW_CHECK_OK(client2.Disconnect()); - - PASS(); -} - -TEST plasma_fetch_tests(void) { - PlasmaClient client1; - ARROW_CHECK_OK( - client1.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); - PlasmaClient client2; - ARROW_CHECK_OK( - client2.Connect("/tmp/store2", "/tmp/manager2", PLASMA_DEFAULT_RELEASE_DELAY)); - ObjectID oid1 = ObjectID::from_random(); - - /* Test for object non-existence. */ - int status; - - /* No object in the system */ - ARROW_CHECK_OK(client1.Info(oid1, &status)); - ASSERT(status == ObjectStatus_Nonexistent); - - /* Test for the object being in local Plasma store. */ - /* First create object. */ - int64_t data_size = 100; - uint8_t metadata[] = {5}; - int64_t metadata_size = sizeof(metadata); - uint8_t* data; - ARROW_CHECK_OK(client1.Create(oid1, data_size, metadata, metadata_size, &data)); - ARROW_CHECK_OK(client1.Seal(oid1)); - - /* Object with ID oid1 has been just inserted. On the next fetch we might - * either find the object or not, depending on whether the Plasma Manager has - * received the notification from the Plasma Store or not. */ - ObjectID oid_array1[1] = {oid1}; - ARROW_CHECK_OK(client1.Fetch(1, oid_array1)); - ARROW_CHECK_OK(client1.Info(oid1, &status)); - ASSERT((status == ObjectStatus_Local) || (status == ObjectStatus_Nonexistent)); - - /* Sleep to make sure Plasma Manager got the notification. */ - sleep(1); - ARROW_CHECK_OK(client1.Info(oid1, &status)); - ASSERT(status == ObjectStatus_Local); - - /* Test for object being remote. */ - ARROW_CHECK_OK(client2.Info(oid1, &status)); - ASSERT(status == ObjectStatus_Remote); - - /* Sleep to make sure the object has been fetched and it is now stored in the - * local Plasma Store. */ - ARROW_CHECK_OK(client2.Fetch(1, oid_array1)); - sleep(1); - ARROW_CHECK_OK(client2.Info(oid1, &status)); - ASSERT(status == ObjectStatus_Local); - - sleep(1); - ARROW_CHECK_OK(client1.Disconnect()); - ARROW_CHECK_OK(client2.Disconnect()); - - PASS(); -} - -void init_data_123(uint8_t* data, uint64_t size, uint8_t base) { - for (int i = 0; i < size; i++) { - data[i] = base + i; - } -} - -bool is_equal_data_123(uint8_t* data1, uint8_t* data2, uint64_t size) { - for (int i = 0; i < size; i++) { - if (data1[i] != data2[i]) { return false; } +// TODO(pcm): At the moment, stdout of the test gets mixed up with +// stdout of the object store. Consider changing that. +pid_t start_store() { + pid_t pid = fork(); + if (pid != 0) { + return pid; } - return true; + execlp("./plasma_store", "./plasma_store", "-m", "10000000", "-s", "/tmp/store", NULL); + return 0; } -TEST plasma_nonblocking_get_tests(void) { +TEST(PlasmaClient, ContainsTest) { + pid_t store = start_store(); PlasmaClient client; - ARROW_CHECK_OK( - client.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); - ObjectID oid = ObjectID::from_random(); - ObjectID oid_array[1] = {oid}; - ObjectBuffer obj_buffer; + ARROW_CHECK_OK(client.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); - /* Test for object non-existence. */ - ARROW_CHECK_OK(client.Get(oid_array, 1, 0, &obj_buffer)); - ASSERT(obj_buffer.data_size == -1); + ObjectID object_id = ObjectID::from_random(); - /* Test for the object being in local Plasma store. */ - /* First create object. */ - int64_t data_size = 4; + // Test for object non-existence. + int has_object; + ARROW_CHECK_OK(client.Contains(object_id, &has_object)); + ASSERT_EQ(has_object, false); + + // Test for the object being in local Plasma store. + // First create object. + int64_t data_size = 100; uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); uint8_t* data; - ARROW_CHECK_OK(client.Create(oid, data_size, metadata, metadata_size, &data)); - init_data_123(data, data_size, 0); - ARROW_CHECK_OK(client.Seal(oid)); - - sleep(1); - ARROW_CHECK_OK(client.Get(oid_array, 1, 0, &obj_buffer)); - ASSERT(is_equal_data_123(data, obj_buffer.data, data_size) == true); + ARROW_CHECK_OK(client.Create(object_id, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client.Seal(object_id)); + // Avoid race condition of Plasma Manager waiting for notification. + ObjectBuffer object_buffer; + ARROW_CHECK_OK(client.Get(&object_id, 1, -1, &object_buffer)); + ARROW_CHECK_OK(client.Contains(object_id, &has_object)); + ASSERT_EQ(has_object, true); - sleep(1); ARROW_CHECK_OK(client.Disconnect()); - - PASS(); + kill(store, SIGKILL); } -TEST plasma_wait_for_objects_tests(void) { - PlasmaClient client1; - ARROW_CHECK_OK( - client1.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); - PlasmaClient client2; - ARROW_CHECK_OK( - client2.Connect("/tmp/store2", "/tmp/manager2", PLASMA_DEFAULT_RELEASE_DELAY)); - ObjectID oid1 = ObjectID::from_random(); - ObjectID oid2 = ObjectID::from_random(); -#define NUM_OBJ_REQUEST 2 -#define WAIT_TIMEOUT_MS 1000 - ObjectRequest obj_requests[NUM_OBJ_REQUEST]; - - obj_requests[0].object_id = oid1; - obj_requests[0].type = PLASMA_QUERY_ANYWHERE; - obj_requests[1].object_id = oid2; - obj_requests[1].type = PLASMA_QUERY_ANYWHERE; - - struct timeval start, end; - gettimeofday(&start, NULL); - int n; - ARROW_CHECK_OK( - client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); - ASSERT(n == 0); - gettimeofday(&end, NULL); - float diff_ms = (end.tv_sec - start.tv_sec); - diff_ms = (((diff_ms * 1000000.) + end.tv_usec) - (start.tv_usec)) / 1000.; - /* Reduce threshold by 10% to make sure we pass consistently. */ - ASSERT(diff_ms > WAIT_TIMEOUT_MS * 0.9); - - /* Create and insert an object in plasma_conn1. */ - int64_t data_size = 4; - uint8_t metadata[] = {5}; - int64_t metadata_size = sizeof(metadata); - uint8_t* data; - ARROW_CHECK_OK(client1.Create(oid1, data_size, metadata, metadata_size, &data)); - ARROW_CHECK_OK(client1.Seal(oid1)); - - ARROW_CHECK_OK( - client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); - ASSERT(n == 1); - - /* Create and insert an object in client2. */ - ARROW_CHECK_OK(client2.Create(oid2, data_size, metadata, metadata_size, &data)); - ARROW_CHECK_OK(client2.Seal(oid2)); - - ARROW_CHECK_OK( - client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); - ASSERT(n == 2); - - ARROW_CHECK_OK( - client2.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); - ASSERT(n == 2); - - obj_requests[0].type = PLASMA_QUERY_LOCAL; - obj_requests[1].type = PLASMA_QUERY_LOCAL; - ARROW_CHECK_OK( - client1.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); - ASSERT(n == 1); - - ARROW_CHECK_OK( - client2.Wait(NUM_OBJ_REQUEST, obj_requests, NUM_OBJ_REQUEST, WAIT_TIMEOUT_MS, n)); - ASSERT(n == 1); - - ARROW_CHECK_OK(client1.Disconnect()); - ARROW_CHECK_OK(client2.Disconnect()); - - PASS(); -} +TEST(PlasmaClient, GetTest) { + pid_t store = start_store(); + PlasmaClient client; + ARROW_CHECK_OK(client.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); -TEST plasma_get_tests(void) { - PlasmaClient client1, client2; - ARROW_CHECK_OK( - client1.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); - ARROW_CHECK_OK( - client2.Connect("/tmp/store2", "/tmp/manager2", PLASMA_DEFAULT_RELEASE_DELAY)); - ObjectID oid1 = ObjectID::from_random(); - ObjectID oid2 = ObjectID::from_random(); - ObjectBuffer obj_buffer; + ObjectID object_id = ObjectID::from_random(); + ObjectBuffer object_buffer; - ObjectID oid_array1[1] = {oid1}; - ObjectID oid_array2[1] = {oid2}; + // Test for object non-existence. + ARROW_CHECK_OK(client.Get(&object_id, 1, 0, &object_buffer)); + ASSERT_EQ(object_buffer.data_size, -1); + // Test for the object being in local Plasma store. + // First create object. int64_t data_size = 4; uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); uint8_t* data; - ARROW_CHECK_OK(client1.Create(oid1, data_size, metadata, metadata_size, &data)); - init_data_123(data, data_size, 1); - ARROW_CHECK_OK(client1.Seal(oid1)); - - ARROW_CHECK_OK(client1.Get(oid_array1, 1, -1, &obj_buffer)); - ASSERT(data[0] == obj_buffer.data[0]); - - ARROW_CHECK_OK(client2.Create(oid2, data_size, metadata, metadata_size, &data)); - init_data_123(data, data_size, 2); - ARROW_CHECK_OK(client2.Seal(oid2)); - - ARROW_CHECK_OK(client1.Fetch(1, oid_array2)); - ARROW_CHECK_OK(client1.Get(oid_array2, 1, -1, &obj_buffer)); - ASSERT(data[0] == obj_buffer.data[0]); + ARROW_CHECK_OK(client.Create(object_id, data_size, metadata, metadata_size, &data)); + for (int64_t i = 0; i < data_size; i++) { + data[i] = static_cast(i % 4); + } + ARROW_CHECK_OK(client.Seal(object_id)); - sleep(1); - ARROW_CHECK_OK(client1.Disconnect()); - ARROW_CHECK_OK(client2.Disconnect()); + ARROW_CHECK_OK(client.Get(&object_id, 1, -1, &object_buffer)); + for (int64_t i = 0; i < data_size; i++) { + ASSERT_EQ(data[i], object_buffer.data[i]); + } - PASS(); + ARROW_CHECK_OK(client.Disconnect()); + kill(store, SIGKILL); } -TEST plasma_get_multiple_tests(void) { - PlasmaClient client1, client2; - ARROW_CHECK_OK( - client1.Connect("/tmp/store1", "/tmp/manager1", PLASMA_DEFAULT_RELEASE_DELAY)); - ARROW_CHECK_OK( - client2.Connect("/tmp/store2", "/tmp/manager2", PLASMA_DEFAULT_RELEASE_DELAY)); - ObjectID oid1 = ObjectID::from_random(); - ObjectID oid2 = ObjectID::from_random(); - ObjectID obj_ids[NUM_OBJ_REQUEST]; - ObjectBuffer obj_buffer[NUM_OBJ_REQUEST]; - int obj1_first = 1, obj2_first = 2; +TEST(PlasmaClient, MultipleGetTest) { + pid_t store = start_store(); + PlasmaClient client; + ARROW_CHECK_OK(client.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); - obj_ids[0] = oid1; - obj_ids[1] = oid2; + ObjectID object_id1 = ObjectID::from_random(); + ObjectID object_id2 = ObjectID::from_random(); + ObjectID object_ids[2] = {object_id1, object_id2}; + ObjectBuffer object_buffer[2]; int64_t data_size = 4; uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); uint8_t* data; - ARROW_CHECK_OK(client1.Create(oid1, data_size, metadata, metadata_size, &data)); - init_data_123(data, data_size, obj1_first); - ARROW_CHECK_OK(client1.Seal(oid1)); + ARROW_CHECK_OK(client.Create(object_id1, data_size, metadata, metadata_size, &data)); + data[0] = 1; + ARROW_CHECK_OK(client.Seal(object_id1)); - /* This only waits for oid1. */ - ARROW_CHECK_OK(client1.Get(obj_ids, 1, -1, obj_buffer)); - ASSERT(data[0] == obj_buffer[0].data[0]); + ARROW_CHECK_OK(client.Create(object_id2, data_size, metadata, metadata_size, &data)); + data[0] = 2; + ARROW_CHECK_OK(client.Seal(object_id2)); - ARROW_CHECK_OK(client2.Create(oid2, data_size, metadata, metadata_size, &data)); - init_data_123(data, data_size, obj2_first); - ARROW_CHECK_OK(client2.Seal(oid2)); + ARROW_CHECK_OK(client.Get(object_ids, 2, -1, object_buffer)); + ASSERT_EQ(object_buffer[0].data[0], 1); + ASSERT_EQ(object_buffer[1].data[0], 2); - ARROW_CHECK_OK(client1.Fetch(2, obj_ids)); - ARROW_CHECK_OK(client1.Get(obj_ids, 2, -1, obj_buffer)); - ASSERT(obj1_first == obj_buffer[0].data[0]); - ASSERT(obj2_first == obj_buffer[1].data[0]); - - sleep(1); - ARROW_CHECK_OK(client1.Disconnect()); - ARROW_CHECK_OK(client2.Disconnect()); - - PASS(); -} - -SUITE(plasma_client_tests) { - RUN_TEST(plasma_status_tests); - RUN_TEST(plasma_fetch_tests); - RUN_TEST(plasma_nonblocking_get_tests); - RUN_TEST(plasma_wait_for_objects_tests); - RUN_TEST(plasma_get_tests); - RUN_TEST(plasma_get_multiple_tests); -} - -GREATEST_MAIN_DEFS(); - -int main(int argc, char** argv) { - GREATEST_MAIN_BEGIN(); - RUN_SUITE(plasma_client_tests); - GREATEST_MAIN_END(); + ARROW_CHECK_OK(client.Disconnect()); + kill(store, SIGKILL); } From 217ff3d8b7d6fd39e9f6798501c793772a79adef Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Thu, 15 Jun 2017 09:22:49 -0700 Subject: [PATCH 25/53] add valgrind heuristic --- cpp/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 37a1647065e..34f89a8cea9 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -362,7 +362,7 @@ function(ADD_ARROW_TEST REL_TEST_NAME) APPEND_STRING PROPERTY COMPILE_FLAGS " -DARROW_VALGRIND") add_test(${TEST_NAME} - valgrind --tool=memcheck --leak-check=full --error-exitcode=1 ${TEST_PATH}) + valgrind --tool=memcheck --leak-check=full --leak-check-heuristics=stdstring --error-exitcode=1 ${TEST_PATH}) elseif(MSVC) add_test(${TEST_NAME} ${TEST_PATH}) else() From 7003a4a43b81523476e976f524b1c15779eff085 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Thu, 15 Jun 2017 13:43:10 -0700 Subject: [PATCH 26/53] fix valgrind test by setting working directory --- cpp/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 34f89a8cea9..32489cf52f7 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -362,7 +362,7 @@ function(ADD_ARROW_TEST REL_TEST_NAME) APPEND_STRING PROPERTY COMPILE_FLAGS " -DARROW_VALGRIND") add_test(${TEST_NAME} - valgrind --tool=memcheck --leak-check=full --leak-check-heuristics=stdstring --error-exitcode=1 ${TEST_PATH}) + bash -c "cd ${EXECUTABLE_OUTPUT_PATH}; valgrind --tool=memcheck --leak-check=full --leak-check-heuristics=stdstring --error-exitcode=1 ${TEST_PATH}") elseif(MSVC) add_test(${TEST_NAME} ${TEST_PATH}) else() From 65ac74336649047bfdd4104b8248162d1c005302 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sun, 18 Jun 2017 20:44:01 -0700 Subject: [PATCH 27/53] remove offending c++ flag from c flags --- cpp/CMakeLists.txt | 4 +++- cpp/src/plasma/CMakeLists.txt | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 32489cf52f7..78dfc0cab8b 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -186,7 +186,9 @@ endif() include(san-config) # For any C code, use the same flags. -# set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS}") +set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS}") +# Remove --std=c++11 to avoid errors from C compilers +string(REPLACE "-std=c++11" "" CMAKE_C_FLAGS ${CMAKE_C_FLAGS}) # Code coverage if ("${ARROW_GENERATE_COVERAGE}") diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index 059759c3463..cc2a1053b5a 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -35,6 +35,8 @@ include_directories("${FLATBUFFERS_INCLUDE_DIR}" "${CMAKE_CURRENT_LIST_DIR}/" "$ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++11 -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200809L -march=native -mtune=native -O3") +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-conversion") + # Compile flatbuffers set(PLASMA_FBS_SRC "${CMAKE_CURRENT_LIST_DIR}/format/plasma.fbs" "${CMAKE_CURRENT_LIST_DIR}/format/common.fbs") From 8daea699f851350729fcd1b17bf486741d8a64ac Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sun, 18 Jun 2017 21:36:50 -0700 Subject: [PATCH 28/53] fix includes according to google styleguide --- cpp/src/plasma/client.cc | 12 ++++++------ cpp/src/plasma/extension.cc | 7 ++++--- cpp/src/plasma/io.cc | 1 + cpp/src/plasma/malloc.cc | 3 ++- cpp/src/plasma/malloc.h | 3 +++ cpp/src/plasma/plasma.cc | 3 ++- cpp/src/plasma/plasma.h | 3 +-- cpp/src/plasma/protocol.cc | 3 ++- cpp/src/plasma/protocol.h | 4 ++-- cpp/src/plasma/store.cc | 3 ++- 10 files changed, 25 insertions(+), 17 deletions(-) diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index 69dd826c25b..168531d7b9f 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -17,6 +17,8 @@ // PLASMA CLIENT: Client library for using the plasma store and manager +#include "plasma/client.h" + #ifdef _WIN32 #include #endif @@ -34,17 +36,15 @@ #include #include -#include "plasma/client.h" -#include "plasma/common.h" -#include "plasma/io.h" -#include "plasma/plasma.h" -#include "plasma/protocol.h" - #include #include #include +#include "plasma/common.h" #include "plasma/fling.h" +#include "plasma/io.h" +#include "plasma/plasma.h" +#include "plasma/protocol.h" #define XXH_STATIC_LINKING_ONLY #include "thirdparty/xxhash.h" diff --git a/cpp/src/plasma/extension.cc b/cpp/src/plasma/extension.cc index 11f3cd6f75a..99fd35572ad 100644 --- a/cpp/src/plasma/extension.cc +++ b/cpp/src/plasma/extension.cc @@ -16,14 +16,15 @@ // under the License. #include "plasma/extension.h" + +#include +#include + #include "plasma/client.h" #include "plasma/common.h" #include "plasma/io.h" #include "plasma/protocol.h" -#include -#include - PyObject* PlasmaOutOfMemoryError; PyObject* PlasmaObjectExistsError; diff --git a/cpp/src/plasma/io.cc b/cpp/src/plasma/io.cc index 213016d5d5a..755b8d7eef8 100644 --- a/cpp/src/plasma/io.cc +++ b/cpp/src/plasma/io.cc @@ -16,6 +16,7 @@ // under the License. #include "plasma/io.h" + #include "plasma/common.h" using arrow::Status; diff --git a/cpp/src/plasma/malloc.cc b/cpp/src/plasma/malloc.cc index 317f9b3de4d..e7ffd1ad377 100644 --- a/cpp/src/plasma/malloc.cc +++ b/cpp/src/plasma/malloc.cc @@ -15,6 +15,8 @@ // specific language governing permissions and limitations // under the License. +#include "plasma/malloc.h" + #include #include #include @@ -26,7 +28,6 @@ #include #include "plasma/common.h" -#include "plasma/malloc.h" extern "C" { void* fake_mmap(size_t); diff --git a/cpp/src/plasma/malloc.h b/cpp/src/plasma/malloc.h index f89a4a9810e..a1c387a7ce7 100644 --- a/cpp/src/plasma/malloc.h +++ b/cpp/src/plasma/malloc.h @@ -18,6 +18,9 @@ #ifndef MALLOC_H #define MALLOC_H +#include +#include + void get_malloc_mapinfo(void* addr, int* fd, int64_t* map_length, ptrdiff_t* offset); #endif /* MALLOC_H */ diff --git a/cpp/src/plasma/plasma.cc b/cpp/src/plasma/plasma.cc index 70e10983fed..2c892781c93 100644 --- a/cpp/src/plasma/plasma.cc +++ b/cpp/src/plasma/plasma.cc @@ -15,12 +15,13 @@ // specific language governing permissions and limitations // under the License. +#include "plasma/plasma.h" + #include #include #include #include "plasma/common.h" -#include "plasma/plasma.h" #include "plasma/protocol.h" int warn_if_sigpipe(int status, int client_sock) { diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h index 39ba2a3e679..11d69765f0c 100644 --- a/cpp/src/plasma/plasma.h +++ b/cpp/src/plasma/plasma.h @@ -18,6 +18,7 @@ #ifndef PLASMA_H #define PLASMA_H +#include #include #include #include @@ -34,8 +35,6 @@ #include "format/common_generated.h" #include "plasma/common.h" -#include - #define HANDLE_SIGPIPE(s, fd_) \ do { \ Status _s = (s); \ diff --git a/cpp/src/plasma/protocol.cc b/cpp/src/plasma/protocol.cc index 7ffea2eca3b..d1339c22f9e 100644 --- a/cpp/src/plasma/protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -15,12 +15,13 @@ // specific language governing permissions and limitations // under the License. +#include "plasma/protocol.h" + #include "flatbuffers/flatbuffers.h" #include "format/plasma_generated.h" #include "plasma/common.h" #include "plasma/io.h" -#include "plasma/protocol.h" using flatbuffers::uoffset_t; diff --git a/cpp/src/plasma/protocol.h b/cpp/src/plasma/protocol.h index 118ab7474c0..e261a623c4d 100644 --- a/cpp/src/plasma/protocol.h +++ b/cpp/src/plasma/protocol.h @@ -18,12 +18,12 @@ #ifndef PLASMA_PROTOCOL_H #define PLASMA_PROTOCOL_H +#include + #include "arrow/status.h" #include "format/plasma_generated.h" #include "plasma/plasma.h" -#include - using arrow::Status; /* Plasma receive message. */ diff --git a/cpp/src/plasma/store.cc b/cpp/src/plasma/store.cc index 73fddc2f354..80357e42bea 100644 --- a/cpp/src/plasma/store.cc +++ b/cpp/src/plasma/store.cc @@ -26,6 +26,8 @@ // It keeps a hash table that maps object_ids (which are 20 byte long, // just enough to store and SHA1 hash) to memory mapped files. +#include "plasma/store.h" + #include #include #include @@ -52,7 +54,6 @@ #include "plasma/fling.h" #include "plasma/io.h" #include "plasma/malloc.h" -#include "plasma/store.h" extern "C" { void* dlmalloc(size_t bytes); From 0fdd4cd5c3d9c23ff736120751a90f20878b149a Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sun, 18 Jun 2017 21:49:52 -0700 Subject: [PATCH 29/53] link libarrow.a and remove hardcoded optimization flags --- cpp/src/plasma/CMakeLists.txt | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index cc2a1053b5a..fa7f803bc4c 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -33,7 +33,7 @@ endif(APPLE) include_directories(SYSTEM ${PYTHON_INCLUDE_DIRS}) include_directories("${FLATBUFFERS_INCLUDE_DIR}" "${CMAKE_CURRENT_LIST_DIR}/" "${CMAKE_CURRENT_LIST_DIR}/thirdparty/" "${CMAKE_CURRENT_LIST_DIR}/../") -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --std=c++11 -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200809L -march=native -mtune=native -O3") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_XOPEN_SOURCE=500 -D_POSIX_C_SOURCE=200809L") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wno-conversion") @@ -94,11 +94,10 @@ add_library(plasma_lib STATIC common.cc io.cc protocol.cc - ../arrow/status.cc fling.cc thirdparty/xxhash.cc) -target_link_libraries(plasma_lib ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT}) +target_link_libraries(plasma_lib ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT} arrow_static) add_dependencies(plasma_lib gen_plasma_fbs) set_source_files_properties(malloc.cc PROPERTIES COMPILE_FLAGS "-Wno-error=conversion") From 77d98227471e941ded1945b1f20a29a42cea1190 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sun, 18 Jun 2017 22:20:16 -0700 Subject: [PATCH 30/53] put all the object code into a common library --- cpp/src/plasma/CMakeLists.txt | 71 +++++++++++++---------------------- 1 file changed, 26 insertions(+), 45 deletions(-) diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index fa7f803bc4c..b4f5fb00b3d 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -65,65 +65,46 @@ if(UNIX AND NOT APPLE) link_libraries(rt) endif() -if(PLASMA_PYTHON) - add_library(plasma SHARED - plasma.cc - extension.cc - protocol.cc - client.cc - thirdparty/xxhash.cc - fling.cc) - - add_dependencies(plasma gen_plasma_fbs) - - if(APPLE) - target_link_libraries(plasma plasma_lib "-undefined dynamic_lookup" ${FLATBUFFERS_STATIC_LIB} ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT}) - else(APPLE) - target_link_libraries(plasma plasma_lib -Wl,--whole-archive ${FLATBUFFERS_STATIC_LIB} -Wl,--no-whole-archive ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT}) - endif(APPLE) -endif() - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") set_source_files_properties(thirdparty/dlmalloc.c PROPERTIES COMPILE_FLAGS -Wno-all) set_source_files_properties(extension.cc PROPERTIES COMPILE_FLAGS -Wno-strict-aliasing) -add_library(plasma_lib STATIC +set(PLASMA_SRCS client.cc - plasma.cc common.cc + eviction_policy.cc + events.cc + fling.cc io.cc + malloc.cc + plasma.cc protocol.cc - fling.cc + thirdparty/ae/ae.c thirdparty/xxhash.cc) -target_link_libraries(plasma_lib ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT} arrow_static) -add_dependencies(plasma_lib gen_plasma_fbs) +ADD_ARROW_LIB(plasma + SOURCES ${PLASMA_SRCS} + DEPENDENCIES gen_plasma_fbs + SHARED_LINK_LIBS ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT} arrow_static + STATIC_LINK_LIBS ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT} arrow_static) set_source_files_properties(malloc.cc PROPERTIES COMPILE_FLAGS "-Wno-error=conversion") -add_executable(plasma_store - store.cc - thirdparty/ae/ae.c - plasma.cc - events.cc - protocol.cc - eviction_policy.cc - fling.cc - malloc.cc) - -add_dependencies(plasma_store gen_plasma_fbs) - -target_link_libraries(plasma_store plasma_lib ${FLATBUFFERS_STATIC_LIB}) - -add_library(plasma_client SHARED client.cc) -target_link_libraries(plasma_client ${FLATBUFFERS_STATIC_LIB}) +add_executable(plasma_store store.cc) +target_link_libraries(plasma_store plasma_static) -target_link_libraries(plasma_client plasma_lib ${FLATBUFFERS_STATIC_LIB}) - -# define_test(client_tests plasma_lib) -# define_test(manager_tests plasma_lib plasma_manager.cc) ADD_ARROW_TEST(test/serialization_tests) -ARROW_TEST_LINK_LIBRARIES(test/serialization_tests plasma_lib) +ARROW_TEST_LINK_LIBRARIES(test/serialization_tests plasma_static) ADD_ARROW_TEST(test/client_tests) -ARROW_TEST_LINK_LIBRARIES(test/client_tests plasma_lib) +ARROW_TEST_LINK_LIBRARIES(test/client_tests plasma_static) + +if(PLASMA_PYTHON) + add_library(plasma_extension SHARED extension.cc) + + if(APPLE) + target_link_libraries(plasma plasma_static "-undefined dynamic_lookup") + else(APPLE) + target_link_libraries(plasma plasma_static -Wl,--whole-archive ${FLATBUFFERS_STATIC_LIB} -Wl,--no-whole-archive) + endif(APPLE) +endif() From 30bd68b70d827bd7cadbded8530aae840207c6a7 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sun, 18 Jun 2017 23:03:37 -0700 Subject: [PATCH 31/53] remove plain pointer in plasma client, part I --- cpp/src/plasma/client.cc | 39 ++++++++++++--------------------------- cpp/src/plasma/client.h | 13 +++++++++++-- 2 files changed, 23 insertions(+), 29 deletions(-) diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index 168531d7b9f..4d2f731c8e5 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -56,16 +56,6 @@ constexpr int64_t kThreadPoolSize = 8; constexpr int64_t kBytesInMB = 1 << 20; static std::vector threadpool_(kThreadPoolSize); -struct ClientMmapTableEntry { - /// The result of mmap for this file descriptor. - uint8_t* pointer; - /// The length of the memory-mapped file. - size_t length; - /// The number of objects in this memory-mapped file that are currently being - /// used by the client. When this count reaches zeros, we unmap the file. - int count; -}; - struct ObjectInUseEntry { /// A count of the number of times this client has called PlasmaClient::Create /// or @@ -87,17 +77,16 @@ uint8_t* lookup_or_mmap(PlasmaClient* conn, int fd, int store_fd_val, int64_t ma auto entry = conn->mmap_table.find(store_fd_val); if (entry != conn->mmap_table.end()) { close(fd); - return entry->second->pointer; + return entry->second.pointer; } else { uint8_t* result = reinterpret_cast( mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); if (result == MAP_FAILED) { ARROW_LOG(FATAL) << "mmap failed"; } close(fd); - ClientMmapTableEntry* entry = new ClientMmapTableEntry(); - entry->pointer = result; - entry->length = map_size; - entry->count = 0; - conn->mmap_table[store_fd_val] = entry; + ClientMmapTableEntry& entry = conn->mmap_table[store_fd_val]; + entry.pointer = result; + entry.length = map_size; + entry.count = 0; return result; } } @@ -107,7 +96,7 @@ uint8_t* lookup_or_mmap(PlasmaClient* conn, int fd, int store_fd_val, int64_t ma uint8_t* lookup_mmapped_file(PlasmaClient* conn, int store_fd_val) { auto entry = conn->mmap_table.find(store_fd_val); ARROW_CHECK(entry != conn->mmap_table.end()); - return entry->second->pointer; + return entry->second.pointer; } void increment_object_count( @@ -129,11 +118,11 @@ void increment_object_count( // PlasmaClient::Release. auto entry = conn->mmap_table.find(object->handle.store_fd); ARROW_CHECK(entry != conn->mmap_table.end()); - ARROW_CHECK(entry->second->count >= 0); + ARROW_CHECK(entry->second.count >= 0); // Update the in_use_object_bytes. conn->in_use_object_bytes += (object_entry->object.data_size + object_entry->object.metadata_size); - entry->second->count += 1; + entry->second.count += 1; } else { object_entry = elem->second; ARROW_CHECK(object_entry->count > 0); @@ -302,13 +291,12 @@ Status PlasmaClient::PerformRelease(ObjectID object_id) { int fd = object_entry->second->object.handle.store_fd; auto entry = mmap_table.find(fd); ARROW_CHECK(entry != mmap_table.end()); - entry->second->count -= 1; - ARROW_CHECK(entry->second->count >= 0); + entry->second.count -= 1; + ARROW_CHECK(entry->second.count >= 0); // If none are being used then unmap the file. - if (entry->second->count == 0) { - munmap(entry->second->pointer, entry->second->length); + if (entry->second.count == 0) { + munmap(entry->second.pointer, entry->second.length); // Remove the corresponding entry from the hash table. - delete entry->second; mmap_table.erase(fd); } // Tell the store that the client no longer needs the object. @@ -514,9 +502,6 @@ Status PlasmaClient::Disconnect() { for (auto& entry : objects_in_use) { delete entry.second; } - for (auto& entry : mmap_table) { - delete entry.second; - } // Close the connections to Plasma. The Plasma store will release the objects // that were in use by us when handling the SIGPIPE. close(store_conn); diff --git a/cpp/src/plasma/client.h b/cpp/src/plasma/client.h index b6b161afad4..394a3f2224b 100644 --- a/cpp/src/plasma/client.h +++ b/cpp/src/plasma/client.h @@ -53,7 +53,16 @@ struct PlasmaClientConfig { size_t release_delay; }; -struct ClientMmapTableEntry; +struct ClientMmapTableEntry { + /// The result of mmap for this file descriptor. + uint8_t* pointer; + /// The length of the memory-mapped file. + size_t length; + /// The number of objects in this memory-mapped file that are currently being + /// used by the client. When this count reaches zeros, we unmap the file. + int count; +}; + struct ObjectInUseEntry; class PlasmaClient { @@ -278,7 +287,7 @@ class PlasmaClient { /// Table of dlmalloc buffer files that have been memory mapped so far. This /// is a hash table mapping a file descriptor to a struct containing the /// address of the corresponding memory-mapped file. - std::unordered_map mmap_table; + std::unordered_map mmap_table; /// A hash table of the object IDs that are currently being used by this /// client. std::unordered_map objects_in_use; From 627b7c75b41c0e4bad44c0f897c61f4a5af3cb63 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sun, 18 Jun 2017 23:26:11 -0700 Subject: [PATCH 32/53] fix python extension name --- cpp/src/plasma/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index b4f5fb00b3d..4cc09e6d051 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -103,8 +103,8 @@ if(PLASMA_PYTHON) add_library(plasma_extension SHARED extension.cc) if(APPLE) - target_link_libraries(plasma plasma_static "-undefined dynamic_lookup") + target_link_libraries(plasma_extension plasma_static "-undefined dynamic_lookup") else(APPLE) - target_link_libraries(plasma plasma_static -Wl,--whole-archive ${FLATBUFFERS_STATIC_LIB} -Wl,--no-whole-archive) + target_link_libraries(plasma_extension plasma_static -Wl,--whole-archive ${FLATBUFFERS_STATIC_LIB} -Wl,--no-whole-archive) endif(APPLE) endif() From ca80e9a6bc7948a184ff4e9969db697e306bc382 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Sun, 18 Jun 2017 23:47:51 -0700 Subject: [PATCH 33/53] remove plain pointer in plasma client, part II --- cpp/src/plasma/client.cc | 34 ++++++++-------------------------- cpp/src/plasma/client.h | 16 ++++++++++++++-- 2 files changed, 22 insertions(+), 28 deletions(-) diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index 4d2f731c8e5..7ab06badeaf 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -56,20 +56,6 @@ constexpr int64_t kThreadPoolSize = 8; constexpr int64_t kBytesInMB = 1 << 20; static std::vector threadpool_(kThreadPoolSize); -struct ObjectInUseEntry { - /// A count of the number of times this client has called PlasmaClient::Create - /// or - /// PlasmaClient::Get on this object ID minus the number of calls to - /// PlasmaClient::Release. - /// When this count reaches zero, we remove the entry from the ObjectsInUse - /// and decrement a count in the relevant ClientMmapTableEntry. - int count; - /// Cached information to read the object. - PlasmaObject object; - /// A flag representing whether the object has been sealed. - bool is_sealed; -}; - // If the file descriptor fd has been mmapped in this client process before, // return the pointer that was returned by mmap, otherwise mmap it and store the // pointer in a hash table. @@ -108,11 +94,11 @@ void increment_object_count( if (elem == conn->objects_in_use.end()) { // Add this object ID to the hash table of object IDs in use. The // corresponding call to free happens in PlasmaClient::Release. - object_entry = new ObjectInUseEntry(); - object_entry->object = *object; - object_entry->count = 0; - object_entry->is_sealed = is_sealed; - conn->objects_in_use[object_id] = object_entry; + conn->objects_in_use[object_id] = std::unique_ptr(new ObjectInUseEntry()); + conn->objects_in_use[object_id]->object = *object; + conn->objects_in_use[object_id]->count = 0; + conn->objects_in_use[object_id]->is_sealed = is_sealed; + object_entry = conn->objects_in_use[object_id].get(); // Increment the count of the number of objects in the memory-mapped file // that are being used. The corresponding decrement should happen in // PlasmaClient::Release. @@ -124,7 +110,7 @@ void increment_object_count( (object_entry->object.data_size + object_entry->object.metadata_size); entry->second.count += 1; } else { - object_entry = elem->second; + object_entry = elem->second.get(); ARROW_CHECK(object_entry->count > 0); } // Increment the count of the number of instances of this object that are @@ -306,7 +292,6 @@ Status PlasmaClient::PerformRelease(ObjectID object_id) { object_entry->second->object.metadata_size); DCHECK_GE(in_use_object_bytes, 0); // Remove the entry from the hash table of objects currently in use. - delete object_entry->second; objects_in_use.erase(object_id); } return Status::OK(); @@ -497,11 +482,8 @@ Status PlasmaClient::Connect(const std::string& store_socket_name, Status PlasmaClient::Disconnect() { // NOTE: We purposefully do not finish sending release calls for objects in // use, so that we don't duplicate PlasmaClient::Release calls (when handling - // a - // SIGTERM, for example). - for (auto& entry : objects_in_use) { - delete entry.second; - } + // a SIGTERM, for example). + // Close the connections to Plasma. The Plasma store will release the objects // that were in use by us when handling the SIGPIPE. close(store_conn); diff --git a/cpp/src/plasma/client.h b/cpp/src/plasma/client.h index 394a3f2224b..c00dedbd4c7 100644 --- a/cpp/src/plasma/client.h +++ b/cpp/src/plasma/client.h @@ -63,7 +63,19 @@ struct ClientMmapTableEntry { int count; }; -struct ObjectInUseEntry; +struct ObjectInUseEntry { + /// A count of the number of times this client has called PlasmaClient::Create + /// or + /// PlasmaClient::Get on this object ID minus the number of calls to + /// PlasmaClient::Release. + /// When this count reaches zero, we remove the entry from the ObjectsInUse + /// and decrement a count in the relevant ClientMmapTableEntry. + int count; + /// Cached information to read the object. + PlasmaObject object; + /// A flag representing whether the object has been sealed. + bool is_sealed; +}; class PlasmaClient { public: @@ -290,7 +302,7 @@ class PlasmaClient { std::unordered_map mmap_table; /// A hash table of the object IDs that are currently being used by this /// client. - std::unordered_map objects_in_use; + std::unordered_map, UniqueIDHasher> objects_in_use; /// Object IDs of the last few release calls. This is a deque and /// is used to delay releasing objects to see if they can be reused by /// subsequent tasks so we do not unneccessarily invalidate cpu caches. From 7b08fd2abadf6e5cd6d18a6f45fc2463db117316 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Mon, 19 Jun 2017 00:11:58 -0700 Subject: [PATCH 34/53] replace ObjectID pass by value with pass by const reference and fix const correctness --- cpp/src/plasma/client.cc | 38 +++++++++++++++---------------- cpp/src/plasma/client.h | 16 ++++++------- cpp/src/plasma/eviction_policy.cc | 6 ++--- cpp/src/plasma/eviction_policy.h | 6 ++--- cpp/src/plasma/plasma.cc | 2 +- cpp/src/plasma/plasma.h | 2 +- cpp/src/plasma/protocol.cc | 4 ++-- cpp/src/plasma/protocol.h | 2 +- cpp/src/plasma/store.cc | 10 ++++---- cpp/src/plasma/store.h | 10 ++++---- 10 files changed, 48 insertions(+), 48 deletions(-) diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index 7ab06badeaf..aff23d1f750 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -86,7 +86,7 @@ uint8_t* lookup_mmapped_file(PlasmaClient* conn, int store_fd_val) { } void increment_object_count( - PlasmaClient* conn, ObjectID object_id, PlasmaObject* object, bool is_sealed) { + PlasmaClient* conn, const ObjectID& object_id, PlasmaObject* object, bool is_sealed) { // Increment the count of the object to track the fact that it is being used. // The corresponding decrement should happen in PlasmaClient::Release. auto elem = conn->objects_in_use.find(object_id); @@ -119,7 +119,7 @@ void increment_object_count( object_entry->count += 1; } -Status PlasmaClient::Create(ObjectID object_id, int64_t data_size, uint8_t* metadata, +Status PlasmaClient::Create(const ObjectID& object_id, int64_t data_size, uint8_t* metadata, int64_t metadata_size, uint8_t** data) { ARROW_LOG(DEBUG) << "called plasma_create on conn " << store_conn << " with size " << data_size << " and metadata size " << metadata_size; @@ -261,7 +261,7 @@ Status PlasmaClient::Get(ObjectID object_ids[], int64_t num_objects, int64_t tim /// /// @param conn The plasma connection. /// @param object_id The object ID to attempt to release. -Status PlasmaClient::PerformRelease(ObjectID object_id) { +Status PlasmaClient::PerformRelease(const ObjectID& object_id) { // Decrement the count of the number of instances of this object that are // being used by this client. The corresponding increment should have happened // in PlasmaClient::Get. @@ -297,7 +297,7 @@ Status PlasmaClient::PerformRelease(ObjectID object_id) { return Status::OK(); } -Status PlasmaClient::Release(ObjectID object_id) { +Status PlasmaClient::Release(const ObjectID& object_id) { // Add the new object to the release history. release_history.push_front(object_id); // If there are too many bytes in use by the client or if there are too many @@ -315,7 +315,7 @@ Status PlasmaClient::Release(ObjectID object_id) { } // This method is used to query whether the plasma store contains an object. -Status PlasmaClient::Contains(ObjectID object_id, int* has_object) { +Status PlasmaClient::Contains(const ObjectID& object_id, int* has_object) { // Check if we already have a reference to the object. if (objects_in_use.count(object_id) > 0) { *has_object = 1; @@ -386,25 +386,22 @@ static uint64_t compute_object_hash(const ObjectBuffer& obj_buffer) { } bool plasma_compute_object_hash( - PlasmaClient* conn, ObjectID obj_id, unsigned char* digest) { + PlasmaClient* conn, ObjectID object_id, unsigned char* digest) { // Get the plasma object data. We pass in a timeout of 0 to indicate that // the operation should timeout immediately. - ObjectBuffer obj_buffer; - ObjectID obj_id_array[1] = {obj_id}; - uint64_t hash; - - ARROW_CHECK_OK(conn->Get(obj_id_array, 1, 0, &obj_buffer)); + ObjectBuffer object_buffer; + ARROW_CHECK_OK(conn->Get(&object_id, 1, 0, &object_buffer)); // If the object was not retrieved, return false. - if (obj_buffer.data_size == -1) { return false; } + if (object_buffer.data_size == -1) { return false; } // Compute the hash. - hash = compute_object_hash(obj_buffer); + uint64_t hash = compute_object_hash(object_buffer); memcpy(digest, &hash, sizeof(hash)); // Release the plasma object. - ARROW_CHECK_OK(conn->Release(obj_id)); + ARROW_CHECK_OK(conn->Release(object_id)); return true; } -Status PlasmaClient::Seal(ObjectID object_id) { +Status PlasmaClient::Seal(const ObjectID& object_id) { // Make sure this client has a reference to the object before sending the // request to Plasma. auto object_entry = objects_in_use.find(object_id); @@ -425,7 +422,7 @@ Status PlasmaClient::Seal(ObjectID object_id) { return Release(object_id); } -Status PlasmaClient::Delete(ObjectID object_id) { +Status PlasmaClient::Delete(const ObjectID& object_id) { // TODO(rkn): In the future, we can use this method to give hints to the // eviction policy about when an object will no longer be needed. return Status::NotImplemented("PlasmaClient::Delete is not implemented."); @@ -497,7 +494,7 @@ bool plasma_manager_is_connected(PlasmaClient* conn) { #define h_addr h_addr_list[0] -Status PlasmaClient::Transfer(const char* address, int port, ObjectID object_id) { +Status PlasmaClient::Transfer(const char* address, int port, const ObjectID& object_id) { return SendDataRequest(manager_conn, object_id, address, port); } @@ -510,13 +507,16 @@ int get_manager_fd(PlasmaClient* conn) { return conn->manager_conn; } -Status PlasmaClient::Info(ObjectID object_id, int* object_status) { +Status PlasmaClient::Info(const ObjectID& object_id, int* object_status) { ARROW_CHECK(manager_conn >= 0); RETURN_NOT_OK(SendStatusRequest(manager_conn, &object_id, 1)); std::vector buffer; RETURN_NOT_OK(PlasmaReceive(manager_conn, MessageType_PlasmaStatusReply, buffer)); - return ReadStatusReply(buffer.data(), &object_id, object_status, 1); + ObjectID id; + RETURN_NOT_OK(ReadStatusReply(buffer.data(), &id, object_status, 1)); + ARROW_CHECK(object_id == id); + return Status::OK(); } Status PlasmaClient::Wait(int64_t num_object_requests, ObjectRequest object_requests[], diff --git a/cpp/src/plasma/client.h b/cpp/src/plasma/client.h index c00dedbd4c7..8be36f7824a 100644 --- a/cpp/src/plasma/client.h +++ b/cpp/src/plasma/client.h @@ -107,7 +107,7 @@ class PlasmaClient { /// metadata, this should be 0. /// @param data The address of the newly created object will be written here. /// @return The return status. - Status Create(ObjectID object_id, int64_t data_size, uint8_t* metadata, + Status Create(const ObjectID& object_id, int64_t data_size, uint8_t* metadata, int64_t metadata_size, uint8_t** data); /// Get some objects from the Plasma Store. This function will block until the @@ -136,7 +136,7 @@ class PlasmaClient { /// /// @param object_id The ID of the object that is no longer needed. /// @return The return status. - Status Release(ObjectID object_id); + Status Release(const ObjectID& object_id); /// Check if the object store contains a particular object and the object has /// been sealed. The result will be stored in has_object. @@ -149,7 +149,7 @@ class PlasmaClient { /// is /// present and 0 if it is not present. /// @return The return status. - Status Contains(ObjectID object_id, int* has_object); + Status Contains(const ObjectID& object_id, int* has_object); /// Seal an object in the object store. The object will be immutable after /// this @@ -157,7 +157,7 @@ class PlasmaClient { /// /// @param object_id The ID of the object to seal. /// @return The return status. - Status Seal(ObjectID object_id); + Status Seal(const ObjectID& object_id); /// Delete an object from the object store. This currently assumes that the /// object is present and has been sealed. @@ -167,7 +167,7 @@ class PlasmaClient { /// /// @param object_id The ID of the object to delete. /// @return The return status. - Status Delete(ObjectID object_id); + Status Delete(const ObjectID& object_id); /// Delete objects until we have freed up num_bytes bytes or there are no more /// released objects that can be deleted. @@ -263,7 +263,7 @@ class PlasmaClient { /// @param port Port of the plasma manager we are transfering to. /// @object_id ObjectID of the object we are transfering. /// @return The return status. - Status Transfer(const char* addr, int port, ObjectID object_id); + Status Transfer(const char* addr, int port, const ObjectID& object_id); /// Return the status of a given object. This method may query the object /// table. @@ -282,11 +282,11 @@ class PlasmaClient { /// - PLASMA_CLIENT_DOES_NOT_EXIST, if the object doesn’t exist in the /// system. /// @return The return status. - Status Info(ObjectID object_id, int* object_status); + Status Info(const ObjectID& object_id, int* object_status); // private: - Status PerformRelease(ObjectID object_id); + Status PerformRelease(const ObjectID& object_id); /// File descriptor of the Unix domain socket that connects to the store. int store_conn; diff --git a/cpp/src/plasma/eviction_policy.cc b/cpp/src/plasma/eviction_policy.cc index 5f184faa29e..3b61ba4633e 100644 --- a/cpp/src/plasma/eviction_policy.cc +++ b/cpp/src/plasma/eviction_policy.cc @@ -62,7 +62,7 @@ int64_t EvictionPolicy::choose_objects_to_evict( return bytes_evicted; } -void EvictionPolicy::object_created(ObjectID object_id) { +void EvictionPolicy::object_created(const ObjectID& object_id) { auto entry = store_info_->objects[object_id].get(); cache_.add(object_id, entry->info.data_size + entry->info.metadata_size); } @@ -94,13 +94,13 @@ bool EvictionPolicy::require_space( } void EvictionPolicy::begin_object_access( - ObjectID object_id, std::vector& objects_to_evict) { + const ObjectID& object_id, std::vector& objects_to_evict) { /* If the object is in the LRU cache, remove it. */ cache_.remove(object_id); } void EvictionPolicy::end_object_access( - ObjectID object_id, std::vector& objects_to_evict) { + const ObjectID& object_id, std::vector& objects_to_evict) { auto entry = store_info_->objects[object_id].get(); /* Add the object to the LRU cache.*/ cache_.add(object_id, entry->info.data_size + entry->info.metadata_size); diff --git a/cpp/src/plasma/eviction_policy.h b/cpp/src/plasma/eviction_policy.h index 51561a684e0..3dc4cc62470 100644 --- a/cpp/src/plasma/eviction_policy.h +++ b/cpp/src/plasma/eviction_policy.h @@ -74,7 +74,7 @@ class EvictionPolicy { * @param object_id The object ID of the object that was created. * @return Void. */ - void object_created(ObjectID object_id); + void object_created(const ObjectID& object_id); /** * This method will be called when the Plasma store needs more space, perhaps @@ -102,7 +102,7 @@ class EvictionPolicy { * be stored into this vector. * @return Void. */ - void begin_object_access(ObjectID object_id, std::vector& objects_to_evict); + void begin_object_access(const ObjectID& object_id, std::vector& objects_to_evict); /** * This method will be called whenever an object in the Plasma store that was @@ -115,7 +115,7 @@ class EvictionPolicy { * be stored into this vector. * @return Void. */ - void end_object_access(ObjectID object_id, std::vector& objects_to_evict); + void end_object_access(const ObjectID& object_id, std::vector& objects_to_evict); /** * Choose some objects to evict from the Plasma store. When this method is diff --git a/cpp/src/plasma/plasma.cc b/cpp/src/plasma/plasma.cc index 2c892781c93..559d8e7f2a6 100644 --- a/cpp/src/plasma/plasma.cc +++ b/cpp/src/plasma/plasma.cc @@ -57,7 +57,7 @@ uint8_t* create_object_info_buffer(ObjectInfoT* object_info) { } ObjectTableEntry* get_object_table_entry( - PlasmaStoreInfo* store_info, ObjectID object_id) { + PlasmaStoreInfo* store_info, const ObjectID& object_id) { auto it = store_info->objects.find(object_id); if (it == store_info->objects.end()) { return NULL; } return it->second.get(); diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h index 11d69765f0c..1d217e52e87 100644 --- a/cpp/src/plasma/plasma.h +++ b/cpp/src/plasma/plasma.h @@ -170,7 +170,7 @@ struct PlasmaStoreInfo { * @return The entry associated with the object_id or NULL if the object_id * is not present. */ -ObjectTableEntry* get_object_table_entry(PlasmaStoreInfo* store_info, ObjectID object_id); +ObjectTableEntry* get_object_table_entry(PlasmaStoreInfo* store_info, const ObjectID& object_id); /** * Print a warning if the status is less than zero. This should be used to check diff --git a/cpp/src/plasma/protocol.cc b/cpp/src/plasma/protocol.cc index d1339c22f9e..38a212bd795 100644 --- a/cpp/src/plasma/protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -27,7 +27,7 @@ using flatbuffers::uoffset_t; flatbuffers::Offset>> to_flatbuffer( - flatbuffers::FlatBufferBuilder& fbb, ObjectID object_ids[], int64_t num_objects) { + flatbuffers::FlatBufferBuilder& fbb, const ObjectID* object_ids, int64_t num_objects) { std::vector> results; for (int64_t i = 0; i < num_objects; i++) { results.push_back(fbb.CreateString(object_ids[i].binary())); @@ -196,7 +196,7 @@ Status ReadDeleteReply(uint8_t* data, ObjectID* object_id) { /* Satus messages. */ -Status SendStatusRequest(int sock, ObjectID object_ids[], int64_t num_objects) { +Status SendStatusRequest(int sock, const ObjectID* object_ids, int64_t num_objects) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaStatusRequest(fbb, to_flatbuffer(fbb, object_ids, num_objects)); diff --git a/cpp/src/plasma/protocol.h b/cpp/src/plasma/protocol.h index e261a623c4d..9f4aee44c9c 100644 --- a/cpp/src/plasma/protocol.h +++ b/cpp/src/plasma/protocol.h @@ -89,7 +89,7 @@ Status ReadDeleteReply(uint8_t* data, ObjectID* object_id); /* Satus messages. */ -Status SendStatusRequest(int sock, ObjectID object_ids[], int64_t num_objects); +Status SendStatusRequest(int sock, const ObjectID* object_ids, int64_t num_objects); Status ReadStatusRequest(uint8_t* data, ObjectID object_ids[], int64_t num_objects); diff --git a/cpp/src/plasma/store.cc b/cpp/src/plasma/store.cc index 80357e42bea..6c573f6b0f4 100644 --- a/cpp/src/plasma/store.cc +++ b/cpp/src/plasma/store.cc @@ -129,7 +129,7 @@ void PlasmaStore::add_client_to_object_clients(ObjectTableEntry* entry, Client* } // Create a new object buffer in the hash table. -int PlasmaStore::create_object(ObjectID object_id, int64_t data_size, +int PlasmaStore::create_object(const ObjectID& object_id, int64_t data_size, int64_t metadata_size, Client* client, PlasmaObject* result) { ARROW_LOG(DEBUG) << "creating object " << object_id.hex(); if (store_info_.objects.count(object_id) != 0) { @@ -253,7 +253,7 @@ void PlasmaStore::return_from_get(GetRequest* get_req) { delete get_req; } -void PlasmaStore::update_object_get_requests(ObjectID object_id) { +void PlasmaStore::update_object_get_requests(const ObjectID& object_id) { std::vector& get_requests = object_get_requests_[object_id]; size_t index = 0; size_t num_requests = get_requests.size(); @@ -345,7 +345,7 @@ int PlasmaStore::remove_client_from_object_clients( } } -void PlasmaStore::release_object(ObjectID object_id, Client* client) { +void PlasmaStore::release_object(const ObjectID& object_id, Client* client) { auto entry = get_object_table_entry(&store_info_, object_id); ARROW_CHECK(entry != NULL); // Remove the client from the object's array of clients. @@ -353,13 +353,13 @@ void PlasmaStore::release_object(ObjectID object_id, Client* client) { } // Check if an object is present. -int PlasmaStore::contains_object(ObjectID object_id) { +int PlasmaStore::contains_object(const ObjectID& object_id) { auto entry = get_object_table_entry(&store_info_, object_id); return entry && (entry->state == PLASMA_SEALED) ? OBJECT_FOUND : OBJECT_NOT_FOUND; } // Seal an object that has been created in the hash table. -void PlasmaStore::seal_object(ObjectID object_id, unsigned char digest[]) { +void PlasmaStore::seal_object(const ObjectID& object_id, unsigned char digest[]) { ARROW_LOG(DEBUG) << "sealing object " << object_id.hex(); auto entry = get_object_table_entry(&store_info_, object_id); ARROW_CHECK(entry != NULL); diff --git a/cpp/src/plasma/store.h b/cpp/src/plasma/store.h index cc8dae7bb9d..a21c7232534 100644 --- a/cpp/src/plasma/store.h +++ b/cpp/src/plasma/store.h @@ -63,7 +63,7 @@ class PlasmaStore { /// - PlasmaError_OutOfMemory, if the store is out of memory and /// cannot create the object. In this case, the client should not call /// plasma_release. - int create_object(ObjectID object_id, int64_t data_size, int64_t metadata_size, + int create_object(const ObjectID& object_id, int64_t data_size, int64_t metadata_size, Client* client, PlasmaObject* result); /// Delete objects that have been created in the hash table. This should only @@ -95,21 +95,21 @@ class PlasmaStore { /// objects /// with the same object ID are the same. /// @return Void. - void seal_object(ObjectID object_id, unsigned char digest[]); + void seal_object(const ObjectID& object_id, unsigned char digest[]); /// Check if the plasma store contains an object: /// /// @param object_id Object ID that will be checked. /// @return OBJECT_FOUND if the object is in the store, OBJECT_NOT_FOUND if /// not - int contains_object(ObjectID object_id); + int contains_object(const ObjectID& object_id); /// Record the fact that a particular client is no longer using an object. /// /// @param object_id The object ID of the object that is being released. /// @param client The client making this request. /// @param Void. - void release_object(ObjectID object_id, Client* client); + void release_object(const ObjectID& object_id, Client* client); /// Subscribe a file descriptor to updates about new sealed objects. /// @@ -140,7 +140,7 @@ class PlasmaStore { void return_from_get(GetRequest* get_req); - void update_object_get_requests(ObjectID object_id); + void update_object_get_requests(const ObjectID& object_id); int remove_client_from_object_clients(ObjectTableEntry* entry, Client* client); From 27f9c9e8c96f88cffdb4057c69bda269aab3736e Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Mon, 19 Jun 2017 18:19:40 -0700 Subject: [PATCH 35/53] fix formatting --- cpp/src/plasma/client.cc | 7 ++++--- cpp/src/plasma/client.h | 3 ++- cpp/src/plasma/eviction_policy.h | 6 ++++-- cpp/src/plasma/plasma.h | 5 +++-- cpp/src/plasma/protocol.cc | 4 ++-- cpp/src/plasma/test/client_tests.cc | 6 ++---- cpp/src/plasma/test/serialization_tests.cc | 6 ++++-- 7 files changed, 21 insertions(+), 16 deletions(-) diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index aff23d1f750..42437629306 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -94,7 +94,8 @@ void increment_object_count( if (elem == conn->objects_in_use.end()) { // Add this object ID to the hash table of object IDs in use. The // corresponding call to free happens in PlasmaClient::Release. - conn->objects_in_use[object_id] = std::unique_ptr(new ObjectInUseEntry()); + conn->objects_in_use[object_id] = + std::unique_ptr(new ObjectInUseEntry()); conn->objects_in_use[object_id]->object = *object; conn->objects_in_use[object_id]->count = 0; conn->objects_in_use[object_id]->is_sealed = is_sealed; @@ -119,8 +120,8 @@ void increment_object_count( object_entry->count += 1; } -Status PlasmaClient::Create(const ObjectID& object_id, int64_t data_size, uint8_t* metadata, - int64_t metadata_size, uint8_t** data) { +Status PlasmaClient::Create(const ObjectID& object_id, int64_t data_size, + uint8_t* metadata, int64_t metadata_size, uint8_t** data) { ARROW_LOG(DEBUG) << "called plasma_create on conn " << store_conn << " with size " << data_size << " and metadata size " << metadata_size; RETURN_NOT_OK(SendCreateRequest(store_conn, object_id, data_size, metadata_size)); diff --git a/cpp/src/plasma/client.h b/cpp/src/plasma/client.h index 8be36f7824a..c02a4dc5bbd 100644 --- a/cpp/src/plasma/client.h +++ b/cpp/src/plasma/client.h @@ -302,7 +302,8 @@ class PlasmaClient { std::unordered_map mmap_table; /// A hash table of the object IDs that are currently being used by this /// client. - std::unordered_map, UniqueIDHasher> objects_in_use; + std::unordered_map, UniqueIDHasher> + objects_in_use; /// Object IDs of the last few release calls. This is a deque and /// is used to delay releasing objects to see if they can be reused by /// subsequent tasks so we do not unneccessarily invalidate cpu caches. diff --git a/cpp/src/plasma/eviction_policy.h b/cpp/src/plasma/eviction_policy.h index 3dc4cc62470..a12f9f1d8e4 100644 --- a/cpp/src/plasma/eviction_policy.h +++ b/cpp/src/plasma/eviction_policy.h @@ -102,7 +102,8 @@ class EvictionPolicy { * be stored into this vector. * @return Void. */ - void begin_object_access(const ObjectID& object_id, std::vector& objects_to_evict); + void begin_object_access( + const ObjectID& object_id, std::vector& objects_to_evict); /** * This method will be called whenever an object in the Plasma store that was @@ -115,7 +116,8 @@ class EvictionPolicy { * be stored into this vector. * @return Void. */ - void end_object_access(const ObjectID& object_id, std::vector& objects_to_evict); + void end_object_access( + const ObjectID& object_id, std::vector& objects_to_evict); /** * Choose some objects to evict from the Plasma store. When this method is diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h index 1d217e52e87..f84d1b2314b 100644 --- a/cpp/src/plasma/plasma.h +++ b/cpp/src/plasma/plasma.h @@ -18,8 +18,8 @@ #ifndef PLASMA_H #define PLASMA_H -#include #include +#include #include #include #include @@ -170,7 +170,8 @@ struct PlasmaStoreInfo { * @return The entry associated with the object_id or NULL if the object_id * is not present. */ -ObjectTableEntry* get_object_table_entry(PlasmaStoreInfo* store_info, const ObjectID& object_id); +ObjectTableEntry* get_object_table_entry( + PlasmaStoreInfo* store_info, const ObjectID& object_id); /** * Print a warning if the status is less than zero. This should be used to check diff --git a/cpp/src/plasma/protocol.cc b/cpp/src/plasma/protocol.cc index 38a212bd795..d557c295f95 100644 --- a/cpp/src/plasma/protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -26,8 +26,8 @@ using flatbuffers::uoffset_t; flatbuffers::Offset>> -to_flatbuffer( - flatbuffers::FlatBufferBuilder& fbb, const ObjectID* object_ids, int64_t num_objects) { +to_flatbuffer(flatbuffers::FlatBufferBuilder& fbb, const ObjectID* object_ids, + int64_t num_objects) { std::vector> results; for (int64_t i = 0; i < num_objects; i++) { results.push_back(fbb.CreateString(object_ids[i].binary())); diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index fad20eaf506..6dd0b08d1d3 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -18,10 +18,10 @@ #include "gtest/gtest.h" #include +#include #include #include #include -#include #include "plasma/client.h" #include "plasma/common.h" @@ -32,9 +32,7 @@ // stdout of the object store. Consider changing that. pid_t start_store() { pid_t pid = fork(); - if (pid != 0) { - return pid; - } + if (pid != 0) { return pid; } execlp("./plasma_store", "./plasma_store", "-m", "10000000", "-s", "/tmp/store", NULL); return 0; } diff --git a/cpp/src/plasma/test/serialization_tests.cc b/cpp/src/plasma/test/serialization_tests.cc index 663d8b03642..85a2836ec13 100644 --- a/cpp/src/plasma/test/serialization_tests.cc +++ b/cpp/src/plasma/test/serialization_tests.cc @@ -165,9 +165,11 @@ TEST(PlasmaSerialization, GetReply) { ASSERT_EQ(object_ids[0], object_ids_return[0]); ASSERT_EQ(object_ids[1], object_ids_return[1]); ASSERT_EQ(memcmp(&plasma_objects[object_ids[0]], &plasma_objects_return[0], - sizeof(PlasmaObject)), 0); + sizeof(PlasmaObject)), + 0); ASSERT_EQ(memcmp(&plasma_objects[object_ids[1]], &plasma_objects_return[1], - sizeof(PlasmaObject)), 0); + sizeof(PlasmaObject)), + 0); close(fd); } From b21f081429d00877b6875ea73c65cfad0f414fd3 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Mon, 19 Jun 2017 19:13:35 -0700 Subject: [PATCH 36/53] fix remaining comments about client --- cpp/src/plasma/client.cc | 200 ++++++++++++++-------------- cpp/src/plasma/client.h | 83 +++++------- cpp/src/plasma/protocol.cc | 8 +- cpp/src/plasma/protocol.h | 8 +- cpp/src/plasma/test/client_tests.cc | 2 +- 5 files changed, 138 insertions(+), 163 deletions(-) diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index 42437629306..f308e0d79c2 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -59,9 +59,9 @@ static std::vector threadpool_(kThreadPoolSize); // If the file descriptor fd has been mmapped in this client process before, // return the pointer that was returned by mmap, otherwise mmap it and store the // pointer in a hash table. -uint8_t* lookup_or_mmap(PlasmaClient* conn, int fd, int store_fd_val, int64_t map_size) { - auto entry = conn->mmap_table.find(store_fd_val); - if (entry != conn->mmap_table.end()) { +uint8_t* PlasmaClient::lookup_or_mmap(int fd, int store_fd_val, int64_t map_size) { + auto entry = mmap_table_.find(store_fd_val); + if (entry != mmap_table_.end()) { close(fd); return entry->second.pointer; } else { @@ -69,7 +69,7 @@ uint8_t* lookup_or_mmap(PlasmaClient* conn, int fd, int store_fd_val, int64_t ma mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); if (result == MAP_FAILED) { ARROW_LOG(FATAL) << "mmap failed"; } close(fd); - ClientMmapTableEntry& entry = conn->mmap_table[store_fd_val]; + ClientMmapTableEntry& entry = mmap_table_[store_fd_val]; entry.pointer = result; entry.length = map_size; entry.count = 0; @@ -79,35 +79,35 @@ uint8_t* lookup_or_mmap(PlasmaClient* conn, int fd, int store_fd_val, int64_t ma // Get a pointer to a file that we know has been memory mapped in this client // process before. -uint8_t* lookup_mmapped_file(PlasmaClient* conn, int store_fd_val) { - auto entry = conn->mmap_table.find(store_fd_val); - ARROW_CHECK(entry != conn->mmap_table.end()); +uint8_t* PlasmaClient::lookup_mmapped_file(int store_fd_val) { + auto entry = mmap_table_.find(store_fd_val); + ARROW_CHECK(entry != mmap_table_.end()); return entry->second.pointer; } -void increment_object_count( - PlasmaClient* conn, const ObjectID& object_id, PlasmaObject* object, bool is_sealed) { +void PlasmaClient::increment_object_count( + const ObjectID& object_id, PlasmaObject* object, bool is_sealed) { // Increment the count of the object to track the fact that it is being used. // The corresponding decrement should happen in PlasmaClient::Release. - auto elem = conn->objects_in_use.find(object_id); + auto elem = objects_in_use_.find(object_id); ObjectInUseEntry* object_entry; - if (elem == conn->objects_in_use.end()) { + if (elem == objects_in_use_.end()) { // Add this object ID to the hash table of object IDs in use. The // corresponding call to free happens in PlasmaClient::Release. - conn->objects_in_use[object_id] = + objects_in_use_[object_id] = std::unique_ptr(new ObjectInUseEntry()); - conn->objects_in_use[object_id]->object = *object; - conn->objects_in_use[object_id]->count = 0; - conn->objects_in_use[object_id]->is_sealed = is_sealed; - object_entry = conn->objects_in_use[object_id].get(); + objects_in_use_[object_id]->object = *object; + objects_in_use_[object_id]->count = 0; + objects_in_use_[object_id]->is_sealed = is_sealed; + object_entry = objects_in_use_[object_id].get(); // Increment the count of the number of objects in the memory-mapped file // that are being used. The corresponding decrement should happen in // PlasmaClient::Release. - auto entry = conn->mmap_table.find(object->handle.store_fd); - ARROW_CHECK(entry != conn->mmap_table.end()); + auto entry = mmap_table_.find(object->handle.store_fd); + ARROW_CHECK(entry != mmap_table_.end()); ARROW_CHECK(entry->second.count >= 0); - // Update the in_use_object_bytes. - conn->in_use_object_bytes += + // Update the in_use_object_bytes_. + in_use_object_bytes_ += (object_entry->object.data_size + object_entry->object.metadata_size); entry->second.count += 1; } else { @@ -122,23 +122,23 @@ void increment_object_count( Status PlasmaClient::Create(const ObjectID& object_id, int64_t data_size, uint8_t* metadata, int64_t metadata_size, uint8_t** data) { - ARROW_LOG(DEBUG) << "called plasma_create on conn " << store_conn << " with size " + ARROW_LOG(DEBUG) << "called plasma_create on conn " << store_conn_ << " with size " << data_size << " and metadata size " << metadata_size; - RETURN_NOT_OK(SendCreateRequest(store_conn, object_id, data_size, metadata_size)); + RETURN_NOT_OK(SendCreateRequest(store_conn_, object_id, data_size, metadata_size)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(store_conn, MessageType_PlasmaCreateReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaCreateReply, buffer)); ObjectID id; PlasmaObject object; RETURN_NOT_OK(ReadCreateReply(buffer.data(), &id, &object)); // If the CreateReply included an error, then the store will not send a file // descriptor. - int fd = recv_fd(store_conn); + int fd = recv_fd(store_conn_); ARROW_CHECK(fd >= 0) << "recv not successful"; ARROW_CHECK(object.data_size == data_size); ARROW_CHECK(object.metadata_size == metadata_size); // The metadata should come right after the data. ARROW_CHECK(object.metadata_offset == object.data_offset + data_size); - *data = lookup_or_mmap(this, fd, object.handle.store_fd, object.handle.mmap_size) + + *data = lookup_or_mmap(fd, object.handle.store_fd, object.handle.mmap_size) + object.data_offset; // If plasma_create is being called from a transfer, then we will not copy the // metadata here. The metadata will be written along with the data streamed @@ -151,23 +151,23 @@ Status PlasmaClient::Create(const ObjectID& object_id, int64_t data_size, // client is using. A call to PlasmaClient::Release is required to decrement // this // count. Cache the reference to the object. - increment_object_count(this, object_id, &object, false); + increment_object_count(object_id, &object, false); // We increment the count a second time (and the corresponding decrement will // happen in a PlasmaClient::Release call in plasma_seal) so even if the // buffer // returned by PlasmaClient::Dreate goes out of scope, the object does not get // released before the call to PlasmaClient::Seal happens. - increment_object_count(this, object_id, &object, false); + increment_object_count(object_id, &object, false); return Status::OK(); } -Status PlasmaClient::Get(ObjectID object_ids[], int64_t num_objects, int64_t timeout_ms, - ObjectBuffer object_buffers[]) { +Status PlasmaClient::Get(const ObjectID* object_ids, int64_t num_objects, int64_t timeout_ms, + ObjectBuffer* object_buffers) { // Fill out the info for the objects that are already in use locally. bool all_present = true; for (int i = 0; i < num_objects; ++i) { - auto object_entry = objects_in_use.find(object_ids[i]); - if (object_entry == objects_in_use.end()) { + auto object_entry = objects_in_use_.find(object_ids[i]); + if (object_entry == objects_in_use_.end()) { // This object is not currently in use by this client, so we need to send // a request to the store. all_present = false; @@ -179,7 +179,7 @@ Status PlasmaClient::Get(ObjectID object_ids[], int64_t num_objects, int64_t tim ARROW_CHECK(object_entry->second->is_sealed) << "Plasma client called get on an unsealed object that it created"; PlasmaObject* object = &object_entry->second->object; - object_buffers[i].data = lookup_mmapped_file(this, object->handle.store_fd); + object_buffers[i].data = lookup_mmapped_file(object->handle.store_fd); object_buffers[i].data = object_buffers[i].data + object->data_offset; object_buffers[i].data_size = object->data_size; object_buffers[i].metadata = object_buffers[i].data + object->data_size; @@ -188,7 +188,7 @@ Status PlasmaClient::Get(ObjectID object_ids[], int64_t num_objects, int64_t tim // client is using. A call to PlasmaClient::Release is required to // decrement this // count. Cache the reference to the object. - increment_object_count(this, object_ids[i], object, true); + increment_object_count(object_ids[i], object, true); } } @@ -196,9 +196,9 @@ Status PlasmaClient::Get(ObjectID object_ids[], int64_t num_objects, int64_t tim // If we get here, then the objects aren't all currently in use by this // client, so we need to send a request to the plasma store. - RETURN_NOT_OK(SendGetRequest(store_conn, object_ids, num_objects, timeout_ms)); + RETURN_NOT_OK(SendGetRequest(store_conn_, object_ids, num_objects, timeout_ms)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(store_conn, MessageType_PlasmaGetReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaGetReply, buffer)); std::vector received_object_ids(num_objects); std::vector object_data(num_objects); PlasmaObject* object; @@ -215,7 +215,7 @@ Status PlasmaClient::Get(ObjectID object_ids[], int64_t num_objects, int64_t tim // We won't use this file descriptor, but the store sent us one, so we // need to receive it and then close it right away so we don't leak file // descriptors. - int fd = recv_fd(store_conn); + int fd = recv_fd(store_conn_); close(fd); ARROW_CHECK(fd >= 0); // We've already filled out the information for this object, so we can @@ -227,10 +227,10 @@ Status PlasmaClient::Get(ObjectID object_ids[], int64_t num_objects, int64_t tim if (object->data_size != -1) { // The object was retrieved. The user will be responsible for releasing // this object. - int fd = recv_fd(store_conn); + int fd = recv_fd(store_conn_); ARROW_CHECK(fd >= 0); object_buffers[i].data = - lookup_or_mmap(this, fd, object->handle.store_fd, object->handle.mmap_size); + lookup_or_mmap(fd, object->handle.store_fd, object->handle.mmap_size); // Finish filling out the return values. object_buffers[i].data = object_buffers[i].data + object->data_offset; object_buffers[i].data_size = object->data_size; @@ -240,7 +240,7 @@ Status PlasmaClient::Get(ObjectID object_ids[], int64_t num_objects, int64_t tim // client is using. A call to PlasmaClient::Release is required to // decrement this // count. Cache the reference to the object. - increment_object_count(this, received_object_ids[i], object, true); + increment_object_count(received_object_ids[i], object, true); } else { // The object was not retrieved. Make sure we already put a -1 here to // indicate that the object was not retrieved. The caller is not @@ -266,8 +266,8 @@ Status PlasmaClient::PerformRelease(const ObjectID& object_id) { // Decrement the count of the number of instances of this object that are // being used by this client. The corresponding increment should have happened // in PlasmaClient::Get. - auto object_entry = objects_in_use.find(object_id); - ARROW_CHECK(object_entry != objects_in_use.end()); + auto object_entry = objects_in_use_.find(object_id); + ARROW_CHECK(object_entry != objects_in_use_.end()); object_entry->second->count -= 1; ARROW_CHECK(object_entry->second->count >= 0); // Check if the client is no longer using this object. @@ -276,63 +276,63 @@ Status PlasmaClient::PerformRelease(const ObjectID& object_id) { // that the client is using. The corresponding increment should have // happened in plasma_get. int fd = object_entry->second->object.handle.store_fd; - auto entry = mmap_table.find(fd); - ARROW_CHECK(entry != mmap_table.end()); + auto entry = mmap_table_.find(fd); + ARROW_CHECK(entry != mmap_table_.end()); entry->second.count -= 1; ARROW_CHECK(entry->second.count >= 0); // If none are being used then unmap the file. if (entry->second.count == 0) { munmap(entry->second.pointer, entry->second.length); // Remove the corresponding entry from the hash table. - mmap_table.erase(fd); + mmap_table_.erase(fd); } // Tell the store that the client no longer needs the object. - RETURN_NOT_OK(SendReleaseRequest(store_conn, object_id)); - // Update the in_use_object_bytes. - in_use_object_bytes -= (object_entry->second->object.data_size + + RETURN_NOT_OK(SendReleaseRequest(store_conn_, object_id)); + // Update the in_use_object_bytes_. + in_use_object_bytes_ -= (object_entry->second->object.data_size + object_entry->second->object.metadata_size); - DCHECK_GE(in_use_object_bytes, 0); + DCHECK_GE(in_use_object_bytes_, 0); // Remove the entry from the hash table of objects currently in use. - objects_in_use.erase(object_id); + objects_in_use_.erase(object_id); } return Status::OK(); } Status PlasmaClient::Release(const ObjectID& object_id) { // Add the new object to the release history. - release_history.push_front(object_id); + release_history_.push_front(object_id); // If there are too many bytes in use by the client or if there are too many // pending release calls, and there are at least some pending release calls in // the release_history list, then release some objects. - while ((in_use_object_bytes > std::min(kL3CacheSizeBytes, store_capacity / 100) || - release_history.size() > config.release_delay) && - release_history.size() > 0) { + while ((in_use_object_bytes_ > std::min(kL3CacheSizeBytes, store_capacity_ / 100) || + release_history_.size() > config_.release_delay) && + release_history_.size() > 0) { // Perform a release for the object ID for the first pending release. - RETURN_NOT_OK(PerformRelease(release_history.back())); + RETURN_NOT_OK(PerformRelease(release_history_.back())); // Remove the last entry from the release history. - release_history.pop_back(); + release_history_.pop_back(); } return Status::OK(); } // This method is used to query whether the plasma store contains an object. -Status PlasmaClient::Contains(const ObjectID& object_id, int* has_object) { +Status PlasmaClient::Contains(const ObjectID& object_id, bool* has_object) { // Check if we already have a reference to the object. - if (objects_in_use.count(object_id) > 0) { + if (objects_in_use_.count(object_id) > 0) { *has_object = 1; } else { // If we don't already have a reference to the object, check with the store // to see if we have the object. - RETURN_NOT_OK(SendContainsRequest(store_conn, object_id)); + RETURN_NOT_OK(SendContainsRequest(store_conn_, object_id)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(store_conn, MessageType_PlasmaContainsReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaContainsReply, buffer)); ObjectID object_id2; RETURN_NOT_OK(ReadContainsReply(buffer.data(), &object_id2, has_object)); } return Status::OK(); } -static void compute_block_hash( +static void ComputeBlockHash( const unsigned char* data, int64_t nbytes, uint64_t* hash) { XXH64_state_t hash_state; XXH64_reset(&hash_state, XXH64_DEFAULT_SEED); @@ -356,11 +356,11 @@ static inline bool compute_object_hash_parallel( // Each thread gets a "chunk" of k blocks, except the suffix thread. for (int i = 0; i < num_threads; i++) { - threadpool_[i] = std::thread(compute_block_hash, + threadpool_[i] = std::thread(ComputeBlockHash, reinterpret_cast(data_address) + i * chunk_size, chunk_size, &threadhash[i]); } - compute_block_hash( + ComputeBlockHash( reinterpret_cast(right_address), suffix, &threadhash[num_threads]); // Join the threads. @@ -405,8 +405,8 @@ bool plasma_compute_object_hash( Status PlasmaClient::Seal(const ObjectID& object_id) { // Make sure this client has a reference to the object before sending the // request to Plasma. - auto object_entry = objects_in_use.find(object_id); - ARROW_CHECK(object_entry != objects_in_use.end()) + auto object_entry = objects_in_use_.find(object_id); + ARROW_CHECK(object_entry != objects_in_use_.end()) << "Plasma client called seal an object without a reference to it"; ARROW_CHECK(!object_entry->second->is_sealed) << "Plasma client called seal an already sealed object"; @@ -414,7 +414,7 @@ Status PlasmaClient::Seal(const ObjectID& object_id) { /// Send the seal request to Plasma. static unsigned char digest[kDigestSize]; ARROW_CHECK(plasma_compute_object_hash(this, object_id, &digest[0])); - RETURN_NOT_OK(SendSealRequest(store_conn, object_id, &digest[0])); + RETURN_NOT_OK(SendSealRequest(store_conn_, object_id, &digest[0])); // We call PlasmaClient::Release to decrement the number of instances of this // object // that are currently being used by this client. The corresponding increment @@ -431,15 +431,15 @@ Status PlasmaClient::Delete(const ObjectID& object_id) { Status PlasmaClient::Evict(int64_t num_bytes, int64_t& num_bytes_evicted) { // Send a request to the store to evict objects. - RETURN_NOT_OK(SendEvictRequest(store_conn, num_bytes)); + RETURN_NOT_OK(SendEvictRequest(store_conn_, num_bytes)); // Wait for a response with the number of bytes actually evicted. std::vector buffer; int64_t type; - RETURN_NOT_OK(ReadMessage(store_conn, &type, buffer)); + RETURN_NOT_OK(ReadMessage(store_conn_, &type, buffer)); return ReadEvictReply(buffer.data(), num_bytes_evicted); } -Status PlasmaClient::Subscribe(int& fd) { +Status PlasmaClient::Subscribe(int* fd) { int sock[2]; // Create a non-blocking socket pair. This will only be used to send // notifications from the Plasma store to the client. @@ -448,32 +448,32 @@ Status PlasmaClient::Subscribe(int& fd) { int flags = fcntl(sock[1], F_GETFL, 0); ARROW_CHECK(fcntl(sock[1], F_SETFL, flags | O_NONBLOCK) == 0); // Tell the Plasma store about the subscription. - RETURN_NOT_OK(SendSubscribeRequest(store_conn)); + RETURN_NOT_OK(SendSubscribeRequest(store_conn_)); // Send the file descriptor that the Plasma store should use to push // notifications about sealed objects to this client. - ARROW_CHECK(send_fd(store_conn, sock[1]) >= 0); + ARROW_CHECK(send_fd(store_conn_, sock[1]) >= 0); close(sock[1]); // Return the file descriptor that the client should use to read notifications // about sealed objects. - fd = sock[0]; + *fd = sock[0]; return Status::OK(); } Status PlasmaClient::Connect(const std::string& store_socket_name, const std::string& manager_socket_name, int release_delay) { - store_conn = connect_ipc_sock_retry(store_socket_name, -1, -1); + store_conn_ = connect_ipc_sock_retry(store_socket_name, -1, -1); if (manager_socket_name != "") { - manager_conn = connect_ipc_sock_retry(manager_socket_name, -1, -1); + manager_conn_ = connect_ipc_sock_retry(manager_socket_name, -1, -1); } else { - manager_conn = -1; + manager_conn_ = -1; } - config.release_delay = release_delay; - in_use_object_bytes = 0; + config_.release_delay = release_delay; + in_use_object_bytes_ = 0; // Send a ConnectRequest to the store to get its memory capacity. - RETURN_NOT_OK(SendConnectRequest(store_conn)); + RETURN_NOT_OK(SendConnectRequest(store_conn_)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(store_conn, MessageType_PlasmaConnectReply, buffer)); - RETURN_NOT_OK(ReadConnectReply(buffer.data(), &store_capacity)); + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaConnectReply, buffer)); + RETURN_NOT_OK(ReadConnectReply(buffer.data(), &store_capacity_)); return Status::OK(); } @@ -484,45 +484,41 @@ Status PlasmaClient::Disconnect() { // Close the connections to Plasma. The Plasma store will release the objects // that were in use by us when handling the SIGPIPE. - close(store_conn); - if (manager_conn >= 0) { close(manager_conn); } + close(store_conn_); + if (manager_conn_ >= 0) { close(manager_conn_); } return Status::OK(); } -bool plasma_manager_is_connected(PlasmaClient* conn) { - return conn->manager_conn >= 0; -} - #define h_addr h_addr_list[0] Status PlasmaClient::Transfer(const char* address, int port, const ObjectID& object_id) { - return SendDataRequest(manager_conn, object_id, address, port); + return SendDataRequest(manager_conn_, object_id, address, port); } -Status PlasmaClient::Fetch(int num_object_ids, ObjectID object_ids[]) { - ARROW_CHECK(manager_conn >= 0); - return SendFetchRequest(manager_conn, object_ids, num_object_ids); +Status PlasmaClient::Fetch(int num_object_ids, const ObjectID* object_ids) { + ARROW_CHECK(manager_conn_ >= 0); + return SendFetchRequest(manager_conn_, object_ids, num_object_ids); } -int get_manager_fd(PlasmaClient* conn) { - return conn->manager_conn; +int PlasmaClient::get_manager_fd() { + return manager_conn_; } Status PlasmaClient::Info(const ObjectID& object_id, int* object_status) { - ARROW_CHECK(manager_conn >= 0); + ARROW_CHECK(manager_conn_ >= 0); - RETURN_NOT_OK(SendStatusRequest(manager_conn, &object_id, 1)); + RETURN_NOT_OK(SendStatusRequest(manager_conn_, &object_id, 1)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(manager_conn, MessageType_PlasmaStatusReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(manager_conn_, MessageType_PlasmaStatusReply, buffer)); ObjectID id; RETURN_NOT_OK(ReadStatusReply(buffer.data(), &id, object_status, 1)); ARROW_CHECK(object_id == id); return Status::OK(); } -Status PlasmaClient::Wait(int64_t num_object_requests, ObjectRequest object_requests[], - int num_ready_objects, int64_t timeout_ms, int& num_objects_ready) { - ARROW_CHECK(manager_conn >= 0); +Status PlasmaClient::Wait(int64_t num_object_requests, ObjectRequest* object_requests, + int num_ready_objects, int64_t timeout_ms, int* num_objects_ready) { + ARROW_CHECK(manager_conn_ >= 0); ARROW_CHECK(num_object_requests > 0); ARROW_CHECK(num_ready_objects > 0); ARROW_CHECK(num_ready_objects <= num_object_requests); @@ -533,22 +529,22 @@ Status PlasmaClient::Wait(int64_t num_object_requests, ObjectRequest object_requ } RETURN_NOT_OK(SendWaitRequest( - manager_conn, object_requests, num_object_requests, num_ready_objects, timeout_ms)); + manager_conn_, object_requests, num_object_requests, num_ready_objects, timeout_ms)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(manager_conn, MessageType_PlasmaWaitReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(manager_conn_, MessageType_PlasmaWaitReply, buffer)); RETURN_NOT_OK(ReadWaitReply(buffer.data(), object_requests, &num_ready_objects)); - num_objects_ready = 0; + *num_objects_ready = 0; for (int i = 0; i < num_object_requests; ++i) { int type = object_requests[i].type; int status = object_requests[i].status; switch (type) { case PLASMA_QUERY_LOCAL: - if (status == ObjectStatus_Local) { num_objects_ready += 1; } + if (status == ObjectStatus_Local) { *num_objects_ready += 1; } break; case PLASMA_QUERY_ANYWHERE: if (status == ObjectStatus_Local || status == ObjectStatus_Remote) { - num_objects_ready += 1; + *num_objects_ready += 1; } else { ARROW_CHECK(status == ObjectStatus_Nonexistent); } diff --git a/cpp/src/plasma/client.h b/cpp/src/plasma/client.h index c02a4dc5bbd..d806fc27b7a 100644 --- a/cpp/src/plasma/client.h +++ b/cpp/src/plasma/client.h @@ -125,8 +125,8 @@ class PlasmaClient { /// data /// size field is -1, then the object was not retrieved. /// @return The return status. - Status Get(ObjectID object_ids[], int64_t num_objects, int64_t timeout_ms, - ObjectBuffer object_buffers[]); + Status Get(const ObjectID* object_ids, int64_t num_objects, int64_t timeout_ms, + ObjectBuffer* object_buffers); /// Tell Plasma that the client no longer needs the object. This should be /// called @@ -145,11 +145,10 @@ class PlasmaClient { /// sealed. /// /// @param object_id The ID of the object whose presence we are checking. - /// @param has_object The function will write 1 at this address if the object - /// is - /// present and 0 if it is not present. + /// @param has_object The function will write true at this address if + /// the object is present and false if it is not present. /// @return The return status. - Status Contains(const ObjectID& object_id, int* has_object); + Status Contains(const ObjectID& object_id, bool* has_object); /// Seal an object in the object store. The object will be immutable after /// this @@ -187,7 +186,7 @@ class PlasmaClient { /// read notifications /// from the object store about sealed objects. /// @return The return status. - Status Subscribe(int& fd); + Status Subscribe(int* fd); /// Disconnect from the local plasma instance, including the local store and /// manager. @@ -220,7 +219,7 @@ class PlasmaClient { /// @param num_object_ids The number of object IDs fetch is being called on. /// @param object_ids The IDs of the objects that fetch is being called on. /// @return The return status. - Status Fetch(int num_object_ids, ObjectID object_ids[]); + Status Fetch(int num_object_ids, const ObjectID* object_ids); /// Wait for (1) a specified number of objects to be available (sealed) in the /// local Plasma Store or in a remote Plasma Store, or (2) for a timeout to @@ -253,8 +252,8 @@ class PlasmaClient { /// the object_requests list. If the returned number is less than /// min_num_ready_objects this means that timeout expired. /// @return The return status. - Status Wait(int64_t num_object_requests, ObjectRequest object_requests[], - int num_ready_objects, int64_t timeout_ms, int& num_objects_ready); + Status Wait(int64_t num_object_requests, ObjectRequest* object_requests, + int num_ready_objects, int64_t timeout_ms, int* num_objects_ready); /// Transfer local object to a different plasma manager. /// @@ -284,50 +283,53 @@ class PlasmaClient { /// @return The return status. Status Info(const ObjectID& object_id, int* object_status); - // private: + /// Get the file descriptor for the socket connection to the plasma manager. + /// + /// @param conn The plasma connection. + /// @return The file descriptor for the manager connection. If there is no + /// connection to the manager, this is -1. + int get_manager_fd(); + private: Status PerformRelease(const ObjectID& object_id); + uint8_t* lookup_or_mmap(int fd, int store_fd_val, int64_t map_size); + + uint8_t* lookup_mmapped_file(int store_fd_val); + + void increment_object_count( + const ObjectID& object_id, PlasmaObject* object, bool is_sealed); + /// File descriptor of the Unix domain socket that connects to the store. - int store_conn; + int store_conn_; /// File descriptor of the Unix domain socket that connects to the manager. - int manager_conn; - /// File descriptor of the Unix domain socket on which client receives event - /// notifications for the objects it subscribes for when these objects are - /// sealed either locally or remotely. - int manager_conn_subscribe; + int manager_conn_; /// Table of dlmalloc buffer files that have been memory mapped so far. This /// is a hash table mapping a file descriptor to a struct containing the /// address of the corresponding memory-mapped file. - std::unordered_map mmap_table; + std::unordered_map mmap_table_; /// A hash table of the object IDs that are currently being used by this /// client. std::unordered_map, UniqueIDHasher> - objects_in_use; + objects_in_use_; /// Object IDs of the last few release calls. This is a deque and /// is used to delay releasing objects to see if they can be reused by /// subsequent tasks so we do not unneccessarily invalidate cpu caches. /// TODO(pcm): replace this with a proper lru cache using the size of the L3 /// cache. - std::deque release_history; + std::deque release_history_; /// The number of bytes in the combined objects that are held in the release /// history doubly-linked list. If this is too large then the client starts /// releasing objects. - int64_t in_use_object_bytes; + int64_t in_use_object_bytes_; /// Configuration options for the plasma client. - PlasmaClientConfig config; + PlasmaClientConfig config_; /// The amount of memory available to the Plasma store. The client needs this /// information to make sure that it does not delay in releasing so much /// memory that the store is unable to evict enough objects to free up space. - int64_t store_capacity; + int64_t store_capacity_; }; -/// Return true if the plasma manager is connected. -/// -/// @param conn The connection to the local plasma store and plasma manager. -/// @return True if the plasma manager is connected and false otherwise. -bool plasma_manager_is_connected(PlasmaClient* conn); - /// Compute the hash of an object in the object store. /// /// @param conn The object containing the connection state. @@ -338,27 +340,4 @@ bool plasma_manager_is_connected(PlasmaClient* conn); bool plasma_compute_object_hash( PlasmaClient* conn, ObjectID object_id, unsigned char* digest); -/** - * Get the file descriptor for the socket connection to the plasma manager. - * - * @param conn The plasma connection. - * @return The file descriptor for the manager connection. If there is no - * connection to the manager, this is -1. - */ -int get_manager_fd(PlasmaClient* conn); - -/** - * Return the information associated to a given object. - * - * @param conn The object containing the connection state. - * @param object_id The ID of the object whose info the client queries. - * @param object_info The object's infirmation. - * @return PLASMA_CLIENT_LOCAL, if the object is in the local Plasma Store. - * PLASMA_CLIENT_NOT_LOCAL, if not. In this case, the caller needs to - * ignore data, metadata_size, and metadata fields. - */ -// int plasma_info(PlasmaConnection *conn, -// ObjectID object_id, -// ObjectInfo *object_info); - #endif /* PLASMA_CLIENT_H */ diff --git a/cpp/src/plasma/protocol.cc b/cpp/src/plasma/protocol.cc index d557c295f95..07cf1d9367e 100644 --- a/cpp/src/plasma/protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -260,7 +260,7 @@ Status ReadContainsRequest(uint8_t* data, ObjectID* object_id) { return Status::OK(); } -Status SendContainsReply(int sock, ObjectID object_id, int has_object) { +Status SendContainsReply(int sock, ObjectID object_id, bool has_object) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaContainsReply(fbb, fbb.CreateString(object_id.binary()), has_object); @@ -269,7 +269,7 @@ Status SendContainsReply(int sock, ObjectID object_id, int has_object) { sock, MessageType_PlasmaContainsReply, fbb.GetSize(), fbb.GetBufferPointer()); } -Status ReadContainsReply(uint8_t* data, ObjectID* object_id, int* has_object) { +Status ReadContainsReply(uint8_t* data, ObjectID* object_id, bool* has_object) { DCHECK(data); auto message = flatbuffers::GetRoot(data); *object_id = ObjectID::from_binary(message->object_id()->str()); @@ -341,7 +341,7 @@ Status ReadEvictReply(uint8_t* data, int64_t& num_bytes) { /* Get messages. */ Status SendGetRequest( - int sock, ObjectID object_ids[], int64_t num_objects, int64_t timeout_ms) { + int sock, const ObjectID* object_ids, int64_t num_objects, int64_t timeout_ms) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaGetRequest( fbb, to_flatbuffer(fbb, object_ids, num_objects), timeout_ms); @@ -402,7 +402,7 @@ Status ReadGetReply(uint8_t* data, ObjectID object_ids[], PlasmaObject plasma_ob /* Fetch messages. */ -Status SendFetchRequest(int sock, ObjectID object_ids[], int64_t num_objects) { +Status SendFetchRequest(int sock, const ObjectID* object_ids, int64_t num_objects) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaFetchRequest(fbb, to_flatbuffer(fbb, object_ids, num_objects)); diff --git a/cpp/src/plasma/protocol.h b/cpp/src/plasma/protocol.h index 9f4aee44c9c..152d0b7749b 100644 --- a/cpp/src/plasma/protocol.h +++ b/cpp/src/plasma/protocol.h @@ -55,7 +55,7 @@ Status ReadSealReply(uint8_t* data, ObjectID* object_id); /* Plasma Get message functions. */ Status SendGetRequest( - int sock, ObjectID object_ids[], int64_t num_objects, int64_t timeout_ms); + int sock, const ObjectID* object_ids, int64_t num_objects, int64_t timeout_ms); Status ReadGetRequest( uint8_t* data, std::vector& object_ids, int64_t* timeout_ms); @@ -107,9 +107,9 @@ Status SendContainsRequest(int sock, ObjectID object_id); Status ReadContainsRequest(uint8_t* data, ObjectID* object_id); -Status SendContainsReply(int sock, ObjectID object_id, int has_object); +Status SendContainsReply(int sock, ObjectID object_id, bool has_object); -Status ReadContainsReply(uint8_t* data, ObjectID* object_id, int* has_object); +Status ReadContainsReply(uint8_t* data, ObjectID* object_id, bool* has_object); /* Plasma Connect message functions. */ @@ -133,7 +133,7 @@ Status ReadEvictReply(uint8_t* data, int64_t& num_bytes); /* Plasma Fetch Remote message functions. */ -Status SendFetchRequest(int sock, ObjectID object_ids[], int64_t num_objects); +Status SendFetchRequest(int sock, const ObjectID* object_ids, int64_t num_objects); Status ReadFetchRequest(uint8_t* data, std::vector& object_ids); diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index 6dd0b08d1d3..13e343eaba6 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -45,7 +45,7 @@ TEST(PlasmaClient, ContainsTest) { ObjectID object_id = ObjectID::from_random(); // Test for object non-existence. - int has_object; + bool has_object; ARROW_CHECK_OK(client.Contains(object_id, &has_object)); ASSERT_EQ(has_object, false); From 6432d3fa1482fa262e4ad31f24ed316a7e6ba752 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Mon, 19 Jun 2017 19:14:36 -0700 Subject: [PATCH 37/53] fix formatting --- cpp/src/plasma/client.cc | 13 ++++++------- cpp/src/plasma/client.h | 2 +- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index f308e0d79c2..7fc5bcca3ec 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -161,8 +161,8 @@ Status PlasmaClient::Create(const ObjectID& object_id, int64_t data_size, return Status::OK(); } -Status PlasmaClient::Get(const ObjectID* object_ids, int64_t num_objects, int64_t timeout_ms, - ObjectBuffer* object_buffers) { +Status PlasmaClient::Get(const ObjectID* object_ids, int64_t num_objects, + int64_t timeout_ms, ObjectBuffer* object_buffers) { // Fill out the info for the objects that are already in use locally. bool all_present = true; for (int i = 0; i < num_objects; ++i) { @@ -290,7 +290,7 @@ Status PlasmaClient::PerformRelease(const ObjectID& object_id) { RETURN_NOT_OK(SendReleaseRequest(store_conn_, object_id)); // Update the in_use_object_bytes_. in_use_object_bytes_ -= (object_entry->second->object.data_size + - object_entry->second->object.metadata_size); + object_entry->second->object.metadata_size); DCHECK_GE(in_use_object_bytes_, 0); // Remove the entry from the hash table of objects currently in use. objects_in_use_.erase(object_id); @@ -332,8 +332,7 @@ Status PlasmaClient::Contains(const ObjectID& object_id, bool* has_object) { return Status::OK(); } -static void ComputeBlockHash( - const unsigned char* data, int64_t nbytes, uint64_t* hash) { +static void ComputeBlockHash(const unsigned char* data, int64_t nbytes, uint64_t* hash) { XXH64_state_t hash_state; XXH64_reset(&hash_state, XXH64_DEFAULT_SEED); XXH64_update(&hash_state, data, nbytes); @@ -528,8 +527,8 @@ Status PlasmaClient::Wait(int64_t num_object_requests, ObjectRequest* object_req object_requests[i].type == PLASMA_QUERY_ANYWHERE); } - RETURN_NOT_OK(SendWaitRequest( - manager_conn_, object_requests, num_object_requests, num_ready_objects, timeout_ms)); + RETURN_NOT_OK(SendWaitRequest(manager_conn_, object_requests, num_object_requests, + num_ready_objects, timeout_ms)); std::vector buffer; RETURN_NOT_OK(PlasmaReceive(manager_conn_, MessageType_PlasmaWaitReply, buffer)); RETURN_NOT_OK(ReadWaitReply(buffer.data(), object_requests, &num_ready_objects)); diff --git a/cpp/src/plasma/client.h b/cpp/src/plasma/client.h index d806fc27b7a..32e781bc6a3 100644 --- a/cpp/src/plasma/client.h +++ b/cpp/src/plasma/client.h @@ -298,7 +298,7 @@ class PlasmaClient { uint8_t* lookup_mmapped_file(int store_fd_val); void increment_object_count( - const ObjectID& object_id, PlasmaObject* object, bool is_sealed); + const ObjectID& object_id, PlasmaObject* object, bool is_sealed); /// File descriptor of the Unix domain socket that connects to the store. int store_conn_; From e7badc48ab4df4f56ada59f17728f75df460f0f7 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Mon, 19 Jun 2017 19:55:39 -0700 Subject: [PATCH 38/53] fix python extension --- cpp/src/plasma/extension.cc | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/cpp/src/plasma/extension.cc b/cpp/src/plasma/extension.cc index 99fd35572ad..6537482a2bf 100644 --- a/cpp/src/plasma/extension.cc +++ b/cpp/src/plasma/extension.cc @@ -193,7 +193,7 @@ PyObject* PyPlasma_contains(PyObject* self, PyObject* args) { &object_id)) { return NULL; } - int has_object; + bool has_object; ARROW_CHECK_OK(client->Contains(object_id, &has_object)); if (has_object) @@ -208,7 +208,7 @@ PyObject* PyPlasma_fetch(PyObject* self, PyObject* args) { if (!PyArg_ParseTuple(args, "O&O", PyObjectToPlasmaClient, &client, &object_id_list)) { return NULL; } - if (!plasma_manager_is_connected(client)) { + if (client->get_manager_fd() == -1) { PyErr_SetString(PyExc_RuntimeError, "Not connected to the plasma manager"); return NULL; } @@ -233,7 +233,7 @@ PyObject* PyPlasma_wait(PyObject* self, PyObject* args) { } Py_ssize_t n = PyList_Size(object_id_list); - if (!plasma_manager_is_connected(client)) { + if (client->get_manager_fd() == -1) { PyErr_SetString(PyExc_RuntimeError, "Not connected to the plasma manager"); return NULL; } @@ -265,7 +265,7 @@ PyObject* PyPlasma_wait(PyObject* self, PyObject* args) { int num_return_objects; Py_BEGIN_ALLOW_THREADS; ARROW_CHECK_OK( - client->Wait(n, object_requests.data(), num_returns, timeout, num_return_objects)); + client->Wait(n, object_requests.data(), num_returns, timeout, &num_return_objects)); Py_END_ALLOW_THREADS; int num_to_return = std::min(num_return_objects, num_returns); @@ -326,7 +326,7 @@ PyObject* PyPlasma_transfer(PyObject* self, PyObject* args) { return NULL; } - if (!plasma_manager_is_connected(client)) { + if (client->get_manager_fd() == -1) { PyErr_SetString(PyExc_RuntimeError, "Not connected to the plasma manager"); return NULL; } @@ -340,7 +340,7 @@ PyObject* PyPlasma_subscribe(PyObject* self, PyObject* args) { if (!PyArg_ParseTuple(args, "O&", PyObjectToPlasmaClient, &client)) { return NULL; } int sock; - ARROW_CHECK_OK(client->Subscribe(sock)); + ARROW_CHECK_OK(client->Subscribe(&sock)); return PyLong_FromLong(sock); } From 214c426c8606aec78691241c9fedbf9c3565c247 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Mon, 19 Jun 2017 20:39:34 -0700 Subject: [PATCH 39/53] fix eviction policy --- cpp/src/plasma/events.cc | 2 +- cpp/src/plasma/events.h | 4 +- cpp/src/plasma/eviction_policy.cc | 16 +-- cpp/src/plasma/eviction_policy.h | 169 ++++++++++++++---------------- cpp/src/plasma/store.cc | 8 +- 5 files changed, 93 insertions(+), 106 deletions(-) diff --git a/cpp/src/plasma/events.cc b/cpp/src/plasma/events.cc index 264716ea456..0f54c989c17 100644 --- a/cpp/src/plasma/events.cc +++ b/cpp/src/plasma/events.cc @@ -36,7 +36,7 @@ EventLoop::EventLoop() { loop_ = aeCreateEventLoop(kInitialEventLoopSize); } -bool EventLoop::add_file_event(int fd, int events, FileCallback callback) { +bool EventLoop::add_file_event(int fd, int events, const FileCallback& callback) { if (file_callbacks_.find(fd) != file_callbacks_.end()) { return false; } auto data = std::unique_ptr(new FileCallback(callback)); void* context = reinterpret_cast(data.get()); diff --git a/cpp/src/plasma/events.h b/cpp/src/plasma/events.h index df5c84ebd5e..0a87d16375c 100644 --- a/cpp/src/plasma/events.h +++ b/cpp/src/plasma/events.h @@ -43,7 +43,7 @@ class EventLoop { // on the file descriptor that this handler has been registered for. // // The arguments are the event flags (read or write). - typedef std::function FileCallback; + using FileCallback = std::function; // This handler will be called when a timer times out. The timer id is // passed as an argument. The return is the number of milliseconds the timer @@ -59,7 +59,7 @@ class EventLoop { /// @param events The flags for events we are listening to (read or write). /// @param callback The callback that will be called when the event happens. /// @return Returns true if the event handler was added successfully. - bool add_file_event(int fd, int events, FileCallback callback); + bool add_file_event(int fd, int events, const FileCallback& callback); /// Remove a file event handler from the event loop. /// diff --git a/cpp/src/plasma/eviction_policy.cc b/cpp/src/plasma/eviction_policy.cc index 3b61ba4633e..4ae6384d425 100644 --- a/cpp/src/plasma/eviction_policy.cc +++ b/cpp/src/plasma/eviction_policy.cc @@ -35,12 +35,12 @@ void LRUCache::remove(const ObjectID& key) { } int64_t LRUCache::choose_objects_to_evict( - int64_t num_bytes_required, std::vector& objects_to_evict) { + int64_t num_bytes_required, std::vector* objects_to_evict) { int64_t bytes_evicted = 0; auto it = item_list_.end(); while (bytes_evicted < num_bytes_required && it != item_list_.begin()) { it--; - objects_to_evict.push_back(it->first); + objects_to_evict->push_back(it->first); bytes_evicted += it->second; } return bytes_evicted; @@ -50,11 +50,11 @@ EvictionPolicy::EvictionPolicy(PlasmaStoreInfo* store_info) : memory_used_(0), store_info_(store_info) {} int64_t EvictionPolicy::choose_objects_to_evict( - int64_t num_bytes_required, std::vector& objects_to_evict) { + int64_t num_bytes_required, std::vector* objects_to_evict) { int64_t bytes_evicted = cache_.choose_objects_to_evict(num_bytes_required, objects_to_evict); /* Update the LRU cache. */ - for (auto& object_id : objects_to_evict) { + for (auto& object_id : *objects_to_evict) { cache_.remove(object_id); } /* Update the number of bytes used. */ @@ -68,7 +68,7 @@ void EvictionPolicy::object_created(const ObjectID& object_id) { } bool EvictionPolicy::require_space( - int64_t size, std::vector& objects_to_evict) { + int64_t size, std::vector* objects_to_evict) { /* Check if there is enough space to create the object. */ int64_t required_space = memory_used_ + size - store_info_->memory_capacity; int64_t num_bytes_evicted; @@ -80,7 +80,7 @@ bool EvictionPolicy::require_space( /* Choose some objects to evict, and update the return pointers. */ num_bytes_evicted = choose_objects_to_evict(space_to_free, objects_to_evict); ARROW_LOG(INFO) << "There is not enough space to create this object, so evicting " - << objects_to_evict.size() << " objects to free up " + << objects_to_evict->size() << " objects to free up " << num_bytes_evicted << " bytes."; } else { num_bytes_evicted = 0; @@ -94,13 +94,13 @@ bool EvictionPolicy::require_space( } void EvictionPolicy::begin_object_access( - const ObjectID& object_id, std::vector& objects_to_evict) { + const ObjectID& object_id, std::vector* objects_to_evict) { /* If the object is in the LRU cache, remove it. */ cache_.remove(object_id); } void EvictionPolicy::end_object_access( - const ObjectID& object_id, std::vector& objects_to_evict) { + const ObjectID& object_id, std::vector* objects_to_evict) { auto entry = store_info_->objects[object_id].get(); /* Add the object to the LRU cache.*/ cache_.add(object_id, entry->info.data_size + entry->info.metadata_size); diff --git a/cpp/src/plasma/eviction_policy.h b/cpp/src/plasma/eviction_policy.h index a12f9f1d8e4..b6d016fd21a 100644 --- a/cpp/src/plasma/eviction_policy.h +++ b/cpp/src/plasma/eviction_policy.h @@ -26,23 +26,13 @@ #include "plasma/common.h" #include "plasma/plasma.h" -/* ==== The eviction policy ==== - * - * This file contains declaration for all functions and data structures that - * need to be provided if you want to implement a new eviction algorithm for the - * Plasma store. - */ +// ==== The eviction policy ==== +// +// This file contains declaration for all functions and data structures that +// need to be provided if you want to implement a new eviction algorithm for the +// Plasma store. class LRUCache { - private: - /** A doubly-linked list containing the items in the cache and - * their sizes in LRU order. */ - typedef std::list> ItemList; - ItemList item_list_; - /** A hash table mapping the object ID of an object in the cache to its - * location in the doubly linked list item_list_. */ - std::unordered_map item_map_; - public: LRUCache() {} @@ -51,97 +41,94 @@ class LRUCache { void remove(const ObjectID& key); int64_t choose_objects_to_evict( - int64_t num_bytes_required, std::vector& objects_to_evict); + int64_t num_bytes_required, std::vector* objects_to_evict); + + private: + /// A doubly-linked list containing the items in the cache and + /// their sizes in LRU order. + typedef std::list> ItemList; + ItemList item_list_; + /// A hash table mapping the object ID of an object in the cache to its + /// location in the doubly linked list item_list_. + std::unordered_map item_map_; }; -/** The eviction policy. */ +/// The eviction policy. class EvictionPolicy { public: - /** - * Construct an eviction policy. - * - * @param store_info Information about the Plasma store that is exposed - * to the eviction policy. - */ + /// Construct an eviction policy. + /// + /// @param store_info Information about the Plasma store that is exposed + /// to the eviction policy. explicit EvictionPolicy(PlasmaStoreInfo* store_info); - /** - * This method will be called whenever an object is first created in order to - * add it to the LRU cache. This is done so that the first time, the Plasma - * store calls begin_object_access, we can remove the object from the LRU - * cache. - * - * @param object_id The object ID of the object that was created. - * @return Void. - */ + /// This method will be called whenever an object is first created in order to + /// add it to the LRU cache. This is done so that the first time, the Plasma + /// store calls begin_object_access, we can remove the object from the LRU + /// cache. + /// + /// @param object_id The object ID of the object that was created. + /// @return Void. void object_created(const ObjectID& object_id); - /** - * This method will be called when the Plasma store needs more space, perhaps - * to create a new object. If the required amount of space cannot be freed up, - * then a fatal error will be thrown. When this method is called, the eviction - * policy will assume that the objects chosen to be evicted will in fact be - * evicted from the Plasma store by the caller. - * - * @param size The size in bytes of the new object, including both data and - * metadata. - * @param objects_to_evict The object IDs that were chosen for eviction will - * be stored into this vector. - * @return True if enough space can be freed and false otherwise. - */ - bool require_space(int64_t size, std::vector& objects_to_evict); - - /** - * This method will be called whenever an unused object in the Plasma store - * starts to be used. When this method is called, the eviction policy will - * assume that the objects chosen to be evicted will in fact be evicted from - * the Plasma store by the caller. - * - * @param object_id The ID of the object that is now being used. - * @param objects_to_evict The object IDs that were chosen for eviction will - * be stored into this vector. - * @return Void. - */ + /// This method will be called when the Plasma store needs more space, perhaps + /// to create a new object. If the required amount of space cannot be freed up, + /// then a fatal error will be thrown. When this method is called, the eviction + /// policy will assume that the objects chosen to be evicted will in fact be + /// evicted from the Plasma store by the caller. + /// + /// @param size The size in bytes of the new object, including both data and + /// metadata. + /// @param objects_to_evict The object IDs that were chosen for eviction will + /// be stored into this vector. + /// @return True if enough space can be freed and false otherwise. + bool require_space(int64_t size, std::vector* objects_to_evict); + + /// This method will be called whenever an unused object in the Plasma store + /// starts to be used. When this method is called, the eviction policy will + /// assume that the objects chosen to be evicted will in fact be evicted from + /// the Plasma store by the caller. + /// + /// @param object_id The ID of the object that is now being used. + /// @param objects_to_evict The object IDs that were chosen for eviction will + /// be stored into this vector. + /// @return Void. void begin_object_access( - const ObjectID& object_id, std::vector& objects_to_evict); - - /** - * This method will be called whenever an object in the Plasma store that was - * being used is no longer being used. When this method is called, the - * eviction policy will assume that the objects chosen to be evicted will in - * fact be evicted from the Plasma store by the caller. - * - * @param object_id The ID of the object that is no longer being used. - * @param objects_to_evict The object IDs that were chosen for eviction will - * be stored into this vector. - * @return Void. - */ + const ObjectID& object_id, std::vector* objects_to_evict); + + /// This method will be called whenever an object in the Plasma store that was + /// being used is no longer being used. When this method is called, the + /// eviction policy will assume that the objects chosen to be evicted will in + /// fact be evicted from the Plasma store by the caller. + /// + /// @param object_id The ID of the object that is no longer being used. + /// @param objects_to_evict The object IDs that were chosen for eviction will + /// be stored into this vector. + /// @return Void. void end_object_access( - const ObjectID& object_id, std::vector& objects_to_evict); - - /** - * Choose some objects to evict from the Plasma store. When this method is - * called, the eviction policy will assume that the objects chosen to be - * evicted will in fact be evicted from the Plasma store by the caller. - * - * @note This method is not part of the API. It is exposed in the header file - * only for testing. - * - * @param num_bytes_required The number of bytes of space to try to free up. - * @param objects_to_evict The object IDs that were chosen for eviction will - * be stored into this vector. - * @return The total number of bytes of space chosen to be evicted. - */ + const ObjectID& object_id, std::vector* objects_to_evict); + + /// Choose some objects to evict from the Plasma store. When this method is + /// called, the eviction policy will assume that the objects chosen to be + /// evicted will in fact be evicted from the Plasma store by the caller. + /// + /// @note This method is not part of the API. It is exposed in the header file + /// only for testing. + /// + /// @param num_bytes_required The number of bytes of space to try to free up. + /// @param objects_to_evict The object IDs that were chosen for eviction will + /// be stored into this vector. + /// @return The total number of bytes of space chosen to be evicted. int64_t choose_objects_to_evict( - int64_t num_bytes_required, std::vector& objects_to_evict); + int64_t num_bytes_required, std::vector* objects_to_evict); private: - /** The amount of memory (in bytes) currently being used. */ + /// The amount of memory (in bytes) currently being used. int64_t memory_used_; - /** Pointer to the plasma store info. */ + /// Pointer to the plasma store info. PlasmaStoreInfo* store_info_; - /** Datastructure for the LRU cache. */ + /// Datastructure for the LRU cache. LRUCache cache_; }; -#endif /* EVICTION_POLICY_H */ +#endif // EVICTION_POLICY_H diff --git a/cpp/src/plasma/store.cc b/cpp/src/plasma/store.cc index 6c573f6b0f4..2f8cfc517c8 100644 --- a/cpp/src/plasma/store.cc +++ b/cpp/src/plasma/store.cc @@ -121,7 +121,7 @@ void PlasmaStore::add_client_to_object_clients(ObjectTableEntry* entry, Client* if (entry->clients.size() == 0) { // Tell the eviction policy that this object is being used. std::vector objects_to_evict; - eviction_policy_.begin_object_access(entry->object_id, objects_to_evict); + eviction_policy_.begin_object_access(entry->object_id, &objects_to_evict); delete_objects(objects_to_evict); } // Add the client pointer to the list of clients using this object. @@ -153,7 +153,7 @@ int PlasmaStore::create_object(const ObjectID& object_id, int64_t data_size, // Tell the eviction policy how much space we need to create this object. std::vector objects_to_evict; bool success = - eviction_policy_.require_space(data_size + metadata_size, objects_to_evict); + eviction_policy_.require_space(data_size + metadata_size, &objects_to_evict); delete_objects(objects_to_evict); // Return an error to the client if not enough space could be freed to // create the object. @@ -334,7 +334,7 @@ int PlasmaStore::remove_client_from_object_clients( if (entry->clients.size() == 0) { // Tell the eviction policy that this object is no longer being used. std::vector objects_to_evict; - eviction_policy_.end_object_access(entry->object_id, objects_to_evict); + eviction_policy_.end_object_access(entry->object_id, &objects_to_evict); delete_objects(objects_to_evict); } // Return 1 to indicate that the client was removed. @@ -580,7 +580,7 @@ Status PlasmaStore::process_message(Client* client) { RETURN_NOT_OK(ReadEvictRequest(input, &num_bytes)); std::vector objects_to_evict; int64_t num_bytes_evicted = - eviction_policy_.choose_objects_to_evict(num_bytes, objects_to_evict); + eviction_policy_.choose_objects_to_evict(num_bytes, &objects_to_evict); delete_objects(objects_to_evict); HANDLE_SIGPIPE(SendEvictReply(client->fd, num_bytes_evicted), client->fd); } break; From b36c6aaac1263ea82bf1dacf8bd4fb33a191a4c1 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Mon, 19 Jun 2017 22:24:33 -0700 Subject: [PATCH 40/53] fix fling.cc --- LICENSE.txt | 20 +++++++++++ cpp/src/plasma/extension.cc | 25 +++++++------ cpp/src/plasma/fling.cc | 33 ++++++++--------- cpp/src/plasma/fling.h | 71 +++++++++++++++++-------------------- 4 files changed, 79 insertions(+), 70 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index d6456956733..3c309eb5b06 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -200,3 +200,23 @@ 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. + +-------------------------------------------------------------------------------- + +src/plasma/fling.cc and src/plasma/fling.h: Apache 2.0 + +Copyright 2013 Sharvil Nanavati + +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. + +-------------------------------------------------------------------------------- diff --git a/cpp/src/plasma/extension.cc b/cpp/src/plasma/extension.cc index 6537482a2bf..b81da512e15 100644 --- a/cpp/src/plasma/extension.cc +++ b/cpp/src/plasma/extension.cc @@ -144,17 +144,16 @@ PyObject* PyPlasma_get(PyObject* self, PyObject* args) { } Py_ssize_t num_object_ids = PyList_Size(object_id_list); - ObjectID* object_ids = new ObjectID[num_object_ids]; - ObjectBuffer* object_buffers = new ObjectBuffer[num_object_ids]; + std::vector object_ids(num_object_ids); + std::vector object_buffers(num_object_ids); for (int i = 0; i < num_object_ids; ++i) { PyStringToUniqueID(PyList_GetItem(object_id_list, i), &object_ids[i]); } Py_BEGIN_ALLOW_THREADS; - ARROW_CHECK_OK(client->Get(object_ids, num_object_ids, timeout_ms, object_buffers)); + ARROW_CHECK_OK(client->Get(object_ids.data(), num_object_ids, timeout_ms, object_buffers.data())); Py_END_ALLOW_THREADS; - delete[] object_ids; PyObject* returns = PyList_New(num_object_ids); for (int i = 0; i < num_object_ids; ++i) { @@ -166,23 +165,22 @@ PyObject* PyPlasma_get(PyObject* self, PyObject* args) { #if PY_MAJOR_VERSION >= 3 char* data = reinterpret_cast(object_buffers[i].data); char* metadata = reinterpret_cast(object_buffers[i].metadata); - PyTuple_SetItem(t, 0, PyMemoryView_FromMemory(data, data_size, PyBUF_READ)); - PyTuple_SetItem(t, 1, PyMemoryView_FromMemory(metadata, metadata_size, PyBUF_READ)); + PyTuple_SET_ITEM(t, 0, PyMemoryView_FromMemory(data, data_size, PyBUF_READ)); + PyTuple_SET_ITEM(t, 1, PyMemoryView_FromMemory(metadata, metadata_size, PyBUF_READ)); #else void* data = reinterpret_cast(object_buffers[i].data); void* metadata = reinterpret_cast(object_buffers[i].metadata); - PyTuple_SetItem(t, 0, PyBuffer_FromMemory(data, data_size)); - PyTuple_SetItem(t, 1, PyBuffer_FromMemory(metadata, metadata_size)); + PyTuple_SET_ITEM(t, 0, PyBuffer_FromMemory(data, data_size)); + PyTuple_SET_ITEM(t, 1, PyBuffer_FromMemory(metadata, metadata_size)); #endif - PyList_SetItem(returns, i, t); + ARROW_CHECK(PyList_SetItem(returns, i, t) == 0); } else { /* The object was not retrieved, so just add None to the list of return * values. */ Py_INCREF(Py_None); - PyList_SetItem(returns, i, Py_None); + ARROW_CHECK(PyList_SetItem(returns, i, Py_None) == 0); } } - delete[] object_buffers; return returns; } @@ -196,10 +194,11 @@ PyObject* PyPlasma_contains(PyObject* self, PyObject* args) { bool has_object; ARROW_CHECK_OK(client->Contains(object_id, &has_object)); - if (has_object) + if (has_object) { Py_RETURN_TRUE; - else + } else { Py_RETURN_FALSE; + } } PyObject* PyPlasma_fetch(PyObject* self, PyObject* args) { diff --git a/cpp/src/plasma/fling.cc b/cpp/src/plasma/fling.cc index 3ad5b611d0d..79da4f43a19 100644 --- a/cpp/src/plasma/fling.cc +++ b/cpp/src/plasma/fling.cc @@ -1,19 +1,16 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at +// Copyright 2013 Sharvil Nanavati // -// http://www.apache.org/licenses/LICENSE-2.0 +// 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 // -// 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. +// 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 "plasma/fling.h" @@ -45,7 +42,7 @@ int send_fd(int conn, int fd) { header->cmsg_len = CMSG_LEN(sizeof(int)); *reinterpret_cast(CMSG_DATA(header)) = fd; - /* Send file descriptor. */ + // Send file descriptor. ssize_t r = sendmsg(conn, &msg, 0); if (r >= 0) { return 0; @@ -80,9 +77,9 @@ int recv_fd(int conn) { } } - /* The sender sent us more than one file descriptor. We've closed - * them all to prevent fd leaks but notify the caller that we got - * a bad message. */ + // The sender sent us more than one file descriptor. We've closed + // them all to prevent fd leaks but notify the caller that we got + // a bad message. if (oh_noes) { close(found_fd); errno = EBADMSG; diff --git a/cpp/src/plasma/fling.h b/cpp/src/plasma/fling.h index 64da6821421..78ac9d17f26 100644 --- a/cpp/src/plasma/fling.h +++ b/cpp/src/plasma/fling.h @@ -1,30 +1,27 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at +// Copyright 2013 Sharvil Nanavati // -// http://www.apache.org/licenses/LICENSE-2.0 +// 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 // -// 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. +// 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. -/* FLING: Exchanging file descriptors over sockets - * - * This is a little library for sending file descriptors over a socket - * between processes. The reason for doing that (as opposed to using - * filenames to share the files) is so (a) no files remain in the - * filesystem after all the processes terminate, (b) to make sure that - * there are no name collisions and (c) to be able to control who has - * access to the data. - * - * Most of the code is from https://github.com/sharvil/flingfd */ +// FLING: Exchanging file descriptors over sockets +// +// This is a little library for sending file descriptors over a socket +// between processes. The reason for doing that (as opposed to using +// filenames to share the files) is so (a) no files remain in the +// filesystem after all the processes terminate, (b) to make sure that +// there are no name collisions and (c) to be able to control who has +// access to the data. +// +// Most of the code is from https://github.com/sharvil/flingfd #include #include @@ -32,8 +29,8 @@ #include #include -/* This is neccessary for Mac OS X, see http://www.apuebook.com/faqs2e.html - * (10). */ +// This is neccessary for Mac OS X, see http://www.apuebook.com/faqs2e.html +// (10). #if !defined(CMSG_SPACE) && !defined(CMSG_LEN) #define CMSG_SPACE(len) (__DARWIN_ALIGN32(sizeof(struct cmsghdr)) + __DARWIN_ALIGN32(len)) #define CMSG_LEN(len) (__DARWIN_ALIGN32(sizeof(struct cmsghdr)) + (len)) @@ -41,19 +38,15 @@ void init_msg(struct msghdr* msg, struct iovec* iov, char* buf, size_t buf_len); -/** - * Send a file descriptor over a unix domain socket. - * - * @param conn Unix domain socket to send the file descriptor over. - * @param fd File descriptor to send over. - * @return Status code which is < 0 on failure. - */ +// Send a file descriptor over a unix domain socket. +// +// @param conn Unix domain socket to send the file descriptor over. +// @param fd File descriptor to send over. +// @return Status code which is < 0 on failure. int send_fd(int conn, int fd); -/** - * Receive a file descriptor over a unix domain socket. - * - * @param conn Unix domain socket to receive the file descriptor from. - * @return File descriptor or a value < 0 on failure. - */ +// Receive a file descriptor over a unix domain socket. +// +// @param conn Unix domain socket to receive the file descriptor from. +// @return File descriptor or a value < 0 on failure. int recv_fd(int conn); From a137e78395c3e8b5d4de02c9b68b32e5401b3809 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Tue, 20 Jun 2017 12:35:19 -0700 Subject: [PATCH 41/53] more fixes --- cpp/src/plasma/client.cc | 14 +- cpp/src/plasma/client.h | 2 +- cpp/src/plasma/common.h | 2 +- cpp/src/plasma/eviction_policy.h | 6 +- cpp/src/plasma/extension.h | 2 +- cpp/src/plasma/io.cc | 6 +- cpp/src/plasma/io.h | 7 +- cpp/src/plasma/malloc.h | 6 +- cpp/src/plasma/plasma.h | 155 ++++++++++----------- cpp/src/plasma/protocol.cc | 2 +- cpp/src/plasma/protocol.h | 2 +- cpp/src/plasma/store.cc | 2 +- cpp/src/plasma/test/serialization_tests.cc | 2 +- 13 files changed, 104 insertions(+), 104 deletions(-) diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index 7fc5bcca3ec..e45d0941622 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -126,7 +126,7 @@ Status PlasmaClient::Create(const ObjectID& object_id, int64_t data_size, << data_size << " and metadata size " << metadata_size; RETURN_NOT_OK(SendCreateRequest(store_conn_, object_id, data_size, metadata_size)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaCreateReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaCreateReply, &buffer)); ObjectID id; PlasmaObject object; RETURN_NOT_OK(ReadCreateReply(buffer.data(), &id, &object)); @@ -198,7 +198,7 @@ Status PlasmaClient::Get(const ObjectID* object_ids, int64_t num_objects, // client, so we need to send a request to the plasma store. RETURN_NOT_OK(SendGetRequest(store_conn_, object_ids, num_objects, timeout_ms)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaGetReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaGetReply, &buffer)); std::vector received_object_ids(num_objects); std::vector object_data(num_objects); PlasmaObject* object; @@ -325,7 +325,7 @@ Status PlasmaClient::Contains(const ObjectID& object_id, bool* has_object) { // to see if we have the object. RETURN_NOT_OK(SendContainsRequest(store_conn_, object_id)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaContainsReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaContainsReply, &buffer)); ObjectID object_id2; RETURN_NOT_OK(ReadContainsReply(buffer.data(), &object_id2, has_object)); } @@ -434,7 +434,7 @@ Status PlasmaClient::Evict(int64_t num_bytes, int64_t& num_bytes_evicted) { // Wait for a response with the number of bytes actually evicted. std::vector buffer; int64_t type; - RETURN_NOT_OK(ReadMessage(store_conn_, &type, buffer)); + RETURN_NOT_OK(ReadMessage(store_conn_, &type, &buffer)); return ReadEvictReply(buffer.data(), num_bytes_evicted); } @@ -471,7 +471,7 @@ Status PlasmaClient::Connect(const std::string& store_socket_name, // Send a ConnectRequest to the store to get its memory capacity. RETURN_NOT_OK(SendConnectRequest(store_conn_)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaConnectReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(store_conn_, MessageType_PlasmaConnectReply, &buffer)); RETURN_NOT_OK(ReadConnectReply(buffer.data(), &store_capacity_)); return Status::OK(); } @@ -508,7 +508,7 @@ Status PlasmaClient::Info(const ObjectID& object_id, int* object_status) { RETURN_NOT_OK(SendStatusRequest(manager_conn_, &object_id, 1)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(manager_conn_, MessageType_PlasmaStatusReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(manager_conn_, MessageType_PlasmaStatusReply, &buffer)); ObjectID id; RETURN_NOT_OK(ReadStatusReply(buffer.data(), &id, object_status, 1)); ARROW_CHECK(object_id == id); @@ -530,7 +530,7 @@ Status PlasmaClient::Wait(int64_t num_object_requests, ObjectRequest* object_req RETURN_NOT_OK(SendWaitRequest(manager_conn_, object_requests, num_object_requests, num_ready_objects, timeout_ms)); std::vector buffer; - RETURN_NOT_OK(PlasmaReceive(manager_conn_, MessageType_PlasmaWaitReply, buffer)); + RETURN_NOT_OK(PlasmaReceive(manager_conn_, MessageType_PlasmaWaitReply, &buffer)); RETURN_NOT_OK(ReadWaitReply(buffer.data(), object_requests, &num_ready_objects)); *num_objects_ready = 0; diff --git a/cpp/src/plasma/client.h b/cpp/src/plasma/client.h index 32e781bc6a3..a1fb745f2cf 100644 --- a/cpp/src/plasma/client.h +++ b/cpp/src/plasma/client.h @@ -340,4 +340,4 @@ class PlasmaClient { bool plasma_compute_object_hash( PlasmaClient* conn, ObjectID object_id, unsigned char* digest); -#endif /* PLASMA_CLIENT_H */ +#endif // PLASMA_CLIENT_H diff --git a/cpp/src/plasma/common.h b/cpp/src/plasma/common.h index 61ed49359e7..85dc74bf86e 100644 --- a/cpp/src/plasma/common.h +++ b/cpp/src/plasma/common.h @@ -48,7 +48,7 @@ class UniqueID { static_assert(std::is_pod::value, "UniqueID must be plain old data"); struct UniqueIDHasher { - /* ObjectID hashing function. */ + // ObjectID hashing function. size_t operator()(const UniqueID& id) const { size_t result; std::memcpy(&result, id.data(), sizeof(size_t)); diff --git a/cpp/src/plasma/eviction_policy.h b/cpp/src/plasma/eviction_policy.h index b6d016fd21a..3815fc6652f 100644 --- a/cpp/src/plasma/eviction_policy.h +++ b/cpp/src/plasma/eviction_policy.h @@ -15,8 +15,8 @@ // specific language governing permissions and limitations // under the License. -#ifndef EVICTION_POLICY_H -#define EVICTION_POLICY_H +#ifndef PLASMA_EVICTION_POLICY_H +#define PLASMA_EVICTION_POLICY_H #include #include @@ -131,4 +131,4 @@ class EvictionPolicy { LRUCache cache_; }; -#endif // EVICTION_POLICY_H +#endif // PLASMA_EVICTION_POLICY_H diff --git a/cpp/src/plasma/extension.h b/cpp/src/plasma/extension.h index 28cf8f2c584..f7a044d2920 100644 --- a/cpp/src/plasma/extension.h +++ b/cpp/src/plasma/extension.h @@ -47,4 +47,4 @@ int PyStringToUniqueID(PyObject* object, ObjectID* object_id) { } } -#endif /* PLASMA_EXTENSION_H */ +#endif // PLASMA_EXTENSION_H diff --git a/cpp/src/plasma/io.cc b/cpp/src/plasma/io.cc index 755b8d7eef8..5875ebb7ae6 100644 --- a/cpp/src/plasma/io.cc +++ b/cpp/src/plasma/io.cc @@ -80,7 +80,7 @@ Status ReadBytes(int fd, uint8_t* cursor, size_t length) { return Status::OK(); } -Status ReadMessage(int fd, int64_t* type, std::vector& buffer) { +Status ReadMessage(int fd, int64_t* type, std::vector* buffer) { int64_t version; RETURN_NOT_OK_ELSE(ReadBytes(fd, reinterpret_cast(&version), sizeof(version)), *type = DISCONNECT_CLIENT); @@ -90,8 +90,8 @@ Status ReadMessage(int fd, int64_t* type, std::vector& buffer) { *type = DISCONNECT_CLIENT); RETURN_NOT_OK_ELSE(ReadBytes(fd, reinterpret_cast(&length), sizeof(length)), *type = DISCONNECT_CLIENT); - if (length > buffer.size()) { buffer.resize(length); } - RETURN_NOT_OK_ELSE(ReadBytes(fd, buffer.data(), length), *type = DISCONNECT_CLIENT); + if (length > buffer->size()) { buffer->resize(length); } + RETURN_NOT_OK_ELSE(ReadBytes(fd, buffer->data(), length), *type = DISCONNECT_CLIENT); return Status::OK(); } diff --git a/cpp/src/plasma/io.h b/cpp/src/plasma/io.h index 453dd7349ce..3cb031990a1 100644 --- a/cpp/src/plasma/io.h +++ b/cpp/src/plasma/io.h @@ -15,6 +15,9 @@ // specific language governing permissions and limitations // under the License. +#ifndef PLASMA_IO_H +#define PLASMA_IO_H + #include #include #include @@ -37,7 +40,7 @@ arrow::Status WriteMessage(int fd, int64_t type, int64_t length, uint8_t* bytes) arrow::Status ReadBytes(int fd, uint8_t* cursor, size_t length); -arrow::Status ReadMessage(int fd, int64_t* type, std::vector& buffer); +arrow::Status ReadMessage(int fd, int64_t* type, std::vector* buffer); int bind_ipc_sock(const std::string& pathname, bool shall_listen); @@ -48,3 +51,5 @@ int connect_ipc_sock_retry(const std::string& pathname, int num_retries, int64_t int AcceptClient(int socket_fd); uint8_t* read_message_async(int sock); + +#endif // PLASMA_IO_H diff --git a/cpp/src/plasma/malloc.h b/cpp/src/plasma/malloc.h index a1c387a7ce7..4d3419339e4 100644 --- a/cpp/src/plasma/malloc.h +++ b/cpp/src/plasma/malloc.h @@ -15,12 +15,12 @@ // specific language governing permissions and limitations // under the License. -#ifndef MALLOC_H -#define MALLOC_H +#ifndef PLASMA_MALLOC_H +#define PLASMA_MALLOC_H #include #include void get_malloc_mapinfo(void* addr, int* fd, int64_t* map_length, ptrdiff_t* offset); -#endif /* MALLOC_H */ +#endif // MALLOC_H diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h index f84d1b2314b..a52313e8500 100644 --- a/cpp/src/plasma/plasma.h +++ b/cpp/src/plasma/plasma.h @@ -15,8 +15,8 @@ // specific language governing permissions and limitations // under the License. -#ifndef PLASMA_H -#define PLASMA_H +#ifndef PLASMA_PLASMA_H +#define PLASMA_PLASMA_H #include #include @@ -25,7 +25,7 @@ #include #include #include -#include /* pid_t */ +#include // pid_t #include #include @@ -51,146 +51,141 @@ } \ } while (0); -/** Allocation granularity used in plasma for object allocation. */ +/// Allocation granularity used in plasma for object allocation. #define BLOCK_SIZE 64 -// Size of object hash digests. +/// Size of object hash digests. constexpr int64_t kDigestSize = sizeof(uint64_t); struct Client; -/** - * Object request data structure. Used in the plasma_wait_for_objects() - * argument. - */ + +/// Object request data structure. Used in the plasma_wait_for_objects() +/// argument. typedef struct { - /** The ID of the requested object. If ID_NIL request any object. */ + /// The ID of the requested object. If ID_NIL request any object. ObjectID object_id; - /** Request associated to the object. It can take one of the following values: - * - PLASMA_QUERY_LOCAL: return if or when the object is available in the - * local Plasma Store. - * - PLASMA_QUERY_ANYWHERE: return if or when the object is available in - * the system (i.e., either in the local or a remote Plasma Store). */ + /// Request associated to the object. It can take one of the following values: + /// - PLASMA_QUERY_LOCAL: return if or when the object is available in the + /// local Plasma Store. + /// - PLASMA_QUERY_ANYWHERE: return if or when the object is available in + /// the system (i.e., either in the local or a remote Plasma Store). int type; - /** Object status. Same as the status returned by plasma_status() function - * call. This is filled in by plasma_wait_for_objects1(): - * - ObjectStatus_Local: object is ready at the local Plasma Store. - * - ObjectStatus_Remote: object is ready at a remote Plasma Store. - * - ObjectStatus_Nonexistent: object does not exist in the system. - * - PLASMA_CLIENT_IN_TRANSFER, if the object is currently being scheduled - * for being transferred or it is transferring. */ + /// Object status. Same as the status returned by plasma_status() function + /// call. This is filled in by plasma_wait_for_objects1(): + /// - ObjectStatus_Local: object is ready at the local Plasma Store. + /// - ObjectStatus_Remote: object is ready at a remote Plasma Store. + /// - ObjectStatus_Nonexistent: object does not exist in the system. + /// - PLASMA_CLIENT_IN_TRANSFER, if the object is currently being scheduled + /// for being transferred or it is transferring. int status; } ObjectRequest; -/** Mapping from object IDs to type and status of the request. */ +/// Mapping from object IDs to type and status of the request. typedef std::unordered_map ObjectRequestMap; -/* Handle to access memory mapped file and map it into client address space. */ +/// Handle to access memory mapped file and map it into client address space. typedef struct { - /** The file descriptor of the memory mapped file in the store. It is used as - * a unique identifier of the file in the client to look up the corresponding - * file descriptor on the client's side. */ + /// The file descriptor of the memory mapped file in the store. It is used as + /// a unique identifier of the file in the client to look up the corresponding + /// file descriptor on the client's side. int store_fd; - /** The size in bytes of the memory mapped file. */ + /// The size in bytes of the memory mapped file. int64_t mmap_size; } object_handle; typedef struct { - /** Handle for memory mapped file the object is stored in. */ + /// Handle for memory mapped file the object is stored in. object_handle handle; - /** The offset in bytes in the memory mapped file of the data. */ + /// The offset in bytes in the memory mapped file of the data. ptrdiff_t data_offset; - /** The offset in bytes in the memory mapped file of the metadata. */ + /// The offset in bytes in the memory mapped file of the metadata. ptrdiff_t metadata_offset; - /** The size in bytes of the data. */ + /// The size in bytes of the data. int64_t data_size; - /** The size in bytes of the metadata. */ + /// The size in bytes of the metadata. int64_t metadata_size; } PlasmaObject; typedef enum { - /** Object was created but not sealed in the local Plasma Store. */ + /// Object was created but not sealed in the local Plasma Store. PLASMA_CREATED = 1, - /** Object is sealed and stored in the local Plasma Store. */ + /// Object is sealed and stored in the local Plasma Store. PLASMA_SEALED } object_state; typedef enum { - /** The object was not found. */ + /// The object was not found. OBJECT_NOT_FOUND = 0, - /** The object was found. */ + /// The object was found. OBJECT_FOUND = 1 } object_status; typedef enum { - /** Query for object in the local plasma store. */ + /// Query for object in the local plasma store. PLASMA_QUERY_LOCAL = 1, - /** Query for object in the local plasma store or in a remote plasma store. */ + /// Query for object in the local plasma store or in a remote plasma store. PLASMA_QUERY_ANYWHERE } object_request_type; -/** This type is used by the Plasma store. It is here because it is exposed to - * the eviction policy. */ +/// This type is used by the Plasma store. It is here because it is exposed to +/// the eviction policy. struct ObjectTableEntry { - /** Object id of this object. */ + /// Object id of this object. ObjectID object_id; - /** Object info like size, creation time and owner. */ + /// Object info like size, creation time and owner. ObjectInfoT info; - /** Memory mapped file containing the object. */ + /// Memory mapped file containing the object. int fd; - /** Size of the underlying map. */ + /// Size of the underlying map. int64_t map_size; - /** Offset from the base of the mmap. */ + /// Offset from the base of the mmap. ptrdiff_t offset; - /** Pointer to the object data. Needed to free the object. */ + /// Pointer to the object data. Needed to free the object. uint8_t* pointer; - /** Set of clients currently using this object. */ + /// Set of clients currently using this object. std::unordered_set clients; - /** The state of the object, e.g., whether it is open or sealed. */ + /// The state of the object, e.g., whether it is open or sealed. object_state state; - /** The digest of the object. Used to see if two objects are the same. */ + /// The digest of the object. Used to see if two objects are the same. unsigned char digest[kDigestSize]; }; -/** The plasma store information that is exposed to the eviction policy. */ +/// The plasma store information that is exposed to the eviction policy. struct PlasmaStoreInfo { - /** Objects that are in the Plasma store. */ + /// Objects that are in the Plasma store. std::unordered_map, UniqueIDHasher> objects; - /** The amount of memory (in bytes) that we allow to be allocated in the - * store. */ + /// The amount of memory (in bytes) that we allow to be allocated in the + /// store. int64_t memory_capacity; }; -/** - * Get an entry from the object table and return NULL if the object_id - * is not present. - * - * @param store_info The PlasmaStoreInfo that contains the object table. - * @param object_id The object_id of the entry we are looking for. - * @return The entry associated with the object_id or NULL if the object_id - * is not present. - */ +/// Get an entry from the object table and return NULL if the object_id +/// is not present. +/// +/// @param store_info The PlasmaStoreInfo that contains the object table. +/// @param object_id The object_id of the entry we are looking for. +/// @return The entry associated with the object_id or NULL if the object_id +/// is not present. ObjectTableEntry* get_object_table_entry( PlasmaStoreInfo* store_info, const ObjectID& object_id); -/** - * Print a warning if the status is less than zero. This should be used to check - * the success of messages sent to plasma clients. We print a warning instead of - * failing because the plasma clients are allowed to die. This is used to handle - * situations where the store writes to a client file descriptor, and the client - * may already have disconnected. If we have processed the disconnection and - * closed the file descriptor, we should get a BAD FILE DESCRIPTOR error. If we - * have not, then we should get a SIGPIPE. If we write to a TCP socket that - * isn't connected yet, then we should get an ECONNRESET. - * - * @param status The status to check. If it is less less than zero, we will - * print a warning. - * @param client_sock The client socket. This is just used to print some extra - * information. - * @return The errno set. - */ +/// Print a warning if the status is less than zero. This should be used to check +/// the success of messages sent to plasma clients. We print a warning instead of +/// failing because the plasma clients are allowed to die. This is used to handle +/// situations where the store writes to a client file descriptor, and the client +/// may already have disconnected. If we have processed the disconnection and +/// closed the file descriptor, we should get a BAD FILE DESCRIPTOR error. If we +/// have not, then we should get a SIGPIPE. If we write to a TCP socket that +/// isn't connected yet, then we should get an ECONNRESET. +/// +/// @param status The status to check. If it is less less than zero, we will +/// print a warning. +/// @param client_sock The client socket. This is just used to print some extra +/// information. +/// @return The errno set. int warn_if_sigpipe(int status, int client_sock); uint8_t* create_object_info_buffer(ObjectInfoT* object_info); -#endif /* PLASMA_H */ +#endif // PLASMA_PLASMA_H diff --git a/cpp/src/plasma/protocol.cc b/cpp/src/plasma/protocol.cc index 07cf1d9367e..ffdfb37b5e7 100644 --- a/cpp/src/plasma/protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -35,7 +35,7 @@ to_flatbuffer(flatbuffers::FlatBufferBuilder& fbb, const ObjectID* object_ids, return fbb.CreateVector(results); } -Status PlasmaReceive(int sock, int64_t message_type, std::vector& buffer) { +Status PlasmaReceive(int sock, int64_t message_type, std::vector* buffer) { int64_t type; RETURN_NOT_OK(ReadMessage(sock, &type, buffer)); ARROW_CHECK(type == message_type) << "type = " << type diff --git a/cpp/src/plasma/protocol.h b/cpp/src/plasma/protocol.h index 152d0b7749b..5d9d1367514 100644 --- a/cpp/src/plasma/protocol.h +++ b/cpp/src/plasma/protocol.h @@ -28,7 +28,7 @@ using arrow::Status; /* Plasma receive message. */ -Status PlasmaReceive(int sock, int64_t message_type, std::vector& buffer); +Status PlasmaReceive(int sock, int64_t message_type, std::vector* buffer); /* Plasma Create message functions. */ diff --git a/cpp/src/plasma/store.cc b/cpp/src/plasma/store.cc index 2f8cfc517c8..f17628728f0 100644 --- a/cpp/src/plasma/store.cc +++ b/cpp/src/plasma/store.cc @@ -528,7 +528,7 @@ void PlasmaStore::subscribe_to_updates(Client* client) { Status PlasmaStore::process_message(Client* client) { int64_t type; - Status s = ReadMessage(client->fd, &type, input_buffer_); + Status s = ReadMessage(client->fd, &type, &input_buffer_); ARROW_CHECK(s.ok() || s.IsIOError()); uint8_t* input = input_buffer_.data(); diff --git a/cpp/src/plasma/test/serialization_tests.cc b/cpp/src/plasma/test/serialization_tests.cc index 85a2836ec13..325cead06e7 100644 --- a/cpp/src/plasma/test/serialization_tests.cc +++ b/cpp/src/plasma/test/serialization_tests.cc @@ -51,7 +51,7 @@ std::vector read_message_from_file(int fd, int message_type) { lseek(fd, 0, SEEK_SET); int64_t type; std::vector data; - ARROW_CHECK_OK(ReadMessage(fd, &type, data)); + ARROW_CHECK_OK(ReadMessage(fd, &type, &data)); ARROW_CHECK(type == message_type); return data; } From 5370ae064ad206897c2b881e121b8c9c0f84fb0d Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Tue, 20 Jun 2017 13:00:46 -0700 Subject: [PATCH 42/53] fix plasma protocol --- cpp/src/plasma/protocol.cc | 144 +++++++++++++------------------------ 1 file changed, 51 insertions(+), 93 deletions(-) diff --git a/cpp/src/plasma/protocol.cc b/cpp/src/plasma/protocol.cc index ffdfb37b5e7..af49b60f58d 100644 --- a/cpp/src/plasma/protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -26,13 +26,13 @@ using flatbuffers::uoffset_t; flatbuffers::Offset>> -to_flatbuffer(flatbuffers::FlatBufferBuilder& fbb, const ObjectID* object_ids, +to_flatbuffer(flatbuffers::FlatBufferBuilder* fbb, const ObjectID* object_ids, int64_t num_objects) { std::vector> results; for (int64_t i = 0; i < num_objects; i++) { - results.push_back(fbb.CreateString(object_ids[i].binary())); + results.push_back(fbb->CreateString(object_ids[i].binary())); } - return fbb.CreateVector(results); + return fbb->CreateVector(results); } Status PlasmaReceive(int sock, int64_t message_type, std::vector* buffer) { @@ -43,16 +43,20 @@ Status PlasmaReceive(int sock, int64_t message_type, std::vector* buffe return Status::OK(); } -/* Create messages. */ +template +Status PlasmaSend(int sock, int64_t message_type, flatbuffers::FlatBufferBuilder* fbb, const Message& message) { + fbb->Finish(message); + return WriteMessage(sock, MessageType_PlasmaCreateRequest, fbb->GetSize(), fbb->GetBufferPointer()); +} + +// Create messages. Status SendCreateRequest( int sock, ObjectID object_id, int64_t data_size, int64_t metadata_size) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaCreateRequest( fbb, fbb.CreateString(object_id.binary()), data_size, metadata_size); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaCreateRequest, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaCreateRequest, &fbb, message); } Status ReadCreateRequest( @@ -73,9 +77,7 @@ Status SendCreateReply( object->metadata_size); auto message = CreatePlasmaCreateReply( fbb, fbb.CreateString(object_id.binary()), &plasma_object, (PlasmaError)error_code); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaCreateReply, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaCreateReply, &fbb, message); } Status ReadCreateReply(uint8_t* data, ObjectID* object_id, PlasmaObject* object) { @@ -91,16 +93,14 @@ Status ReadCreateReply(uint8_t* data, ObjectID* object_id, PlasmaObject* object) return plasma_error_status(message->error()); } -/* Seal messages. */ +// Seal messages. Status SendSealRequest(int sock, ObjectID object_id, unsigned char* digest) { flatbuffers::FlatBufferBuilder fbb; auto digest_string = fbb.CreateString(reinterpret_cast(digest), kDigestSize); auto message = CreatePlasmaSealRequest(fbb, fbb.CreateString(object_id.binary()), digest_string); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaSealRequest, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaSealRequest, &fbb, message); } Status ReadSealRequest(uint8_t* data, ObjectID* object_id, unsigned char* digest) { @@ -116,9 +116,7 @@ Status SendSealReply(int sock, ObjectID object_id, int error) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaSealReply( fbb, fbb.CreateString(object_id.binary()), (PlasmaError)error); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaSealReply, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaSealReply, &fbb, message); } Status ReadSealReply(uint8_t* data, ObjectID* object_id) { @@ -128,14 +126,12 @@ Status ReadSealReply(uint8_t* data, ObjectID* object_id) { return plasma_error_status(message->error()); } -/* Release messages. */ +// Release messages. Status SendReleaseRequest(int sock, ObjectID object_id) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaSealRequest(fbb, fbb.CreateString(object_id.binary())); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaReleaseRequest, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaReleaseRequest, &fbb, message); } Status ReadReleaseRequest(uint8_t* data, ObjectID* object_id) { @@ -149,9 +145,7 @@ Status SendReleaseReply(int sock, ObjectID object_id, int error) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaReleaseReply( fbb, fbb.CreateString(object_id.binary()), (PlasmaError)error); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaReleaseReply, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaReleaseReply, &fbb, message); } Status ReadReleaseReply(uint8_t* data, ObjectID* object_id) { @@ -161,14 +155,12 @@ Status ReadReleaseReply(uint8_t* data, ObjectID* object_id) { return plasma_error_status(message->error()); } -/* Delete messages. */ +// Delete messages. Status SendDeleteRequest(int sock, ObjectID object_id) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaDeleteRequest(fbb, fbb.CreateString(object_id.binary())); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaDeleteRequest, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaDeleteRequest, &fbb, message); } Status ReadDeleteRequest(uint8_t* data, ObjectID* object_id) { @@ -182,9 +174,7 @@ Status SendDeleteReply(int sock, ObjectID object_id, int error) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaDeleteReply( fbb, fbb.CreateString(object_id.binary()), (PlasmaError)error); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaDeleteReply, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaDeleteReply, &fbb, message); } Status ReadDeleteReply(uint8_t* data, ObjectID* object_id) { @@ -194,15 +184,13 @@ Status ReadDeleteReply(uint8_t* data, ObjectID* object_id) { return plasma_error_status(message->error()); } -/* Satus messages. */ +// Satus messages. Status SendStatusRequest(int sock, const ObjectID* object_ids, int64_t num_objects) { flatbuffers::FlatBufferBuilder fbb; auto message = - CreatePlasmaStatusRequest(fbb, to_flatbuffer(fbb, object_ids, num_objects)); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaStatusRequest, fbb.GetSize(), fbb.GetBufferPointer()); + CreatePlasmaStatusRequest(fbb, to_flatbuffer(&fbb, object_ids, num_objects)); + return PlasmaSend(sock, MessageType_PlasmaStatusRequest, &fbb, message); } Status ReadStatusRequest(uint8_t* data, ObjectID object_ids[], int64_t num_objects) { @@ -217,11 +205,9 @@ Status ReadStatusRequest(uint8_t* data, ObjectID object_ids[], int64_t num_objec Status SendStatusReply( int sock, ObjectID object_ids[], int object_status[], int64_t num_objects) { flatbuffers::FlatBufferBuilder fbb; - auto message = CreatePlasmaStatusReply(fbb, to_flatbuffer(fbb, object_ids, num_objects), + auto message = CreatePlasmaStatusReply(fbb, to_flatbuffer(&fbb, object_ids, num_objects), fbb.CreateVector(object_status, num_objects)); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaStatusReply, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaStatusReply, &fbb, message); } int64_t ReadStatusReply_num_objects(uint8_t* data) { @@ -243,14 +229,12 @@ Status ReadStatusReply( return Status::OK(); } -/* Contains messages. */ +// Contains messages. Status SendContainsRequest(int sock, ObjectID object_id) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaContainsRequest(fbb, fbb.CreateString(object_id.binary())); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaContainsRequest, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaContainsRequest, &fbb, message); } Status ReadContainsRequest(uint8_t* data, ObjectID* object_id) { @@ -264,9 +248,7 @@ Status SendContainsReply(int sock, ObjectID object_id, bool has_object) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaContainsReply(fbb, fbb.CreateString(object_id.binary()), has_object); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaContainsReply, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaContainsReply, &fbb, message); } Status ReadContainsReply(uint8_t* data, ObjectID* object_id, bool* has_object) { @@ -277,14 +259,12 @@ Status ReadContainsReply(uint8_t* data, ObjectID* object_id, bool* has_object) { return Status::OK(); } -/* Connect messages. */ +// Connect messages. Status SendConnectRequest(int sock) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaConnectRequest(fbb); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaConnectRequest, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaConnectRequest, &fbb, message); } Status ReadConnectRequest(uint8_t* data) { @@ -294,9 +274,7 @@ Status ReadConnectRequest(uint8_t* data) { Status SendConnectReply(int sock, int64_t memory_capacity) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaConnectReply(fbb, memory_capacity); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaConnectReply, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaConnectReply, &fbb, message); } Status ReadConnectReply(uint8_t* data, int64_t* memory_capacity) { @@ -306,14 +284,12 @@ Status ReadConnectReply(uint8_t* data, int64_t* memory_capacity) { return Status::OK(); } -/* Evict messages. */ +// Evict messages. Status SendEvictRequest(int sock, int64_t num_bytes) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaEvictRequest(fbb, num_bytes); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaEvictRequest, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaEvictRequest, &fbb, message); } Status ReadEvictRequest(uint8_t* data, int64_t* num_bytes) { @@ -326,9 +302,7 @@ Status ReadEvictRequest(uint8_t* data, int64_t* num_bytes) { Status SendEvictReply(int sock, int64_t num_bytes) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaEvictReply(fbb, num_bytes); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaEvictReply, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaEvictReply, &fbb, message); } Status ReadEvictReply(uint8_t* data, int64_t& num_bytes) { @@ -338,16 +312,14 @@ Status ReadEvictReply(uint8_t* data, int64_t& num_bytes) { return Status::OK(); } -/* Get messages. */ +// Get messages. Status SendGetRequest( int sock, const ObjectID* object_ids, int64_t num_objects, int64_t timeout_ms) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaGetRequest( - fbb, to_flatbuffer(fbb, object_ids, num_objects), timeout_ms); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaGetRequest, fbb.GetSize(), fbb.GetBufferPointer()); + fbb, to_flatbuffer(&fbb, object_ids, num_objects), timeout_ms); + return PlasmaSend(sock, MessageType_PlasmaGetRequest, &fbb, message); } Status ReadGetRequest( @@ -374,11 +346,9 @@ Status SendGetReply(int sock, ObjectID object_ids[], object.data_offset, object.data_size, object.metadata_offset, object.metadata_size)); } - auto message = CreatePlasmaGetReply(fbb, to_flatbuffer(fbb, object_ids, num_objects), + auto message = CreatePlasmaGetReply(fbb, to_flatbuffer(&fbb, object_ids, num_objects), fbb.CreateVectorOfStructs(objects.data(), num_objects)); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaGetReply, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaGetReply, &fbb, message); } Status ReadGetReply(uint8_t* data, ObjectID object_ids[], PlasmaObject plasma_objects[], @@ -400,15 +370,13 @@ Status ReadGetReply(uint8_t* data, ObjectID object_ids[], PlasmaObject plasma_ob return Status::OK(); } -/* Fetch messages. */ +// Fetch messages. Status SendFetchRequest(int sock, const ObjectID* object_ids, int64_t num_objects) { flatbuffers::FlatBufferBuilder fbb; auto message = - CreatePlasmaFetchRequest(fbb, to_flatbuffer(fbb, object_ids, num_objects)); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaFetchRequest, fbb.GetSize(), fbb.GetBufferPointer()); + CreatePlasmaFetchRequest(fbb, to_flatbuffer(&fbb, object_ids, num_objects)); + return PlasmaSend(sock, MessageType_PlasmaFetchRequest, &fbb, message); } Status ReadFetchRequest(uint8_t* data, std::vector& object_ids) { @@ -420,7 +388,7 @@ Status ReadFetchRequest(uint8_t* data, std::vector& object_ids) { return Status::OK(); } -/* Wait messages. */ +// Wait messages. Status SendWaitRequest(int sock, ObjectRequest object_requests[], int64_t num_requests, int num_ready_objects, int64_t timeout_ms) { @@ -435,9 +403,7 @@ Status SendWaitRequest(int sock, ObjectRequest object_requests[], int64_t num_re auto message = CreatePlasmaWaitRequest( fbb, fbb.CreateVector(object_request_specs), num_ready_objects, timeout_ms); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaWaitRequest, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaWaitRequest, &fbb, message); } Status ReadWaitRequest(uint8_t* data, ObjectRequestMap& object_requests, @@ -470,9 +436,7 @@ Status SendWaitReply( auto message = CreatePlasmaWaitReply( fbb, fbb.CreateVector(object_replies.data(), num_ready_objects), num_ready_objects); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaWaitReply, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaWaitReply, &fbb, message); } Status ReadWaitReply( @@ -489,26 +453,22 @@ Status ReadWaitReply( return Status::OK(); } -/* Subscribe messages. */ +// Subscribe messages. Status SendSubscribeRequest(int sock) { flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaSubscribeRequest(fbb); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaSubscribeRequest, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaSubscribeRequest, &fbb, message); } -/* Data messages. */ +// Data messages. Status SendDataRequest(int sock, ObjectID object_id, const char* address, int port) { flatbuffers::FlatBufferBuilder fbb; auto addr = fbb.CreateString(address, strlen(address)); auto message = CreatePlasmaDataRequest(fbb, fbb.CreateString(object_id.binary()), addr, port); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaDataRequest, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaDataRequest, &fbb, message); } Status ReadDataRequest(uint8_t* data, ObjectID* object_id, char** address, int* port) { @@ -526,9 +486,7 @@ Status SendDataReply( flatbuffers::FlatBufferBuilder fbb; auto message = CreatePlasmaDataReply( fbb, fbb.CreateString(object_id.binary()), object_size, metadata_size); - fbb.Finish(message); - return WriteMessage( - sock, MessageType_PlasmaDataReply, fbb.GetSize(), fbb.GetBufferPointer()); + return PlasmaSend(sock, MessageType_PlasmaDataReply, &fbb, message); } Status ReadDataReply( From 81437920a416bd0cc3db25295dc7da54be747de0 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Tue, 20 Jun 2017 13:02:57 -0700 Subject: [PATCH 43/53] fix linting --- cpp/src/plasma/client.h | 2 +- cpp/src/plasma/extension.cc | 6 ++++-- cpp/src/plasma/extension.h | 2 +- cpp/src/plasma/io.h | 2 +- cpp/src/plasma/malloc.h | 2 +- cpp/src/plasma/plasma.h | 5 ++--- cpp/src/plasma/protocol.cc | 13 ++++++++----- 7 files changed, 18 insertions(+), 14 deletions(-) diff --git a/cpp/src/plasma/client.h b/cpp/src/plasma/client.h index a1fb745f2cf..fb3a161795d 100644 --- a/cpp/src/plasma/client.h +++ b/cpp/src/plasma/client.h @@ -340,4 +340,4 @@ class PlasmaClient { bool plasma_compute_object_hash( PlasmaClient* conn, ObjectID object_id, unsigned char* digest); -#endif // PLASMA_CLIENT_H +#endif // PLASMA_CLIENT_H diff --git a/cpp/src/plasma/extension.cc b/cpp/src/plasma/extension.cc index b81da512e15..5d61e337c10 100644 --- a/cpp/src/plasma/extension.cc +++ b/cpp/src/plasma/extension.cc @@ -152,7 +152,8 @@ PyObject* PyPlasma_get(PyObject* self, PyObject* args) { } Py_BEGIN_ALLOW_THREADS; - ARROW_CHECK_OK(client->Get(object_ids.data(), num_object_ids, timeout_ms, object_buffers.data())); + ARROW_CHECK_OK( + client->Get(object_ids.data(), num_object_ids, timeout_ms, object_buffers.data())); Py_END_ALLOW_THREADS; PyObject* returns = PyList_New(num_object_ids); @@ -166,7 +167,8 @@ PyObject* PyPlasma_get(PyObject* self, PyObject* args) { char* data = reinterpret_cast(object_buffers[i].data); char* metadata = reinterpret_cast(object_buffers[i].metadata); PyTuple_SET_ITEM(t, 0, PyMemoryView_FromMemory(data, data_size, PyBUF_READ)); - PyTuple_SET_ITEM(t, 1, PyMemoryView_FromMemory(metadata, metadata_size, PyBUF_READ)); + PyTuple_SET_ITEM( + t, 1, PyMemoryView_FromMemory(metadata, metadata_size, PyBUF_READ)); #else void* data = reinterpret_cast(object_buffers[i].data); void* metadata = reinterpret_cast(object_buffers[i].metadata); diff --git a/cpp/src/plasma/extension.h b/cpp/src/plasma/extension.h index f7a044d2920..cee30abb359 100644 --- a/cpp/src/plasma/extension.h +++ b/cpp/src/plasma/extension.h @@ -47,4 +47,4 @@ int PyStringToUniqueID(PyObject* object, ObjectID* object_id) { } } -#endif // PLASMA_EXTENSION_H +#endif // PLASMA_EXTENSION_H diff --git a/cpp/src/plasma/io.h b/cpp/src/plasma/io.h index 3cb031990a1..43c3fb53549 100644 --- a/cpp/src/plasma/io.h +++ b/cpp/src/plasma/io.h @@ -52,4 +52,4 @@ int AcceptClient(int socket_fd); uint8_t* read_message_async(int sock); -#endif // PLASMA_IO_H +#endif // PLASMA_IO_H diff --git a/cpp/src/plasma/malloc.h b/cpp/src/plasma/malloc.h index 4d3419339e4..b4af2c826b5 100644 --- a/cpp/src/plasma/malloc.h +++ b/cpp/src/plasma/malloc.h @@ -23,4 +23,4 @@ void get_malloc_mapinfo(void* addr, int* fd, int64_t* map_length, ptrdiff_t* offset); -#endif // MALLOC_H +#endif // MALLOC_H diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h index a52313e8500..a1164d55763 100644 --- a/cpp/src/plasma/plasma.h +++ b/cpp/src/plasma/plasma.h @@ -25,7 +25,7 @@ #include #include #include -#include // pid_t +#include // pid_t #include #include @@ -59,7 +59,6 @@ constexpr int64_t kDigestSize = sizeof(uint64_t); struct Client; - /// Object request data structure. Used in the plasma_wait_for_objects() /// argument. typedef struct { @@ -188,4 +187,4 @@ int warn_if_sigpipe(int status, int client_sock); uint8_t* create_object_info_buffer(ObjectInfoT* object_info); -#endif // PLASMA_PLASMA_H +#endif // PLASMA_PLASMA_H diff --git a/cpp/src/plasma/protocol.cc b/cpp/src/plasma/protocol.cc index af49b60f58d..92a7076c964 100644 --- a/cpp/src/plasma/protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -43,10 +43,12 @@ Status PlasmaReceive(int sock, int64_t message_type, std::vector* buffe return Status::OK(); } -template -Status PlasmaSend(int sock, int64_t message_type, flatbuffers::FlatBufferBuilder* fbb, const Message& message) { +template +Status PlasmaSend(int sock, int64_t message_type, flatbuffers::FlatBufferBuilder* fbb, + const Message& message) { fbb->Finish(message); - return WriteMessage(sock, MessageType_PlasmaCreateRequest, fbb->GetSize(), fbb->GetBufferPointer()); + return WriteMessage( + sock, MessageType_PlasmaCreateRequest, fbb->GetSize(), fbb->GetBufferPointer()); } // Create messages. @@ -205,8 +207,9 @@ Status ReadStatusRequest(uint8_t* data, ObjectID object_ids[], int64_t num_objec Status SendStatusReply( int sock, ObjectID object_ids[], int object_status[], int64_t num_objects) { flatbuffers::FlatBufferBuilder fbb; - auto message = CreatePlasmaStatusReply(fbb, to_flatbuffer(&fbb, object_ids, num_objects), - fbb.CreateVector(object_status, num_objects)); + auto message = + CreatePlasmaStatusReply(fbb, to_flatbuffer(&fbb, object_ids, num_objects), + fbb.CreateVector(object_status, num_objects)); return PlasmaSend(sock, MessageType_PlasmaStatusReply, &fbb, message); } From 00f17f24efef3689a2bed95538953ac24799b365 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Tue, 20 Jun 2017 13:51:47 -0700 Subject: [PATCH 44/53] fix licenses --- LICENSE.txt | 76 ++++++++++++++++++++++++++ cpp/src/plasma/plasma.h | 1 + cpp/src/plasma/store.cc | 5 +- cpp/src/plasma/thirdparty/ae/zmalloc.h | 29 ++++++++++ 4 files changed, 109 insertions(+), 2 deletions(-) diff --git a/LICENSE.txt b/LICENSE.txt index 3c309eb5b06..70007337937 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -220,3 +220,79 @@ See the License for the specific language governing permissions and limitations under the License. -------------------------------------------------------------------------------- + +src/plasma/thirdparty/ae: Modified / 3-Clause BSD + +Copyright (c) 2006-2010, Salvatore Sanfilippo +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 Redis 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. + +-------------------------------------------------------------------------------- + +src/plasma/thirdparty/dlmalloc.c: CC0 + +This is a version (aka dlmalloc) of malloc/free/realloc written by +Doug Lea and released to the public domain, as explained at +http://creativecommons.org/publicdomain/zero/1.0/ Send questions, +comments, complaints, performance data, etc to dl@cs.oswego.edu + +-------------------------------------------------------------------------------- + +src/plasma/thirdparty/xxhash: BSD 2-Clause License + +xxHash - Fast Hash algorithm +Copyright (C) 2012-2016, Yann Collet + +BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +You can contact the author at : +- xxHash homepage: http://www.xxhash.com +- xxHash source repository : https://github.com/Cyan4973/xxHash + +-------------------------------------------------------------------------------- diff --git a/cpp/src/plasma/plasma.h b/cpp/src/plasma/plasma.h index a1164d55763..275d0c7a416 100644 --- a/cpp/src/plasma/plasma.h +++ b/cpp/src/plasma/plasma.h @@ -93,6 +93,7 @@ typedef struct { int64_t mmap_size; } object_handle; +// TODO(pcm): Replace this by the flatbuffers message PlasmaObjectSpec. typedef struct { /// Handle for memory mapped file the object is stored in. object_handle handle; diff --git a/cpp/src/plasma/store.cc b/cpp/src/plasma/store.cc index f17628728f0..5151a44d721 100644 --- a/cpp/src/plasma/store.cc +++ b/cpp/src/plasma/store.cc @@ -62,8 +62,7 @@ void dlfree(void* mem); size_t dlmalloc_set_footprint_limit(size_t bytes); } -class GetRequest { - public: +struct GetRequest { GetRequest(Client* client, const std::vector& object_ids); /// The client that called get. Client* client; @@ -100,12 +99,14 @@ PlasmaStore::PlasmaStore(EventLoop* loop, int64_t system_memory) store_info_.memory_capacity = system_memory; } +// TODO(pcm): Get rid of this destructor by using RAII to clean up data. PlasmaStore::~PlasmaStore() { for (const auto& element : pending_notifications_) { auto object_notifications = element.second.object_notifications; for (size_t i = 0; i < object_notifications.size(); ++i) { uint8_t* notification = reinterpret_cast(object_notifications.at(i)); uint8_t* data = notification; + // TODO(pcm): Get rid of this delete. delete[] data; } } diff --git a/cpp/src/plasma/thirdparty/ae/zmalloc.h b/cpp/src/plasma/thirdparty/ae/zmalloc.h index 54c8a69cb2e..6c27dd4e5c3 100644 --- a/cpp/src/plasma/thirdparty/ae/zmalloc.h +++ b/cpp/src/plasma/thirdparty/ae/zmalloc.h @@ -1,3 +1,32 @@ +/* + * Copyright (c) 2009-2012, Salvatore Sanfilippo + * 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 Redis 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. + */ + #ifndef _ZMALLOC_H #define _ZMALLOC_H From 4497e337565cd3db951f6f2692a1e4c548cea1bf Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Tue, 20 Jun 2017 14:18:35 -0700 Subject: [PATCH 45/53] fix tests --- cpp/src/plasma/protocol.cc | 3 +- cpp/src/plasma/test/client_tests.cc | 83 +++++++++++++---------------- 2 files changed, 38 insertions(+), 48 deletions(-) diff --git a/cpp/src/plasma/protocol.cc b/cpp/src/plasma/protocol.cc index 92a7076c964..246aa297360 100644 --- a/cpp/src/plasma/protocol.cc +++ b/cpp/src/plasma/protocol.cc @@ -47,8 +47,7 @@ template Status PlasmaSend(int sock, int64_t message_type, flatbuffers::FlatBufferBuilder* fbb, const Message& message) { fbb->Finish(message); - return WriteMessage( - sock, MessageType_PlasmaCreateRequest, fbb->GetSize(), fbb->GetBufferPointer()); + return WriteMessage(sock, message_type, fbb->GetSize(), fbb->GetBufferPointer()); } // Create messages. diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index 13e343eaba6..216594efc33 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -28,25 +28,33 @@ #include "plasma/plasma.h" #include "plasma/protocol.h" -// TODO(pcm): At the moment, stdout of the test gets mixed up with -// stdout of the object store. Consider changing that. -pid_t start_store() { - pid_t pid = fork(); - if (pid != 0) { return pid; } - execlp("./plasma_store", "./plasma_store", "-m", "10000000", "-s", "/tmp/store", NULL); - return 0; -} - -TEST(PlasmaClient, ContainsTest) { - pid_t store = start_store(); - PlasmaClient client; - ARROW_CHECK_OK(client.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); +class TestPlasmaStore : public ::testing::Test { + public: + // TODO(pcm): At the moment, stdout of the test gets mixed up with + // stdout of the object store. Consider changing that. + void SetUp() { + pid_ = fork(); + if (pid_ != 0) { + ARROW_CHECK_OK(client_.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); + return; + } + execlp("./plasma_store", "./plasma_store", "-m", "10000000", "-s", "/tmp/store", NULL); + } + virtual void Finish() { + ARROW_CHECK_OK(client_.Disconnect()); + kill(pid_, SIGKILL); + } + protected: + pid_t pid_; + PlasmaClient client_; +}; +TEST_F(TestPlasmaStore, ContainsTest) { ObjectID object_id = ObjectID::from_random(); // Test for object non-existence. bool has_object; - ARROW_CHECK_OK(client.Contains(object_id, &has_object)); + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); ASSERT_EQ(has_object, false); // Test for the object being in local Plasma store. @@ -55,28 +63,21 @@ TEST(PlasmaClient, ContainsTest) { uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); uint8_t* data; - ARROW_CHECK_OK(client.Create(object_id, data_size, metadata, metadata_size, &data)); - ARROW_CHECK_OK(client.Seal(object_id)); + ARROW_CHECK_OK(client_.Create(object_id, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client_.Seal(object_id)); // Avoid race condition of Plasma Manager waiting for notification. ObjectBuffer object_buffer; - ARROW_CHECK_OK(client.Get(&object_id, 1, -1, &object_buffer)); - ARROW_CHECK_OK(client.Contains(object_id, &has_object)); + ARROW_CHECK_OK(client_.Get(&object_id, 1, -1, &object_buffer)); + ARROW_CHECK_OK(client_.Contains(object_id, &has_object)); ASSERT_EQ(has_object, true); - - ARROW_CHECK_OK(client.Disconnect()); - kill(store, SIGKILL); } -TEST(PlasmaClient, GetTest) { - pid_t store = start_store(); - PlasmaClient client; - ARROW_CHECK_OK(client.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); - +TEST_F(TestPlasmaStore, GetTest) { ObjectID object_id = ObjectID::from_random(); ObjectBuffer object_buffer; // Test for object non-existence. - ARROW_CHECK_OK(client.Get(&object_id, 1, 0, &object_buffer)); + ARROW_CHECK_OK(client_.Get(&object_id, 1, 0, &object_buffer)); ASSERT_EQ(object_buffer.data_size, -1); // Test for the object being in local Plasma store. @@ -85,26 +86,19 @@ TEST(PlasmaClient, GetTest) { uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); uint8_t* data; - ARROW_CHECK_OK(client.Create(object_id, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client_.Create(object_id, data_size, metadata, metadata_size, &data)); for (int64_t i = 0; i < data_size; i++) { data[i] = static_cast(i % 4); } - ARROW_CHECK_OK(client.Seal(object_id)); + ARROW_CHECK_OK(client_.Seal(object_id)); - ARROW_CHECK_OK(client.Get(&object_id, 1, -1, &object_buffer)); + ARROW_CHECK_OK(client_.Get(&object_id, 1, -1, &object_buffer)); for (int64_t i = 0; i < data_size; i++) { ASSERT_EQ(data[i], object_buffer.data[i]); } - - ARROW_CHECK_OK(client.Disconnect()); - kill(store, SIGKILL); } -TEST(PlasmaClient, MultipleGetTest) { - pid_t store = start_store(); - PlasmaClient client; - ARROW_CHECK_OK(client.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); - +TEST_F(TestPlasmaStore, MultipleGetTest) { ObjectID object_id1 = ObjectID::from_random(); ObjectID object_id2 = ObjectID::from_random(); ObjectID object_ids[2] = {object_id1, object_id2}; @@ -114,18 +108,15 @@ TEST(PlasmaClient, MultipleGetTest) { uint8_t metadata[] = {5}; int64_t metadata_size = sizeof(metadata); uint8_t* data; - ARROW_CHECK_OK(client.Create(object_id1, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client_.Create(object_id1, data_size, metadata, metadata_size, &data)); data[0] = 1; - ARROW_CHECK_OK(client.Seal(object_id1)); + ARROW_CHECK_OK(client_.Seal(object_id1)); - ARROW_CHECK_OK(client.Create(object_id2, data_size, metadata, metadata_size, &data)); + ARROW_CHECK_OK(client_.Create(object_id2, data_size, metadata, metadata_size, &data)); data[0] = 2; - ARROW_CHECK_OK(client.Seal(object_id2)); + ARROW_CHECK_OK(client_.Seal(object_id2)); - ARROW_CHECK_OK(client.Get(object_ids, 2, -1, object_buffer)); + ARROW_CHECK_OK(client_.Get(object_ids, 2, -1, object_buffer)); ASSERT_EQ(object_buffer[0].data[0], 1); ASSERT_EQ(object_buffer[1].data[0], 2); - - ARROW_CHECK_OK(client.Disconnect()); - kill(store, SIGKILL); } From 61d421b511a43c78187e3f12c38c6004117c467e Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Tue, 20 Jun 2017 15:10:26 -0700 Subject: [PATCH 46/53] fix formatting --- cpp/src/plasma/test/client_tests.cc | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index 216594efc33..966785adbdc 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -38,12 +38,14 @@ class TestPlasmaStore : public ::testing::Test { ARROW_CHECK_OK(client_.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); return; } - execlp("./plasma_store", "./plasma_store", "-m", "10000000", "-s", "/tmp/store", NULL); + execlp( + "./plasma_store", "./plasma_store", "-m", "10000000", "-s", "/tmp/store", NULL); } virtual void Finish() { ARROW_CHECK_OK(client_.Disconnect()); kill(pid_, SIGKILL); } + protected: pid_t pid_; PlasmaClient client_; From 85aa17104e315abfd73c04abc816c3e5eaa0deda Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Tue, 20 Jun 2017 16:34:15 -0700 Subject: [PATCH 47/53] fix mac tests --- cpp/src/plasma/store.h | 2 +- cpp/src/plasma/test/client_tests.cc | 14 +++++--------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/cpp/src/plasma/store.h b/cpp/src/plasma/store.h index a21c7232534..8bd94265410 100644 --- a/cpp/src/plasma/store.h +++ b/cpp/src/plasma/store.h @@ -27,7 +27,7 @@ #include "plasma/plasma.h" #include "plasma/protocol.h" -class GetRequest; +struct GetRequest; struct NotificationQueue { /// The object notifications for clients. We notify the client about the diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index 966785adbdc..8f53b0e664c 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -33,21 +34,16 @@ class TestPlasmaStore : public ::testing::Test { // TODO(pcm): At the moment, stdout of the test gets mixed up with // stdout of the object store. Consider changing that. void SetUp() { - pid_ = fork(); - if (pid_ != 0) { - ARROW_CHECK_OK(client_.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); - return; - } - execlp( - "./plasma_store", "./plasma_store", "-m", "10000000", "-s", "/tmp/store", NULL); + system("./plasma_store -m 1000000000 -s /tmp/store &"); + ARROW_CHECK_OK(client_.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); } virtual void Finish() { ARROW_CHECK_OK(client_.Disconnect()); - kill(pid_, SIGKILL); + system("killall plasma_store"); + usleep(1000000); } protected: - pid_t pid_; PlasmaClient client_; }; From 4c474d716086dff810598268b26b71f42af23894 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Tue, 20 Jun 2017 18:28:52 -0700 Subject: [PATCH 48/53] run plasma_store from the right directory --- cpp/src/plasma/test/client_tests.cc | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index 8f53b0e664c..8018d9af730 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -29,12 +29,16 @@ #include "plasma/plasma.h" #include "plasma/protocol.h" +std::string g_test_executable; + class TestPlasmaStore : public ::testing::Test { public: // TODO(pcm): At the moment, stdout of the test gets mixed up with // stdout of the object store. Consider changing that. void SetUp() { - system("./plasma_store -m 1000000000 -s /tmp/store &"); + std::string plasma_directory = g_test_executable.substr(0, g_test_executable.find_last_of("/")); + std::string plasma_command = plasma_directory + "/plasma_store -m 1000000000 -s /tmp/store &"; + system(plasma_command.c_str()); ARROW_CHECK_OK(client_.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); } virtual void Finish() { @@ -118,3 +122,9 @@ TEST_F(TestPlasmaStore, MultipleGetTest) { ASSERT_EQ(object_buffer[0].data[0], 1); ASSERT_EQ(object_buffer[1].data[0], 2); } + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + g_test_executable = std::string(argv[0]); + return RUN_ALL_TESTS(); +} From 80f9df4061a739dca30072041a15a214408e3577 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Tue, 20 Jun 2017 18:55:56 -0700 Subject: [PATCH 49/53] make format --- cpp/src/plasma/test/client_tests.cc | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index 8018d9af730..822effd04ab 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -36,8 +36,10 @@ class TestPlasmaStore : public ::testing::Test { // TODO(pcm): At the moment, stdout of the test gets mixed up with // stdout of the object store. Consider changing that. void SetUp() { - std::string plasma_directory = g_test_executable.substr(0, g_test_executable.find_last_of("/")); - std::string plasma_command = plasma_directory + "/plasma_store -m 1000000000 -s /tmp/store &"; + std::string plasma_directory = + g_test_executable.substr(0, g_test_executable.find_last_of("/")); + std::string plasma_command = + plasma_directory + "/plasma_store -m 1000000000 -s /tmp/store &"; system(plasma_command.c_str()); ARROW_CHECK_OK(client_.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); } From 0f321e16a68e95e2aa4cf82b10a9303b86948386 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Tue, 20 Jun 2017 20:20:10 -0700 Subject: [PATCH 50/53] try to fix tests --- cpp/src/plasma/test/client_tests.cc | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index 822effd04ab..1e2c3fe9e65 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -45,8 +45,7 @@ class TestPlasmaStore : public ::testing::Test { } virtual void Finish() { ARROW_CHECK_OK(client_.Disconnect()); - system("killall plasma_store"); - usleep(1000000); + system("killall plasma_store &"); } protected: From 16d1f716b220e3dbce7193271d4a8648d77de87d Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Wed, 21 Jun 2017 10:29:42 -0700 Subject: [PATCH 51/53] fix test hanging --- cpp/src/plasma/test/client_tests.cc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cpp/src/plasma/test/client_tests.cc b/cpp/src/plasma/test/client_tests.cc index 1e2c3fe9e65..dc457731b69 100644 --- a/cpp/src/plasma/test/client_tests.cc +++ b/cpp/src/plasma/test/client_tests.cc @@ -39,7 +39,8 @@ class TestPlasmaStore : public ::testing::Test { std::string plasma_directory = g_test_executable.substr(0, g_test_executable.find_last_of("/")); std::string plasma_command = - plasma_directory + "/plasma_store -m 1000000000 -s /tmp/store &"; + plasma_directory + + "/plasma_store -m 1000000000 -s /tmp/store 1> /dev/null 2> /dev/null &"; system(plasma_command.c_str()); ARROW_CHECK_OK(client_.Connect("/tmp/store", "", PLASMA_DEFAULT_RELEASE_DELAY)); } From d67160c55c9f94c895962113305ec7887a2cf505 Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Wed, 21 Jun 2017 10:52:57 -0700 Subject: [PATCH 52/53] build dlmalloc with -O3 --- cpp/src/plasma/CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cpp/src/plasma/CMakeLists.txt b/cpp/src/plasma/CMakeLists.txt index 4cc09e6d051..992c33ed0fc 100644 --- a/cpp/src/plasma/CMakeLists.txt +++ b/cpp/src/plasma/CMakeLists.txt @@ -89,7 +89,9 @@ ADD_ARROW_LIB(plasma SHARED_LINK_LIBS ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT} arrow_static STATIC_LINK_LIBS ${FLATBUFFERS_STATIC_LIB} ${CMAKE_THREAD_LIBS_INIT} arrow_static) -set_source_files_properties(malloc.cc PROPERTIES COMPILE_FLAGS "-Wno-error=conversion") +# The optimization flag -O3 is suggested by dlmalloc.c, which is #included in +# malloc.cc; we set it here regardless of whether we do a debug or release build. +set_source_files_properties(malloc.cc PROPERTIES COMPILE_FLAGS "-Wno-error=conversion -O3") add_executable(plasma_store store.cc) target_link_libraries(plasma_store plasma_static) From c100a4535d5ba7e8cdd746cc46a88f92286dbd4e Mon Sep 17 00:00:00 2001 From: Philipp Moritz Date: Wed, 21 Jun 2017 11:17:00 -0700 Subject: [PATCH 53/53] fixes --- cpp/src/plasma/client.cc | 1 + cpp/src/plasma/events.cc | 2 +- cpp/src/plasma/events.h | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/cpp/src/plasma/client.cc b/cpp/src/plasma/client.cc index e45d0941622..dcb78e7ec52 100644 --- a/cpp/src/plasma/client.cc +++ b/cpp/src/plasma/client.cc @@ -67,6 +67,7 @@ uint8_t* PlasmaClient::lookup_or_mmap(int fd, int store_fd_val, int64_t map_size } else { uint8_t* result = reinterpret_cast( mmap(NULL, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)); + // TODO(pcm): Don't fail here, instead return a Status. if (result == MAP_FAILED) { ARROW_LOG(FATAL) << "mmap failed"; } close(fd); ClientMmapTableEntry& entry = mmap_table_[store_fd_val]; diff --git a/cpp/src/plasma/events.cc b/cpp/src/plasma/events.cc index 0f54c989c17..a9f7356e1f6 100644 --- a/cpp/src/plasma/events.cc +++ b/cpp/src/plasma/events.cc @@ -65,7 +65,7 @@ void EventLoop::run() { aeMain(loop_); } -int64_t EventLoop::add_timer(int64_t timeout, TimerCallback callback) { +int64_t EventLoop::add_timer(int64_t timeout, const TimerCallback& callback) { auto data = std::unique_ptr(new TimerCallback(callback)); void* context = reinterpret_cast(data.get()); int64_t timer_id = diff --git a/cpp/src/plasma/events.h b/cpp/src/plasma/events.h index 0a87d16375c..bd93d6bb2a6 100644 --- a/cpp/src/plasma/events.h +++ b/cpp/src/plasma/events.h @@ -49,7 +49,7 @@ class EventLoop { // passed as an argument. The return is the number of milliseconds the timer // shall be reset to or kEventLoopTimerDone if the timer shall not be // triggered again. - typedef std::function TimerCallback; + using TimerCallback = std::function; EventLoop(); @@ -73,7 +73,7 @@ class EventLoop { /// @param timeout The timeout in milliseconds. /// @param callback The callback for the timeout. /// @return The ID of the newly created timer. - int64_t add_timer(int64_t timeout, TimerCallback callback); + int64_t add_timer(int64_t timeout, const TimerCallback& callback); /// Remove a timer handler from the event loop. ///