aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/core/lib/support
diff options
context:
space:
mode:
Diffstat (limited to 'src/core/lib/support')
-rw-r--r--src/core/lib/support/alloc.c92
-rw-r--r--src/core/lib/support/avl.c288
-rw-r--r--src/core/lib/support/backoff.c76
-rw-r--r--src/core/lib/support/backoff.h68
-rw-r--r--src/core/lib/support/block_annotate.h48
-rw-r--r--src/core/lib/support/cmdline.c347
-rw-r--r--src/core/lib/support/cpu_iphone.c49
-rw-r--r--src/core/lib/support/cpu_linux.c78
-rw-r--r--src/core/lib/support/cpu_posix.c77
-rw-r--r--src/core/lib/support/cpu_windows.c47
-rw-r--r--src/core/lib/support/env.h60
-rw-r--r--src/core/lib/support/env_linux.c89
-rw-r--r--src/core/lib/support/env_posix.c57
-rw-r--r--src/core/lib/support/env_win32.c73
-rw-r--r--src/core/lib/support/histogram.c244
-rw-r--r--src/core/lib/support/host_port.c110
-rw-r--r--src/core/lib/support/load_file.c91
-rw-r--r--src/core/lib/support/load_file.h55
-rw-r--r--src/core/lib/support/log.c66
-rw-r--r--src/core/lib/support/log_android.c87
-rw-r--r--src/core/lib/support/log_linux.c106
-rw-r--r--src/core/lib/support/log_posix.c102
-rw-r--r--src/core/lib/support/log_win32.c126
-rw-r--r--src/core/lib/support/murmur_hash.c96
-rw-r--r--src/core/lib/support/murmur_hash.h44
-rw-r--r--src/core/lib/support/slice.c343
-rw-r--r--src/core/lib/support/slice_buffer.c282
-rw-r--r--src/core/lib/support/stack_lockfree.c185
-rw-r--r--src/core/lib/support/stack_lockfree.h53
-rw-r--r--src/core/lib/support/string.c296
-rw-r--r--src/core/lib/support/string.h121
-rw-r--r--src/core/lib/support/string_posix.c86
-rw-r--r--src/core/lib/support/string_win32.c109
-rw-r--r--src/core/lib/support/string_win32.h47
-rw-r--r--src/core/lib/support/subprocess_posix.c112
-rw-r--r--src/core/lib/support/subprocess_windows.c141
-rw-r--r--src/core/lib/support/sync.c127
-rw-r--r--src/core/lib/support/sync_posix.c104
-rw-r--r--src/core/lib/support/sync_win32.c133
-rw-r--r--src/core/lib/support/thd.c64
-rw-r--r--src/core/lib/support/thd_internal.h39
-rw-r--r--src/core/lib/support/thd_posix.c95
-rw-r--r--src/core/lib/support/thd_win32.c117
-rw-r--r--src/core/lib/support/time.c304
-rw-r--r--src/core/lib/support/time_posix.c170
-rw-r--r--src/core/lib/support/time_precise.c89
-rw-r--r--src/core/lib/support/time_precise.h42
-rw-r--r--src/core/lib/support/time_win32.c110
-rw-r--r--src/core/lib/support/tls_pthread.c45
-rw-r--r--src/core/lib/support/tmpfile.h55
-rw-r--r--src/core/lib/support/tmpfile_posix.c85
-rw-r--r--src/core/lib/support/tmpfile_win32.c84
-rw-r--r--src/core/lib/support/wrap_memcpy.c53
53 files changed, 6067 insertions, 0 deletions
diff --git a/src/core/lib/support/alloc.c b/src/core/lib/support/alloc.c
new file mode 100644
index 0000000000..618c3f6acd
--- /dev/null
+++ b/src/core/lib/support/alloc.c
@@ -0,0 +1,92 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/alloc.h>
+
+#include <grpc/support/log.h>
+#include <grpc/support/port_platform.h>
+#include <stdlib.h>
+#include "src/core/lib/profiling/timers.h"
+
+static gpr_allocation_functions g_alloc_functions = {malloc, realloc, free};
+
+gpr_allocation_functions gpr_get_allocation_functions() {
+ return g_alloc_functions;
+}
+
+void gpr_set_allocation_functions(gpr_allocation_functions functions) {
+ GPR_ASSERT(functions.malloc_fn != NULL);
+ GPR_ASSERT(functions.realloc_fn != NULL);
+ GPR_ASSERT(functions.free_fn != NULL);
+ g_alloc_functions = functions;
+}
+
+void *gpr_malloc(size_t size) {
+ void *p;
+ if (size == 0) return NULL;
+ GPR_TIMER_BEGIN("gpr_malloc", 0);
+ p = g_alloc_functions.malloc_fn(size);
+ if (!p) {
+ abort();
+ }
+ GPR_TIMER_END("gpr_malloc", 0);
+ return p;
+}
+
+void gpr_free(void *p) {
+ GPR_TIMER_BEGIN("gpr_free", 0);
+ g_alloc_functions.free_fn(p);
+ GPR_TIMER_END("gpr_free", 0);
+}
+
+void *gpr_realloc(void *p, size_t size) {
+ if ((size == 0) && (p == NULL)) return NULL;
+ GPR_TIMER_BEGIN("gpr_realloc", 0);
+ p = g_alloc_functions.realloc_fn(p, size);
+ if (!p) {
+ abort();
+ }
+ GPR_TIMER_END("gpr_realloc", 0);
+ return p;
+}
+
+void *gpr_malloc_aligned(size_t size, size_t alignment_log) {
+ size_t alignment = ((size_t)1) << alignment_log;
+ size_t extra = alignment - 1 + sizeof(void *);
+ void *p = gpr_malloc(size + extra);
+ void **ret = (void **)(((uintptr_t)p + extra) & ~(alignment - 1));
+ ret[-1] = p;
+ return (void *)ret;
+}
+
+void gpr_free_aligned(void *ptr) { gpr_free(((void **)ptr)[-1]); }
diff --git a/src/core/lib/support/avl.c b/src/core/lib/support/avl.c
new file mode 100644
index 0000000000..8d3ce23e6c
--- /dev/null
+++ b/src/core/lib/support/avl.c
@@ -0,0 +1,288 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/avl.h>
+
+#include <assert.h>
+#include <stdlib.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/useful.h>
+
+gpr_avl gpr_avl_create(const gpr_avl_vtable *vtable) {
+ gpr_avl out;
+ out.vtable = vtable;
+ out.root = NULL;
+ return out;
+}
+
+static gpr_avl_node *ref_node(gpr_avl_node *node) {
+ if (node) {
+ gpr_ref(&node->refs);
+ }
+ return node;
+}
+
+static void unref_node(const gpr_avl_vtable *vtable, gpr_avl_node *node) {
+ if (node == NULL) {
+ return;
+ }
+ if (gpr_unref(&node->refs)) {
+ vtable->destroy_key(node->key);
+ vtable->destroy_value(node->value);
+ unref_node(vtable, node->left);
+ unref_node(vtable, node->right);
+ gpr_free(node);
+ }
+}
+
+static long node_height(gpr_avl_node *node) {
+ return node == NULL ? 0 : node->height;
+}
+
+#ifndef NDEBUG
+static long calculate_height(gpr_avl_node *node) {
+ return node == NULL ? 0 : 1 + GPR_MAX(calculate_height(node->left),
+ calculate_height(node->right));
+}
+
+static gpr_avl_node *assert_invariants(gpr_avl_node *n) {
+ if (n == NULL) return NULL;
+ assert_invariants(n->left);
+ assert_invariants(n->right);
+ assert(calculate_height(n) == n->height);
+ assert(labs(node_height(n->left) - node_height(n->right)) <= 1);
+ return n;
+}
+#else
+static gpr_avl_node *assert_invariants(gpr_avl_node *n) { return n; }
+#endif
+
+gpr_avl_node *new_node(void *key, void *value, gpr_avl_node *left,
+ gpr_avl_node *right) {
+ gpr_avl_node *node = gpr_malloc(sizeof(*node));
+ gpr_ref_init(&node->refs, 1);
+ node->key = key;
+ node->value = value;
+ node->left = assert_invariants(left);
+ node->right = assert_invariants(right);
+ node->height = 1 + GPR_MAX(node_height(left), node_height(right));
+ return node;
+}
+
+static gpr_avl_node *get(const gpr_avl_vtable *vtable, gpr_avl_node *node,
+ void *key) {
+ long cmp;
+
+ if (node == NULL) {
+ return NULL;
+ }
+
+ cmp = vtable->compare_keys(node->key, key);
+ if (cmp == 0) {
+ return node;
+ } else if (cmp > 0) {
+ return get(vtable, node->left, key);
+ } else {
+ return get(vtable, node->right, key);
+ }
+}
+
+void *gpr_avl_get(gpr_avl avl, void *key) {
+ gpr_avl_node *node = get(avl.vtable, avl.root, key);
+ return node ? node->value : NULL;
+}
+
+static gpr_avl_node *rotate_left(const gpr_avl_vtable *vtable, void *key,
+ void *value, gpr_avl_node *left,
+ gpr_avl_node *right) {
+ gpr_avl_node *n =
+ new_node(vtable->copy_key(right->key), vtable->copy_value(right->value),
+ new_node(key, value, left, ref_node(right->left)),
+ ref_node(right->right));
+ unref_node(vtable, right);
+ return n;
+}
+
+static gpr_avl_node *rotate_right(const gpr_avl_vtable *vtable, void *key,
+ void *value, gpr_avl_node *left,
+ gpr_avl_node *right) {
+ gpr_avl_node *n = new_node(
+ vtable->copy_key(left->key), vtable->copy_value(left->value),
+ ref_node(left->left), new_node(key, value, ref_node(left->right), right));
+ unref_node(vtable, left);
+ return n;
+}
+
+static gpr_avl_node *rotate_left_right(const gpr_avl_vtable *vtable, void *key,
+ void *value, gpr_avl_node *left,
+ gpr_avl_node *right) {
+ /* rotate_right(..., rotate_left(left), right) */
+ gpr_avl_node *n = new_node(
+ vtable->copy_key(left->right->key),
+ vtable->copy_value(left->right->value),
+ new_node(vtable->copy_key(left->key), vtable->copy_value(left->value),
+ ref_node(left->left), ref_node(left->right->left)),
+ new_node(key, value, ref_node(left->right->right), right));
+ unref_node(vtable, left);
+ return n;
+}
+
+static gpr_avl_node *rotate_right_left(const gpr_avl_vtable *vtable, void *key,
+ void *value, gpr_avl_node *left,
+ gpr_avl_node *right) {
+ /* rotate_left(..., left, rotate_right(right)) */
+ gpr_avl_node *n = new_node(
+ vtable->copy_key(right->left->key),
+ vtable->copy_value(right->left->value),
+ new_node(key, value, left, ref_node(right->left->left)),
+ new_node(vtable->copy_key(right->key), vtable->copy_value(right->value),
+ ref_node(right->left->right), ref_node(right->right)));
+ unref_node(vtable, right);
+ return n;
+}
+
+static gpr_avl_node *rebalance(const gpr_avl_vtable *vtable, void *key,
+ void *value, gpr_avl_node *left,
+ gpr_avl_node *right) {
+ switch (node_height(left) - node_height(right)) {
+ case 2:
+ if (node_height(left->left) - node_height(left->right) == -1) {
+ return assert_invariants(
+ rotate_left_right(vtable, key, value, left, right));
+ } else {
+ return assert_invariants(rotate_right(vtable, key, value, left, right));
+ }
+ case -2:
+ if (node_height(right->left) - node_height(right->right) == 1) {
+ return assert_invariants(
+ rotate_right_left(vtable, key, value, left, right));
+ } else {
+ return assert_invariants(rotate_left(vtable, key, value, left, right));
+ }
+ default:
+ return assert_invariants(new_node(key, value, left, right));
+ }
+}
+
+static gpr_avl_node *add(const gpr_avl_vtable *vtable, gpr_avl_node *node,
+ void *key, void *value) {
+ long cmp;
+ if (node == NULL) {
+ return new_node(key, value, NULL, NULL);
+ }
+ cmp = vtable->compare_keys(node->key, key);
+ if (cmp == 0) {
+ return new_node(key, value, ref_node(node->left), ref_node(node->right));
+ } else if (cmp > 0) {
+ return rebalance(
+ vtable, vtable->copy_key(node->key), vtable->copy_value(node->value),
+ add(vtable, node->left, key, value), ref_node(node->right));
+ } else {
+ return rebalance(vtable, vtable->copy_key(node->key),
+ vtable->copy_value(node->value), ref_node(node->left),
+ add(vtable, node->right, key, value));
+ }
+}
+
+gpr_avl gpr_avl_add(gpr_avl avl, void *key, void *value) {
+ gpr_avl_node *old_root = avl.root;
+ avl.root = add(avl.vtable, avl.root, key, value);
+ assert_invariants(avl.root);
+ unref_node(avl.vtable, old_root);
+ return avl;
+}
+
+static gpr_avl_node *in_order_head(gpr_avl_node *node) {
+ while (node->left != NULL) {
+ node = node->left;
+ }
+ return node;
+}
+
+static gpr_avl_node *in_order_tail(gpr_avl_node *node) {
+ while (node->right != NULL) {
+ node = node->right;
+ }
+ return node;
+}
+
+static gpr_avl_node *remove(const gpr_avl_vtable *vtable, gpr_avl_node *node,
+ void *key) {
+ long cmp;
+ if (node == NULL) {
+ return NULL;
+ }
+ cmp = vtable->compare_keys(node->key, key);
+ if (cmp == 0) {
+ if (node->left == NULL) {
+ return ref_node(node->right);
+ } else if (node->right == NULL) {
+ return ref_node(node->left);
+ } else if (node->left->height < node->right->height) {
+ gpr_avl_node *h = in_order_head(node->right);
+ return rebalance(vtable, vtable->copy_key(h->key),
+ vtable->copy_value(h->value), ref_node(node->left),
+ remove(vtable, node->right, h->key));
+ } else {
+ gpr_avl_node *h = in_order_tail(node->left);
+ return rebalance(
+ vtable, vtable->copy_key(h->key), vtable->copy_value(h->value),
+ remove(vtable, node->left, h->key), ref_node(node->right));
+ }
+ } else if (cmp > 0) {
+ return rebalance(vtable, vtable->copy_key(node->key),
+ vtable->copy_value(node->value),
+ remove(vtable, node->left, key), ref_node(node->right));
+ } else {
+ return rebalance(vtable, vtable->copy_key(node->key),
+ vtable->copy_value(node->value), ref_node(node->left),
+ remove(vtable, node->right, key));
+ }
+}
+
+gpr_avl gpr_avl_remove(gpr_avl avl, void *key) {
+ gpr_avl_node *old_root = avl.root;
+ avl.root = remove(avl.vtable, avl.root, key);
+ assert_invariants(avl.root);
+ unref_node(avl.vtable, old_root);
+ return avl;
+}
+
+gpr_avl gpr_avl_ref(gpr_avl avl) {
+ ref_node(avl.root);
+ return avl;
+}
+
+void gpr_avl_unref(gpr_avl avl) { unref_node(avl.vtable, avl.root); }
diff --git a/src/core/lib/support/backoff.c b/src/core/lib/support/backoff.c
new file mode 100644
index 0000000000..e89ef47220
--- /dev/null
+++ b/src/core/lib/support/backoff.c
@@ -0,0 +1,76 @@
+/*
+ *
+ * Copyright 2016, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "src/core/lib/support/backoff.h"
+
+#include <grpc/support/useful.h>
+
+void gpr_backoff_init(gpr_backoff *backoff, double multiplier, double jitter,
+ int64_t min_timeout_millis, int64_t max_timeout_millis) {
+ backoff->multiplier = multiplier;
+ backoff->jitter = jitter;
+ backoff->min_timeout_millis = min_timeout_millis;
+ backoff->max_timeout_millis = max_timeout_millis;
+ backoff->rng_state = (uint32_t)gpr_now(GPR_CLOCK_REALTIME).tv_nsec;
+}
+
+gpr_timespec gpr_backoff_begin(gpr_backoff *backoff, gpr_timespec now) {
+ backoff->current_timeout_millis = backoff->min_timeout_millis;
+ return gpr_time_add(
+ now, gpr_time_from_millis(backoff->current_timeout_millis, GPR_TIMESPAN));
+}
+
+/* Generate a random number between 0 and 1. */
+static double generate_uniform_random_number(uint32_t *rng_state) {
+ *rng_state = (1103515245 * *rng_state + 12345) % ((uint32_t)1 << 31);
+ return *rng_state / (double)((uint32_t)1 << 31);
+}
+
+gpr_timespec gpr_backoff_step(gpr_backoff *backoff, gpr_timespec now) {
+ double new_timeout_millis =
+ backoff->multiplier * (double)backoff->current_timeout_millis;
+ double jitter_range = backoff->jitter * new_timeout_millis;
+ double jitter =
+ (2 * generate_uniform_random_number(&backoff->rng_state) - 1) *
+ jitter_range;
+ backoff->current_timeout_millis =
+ GPR_CLAMP((int64_t)(new_timeout_millis + jitter),
+ backoff->min_timeout_millis, backoff->max_timeout_millis);
+ return gpr_time_add(
+ now, gpr_time_from_millis(backoff->current_timeout_millis, GPR_TIMESPAN));
+}
+
+void gpr_backoff_reset(gpr_backoff *backoff) {
+ // forces step() to return a timeout of min_timeout_millis
+ backoff->current_timeout_millis = 0;
+}
diff --git a/src/core/lib/support/backoff.h b/src/core/lib/support/backoff.h
new file mode 100644
index 0000000000..6d40c15546
--- /dev/null
+++ b/src/core/lib/support/backoff.h
@@ -0,0 +1,68 @@
+/*
+ *
+ * Copyright 2016, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SUPPORT_BACKOFF_H
+#define GRPC_CORE_LIB_SUPPORT_BACKOFF_H
+
+#include <grpc/support/time.h>
+
+typedef struct {
+ /// const: multiplier between retry attempts
+ double multiplier;
+ /// const: amount to randomize backoffs
+ double jitter;
+ /// const: minimum time between retries in milliseconds
+ int64_t min_timeout_millis;
+ /// const: maximum time between retries in milliseconds
+ int64_t max_timeout_millis;
+
+ /// random number generator
+ uint32_t rng_state;
+
+ /// current retry timeout in milliseconds
+ int64_t current_timeout_millis;
+} gpr_backoff;
+
+/// Initialize backoff machinery - does not need to be destroyed
+void gpr_backoff_init(gpr_backoff *backoff, double multiplier, double jitter,
+ int64_t min_timeout_millis, int64_t max_timeout_millis);
+
+/// Begin retry loop: returns a timespec for the NEXT retry
+gpr_timespec gpr_backoff_begin(gpr_backoff *backoff, gpr_timespec now);
+/// Step a retry loop: returns a timespec for the NEXT retry
+gpr_timespec gpr_backoff_step(gpr_backoff *backoff, gpr_timespec now);
+/// Reset the backoff, so the next gpr_backoff_step will be a gpr_backoff_begin
+/// instead
+void gpr_backoff_reset(gpr_backoff *backoff);
+
+#endif /* GRPC_CORE_LIB_SUPPORT_BACKOFF_H */
diff --git a/src/core/lib/support/block_annotate.h b/src/core/lib/support/block_annotate.h
new file mode 100644
index 0000000000..8fb380241f
--- /dev/null
+++ b/src/core/lib/support/block_annotate.h
@@ -0,0 +1,48 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SUPPORT_BLOCK_ANNOTATE_H
+#define GRPC_CORE_LIB_SUPPORT_BLOCK_ANNOTATE_H
+
+/* These annotations identify the beginning and end of regions where
+ the code may block for reasons other than synchronization functions.
+ These include poll, epoll, and getaddrinfo. */
+
+#define GRPC_SCHEDULING_START_BLOCKING_REGION \
+ do { \
+ } while (0)
+#define GRPC_SCHEDULING_END_BLOCKING_REGION \
+ do { \
+ } while (0)
+
+#endif /* GRPC_CORE_LIB_SUPPORT_BLOCK_ANNOTATE_H */
diff --git a/src/core/lib/support/cmdline.c b/src/core/lib/support/cmdline.c
new file mode 100644
index 0000000000..d47498676d
--- /dev/null
+++ b/src/core/lib/support/cmdline.c
@@ -0,0 +1,347 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/cmdline.h>
+
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include "src/core/lib/support/string.h"
+
+typedef enum { ARGTYPE_INT, ARGTYPE_BOOL, ARGTYPE_STRING } argtype;
+
+typedef struct arg {
+ const char *name;
+ const char *help;
+ argtype type;
+ void *value;
+ struct arg *next;
+} arg;
+
+struct gpr_cmdline {
+ const char *description;
+ arg *args;
+ const char *argv0;
+
+ const char *extra_arg_name;
+ const char *extra_arg_help;
+ void (*extra_arg)(void *user_data, const char *arg);
+ void *extra_arg_user_data;
+
+ int (*state)(gpr_cmdline *cl, char *arg);
+ arg *cur_arg;
+
+ int survive_failure;
+};
+
+static int normal_state(gpr_cmdline *cl, char *arg);
+
+gpr_cmdline *gpr_cmdline_create(const char *description) {
+ gpr_cmdline *cl = gpr_malloc(sizeof(gpr_cmdline));
+ memset(cl, 0, sizeof(gpr_cmdline));
+
+ cl->description = description;
+ cl->state = normal_state;
+
+ return cl;
+}
+
+void gpr_cmdline_set_survive_failure(gpr_cmdline *cl) {
+ cl->survive_failure = 1;
+}
+
+void gpr_cmdline_destroy(gpr_cmdline *cl) {
+ while (cl->args) {
+ arg *a = cl->args;
+ cl->args = a->next;
+ gpr_free(a);
+ }
+ gpr_free(cl);
+}
+
+static void add_arg(gpr_cmdline *cl, const char *name, const char *help,
+ argtype type, void *value) {
+ arg *a;
+
+ for (a = cl->args; a; a = a->next) {
+ GPR_ASSERT(0 != strcmp(a->name, name));
+ }
+
+ a = gpr_malloc(sizeof(arg));
+ memset(a, 0, sizeof(arg));
+ a->name = name;
+ a->help = help;
+ a->type = type;
+ a->value = value;
+ a->next = cl->args;
+ cl->args = a;
+}
+
+void gpr_cmdline_add_int(gpr_cmdline *cl, const char *name, const char *help,
+ int *value) {
+ add_arg(cl, name, help, ARGTYPE_INT, value);
+}
+
+void gpr_cmdline_add_flag(gpr_cmdline *cl, const char *name, const char *help,
+ int *value) {
+ add_arg(cl, name, help, ARGTYPE_BOOL, value);
+}
+
+void gpr_cmdline_add_string(gpr_cmdline *cl, const char *name, const char *help,
+ char **value) {
+ add_arg(cl, name, help, ARGTYPE_STRING, value);
+}
+
+void gpr_cmdline_on_extra_arg(
+ gpr_cmdline *cl, const char *name, const char *help,
+ void (*on_extra_arg)(void *user_data, const char *arg), void *user_data) {
+ GPR_ASSERT(!cl->extra_arg);
+ GPR_ASSERT(on_extra_arg);
+
+ cl->extra_arg = on_extra_arg;
+ cl->extra_arg_user_data = user_data;
+ cl->extra_arg_name = name;
+ cl->extra_arg_help = help;
+}
+
+/* recursively descend argument list, adding the last element
+ to s first - so that arguments are added in the order they were
+ added to the list by api calls */
+static void add_args_to_usage(gpr_strvec *s, arg *a) {
+ char *tmp;
+
+ if (!a) return;
+ add_args_to_usage(s, a->next);
+
+ switch (a->type) {
+ case ARGTYPE_BOOL:
+ gpr_asprintf(&tmp, " [--%s|--no-%s]", a->name, a->name);
+ gpr_strvec_add(s, tmp);
+ break;
+ case ARGTYPE_STRING:
+ gpr_asprintf(&tmp, " [--%s=string]", a->name);
+ gpr_strvec_add(s, tmp);
+ break;
+ case ARGTYPE_INT:
+ gpr_asprintf(&tmp, " [--%s=int]", a->name);
+ gpr_strvec_add(s, tmp);
+ break;
+ }
+}
+
+char *gpr_cmdline_usage_string(gpr_cmdline *cl, const char *argv0) {
+ /* TODO(ctiller): make this prettier */
+ gpr_strvec s;
+ char *tmp;
+ const char *name = strrchr(argv0, '/');
+
+ if (name) {
+ name++;
+ } else {
+ name = argv0;
+ }
+
+ gpr_strvec_init(&s);
+
+ gpr_asprintf(&tmp, "Usage: %s", name);
+ gpr_strvec_add(&s, tmp);
+ add_args_to_usage(&s, cl->args);
+ if (cl->extra_arg) {
+ gpr_asprintf(&tmp, " [%s...]", cl->extra_arg_name);
+ gpr_strvec_add(&s, tmp);
+ }
+ gpr_strvec_add(&s, gpr_strdup("\n"));
+
+ tmp = gpr_strvec_flatten(&s, NULL);
+ gpr_strvec_destroy(&s);
+ return tmp;
+}
+
+static int print_usage_and_die(gpr_cmdline *cl) {
+ char *usage = gpr_cmdline_usage_string(cl, cl->argv0);
+ fprintf(stderr, "%s", usage);
+ gpr_free(usage);
+ if (!cl->survive_failure) {
+ exit(1);
+ }
+ return 0;
+}
+
+static int extra_state(gpr_cmdline *cl, char *str) {
+ if (!cl->extra_arg) {
+ return print_usage_and_die(cl);
+ }
+ cl->extra_arg(cl->extra_arg_user_data, str);
+ return 1;
+}
+
+static arg *find_arg(gpr_cmdline *cl, char *name) {
+ arg *a;
+
+ for (a = cl->args; a; a = a->next) {
+ if (0 == strcmp(a->name, name)) {
+ break;
+ }
+ }
+
+ if (!a) {
+ fprintf(stderr, "Unknown argument: %s\n", name);
+ return NULL;
+ }
+
+ return a;
+}
+
+static int value_state(gpr_cmdline *cl, char *str) {
+ long intval;
+ char *end;
+
+ GPR_ASSERT(cl->cur_arg);
+
+ switch (cl->cur_arg->type) {
+ case ARGTYPE_INT:
+ intval = strtol(str, &end, 0);
+ if (*end || intval < INT_MIN || intval > INT_MAX) {
+ fprintf(stderr, "expected integer, got '%s' for %s\n", str,
+ cl->cur_arg->name);
+ return print_usage_and_die(cl);
+ }
+ *(int *)cl->cur_arg->value = (int)intval;
+ break;
+ case ARGTYPE_BOOL:
+ if (0 == strcmp(str, "1") || 0 == strcmp(str, "true")) {
+ *(int *)cl->cur_arg->value = 1;
+ } else if (0 == strcmp(str, "0") || 0 == strcmp(str, "false")) {
+ *(int *)cl->cur_arg->value = 0;
+ } else {
+ fprintf(stderr, "expected boolean, got '%s' for %s\n", str,
+ cl->cur_arg->name);
+ return print_usage_and_die(cl);
+ }
+ break;
+ case ARGTYPE_STRING:
+ *(char **)cl->cur_arg->value = str;
+ break;
+ }
+
+ cl->state = normal_state;
+ return 1;
+}
+
+static int normal_state(gpr_cmdline *cl, char *str) {
+ char *eq = NULL;
+ char *tmp = NULL;
+ char *arg_name = NULL;
+ int r = 1;
+
+ if (0 == strcmp(str, "-help") || 0 == strcmp(str, "--help") ||
+ 0 == strcmp(str, "-h")) {
+ return print_usage_and_die(cl);
+ }
+
+ cl->cur_arg = NULL;
+
+ if (str[0] == '-') {
+ if (str[1] == '-') {
+ if (str[2] == 0) {
+ /* handle '--' to move to just extra args */
+ cl->state = extra_state;
+ return 1;
+ }
+ str += 2;
+ } else {
+ str += 1;
+ }
+ /* first byte of str is now past the leading '-' or '--' */
+ if (str[0] == 'n' && str[1] == 'o' && str[2] == '-') {
+ /* str is of the form '--no-foo' - it's a flag disable */
+ str += 3;
+ cl->cur_arg = find_arg(cl, str);
+ if (cl->cur_arg == NULL) {
+ return print_usage_and_die(cl);
+ }
+ if (cl->cur_arg->type != ARGTYPE_BOOL) {
+ fprintf(stderr, "%s is not a flag argument\n", str);
+ return print_usage_and_die(cl);
+ }
+ *(int *)cl->cur_arg->value = 0;
+ return 1; /* early out */
+ }
+ eq = strchr(str, '=');
+ if (eq != NULL) {
+ /* copy the string into a temp buffer and extract the name */
+ tmp = arg_name = gpr_malloc((size_t)(eq - str + 1));
+ memcpy(arg_name, str, (size_t)(eq - str));
+ arg_name[eq - str] = 0;
+ } else {
+ arg_name = str;
+ }
+ cl->cur_arg = find_arg(cl, arg_name);
+ if (cl->cur_arg == NULL) {
+ return print_usage_and_die(cl);
+ }
+ if (eq != NULL) {
+ /* str was of the type --foo=value, parse the value */
+ r = value_state(cl, eq + 1);
+ } else if (cl->cur_arg->type != ARGTYPE_BOOL) {
+ /* flag types don't have a '--foo value' variant, other types do */
+ cl->state = value_state;
+ } else {
+ /* flag parameter: just set the value */
+ *(int *)cl->cur_arg->value = 1;
+ }
+ } else {
+ r = extra_state(cl, str);
+ }
+
+ gpr_free(tmp);
+ return r;
+}
+
+int gpr_cmdline_parse(gpr_cmdline *cl, int argc, char **argv) {
+ int i;
+
+ GPR_ASSERT(argc >= 1);
+ cl->argv0 = argv[0];
+
+ for (i = 1; i < argc; i++) {
+ if (!cl->state(cl, argv[i])) {
+ return 0;
+ }
+ }
+ return 1;
+}
diff --git a/src/core/lib/support/cpu_iphone.c b/src/core/lib/support/cpu_iphone.c
new file mode 100644
index 0000000000..82b49b47bc
--- /dev/null
+++ b/src/core/lib/support/cpu_iphone.c
@@ -0,0 +1,49 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_CPU_IPHONE
+
+/* Probably 2 instead of 1, but see comment on gpr_cpu_current_cpu. */
+unsigned gpr_cpu_num_cores(void) { return 1; }
+
+/* Most code that's using this is using it to shard across work queues. So
+ unless profiling shows it's a problem or there appears a way to detect the
+ currently running CPU core, let's have it shard the default way.
+ Note that the interface in cpu.h lets gpr_cpu_num_cores return 0, but doing
+ it makes it impossible for gpr_cpu_current_cpu to satisfy its stated range,
+ and some code might be relying on it. */
+unsigned gpr_cpu_current_cpu(void) { return 0; }
+
+#endif /* GPR_CPU_IPHONE */
diff --git a/src/core/lib/support/cpu_linux.c b/src/core/lib/support/cpu_linux.c
new file mode 100644
index 0000000000..d6f7e7d3da
--- /dev/null
+++ b/src/core/lib/support/cpu_linux.c
@@ -0,0 +1,78 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif /* _GNU_SOURCE */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_CPU_LINUX
+
+#include <errno.h>
+#include <sched.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <grpc/support/cpu.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+static int ncpus = 0;
+
+static void init_num_cpus() {
+ /* This must be signed. sysconf returns -1 when the number cannot be
+ determined */
+ ncpus = (int)sysconf(_SC_NPROCESSORS_ONLN);
+ if (ncpus < 1) {
+ gpr_log(GPR_ERROR, "Cannot determine number of CPUs: assuming 1");
+ ncpus = 1;
+ }
+}
+
+unsigned gpr_cpu_num_cores(void) {
+ static gpr_once once = GPR_ONCE_INIT;
+ gpr_once_init(&once, init_num_cpus);
+ return (unsigned)ncpus;
+}
+
+unsigned gpr_cpu_current_cpu(void) {
+ int cpu = sched_getcpu();
+ if (cpu < 0) {
+ gpr_log(GPR_ERROR, "Error determining current CPU: %s\n", strerror(errno));
+ return 0;
+ }
+ return (unsigned)cpu;
+}
+
+#endif /* GPR_CPU_LINUX */
diff --git a/src/core/lib/support/cpu_posix.c b/src/core/lib/support/cpu_posix.c
new file mode 100644
index 0000000000..667bde7cad
--- /dev/null
+++ b/src/core/lib/support/cpu_posix.c
@@ -0,0 +1,77 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_CPU_POSIX
+
+#include <errno.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+static __thread char magic_thread_local;
+
+static long ncpus = 0;
+
+static void init_ncpus() {
+ ncpus = sysconf(_SC_NPROCESSORS_ONLN);
+ if (ncpus < 1 || ncpus > INT32_MAX) {
+ gpr_log(GPR_ERROR, "Cannot determine number of CPUs: assuming 1");
+ ncpus = 1;
+ }
+}
+
+unsigned gpr_cpu_num_cores(void) {
+ static gpr_once once = GPR_ONCE_INIT;
+ gpr_once_init(&once, init_ncpus);
+ return (unsigned)ncpus;
+}
+
+/* This is a cheap, but good enough, pointer hash for sharding things: */
+static size_t shard_ptr(const void *info) {
+ size_t x = (size_t)info;
+ return ((x >> 4) ^ (x >> 9) ^ (x >> 14)) % gpr_cpu_num_cores();
+}
+
+unsigned gpr_cpu_current_cpu(void) {
+ /* NOTE: there's no way I know to return the actual cpu index portably...
+ most code that's using this is using it to shard across work queues though,
+ so here we use thread identity instead to achieve a similar though not
+ identical effect */
+ return (unsigned)shard_ptr(&magic_thread_local);
+}
+
+#endif /* GPR_CPU_POSIX */
diff --git a/src/core/lib/support/cpu_windows.c b/src/core/lib/support/cpu_windows.c
new file mode 100644
index 0000000000..ce32eb0a9d
--- /dev/null
+++ b/src/core/lib/support/cpu_windows.c
@@ -0,0 +1,47 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WIN32
+#include <grpc/support/log.h>
+
+unsigned gpr_cpu_num_cores(void) {
+ SYSTEM_INFO si;
+ GetSystemInfo(&si);
+ return si.dwNumberOfProcessors;
+}
+
+unsigned gpr_cpu_current_cpu(void) { return GetCurrentProcessorNumber(); }
+
+#endif /* GPR_WIN32 */
diff --git a/src/core/lib/support/env.h b/src/core/lib/support/env.h
new file mode 100644
index 0000000000..ec3959bc6e
--- /dev/null
+++ b/src/core/lib/support/env.h
@@ -0,0 +1,60 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SUPPORT_ENV_H
+#define GRPC_CORE_LIB_SUPPORT_ENV_H
+
+#include <stdio.h>
+
+#include <grpc/support/slice.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Env utility functions */
+
+/* Gets the environment variable value with the specified name.
+ Returns a newly allocated string. It is the responsability of the caller to
+ gpr_free the return value if not NULL (which means that the environment
+ variable exists). */
+char *gpr_getenv(const char *name);
+
+/* Sets the the environment with the specified name to the specified value. */
+void gpr_setenv(const char *name, const char *value);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* GRPC_CORE_LIB_SUPPORT_ENV_H */
diff --git a/src/core/lib/support/env_linux.c b/src/core/lib/support/env_linux.c
new file mode 100644
index 0000000000..2436eb20b0
--- /dev/null
+++ b/src/core/lib/support/env_linux.c
@@ -0,0 +1,89 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* for secure_getenv. */
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_LINUX_ENV
+
+#include "src/core/lib/support/env.h"
+
+#include <dlfcn.h>
+#include <features.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/useful.h>
+
+#include "src/core/lib/support/string.h"
+
+char *gpr_getenv(const char *name) {
+#if defined(GPR_BACKWARDS_COMPATIBILITY_MODE)
+ typedef char *(*getenv_type)(const char *);
+ static getenv_type getenv_func = NULL;
+ /* Check to see which getenv variant is supported (go from most
+ * to least secure) */
+ const char *names[] = {"secure_getenv", "__secure_getenv", "getenv"};
+ for (size_t i = 0; getenv_func == NULL && i < GPR_ARRAY_SIZE(names); i++) {
+ getenv_func = (getenv_type)dlsym(RTLD_DEFAULT, names[i]);
+ if (getenv_func != NULL && strstr(names[i], "secure") == NULL) {
+ gpr_log(GPR_DEBUG,
+ "Warning: insecure environment read function '%s' used",
+ names[i]);
+ }
+ }
+ char *result = getenv_func(name);
+ return result == NULL ? result : gpr_strdup(result);
+#elif __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17)
+ char *result = secure_getenv(name);
+ return result == NULL ? result : gpr_strdup(result);
+#else
+ gpr_log(GPR_DEBUG, "Warning: insecure environment read function '%s' used",
+ "getenv");
+ char *result = getenv(name);
+ return result == NULL ? result : gpr_strdup(result);
+#endif
+}
+
+void gpr_setenv(const char *name, const char *value) {
+ int res = setenv(name, value, 1);
+ GPR_ASSERT(res == 0);
+}
+
+#endif /* GPR_LINUX_ENV */
diff --git a/src/core/lib/support/env_posix.c b/src/core/lib/support/env_posix.c
new file mode 100644
index 0000000000..ff47630443
--- /dev/null
+++ b/src/core/lib/support/env_posix.c
@@ -0,0 +1,57 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_POSIX_ENV
+
+#include "src/core/lib/support/env.h"
+
+#include <stdlib.h>
+
+#include <grpc/support/log.h>
+
+#include <grpc/support/string_util.h>
+#include "src/core/lib/support/string.h"
+
+char *gpr_getenv(const char *name) {
+ char *result = getenv(name);
+ return result == NULL ? result : gpr_strdup(result);
+}
+
+void gpr_setenv(const char *name, const char *value) {
+ int res = setenv(name, value, 1);
+ GPR_ASSERT(res == 0);
+}
+
+#endif /* GPR_POSIX_ENV */
diff --git a/src/core/lib/support/env_win32.c b/src/core/lib/support/env_win32.c
new file mode 100644
index 0000000000..ef84c941df
--- /dev/null
+++ b/src/core/lib/support/env_win32.c
@@ -0,0 +1,73 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WIN32
+
+#include "src/core/lib/support/env.h"
+#include "src/core/lib/support/string.h"
+
+#ifdef __MINGW32__
+errno_t getenv_s(size_t *size_needed, char *buffer, size_t size,
+ const char *varname);
+#else
+#include <stdlib.h>
+#endif
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+char *gpr_getenv(const char *name) {
+ size_t size;
+ char *result = NULL;
+ errno_t err;
+
+ err = getenv_s(&size, NULL, 0, name);
+ if (err || (size == 0)) return NULL;
+ result = gpr_malloc(size);
+ err = getenv_s(&size, result, size, name);
+ if (err) {
+ gpr_free(result);
+ return NULL;
+ }
+ return result;
+}
+
+void gpr_setenv(const char *name, const char *value) {
+ errno_t res = _putenv_s(name, value);
+ GPR_ASSERT(res == 0);
+}
+
+#endif /* GPR_WIN32 */
diff --git a/src/core/lib/support/histogram.c b/src/core/lib/support/histogram.c
new file mode 100644
index 0000000000..7b016bbc78
--- /dev/null
+++ b/src/core/lib/support/histogram.c
@@ -0,0 +1,244 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/histogram.h>
+
+#include <math.h>
+#include <stddef.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/port_platform.h>
+#include <grpc/support/useful.h>
+
+/* Histograms are stored with exponentially increasing bucket sizes.
+ The first bucket is [0, m) where m = 1 + resolution
+ Bucket n (n>=1) contains [m**n, m**(n+1))
+ There are sufficient buckets to reach max_bucket_start */
+
+struct gpr_histogram {
+ /* Sum of all values seen so far */
+ double sum;
+ /* Sum of squares of all values seen so far */
+ double sum_of_squares;
+ /* number of values seen so far */
+ double count;
+ /* m in the description */
+ double multiplier;
+ double one_on_log_multiplier;
+ /* minimum value seen */
+ double min_seen;
+ /* maximum value seen */
+ double max_seen;
+ /* maximum representable value */
+ double max_possible;
+ /* number of buckets */
+ size_t num_buckets;
+ /* the buckets themselves */
+ uint32_t *buckets;
+};
+
+/* determine a bucket index given a value - does no bounds checking */
+static size_t bucket_for_unchecked(gpr_histogram *h, double x) {
+ return (size_t)(log(x) * h->one_on_log_multiplier);
+}
+
+/* bounds checked version of the above */
+static size_t bucket_for(gpr_histogram *h, double x) {
+ size_t bucket = bucket_for_unchecked(h, GPR_CLAMP(x, 1.0, h->max_possible));
+ GPR_ASSERT(bucket < h->num_buckets);
+ return bucket;
+}
+
+/* at what value does a bucket start? */
+static double bucket_start(gpr_histogram *h, double x) {
+ return pow(h->multiplier, x);
+}
+
+gpr_histogram *gpr_histogram_create(double resolution,
+ double max_bucket_start) {
+ gpr_histogram *h = gpr_malloc(sizeof(gpr_histogram));
+ GPR_ASSERT(resolution > 0.0);
+ GPR_ASSERT(max_bucket_start > resolution);
+ h->sum = 0.0;
+ h->sum_of_squares = 0.0;
+ h->multiplier = 1.0 + resolution;
+ h->one_on_log_multiplier = 1.0 / log(1.0 + resolution);
+ h->max_possible = max_bucket_start;
+ h->count = 0.0;
+ h->min_seen = max_bucket_start;
+ h->max_seen = 0.0;
+ h->num_buckets = bucket_for_unchecked(h, max_bucket_start) + 1;
+ GPR_ASSERT(h->num_buckets > 1);
+ GPR_ASSERT(h->num_buckets < 100000000);
+ h->buckets = gpr_malloc(sizeof(uint32_t) * h->num_buckets);
+ memset(h->buckets, 0, sizeof(uint32_t) * h->num_buckets);
+ return h;
+}
+
+void gpr_histogram_destroy(gpr_histogram *h) {
+ gpr_free(h->buckets);
+ gpr_free(h);
+}
+
+void gpr_histogram_add(gpr_histogram *h, double x) {
+ h->sum += x;
+ h->sum_of_squares += x * x;
+ h->count++;
+ if (x < h->min_seen) {
+ h->min_seen = x;
+ }
+ if (x > h->max_seen) {
+ h->max_seen = x;
+ }
+ h->buckets[bucket_for(h, x)]++;
+}
+
+int gpr_histogram_merge(gpr_histogram *dst, const gpr_histogram *src) {
+ if ((dst->num_buckets != src->num_buckets) ||
+ (dst->multiplier != src->multiplier)) {
+ /* Fail because these histograms don't match */
+ return 0;
+ }
+ gpr_histogram_merge_contents(dst, src->buckets, src->num_buckets,
+ src->min_seen, src->max_seen, src->sum,
+ src->sum_of_squares, src->count);
+ return 1;
+}
+
+void gpr_histogram_merge_contents(gpr_histogram *dst, const uint32_t *data,
+ size_t data_count, double min_seen,
+ double max_seen, double sum,
+ double sum_of_squares, double count) {
+ size_t i;
+ GPR_ASSERT(dst->num_buckets == data_count);
+ dst->sum += sum;
+ dst->sum_of_squares += sum_of_squares;
+ dst->count += count;
+ if (min_seen < dst->min_seen) {
+ dst->min_seen = min_seen;
+ }
+ if (max_seen > dst->max_seen) {
+ dst->max_seen = max_seen;
+ }
+ for (i = 0; i < dst->num_buckets; i++) {
+ dst->buckets[i] += data[i];
+ }
+}
+
+static double threshold_for_count_below(gpr_histogram *h, double count_below) {
+ double count_so_far;
+ double lower_bound;
+ double upper_bound;
+ size_t lower_idx;
+ size_t upper_idx;
+
+ if (h->count == 0) {
+ return 0.0;
+ }
+
+ if (count_below <= 0) {
+ return h->min_seen;
+ }
+ if (count_below >= h->count) {
+ return h->max_seen;
+ }
+
+ /* find the lowest bucket that gets us above count_below */
+ count_so_far = 0.0;
+ for (lower_idx = 0; lower_idx < h->num_buckets; lower_idx++) {
+ count_so_far += h->buckets[lower_idx];
+ if (count_so_far >= count_below) {
+ break;
+ }
+ }
+ if (count_so_far == count_below) {
+ /* this bucket hits the threshold exactly... we should be midway through
+ any run of zero values following the bucket */
+ for (upper_idx = lower_idx + 1; upper_idx < h->num_buckets; upper_idx++) {
+ if (h->buckets[upper_idx]) {
+ break;
+ }
+ }
+ return (bucket_start(h, (double)lower_idx) +
+ bucket_start(h, (double)upper_idx)) /
+ 2.0;
+ } else {
+ /* treat values as uniform throughout the bucket, and find where this value
+ should lie */
+ lower_bound = bucket_start(h, (double)lower_idx);
+ upper_bound = bucket_start(h, (double)(lower_idx + 1));
+ return GPR_CLAMP(upper_bound -
+ (upper_bound - lower_bound) *
+ (count_so_far - count_below) /
+ h->buckets[lower_idx],
+ h->min_seen, h->max_seen);
+ }
+}
+
+double gpr_histogram_percentile(gpr_histogram *h, double percentile) {
+ return threshold_for_count_below(h, h->count * percentile / 100.0);
+}
+
+double gpr_histogram_mean(gpr_histogram *h) {
+ GPR_ASSERT(h->count != 0);
+ return h->sum / h->count;
+}
+
+double gpr_histogram_stddev(gpr_histogram *h) {
+ return sqrt(gpr_histogram_variance(h));
+}
+
+double gpr_histogram_variance(gpr_histogram *h) {
+ if (h->count == 0) return 0.0;
+ return (h->sum_of_squares * h->count - h->sum * h->sum) /
+ (h->count * h->count);
+}
+
+double gpr_histogram_maximum(gpr_histogram *h) { return h->max_seen; }
+
+double gpr_histogram_minimum(gpr_histogram *h) { return h->min_seen; }
+
+double gpr_histogram_count(gpr_histogram *h) { return h->count; }
+
+double gpr_histogram_sum(gpr_histogram *h) { return h->sum; }
+
+double gpr_histogram_sum_of_squares(gpr_histogram *h) {
+ return h->sum_of_squares;
+}
+
+const uint32_t *gpr_histogram_get_contents(gpr_histogram *h, size_t *size) {
+ *size = h->num_buckets;
+ return h->buckets;
+}
diff --git a/src/core/lib/support/host_port.c b/src/core/lib/support/host_port.c
new file mode 100644
index 0000000000..f19bdbc835
--- /dev/null
+++ b/src/core/lib/support/host_port.c
@@ -0,0 +1,110 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/host_port.h>
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include "src/core/lib/support/string.h"
+
+int gpr_join_host_port(char **out, const char *host, int port) {
+ if (host[0] != '[' && strchr(host, ':') != NULL) {
+ /* IPv6 literals must be enclosed in brackets. */
+ return gpr_asprintf(out, "[%s]:%d", host, port);
+ } else {
+ /* Ordinary non-bracketed host:port. */
+ return gpr_asprintf(out, "%s:%d", host, port);
+ }
+}
+
+int gpr_split_host_port(const char *name, char **host, char **port) {
+ const char *host_start;
+ size_t host_len;
+ const char *port_start;
+
+ *host = NULL;
+ *port = NULL;
+
+ if (name[0] == '[') {
+ /* Parse a bracketed host, typically an IPv6 literal. */
+ const char *rbracket = strchr(name, ']');
+ if (rbracket == NULL) {
+ /* Unmatched [ */
+ return 0;
+ }
+ if (rbracket[1] == '\0') {
+ /* ]<end> */
+ port_start = NULL;
+ } else if (rbracket[1] == ':') {
+ /* ]:<port?> */
+ port_start = rbracket + 2;
+ } else {
+ /* ]<invalid> */
+ return 0;
+ }
+ host_start = name + 1;
+ host_len = (size_t)(rbracket - host_start);
+ if (memchr(host_start, ':', host_len) == NULL) {
+ /* Require all bracketed hosts to contain a colon, because a hostname or
+ IPv4 address should never use brackets. */
+ return 0;
+ }
+ } else {
+ const char *colon = strchr(name, ':');
+ if (colon != NULL && strchr(colon + 1, ':') == NULL) {
+ /* Exactly 1 colon. Split into host:port. */
+ host_start = name;
+ host_len = (size_t)(colon - name);
+ port_start = colon + 1;
+ } else {
+ /* 0 or 2+ colons. Bare hostname or IPv6 litearal. */
+ host_start = name;
+ host_len = strlen(name);
+ port_start = NULL;
+ }
+ }
+
+ /* Allocate return values. */
+ *host = gpr_malloc(host_len + 1);
+ memcpy(*host, host_start, host_len);
+ (*host)[host_len] = '\0';
+
+ if (port_start != NULL) {
+ *port = gpr_strdup(port_start);
+ }
+
+ return 1;
+}
diff --git a/src/core/lib/support/load_file.c b/src/core/lib/support/load_file.c
new file mode 100644
index 0000000000..f30aacdd4f
--- /dev/null
+++ b/src/core/lib/support/load_file.c
@@ -0,0 +1,91 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "src/core/lib/support/load_file.h"
+
+#include <errno.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/support/block_annotate.h"
+#include "src/core/lib/support/string.h"
+
+gpr_slice gpr_load_file(const char *filename, int add_null_terminator,
+ int *success) {
+ unsigned char *contents = NULL;
+ size_t contents_size = 0;
+ char *error_msg = NULL;
+ gpr_slice result = gpr_empty_slice();
+ FILE *file;
+ size_t bytes_read = 0;
+
+ GRPC_SCHEDULING_START_BLOCKING_REGION;
+ file = fopen(filename, "rb");
+ if (file == NULL) {
+ gpr_asprintf(&error_msg, "Could not open file %s (error = %s).", filename,
+ strerror(errno));
+ GPR_ASSERT(error_msg != NULL);
+ goto end;
+ }
+ fseek(file, 0, SEEK_END);
+ /* Converting to size_t on the assumption that it will not fail */
+ contents_size = (size_t)ftell(file);
+ fseek(file, 0, SEEK_SET);
+ contents = gpr_malloc(contents_size + (add_null_terminator ? 1 : 0));
+ bytes_read = fread(contents, 1, contents_size, file);
+ if (bytes_read < contents_size) {
+ GPR_ASSERT(ferror(file));
+ gpr_asprintf(&error_msg, "Error %s occured while reading file %s.",
+ strerror(errno), filename);
+ GPR_ASSERT(error_msg != NULL);
+ goto end;
+ }
+ if (success != NULL) *success = 1;
+ if (add_null_terminator) {
+ contents[contents_size++] = 0;
+ }
+ result = gpr_slice_new(contents, contents_size, gpr_free);
+
+end:
+ if (error_msg != NULL) {
+ gpr_log(GPR_ERROR, "%s", error_msg);
+ gpr_free(error_msg);
+ if (success != NULL) *success = 0;
+ }
+ if (file != NULL) fclose(file);
+ GRPC_SCHEDULING_END_BLOCKING_REGION;
+ return result;
+}
diff --git a/src/core/lib/support/load_file.h b/src/core/lib/support/load_file.h
new file mode 100644
index 0000000000..9a4b27942e
--- /dev/null
+++ b/src/core/lib/support/load_file.h
@@ -0,0 +1,55 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SUPPORT_LOAD_FILE_H
+#define GRPC_CORE_LIB_SUPPORT_LOAD_FILE_H
+
+#include <stdio.h>
+
+#include <grpc/support/slice.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Loads the content of a file into a slice. add_null_terminator will add
+ a NULL terminator if non-zero. The success parameter, if not NULL,
+ will be set to 1 in case of success and 0 in case of failure. */
+gpr_slice gpr_load_file(const char *filename, int add_null_terminator,
+ int *success);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* GRPC_CORE_LIB_SUPPORT_LOAD_FILE_H */
diff --git a/src/core/lib/support/log.c b/src/core/lib/support/log.c
new file mode 100644
index 0000000000..04156a5b1f
--- /dev/null
+++ b/src/core/lib/support/log.c
@@ -0,0 +1,66 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/log.h>
+#include <grpc/support/port_platform.h>
+
+#include <stdio.h>
+#include <string.h>
+
+extern void gpr_default_log(gpr_log_func_args *args);
+static gpr_log_func g_log_func = gpr_default_log;
+
+const char *gpr_log_severity_string(gpr_log_severity severity) {
+ switch (severity) {
+ case GPR_LOG_SEVERITY_DEBUG:
+ return "D";
+ case GPR_LOG_SEVERITY_INFO:
+ return "I";
+ case GPR_LOG_SEVERITY_ERROR:
+ return "E";
+ }
+ GPR_UNREACHABLE_CODE(return "UNKNOWN");
+}
+
+void gpr_log_message(const char *file, int line, gpr_log_severity severity,
+ const char *message) {
+ gpr_log_func_args lfargs;
+ memset(&lfargs, 0, sizeof(lfargs));
+ lfargs.file = file;
+ lfargs.line = line;
+ lfargs.severity = severity;
+ lfargs.message = message;
+ g_log_func(&lfargs);
+}
+
+void gpr_set_log_function(gpr_log_func f) { g_log_func = f; }
diff --git a/src/core/lib/support/log_android.c b/src/core/lib/support/log_android.c
new file mode 100644
index 0000000000..94c8100fd7
--- /dev/null
+++ b/src/core/lib/support/log_android.c
@@ -0,0 +1,87 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_ANDROID
+
+#include <android/log.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+static android_LogPriority severity_to_log_priority(gpr_log_severity severity) {
+ switch (severity) {
+ case GPR_LOG_SEVERITY_DEBUG:
+ return ANDROID_LOG_DEBUG;
+ case GPR_LOG_SEVERITY_INFO:
+ return ANDROID_LOG_INFO;
+ case GPR_LOG_SEVERITY_ERROR:
+ return ANDROID_LOG_ERROR;
+ }
+ return ANDROID_LOG_DEFAULT;
+}
+
+void gpr_log(const char *file, int line, gpr_log_severity severity,
+ const char *format, ...) {
+ char *message = NULL;
+ va_list args;
+ va_start(args, format);
+ vasprintf(&message, format, args);
+ va_end(args);
+ gpr_log_message(file, line, severity, message);
+ free(message);
+}
+
+void gpr_default_log(gpr_log_func_args *args) {
+ char *final_slash;
+ const char *display_file;
+ char *output = NULL;
+
+ final_slash = strrchr(args->file, '/');
+ if (final_slash == NULL)
+ display_file = args->file;
+ else
+ display_file = final_slash + 1;
+
+ asprintf(&output, "%s:%d] %s", display_file, args->line, args->message);
+
+ __android_log_write(severity_to_log_priority(args->severity), "GRPC", output);
+
+ /* allocated by asprintf => use free, not gpr_free */
+ free(output);
+}
+
+#endif /* GPR_ANDROID */
diff --git a/src/core/lib/support/log_linux.c b/src/core/lib/support/log_linux.c
new file mode 100644
index 0000000000..ff3febb38e
--- /dev/null
+++ b/src/core/lib/support/log_linux.c
@@ -0,0 +1,106 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef _POSIX_SOURCE
+#define _POSIX_SOURCE
+#endif
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_LINUX
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/time.h>
+#include <linux/unistd.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/syscall.h>
+#include <time.h>
+#include <unistd.h>
+
+static long gettid(void) { return syscall(__NR_gettid); }
+
+void gpr_log(const char *file, int line, gpr_log_severity severity,
+ const char *format, ...) {
+ char *message = NULL;
+ va_list args;
+ va_start(args, format);
+ if (vasprintf(&message, format, args) == -1) {
+ va_end(args);
+ return;
+ }
+ va_end(args);
+ gpr_log_message(file, line, severity, message);
+ /* message has been allocated by vasprintf above, and needs free */
+ free(message);
+}
+
+void gpr_default_log(gpr_log_func_args *args) {
+ char *final_slash;
+ char *prefix;
+ const char *display_file;
+ char time_buffer[64];
+ time_t timer;
+ gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
+ struct tm tm;
+
+ timer = (time_t)now.tv_sec;
+ final_slash = strrchr(args->file, '/');
+ if (final_slash == NULL)
+ display_file = args->file;
+ else
+ display_file = final_slash + 1;
+
+ if (!localtime_r(&timer, &tm)) {
+ strcpy(time_buffer, "error:localtime");
+ } else if (0 ==
+ strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) {
+ strcpy(time_buffer, "error:strftime");
+ }
+
+ gpr_asprintf(&prefix, "%s%s.%09d %7tu %s:%d]",
+ gpr_log_severity_string(args->severity), time_buffer,
+ (int)(now.tv_nsec), gettid(), display_file, args->line);
+
+ fprintf(stderr, "%-60s %s\n", prefix, args->message);
+ gpr_free(prefix);
+}
+
+#endif
diff --git a/src/core/lib/support/log_posix.c b/src/core/lib/support/log_posix.c
new file mode 100644
index 0000000000..6ae6320767
--- /dev/null
+++ b/src/core/lib/support/log_posix.c
@@ -0,0 +1,102 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#if defined(GPR_POSIX_LOG)
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <pthread.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+
+static intptr_t gettid(void) { return (intptr_t)pthread_self(); }
+
+void gpr_log(const char *file, int line, gpr_log_severity severity,
+ const char *format, ...) {
+ char buf[64];
+ char *allocated = NULL;
+ char *message = NULL;
+ int ret;
+ va_list args;
+ va_start(args, format);
+ ret = vsnprintf(buf, sizeof(buf), format, args);
+ va_end(args);
+ if (ret < 0) {
+ message = NULL;
+ } else if ((size_t)ret <= sizeof(buf) - 1) {
+ message = buf;
+ } else {
+ message = allocated = gpr_malloc((size_t)ret + 1);
+ va_start(args, format);
+ vsnprintf(message, (size_t)(ret + 1), format, args);
+ va_end(args);
+ }
+ gpr_log_message(file, line, severity, message);
+ gpr_free(allocated);
+}
+
+void gpr_default_log(gpr_log_func_args *args) {
+ char *final_slash;
+ const char *display_file;
+ char time_buffer[64];
+ time_t timer;
+ gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
+ struct tm tm;
+
+ timer = (time_t)now.tv_sec;
+ final_slash = strrchr(args->file, '/');
+ if (final_slash == NULL)
+ display_file = args->file;
+ else
+ display_file = final_slash + 1;
+
+ if (!localtime_r(&timer, &tm)) {
+ strcpy(time_buffer, "error:localtime");
+ } else if (0 ==
+ strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) {
+ strcpy(time_buffer, "error:strftime");
+ }
+
+ fprintf(stderr, "%s%s.%09d %7tu %s:%d] %s\n",
+ gpr_log_severity_string(args->severity), time_buffer,
+ (int)(now.tv_nsec), gettid(), display_file, args->line,
+ args->message);
+}
+
+#endif /* defined(GPR_POSIX_LOG) */
diff --git a/src/core/lib/support/log_win32.c b/src/core/lib/support/log_win32.c
new file mode 100644
index 0000000000..ba78497a0a
--- /dev/null
+++ b/src/core/lib/support/log_win32.c
@@ -0,0 +1,126 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WIN32
+
+#include <stdarg.h>
+#include <stdio.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/log_win32.h>
+#include <grpc/support/string_util.h>
+#include <grpc/support/time.h>
+
+#include "src/core/lib/support/string.h"
+#include "src/core/lib/support/string_win32.h"
+
+void gpr_log(const char *file, int line, gpr_log_severity severity,
+ const char *format, ...) {
+ char *message = NULL;
+ va_list args;
+ int ret;
+
+ /* Determine the length. */
+ va_start(args, format);
+ ret = _vscprintf(format, args);
+ va_end(args);
+ if (ret < 0) {
+ message = NULL;
+ } else {
+ /* Allocate a new buffer, with space for the NUL terminator. */
+ size_t strp_buflen = (size_t)ret + 1;
+ message = gpr_malloc(strp_buflen);
+
+ /* Print to the buffer. */
+ va_start(args, format);
+ ret = vsnprintf_s(message, strp_buflen, _TRUNCATE, format, args);
+ va_end(args);
+ if ((size_t)ret != strp_buflen - 1) {
+ /* This should never happen. */
+ gpr_free(message);
+ message = NULL;
+ }
+ }
+
+ gpr_log_message(file, line, severity, message);
+ gpr_free(message);
+}
+
+/* Simple starter implementation */
+void gpr_default_log(gpr_log_func_args *args) {
+ char *final_slash;
+ const char *display_file;
+ char time_buffer[64];
+ time_t timer;
+ gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME);
+ struct tm tm;
+
+ timer = (time_t)now.tv_sec;
+ final_slash = strrchr(args->file, '\\');
+ if (final_slash == NULL)
+ display_file = args->file;
+ else
+ display_file = final_slash + 1;
+
+ if (localtime_s(&tm, &timer)) {
+ strcpy(time_buffer, "error:localtime");
+ } else if (0 ==
+ strftime(time_buffer, sizeof(time_buffer), "%m%d %H:%M:%S", &tm)) {
+ strcpy(time_buffer, "error:strftime");
+ }
+
+ fprintf(stderr, "%s%s.%09u %5lu %s:%d] %s\n",
+ gpr_log_severity_string(args->severity), time_buffer,
+ (int)(now.tv_nsec), GetCurrentThreadId(), display_file, args->line,
+ args->message);
+ fflush(stderr);
+}
+
+char *gpr_format_message(int messageid) {
+ LPTSTR tmessage;
+ char *message;
+ DWORD status = FormatMessage(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, (DWORD)messageid, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPTSTR)(&tmessage), 0, NULL);
+ if (status == 0) return gpr_strdup("Unable to retrieve error string");
+ message = gpr_tchar_to_char(tmessage);
+ LocalFree(tmessage);
+ return message;
+}
+
+#endif /* GPR_WIN32 */
diff --git a/src/core/lib/support/murmur_hash.c b/src/core/lib/support/murmur_hash.c
new file mode 100644
index 0000000000..5711fff0c0
--- /dev/null
+++ b/src/core/lib/support/murmur_hash.c
@@ -0,0 +1,96 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "src/core/lib/support/murmur_hash.h"
+
+#define ROTL32(x, r) ((x) << (r)) | ((x) >> (32 - (r)))
+
+#define FMIX32(h) \
+ (h) ^= (h) >> 16; \
+ (h) *= 0x85ebca6b; \
+ (h) ^= (h) >> 13; \
+ (h) *= 0xc2b2ae35; \
+ (h) ^= (h) >> 16;
+
+/* Block read - if your platform needs to do endian-swapping or can only
+ handle aligned reads, do the conversion here */
+#define GETBLOCK32(p, i) (p)[(i)]
+
+uint32_t gpr_murmur_hash3(const void *key, size_t len, uint32_t seed) {
+ const uint8_t *data = (const uint8_t *)key;
+ const size_t nblocks = len / 4;
+ int i;
+
+ uint32_t h1 = seed;
+ uint32_t k1;
+
+ const uint32_t c1 = 0xcc9e2d51;
+ const uint32_t c2 = 0x1b873593;
+
+ const uint32_t *blocks = ((const uint32_t *)key) + nblocks;
+ const uint8_t *tail = (const uint8_t *)(data + nblocks * 4);
+
+ /* body */
+ for (i = -(int)nblocks; i; i++) {
+ k1 = GETBLOCK32(blocks, i);
+
+ k1 *= c1;
+ k1 = ROTL32(k1, 15);
+ k1 *= c2;
+
+ h1 ^= k1;
+ h1 = ROTL32(h1, 13);
+ h1 = h1 * 5 + 0xe6546b64;
+ }
+
+ k1 = 0;
+
+ /* tail */
+ switch (len & 3) {
+ case 3:
+ k1 ^= ((uint32_t)tail[2]) << 16;
+ case 2:
+ k1 ^= ((uint32_t)tail[1]) << 8;
+ case 1:
+ k1 ^= tail[0];
+ k1 *= c1;
+ k1 = ROTL32(k1, 15);
+ k1 *= c2;
+ h1 ^= k1;
+ };
+
+ /* finalization */
+ h1 ^= (uint32_t)len;
+ FMIX32(h1);
+ return h1;
+}
diff --git a/src/core/lib/support/murmur_hash.h b/src/core/lib/support/murmur_hash.h
new file mode 100644
index 0000000000..6d282ff358
--- /dev/null
+++ b/src/core/lib/support/murmur_hash.h
@@ -0,0 +1,44 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SUPPORT_MURMUR_HASH_H
+#define GRPC_CORE_LIB_SUPPORT_MURMUR_HASH_H
+
+#include <grpc/support/port_platform.h>
+
+#include <stddef.h>
+
+/* compute the hash of key (length len) */
+uint32_t gpr_murmur_hash3(const void *key, size_t len, uint32_t seed);
+
+#endif /* GRPC_CORE_LIB_SUPPORT_MURMUR_HASH_H */
diff --git a/src/core/lib/support/slice.c b/src/core/lib/support/slice.c
new file mode 100644
index 0000000000..b9a7c77bda
--- /dev/null
+++ b/src/core/lib/support/slice.c
@@ -0,0 +1,343 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/slice.h>
+
+#include <string.h>
+
+gpr_slice gpr_empty_slice(void) {
+ gpr_slice out;
+ out.refcount = 0;
+ out.data.inlined.length = 0;
+ return out;
+}
+
+gpr_slice gpr_slice_ref(gpr_slice slice) {
+ if (slice.refcount) {
+ slice.refcount->ref(slice.refcount);
+ }
+ return slice;
+}
+
+void gpr_slice_unref(gpr_slice slice) {
+ if (slice.refcount) {
+ slice.refcount->unref(slice.refcount);
+ }
+}
+
+/* gpr_slice_from_static_string support structure - a refcount that does
+ nothing */
+static void noop_ref_or_unref(void *unused) {}
+
+static gpr_slice_refcount noop_refcount = {noop_ref_or_unref,
+ noop_ref_or_unref};
+
+gpr_slice gpr_slice_from_static_string(const char *s) {
+ gpr_slice slice;
+ slice.refcount = &noop_refcount;
+ slice.data.refcounted.bytes = (uint8_t *)s;
+ slice.data.refcounted.length = strlen(s);
+ return slice;
+}
+
+/* gpr_slice_new support structures - we create a refcount object extended
+ with the user provided data pointer & destroy function */
+typedef struct new_slice_refcount {
+ gpr_slice_refcount rc;
+ gpr_refcount refs;
+ void (*user_destroy)(void *);
+ void *user_data;
+} new_slice_refcount;
+
+static void new_slice_ref(void *p) {
+ new_slice_refcount *r = p;
+ gpr_ref(&r->refs);
+}
+
+static void new_slice_unref(void *p) {
+ new_slice_refcount *r = p;
+ if (gpr_unref(&r->refs)) {
+ r->user_destroy(r->user_data);
+ gpr_free(r);
+ }
+}
+
+gpr_slice gpr_slice_new(void *p, size_t len, void (*destroy)(void *)) {
+ gpr_slice slice;
+ new_slice_refcount *rc = gpr_malloc(sizeof(new_slice_refcount));
+ gpr_ref_init(&rc->refs, 1);
+ rc->rc.ref = new_slice_ref;
+ rc->rc.unref = new_slice_unref;
+ rc->user_destroy = destroy;
+ rc->user_data = p;
+
+ slice.refcount = &rc->rc;
+ slice.data.refcounted.bytes = p;
+ slice.data.refcounted.length = len;
+ return slice;
+}
+
+/* gpr_slice_new_with_len support structures - we create a refcount object
+ extended with the user provided data pointer & destroy function */
+typedef struct new_with_len_slice_refcount {
+ gpr_slice_refcount rc;
+ gpr_refcount refs;
+ void *user_data;
+ size_t user_length;
+ void (*user_destroy)(void *, size_t);
+} new_with_len_slice_refcount;
+
+static void new_with_len_ref(void *p) {
+ new_with_len_slice_refcount *r = p;
+ gpr_ref(&r->refs);
+}
+
+static void new_with_len_unref(void *p) {
+ new_with_len_slice_refcount *r = p;
+ if (gpr_unref(&r->refs)) {
+ r->user_destroy(r->user_data, r->user_length);
+ gpr_free(r);
+ }
+}
+
+gpr_slice gpr_slice_new_with_len(void *p, size_t len,
+ void (*destroy)(void *, size_t)) {
+ gpr_slice slice;
+ new_with_len_slice_refcount *rc =
+ gpr_malloc(sizeof(new_with_len_slice_refcount));
+ gpr_ref_init(&rc->refs, 1);
+ rc->rc.ref = new_with_len_ref;
+ rc->rc.unref = new_with_len_unref;
+ rc->user_destroy = destroy;
+ rc->user_data = p;
+ rc->user_length = len;
+
+ slice.refcount = &rc->rc;
+ slice.data.refcounted.bytes = p;
+ slice.data.refcounted.length = len;
+ return slice;
+}
+
+gpr_slice gpr_slice_from_copied_buffer(const char *source, size_t length) {
+ gpr_slice slice = gpr_slice_malloc(length);
+ memcpy(GPR_SLICE_START_PTR(slice), source, length);
+ return slice;
+}
+
+gpr_slice gpr_slice_from_copied_string(const char *source) {
+ return gpr_slice_from_copied_buffer(source, strlen(source));
+}
+
+typedef struct {
+ gpr_slice_refcount base;
+ gpr_refcount refs;
+} malloc_refcount;
+
+static void malloc_ref(void *p) {
+ malloc_refcount *r = p;
+ gpr_ref(&r->refs);
+}
+
+static void malloc_unref(void *p) {
+ malloc_refcount *r = p;
+ if (gpr_unref(&r->refs)) {
+ gpr_free(r);
+ }
+}
+
+gpr_slice gpr_slice_malloc(size_t length) {
+ gpr_slice slice;
+
+ if (length > sizeof(slice.data.inlined.bytes)) {
+ /* Memory layout used by the slice created here:
+
+ +-----------+----------------------------------------------------------+
+ | refcount | bytes |
+ +-----------+----------------------------------------------------------+
+
+ refcount is a malloc_refcount
+ bytes is an array of bytes of the requested length
+ Both parts are placed in the same allocation returned from gpr_malloc */
+ malloc_refcount *rc = gpr_malloc(sizeof(malloc_refcount) + length);
+
+ /* Initial refcount on rc is 1 - and it's up to the caller to release
+ this reference. */
+ gpr_ref_init(&rc->refs, 1);
+
+ rc->base.ref = malloc_ref;
+ rc->base.unref = malloc_unref;
+
+ /* Build up the slice to be returned. */
+ /* The slices refcount points back to the allocated block. */
+ slice.refcount = &rc->base;
+ /* The data bytes are placed immediately after the refcount struct */
+ slice.data.refcounted.bytes = (uint8_t *)(rc + 1);
+ /* And the length of the block is set to the requested length */
+ slice.data.refcounted.length = length;
+ } else {
+ /* small slice: just inline the data */
+ slice.refcount = NULL;
+ slice.data.inlined.length = (uint8_t)length;
+ }
+ return slice;
+}
+
+gpr_slice gpr_slice_sub_no_ref(gpr_slice source, size_t begin, size_t end) {
+ gpr_slice subset;
+
+ GPR_ASSERT(end >= begin);
+
+ if (source.refcount) {
+ /* Enforce preconditions */
+ GPR_ASSERT(source.data.refcounted.length >= end);
+
+ /* Build the result */
+ subset.refcount = source.refcount;
+ /* Point into the source array */
+ subset.data.refcounted.bytes = source.data.refcounted.bytes + begin;
+ subset.data.refcounted.length = end - begin;
+ } else {
+ /* Enforce preconditions */
+ GPR_ASSERT(source.data.inlined.length >= end);
+ subset.refcount = NULL;
+ subset.data.inlined.length = (uint8_t)(end - begin);
+ memcpy(subset.data.inlined.bytes, source.data.inlined.bytes + begin,
+ end - begin);
+ }
+ return subset;
+}
+
+gpr_slice gpr_slice_sub(gpr_slice source, size_t begin, size_t end) {
+ gpr_slice subset;
+
+ if (end - begin <= sizeof(subset.data.inlined.bytes)) {
+ subset.refcount = NULL;
+ subset.data.inlined.length = (uint8_t)(end - begin);
+ memcpy(subset.data.inlined.bytes, GPR_SLICE_START_PTR(source) + begin,
+ end - begin);
+ } else {
+ subset = gpr_slice_sub_no_ref(source, begin, end);
+ /* Bump the refcount */
+ subset.refcount->ref(subset.refcount);
+ }
+ return subset;
+}
+
+gpr_slice gpr_slice_split_tail(gpr_slice *source, size_t split) {
+ gpr_slice tail;
+
+ if (source->refcount == NULL) {
+ /* inlined data, copy it out */
+ GPR_ASSERT(source->data.inlined.length >= split);
+ tail.refcount = NULL;
+ tail.data.inlined.length = (uint8_t)(source->data.inlined.length - split);
+ memcpy(tail.data.inlined.bytes, source->data.inlined.bytes + split,
+ tail.data.inlined.length);
+ source->data.inlined.length = (uint8_t)split;
+ } else {
+ size_t tail_length = source->data.refcounted.length - split;
+ GPR_ASSERT(source->data.refcounted.length >= split);
+ if (tail_length < sizeof(tail.data.inlined.bytes)) {
+ /* Copy out the bytes - it'll be cheaper than refcounting */
+ tail.refcount = NULL;
+ tail.data.inlined.length = (uint8_t)tail_length;
+ memcpy(tail.data.inlined.bytes, source->data.refcounted.bytes + split,
+ tail_length);
+ } else {
+ /* Build the result */
+ tail.refcount = source->refcount;
+ /* Bump the refcount */
+ tail.refcount->ref(tail.refcount);
+ /* Point into the source array */
+ tail.data.refcounted.bytes = source->data.refcounted.bytes + split;
+ tail.data.refcounted.length = tail_length;
+ }
+ source->data.refcounted.length = split;
+ }
+
+ return tail;
+}
+
+gpr_slice gpr_slice_split_head(gpr_slice *source, size_t split) {
+ gpr_slice head;
+
+ if (source->refcount == NULL) {
+ GPR_ASSERT(source->data.inlined.length >= split);
+
+ head.refcount = NULL;
+ head.data.inlined.length = (uint8_t)split;
+ memcpy(head.data.inlined.bytes, source->data.inlined.bytes, split);
+ source->data.inlined.length =
+ (uint8_t)(source->data.inlined.length - split);
+ memmove(source->data.inlined.bytes, source->data.inlined.bytes + split,
+ source->data.inlined.length);
+ } else if (split < sizeof(head.data.inlined.bytes)) {
+ GPR_ASSERT(source->data.refcounted.length >= split);
+
+ head.refcount = NULL;
+ head.data.inlined.length = (uint8_t)split;
+ memcpy(head.data.inlined.bytes, source->data.refcounted.bytes, split);
+ source->data.refcounted.bytes += split;
+ source->data.refcounted.length -= split;
+ } else {
+ GPR_ASSERT(source->data.refcounted.length >= split);
+
+ /* Build the result */
+ head.refcount = source->refcount;
+ /* Bump the refcount */
+ head.refcount->ref(head.refcount);
+ /* Point into the source array */
+ head.data.refcounted.bytes = source->data.refcounted.bytes;
+ head.data.refcounted.length = split;
+ source->data.refcounted.bytes += split;
+ source->data.refcounted.length -= split;
+ }
+
+ return head;
+}
+
+int gpr_slice_cmp(gpr_slice a, gpr_slice b) {
+ int d = (int)(GPR_SLICE_LENGTH(a) - GPR_SLICE_LENGTH(b));
+ if (d != 0) return d;
+ return memcmp(GPR_SLICE_START_PTR(a), GPR_SLICE_START_PTR(b),
+ GPR_SLICE_LENGTH(a));
+}
+
+int gpr_slice_str_cmp(gpr_slice a, const char *b) {
+ size_t b_length = strlen(b);
+ int d = (int)(GPR_SLICE_LENGTH(a) - b_length);
+ if (d != 0) return d;
+ return memcmp(GPR_SLICE_START_PTR(a), b, b_length);
+}
diff --git a/src/core/lib/support/slice_buffer.c b/src/core/lib/support/slice_buffer.c
new file mode 100644
index 0000000000..66f111d767
--- /dev/null
+++ b/src/core/lib/support/slice_buffer.c
@@ -0,0 +1,282 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+#include <grpc/support/slice_buffer.h>
+
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/useful.h>
+
+/* grow a buffer; requires GRPC_SLICE_BUFFER_INLINE_ELEMENTS > 1 */
+#define GROW(x) (3 * (x) / 2)
+
+static void maybe_embiggen(gpr_slice_buffer *sb) {
+ if (sb->count == sb->capacity) {
+ sb->capacity = GROW(sb->capacity);
+ GPR_ASSERT(sb->capacity > sb->count);
+ if (sb->slices == sb->inlined) {
+ sb->slices = gpr_malloc(sb->capacity * sizeof(gpr_slice));
+ memcpy(sb->slices, sb->inlined, sb->count * sizeof(gpr_slice));
+ } else {
+ sb->slices = gpr_realloc(sb->slices, sb->capacity * sizeof(gpr_slice));
+ }
+ }
+}
+
+void gpr_slice_buffer_init(gpr_slice_buffer *sb) {
+ sb->count = 0;
+ sb->length = 0;
+ sb->capacity = GRPC_SLICE_BUFFER_INLINE_ELEMENTS;
+ sb->slices = sb->inlined;
+}
+
+void gpr_slice_buffer_destroy(gpr_slice_buffer *sb) {
+ gpr_slice_buffer_reset_and_unref(sb);
+ if (sb->slices != sb->inlined) {
+ gpr_free(sb->slices);
+ }
+}
+
+uint8_t *gpr_slice_buffer_tiny_add(gpr_slice_buffer *sb, size_t n) {
+ gpr_slice *back;
+ uint8_t *out;
+
+ sb->length += n;
+
+ if (sb->count == 0) goto add_new;
+ back = &sb->slices[sb->count - 1];
+ if (back->refcount) goto add_new;
+ if ((back->data.inlined.length + n) > sizeof(back->data.inlined.bytes))
+ goto add_new;
+ out = back->data.inlined.bytes + back->data.inlined.length;
+ back->data.inlined.length = (uint8_t)(back->data.inlined.length + n);
+ return out;
+
+add_new:
+ maybe_embiggen(sb);
+ back = &sb->slices[sb->count];
+ sb->count++;
+ back->refcount = NULL;
+ back->data.inlined.length = (uint8_t)n;
+ return back->data.inlined.bytes;
+}
+
+size_t gpr_slice_buffer_add_indexed(gpr_slice_buffer *sb, gpr_slice s) {
+ size_t out = sb->count;
+ maybe_embiggen(sb);
+ sb->slices[out] = s;
+ sb->length += GPR_SLICE_LENGTH(s);
+ sb->count = out + 1;
+ return out;
+}
+
+void gpr_slice_buffer_add(gpr_slice_buffer *sb, gpr_slice s) {
+ size_t n = sb->count;
+ /* if both the last slice in the slice buffer and the slice being added
+ are inlined (that is, that they carry their data inside the slice data
+ structure), and the back slice is not full, then concatenate directly
+ into the back slice, preventing many small slices being passed into
+ writes */
+ if (!s.refcount && n) {
+ gpr_slice *back = &sb->slices[n - 1];
+ if (!back->refcount && back->data.inlined.length < GPR_SLICE_INLINED_SIZE) {
+ if (s.data.inlined.length + back->data.inlined.length <=
+ GPR_SLICE_INLINED_SIZE) {
+ memcpy(back->data.inlined.bytes + back->data.inlined.length,
+ s.data.inlined.bytes, s.data.inlined.length);
+ back->data.inlined.length =
+ (uint8_t)(back->data.inlined.length + s.data.inlined.length);
+ } else {
+ size_t cp1 = GPR_SLICE_INLINED_SIZE - back->data.inlined.length;
+ memcpy(back->data.inlined.bytes + back->data.inlined.length,
+ s.data.inlined.bytes, cp1);
+ back->data.inlined.length = GPR_SLICE_INLINED_SIZE;
+ maybe_embiggen(sb);
+ back = &sb->slices[n];
+ sb->count = n + 1;
+ back->refcount = NULL;
+ back->data.inlined.length = (uint8_t)(s.data.inlined.length - cp1);
+ memcpy(back->data.inlined.bytes, s.data.inlined.bytes + cp1,
+ s.data.inlined.length - cp1);
+ }
+ sb->length += s.data.inlined.length;
+ return; /* early out */
+ }
+ }
+ gpr_slice_buffer_add_indexed(sb, s);
+}
+
+void gpr_slice_buffer_addn(gpr_slice_buffer *sb, gpr_slice *s, size_t n) {
+ size_t i;
+ for (i = 0; i < n; i++) {
+ gpr_slice_buffer_add(sb, s[i]);
+ }
+}
+
+void gpr_slice_buffer_pop(gpr_slice_buffer *sb) {
+ if (sb->count != 0) {
+ size_t count = --sb->count;
+ sb->length -= GPR_SLICE_LENGTH(sb->slices[count]);
+ }
+}
+
+void gpr_slice_buffer_reset_and_unref(gpr_slice_buffer *sb) {
+ size_t i;
+
+ for (i = 0; i < sb->count; i++) {
+ gpr_slice_unref(sb->slices[i]);
+ }
+
+ sb->count = 0;
+ sb->length = 0;
+}
+
+void gpr_slice_buffer_swap(gpr_slice_buffer *a, gpr_slice_buffer *b) {
+ GPR_SWAP(size_t, a->count, b->count);
+ GPR_SWAP(size_t, a->capacity, b->capacity);
+ GPR_SWAP(size_t, a->length, b->length);
+
+ if (a->slices == a->inlined) {
+ if (b->slices == b->inlined) {
+ /* swap contents of inlined buffer */
+ gpr_slice temp[GRPC_SLICE_BUFFER_INLINE_ELEMENTS];
+ memcpy(temp, a->slices, b->count * sizeof(gpr_slice));
+ memcpy(a->slices, b->slices, a->count * sizeof(gpr_slice));
+ memcpy(b->slices, temp, b->count * sizeof(gpr_slice));
+ } else {
+ /* a is inlined, b is not - copy a inlined into b, fix pointers */
+ a->slices = b->slices;
+ b->slices = b->inlined;
+ memcpy(b->slices, a->inlined, b->count * sizeof(gpr_slice));
+ }
+ } else if (b->slices == b->inlined) {
+ /* b is inlined, a is not - copy b inlined int a, fix pointers */
+ b->slices = a->slices;
+ a->slices = a->inlined;
+ memcpy(a->slices, b->inlined, a->count * sizeof(gpr_slice));
+ } else {
+ /* no inlining: easy swap */
+ GPR_SWAP(gpr_slice *, a->slices, b->slices);
+ }
+}
+
+void gpr_slice_buffer_move_into(gpr_slice_buffer *src, gpr_slice_buffer *dst) {
+ /* anything to move? */
+ if (src->count == 0) {
+ return;
+ }
+ /* anything in dst? */
+ if (dst->count == 0) {
+ gpr_slice_buffer_swap(src, dst);
+ return;
+ }
+ /* both buffers have data - copy, and reset src */
+ gpr_slice_buffer_addn(dst, src->slices, src->count);
+ src->count = 0;
+ src->length = 0;
+}
+
+void gpr_slice_buffer_move_first(gpr_slice_buffer *src, size_t n,
+ gpr_slice_buffer *dst) {
+ size_t src_idx;
+ size_t output_len = dst->length + n;
+ size_t new_input_len = src->length - n;
+ GPR_ASSERT(src->length >= n);
+ if (src->length == n) {
+ gpr_slice_buffer_move_into(src, dst);
+ return;
+ }
+ src_idx = 0;
+ while (src_idx < src->capacity) {
+ gpr_slice slice = src->slices[src_idx];
+ size_t slice_len = GPR_SLICE_LENGTH(slice);
+ if (n > slice_len) {
+ gpr_slice_buffer_add(dst, slice);
+ n -= slice_len;
+ src_idx++;
+ } else if (n == slice_len) {
+ gpr_slice_buffer_add(dst, slice);
+ src_idx++;
+ break;
+ } else { /* n < slice_len */
+ src->slices[src_idx] = gpr_slice_split_tail(&slice, n);
+ GPR_ASSERT(GPR_SLICE_LENGTH(slice) == n);
+ GPR_ASSERT(GPR_SLICE_LENGTH(src->slices[src_idx]) == slice_len - n);
+ gpr_slice_buffer_add(dst, slice);
+ break;
+ }
+ }
+ GPR_ASSERT(dst->length == output_len);
+ memmove(src->slices, src->slices + src_idx,
+ sizeof(gpr_slice) * (src->count - src_idx));
+ src->count -= src_idx;
+ src->length = new_input_len;
+ GPR_ASSERT(src->count > 0);
+}
+
+void gpr_slice_buffer_trim_end(gpr_slice_buffer *sb, size_t n,
+ gpr_slice_buffer *garbage) {
+ GPR_ASSERT(n <= sb->length);
+ sb->length -= n;
+ for (;;) {
+ size_t idx = sb->count - 1;
+ gpr_slice slice = sb->slices[idx];
+ size_t slice_len = GPR_SLICE_LENGTH(slice);
+ if (slice_len > n) {
+ sb->slices[idx] = gpr_slice_split_head(&slice, slice_len - n);
+ gpr_slice_buffer_add_indexed(garbage, slice);
+ return;
+ } else if (slice_len == n) {
+ gpr_slice_buffer_add_indexed(garbage, slice);
+ sb->count = idx;
+ return;
+ } else {
+ gpr_slice_buffer_add_indexed(garbage, slice);
+ n -= slice_len;
+ sb->count = idx;
+ }
+ }
+}
+
+gpr_slice gpr_slice_buffer_take_first(gpr_slice_buffer *sb) {
+ gpr_slice slice;
+ GPR_ASSERT(sb->count > 0);
+ slice = sb->slices[0];
+ memmove(&sb->slices[0], &sb->slices[1], (sb->count - 1) * sizeof(gpr_slice));
+ sb->count--;
+ sb->length -= GPR_SLICE_LENGTH(slice);
+ return slice;
+}
diff --git a/src/core/lib/support/stack_lockfree.c b/src/core/lib/support/stack_lockfree.c
new file mode 100644
index 0000000000..9d7c9e5a38
--- /dev/null
+++ b/src/core/lib/support/stack_lockfree.c
@@ -0,0 +1,185 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "src/core/lib/support/stack_lockfree.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/atm.h>
+#include <grpc/support/log.h>
+#include <grpc/support/port_platform.h>
+
+/* The lockfree node structure is a single architecture-level
+ word that allows for an atomic CAS to set it up. */
+struct lockfree_node_contents {
+ /* next thing to look at. Actual index for head, next index otherwise */
+ uint16_t index;
+#ifdef GPR_ARCH_64
+ uint16_t pad;
+ uint32_t aba_ctr;
+#else
+#ifdef GPR_ARCH_32
+ uint16_t aba_ctr;
+#else
+#error Unsupported bit width architecture
+#endif
+#endif
+};
+
+/* Use a union to make sure that these are in the same bits as an atm word */
+typedef union lockfree_node {
+ gpr_atm atm;
+ struct lockfree_node_contents contents;
+} lockfree_node;
+
+/* make sure that entries aligned to 8-bytes */
+#define ENTRY_ALIGNMENT_BITS 3
+/* reserve this entry as invalid */
+#define INVALID_ENTRY_INDEX ((1 << 16) - 1)
+
+struct gpr_stack_lockfree {
+ lockfree_node *entries;
+ lockfree_node head; /* An atomic entry describing curr head */
+
+#ifndef NDEBUG
+ /* Bitmap of pushed entries to check for double-push or pop */
+ gpr_atm pushed[(INVALID_ENTRY_INDEX + 1) / (8 * sizeof(gpr_atm))];
+#endif
+};
+
+gpr_stack_lockfree *gpr_stack_lockfree_create(size_t entries) {
+ gpr_stack_lockfree *stack;
+ stack = gpr_malloc(sizeof(*stack));
+ /* Since we only allocate 16 bits to represent an entry number,
+ * make sure that we are within the desired range */
+ /* Reserve the highest entry number as a dummy */
+ GPR_ASSERT(entries < INVALID_ENTRY_INDEX);
+ stack->entries = gpr_malloc_aligned(entries * sizeof(stack->entries[0]),
+ ENTRY_ALIGNMENT_BITS);
+ /* Clear out all entries */
+ memset(stack->entries, 0, entries * sizeof(stack->entries[0]));
+ memset(&stack->head, 0, sizeof(stack->head));
+#ifndef NDEBUG
+ memset(&stack->pushed, 0, sizeof(stack->pushed));
+#endif
+
+ GPR_ASSERT(sizeof(stack->entries->atm) == sizeof(stack->entries->contents));
+
+ /* Point the head at reserved dummy entry */
+ stack->head.contents.index = INVALID_ENTRY_INDEX;
+/* Fill in the pad and aba_ctr to avoid confusing memcheck tools */
+#ifdef GPR_ARCH_64
+ stack->head.contents.pad = 0;
+#endif
+ stack->head.contents.aba_ctr = 0;
+ return stack;
+}
+
+void gpr_stack_lockfree_destroy(gpr_stack_lockfree *stack) {
+ gpr_free_aligned(stack->entries);
+ gpr_free(stack);
+}
+
+int gpr_stack_lockfree_push(gpr_stack_lockfree *stack, int entry) {
+ lockfree_node head;
+ lockfree_node newhead;
+ lockfree_node curent;
+ lockfree_node newent;
+
+ /* First fill in the entry's index and aba ctr for new head */
+ newhead.contents.index = (uint16_t)entry;
+#ifdef GPR_ARCH_64
+ /* Fill in the pad to avoid confusing memcheck tools */
+ newhead.contents.pad = 0;
+#endif
+
+ /* Also post-increment the aba_ctr */
+ curent.atm = gpr_atm_no_barrier_load(&stack->entries[entry].atm);
+ newhead.contents.aba_ctr = ++curent.contents.aba_ctr;
+ gpr_atm_no_barrier_store(&stack->entries[entry].atm, curent.atm);
+
+#ifndef NDEBUG
+ /* Check for double push */
+ {
+ int pushed_index = entry / (int)(8 * sizeof(gpr_atm));
+ int pushed_bit = entry % (int)(8 * sizeof(gpr_atm));
+ gpr_atm old_val;
+
+ old_val = gpr_atm_no_barrier_fetch_add(&stack->pushed[pushed_index],
+ ((gpr_atm)1 << pushed_bit));
+ GPR_ASSERT((old_val & (((gpr_atm)1) << pushed_bit)) == 0);
+ }
+#endif
+
+ do {
+ /* Atomically get the existing head value for use */
+ head.atm = gpr_atm_no_barrier_load(&(stack->head.atm));
+ /* Point to it */
+ newent.atm = gpr_atm_no_barrier_load(&stack->entries[entry].atm);
+ newent.contents.index = head.contents.index;
+ gpr_atm_no_barrier_store(&stack->entries[entry].atm, newent.atm);
+ } while (!gpr_atm_rel_cas(&(stack->head.atm), head.atm, newhead.atm));
+ /* Use rel_cas above to make sure that entry index is set properly */
+ return head.contents.index == INVALID_ENTRY_INDEX;
+}
+
+int gpr_stack_lockfree_pop(gpr_stack_lockfree *stack) {
+ lockfree_node head;
+ lockfree_node newhead;
+
+ do {
+ head.atm = gpr_atm_acq_load(&(stack->head.atm));
+ if (head.contents.index == INVALID_ENTRY_INDEX) {
+ return -1;
+ }
+ newhead.atm =
+ gpr_atm_no_barrier_load(&(stack->entries[head.contents.index].atm));
+
+ } while (!gpr_atm_no_barrier_cas(&(stack->head.atm), head.atm, newhead.atm));
+#ifndef NDEBUG
+ /* Check for valid pop */
+ {
+ int pushed_index = head.contents.index / (8 * sizeof(gpr_atm));
+ int pushed_bit = head.contents.index % (8 * sizeof(gpr_atm));
+ gpr_atm old_val;
+
+ old_val = gpr_atm_no_barrier_fetch_add(&stack->pushed[pushed_index],
+ -((gpr_atm)1 << pushed_bit));
+ GPR_ASSERT((old_val & (((gpr_atm)1) << pushed_bit)) != 0);
+ }
+#endif
+
+ return head.contents.index;
+}
diff --git a/src/core/lib/support/stack_lockfree.h b/src/core/lib/support/stack_lockfree.h
new file mode 100644
index 0000000000..35ef7c2959
--- /dev/null
+++ b/src/core/lib/support/stack_lockfree.h
@@ -0,0 +1,53 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SUPPORT_STACK_LOCKFREE_H
+#define GRPC_CORE_LIB_SUPPORT_STACK_LOCKFREE_H
+
+#include <stddef.h>
+
+typedef struct gpr_stack_lockfree gpr_stack_lockfree;
+
+/* This stack must specify the maximum number of entries to track.
+ The current implementation only allows up to 65534 entries */
+gpr_stack_lockfree *gpr_stack_lockfree_create(size_t entries);
+void gpr_stack_lockfree_destroy(gpr_stack_lockfree *stack);
+
+/* Pass in a valid entry number for the next stack entry */
+/* Returns 1 if this is the first element on the stack, 0 otherwise */
+int gpr_stack_lockfree_push(gpr_stack_lockfree *, int entry);
+
+/* Returns -1 on empty or the actual entry number */
+int gpr_stack_lockfree_pop(gpr_stack_lockfree *stack);
+
+#endif /* GRPC_CORE_LIB_SUPPORT_STACK_LOCKFREE_H */
diff --git a/src/core/lib/support/string.c b/src/core/lib/support/string.c
new file mode 100644
index 0000000000..a2ab6c5f1f
--- /dev/null
+++ b/src/core/lib/support/string.c
@@ -0,0 +1,296 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "src/core/lib/support/string.h"
+
+#include <ctype.h>
+#include <stddef.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/port_platform.h>
+#include <grpc/support/useful.h>
+
+char *gpr_strdup(const char *src) {
+ char *dst;
+ size_t len;
+
+ if (!src) {
+ return NULL;
+ }
+
+ len = strlen(src) + 1;
+ dst = gpr_malloc(len);
+
+ memcpy(dst, src, len);
+
+ return dst;
+}
+
+typedef struct {
+ size_t capacity;
+ size_t length;
+ char *data;
+} dump_out;
+
+static dump_out dump_out_create(void) {
+ dump_out r = {0, 0, NULL};
+ return r;
+}
+
+static void dump_out_append(dump_out *out, char c) {
+ if (out->length == out->capacity) {
+ out->capacity = GPR_MAX(8, 2 * out->capacity);
+ out->data = gpr_realloc(out->data, out->capacity);
+ }
+ out->data[out->length++] = c;
+}
+
+static void hexdump(dump_out *out, const char *buf, size_t len) {
+ static const char hex[16] = "0123456789abcdef";
+
+ const uint8_t *const beg = (const uint8_t *)buf;
+ const uint8_t *const end = beg + len;
+ const uint8_t *cur;
+
+ for (cur = beg; cur != end; ++cur) {
+ if (cur != beg) dump_out_append(out, ' ');
+ dump_out_append(out, hex[*cur >> 4]);
+ dump_out_append(out, hex[*cur & 0xf]);
+ }
+}
+
+static void asciidump(dump_out *out, const char *buf, size_t len) {
+ const uint8_t *const beg = (const uint8_t *)buf;
+ const uint8_t *const end = beg + len;
+ const uint8_t *cur;
+ int out_was_empty = (out->length == 0);
+ if (!out_was_empty) {
+ dump_out_append(out, ' ');
+ dump_out_append(out, '\'');
+ }
+ for (cur = beg; cur != end; ++cur) {
+ dump_out_append(out, (char)(isprint(*cur) ? *(char *)cur : '.'));
+ }
+ if (!out_was_empty) {
+ dump_out_append(out, '\'');
+ }
+}
+
+char *gpr_dump(const char *buf, size_t len, uint32_t flags) {
+ dump_out out = dump_out_create();
+ if (flags & GPR_DUMP_HEX) {
+ hexdump(&out, buf, len);
+ }
+ if (flags & GPR_DUMP_ASCII) {
+ asciidump(&out, buf, len);
+ }
+ dump_out_append(&out, 0);
+ return out.data;
+}
+
+char *gpr_dump_slice(gpr_slice s, uint32_t flags) {
+ return gpr_dump((const char *)GPR_SLICE_START_PTR(s), GPR_SLICE_LENGTH(s),
+ flags);
+}
+
+int gpr_parse_bytes_to_uint32(const char *buf, size_t len, uint32_t *result) {
+ uint32_t out = 0;
+ uint32_t new;
+ size_t i;
+
+ if (len == 0) return 0; /* must have some bytes */
+
+ for (i = 0; i < len; i++) {
+ if (buf[i] < '0' || buf[i] > '9') return 0; /* bad char */
+ new = 10 * out + (uint32_t)(buf[i] - '0');
+ if (new < out) return 0; /* overflow */
+ out = new;
+ }
+
+ *result = out;
+ return 1;
+}
+
+void gpr_reverse_bytes(char *str, int len) {
+ char *p1, *p2;
+ for (p1 = str, p2 = str + len - 1; p2 > p1; ++p1, --p2) {
+ char temp = *p1;
+ *p1 = *p2;
+ *p2 = temp;
+ }
+}
+
+int gpr_ltoa(long value, char *string) {
+ long sign;
+ int i = 0;
+
+ if (value == 0) {
+ string[0] = '0';
+ string[1] = 0;
+ return 1;
+ }
+
+ sign = value < 0 ? -1 : 1;
+ while (value) {
+ string[i++] = (char)('0' + sign * (value % 10));
+ value /= 10;
+ }
+ if (sign < 0) string[i++] = '-';
+ gpr_reverse_bytes(string, i);
+ string[i] = 0;
+ return i;
+}
+
+int int64_ttoa(int64_t value, char *string) {
+ int64_t sign;
+ int i = 0;
+
+ if (value == 0) {
+ string[0] = '0';
+ string[1] = 0;
+ return 1;
+ }
+
+ sign = value < 0 ? -1 : 1;
+ while (value) {
+ string[i++] = (char)('0' + sign * (value % 10));
+ value /= 10;
+ }
+ if (sign < 0) string[i++] = '-';
+ gpr_reverse_bytes(string, i);
+ string[i] = 0;
+ return i;
+}
+
+char *gpr_strjoin(const char **strs, size_t nstrs, size_t *final_length) {
+ return gpr_strjoin_sep(strs, nstrs, "", final_length);
+}
+
+char *gpr_strjoin_sep(const char **strs, size_t nstrs, const char *sep,
+ size_t *final_length) {
+ const size_t sep_len = strlen(sep);
+ size_t out_length = 0;
+ size_t i;
+ char *out;
+ for (i = 0; i < nstrs; i++) {
+ out_length += strlen(strs[i]);
+ }
+ out_length += 1; /* null terminator */
+ if (nstrs > 0) {
+ out_length += sep_len * (nstrs - 1); /* separators */
+ }
+ out = gpr_malloc(out_length);
+ out_length = 0;
+ for (i = 0; i < nstrs; i++) {
+ const size_t slen = strlen(strs[i]);
+ if (i != 0) {
+ memcpy(out + out_length, sep, sep_len);
+ out_length += sep_len;
+ }
+ memcpy(out + out_length, strs[i], slen);
+ out_length += slen;
+ }
+ out[out_length] = 0;
+ if (final_length != NULL) {
+ *final_length = out_length;
+ }
+ return out;
+}
+
+/** Finds the initial (\a begin) and final (\a end) offsets of the next
+ * substring from \a str + \a read_offset until the next \a sep or the end of \a
+ * str.
+ *
+ * Returns 1 and updates \a begin and \a end. Returns 0 otherwise. */
+static int slice_find_separator_offset(const gpr_slice str, const char *sep,
+ const size_t read_offset, size_t *begin,
+ size_t *end) {
+ size_t i;
+ const uint8_t *str_ptr = GPR_SLICE_START_PTR(str) + read_offset;
+ const size_t str_len = GPR_SLICE_LENGTH(str) - read_offset;
+ const size_t sep_len = strlen(sep);
+ if (str_len < sep_len) {
+ return 0;
+ }
+
+ for (i = 0; i <= str_len - sep_len; i++) {
+ if (memcmp(str_ptr + i, sep, sep_len) == 0) {
+ *begin = read_offset;
+ *end = read_offset + i;
+ return 1;
+ }
+ }
+ return 0;
+}
+
+void gpr_slice_split(gpr_slice str, const char *sep, gpr_slice_buffer *dst) {
+ const size_t sep_len = strlen(sep);
+ size_t begin, end;
+
+ GPR_ASSERT(sep_len > 0);
+
+ if (slice_find_separator_offset(str, sep, 0, &begin, &end) != 0) {
+ do {
+ gpr_slice_buffer_add_indexed(dst, gpr_slice_sub(str, begin, end));
+ } while (slice_find_separator_offset(str, sep, end + sep_len, &begin,
+ &end) != 0);
+ gpr_slice_buffer_add_indexed(
+ dst, gpr_slice_sub(str, end + sep_len, GPR_SLICE_LENGTH(str)));
+ } else { /* no sep found, add whole input */
+ gpr_slice_buffer_add_indexed(dst, gpr_slice_ref(str));
+ }
+}
+
+void gpr_strvec_init(gpr_strvec *sv) { memset(sv, 0, sizeof(*sv)); }
+
+void gpr_strvec_destroy(gpr_strvec *sv) {
+ size_t i;
+ for (i = 0; i < sv->count; i++) {
+ gpr_free(sv->strs[i]);
+ }
+ gpr_free(sv->strs);
+}
+
+void gpr_strvec_add(gpr_strvec *sv, char *str) {
+ if (sv->count == sv->capacity) {
+ sv->capacity = GPR_MAX(sv->capacity + 8, sv->capacity * 2);
+ sv->strs = gpr_realloc(sv->strs, sizeof(char *) * sv->capacity);
+ }
+ sv->strs[sv->count++] = str;
+}
+
+char *gpr_strvec_flatten(gpr_strvec *sv, size_t *final_length) {
+ return gpr_strjoin((const char **)sv->strs, sv->count, final_length);
+}
diff --git a/src/core/lib/support/string.h b/src/core/lib/support/string.h
new file mode 100644
index 0000000000..ea58610914
--- /dev/null
+++ b/src/core/lib/support/string.h
@@ -0,0 +1,121 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SUPPORT_STRING_H
+#define GRPC_CORE_LIB_SUPPORT_STRING_H
+
+#include <stddef.h>
+
+#include <grpc/support/port_platform.h>
+#include <grpc/support/slice.h>
+#include <grpc/support/slice_buffer.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* String utility functions */
+
+/* Flags for gpr_dump function. */
+#define GPR_DUMP_HEX 0x00000001
+#define GPR_DUMP_ASCII 0x00000002
+
+/* Converts array buf, of length len, into a C string according to the flags.
+ Result should be freed with gpr_free() */
+char *gpr_dump(const char *buf, size_t len, uint32_t flags);
+
+/* Calls gpr_dump on a slice. */
+char *gpr_dump_slice(gpr_slice slice, uint32_t flags);
+
+/* Parses an array of bytes into an integer (base 10). Returns 1 on success,
+ 0 on failure. */
+int gpr_parse_bytes_to_uint32(const char *data, size_t length,
+ uint32_t *result);
+
+/* Minimum buffer size for calling ltoa */
+#define GPR_LTOA_MIN_BUFSIZE (3 * sizeof(long))
+
+/* Convert a long to a string in base 10; returns the length of the
+ output string (or 0 on failure).
+ output must be at least GPR_LTOA_MIN_BUFSIZE bytes long. */
+int gpr_ltoa(long value, char *output);
+
+/* Minimum buffer size for calling int64toa */
+#define GPR_INT64TOA_MIN_BUFSIZE (3 * sizeof(int64_t))
+
+/* Convert an int64 to a string in base 10; returns the length of the
+output string (or 0 on failure).
+output must be at least GPR_INT64TOA_MIN_BUFSIZE bytes long.
+NOTE: This function ensures sufficient bit width even on Win x64,
+where long is 32bit is size.*/
+int int64_ttoa(int64_t value, char *output);
+
+/* Reverse a run of bytes */
+void gpr_reverse_bytes(char *str, int len);
+
+/* Join a set of strings, returning the resulting string.
+ Total combined length (excluding null terminator) is returned in total_length
+ if it is non-null. */
+char *gpr_strjoin(const char **strs, size_t nstrs, size_t *total_length);
+
+/* Join a set of strings using a separator, returning the resulting string.
+ Total combined length (excluding null terminator) is returned in total_length
+ if it is non-null. */
+char *gpr_strjoin_sep(const char **strs, size_t nstrs, const char *sep,
+ size_t *total_length);
+
+/** Split \a str by the separator \a sep. Results are stored in \a dst, which
+ * should be a properly initialized instance. */
+void gpr_slice_split(gpr_slice str, const char *sep, gpr_slice_buffer *dst);
+
+/* A vector of strings... for building up a final string one piece at a time */
+typedef struct {
+ char **strs;
+ size_t count;
+ size_t capacity;
+} gpr_strvec;
+
+/* Initialize/destroy */
+void gpr_strvec_init(gpr_strvec *strs);
+void gpr_strvec_destroy(gpr_strvec *strs);
+/* Add a string to a strvec, takes ownership of the string */
+void gpr_strvec_add(gpr_strvec *strs, char *add);
+/* Return a joined string with all added substrings, optionally setting
+ total_length as per gpr_strjoin */
+char *gpr_strvec_flatten(gpr_strvec *strs, size_t *total_length);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* GRPC_CORE_LIB_SUPPORT_STRING_H */
diff --git a/src/core/lib/support/string_posix.c b/src/core/lib/support/string_posix.c
new file mode 100644
index 0000000000..c804ed5ded
--- /dev/null
+++ b/src/core/lib/support/string_posix.c
@@ -0,0 +1,86 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_POSIX_STRING
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+
+int gpr_asprintf(char **strp, const char *format, ...) {
+ va_list args;
+ int ret;
+ char buf[64];
+ size_t strp_buflen;
+
+ /* Use a constant-sized buffer to determine the length. */
+ va_start(args, format);
+ ret = vsnprintf(buf, sizeof(buf), format, args);
+ va_end(args);
+ if (ret < 0) {
+ *strp = NULL;
+ return -1;
+ }
+
+ /* Allocate a new buffer, with space for the NUL terminator. */
+ strp_buflen = (size_t)ret + 1;
+ if ((*strp = gpr_malloc(strp_buflen)) == NULL) {
+ /* This shouldn't happen, because gpr_malloc() calls abort(). */
+ return -1;
+ }
+
+ /* Return early if we have all the bytes. */
+ if (strp_buflen <= sizeof(buf)) {
+ memcpy(*strp, buf, strp_buflen);
+ return ret;
+ }
+
+ /* Try again using the larger buffer. */
+ va_start(args, format);
+ ret = vsnprintf(*strp, strp_buflen, format, args);
+ va_end(args);
+ if ((size_t)ret == strp_buflen - 1) {
+ return ret;
+ }
+
+ /* This should never happen. */
+ gpr_free(*strp);
+ *strp = NULL;
+ return -1;
+}
+
+#endif /* GPR_POSIX_STRING */
diff --git a/src/core/lib/support/string_win32.c b/src/core/lib/support/string_win32.c
new file mode 100644
index 0000000000..a2f9857356
--- /dev/null
+++ b/src/core/lib/support/string_win32.c
@@ -0,0 +1,109 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* Posix code for gpr snprintf support. */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WIN32
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+#include <grpc/support/alloc.h>
+
+#include "src/core/lib/support/string.h"
+
+int gpr_asprintf(char **strp, const char *format, ...) {
+ va_list args;
+ int ret;
+ size_t strp_buflen;
+
+ /* Determine the length. */
+ va_start(args, format);
+ ret = _vscprintf(format, args);
+ va_end(args);
+ if (ret < 0) {
+ *strp = NULL;
+ return -1;
+ }
+
+ /* Allocate a new buffer, with space for the NUL terminator. */
+ strp_buflen = (size_t)ret + 1;
+ if ((*strp = gpr_malloc(strp_buflen)) == NULL) {
+ /* This shouldn't happen, because gpr_malloc() calls abort(). */
+ return -1;
+ }
+
+ /* Print to the buffer. */
+ va_start(args, format);
+ ret = vsnprintf_s(*strp, strp_buflen, _TRUNCATE, format, args);
+ va_end(args);
+ if ((size_t)ret == strp_buflen - 1) {
+ return ret;
+ }
+
+ /* This should never happen. */
+ gpr_free(*strp);
+ *strp = NULL;
+ return -1;
+}
+
+#if defined UNICODE || defined _UNICODE
+LPTSTR
+gpr_char_to_tchar(LPCSTR input) {
+ LPTSTR ret;
+ int needed = MultiByteToWideChar(CP_UTF8, 0, input, -1, NULL, 0);
+ if (needed <= 0) return NULL;
+ ret = gpr_malloc((unsigned)needed * sizeof(TCHAR));
+ MultiByteToWideChar(CP_UTF8, 0, input, -1, ret, needed);
+ return ret;
+}
+
+LPSTR
+gpr_tchar_to_char(LPCTSTR input) {
+ LPSTR ret;
+ int needed = WideCharToMultiByte(CP_UTF8, 0, input, -1, NULL, 0, NULL, NULL);
+ if (needed <= 0) return NULL;
+ ret = gpr_malloc((unsigned)needed);
+ WideCharToMultiByte(CP_UTF8, 0, input, -1, ret, needed, NULL, NULL);
+ return ret;
+}
+#else
+char *gpr_tchar_to_char(LPTSTR input) { return gpr_strdup(input); }
+
+char *gpr_char_to_tchar(LPTSTR input) { return gpr_strdup(input); }
+#endif
+
+#endif /* GPR_WIN32 */
diff --git a/src/core/lib/support/string_win32.h b/src/core/lib/support/string_win32.h
new file mode 100644
index 0000000000..ff4a694ca9
--- /dev/null
+++ b/src/core/lib/support/string_win32.h
@@ -0,0 +1,47 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SUPPORT_STRING_WIN32_H
+#define GRPC_CORE_LIB_SUPPORT_STRING_WIN32_H
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WIN32
+
+/* These allocate new strings using gpr_malloc to convert from and to utf-8. */
+LPTSTR gpr_char_to_tchar(LPCSTR input);
+LPSTR gpr_tchar_to_char(LPCTSTR input);
+
+#endif /* GPR_WIN32 */
+
+#endif /* GRPC_CORE_LIB_SUPPORT_STRING_WIN32_H */
diff --git a/src/core/lib/support/subprocess_posix.c b/src/core/lib/support/subprocess_posix.c
new file mode 100644
index 0000000000..4f4de9298e
--- /dev/null
+++ b/src/core/lib/support/subprocess_posix.c
@@ -0,0 +1,112 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_POSIX_SUBPROCESS
+
+#include <grpc/support/subprocess.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+
+struct gpr_subprocess {
+ int pid;
+ int joined;
+};
+
+const char *gpr_subprocess_binary_extension() { return ""; }
+
+gpr_subprocess *gpr_subprocess_create(int argc, const char **argv) {
+ gpr_subprocess *r;
+ int pid;
+ char **exec_args;
+
+ pid = fork();
+ if (pid == -1) {
+ return NULL;
+ } else if (pid == 0) {
+ exec_args = gpr_malloc(((size_t)argc + 1) * sizeof(char *));
+ memcpy(exec_args, argv, (size_t)argc * sizeof(char *));
+ exec_args[argc] = NULL;
+ execv(exec_args[0], exec_args);
+ /* if we reach here, an error has occurred */
+ gpr_log(GPR_ERROR, "execv '%s' failed: %s", exec_args[0], strerror(errno));
+ _exit(1);
+ return NULL;
+ } else {
+ r = gpr_malloc(sizeof(gpr_subprocess));
+ memset(r, 0, sizeof(*r));
+ r->pid = pid;
+ return r;
+ }
+}
+
+void gpr_subprocess_destroy(gpr_subprocess *p) {
+ if (!p->joined) {
+ kill(p->pid, SIGKILL);
+ gpr_subprocess_join(p);
+ }
+ gpr_free(p);
+}
+
+int gpr_subprocess_join(gpr_subprocess *p) {
+ int status;
+retry:
+ if (waitpid(p->pid, &status, 0) == -1) {
+ if (errno == EINTR) {
+ goto retry;
+ }
+ gpr_log(GPR_ERROR, "waitpid failed: %s", strerror(errno));
+ return -1;
+ }
+ return status;
+}
+
+void gpr_subprocess_interrupt(gpr_subprocess *p) {
+ if (!p->joined) {
+ kill(p->pid, SIGINT);
+ }
+}
+
+#endif /* GPR_POSIX_SUBPROCESS */
diff --git a/src/core/lib/support/subprocess_windows.c b/src/core/lib/support/subprocess_windows.c
new file mode 100644
index 0000000000..264306f1bd
--- /dev/null
+++ b/src/core/lib/support/subprocess_windows.c
@@ -0,0 +1,141 @@
+/*
+ *
+ * Copyright 2016, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WINDOWS_SUBPROCESS
+
+#include <string.h>
+#include <tchar.h>
+#include <windows.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/subprocess.h>
+#include "src/core/lib/support/string.h"
+#include "src/core/lib/support/string_win32.h"
+
+struct gpr_subprocess {
+ PROCESS_INFORMATION pi;
+ int joined;
+ int interrupted;
+};
+
+const char *gpr_subprocess_binary_extension() { return ".exe"; }
+
+gpr_subprocess *gpr_subprocess_create(int argc, const char **argv) {
+ gpr_subprocess *r;
+
+ STARTUPINFO si;
+ PROCESS_INFORMATION pi;
+
+ char *args = gpr_strjoin_sep(argv, (size_t)argc, " ", NULL);
+ TCHAR *args_tchar;
+
+ args_tchar = gpr_char_to_tchar(args);
+ gpr_free(args);
+
+ memset(&si, 0, sizeof(si));
+ si.cb = sizeof(si);
+ memset(&pi, 0, sizeof(pi));
+
+ if (!CreateProcess(NULL, args_tchar, NULL, NULL, FALSE,
+ CREATE_NEW_PROCESS_GROUP, NULL, NULL, &si, &pi)) {
+ gpr_free(args_tchar);
+ return NULL;
+ }
+ gpr_free(args_tchar);
+
+ r = gpr_malloc(sizeof(gpr_subprocess));
+ memset(r, 0, sizeof(*r));
+ r->pi = pi;
+ return r;
+}
+
+void gpr_subprocess_destroy(gpr_subprocess *p) {
+ if (p) {
+ if (!p->joined) {
+ gpr_subprocess_interrupt(p);
+ gpr_subprocess_join(p);
+ }
+ if (p->pi.hProcess) {
+ CloseHandle(p->pi.hProcess);
+ }
+ if (p->pi.hThread) {
+ CloseHandle(p->pi.hThread);
+ }
+ gpr_free(p);
+ }
+}
+
+int gpr_subprocess_join(gpr_subprocess *p) {
+ DWORD dwExitCode;
+ if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) {
+ if (dwExitCode == STILL_ACTIVE) {
+ if (WaitForSingleObject(p->pi.hProcess, INFINITE) == WAIT_OBJECT_0) {
+ p->joined = 1;
+ goto getExitCode;
+ }
+ return -1; // failed to join
+ } else {
+ goto getExitCode;
+ }
+ } else {
+ return -1; // failed to get exit code
+ }
+
+getExitCode:
+ if (p->interrupted) {
+ return 0;
+ }
+ if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) {
+ return (int)dwExitCode;
+ } else {
+ return -1; // failed to get exit code
+ }
+}
+
+void gpr_subprocess_interrupt(gpr_subprocess *p) {
+ DWORD dwExitCode;
+ if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) {
+ if (dwExitCode == STILL_ACTIVE) {
+ gpr_log(GPR_INFO, "sending ctrl-break");
+ GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, p->pi.dwProcessId);
+ p->joined = 1;
+ p->interrupted = 1;
+ }
+ }
+ return;
+}
+
+#endif /* GPR_WINDOWS_SUBPROCESS */
diff --git a/src/core/lib/support/sync.c b/src/core/lib/support/sync.c
new file mode 100644
index 0000000000..44b83f8175
--- /dev/null
+++ b/src/core/lib/support/sync.c
@@ -0,0 +1,127 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* Generic implementation of synchronization primitives. */
+
+#include <grpc/support/atm.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+
+/* Number of mutexes to allocate for events, to avoid lock contention.
+ Should be a prime. */
+enum { event_sync_partitions = 31 };
+
+/* Events are partitioned by address to avoid lock contention. */
+static struct sync_array_s {
+ gpr_mu mu;
+ gpr_cv cv;
+} sync_array[event_sync_partitions];
+
+/* This routine is executed once on first use, via event_once */
+static gpr_once event_once = GPR_ONCE_INIT;
+static void event_initialize(void) {
+ int i;
+ for (i = 0; i != event_sync_partitions; i++) {
+ gpr_mu_init(&sync_array[i].mu);
+ gpr_cv_init(&sync_array[i].cv);
+ }
+}
+
+/* Hash ev into an element of sync_array[]. */
+static struct sync_array_s *hash(gpr_event *ev) {
+ return &sync_array[((uintptr_t)ev) % event_sync_partitions];
+}
+
+void gpr_event_init(gpr_event *ev) {
+ gpr_once_init(&event_once, &event_initialize);
+ ev->state = 0;
+}
+
+void gpr_event_set(gpr_event *ev, void *value) {
+ struct sync_array_s *s = hash(ev);
+ gpr_mu_lock(&s->mu);
+ GPR_ASSERT(gpr_atm_acq_load(&ev->state) == 0);
+ gpr_atm_rel_store(&ev->state, (gpr_atm)value);
+ gpr_cv_broadcast(&s->cv);
+ gpr_mu_unlock(&s->mu);
+ GPR_ASSERT(value != NULL);
+}
+
+void *gpr_event_get(gpr_event *ev) {
+ return (void *)gpr_atm_acq_load(&ev->state);
+}
+
+void *gpr_event_wait(gpr_event *ev, gpr_timespec abs_deadline) {
+ void *result = (void *)gpr_atm_acq_load(&ev->state);
+ if (result == NULL) {
+ struct sync_array_s *s = hash(ev);
+ gpr_mu_lock(&s->mu);
+ do {
+ result = (void *)gpr_atm_acq_load(&ev->state);
+ } while (result == NULL && !gpr_cv_wait(&s->cv, &s->mu, abs_deadline));
+ gpr_mu_unlock(&s->mu);
+ }
+ return result;
+}
+
+void gpr_ref_init(gpr_refcount *r, int n) { gpr_atm_rel_store(&r->count, n); }
+
+void gpr_ref(gpr_refcount *r) { gpr_atm_no_barrier_fetch_add(&r->count, 1); }
+
+void gpr_ref_non_zero(gpr_refcount *r) {
+ gpr_atm prior = gpr_atm_no_barrier_fetch_add(&r->count, 1);
+ GPR_ASSERT(prior > 0);
+}
+
+void gpr_refn(gpr_refcount *r, int n) {
+ gpr_atm_no_barrier_fetch_add(&r->count, n);
+}
+
+int gpr_unref(gpr_refcount *r) {
+ gpr_atm prior = gpr_atm_full_fetch_add(&r->count, -1);
+ GPR_ASSERT(prior > 0);
+ return prior == 1;
+}
+
+void gpr_stats_init(gpr_stats_counter *c, intptr_t n) {
+ gpr_atm_rel_store(&c->value, n);
+}
+
+void gpr_stats_inc(gpr_stats_counter *c, intptr_t inc) {
+ gpr_atm_no_barrier_fetch_add(&c->value, inc);
+}
+
+intptr_t gpr_stats_read(const gpr_stats_counter *c) {
+ /* don't need acquire-load, but we have no no-barrier load yet */
+ return gpr_atm_acq_load(&c->value);
+}
diff --git a/src/core/lib/support/sync_posix.c b/src/core/lib/support/sync_posix.c
new file mode 100644
index 0000000000..dcb0969a4e
--- /dev/null
+++ b/src/core/lib/support/sync_posix.c
@@ -0,0 +1,104 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_POSIX_SYNC
+
+#include <errno.h>
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+#include <time.h>
+#include "src/core/lib/profiling/timers.h"
+
+void gpr_mu_init(gpr_mu* mu) { GPR_ASSERT(pthread_mutex_init(mu, NULL) == 0); }
+
+void gpr_mu_destroy(gpr_mu* mu) { GPR_ASSERT(pthread_mutex_destroy(mu) == 0); }
+
+void gpr_mu_lock(gpr_mu* mu) {
+ GPR_TIMER_BEGIN("gpr_mu_lock", 0);
+ GPR_ASSERT(pthread_mutex_lock(mu) == 0);
+ GPR_TIMER_END("gpr_mu_lock", 0);
+}
+
+void gpr_mu_unlock(gpr_mu* mu) {
+ GPR_TIMER_BEGIN("gpr_mu_unlock", 0);
+ GPR_ASSERT(pthread_mutex_unlock(mu) == 0);
+ GPR_TIMER_END("gpr_mu_unlock", 0);
+}
+
+int gpr_mu_trylock(gpr_mu* mu) {
+ int err;
+ GPR_TIMER_BEGIN("gpr_mu_trylock", 0);
+ err = pthread_mutex_trylock(mu);
+ GPR_ASSERT(err == 0 || err == EBUSY);
+ GPR_TIMER_END("gpr_mu_trylock", 0);
+ return err == 0;
+}
+
+/*----------------------------------------*/
+
+void gpr_cv_init(gpr_cv* cv) { GPR_ASSERT(pthread_cond_init(cv, NULL) == 0); }
+
+void gpr_cv_destroy(gpr_cv* cv) { GPR_ASSERT(pthread_cond_destroy(cv) == 0); }
+
+int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) {
+ int err = 0;
+ if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) ==
+ 0) {
+ err = pthread_cond_wait(cv, mu);
+ } else {
+ struct timespec abs_deadline_ts;
+ abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_REALTIME);
+ abs_deadline_ts.tv_sec = (time_t)abs_deadline.tv_sec;
+ abs_deadline_ts.tv_nsec = abs_deadline.tv_nsec;
+ err = pthread_cond_timedwait(cv, mu, &abs_deadline_ts);
+ }
+ GPR_ASSERT(err == 0 || err == ETIMEDOUT || err == EAGAIN);
+ return err == ETIMEDOUT;
+}
+
+void gpr_cv_signal(gpr_cv* cv) { GPR_ASSERT(pthread_cond_signal(cv) == 0); }
+
+void gpr_cv_broadcast(gpr_cv* cv) {
+ GPR_ASSERT(pthread_cond_broadcast(cv) == 0);
+}
+
+/*----------------------------------------*/
+
+void gpr_once_init(gpr_once* once, void (*init_function)(void)) {
+ GPR_ASSERT(pthread_once(once, init_function) == 0);
+}
+
+#endif /* GRP_POSIX_SYNC */
diff --git a/src/core/lib/support/sync_win32.c b/src/core/lib/support/sync_win32.c
new file mode 100644
index 0000000000..470a9f9704
--- /dev/null
+++ b/src/core/lib/support/sync_win32.c
@@ -0,0 +1,133 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* Win32 code for gpr synchronization support. */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WIN32
+
+#include <grpc/support/log.h>
+#include <grpc/support/sync.h>
+#include <grpc/support/time.h>
+
+void gpr_mu_init(gpr_mu *mu) {
+ InitializeCriticalSection(&mu->cs);
+ mu->locked = 0;
+}
+
+void gpr_mu_destroy(gpr_mu *mu) { DeleteCriticalSection(&mu->cs); }
+
+void gpr_mu_lock(gpr_mu *mu) {
+ EnterCriticalSection(&mu->cs);
+ GPR_ASSERT(!mu->locked);
+ mu->locked = 1;
+}
+
+void gpr_mu_unlock(gpr_mu *mu) {
+ mu->locked = 0;
+ LeaveCriticalSection(&mu->cs);
+}
+
+int gpr_mu_trylock(gpr_mu *mu) {
+ int result = TryEnterCriticalSection(&mu->cs);
+ if (result) {
+ if (mu->locked) { /* This thread already holds the lock. */
+ LeaveCriticalSection(&mu->cs); /* Decrement lock count. */
+ result = 0; /* Indicate failure */
+ }
+ mu->locked = 1;
+ }
+ return result;
+}
+
+/*----------------------------------------*/
+
+void gpr_cv_init(gpr_cv *cv) { InitializeConditionVariable(cv); }
+
+void gpr_cv_destroy(gpr_cv *cv) {
+ /* Condition variables don't need destruction in Win32. */
+}
+
+int gpr_cv_wait(gpr_cv *cv, gpr_mu *mu, gpr_timespec abs_deadline) {
+ int timeout = 0;
+ DWORD timeout_max_ms;
+ mu->locked = 0;
+ if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) ==
+ 0) {
+ SleepConditionVariableCS(cv, &mu->cs, INFINITE);
+ } else {
+ abs_deadline = gpr_convert_clock_type(abs_deadline, GPR_CLOCK_REALTIME);
+ gpr_timespec now = gpr_now(abs_deadline.clock_type);
+ int64_t now_ms = (int64_t)now.tv_sec * 1000 + now.tv_nsec / 1000000;
+ int64_t deadline_ms =
+ (int64_t)abs_deadline.tv_sec * 1000 + abs_deadline.tv_nsec / 1000000;
+ if (now_ms >= deadline_ms) {
+ timeout = 1;
+ } else {
+ if ((deadline_ms - now_ms) >= INFINITE) {
+ timeout_max_ms = INFINITE - 1;
+ } else {
+ timeout_max_ms = (DWORD)(deadline_ms - now_ms);
+ }
+ timeout = (SleepConditionVariableCS(cv, &mu->cs, timeout_max_ms) == 0 &&
+ GetLastError() == ERROR_TIMEOUT);
+ }
+ }
+ mu->locked = 1;
+ return timeout;
+}
+
+void gpr_cv_signal(gpr_cv *cv) { WakeConditionVariable(cv); }
+
+void gpr_cv_broadcast(gpr_cv *cv) { WakeAllConditionVariable(cv); }
+
+/*----------------------------------------*/
+
+static void *dummy;
+struct run_once_func_arg {
+ void (*init_function)(void);
+};
+static BOOL CALLBACK run_once_func(gpr_once *once, void *v, void **pv) {
+ struct run_once_func_arg *arg = v;
+ (*arg->init_function)();
+ return 1;
+}
+
+void gpr_once_init(gpr_once *once, void (*init_function)(void)) {
+ struct run_once_func_arg arg;
+ arg.init_function = init_function;
+ InitOnceExecuteOnce(once, run_once_func, &arg, &dummy);
+}
+
+#endif /* GPR_WIN32 */
diff --git a/src/core/lib/support/thd.c b/src/core/lib/support/thd.c
new file mode 100644
index 0000000000..41daeb5d0e
--- /dev/null
+++ b/src/core/lib/support/thd.c
@@ -0,0 +1,64 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* Posix implementation for gpr threads. */
+
+#include <memory.h>
+
+#include <grpc/support/thd.h>
+
+enum { GPR_THD_JOINABLE = 1 };
+
+gpr_thd_options gpr_thd_options_default(void) {
+ gpr_thd_options options;
+ memset(&options, 0, sizeof(options));
+ return options;
+}
+
+void gpr_thd_options_set_detached(gpr_thd_options* options) {
+ options->flags &= ~GPR_THD_JOINABLE;
+}
+
+void gpr_thd_options_set_joinable(gpr_thd_options* options) {
+ options->flags |= GPR_THD_JOINABLE;
+}
+
+int gpr_thd_options_is_detached(const gpr_thd_options* options) {
+ if (!options) return 1;
+ return (options->flags & GPR_THD_JOINABLE) == 0;
+}
+
+int gpr_thd_options_is_joinable(const gpr_thd_options* options) {
+ if (!options) return 0;
+ return (options->flags & GPR_THD_JOINABLE) == GPR_THD_JOINABLE;
+}
diff --git a/src/core/lib/support/thd_internal.h b/src/core/lib/support/thd_internal.h
new file mode 100644
index 0000000000..975d5537cc
--- /dev/null
+++ b/src/core/lib/support/thd_internal.h
@@ -0,0 +1,39 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SUPPORT_THD_INTERNAL_H
+#define GRPC_CORE_LIB_SUPPORT_THD_INTERNAL_H
+
+/* Internal interfaces between modules within the gpr support library. */
+
+#endif /* GRPC_CORE_LIB_SUPPORT_THD_INTERNAL_H */
diff --git a/src/core/lib/support/thd_posix.c b/src/core/lib/support/thd_posix.c
new file mode 100644
index 0000000000..2fc23bffaf
--- /dev/null
+++ b/src/core/lib/support/thd_posix.c
@@ -0,0 +1,95 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* Posix implementation for gpr threads. */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_POSIX_SYNC
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/thd.h>
+#include <grpc/support/useful.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <string.h>
+
+struct thd_arg {
+ void (*body)(void *arg); /* body of a thread */
+ void *arg; /* argument to a thread */
+};
+
+/* Body of every thread started via gpr_thd_new. */
+static void *thread_body(void *v) {
+ struct thd_arg a = *(struct thd_arg *)v;
+ free(v);
+ (*a.body)(a.arg);
+ return NULL;
+}
+
+int gpr_thd_new(gpr_thd_id *t, void (*thd_body)(void *arg), void *arg,
+ const gpr_thd_options *options) {
+ int thread_started;
+ pthread_attr_t attr;
+ pthread_t p;
+ /* don't use gpr_malloc as we may cause an infinite recursion with
+ * the profiling code */
+ struct thd_arg *a = malloc(sizeof(*a));
+ GPR_ASSERT(a != NULL);
+ a->body = thd_body;
+ a->arg = arg;
+
+ GPR_ASSERT(pthread_attr_init(&attr) == 0);
+ if (gpr_thd_options_is_detached(options)) {
+ GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) ==
+ 0);
+ } else {
+ GPR_ASSERT(pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) ==
+ 0);
+ }
+ thread_started = (pthread_create(&p, &attr, &thread_body, a) == 0);
+ GPR_ASSERT(pthread_attr_destroy(&attr) == 0);
+ if (!thread_started) {
+ /* don't use gpr_free, as this was allocated using malloc (see above) */
+ free(a);
+ }
+ *t = (gpr_thd_id)p;
+ return thread_started;
+}
+
+gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)pthread_self(); }
+
+void gpr_thd_join(gpr_thd_id t) { pthread_join((pthread_t)t, NULL); }
+
+#endif /* GPR_POSIX_SYNC */
diff --git a/src/core/lib/support/thd_win32.c b/src/core/lib/support/thd_win32.c
new file mode 100644
index 0000000000..6deb3140eb
--- /dev/null
+++ b/src/core/lib/support/thd_win32.c
@@ -0,0 +1,117 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* Windows implementation for gpr threads. */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WIN32
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/thd.h>
+#include <string.h>
+
+#if defined(_MSC_VER)
+#define thread_local __declspec(thread)
+#elif defined(__GNUC__)
+#define thread_local __thread
+#else
+#error "Unknown compiler - please file a bug report"
+#endif
+
+struct thd_info {
+ void (*body)(void *arg); /* body of a thread */
+ void *arg; /* argument to a thread */
+ HANDLE join_event; /* if joinable, the join event */
+ int joinable; /* true if not detached */
+};
+
+static thread_local struct thd_info *g_thd_info;
+
+/* Destroys a thread info */
+static void destroy_thread(struct thd_info *t) {
+ if (t->joinable) CloseHandle(t->join_event);
+ gpr_free(t);
+}
+
+/* Body of every thread started via gpr_thd_new. */
+static DWORD WINAPI thread_body(void *v) {
+ g_thd_info = (struct thd_info *)v;
+ g_thd_info->body(g_thd_info->arg);
+ if (g_thd_info->joinable) {
+ BOOL ret = SetEvent(g_thd_info->join_event);
+ GPR_ASSERT(ret);
+ } else {
+ destroy_thread(g_thd_info);
+ }
+ return 0;
+}
+
+int gpr_thd_new(gpr_thd_id *t, void (*thd_body)(void *arg), void *arg,
+ const gpr_thd_options *options) {
+ HANDLE handle;
+ struct thd_info *info = gpr_malloc(sizeof(*info));
+ info->body = thd_body;
+ info->arg = arg;
+ *t = 0;
+ if (gpr_thd_options_is_joinable(options)) {
+ info->joinable = 1;
+ info->join_event = CreateEvent(NULL, FALSE, FALSE, NULL);
+ if (info->join_event == NULL) {
+ gpr_free(info);
+ return 0;
+ }
+ } else {
+ info->joinable = 0;
+ }
+ handle = CreateThread(NULL, 64 * 1024, thread_body, info, 0, NULL);
+ if (handle == NULL) {
+ destroy_thread(info);
+ } else {
+ *t = (gpr_thd_id)info;
+ CloseHandle(handle);
+ }
+ return handle != NULL;
+}
+
+gpr_thd_id gpr_thd_currentid(void) { return (gpr_thd_id)g_thd_info; }
+
+void gpr_thd_join(gpr_thd_id t) {
+ struct thd_info *info = (struct thd_info *)t;
+ DWORD ret = WaitForSingleObject(info->join_event, INFINITE);
+ GPR_ASSERT(ret == WAIT_OBJECT_0);
+ destroy_thread(info);
+}
+
+#endif /* GPR_WIN32 */
diff --git a/src/core/lib/support/time.c b/src/core/lib/support/time.c
new file mode 100644
index 0000000000..57f8331194
--- /dev/null
+++ b/src/core/lib/support/time.c
@@ -0,0 +1,304 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* Generic implementation of time calls. */
+
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+
+int gpr_time_cmp(gpr_timespec a, gpr_timespec b) {
+ int cmp = (a.tv_sec > b.tv_sec) - (a.tv_sec < b.tv_sec);
+ GPR_ASSERT(a.clock_type == b.clock_type);
+ if (cmp == 0) {
+ cmp = (a.tv_nsec > b.tv_nsec) - (a.tv_nsec < b.tv_nsec);
+ }
+ return cmp;
+}
+
+gpr_timespec gpr_time_min(gpr_timespec a, gpr_timespec b) {
+ return gpr_time_cmp(a, b) < 0 ? a : b;
+}
+
+gpr_timespec gpr_time_max(gpr_timespec a, gpr_timespec b) {
+ return gpr_time_cmp(a, b) > 0 ? a : b;
+}
+
+gpr_timespec gpr_time_0(gpr_clock_type type) {
+ gpr_timespec out;
+ out.tv_sec = 0;
+ out.tv_nsec = 0;
+ out.clock_type = type;
+ return out;
+}
+
+gpr_timespec gpr_inf_future(gpr_clock_type type) {
+ gpr_timespec out;
+ out.tv_sec = INT64_MAX;
+ out.tv_nsec = 0;
+ out.clock_type = type;
+ return out;
+}
+
+gpr_timespec gpr_inf_past(gpr_clock_type type) {
+ gpr_timespec out;
+ out.tv_sec = INT64_MIN;
+ out.tv_nsec = 0;
+ out.clock_type = type;
+ return out;
+}
+
+/* TODO(ctiller): consider merging _nanos, _micros, _millis into a single
+ function for maintainability. Similarly for _seconds, _minutes, and _hours */
+
+gpr_timespec gpr_time_from_nanos(int64_t ns, gpr_clock_type type) {
+ gpr_timespec result;
+ result.clock_type = type;
+ if (ns == INT64_MAX) {
+ result = gpr_inf_future(type);
+ } else if (ns == INT64_MIN) {
+ result = gpr_inf_past(type);
+ } else if (ns >= 0) {
+ result.tv_sec = ns / GPR_NS_PER_SEC;
+ result.tv_nsec = (int32_t)(ns - result.tv_sec * GPR_NS_PER_SEC);
+ } else {
+ /* Calculation carefully formulated to avoid any possible under/overflow. */
+ result.tv_sec = (-(999999999 - (ns + GPR_NS_PER_SEC)) / GPR_NS_PER_SEC) - 1;
+ result.tv_nsec = (int32_t)(ns - result.tv_sec * GPR_NS_PER_SEC);
+ }
+ return result;
+}
+
+gpr_timespec gpr_time_from_micros(int64_t us, gpr_clock_type type) {
+ gpr_timespec result;
+ result.clock_type = type;
+ if (us == INT64_MAX) {
+ result = gpr_inf_future(type);
+ } else if (us == INT64_MIN) {
+ result = gpr_inf_past(type);
+ } else if (us >= 0) {
+ result.tv_sec = us / 1000000;
+ result.tv_nsec = (int32_t)((us - result.tv_sec * 1000000) * 1000);
+ } else {
+ /* Calculation carefully formulated to avoid any possible under/overflow. */
+ result.tv_sec = (-(999999 - (us + 1000000)) / 1000000) - 1;
+ result.tv_nsec = (int32_t)((us - result.tv_sec * 1000000) * 1000);
+ }
+ return result;
+}
+
+gpr_timespec gpr_time_from_millis(int64_t ms, gpr_clock_type type) {
+ gpr_timespec result;
+ result.clock_type = type;
+ if (ms == INT64_MAX) {
+ result = gpr_inf_future(type);
+ } else if (ms == INT64_MIN) {
+ result = gpr_inf_past(type);
+ } else if (ms >= 0) {
+ result.tv_sec = ms / 1000;
+ result.tv_nsec = (int32_t)((ms - result.tv_sec * 1000) * 1000000);
+ } else {
+ /* Calculation carefully formulated to avoid any possible under/overflow. */
+ result.tv_sec = (-(999 - (ms + 1000)) / 1000) - 1;
+ result.tv_nsec = (int32_t)((ms - result.tv_sec * 1000) * 1000000);
+ }
+ return result;
+}
+
+gpr_timespec gpr_time_from_seconds(int64_t s, gpr_clock_type type) {
+ gpr_timespec result;
+ result.clock_type = type;
+ if (s == INT64_MAX) {
+ result = gpr_inf_future(type);
+ } else if (s == INT64_MIN) {
+ result = gpr_inf_past(type);
+ } else {
+ result.tv_sec = s;
+ result.tv_nsec = 0;
+ }
+ return result;
+}
+
+gpr_timespec gpr_time_from_minutes(int64_t m, gpr_clock_type type) {
+ gpr_timespec result;
+ result.clock_type = type;
+ if (m >= INT64_MAX / 60) {
+ result = gpr_inf_future(type);
+ } else if (m <= INT64_MIN / 60) {
+ result = gpr_inf_past(type);
+ } else {
+ result.tv_sec = m * 60;
+ result.tv_nsec = 0;
+ }
+ return result;
+}
+
+gpr_timespec gpr_time_from_hours(int64_t h, gpr_clock_type type) {
+ gpr_timespec result;
+ result.clock_type = type;
+ if (h >= INT64_MAX / 3600) {
+ result = gpr_inf_future(type);
+ } else if (h <= INT64_MIN / 3600) {
+ result = gpr_inf_past(type);
+ } else {
+ result.tv_sec = h * 3600;
+ result.tv_nsec = 0;
+ }
+ return result;
+}
+
+gpr_timespec gpr_time_add(gpr_timespec a, gpr_timespec b) {
+ gpr_timespec sum;
+ int64_t inc = 0;
+ GPR_ASSERT(b.clock_type == GPR_TIMESPAN);
+ sum.clock_type = a.clock_type;
+ sum.tv_nsec = a.tv_nsec + b.tv_nsec;
+ if (sum.tv_nsec >= GPR_NS_PER_SEC) {
+ sum.tv_nsec -= GPR_NS_PER_SEC;
+ inc++;
+ }
+ if (a.tv_sec == INT64_MAX || a.tv_sec == INT64_MIN) {
+ sum = a;
+ } else if (b.tv_sec == INT64_MAX ||
+ (b.tv_sec >= 0 && a.tv_sec >= INT64_MAX - b.tv_sec)) {
+ sum = gpr_inf_future(sum.clock_type);
+ } else if (b.tv_sec == INT64_MIN ||
+ (b.tv_sec <= 0 && a.tv_sec <= INT64_MIN - b.tv_sec)) {
+ sum = gpr_inf_past(sum.clock_type);
+ } else {
+ sum.tv_sec = a.tv_sec + b.tv_sec;
+ if (inc != 0 && sum.tv_sec == INT64_MAX - 1) {
+ sum = gpr_inf_future(sum.clock_type);
+ } else {
+ sum.tv_sec += inc;
+ }
+ }
+ return sum;
+}
+
+gpr_timespec gpr_time_sub(gpr_timespec a, gpr_timespec b) {
+ gpr_timespec diff;
+ int64_t dec = 0;
+ if (b.clock_type == GPR_TIMESPAN) {
+ diff.clock_type = a.clock_type;
+ } else {
+ GPR_ASSERT(a.clock_type == b.clock_type);
+ diff.clock_type = GPR_TIMESPAN;
+ }
+ diff.tv_nsec = a.tv_nsec - b.tv_nsec;
+ if (diff.tv_nsec < 0) {
+ diff.tv_nsec += GPR_NS_PER_SEC;
+ dec++;
+ }
+ if (a.tv_sec == INT64_MAX || a.tv_sec == INT64_MIN) {
+ diff = a;
+ } else if (b.tv_sec == INT64_MIN ||
+ (b.tv_sec <= 0 && a.tv_sec >= INT64_MAX + b.tv_sec)) {
+ diff = gpr_inf_future(GPR_CLOCK_REALTIME);
+ } else if (b.tv_sec == INT64_MAX ||
+ (b.tv_sec >= 0 && a.tv_sec <= INT64_MIN + b.tv_sec)) {
+ diff = gpr_inf_past(GPR_CLOCK_REALTIME);
+ } else {
+ diff.tv_sec = a.tv_sec - b.tv_sec;
+ if (dec != 0 && diff.tv_sec == INT64_MIN + 1) {
+ diff = gpr_inf_past(GPR_CLOCK_REALTIME);
+ } else {
+ diff.tv_sec -= dec;
+ }
+ }
+ return diff;
+}
+
+int gpr_time_similar(gpr_timespec a, gpr_timespec b, gpr_timespec threshold) {
+ int cmp_ab;
+
+ GPR_ASSERT(a.clock_type == b.clock_type);
+ GPR_ASSERT(threshold.clock_type == GPR_TIMESPAN);
+
+ cmp_ab = gpr_time_cmp(a, b);
+ if (cmp_ab == 0) return 1;
+ if (cmp_ab < 0) {
+ return gpr_time_cmp(gpr_time_sub(b, a), threshold) <= 0;
+ } else {
+ return gpr_time_cmp(gpr_time_sub(a, b), threshold) <= 0;
+ }
+}
+
+int32_t gpr_time_to_millis(gpr_timespec t) {
+ if (t.tv_sec >= 2147483) {
+ if (t.tv_sec == 2147483 && t.tv_nsec < 648 * GPR_NS_PER_MS) {
+ return 2147483 * GPR_MS_PER_SEC + t.tv_nsec / GPR_NS_PER_MS;
+ }
+ return 2147483647;
+ } else if (t.tv_sec <= -2147483) {
+ /* TODO(ctiller): correct handling here (it's so far in the past do we
+ care?) */
+ return -2147483647;
+ } else {
+ return (int32_t)(t.tv_sec * GPR_MS_PER_SEC + t.tv_nsec / GPR_NS_PER_MS);
+ }
+}
+
+double gpr_timespec_to_micros(gpr_timespec t) {
+ return (double)t.tv_sec * GPR_US_PER_SEC + t.tv_nsec * 1e-3;
+}
+
+gpr_timespec gpr_convert_clock_type(gpr_timespec t, gpr_clock_type clock_type) {
+ if (t.clock_type == clock_type) {
+ return t;
+ }
+
+ if (t.tv_nsec == 0) {
+ if (t.tv_sec == INT64_MAX) {
+ t.clock_type = clock_type;
+ return t;
+ }
+ if (t.tv_sec == INT64_MIN) {
+ t.clock_type = clock_type;
+ return t;
+ }
+ }
+
+ if (clock_type == GPR_TIMESPAN) {
+ return gpr_time_sub(t, gpr_now(t.clock_type));
+ }
+
+ if (t.clock_type == GPR_TIMESPAN) {
+ return gpr_time_add(gpr_now(clock_type), t);
+ }
+
+ return gpr_time_add(gpr_now(clock_type),
+ gpr_time_sub(t, gpr_now(t.clock_type)));
+}
diff --git a/src/core/lib/support/time_posix.c b/src/core/lib/support/time_posix.c
new file mode 100644
index 0000000000..f5f62dadc6
--- /dev/null
+++ b/src/core/lib/support/time_posix.c
@@ -0,0 +1,170 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+#include "src/core/lib/support/time_precise.h"
+
+#ifdef GPR_POSIX_TIME
+
+#include <stdlib.h>
+#include <time.h>
+#include <unistd.h>
+#ifdef __linux__
+#include <sys/syscall.h>
+#endif
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include "src/core/lib/support/block_annotate.h"
+
+static struct timespec timespec_from_gpr(gpr_timespec gts) {
+ struct timespec rv;
+ if (sizeof(time_t) < sizeof(int64_t)) {
+ /* fine to assert, as this is only used in gpr_sleep_until */
+ GPR_ASSERT(gts.tv_sec <= INT32_MAX && gts.tv_sec >= INT32_MIN);
+ }
+ rv.tv_sec = (time_t)gts.tv_sec;
+ rv.tv_nsec = gts.tv_nsec;
+ return rv;
+}
+
+#if _POSIX_TIMERS > 0
+static gpr_timespec gpr_from_timespec(struct timespec ts,
+ gpr_clock_type clock_type) {
+ /*
+ * timespec.tv_sec can have smaller size than gpr_timespec.tv_sec,
+ * but we are only using this function to implement gpr_now
+ * so there's no need to handle "infinity" values.
+ */
+ gpr_timespec rv;
+ rv.tv_sec = ts.tv_sec;
+ rv.tv_nsec = (int32_t)ts.tv_nsec;
+ rv.clock_type = clock_type;
+ return rv;
+}
+
+/** maps gpr_clock_type --> clockid_t for clock_gettime */
+static const clockid_t clockid_for_gpr_clock[] = {CLOCK_MONOTONIC,
+ CLOCK_REALTIME};
+
+void gpr_time_init(void) { gpr_precise_clock_init(); }
+
+gpr_timespec gpr_now(gpr_clock_type clock_type) {
+ struct timespec now;
+ GPR_ASSERT(clock_type != GPR_TIMESPAN);
+ if (clock_type == GPR_CLOCK_PRECISE) {
+ gpr_timespec ret;
+ gpr_precise_clock_now(&ret);
+ return ret;
+ } else {
+#if defined(GPR_BACKWARDS_COMPATIBILITY_MODE) && defined(__linux__)
+ /* avoid ABI problems by invoking syscalls directly */
+ syscall(SYS_clock_gettime, clockid_for_gpr_clock[clock_type], &now);
+#else
+ clock_gettime(clockid_for_gpr_clock[clock_type], &now);
+#endif
+ return gpr_from_timespec(now, clock_type);
+ }
+}
+#else
+/* For some reason Apple's OSes haven't implemented clock_gettime. */
+
+#include <mach/mach.h>
+#include <mach/mach_time.h>
+#include <sys/time.h>
+
+static double g_time_scale;
+static uint64_t g_time_start;
+
+void gpr_time_init(void) {
+ mach_timebase_info_data_t tb = {0, 1};
+ gpr_precise_clock_init();
+ mach_timebase_info(&tb);
+ g_time_scale = tb.numer;
+ g_time_scale /= tb.denom;
+ g_time_start = mach_absolute_time();
+}
+
+gpr_timespec gpr_now(gpr_clock_type clock) {
+ gpr_timespec now;
+ struct timeval now_tv;
+ double now_dbl;
+
+ now.clock_type = clock;
+ switch (clock) {
+ case GPR_CLOCK_REALTIME:
+ gettimeofday(&now_tv, NULL);
+ now.tv_sec = now_tv.tv_sec;
+ now.tv_nsec = now_tv.tv_usec * 1000;
+ break;
+ case GPR_CLOCK_MONOTONIC:
+ now_dbl = (mach_absolute_time() - g_time_start) * g_time_scale;
+ now.tv_sec = (int64_t)(now_dbl * 1e-9);
+ now.tv_nsec = (int32_t)(now_dbl - ((double)now.tv_sec) * 1e9);
+ break;
+ case GPR_CLOCK_PRECISE:
+ gpr_precise_clock_now(&now);
+ break;
+ case GPR_TIMESPAN:
+ abort();
+ }
+
+ return now;
+}
+#endif
+
+void gpr_sleep_until(gpr_timespec until) {
+ gpr_timespec now;
+ gpr_timespec delta;
+ struct timespec delta_ts;
+ int ns_result;
+
+ for (;;) {
+ /* We could simplify by using clock_nanosleep instead, but it might be
+ * slightly less portable. */
+ now = gpr_now(until.clock_type);
+ if (gpr_time_cmp(until, now) <= 0) {
+ return;
+ }
+
+ delta = gpr_time_sub(until, now);
+ delta_ts = timespec_from_gpr(delta);
+ GRPC_SCHEDULING_START_BLOCKING_REGION;
+ ns_result = nanosleep(&delta_ts, NULL);
+ GRPC_SCHEDULING_END_BLOCKING_REGION;
+ if (ns_result == 0) {
+ break;
+ }
+ }
+}
+
+#endif /* GPR_POSIX_TIME */
diff --git a/src/core/lib/support/time_precise.c b/src/core/lib/support/time_precise.c
new file mode 100644
index 0000000000..a2cf74bc84
--- /dev/null
+++ b/src/core/lib/support/time_precise.c
@@ -0,0 +1,89 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <stdio.h>
+
+#ifdef GRPC_TIMERS_RDTSC
+#if defined(__i386__)
+static void gpr_get_cycle_counter(long long int *clk) {
+ long long int ret;
+ __asm__ volatile("rdtsc" : "=A"(ret));
+ *clk = ret;
+}
+
+// ----------------------------------------------------------------
+#elif defined(__x86_64__) || defined(__amd64__)
+static void gpr_get_cycle_counter(long long int *clk) {
+ unsigned long long low, high;
+ __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
+ *clk = (long long)(high << 32) | (long long)low;
+}
+#endif
+
+static double cycles_per_second = 0;
+static long long int start_cycle;
+void gpr_precise_clock_init(void) {
+ time_t start;
+ long long end_cycle;
+ gpr_log(GPR_DEBUG, "Calibrating timers");
+ start = time(NULL);
+ while (time(NULL) == start)
+ ;
+ gpr_get_cycle_counter(&start_cycle);
+ while (time(NULL) <= start + 10)
+ ;
+ gpr_get_cycle_counter(&end_cycle);
+ cycles_per_second = (double)(end_cycle - start_cycle) / 10.0;
+ gpr_log(GPR_DEBUG, "... cycles_per_second = %f\n", cycles_per_second);
+}
+
+void gpr_precise_clock_now(gpr_timespec *clk) {
+ long long int counter;
+ double secs;
+ gpr_get_cycle_counter(&counter);
+ secs = (double)(counter - start_cycle) / cycles_per_second;
+ clk->clock_type = GPR_CLOCK_PRECISE;
+ clk->tv_sec = (int64_t)secs;
+ clk->tv_nsec = (int32_t)(1e9 * (secs - (double)clk->tv_sec));
+}
+
+#else /* GRPC_TIMERS_RDTSC */
+void gpr_precise_clock_init(void) {}
+
+void gpr_precise_clock_now(gpr_timespec *clk) {
+ *clk = gpr_now(GPR_CLOCK_REALTIME);
+ clk->clock_type = GPR_CLOCK_PRECISE;
+}
+#endif /* GRPC_TIMERS_RDTSC */
diff --git a/src/core/lib/support/time_precise.h b/src/core/lib/support/time_precise.h
new file mode 100644
index 0000000000..30818d04b9
--- /dev/null
+++ b/src/core/lib/support/time_precise.h
@@ -0,0 +1,42 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SUPPORT_TIME_PRECISE_H
+#define GRPC_CORE_LIB_SUPPORT_TIME_PRECISE_H
+
+#include <grpc/support/time.h>
+
+void gpr_precise_clock_init(void);
+void gpr_precise_clock_now(gpr_timespec *clk);
+
+#endif /* GRPC_CORE_LIB_SUPPORT_TIME_PRECISE_H */
diff --git a/src/core/lib/support/time_win32.c b/src/core/lib/support/time_win32.c
new file mode 100644
index 0000000000..f7acbd14a6
--- /dev/null
+++ b/src/core/lib/support/time_win32.c
@@ -0,0 +1,110 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* Win32 code for gpr time support. */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WIN32
+
+#include <grpc/support/log.h>
+#include <grpc/support/time.h>
+#include <limits.h>
+#include <process.h>
+#include <sys/timeb.h>
+
+#include "src/core/lib/support/block_annotate.h"
+#include "src/core/lib/support/time_precise.h"
+
+static LARGE_INTEGER g_start_time;
+static double g_time_scale;
+
+void gpr_time_init(void) {
+ LARGE_INTEGER frequency;
+ QueryPerformanceFrequency(&frequency);
+ QueryPerformanceCounter(&g_start_time);
+ g_time_scale = 1.0 / (double)frequency.QuadPart;
+}
+
+gpr_timespec gpr_now(gpr_clock_type clock) {
+ gpr_timespec now_tv;
+ LONGLONG diff;
+ struct _timeb now_tb;
+ LARGE_INTEGER timestamp;
+ double now_dbl;
+ now_tv.clock_type = clock;
+ switch (clock) {
+ case GPR_CLOCK_REALTIME:
+ _ftime_s(&now_tb);
+ now_tv.tv_sec = (int64_t)now_tb.time;
+ now_tv.tv_nsec = now_tb.millitm * 1000000;
+ break;
+ case GPR_CLOCK_MONOTONIC:
+ case GPR_CLOCK_PRECISE:
+ QueryPerformanceCounter(&timestamp);
+ diff = timestamp.QuadPart - g_start_time.QuadPart;
+ now_dbl = (double)diff * g_time_scale;
+ now_tv.tv_sec = (int64_t)now_dbl;
+ now_tv.tv_nsec = (int32_t)((now_dbl - (double)now_tv.tv_sec) * 1e9);
+ break;
+ case GPR_TIMESPAN:
+ abort();
+ break;
+ }
+ return now_tv;
+}
+
+void gpr_sleep_until(gpr_timespec until) {
+ gpr_timespec now;
+ gpr_timespec delta;
+ int64_t sleep_millis;
+
+ for (;;) {
+ /* We could simplify by using clock_nanosleep instead, but it might be
+ * slightly less portable. */
+ now = gpr_now(until.clock_type);
+ if (gpr_time_cmp(until, now) <= 0) {
+ return;
+ }
+
+ delta = gpr_time_sub(until, now);
+ sleep_millis =
+ delta.tv_sec * GPR_MS_PER_SEC + delta.tv_nsec / GPR_NS_PER_MS;
+ GPR_ASSERT((sleep_millis >= 0) && (sleep_millis <= INT_MAX));
+ GRPC_SCHEDULING_START_BLOCKING_REGION;
+ Sleep((DWORD)sleep_millis);
+ GRPC_SCHEDULING_END_BLOCKING_REGION;
+ }
+}
+
+#endif /* GPR_WIN32 */
diff --git a/src/core/lib/support/tls_pthread.c b/src/core/lib/support/tls_pthread.c
new file mode 100644
index 0000000000..9683a6e547
--- /dev/null
+++ b/src/core/lib/support/tls_pthread.c
@@ -0,0 +1,45 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_PTHREAD_TLS
+
+#include <grpc/support/tls.h>
+
+intptr_t gpr_tls_set(struct gpr_pthread_thread_local *tls, intptr_t value) {
+ GPR_ASSERT(0 == pthread_setspecific(tls->key, (void *)value));
+ return value;
+}
+
+#endif /* GPR_PTHREAD_TLS */
diff --git a/src/core/lib/support/tmpfile.h b/src/core/lib/support/tmpfile.h
new file mode 100644
index 0000000000..059142ab0f
--- /dev/null
+++ b/src/core/lib/support/tmpfile.h
@@ -0,0 +1,55 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef GRPC_CORE_LIB_SUPPORT_TMPFILE_H
+#define GRPC_CORE_LIB_SUPPORT_TMPFILE_H
+
+#include <stdio.h>
+
+#include <grpc/support/slice.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Creates a temporary file from a prefix.
+ If tmp_filename is not NULL, *tmp_filename is assigned the name of the
+ created file and it is the responsibility of the caller to gpr_free it
+ unless an error occurs in which case it will be set to NULL. */
+FILE *gpr_tmpfile(const char *prefix, char **tmp_filename);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* GRPC_CORE_LIB_SUPPORT_TMPFILE_H */
diff --git a/src/core/lib/support/tmpfile_posix.c b/src/core/lib/support/tmpfile_posix.c
new file mode 100644
index 0000000000..9e0e7ad808
--- /dev/null
+++ b/src/core/lib/support/tmpfile_posix.c
@@ -0,0 +1,85 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_POSIX_FILE
+
+#include "src/core/lib/support/tmpfile.h"
+
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/support/string.h"
+
+FILE *gpr_tmpfile(const char *prefix, char **tmp_filename) {
+ FILE *result = NULL;
+ char *template;
+ int fd;
+
+ if (tmp_filename != NULL) *tmp_filename = NULL;
+
+ gpr_asprintf(&template, "/tmp/%s_XXXXXX", prefix);
+ GPR_ASSERT(template != NULL);
+
+ fd = mkstemp(template);
+ if (fd == -1) {
+ gpr_log(GPR_ERROR, "mkstemp failed for template %s with error %s.",
+ template, strerror(errno));
+ goto end;
+ }
+ result = fdopen(fd, "w+");
+ if (result == NULL) {
+ gpr_log(GPR_ERROR, "Could not open file %s from fd %d (error = %s).",
+ template, fd, strerror(errno));
+ unlink(template);
+ close(fd);
+ goto end;
+ }
+
+end:
+ if (result != NULL && tmp_filename != NULL) {
+ *tmp_filename = template;
+ } else {
+ gpr_free(template);
+ }
+ return result;
+}
+
+#endif /* GPR_POSIX_FILE */
diff --git a/src/core/lib/support/tmpfile_win32.c b/src/core/lib/support/tmpfile_win32.c
new file mode 100644
index 0000000000..0cb2904f8d
--- /dev/null
+++ b/src/core/lib/support/tmpfile_win32.c
@@ -0,0 +1,84 @@
+/*
+ *
+ * Copyright 2015, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <grpc/support/port_platform.h>
+
+#ifdef GPR_WIN32
+
+#include <io.h>
+#include <stdio.h>
+#include <string.h>
+#include <tchar.h>
+
+#include <grpc/support/alloc.h>
+#include <grpc/support/log.h>
+#include <grpc/support/string_util.h>
+
+#include "src/core/lib/support/string_win32.h"
+#include "src/core/lib/support/tmpfile.h"
+
+FILE *gpr_tmpfile(const char *prefix, char **tmp_filename_out) {
+ FILE *result = NULL;
+ LPTSTR template_string = NULL;
+ TCHAR tmp_path[MAX_PATH];
+ TCHAR tmp_filename[MAX_PATH];
+ DWORD status;
+ UINT success;
+
+ if (tmp_filename_out != NULL) *tmp_filename_out = NULL;
+
+ /* Convert our prefix to TCHAR. */
+ template_string = gpr_char_to_tchar(prefix);
+ GPR_ASSERT(template_string);
+
+ /* Get the path to the best temporary folder available. */
+ status = GetTempPath(MAX_PATH, tmp_path);
+ if (status == 0 || status > MAX_PATH) goto end;
+
+ /* Generate a unique filename with our template + temporary path. */
+ success = GetTempFileName(tmp_path, template_string, 0, tmp_filename);
+ if (!success) goto end;
+
+ /* Open a file there. */
+ if (_tfopen_s(&result, tmp_filename, TEXT("wb+")) != 0) goto end;
+
+end:
+ if (result && tmp_filename_out) {
+ *tmp_filename_out = gpr_tchar_to_char(tmp_filename);
+ }
+
+ gpr_free(template_string);
+ return result;
+}
+
+#endif /* GPR_WIN32 */
diff --git a/src/core/lib/support/wrap_memcpy.c b/src/core/lib/support/wrap_memcpy.c
new file mode 100644
index 0000000000..15c289f7b8
--- /dev/null
+++ b/src/core/lib/support/wrap_memcpy.c
@@ -0,0 +1,53 @@
+/*
+ *
+ * Copyright 2016, Google 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 Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <string.h>
+
+/* Provide a wrapped memcpy for targets that need to be backwards
+ * compatible with older libc's.
+ *
+ * Enable by setting LDFLAGS=-Wl,-wrap,memcpy when linking.
+ */
+
+#ifdef __linux__
+#ifdef __x86_64__
+__asm__(".symver memcpy,memcpy@GLIBC_2.2.5");
+void *__wrap_memcpy(void *destination, const void *source, size_t num) {
+ return memcpy(destination, source, num);
+}
+#else /* !__x86_64__ */
+void *__wrap_memcpy(void *destination, const void *source, size_t num) {
+ return memmove(destination, source, num);
+}
+#endif
+#endif