+ for (Cleaner *cleaner(cleaner_); cleaner != NULL; ) {
+ Cleaner *next(cleaner->next_);
+ (*cleaner->code_)(cleaner->data_);
+ cleaner = next;
+ }
+ }
+
+ template <typename Type_>
+ Type_ *malloc(size_t size, size_t alignment = CYAlignment) {
+ uint8_t *end(data_);
+ CYAlign(end, alignment);
+ end += size;
+
+ if (size_t(end - data_) > size_) {
+ size_t need(sizeof(Cleaner));
+ CYAlign(need, alignment);
+ need += size;
+ size_ = std::max<size_t>(next_, need);
+ next_ *= 2;
+ data_ = reinterpret_cast<uint8_t *>(::malloc(size_));
+ atexit(free, data_);
+ _assert(size <= size_);
+ }
+
+ uint8_t *data(data_);
+ CYAlign(data, alignment);
+ end = data + size;
+ size_ -= end - data_;
+ data_ = end;
+ return reinterpret_cast<Type_ *>(data);
+ }
+
+ char *strdup(const char *data) {
+ if (data == NULL)
+ return NULL;
+ return memdup(data, strlen(data) + 1, 1);
+ }
+
+ template <typename Type_>
+ Type_ *memdup(const Type_ *data, size_t size, size_t alignment = CYAlignment) {
+ Type_ *copy(malloc<Type_>(size, alignment));
+ memcpy(copy, data, size);
+ return copy;
+ }
+
+ char *strndup(const char *data, size_t size) {
+ return strmemdup(data, strnlen(data, size));
+ }
+
+ char *strmemdup(const char *data, size_t size) {
+ char *copy(malloc<char>(size + 1, 1));
+ memcpy(copy, data, size);
+ copy[size] = '\0';
+ return copy;
+ }
+
+ // XXX: this could be made much more efficient
+ __attribute__((__sentinel__))
+ char *strcat(const char *data, ...) {
+ size_t size(strlen(data)); {
+ va_list args;
+ va_start(args, data);
+
+ while (const char *arg = va_arg(args, const char *))
+ size += strlen(arg);
+
+ va_end(args);
+ }
+
+ char *copy(malloc<char>(size + 1, 1)); {
+ va_list args;
+ va_start(args, data);
+
+ size_t offset(strlen(data));
+ memcpy(copy, data, offset);
+
+ while (const char *arg = va_arg(args, const char *)) {
+ size_t size(strlen(arg));
+ memcpy(copy + offset, arg, size);
+ offset += size;
+ }
+
+ va_end(args);
+ }
+
+ copy[size] = '\0';
+ return copy;