<|start_filename|>arch/x64/sysroot/include/sys/reg.h<|end_filename|>
#pragma once

#include <limits.h>
#include <unistd.h>

#include <bits/reg.h>


<|start_filename|>arch/x64/sysroot/include/stdnoreturn.h<|end_filename|>
#pragma once

#ifndef __cplusplus
#include <features.h>
#define noreturn _Noreturn
#endif


<|start_filename|>arch/x64/sysroot/include/zircon/hw/usb-dfu.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

// clang-format off

#include <zircon/compiler.h>
#include <zircon/types.h>

__BEGIN_CDECLS;

// USB DFU Spec, Rev 1.1

// DFU Class-Specific Request Values
// Table 3.2
#define USB_DFU_DETACH     0x00
#define USB_DFU_DNLOAD     0x01
#define USB_DFU_UPLOAD     0x02
#define USB_DFU_GET_STATUS 0x03
#define USB_DFU_CLR_STATUS 0x04
#define USB_DFU_GET_STATE  0x05
#define USB_DFU_ABORT      0x06

// DFU Class-Specific Descriptor Types
// Table 4.1.3
#define USB_DFU_CS_FUNCTIONAL 0x21

typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;  // USB_DFU_CS_FUNCTIONAL
    uint8_t bmAttributes;
    uint16_t wDetachTimeOut;
    uint16_t wTransferSize;
    uint16_t bcdDFUVersion;
} __PACKED usb_dfu_func_desc_t;

// DFU_GET_STATUS Response
// Section 6.1.2
typedef struct {
    uint8_t bStatus;
    uint8_t bwPollTimeout[3];  // 24 bit unsigned integer
    uint8_t bState;
    uint8_t bString;
} __PACKED usb_dfu_get_status_data_t;

// DFU Device Status Values
#define USB_DFU_STATUS_OK                     0x00
#define USB_DFU_STATUS_ERR_TARGET             0x01
#define USB_DFU_STATUS_ERR_FILE               0x02
#define USB_DFU_STATUS_ERR_WRITE              0x03
#define USB_DFU_STATUS_ERR_ERASE              0x04
#define USB_DFU_STATUS_ERR_CHECK_ERASED       0x05
#define USB_DFU_STATUS_ERR_PROG               0x06
#define USB_DFU_STATUS_ERR_VERIFY             0x07
#define USB_DFU_STATUS_ERR_ADDRESS            0x08
#define USB_DFU_STATUS_ERR_NOT_DONE           0x09
#define USB_DFU_STATUS_ERR_FIRMWARE           0x0A
#define USB_DFU_STATUS_ERR_VENDOR             0x0B
#define USB_DFU_STATUS_ERR_USER               0x0C
#define USB_DFU_STATUS_ERR_POR                0x0D
#define USB_DFU_STATUS_ERR_UNKNOWN            0x0E
#define USB_DFU_STATUS_ERR_STALLED_PKT        0x0F

// DFU Device State Values
#define USB_DFU_STATE_APP_IDLE                0x00
#define USB_DFU_STATE_APP_DETACH              0x01
#define USB_DFU_STATE_DFU_IDLE                0x02
#define USB_DFU_STATE_DFU_DNLOAD_SYNC         0x03
#define USB_DFU_STATE_DFU_DNBUSY              0x04
#define USB_DFU_STATE_DFU_DNLOAD_IDLE         0x05
#define USB_DFU_STATE_DFU_MANIFEST_SYNC       0x06
#define USB_DFU_STATE_DFU_MANIFEST            0x07
#define USB_DFU_STATE_DFU_MANIFEST_WAIT_RESET 0x08
#define USB_DFU_STATE_DFU_UPLOAD_IDLE         0x09
#define USB_DFU_STATE_DFU_ERROR               0x0A

__END_CDECLS;


<|start_filename|>pkg/fidl_cpp/include/lib/fidl/cpp/interface_ptr_set.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIDL_CPP_INTERFACE_PTR_SET_H_
#define LIB_FIDL_CPP_INTERFACE_PTR_SET_H_

#include <zircon/assert.h>
#include <vector>

#include "lib/fidl/cpp/interface_ptr.h"

namespace fidl {

// Contains a set of |InterfacePtr| objects, each with their own channels.
//
// An |InterfacePtr| is removed from the set and destroyed when its underlying
// channel experiences an error. When the set is destroyed, all the underlying
// channels are closed.
//
// An |InterfacePtrSet| is useful for broadcasting messages to a set of clients,
// each with their own implementation of |Interface|.
//
// See also:
//
//  * |BindingSet|, which is the server analog of an |InterfacePtrSet|.
template <typename Interface>
class InterfacePtrSet {
 public:
  using StorageType = std::vector<std::unique_ptr<InterfacePtr<Interface>>>;
  using Ptr = InterfacePtr<Interface>;

  // Creates an empty |InterfacePtrSet|.
  InterfacePtrSet() = default;

  InterfacePtrSet(const InterfacePtrSet& other) = delete;
  InterfacePtrSet& operator=(const InterfacePtrSet& other) = delete;

  // Adds the given |InterfacePtr| to the set.
  //
  // The |InterfacePtr| must already be bound to a channel. The |InterfacePtr|
  // will be removed from the set when its underlying channel experiences an
  // error.
  void AddInterfacePtr(InterfacePtr<Interface> ptr) {
    ZX_DEBUG_ASSERT(ptr.is_bound());
    // Allocated a new |InterfacePtr| so that we can have a unique value to use
    // as a key for removing the InterfacePtr. Otherwise, we'll lose track of
    // the InterfacePtr when the vector resizes.
    ptrs_.push_back(std::make_unique<Ptr>(std::move(ptr)));
    auto* pointer = ptrs_.back().get();
    pointer->set_error_handler(
        [pointer, this](zx_status_t status) { this->RemoveOnError(pointer); });
  }

  // The |InterfacePtr| objects stored in this set.
  //
  // This collection of bindings can be invalidated when an |InterfacePtr| in
  // the set encounters a connection error because connection errors causes the
  // |InterfacePtrSet| to remove the |InterfacePtr| from the set.
  const StorageType& ptrs() const { return ptrs_; }

  // Closes all channels associated with |InterfacePtr| objects in the set.
  //
  // After this method returns, the set is empty.
  void CloseAll() { ptrs_.clear(); }

  // The number of |InterfacePtr| objects in the set.
  //
  // This number might be smaller than the number of |InterfacePtr| objects
  // added to the set if some of the underlying channels have experienced an
  // error.
  size_t size() const { return ptrs_.size(); }

 private:
  // Removes the given |pointer| from the set.
  //
  // Called from the error handler callback for |pointer|.
  void RemoveOnError(Ptr* pointer) {
    auto it = std::find_if(ptrs_.begin(), ptrs_.end(),
                           [pointer](const std::unique_ptr<Ptr>& p) {
                             return p.get() == pointer;
                           });
    ZX_DEBUG_ASSERT(it != ptrs_.end());
    ptrs_.erase(it);
  }

  // We use |unique_ptr| rather than just |InterfacePtr| so that we can keep
  // track of the |InterfacePtr| objects after the |vector| resizes and moves
  // its contents to its new buffer.
  StorageType ptrs_;
};

}  // namespace fidl

#endif  // LIB_FIDL_CPP_INTERFACE_PTR_SET_H_


<|start_filename|>pkg/fidl/include/lib/fidl/cpp/string_view.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIDL_CPP_STRING_VIEW_H_
#define LIB_FIDL_CPP_STRING_VIEW_H_

#include <zircon/fidl.h>

namespace fidl {

class StringView : public fidl_string_t {
public:
    StringView() : fidl_string_t{} {}

    uint64_t size() const { return fidl_string_t::size; }
    void set_size(uint64_t size) { fidl_string_t::size = size; }

    const char* data() const { return fidl_string_t::data; }
    void set_data(char* data) { fidl_string_t::data = data; }

    char* mutable_data() const { return fidl_string_t::data; }

    bool is_null() const { return fidl_string_t::data == nullptr; }
    bool empty() const { return fidl_string_t::size == 0; }

    const char& at(size_t offset) const { return data()[offset]; }
    char& at(size_t offset) { return mutable_data()[offset]; }

    const char& operator[](size_t offset) const { return at(offset); }
    char& operator[](size_t offset) { return at(offset); }

    char* begin() { return mutable_data(); }
    const char* begin() const { return data(); }
    const char* cbegin() const { return data(); }

    char* end() { return mutable_data() + size(); }
    const char* end() const { return data() + size(); }
    const char* cend() const { return data() + size(); }

    fidl_string_t* impl() { return this; }
};

} // namespace fidl

#endif // LIB_FIDL_CPP_STRING_VIEW_H_


<|start_filename|>arch/x64/sysroot/include/zircon/syscalls/hypervisor.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

#include <assert.h>

#include <zircon/compiler.h>
#include <zircon/types.h>

__BEGIN_CDECLS

// clang-format off
typedef uint32_t zx_guest_trap_t;

#define ZX_GUEST_TRAP_BELL ((zx_guest_trap_t) 0u)
#define ZX_GUEST_TRAP_MEM  ((zx_guest_trap_t) 1u)
#define ZX_GUEST_TRAP_IO   ((zx_guest_trap_t) 2u)

typedef uint32_t zx_vcpu_t;

#define ZX_VCPU_STATE ((zx_vcpu_t) 0u)
#define ZX_VCPU_IO    ((zx_vcpu_t) 1u)
// clang-format on

// Structure to read and write VCPU state.
typedef struct zx_vcpu_state {
#if __aarch64__
    uint64_t x[31];
    uint64_t sp;
    // Contains only the user-controllable upper 4-bits (NZCV).
    uint32_t cpsr;
#elif __x86_64__
    uint64_t rax;
    uint64_t rcx;
    uint64_t rdx;
    uint64_t rbx;
    uint64_t rsp;
    uint64_t rbp;
    uint64_t rsi;
    uint64_t rdi;
    uint64_t r8;
    uint64_t r9;
    uint64_t r10;
    uint64_t r11;
    uint64_t r12;
    uint64_t r13;
    uint64_t r14;
    uint64_t r15;
    // Contains only the user-controllable lower 32-bits.
    uint64_t rflags;
#endif
} zx_vcpu_state_t;

// Structure to read and write VCPU state for IO ports.
typedef struct zx_vcpu_io {
    uint8_t access_size;
    union {
        uint8_t u8;
        uint16_t u16;
        uint32_t u32;
        uint8_t data[4];
    };
} zx_vcpu_io_t;

__END_CDECLS


<|start_filename|>pkg/fit/include/lib/fit/function.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIT_FUNCTION_H_
#define LIB_FIT_FUNCTION_H_

#include <memory>
#include <type_traits>

#include "function_internal.h"
#include "nullable.h"

namespace fit {

template <size_t inline_target_size, bool require_inline,
          typename Result, typename... Args>
class function_impl;

// The default size allowance for storing a target inline within a function
// object, in bytes.  This default allows for inline storage of targets
// as big as two pointers, such as an object pointer and a pointer to a member
// function.
constexpr size_t default_inline_target_size = sizeof(void*) * 2;

// A |fit::function| is a move-only polymorphic function wrapper.
//
// |fit::function<T>| behaves like |std::function<T>| except that it is move-only
// instead of copyable so it can hold targets which cannot be copied, such as
// mutable lambdas.
//
// Targets of up to |inline_target_size| bytes in size (rounded up for memory
// alignment) are stored inline within the function object without incurring
// any heap allocation.  Larger callable objects will be moved to the heap as
// required.
//
// See also |fit::inline_function<T, size>| for more control over allocation
// behavior.
//
// SYNOPSIS
//
// |T| is the function's signature.  e.g. void(int, std::string).
//
// |inline_target_size| is the minimum size of target that is guaranteed to
// fit within a function without requiring heap allocation.
// Defaults to |default_inline_target_size|.
//
// Class members are documented in |fit::function_impl|.
//
// EXAMPLES
//
// - https://fuchsia.googlesource.com/zircon/+/master/system/utest/fit/examples/function_example1.cpp
// - https://fuchsia.googlesource.com/zircon/+/master/system/utest/fit/examples/function_example2.cpp
//
template <typename T, size_t inline_target_size = default_inline_target_size>
using function = function_impl<inline_target_size, false, T>;

// A move-only callable object wrapper which forces callables to be stored inline
// and never performs heap allocation.
//
// Behaves just like |fit::function<T, inline_target_size>| except that attempting
// to store a target larger than |inline_target_size| will fail to compile.
template <typename T, size_t inline_target_size = default_inline_target_size>
using inline_function = function_impl<inline_target_size, true, T>;

// Synonym for a function which takes no arguments and produces no result.
using closure = function<void()>;

// Function implementation details.
// See |fit::function| documentation for more information.
template <size_t inline_target_size, bool require_inline,
          typename Result, typename... Args>
class function_impl<inline_target_size, require_inline, Result(Args...)> final {
    using ops_type = const ::fit::internal::target_ops<Result, Args...>*;
    using storage_type = typename std::aligned_storage<
        (inline_target_size >= sizeof(void*)
             ? inline_target_size
             : sizeof(void*))>::type; // avoid including <algorithm> just for max
    template <typename Callable>
    using target_type = ::fit::internal::target<
        Callable,
        (sizeof(Callable) <= sizeof(storage_type)),
        Result, Args...>;
    using null_target_type = target_type<decltype(nullptr)>;

public:
    // The function's result type.
    using result_type = Result;

    // // Creates a function with an empty target.
    function_impl() {
        initialize_null_target();
    }

    // Creates a function with an empty target.
    function_impl(decltype(nullptr)) {
        initialize_null_target();
    }

    // Creates a function bound to the specified function pointer.
    // If target == nullptr, assigns an empty target.
    function_impl(Result (*target)(Args...)) {
        initialize_target(target);
    }

    // Creates a function bound to the specified callable object.
    // If target == nullptr, assigns an empty target.
    //
    // For functors, we need to capture the raw type but also restrict on the existence of an
    // appropriate operator () to resolve overloads and implicit casts properly.
    template <typename Callable,
              typename = std::enable_if_t<
                  std::is_convertible<
                      decltype(std::declval<Callable&>()(
                          std::declval<Args>()...)),
                      result_type>::value>>
    function_impl(Callable target) {
        initialize_target(std::move(target));
    }

    // Creates a function with a target moved from another function,
    // leaving the other function with an empty target.
    function_impl(function_impl&& other) {
        move_target_from(std::move(other));
    }

    // Destroys the function, releasing its target.
    ~function_impl() {
        destroy_target();
    }

    // Returns true if the function has a non-empty target.
    explicit operator bool() const {
        return ops_ != &null_target_type::ops;
    };

    // Invokes the function's target.
    // Aborts if the function's target is empty.
    Result operator()(Args... args) const {
        return ops_->invoke(&bits_, std::forward<Args>(args)...);
    }

    // Assigns an empty target.
    function_impl& operator=(decltype(nullptr)) {
        destroy_target();
        initialize_null_target();
        return *this;
    }

    // Assigns the function's target.
    // If target == nullptr, assigns an empty target.
    template <typename Callable,
              typename = std::enable_if_t<
                  std::is_convertible<
                      decltype(std::declval<Callable&>()(
                          std::declval<Args>()...)),
                      result_type>::value>>
    function_impl& operator=(Callable target) {
        destroy_target();
        initialize_target(std::move(target));
        return *this;
    }

    // Assigns the function with a target moved from another function,
    // leaving the other function with an empty target.
    function_impl& operator=(function_impl&& other) {
        if (&other == this)
            return *this;
        destroy_target();
        move_target_from(std::move(other));
        return *this;
    }

    // Swaps the functions' targets.
    void swap(function_impl& other) {
        if (&other == this)
            return;
        ops_type temp_ops = ops_;
        storage_type temp_bits;
        ops_->move(&bits_, &temp_bits);

        ops_ = other.ops_;
        other.ops_->move(&other.bits_, &bits_);

        other.ops_ = temp_ops;
        temp_ops->move(&temp_bits, &other.bits_);
    }

    // Returns a pointer to the function's target.
    template <typename Callable>
    Callable* target() {
        check_target_type<Callable>();
        return static_cast<Callable*>(ops_->get(&bits_));
    }

    // Returns a pointer to the function's target.
    template <typename Callable>
    const Callable* target() const {
        check_target_type<Callable>();
        return static_cast<Callable*>(ops_->get(&bits_));
    }

    // Returns a new function object which invokes the same target.
    // The target itself is not copied; it is moved to the heap and its
    // lifetime is extended until all references have been released.
    //
    // Note: This method is not supported on |fit::inline_function<>|
    //       because it may incur a heap allocation which is contrary to
    //       the stated purpose of |fit::inline_function<>|.
    function_impl share() {
        static_assert(!require_inline, "Inline functions cannot be shared.");
        // TODO(jeffbrown): Replace shared_ptr with a better ref-count mechanism.
        // TODO(jeffbrown): This definition breaks the client's ability to use
        // |target()| because the target's type has changed.  We could fix this
        // by defining a new target type (and vtable) for shared targets
        // although it would be nice to avoid memory overhead and code expansion
        // when sharing is not used.
        struct ref {
            std::shared_ptr<function_impl> target;
            Result operator()(Args... args) {
                return (*target)(std::forward<Args>(args)...);
            }
        };
        if (ops_ != &target_type<ref>::ops) {
            if (ops_ == &null_target_type::ops) {
                return nullptr;
            }
            auto target = ref{std::make_shared<function_impl>(std::move(*this))};
            *this = std::move(target);
        }
        return function_impl(*static_cast<ref*>(ops_->get(&bits_)));
    }

    function_impl(const function_impl& other) = delete;
    function_impl& operator=(const function_impl& other) = delete;

private:
    // assumes target is uninitialized
    void initialize_null_target() {
        ops_ = &null_target_type::ops;
    }

    // assumes target is uninitialized
    template <typename Callable>
    void initialize_target(Callable target) {
        static_assert(!require_inline || sizeof(Callable) <= inline_target_size,
                      "Callable too large to store inline as requested.");
        if (is_null(target)) {
            initialize_null_target();
        } else {
            ops_ = &target_type<Callable>::ops;
            target_type<Callable>::initialize(&bits_, std::move(target));
        }
    }

    // leaves target uninitialized
    void destroy_target() {
        ops_->destroy(&bits_);
    }

    // leaves other target initialized to null
    void move_target_from(function_impl&& other) {
        ops_ = other.ops_;
        other.ops_->move(&other.bits_, &bits_);
        other.initialize_null_target();
    }

    template <typename Callable>
    void check_target_type() const {
        if (ops_ != &target_type<Callable>::ops)
            abort();
    }

    ops_type ops_;
    mutable storage_type bits_;
}; // namespace fit

template <size_t inline_target_size, bool require_inline, typename Result, typename... Args>
void swap(function_impl<inline_target_size, require_inline, Result, Args...>& a,
          function_impl<inline_target_size, require_inline, Result, Args...>& b) {
    a.swap(b);
}

template <size_t inline_target_size, bool require_inline, typename Result, typename... Args>
bool operator==(const function_impl<inline_target_size, require_inline, Result, Args...>& f,
                decltype(nullptr)) {
    return !f;
}
template <size_t inline_target_size, bool require_inline, typename Result, typename... Args>
bool operator==(decltype(nullptr),
                const function_impl<inline_target_size, require_inline, Result, Args...>& f) {
    return !f;
}
template <size_t inline_target_size, bool require_inline, typename Result, typename... Args>
bool operator!=(const function_impl<inline_target_size, require_inline, Result, Args...>& f,
                decltype(nullptr)) {
    return !!f;
}
template <size_t inline_target_size, bool require_inline, typename Result, typename... Args>
bool operator!=(decltype(nullptr),
                const function_impl<inline_target_size, require_inline, Result, Args...>& f) {
    return !!f;
}

// Returns a Callable object which invokes a member function of an object.
template <typename R, typename T, typename... Args>
auto bind_member(T* instance, R (T::*fn)(Args...)) {
    return [instance, fn](Args... args) {
        return (instance->*fn)(std::forward<Args>(args)...);
    };
}

} // namespace fit

#endif // LIB_FIT_FUNCTION_H_


<|start_filename|>arch/x64/sysroot/include/malloc.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#define __NEED_size_t

#include <bits/alltypes.h>

void* malloc(size_t);
void* calloc(size_t, size_t);
void* realloc(void*, size_t);
void free(void*);
void* valloc(size_t);
void* memalign(size_t, size_t);

size_t malloc_usable_size(void*);

#ifdef __cplusplus
}
#endif


<|start_filename|>dart/fuchsia_modular/lib/src/entity/internal/_link_entity.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:fidl/fidl.dart';
import 'package:fidl_fuchsia_mem/fidl_async.dart' as fuchsia_mem;
import 'package:fidl_fuchsia_modular/fidl_async.dart' as fidl;
import 'package:meta/meta.dart';
import 'package:zircon/zircon.dart';

import '../../internal/_component_context.dart';
import '../../module/internal/_module_context.dart';
import '../entity.dart';
import '../entity_codec.dart';

/// An [Entity] implementation which supports
/// data that lives inside links.
///
/// Note: This is a temporary solution that will go away when links are removed.
class LinkEntity<T> implements Entity<T> {
  /// The name of the link to pull data from
  final String linkName;

  /// The codec used to decode/encode data
  final EntityCodec codec;

  fidl.Link _link;

  /// Constructor
  LinkEntity({
    @required this.linkName,
    @required this.codec,
  })  : assert(linkName != null),
        assert(codec != null);

  @override
  Future<T> getData() async => _getSnapshot();

  @override
  Stream<T> watch() {
    final link = _getLink();
    final controller = StreamController<fuchsia_mem.Buffer>();
    final watcher = _LinkWatcher(onNotify: (buffer) async {
      controller.add(buffer);
    });

    link.watch(watcher.getInterfaceHandle());

    // if the user closed the stream we close the binding to the watcher
    controller.onCancel = watcher.binding.close;

    // if the connection closes then we close the stream
    watcher.binding.whenClosed.then((_) {
      if (!controller.isClosed) {
        controller.close();
      }
    });

    // Use _getSnapshot here instead of using the buffer directly because
    // most uses of links are using the entityRef value on the link instead
    // of raw json.
    return controller.stream.asyncMap((_) => _getSnapshot());
  }

  @override
  Future<void> write(T value) async {
    final link = _getLink();

    // Convert the object to raw bytes
    final bytes = codec.encode(value);

    // need to base64 encode so we can encode it as json.
    final b64ByteString = base64.encode(bytes);
    final jsonString = json.encode(b64ByteString);

    // convert the json encoded string into bytes so we can put it in a vmo
    final jsonData = Uint8List.fromList(utf8.encode(jsonString));
    final vmo = SizedVmo.fromUint8List(jsonData);
    final buffer = fuchsia_mem.Buffer(vmo: vmo, size: jsonData.length);

    await link.set(null, buffer);
  }

  Future<T> _getEntityData<T>(String entityReference) async {
    final resolver = fidl.EntityResolverProxy();
    await getComponentContext().getEntityResolver(resolver.ctrl.request());

    final entity = fidl.EntityProxy();
    await resolver.resolveEntity(entityReference, entity.ctrl.request());

    final types = await entity.getTypes();
    if (!types.contains(codec.type)) {
      throw EntityTypeException(codec.type);
    }

    final buffer = await entity.getData(codec.type);
    final dataVmo = SizedVmo(buffer.vmo.handle, buffer.size);
    final result = dataVmo.read(buffer.size);

    if (result.status != 0) {
      throw new Exception('Failed to read VMO');
    }

    dataVmo.close();

    return codec.decode(result.bytesAsUint8List());
  }

  T _getJsonData<T>(fuchsia_mem.Buffer jsonBuffer) {
    final vmo = SizedVmo(jsonBuffer.vmo.handle, jsonBuffer.size);
    final result = vmo.read(jsonBuffer.size);
    if (result.status != 0) {
      throw Exception('Failed to read VMO');
    }
    vmo.close();

    final resultBytes = result.bytesAsUint8List();
    Uint8List bytesToDecode;

    try {
      // Try to decode the values in the format that this entity encoded them
      final utf8String = utf8.decode(resultBytes);
      final jsonDecoded = json.decode(utf8String);
      bytesToDecode = base64.decode(jsonDecoded);
    } on Exception catch (_) {
      bytesToDecode = resultBytes;
    }

    return codec.decode(bytesToDecode);
  }

  fidl.Link _getLink() {
    if (_link != null) {
      return _link;
    }

    // Store the Link instead of the LinkProxy to avoid closing.
    fidl.LinkProxy linkProxy = fidl.LinkProxy();
    _link = linkProxy;
    getModuleContext().getLink(linkName, linkProxy.ctrl.request());

    return _link;
  }

  Future<T> _getSnapshot() async {
    final link = _getLink();

    final buffer = await link.get(null);
    if (buffer == null) {
      final entityReference = await link.getEntity();
      if (entityReference == null) {
        return null;
      }
      return _getEntityData(entityReference);
    }
    return _getJsonData(buffer);
  }
}

class _LinkWatcher extends fidl.LinkWatcher {
  final fidl.LinkWatcherBinding binding = fidl.LinkWatcherBinding();
  final Future<void> Function(fuchsia_mem.Buffer) onNotify;

  _LinkWatcher({@required this.onNotify}) : assert(onNotify != null);

  InterfaceHandle<fidl.LinkWatcher> getInterfaceHandle() {
    if (binding.isBound) {
      throw Exception(
          'Attempting to call _LinkWatcher.getInterfaceHandle on already bound binding');
    }
    return binding.wrap(this);
  }

  @override
  Future<void> notify(fuchsia_mem.Buffer data) => onNotify(data);
}


<|start_filename|>arch/x64/sysroot/include/tar.h<|end_filename|>
#pragma once

#define TSUID 04000
#define TSGID 02000
#define TSVTX 01000
#define TUREAD 00400
#define TUWRITE 00200
#define TUEXEC 00100
#define TGREAD 00040
#define TGWRITE 00020
#define TGEXEC 00010
#define TOREAD 00004
#define TOWRITE 00002
#define TOEXEC 00001

#define REGTYPE '0'
#define AREGTYPE '\0'
#define LNKTYPE '1'
#define SYMTYPE '2'
#define CHRTYPE '3'
#define BLKTYPE '4'
#define DIRTYPE '5'
#define FIFOTYPE '6'
#define CONTTYPE '7'

#define TMAGIC "ustar"
#define TMAGLEN 6

#define TVERSION "00"
#define TVERSLEN 2


<|start_filename|>arch/x64/sysroot/include/zircon/limits.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef ZIRCON_LIMITS_H_
#define ZIRCON_LIMITS_H_

#include <stdint.h>

#define ZX_PAGE_SHIFT ((uint32_t)12u)
#define ZX_PAGE_SIZE ((uint32_t)(1u << ZX_PAGE_SHIFT))
#define ZX_PAGE_MASK (ZX_PAGE_SIZE - 1u)

#endif // ZIRCON_LIMITS_H_


<|start_filename|>dart/fuchsia_media/lib/media.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/// A package which provides idiomatic dart APIs
/// for working with the fuchsia.media system.
export 'src/media.dart';


<|start_filename|>arch/x64/sysroot/include/sysexits.h<|end_filename|>
#pragma once

#define EX_OK 0
#define EX__BASE 64
#define EX_USAGE 64
#define EX_DATAERR 65
#define EX_NOINPUT 66
#define EX_NOUSER 67
#define EX_NOHOST 68
#define EX_UNAVAILABLE 69
#define EX_SOFTWARE 70
#define EX_OSERR 71
#define EX_OSFILE 72
#define EX_CANTCREAT 73
#define EX_IOERR 74
#define EX_TEMPFAIL 75
#define EX_PROTOCOL 76
#define EX_NOPERM 77
#define EX_CONFIG 78
#define EX__MAX 78


<|start_filename|>pkg/zx/include/lib/zx/socket.h<|end_filename|>
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_ZX_SOCKET_H_
#define LIB_ZX_SOCKET_H_

#include <lib/zx/handle.h>
#include <lib/zx/object.h>

namespace zx {

class socket : public object<socket> {
public:
    static constexpr zx_obj_type_t TYPE = ZX_OBJ_TYPE_SOCKET;

    constexpr socket() = default;

    explicit socket(zx_handle_t value) : object(value) {}

    explicit socket(handle&& h) : object(h.release()) {}

    socket(socket&& other) : object(other.release()) {}

    socket& operator=(socket&& other) {
        reset(other.release());
        return *this;
    }

    static zx_status_t create(uint32_t options, socket* endpoint0,
                              socket* endpoint1);

    zx_status_t write(uint32_t options, const void* buffer, size_t len,
                      size_t* actual) const {
        return zx_socket_write(get(), options, buffer, len, actual);
    }

    zx_status_t read(uint32_t options, void* buffer, size_t len,
                     size_t* actual) const {
        return zx_socket_read(get(), options, buffer, len, actual);
    }

    zx_status_t share(socket socket_to_share) const {
        return zx_socket_share(get(), socket_to_share.release());
    }

    zx_status_t accept(socket* out_socket) const {
        // We use a temporary to handle the case where |this| and |out_socket|
        // are aliased.
        socket result;
        zx_status_t status = zx_socket_accept(get(), result.reset_and_get_address());
        out_socket->reset(result.release());
        return status;
    }

    zx_status_t shutdown(uint32_t options) const {
        return zx_socket_shutdown(get(), options);
    }
};

using unowned_socket = unowned<socket>;

} // namespace zx

#endif  // LIB_ZX_SOCKET_H_


<|start_filename|>arch/x64/sysroot/include/zircon/dlfcn.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

#include <dlfcn.h>
#include <zircon/compiler.h>
#include <zircon/types.h>

__BEGIN_CDECLS

// Loads a dynamic shared object stored in |vmo|.
// Acts identically to dlopen, but acts on a vmo
// instead of a file path.
//
// Does not take ownership of the input vmo.
void* dlopen_vmo(zx_handle_t vmo, int mode);

// Replace the handle to the "loader service" used to map names
// to VM objects for dlopen et al.  This takes ownership of the
// given handle, and gives the caller ownership of the old handle
// in the return value.
zx_handle_t dl_set_loader_service(zx_handle_t new_svc);

// Ask the active "loader service" (if there is one), to return
// a new connection.  Not all loader services need support this.
// On success, a channel handle to the new connection is returned
// via out.
zx_status_t dl_clone_loader_service(zx_handle_t* out);

__END_CDECLS


<|start_filename|>dart/zircon/lib/src/socket_reader.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

part of zircon;

// ignore_for_file: public_member_api_docs

class SocketReaderError extends Error {
  final Object error;
  final StackTrace stacktrace;

  SocketReaderError(this.error, this.stacktrace);

  @override
  String toString() => error.toString();
}

typedef SocketReaderReadableHandler = void Function();
typedef SocketReaderErrorHandler = void Function(SocketReaderError error);

class SocketReader {
  Socket get socket => _socket;
  Socket _socket;

  bool get isBound => _socket != null;

  HandleWaiter _waiter;

  SocketReaderReadableHandler onReadable;
  SocketReaderErrorHandler onError;

  void bind(Socket socket) {
    if (isBound) {
      throw new ZirconApiError('SocketReader is already bound.');
    }
    _socket = socket;
    _asyncWait();
  }

  Socket unbind() {
    if (!isBound) {
      throw new ZirconApiError('SocketReader is not bound');
    }
    _waiter.cancel();
    final Socket result = _socket;
    _socket = null;
    return result;
  }

  void close() {
    if (!isBound) {
      return;
    }
    _waiter.cancel();
    _socket.close();
    _socket = null;
  }

  void _asyncWait() {
    _waiter = _socket.handle
        .asyncWait(Socket.READABLE | Socket.PEER_CLOSED, _handleWaitComplete);
  }

  void _errorSoon(SocketReaderError error) {
    if (onError == null) {
      return;
    }
    scheduleMicrotask(() {
      // We need to re-check onError because it might have changed during the
      // asynchronous gap.
      if (onError != null) {
        onError(error);
      }
    });
  }

  @override
  String toString() => 'SocketReader($_socket)';

  void _handleWaitComplete(int status, int pending) {
    assert(isBound);
    if (status != ZX.OK) {
      close();
      _errorSoon(new SocketReaderError(
          'Wait completed with status ${getStringForStatus(status)} ($status)',
          null));
      return;
    }
    // TODO(abarth): Change this try/catch pattern now that we don't use
    // RawReceivePort any more.
    try {
      if ((pending & Socket.READABLE) != 0) {
        if (onReadable != null) {
          onReadable();
        }
        if (isBound) {
          _asyncWait();
        }
      } else if ((pending & Socket.PEER_CLOSED) != 0) {
        close();
        _errorSoon(null);
      }
      // ignore: avoid_catching_errors
    } on Error catch (_) {
      // An Error exception from the core libraries is probably a programming
      // error that can't be handled. We rethrow the error so that
      // FidlEventHandlers can't swallow it by mistake.
      rethrow;
      // ignore: avoid_catches_without_on_clauses
    } catch (e, s) {
      close();
      _errorSoon(new SocketReaderError(e, s));
    }
  }
}


<|start_filename|>arch/x64/sysroot/include/paths.h<|end_filename|>
#pragma once

#define _PATH_DEFPATH "/usr/local/bin:/bin:/usr/bin"
#define _PATH_STDPATH "/bin:/usr/bin:/sbin:/usr/sbin"

#define _PATH_BSHELL "/bin/sh"
#define _PATH_CONSOLE "/dev/console"
#define _PATH_DEVNULL "/dev/null"
#define _PATH_KLOG "/proc/kmsg"
#define _PATH_MAILDIR "/var/mail"
#define _PATH_MAN "/usr/share/man"
#define _PATH_MNTTAB "/etc/fstab"
#define _PATH_MOUNTED "/etc/mtab"
#define _PATH_NOLOGIN "/etc/nologin"
#define _PATH_SENDMAIL "/usr/sbin/sendmail"
#define _PATH_SHELLS "/etc/shells"
#define _PATH_TTY "/dev/tty"
#define _PATH_VI "/usr/bin/vi"
#define _PATH_WTMP "/dev/null/wtmp"

#define _PATH_DEV "/dev/"
#define _PATH_TMP "/tmp/"
#define _PATH_VARDB "/var/lib/misc/"
#define _PATH_VARRUN "/var/run/"
#define _PATH_VARTMP "/var/tmp/"


<|start_filename|>arch/x64/sysroot/include/zircon/tls.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef ZIRCON_TLS_
#define ZIRCON_TLS_

// These constants are part of the C/C++ ABI known to compilers for
// *-fuchsia targets.  These are offsets from the thread pointer.

// This file must be includable in assembly files.

#if defined(__x86_64__)

#define ZX_TLS_STACK_GUARD_OFFSET       0x10
#define ZX_TLS_UNSAFE_SP_OFFSET         0x18

#elif defined(__aarch64__)

#define ZX_TLS_STACK_GUARD_OFFSET       (-0x10)
#define ZX_TLS_UNSAFE_SP_OFFSET         (-0x8)

#else

#error what architecture?

#endif

#endif // ZIRCON_TLS_


<|start_filename|>arch/x64/sysroot/include/sys/sem.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>

#define __NEED_size_t
#define __NEED_pid_t
#define __NEED_time_t
#ifdef _GNU_SOURCE
#define __NEED_struct_timespec
#endif
#include <bits/alltypes.h>

#include <sys/ipc.h>

#define SEM_UNDO 0x1000
#define GETPID 11
#define GETVAL 12
#define GETALL 13
#define GETNCNT 14
#define GETZCNT 15
#define SETVAL 16
#define SETALL 17

#include <endian.h>

#include <bits/sem.h>

#define _SEM_SEMUN_UNDEFINED 1

#define SEM_STAT 18
#define SEM_INFO 19

struct seminfo {
    int semmap;
    int semmni;
    int semmns;
    int semmnu;
    int semmsl;
    int semopm;
    int semume;
    int semusz;
    int semvzx;
    int semaem;
};

struct sembuf {
    unsigned short sem_num;
    short sem_op;
    short sem_flg;
};

int semctl(int, int, int, ...);
int semget(key_t, int, int);
int semop(int, struct sembuf*, size_t);

#ifdef _GNU_SOURCE
int semtimedop(int, struct sembuf*, size_t, const struct timespec*);
#endif

#ifdef __cplusplus
}
#endif


<|start_filename|>dart/fuchsia_modular/lib/src/module/internal/_intent_handler_impl.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:fidl/fidl.dart';
import 'package:fidl_fuchsia_modular/fidl_async.dart' as fidl;
import 'package:fuchsia_services/services.dart';
import 'package:fuchsia_modular/lifecycle.dart';

import '../intent.dart';
import '_fidl_transformers.dart';

/// A concrete implementation of the [fidl.IntentHandler] interface.
/// This class not intended to be used directly by authors but instead should
/// be used by classes which need to expose the [fidl.IntentHandler] interface
/// and forward intents to handlers. See the Module class for an example of
/// this in practice.
///
/// Note: This class must be exposed to the framework before it attempts to
/// call handle intent or there is a risk of missing intents.
class IntentHandlerImpl extends fidl.IntentHandler {
  fidl.IntentHandlerBinding _intentHandlerBinding;

  /// A function which is invoked when the host receives a [handleIntent] call.
  void Function(Intent intent) onHandleIntent;

  /// The constructor for the [IntentHandlerImpl].
  /// The [startupContext] is an optional parameter that will
  /// default to using [StartupContext.fromStartupInfo] if not present.
  IntentHandlerImpl({StartupContext startupContext}) {
    _exposeService(startupContext ?? StartupContext.fromStartupInfo());
    Lifecycle().addTerminateListener(_terminate);
  }

  // Note: this method needs to run before the first iteration of
  // the event loop or the framework will not bind to it.
  @override
  Future<void> handleIntent(fidl.Intent intent) async {
    if (onHandleIntent == null) {
      return null;
    }
    // convert to the non-fidl intent.
    onHandleIntent(convertFidlIntentToIntent(intent));
  }

  void _clearBinding() {
    if (_intentHandlerBinding != null && _intentHandlerBinding.isBound) {
      _intentHandlerBinding.unbind();
      _intentHandlerBinding = null;
    }
  }

  // any necessary cleanup should be done in this method.
  void _exposeService(StartupContext startupContext) {
    startupContext.outgoingServices.addServiceForName(
      (InterfaceRequest<fidl.IntentHandler> request) {
        _clearBinding();
        _intentHandlerBinding = fidl.IntentHandlerBinding()
          ..bind(this, request);
      },
      fidl.IntentHandler.$serviceName,
    );
  }

  Future<void> _terminate() async {
    _clearBinding();
    onHandleIntent = null;
  }
}


<|start_filename|>arch/x64/sysroot/include/err.h<|end_filename|>
#pragma once

#include <features.h>
#include <stdarg.h>

#ifdef __cplusplus
extern "C" {
#endif

void warn(const char*, ...);
void vwarn(const char*, va_list);
void warnx(const char*, ...);
void vwarnx(const char*, va_list);

_Noreturn void err(int, const char*, ...);
_Noreturn void verr(int, const char*, va_list);
_Noreturn void errx(int, const char*, ...);
_Noreturn void verrx(int, const char*, va_list);

#ifdef __cplusplus
}
#endif


<|start_filename|>dart/fuchsia_modular/lib/src/agent/agent_task_handler.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: one_member_abstracts

/// The [AgentTaskHandler] class is an abstract class which is intended to be
/// extended by agent authors to handle incoming tasks. The class is intended to
/// be registered with the [Agent] class inside of the agent's main method.
abstract class AgentTaskHandler {
  /// Called when some task identified by [taskId] is scheduled to run. The task
  /// was first posted by agent using [Agent.scheduleTask(...)].
  ///
  /// The future will complete when all work related to this task is completed.
  /// Note that the framework may call [Lifecycle.Terminate()] before this
  /// method returns.
  Future<void> runTask(String taskId);
}

<|start_filename|>arch/x64/sysroot/include/threads.h<|end_filename|>
#pragma once

#include <features.h>
#include <time.h>

#ifdef __cplusplus
extern "C" {
typedef unsigned long thrd_t;
#else
typedef struct __pthread* thrd_t;
#define thread_local _Thread_local
#endif

typedef unsigned tss_t;
typedef int (*thrd_start_t)(void*);
typedef void (*tss_dtor_t)(void*);

#define __NEED_cnd_t
#define __NEED_mtx_t
#define __NEED_once_flag

#include <bits/alltypes.h>

#define TSS_DTOR_ITERATIONS 4

enum {
    thrd_success = 0,
    thrd_busy = 1,
    thrd_error = 2,
    thrd_nomem = 3,
    thrd_timedout = 4,
};

// These are bitfield values; initialize with e.g. (mtx_plain|mtx_timed).
// mtx_recursive is not implemented.
enum {
    mtx_plain = 0,
    mtx_recursive = 1,
    mtx_timed = 2,
};

#ifdef _ALL_SOURCE
#define MTX_INIT \
    {}
#define CND_INIT \
    {}
#endif

#define ONCE_FLAG_INIT 0

int thrd_create(thrd_t*, thrd_start_t, void*);
#ifdef _ALL_SOURCE
// |name| is silently truncated to a maximum of ZX_MAX_NAME_LEN-1 characters.
int thrd_create_with_name(thrd_t*, thrd_start_t, void*, const char* name);
#endif
_Noreturn void thrd_exit(int);

int thrd_detach(thrd_t);
int thrd_join(thrd_t, int*);

int thrd_sleep(const struct timespec*, struct timespec*);
void thrd_yield(void);

thrd_t thrd_current(void);
int thrd_equal(thrd_t, thrd_t);
#ifndef __cplusplus
#define thrd_equal(A, B) ((A) == (B))
#endif

void call_once(once_flag*, void (*)(void));

int mtx_init(mtx_t*, int);
void mtx_destroy(mtx_t*);

int mtx_lock(mtx_t* __m)
#ifdef __clang__
    __attribute__((__acquire_capability__(__m)))
#endif
;
int mtx_timedlock(mtx_t* __restrict, const struct timespec* __restrict);
int mtx_trylock(mtx_t*);
int mtx_unlock(mtx_t* __m)
#ifdef __clang__
    __attribute__((__release_capability__(__m)))
#endif
;

int cnd_init(cnd_t*);
void cnd_destroy(cnd_t*);

int cnd_broadcast(cnd_t*);
int cnd_signal(cnd_t*);

int cnd_timedwait(cnd_t* __restrict, mtx_t* __restrict, const struct timespec* __restrict);
int cnd_wait(cnd_t*, mtx_t*);

int tss_create(tss_t*, tss_dtor_t);
void tss_delete(tss_t key);

int tss_set(tss_t, void*);
void* tss_get(tss_t);

#ifdef __cplusplus
}
#endif


<|start_filename|>arch/x64/sysroot/include/zircon/hw/gpt.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

#include <stdbool.h>
#include <stdint.h>

#include <zircon/compiler.h>

#define GPT_MAGIC (0x5452415020494645ull) // 'EFI PART'
#define GPT_HEADER_SIZE 0x5c
#define GPT_ENTRY_SIZE  0x80
#define GPT_GUID_LEN 16
#define GPT_GUID_STRLEN 37
#define GPT_NAME_LEN 72

typedef struct gpt_header {
    uint64_t magic;
    uint32_t revision;
    uint32_t size;
    uint32_t crc32;
    uint32_t reserved0;
    uint64_t current;
    uint64_t backup;
    uint64_t first;
    uint64_t last;
    uint8_t guid[GPT_GUID_LEN];
    uint64_t entries;
    uint32_t entries_count;
    uint32_t entries_size;
    uint32_t entries_crc;
} __PACKED gpt_header_t;

typedef struct gpt_entry {
    uint8_t type[GPT_GUID_LEN];
    uint8_t guid[GPT_GUID_LEN];
    uint64_t first;
    uint64_t last;
    uint64_t flags;
    uint8_t name[GPT_NAME_LEN];  // UTF-16 on disk
} __PACKED gpt_entry_t;

#define GUID_EMPTY_VALUE {                         \
    0x00, 0x00, 0x00, 0x00,                        \
    0x00, 0x00,                                    \
    0x00, 0x00,                                    \
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 \
}

#define GUID_EFI_VALUE {                           \
    0x28, 0x73, 0x2a, 0xc1,                        \
    0x1f, 0xf8,                                    \
    0xd2, 0x11,                                    \
    0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b \
}

// GUID for a system partition
#define GUID_SYSTEM_STRING "606B000B-B7C7-4653-A7D5-B737332C899D"
#define GUID_SYSTEM_VALUE {                        \
    0x0b, 0x00, 0x6b, 0x60,                        \
    0xc7, 0xb7,                                    \
    0x53, 0x46,                                    \
    0xa7, 0xd5, 0xb7, 0x37, 0x33, 0x2c, 0x89, 0x9d \
}

// GUID for a data partition
#define GUID_DATA_STRING "08185F0C-892D-428A-A789-DBEEC8F55E6A"
#define GUID_DATA_VALUE {                          \
    0x0c, 0x5f, 0x18, 0x08,                        \
    0x2d, 0x89,                                    \
    0x8a, 0x42,                                    \
    0xa7, 0x89, 0xdb, 0xee, 0xc8, 0xf5, 0x5e, 0x6a \
}

// GUID for a installer partition
#define GUID_INSTALL_STRING "48435546-4953-2041-494E-5354414C4C52"
#define GUID_INSTALL_VALUE {                       \
    0x46, 0x55, 0x43, 0x48,                        \
    0x53, 0x49,                                    \
    0x41, 0x20,                                    \
    0x49, 0x4E, 0x53, 0x54, 0x41, 0x4C, 0x4C, 0x52 \
}

#define GUID_BLOB_STRING "2967380E-134C-4CBB-B6DA-17E7CE1CA45D"
#define GUID_BLOB_VALUE {                          \
    0x0e, 0x38, 0x67, 0x29,                        \
    0x4c, 0x13,                                    \
    0xbb, 0x4c,                                    \
    0xb6, 0xda, 0x17, 0xe7, 0xce, 0x1c, 0xa4, 0x5d \
}

#define GUID_FVM_STRING "41D0E340-57E3-954E-8C1E-17ECAC44CFF5"
#define GUID_FVM_VALUE {                           \
    0x40, 0xe3, 0xd0, 0x41,                        \
    0xe3, 0x57,                                    \
    0x4e, 0x95,                                    \
    0x8c, 0x1e, 0x17, 0xec, 0xac, 0x44, 0xcf, 0xf5 \
}

#define GUID_ZIRCON_A_STRING "DE30CC86-1F4A-4A31-93C4-66F147D33E05"
#define GUID_ZIRCON_A_VALUE { \
    0x86, 0xcc, 0x30, 0xde, \
    0x4a, 0x1f, \
    0x31, 0x4a, \
    0x93, 0xc4, 0x66, 0xf1, 0x47, 0xd3, 0x3e, 0x05, \
}

#define GUID_ZIRCON_B_STRING "23CC04DF-C278-4CE7-8471-897D1A4BCDF7"
#define GUID_ZIRCON_B_VALUE { \
    0xdf, 0x04, 0xcc, 0x23, \
    0x78, 0xc2, \
    0xe7, 0x4c, \
    0x84, 0x71, 0x89, 0x7d, 0x1a, 0x4b, 0xcd, 0xf7 \
}

#define GUID_ZIRCON_R_STRING "A0E5CF57-2DEF-46BE-A80C-A2067C37CD49"
#define GUID_ZIRCON_R_VALUE { \
    0x57, 0xcf, 0xe5, 0xa0, \
    0xef, 0x2d, \
    0xbe, 0x46, \
    0xa8, 0x0c, 0xa2, 0x06, 0x7c, 0x37, 0xcd, 0x49 \
}

#define GUID_SYS_CONFIG_STRING "4E5E989E-4C86-11E8-A15B-480FCF35F8E6"
#define GUID_SYS_CONFIG_VALUE { \
    0x9e, 0x98, 0x5e, 0x4e,                        \
    0x86, 0x4c,                                    \
    0xe8, 0x11,                                    \
    0xa1, 0x5b, 0x48, 0x0f, 0xcf, 0x35, 0xf8, 0xe6 \
}

#define GUID_FACTORY_CONFIG_STRING "5A3A90BE-4C86-11E8-A15B-480FCF35F8E6"
#define GUID_FACTORY_CONFIG_VALUE { \
    0xbe, 0x90, 0x3a, 0x5a,                        \
    0x86, 0x4c,                                    \
    0xe8, 0x11,                                    \
    0xa1, 0x5b, 0x48, 0x0f, 0xcf, 0x35, 0xf8, 0xe6 \
}

#define GUID_BOOTLOADER_STRING "5ECE94FE-4C86-11E8-A15B-480FCF35F8E6"
#define GUID_BOOTLOADER_VALUE { \
    0xfe, 0x94, 0xce, 0x5e,                        \
    0x86, 0x4c,                                    \
    0xe8, 0x11,                                    \
    0xa1, 0x5b, 0x48, 0x0f, 0xcf, 0x35, 0xf8, 0xe6 \
}

#define GUID_TEST_STRING "8B94D043-30BE-4871-9DFA-D69556E8C1F3"
#define GUID_TEST_VALUE { \
    0x43, 0xD0, 0x94, 0x8b,                        \
    0xbe, 0x30,                                    \
    0x71, 0x38,                                    \
    0x9d, 0xfa, 0xd6, 0x95, 0x56, 0xe8, 0xc1, 0xf3 \
}

#define GUID_VBMETA_A_STRING "A13B4D9A-EC5F-11E8-97D8-6C3BE52705BF"
#define GUID_VBMETA_A_VALUE { \
    0x9a, 0x4d, 0x3b, 0xa1,                        \
    0x5f, 0xec,                                    \
    0xd8, 0x97,                                    \
    0x6c, 0x3b, 0x6c, 0x3b, 0xe2, 0x27, 0x05, 0xbf \
}

#define GUID_VBMETA_B_STRING "A288ABF2-EC5F-11E8-97D8-6C3BE52705BF"
#define GUID_VBMETA_B_VALUE { \
    0xf2, 0xab, 0x88, 0xa2,                        \
    0x5f, 0xec,                                    \
    0xd8, 0x97,                                    \
    0x6c, 0x3b, 0x6c, 0x3b, 0xe2, 0x27, 0x05, 0xbf \
}


<|start_filename|>arch/x64/sysroot/include/zircon/time.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT

#pragma once

#include <zircon/compiler.h>
#include <zircon/types.h>

// These functions perform overflow-safe time arithmetic, clamping to ZX_TIME_INFINITE in case of
// overflow and ZX_TIME_INFINITE_PAST in case of underflow.
//
// C++ code should use zx::time and zx::duration instead.
//
// The naming scheme is zx_<first argument>_<operation>_<second argument>.
//
// TODO(maniscalco): Consider expanding the set of operations to include division, modulo, unit
// conversion, and floating point math.

__CONSTEXPR static inline zx_time_t zx_time_add_duration(zx_time_t time, zx_duration_t duration) {
    zx_time_t x = 0;
    if (unlikely(add_overflow(time, duration, &x))) {
        if (x >= 0) {
            return ZX_TIME_INFINITE_PAST;
        } else {
            return ZX_TIME_INFINITE;
        }
    }
    return x;
}

__CONSTEXPR static inline zx_time_t zx_time_sub_duration(zx_time_t time, zx_duration_t duration) {
    zx_time_t x = 0;
    if (unlikely(sub_overflow(time, duration, &x))) {
        if (x >= 0) {
            return ZX_TIME_INFINITE_PAST;
        } else {
            return ZX_TIME_INFINITE;
        }

    }
    return x;
}

__CONSTEXPR static inline zx_duration_t zx_time_sub_time(zx_time_t time1, zx_time_t time2) {
    zx_duration_t x = 0;
    if (unlikely(sub_overflow(time1, time2, &x))) {
        if (x >= 0) {
            return ZX_TIME_INFINITE_PAST;
        } else {
            return ZX_TIME_INFINITE;
        }
    }
    return x;
}

__CONSTEXPR static inline zx_duration_t zx_duration_add_duration(zx_duration_t dur1,
                                                                 zx_duration_t dur2) {
    zx_duration_t x = 0;
    if (unlikely(add_overflow(dur1, dur2, &x))) {
        if (x >= 0) {
            return ZX_TIME_INFINITE_PAST;
        } else {
            return ZX_TIME_INFINITE;
        }
    }
    return x;
}

__CONSTEXPR static inline zx_duration_t zx_duration_sub_duration(zx_duration_t dur1,
                                                                 zx_duration_t dur2) {
    zx_duration_t x = 0;
    if (unlikely(sub_overflow(dur1, dur2, &x))) {
        if (x >= 0) {
            return ZX_TIME_INFINITE_PAST;
        } else {
            return ZX_TIME_INFINITE;
        }
    }
    return x;
}

__CONSTEXPR static inline zx_duration_t zx_duration_mul_int64(zx_duration_t duration,
                                                              int64_t multiplier) {
    zx_duration_t x = 0;
    if (unlikely(mul_overflow(duration, multiplier, &x))) {
        if ((duration > 0 && multiplier > 0) || (duration < 0 && multiplier < 0)) {
            return ZX_TIME_INFINITE;
        } else {
            return ZX_TIME_INFINITE_PAST;
        }
    }
    return x;
}


<|start_filename|>arch/x64/sysroot/include/fmtmsg.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#define MM_HARD 1
#define MM_SOFT 2
#define MM_FIRM 4

#define MM_APPL 8
#define MM_UTIL 16
#define MM_OPSYS 32

#define MM_RECOVER 64
#define MM_NRECOV 128

#define MM_PRINT 256
#define MM_CONSOLE 512

#define MM_NULLMC 0L

#define MM_HALT 1
#define MM_ERROR 2
#define MM_WARNING 3
#define MM_INFO 4
#define MM_NOSEV 0

#define MM_OK 0
#define MM_NOTOK (-1)
#define MM_NOMSG 1
#define MM_NOCON 4

#define MM_NULLLBL ((char*)0)
#define MM_NULLTXT ((char*)0)
#define MM_NULLACT ((char*)0)
#define MM_NULLTAG ((char*)0)
#define MM_NULLSEV 0

int fmtmsg(long, const char*, int, const char*, const char*, const char*);

#ifdef __cplusplus
}
#endif


<|start_filename|>pkg/fidl_cpp_base/include/lib/fidl/cpp/clone.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIDL_CPP_CLONE_H_
#define LIB_FIDL_CPP_CLONE_H_

#include <lib/fidl/cpp/array.h>
#include <zircon/assert.h>
#include <memory>
#include "lib/fidl/cpp/string.h"
#include "lib/fidl/cpp/traits.h"
#include "lib/fidl/cpp/vector.h"

namespace fidl {

#ifdef __Fuchsia__
namespace internal {

template <typename T>
inline typename std::enable_if<zx::object_traits<T>::supports_duplication,
                               zx_status_t>::type
CloneKernelObject(const zx::object<T>& object, zx::object<T>* result) {
  return object.duplicate(ZX_RIGHT_SAME_RIGHTS, result);
}

template <typename T>
inline typename std::enable_if<!zx::object_traits<T>::supports_duplication,
                               zx_status_t>::type
CloneKernelObject(const zx::object<T>& object, zx::object<T>* result) {
  return ZX_ERR_ACCESS_DENIED;
}

}  // namespace internal
#endif  // __Fuchsia__

// Deep copies the contents of |value| into |result|.
// This operation also attempts to duplicate any handles the value contains.
//
// Returns an error if the value could not be cloned, perhaps because a
// handle was not duplicable.
//
// There are many overloads of this function with the following signature:
//   zx_status_t Clone(const T& value, T* result);
template <typename T>
inline typename std::enable_if<IsPrimitive<T>::value, zx_status_t>::type Clone(
    const T& value, T* result) {
  *result = value;
  return ZX_OK;
}

template <typename T>
inline
#ifdef __Fuchsia__
    typename std::enable_if<!IsPrimitive<T>::value &&
                                !std::is_base_of<zx::object_base, T>::value,
                            zx_status_t>::type
#else   // __Fuchsia__
    typename std::enable_if<!IsPrimitive<T>::value, zx_status_t>::type
#endif  // __Fuchsia__
    Clone(const T& value, T* result) {
  return value.Clone(result);
}

#ifdef __Fuchsia__
template <typename T>
zx_status_t Clone(const zx::object<T>& value, zx::object<T>* result) {
  if (!value) {
    result->reset();
    return ZX_OK;
  }
  return internal::CloneKernelObject(value, result);
}
#endif  // __Fuchsia__

template <typename T>
inline zx_status_t Clone(const std::unique_ptr<T>& value,
                         std::unique_ptr<T>* result) {
  if (!value) {
    result->reset();
    return ZX_OK;
  }
  *result = std::make_unique<T>();
  return Clone(*value, result->get());
}

template <typename T>
inline typename std::enable_if<!IsPrimitive<T>::value, zx_status_t>::type Clone(
    const VectorPtr<T>& value, VectorPtr<T>* result) {
  if (!value) {
    *result = VectorPtr<T>();
    return ZX_OK;
  }
  result->resize(value->size());
  for (size_t i = 0; i < value->size(); ++i) {
    zx_status_t status = Clone(value->at(i), &(*result)->at(i));
    if (status != ZX_OK)
      return status;
  }
  return ZX_OK;
}

template <typename T>
inline typename std::enable_if<IsPrimitive<T>::value, zx_status_t>::type Clone(
    const VectorPtr<T>& value, VectorPtr<T>* result) {
  if (!value) {
    *result = VectorPtr<T>();
    return ZX_OK;
  }
  result->reset(*value);
  return ZX_OK;
}

template <typename T, size_t N>
inline zx_status_t Clone(const Array<T, N>& value, Array<T, N>* result) {
  for (size_t i = 0; i < N; ++i) {
    zx_status_t status = Clone(value[i], &result->at(i));
    if (status != ZX_OK)
      return status;
  }
  return ZX_OK;
}

zx_status_t Clone(const StringPtr& value, StringPtr* result);

// Returns a deep copy of |value|.
// This operation also attempts to duplicate any handles the value contains.
//
// Crashes the program if the value could not be cloned, perhaps because a
// handle was not duplicable.
template <typename T>
inline T Clone(const T& value) {
  T clone;
  zx_status_t status = Clone(value, &clone);
  ZX_ASSERT(status == ZX_OK);
  return clone;
}

}  // namespace fidl

#endif  // LIB_FIDL_CPP_CODING_TRAITS_H_


<|start_filename|>arch/x64/sysroot/include/sys/uio.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>

#define __NEED_size_t
#define __NEED_ssize_t
#define __NEED_struct_iovec

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#define __NEED_off_t
#endif

#include <bits/alltypes.h>

#define UIO_MAXIOV 1024

ssize_t readv(int, const struct iovec*, int);
ssize_t writev(int, const struct iovec*, int);

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
ssize_t preadv(int, const struct iovec*, int, off_t);
ssize_t pwritev(int, const struct iovec*, int, off_t);
#endif

#ifdef __cplusplus
}
#endif


<|start_filename|>dart/fuchsia_modular/lib/src/module/module.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:fidl_fuchsia_modular/fidl_async.dart' as fidl;
import 'package:fuchsia_services/services.dart';
import 'package:meta/meta.dart';

import 'embedded_module.dart';
import 'intent_handler.dart';
import 'internal/_intent_handler_impl.dart';
import 'internal/_module_impl.dart';

/// The [Module] class provides a mechanism for module authors
/// to interact with the underlying framework. The main responsibilities
/// of the [Module] class are to implement the intent handler
/// interface and the lifecycle interface.
abstract class Module {
  static Module _module;

  /// returns a shared instance of this.
  factory Module() {
    return _module ??= ModuleImpl(
      intentHandlerImpl:
          IntentHandlerImpl(startupContext: StartupContext.fromStartupInfo()),
    );
  }

  /// Starts a new Module instance and adds it to the story. The Module to
  /// execute is identified by the contents of [intent] and the Module instance
  /// is given a [name] in the scope of the starting Module instance. The view
  /// for the Module is given to the StoryShell for display.
  ///
  /// Providing a [surfaceRelation] advises the StoryShell on how to layout
  /// surfaces that the new module creates. If [surfaceRelation] is `null` then
  /// a default relation is used. Note, [surfaceRelation] is an optional
  /// parameter so a default value will be provided:
  /// ```
  /// fidl.SurfaceRelation surfaceRelation = const fidl.SurfaceRelation(
  ///    arrangement: fidl.SurfaceArrangement.copresent,
  ///    dependency: fidl.SurfaceDependency.dependent,
  ///    emphasis: 0.5,
  /// )
  ///```
  ///
  /// If this method is called again with the same [name] by the same Module
  /// instance, but with different arguments, a new module will be started and
  /// replace the existing one (the ModuleController of the existing module will
  /// be closed). If the [intent] is resolved to the same module, the module
  /// will get the intent.
  ///
  /// A [fidl.ModuleController] is returned to the caller to control the start
  /// Module instance. Closing this connection doesn't affect its Module
  /// instance; it just relinquishes the ability of the caller to control the
  /// Module instance.
  ///
  /// The [name] parameter can be used identify a view in the resulting story
  /// and can be used to either update a running module with a new [intent] or
  /// can be used to replace an existing module in the same space if the intent
  /// resolves to a new module instance.
  /// ```
  /// // This code will result in one view being displayed on
  /// // screen with either one module receiving two intents if the
  /// // intents resolve to the same module binaries or one module
  /// // being started and then torn down to start a new module.
  /// Module().addModuleToStory(name: 'foo', intent: foo_intent);
  /// Module().addModuleToStory(name: 'foo', intent: bar_intent);
  /// ```
  ///
  /// ```
  /// // This code will result in two views being displayed on
  /// // screen. They may be the same binary but two different processes
  /// // or they may be two binaries depending on how what modules
  /// // are resolved.
  /// Module().addModuleToStory(name: 'foo', intent: foo_intent);
  /// Module().addModuleToStory(name: 'bar', intent: bar_intent);
  /// ```
  Future<fidl.ModuleController> addModuleToStory({
    @required String name,
    @required fidl.Intent intent,
    fidl.SurfaceRelation surfaceRelation,
  });

  /// This method functions similarly to [addModuleToStory()], but instead
  /// of relying on the story shell for display it is up to the caller to
  /// display the view from the new module.
  ///
  /// The method will complete with an [EmbeddedModule] which contains the
  /// [fidl.ModuleController] and the [InterfaceHandle<views_fidl.ViewOwner>].
  /// The view owner handle can be used to create view to display in your
  /// module's view hierarchy. This is commonly done in Flutter modules with
  /// the ChildView widget.
  ///
  /// If no modules are found a [ModuleResolutionException] will be thrown.
  @experimental
  Future<EmbeddedModule> embedModule({
    @required String name,
    @required fidl.Intent intent,
  });

  /// Registers the [intentHandler] with this.
  ///
  /// This method must be called in the main function of the module
  /// so the framework has a chance to connect the intent handler.
  ///
  /// ```
  /// void main(List<String> args) {
  ///   Module()
  ///     ..registerIntentHandler(MyHandler());
  /// }
  /// ```
  void registerIntentHandler(IntentHandler intentHandler);

  /// Requests that the current story and module gain focus. It's up to the
  /// story shell and session shell to honor that request.
  void requestFocus();

  /// When [RemoveSelfFromStory()] is called the framework will stop the
  /// module and remove it from the story. If there are no more running modules
  /// in the story the story will be stopped.
  void removeSelfFromStory();

}


<|start_filename|>arch/x64/sysroot/include/netinet/tcp.h<|end_filename|>
#pragma once

#include <features.h>

#define TCP_NODELAY 1
#define TCP_MAXSEG 2
#define TCP_CORK 3
#define TCP_KEEPIDLE 4
#define TCP_KEEPINTVL 5
#define TCP_KEEPCNT 6
#define TCP_SYNCNT 7
#define TCP_LINGER2 8
#define TCP_DEFER_ACCEPT 9
#define TCP_WINDOW_CLAMP 10
#define TCP_INFO 11
#define TCP_QUICKACK 12
#define TCP_CONGESTION 13
#define TCP_MD5SIG 14
#define TCP_THIN_LINEAR_TIMEOUTS 16
#define TCP_THIN_DUPACK 17
#define TCP_USER_TIMEOUT 18
#define TCP_REPAIR 19
#define TCP_REPAIR_QUEUE 20
#define TCP_QUEUE_SEQ 21
#define TCP_REPAIR_OPTIONS 22
#define TCP_FASTOPEN 23
#define TCP_TIMESTAMP 24
#define TCP_NOTSENT_LOWAT 25
#define TCP_CC_INFO 26
#define TCP_SAVE_SYN 27
#define TCP_SAVED_SYN 28

#define TCP_ESTABLISHED 1
#define TCP_SYN_SENT 2
#define TCP_SYN_RECV 3
#define TCP_FIN_WAIT1 4
#define TCP_FIN_WAIT2 5
#define TCP_TIME_WAIT 6
#define TCP_CLOSE 7
#define TCP_CLOSE_WAIT 8
#define TCP_LAST_ACK 9
#define TCP_LISTEN 10
#define TCP_CLOSING 11

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#define TCPOPT_EOL 0
#define TCPOPT_NOP 1
#define TCPOPT_MAXSEG 2
#define TCPOPT_WINDOW 3
#define TCPOPT_SACK_PERMITTED 4
#define TCPOPT_SACK 5
#define TCPOPT_TIMESTAMP 8
#define TCPOLEN_SACK_PERMITTED 2
#define TCPOLEN_WINDOW 3
#define TCPOLEN_MAXSEG 4
#define TCPOLEN_TIMESTAMP 10

#define SOL_TCP 6

#include <endian.h>
#include <stdint.h>
#include <sys/socket.h>
#include <sys/types.h>

typedef uint32_t tcp_seq;

#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PUSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20

struct tcphdr {
#ifdef _GNU_SOURCE
#ifdef __GNUC__
    __extension__
#endif
        union {
        struct {

            uint16_t source;
            uint16_t dest;
            uint32_t seq;
            uint32_t ack_seq;
#if __BYTE_ORDER == __LITTLE_ENDIAN
            uint16_t res1 : 4;
            uint16_t doff : 4;
            uint16_t fin : 1;
            uint16_t syn : 1;
            uint16_t rst : 1;
            uint16_t psh : 1;
            uint16_t ack : 1;
            uint16_t urg : 1;
            uint16_t res2 : 2;
#else
            uint16_t doff : 4;
            uint16_t res1 : 4;
            uint16_t res2 : 2;
            uint16_t urg : 1;
            uint16_t ack : 1;
            uint16_t psh : 1;
            uint16_t rst : 1;
            uint16_t syn : 1;
            uint16_t fin : 1;
#endif
            uint16_t window;
            uint16_t check;
            uint16_t urg_ptr;
        };
        struct {
#endif

            uint16_t th_sport;
            uint16_t th_dport;
            uint32_t th_seq;
            uint32_t th_ack;
#if __BYTE_ORDER == __LITTLE_ENDIAN
            uint8_t th_x2 : 4;
            uint8_t th_off : 4;
#else
    uint8_t th_off : 4;
    uint8_t th_x2 : 4;
#endif
            uint8_t th_flags;
            uint16_t th_win;
            uint16_t th_sum;
            uint16_t th_urp;

#ifdef _GNU_SOURCE
        };
    };
#endif
};
#endif

#ifdef _GNU_SOURCE
#define TCPI_OPT_TIMESTAMPS 1
#define TCPI_OPT_SACK 2
#define TCPI_OPT_WSCALE 4
#define TCPI_OPT_ECN 8

#define TCP_CA_Open 0
#define TCP_CA_Disorder 1
#define TCP_CA_CWR 2
#define TCP_CA_Recovery 3
#define TCP_CA_Loss 4

struct tcp_info {
    uint8_t tcpi_state;
    uint8_t tcpi_ca_state;
    uint8_t tcpi_retransmits;
    uint8_t tcpi_probes;
    uint8_t tcpi_backoff;
    uint8_t tcpi_options;
    uint8_t tcpi_snd_wscale : 4, tcpi_rcv_wscale : 4;
    uint32_t tcpi_rto;
    uint32_t tcpi_ato;
    uint32_t tcpi_snd_mss;
    uint32_t tcpi_rcv_mss;
    uint32_t tcpi_unacked;
    uint32_t tcpi_sacked;
    uint32_t tcpi_lost;
    uint32_t tcpi_retrans;
    uint32_t tcpi_fackets;
    uint32_t tcpi_last_data_sent;
    uint32_t tcpi_last_ack_sent;
    uint32_t tcpi_last_data_recv;
    uint32_t tcpi_last_ack_recv;
    uint32_t tcpi_pmtu;
    uint32_t tcpi_rcv_ssthresh;
    uint32_t tcpi_rtt;
    uint32_t tcpi_rttvar;
    uint32_t tcpi_snd_ssthresh;
    uint32_t tcpi_snd_cwnd;
    uint32_t tcpi_advmss;
    uint32_t tcpi_reordering;
    uint32_t tcpi_rcv_rtt;
    uint32_t tcpi_rcv_space;
    uint32_t tcpi_total_retrans;
    uint64_t tcpi_pacing_rate;
    uint64_t tcpi_max_pacing_rate;
    uint64_t tcpi_bytes_acked;
    uint64_t tcpi_bytes_received;
    uint32_t tcpi_segs_out;
    uint32_t tcpi_segs_in;
};

#define TCP_MD5SIG_MAXKEYLEN 80

struct tcp_md5sig {
    struct sockaddr_storage tcpm_addr;
    uint16_t __tcpm_pad1;
    uint16_t tcpm_keylen;
    uint32_t __tcpm_pad2;
    uint8_t tcpm_key[TCP_MD5SIG_MAXKEYLEN];
};

#endif


<|start_filename|>arch/x64/sysroot/include/ar.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#define ARMAG "!<arch>\n"
#define SARMAG 8
#define ARFMAG "`\n"

struct ar_hdr {
    char ar_name[16];
    char ar_date[12];
    char ar_uid[6], ar_gid[6];
    char ar_mode[8];
    char ar_size[10];
    char ar_fmag[2];
};

#ifdef __cplusplus
}
#endif


<|start_filename|>arch/x64/sysroot/include/sys/mman.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>

#define __NEED_mode_t
#define __NEED_size_t
#define __NEED_off_t

#include <bits/alltypes.h>

#define MAP_FAILED ((void*)-1)

#define MAP_SHARED 0x01
#define MAP_PRIVATE 0x02
#define MAP_TYPE 0x0f
#define MAP_FIXED 0x10
#define MAP_ANON 0x20
#define MAP_ANONYMOUS MAP_ANON
#define MAP_NORESERVE 0x4000
#define MAP_GROWSDOWN 0x0100
#define MAP_DENYWRITE 0x0800
#define MAP_EXECUTABLE 0x1000
#define MAP_LOCKED 0x2000
#define MAP_POPULATE 0x8000
#define MAP_NONBLOCK 0x10000
#define MAP_STACK 0x20000
#define MAP_HUGETLB 0x40000
#define MAP_FILE 0

#define PROT_NONE 0
#define PROT_READ 1
#define PROT_WRITE 2
#define PROT_EXEC 4
#define PROT_GROWSDOWN 0x01000000
#define PROT_GROWSUP 0x02000000

#define MS_ASYNC 1
#define MS_INVALIDATE 2
#define MS_SYNC 4

#define MCL_CURRENT 1
#define MCL_FUTURE 2
#define MCL_ONFAULT 4

#define POSIX_MADV_NORMAL 0
#define POSIX_MADV_RANDOM 1
#define POSIX_MADV_SEQUENTIAL 2
#define POSIX_MADV_WILLNEED 3
#define POSIX_MADV_DONTNEED 4

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#define MADV_NORMAL 0
#define MADV_RANDOM 1
#define MADV_SEQUENTIAL 2
#define MADV_WILLNEED 3
#define MADV_DONTNEED 4
#define MADV_FREE 8
#define MADV_REMOVE 9
#define MADV_DONTFORK 10
#define MADV_DOFORK 11
#define MADV_MERGEABLE 12
#define MADV_UNMERGEABLE 13
#define MADV_HUGEPAGE 14
#define MADV_NOHUGEPAGE 15
#define MADV_DONTDUMP 16
#define MADV_DODUMP 17
#define MADV_HWPOISON 100
#define MADV_SOFT_OFFLINE 101
#endif

void* mmap(void*, size_t, int, int, int, off_t);
int munmap(void*, size_t);

int mprotect(void*, size_t, int);
int msync(void*, size_t, int);

int posix_madvise(void*, size_t, int);

int mlock(const void*, size_t);
int munlock(const void*, size_t);
int mlockall(int);
int munlockall(void);

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#define MLOCK_ONFAULT 0x01
int madvise(void*, size_t, int);
#endif

int shm_open(const char*, int, mode_t);
int shm_unlink(const char*);

#ifdef __cplusplus
}
#endif


<|start_filename|>dart/fuchsia_modular/lib/src/lifecycle/lifecycle.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'internal/_lifecycle_impl.dart';

/// Allows running components to be notified when lifecycle events happen in the
/// system.
abstract class Lifecycle {
  static Lifecycle _lifecycle;

  /// Initializes the shared [Lifecycle] instance
  factory Lifecycle() {
    return _lifecycle ??= LifecycleImpl();
  }

  /// Adds a terminate [listener] which will be called when the system starts to
  /// shutdown this process. Returns `false` if this listener was already added.
  bool addTerminateListener(Future<void> Function() listener);
}


<|start_filename|>pkg/zx/include/lib/zx/log.h<|end_filename|>
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_ZX_LOG_H_
#define LIB_ZX_LOG_H_

#include <lib/zx/handle.h>
#include <lib/zx/object.h>

namespace zx {

class log : public object<log> {
public:
    static constexpr zx_obj_type_t TYPE = ZX_OBJ_TYPE_LOG;

    constexpr log() = default;

    explicit log(zx_handle_t value) : object(value) {}

    explicit log(handle&& h) : object(h.release()) {}

    log(log&& other) : object(other.release()) {}

    log& operator=(log&& other) {
        reset(other.release());
        return *this;
    }

    static zx_status_t create(uint32_t flags, log* result);

    zx_status_t write(uint32_t len, const void* buffer, uint32_t flags) const {
        return zx_log_write(get(), len, buffer, flags);
    }

    zx_status_t read(uint32_t len, void* buffer, uint32_t flags) const {
        return zx_log_read(get(), len, buffer, flags);
    }
};

using unowned_log = unowned<log>;

} // namespace zx

#endif  // LIB_ZX_LOG_H_


<|start_filename|>pkg/zx/include/lib/zx/fifo.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_ZX_FIFO_H_
#define LIB_ZX_FIFO_H_

#include <lib/zx/handle.h>
#include <lib/zx/object.h>

namespace zx {

class fifo : public object<fifo> {
public:
    static constexpr zx_obj_type_t TYPE = ZX_OBJ_TYPE_FIFO;

    constexpr fifo() = default;

    explicit fifo(zx_handle_t value) : object(value) {}

    explicit fifo(handle&& h) : object(h.release()) {}

    fifo(fifo&& other) : object(other.release()) {}

    fifo& operator=(fifo&& other) {
        reset(other.release());
        return *this;
    }

    static zx_status_t create(uint32_t elem_count, uint32_t elem_size,
                              uint32_t options, fifo* out0, fifo* out1);

    zx_status_t write(size_t elem_size, const void* buffer, size_t count, size_t* actual_count) const {
        return zx_fifo_write(get(), elem_size, buffer, count, actual_count);
    }

    zx_status_t read(size_t elem_size, void* buffer, size_t count, size_t* actual_count) const {
        return zx_fifo_read(get(), elem_size, buffer, count, actual_count);
    }

};

using unowned_fifo = unowned<fifo>;

} // namespace zx

#endif  // LIB_ZX_FIFO_H_


<|start_filename|>arch/x64/sysroot/include/link.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <elf.h>
#define __NEED_size_t
#define __NEED_uint32_t
#include <bits/alltypes.h>

#define ElfW(type) Elf64_##type

/* this is the same everywhere except alpha and s390 */
typedef uint32_t Elf_Symndx;

struct dl_phdr_info {
    ElfW(Addr) dlpi_addr;
    const char* dlpi_name;
    const ElfW(Phdr) * dlpi_phdr;
    ElfW(Half) dlpi_phnum;
    unsigned long long int dlpi_adds;
    unsigned long long int dlpi_subs;
    size_t dlpi_tls_modid;
    void* dlpi_tls_data;
};

struct link_map {
    ElfW(Addr) l_addr;
    char* l_name;
    ElfW(Dyn) * l_ld;
    struct link_map *l_next, *l_prev;
};

struct r_debug {
    int r_version;
    struct link_map* r_map;
    ElfW(Addr) r_brk;
    enum { RT_CONSISTENT,
           RT_ADD,
           RT_DELETE } r_state;
    ElfW(Addr) r_ldbase;
};

int dl_iterate_phdr(int (*)(struct dl_phdr_info*, size_t, void*), void*);

#ifdef __cplusplus
}
#endif


<|start_filename|>arch/x64/sysroot/include/bits/x86_64/stat.h<|end_filename|>
/* copied from kernel definition, but with padding replaced
 * by the corresponding correctly-sized userspace types. */

struct stat {
    dev_t st_dev;
    ino_t st_ino;
    nlink_t st_nlink;

    mode_t st_mode;
    uid_t st_uid;
    gid_t st_gid;
    unsigned int __pad0;
    dev_t st_rdev;
    off_t st_size;
    blksize_t st_blksize;
    blkcnt_t st_blocks;

    struct timespec st_atim;
    struct timespec st_mtim;
    struct timespec st_ctim;
    long __unused[3];
};


<|start_filename|>dart/fuchsia_services/lib/services.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/// The base-level functionality required by any component on Fuchsia.
export 'src/environment_service_connection.dart';
export 'src/service_connection.dart';
export 'src/service_provider_impl.dart';
export 'src/startup_context.dart';


<|start_filename|>arch/x64/sysroot/include/dirent.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>

#define __NEED_ino_t
#define __NEED_off_t
#if defined(_BSD_SOURCE) || defined(_GNU_SOURCE)
#define __NEED_size_t
#endif

#include <bits/alltypes.h>

typedef struct __dirstream DIR;

struct dirent {
    ino_t d_ino;
    off_t d_off;
    unsigned short d_reclen;
    unsigned char d_type;
    char d_name[256];
};

#define d_fileno d_ino

int closedir(DIR*);
DIR* fdopendir(int);
DIR* opendir(const char*);
struct dirent* readdir(DIR*);
int readdir_r(DIR* __restrict, struct dirent* __restrict, struct dirent** __restrict);
void rewinddir(DIR*);
void seekdir(DIR*, long);
long telldir(DIR*);
int dirfd(DIR*);

int alphasort(const struct dirent**, const struct dirent**);
int scandir(const char*, struct dirent***, int (*)(const struct dirent*),
            int (*)(const struct dirent**, const struct dirent**));

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#define DT_UNKNOWN 0
#define DT_FIFO 1
#define DT_CHR 2
#define DT_DIR 4
#define DT_BLK 6
#define DT_REG 8
#define DT_LNK 10
#define DT_SOCK 12
#define DT_WHT 14
#define IFTODT(x) ((x) >> 12 & 017)
#define DTTOIF(x) ((x) << 12)
int getdents(int, struct dirent*, size_t);
#endif

#ifdef _GNU_SOURCE
int versionsort(const struct dirent**, const struct dirent**);
#endif

#ifdef __cplusplus
}
#endif


<|start_filename|>pkg/fit/include/lib/fit/promise_internal.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIT_PROMISE_INTERNAL_H_
#define LIB_FIT_PROMISE_INTERNAL_H_

#include <assert.h>

#include <tuple>
#include <type_traits>
#include <utility>

#include "function.h"
#include "nullable.h"
#include "result.h"
#include "traits.h"

namespace fit {

template <typename Continuation>
class promise_impl;

template <typename Promise>
class future_impl;

class context;
class executor;
class suspended_task;

namespace internal {

// Determines whether a type is a kind of fit::result.
template <typename Result>
struct is_result : std::false_type {};
template <typename V, typename E>
struct is_result<::fit::result<V, E>> : std::true_type {};

// Deduces a continuation's result.
// Also ensures that the continuation has a compatible signature.
template <typename Continuation,
          typename = std::enable_if_t<is_result<
              decltype(std::declval<Continuation&>()(
                  std::declval<::fit::context&>()))>::value>>
struct continuation_traits {
    using type = Continuation;
    using result_type = decltype(std::declval<Continuation&>()(std::declval<::fit::context&>()));
};
template <typename Continuation, typename = fit::void_t<>>
struct is_continuation : std::false_type {};
template <typename Continuation>
struct is_continuation<
    Continuation,
    fit::void_t<typename continuation_traits<Continuation>::type>>
    : std::true_type {};

// Wraps a handler function and adapts its return type to a fit::result
// via its specializations.
template <typename Handler, typename DefaultV, typename DefaultE,
          typename ReturnType = typename callable_traits<Handler>::return_type,
          bool callable_result = ::fit::is_callable<ReturnType>::value>
class result_adapter final {
    // This expression always evaluates to false but depends on the template
    // type parameters so that it only gets evaluated when the template is
    // expanded.  If we simply wrote "false", the compiler would raise the
    // static assertion failure as soon as it encountered the statement.
    template <typename T>
    struct check_result { static constexpr bool value = false; };
    static_assert(
        check_result<ReturnType>::value,
        "The provided handler's result type was expected to be "
        "fit::result<V, E>, fit::ok_result<V>, fit::error_result<E>, "
        "fit::pending_result, void, or a continuation with the signature "
        "fit::result<V, E>(fit::context&).  "
        "Please refer to the combinator's documentation for a list of "
        "supported handler function signatures.");
};

// Supports handlers that return void.
template <typename Handler, typename DefaultV, typename DefaultE>
class result_adapter<Handler, DefaultV, DefaultE, void, false> final {
public:
    using result_type = ::fit::result<DefaultV, DefaultE>;

    explicit result_adapter(Handler handler)
        : handler_(std::move(handler)) {}

    template <typename... Args>
    result_type call(::fit::context& context, Args... args) {
        handler_(std::forward<Args>(args)...);
        return ::fit::ok();
    }

private:
    Handler handler_;
};

// Supports handlers that return pending_result.
template <typename Handler, typename DefaultV, typename DefaultE>
class result_adapter<Handler, DefaultV, DefaultE, ::fit::pending_result, false> final {
public:
    using result_type = ::fit::result<DefaultV, DefaultE>;

    explicit result_adapter(Handler handler)
        : handler_(std::move(handler)) {}

    template <typename... Args>
    result_type call(::fit::context& context, Args... args) {
        return handler_(std::forward<Args>(args)...);
    }

private:
    Handler handler_;
};

// Supports handlers that return ok_result<V>.
template <typename Handler, typename DefaultV, typename DefaultE,
          typename V>
class result_adapter<Handler, DefaultV, DefaultE, ::fit::ok_result<V>, false> final {
public:
    using result_type = ::fit::result<V, DefaultE>;

    explicit result_adapter(Handler handler)
        : handler_(std::move(handler)) {}

    template <typename... Args>
    result_type call(::fit::context& context, Args... args) {
        return handler_(std::forward<Args>(args)...);
    }

private:
    Handler handler_;
};

// Supports handlers that return error_result<E>.
template <typename Handler, typename DefaultV, typename DefaultE,
          typename E>
class result_adapter<Handler, DefaultV, DefaultE, ::fit::error_result<E>, false> final {
public:
    using result_type = ::fit::result<DefaultV, E>;

    explicit result_adapter(Handler handler)
        : handler_(std::move(handler)) {}

    template <typename... Args>
    result_type call(::fit::context& context, Args... args) {
        return handler_(std::forward<Args>(args)...);
    }

private:
    Handler handler_;
};

// Supports handlers that return result<V, E>.
template <typename Handler, typename DefaultV, typename DefaultE,
          typename V, typename E>
class result_adapter<Handler, DefaultV, DefaultE, ::fit::result<V, E>, false> final {
public:
    using result_type = ::fit::result<V, E>;

    explicit result_adapter(Handler handler)
        : handler_(std::move(handler)) {}

    template <typename... Args>
    result_type call(::fit::context& context, Args... args) {
        return handler_(std::forward<Args>(args)...);
    }

private:
    Handler handler_;
};

// Supports handlers that return continuations or promises.
// This works for any callable whose signature is:
//     fit::result<...>(fit::context&)
template <typename Handler, typename DefaultV, typename DefaultE,
          typename ReturnType>
class result_adapter<Handler, DefaultV, DefaultE, ReturnType, true> final {
    // If the handler doesn't actually return a continuation then the
    // compilation will fail here which is slightly easier to diagnose
    // than if we dropped the result_adapter specialization entirely.
    using continuation_traits = continuation_traits<ReturnType>;
    using continuation_type = typename continuation_traits::type;

public:
    using result_type = typename continuation_traits::result_type;

    explicit result_adapter(Handler handler)
        : handler_(std::move(handler)) {}

    template <typename... Args>
    result_type call(::fit::context& context, Args... args) {
        if (handler_) {
            continuation_ = (*handler_)(std::forward<Args>(args)...);
            handler_.reset();
        }
        if (!continuation_) {
            return ::fit::pending();
        }
        return (*continuation_)(context);
    }

private:
    ::fit::nullable<Handler> handler_;
    ::fit::nullable<continuation_type> continuation_;
};

// Wraps a handler that may or may not have a fit::context& as first argument.
// This is determined by checking the argument count.
template <typename Handler, typename DefaultV, typename DefaultE,
          size_t num_args = 0,
          int excess_args =
              (static_cast<int>(
                   ::fit::callable_traits<Handler>::args::size) -
               static_cast<int>(num_args))>
class context_adapter final {
    static_assert(
        excess_args >= 0,
        "The provided handler has too few arguments.  "
        "Please refer to the combinator's documentation for a list of "
        "supported handler function signatures.");
    static_assert(
        excess_args <= 1,
        "The provided handler has too many arguments.  "
        "Please refer to the combinator's documentation for a list of "
        "supported handler function signatures.");
};

// Supports handlers without a context argument.
template <typename Handler, typename DefaultV, typename DefaultE,
          size_t num_args>
class context_adapter<Handler, DefaultV, DefaultE, num_args, 0> final {
    using base_type = result_adapter<Handler, DefaultV, DefaultE>;

public:
    using result_type = typename base_type::result_type;
    static constexpr size_t next_arg_index = 0;

    explicit context_adapter(Handler handler)
        : base_(std::move(handler)) {}

    template <typename... Args>
    result_type call(::fit::context& context, Args... args) {
        return base_.template call<Args...>(context, std::forward<Args>(args)...);
    }

private:
    base_type base_;
};

// Supports handlers with a context argument.
template <typename Handler, typename DefaultV, typename DefaultE,
          size_t num_args>
class context_adapter<Handler, DefaultV, DefaultE, num_args, 1> final {
    using base_type = result_adapter<Handler, DefaultV, DefaultE>;
    using context_arg_type =
        typename ::fit::callable_traits<Handler>::args::template at<0>;
    static_assert(
        std::is_same<context_arg_type, ::fit::context&>::value,
        "The provided handler's first argument was expected to be of type "
        "fit::context& based on the number of arguments it has.  "
        "Please refer to the combinator's documentation for a list of "
        "supported handler function signatures.");

public:
    using result_type = typename base_type::result_type;
    static constexpr size_t next_arg_index = 1;

    explicit context_adapter(Handler handler)
        : base_(std::move(handler)) {}

    template <typename... Args>
    result_type call(::fit::context& context, Args... args) {
        return base_.template call<::fit::context&, Args...>(
            context, context, std::forward<Args>(args)...);
    }

private:
    base_type base_;
};

// Wraps a handler that may accept a context argument.
template <typename Handler>
class context_handler_invoker final {
    using base_type = context_adapter<Handler, void, void, 0>;

public:
    using result_type = typename base_type::result_type;

    explicit context_handler_invoker(Handler handler)
        : base_(std::move(handler)) {}

    result_type operator()(::fit::context& context) {
        return base_.template call<>(context);
    }

private:
    base_type base_;
};

// Wraps a handler that may accept a context and result argument.
template <typename Handler, typename PriorResult>
class result_handler_invoker final {
    using base_type = context_adapter<Handler, void, void, 1>;
    using result_arg_type =
        typename ::fit::callable_traits<Handler>::args::template at<
            base_type::next_arg_index>;
    static_assert(
        (std::is_same<result_arg_type, PriorResult>::value &&
         std::is_copy_constructible<result_arg_type>::value) ||
            std::is_same<result_arg_type, PriorResult&>::value ||
            std::is_same<result_arg_type, const PriorResult&>::value,
        "The provided handler's last argument was expected to be of type "
        "fit::result<V, E>&, const fit::result<V, E>&, or fit::result<V, E> "
        "(if the result is copy-constructible).  "
        "Please refer to the combinator's documentation for a list of "
        "supported handler function signatures.");

public:
    using result_type = typename base_type::result_type;

    explicit result_handler_invoker(Handler handler)
        : base_(std::move(handler)) {}

    result_type operator()(::fit::context& context, PriorResult& result) {
        return base_.template call<PriorResult&>(context, result);
    }

private:
    base_type base_;
};

// Wraps a handler that may accept a context and value argument.
template <typename Handler, typename PriorResult,
          typename V = typename PriorResult::value_type>
class value_handler_invoker final {
    using base_type = context_adapter<Handler,
                                      void, typename PriorResult::error_type, 1>;
    using value_arg_type =
        typename ::fit::callable_traits<Handler>::args::template at<
            base_type::next_arg_index>;
    static_assert(
        (std::is_same<value_arg_type, V>::value &&
         std::is_copy_constructible<value_arg_type>::value) ||
            std::is_same<value_arg_type, V&>::value ||
            std::is_same<value_arg_type, const V&>::value,
        "The provided handler's last argument was expected to be of type "
        "V&, const V&, or V (if the value is copy-constructible).  "
        "Please refer to the combinator's documentation for a list of "
        "supported handler function signatures.");

public:
    using result_type = typename base_type::result_type;

    explicit value_handler_invoker(Handler handler)
        : base_(std::move(handler)) {}

    result_type operator()(::fit::context& context, PriorResult& result) {
        return base_.template call<V&>(context, result.value());
    }

private:
    base_type base_;
};

// Specialization for void value.
template <typename Handler, typename PriorResult>
class value_handler_invoker<Handler, PriorResult, void> final {
    using base_type = context_adapter<Handler,
                                      void, typename PriorResult::error_type, 0>;

public:
    using result_type = typename base_type::result_type;

    explicit value_handler_invoker(Handler handler)
        : base_(std::move(handler)) {}

    result_type operator()(::fit::context& context, PriorResult& result) {
        return base_.template call<>(context);
    }

private:
    base_type base_;
};

// Wraps a handler that may accept a context and error argument.
template <typename Handler, typename PriorResult,
          typename E = typename PriorResult::error_type>
class error_handler_invoker final {
    using base_type = context_adapter<Handler,
                                      typename PriorResult::value_type, void, 1>;
    using error_arg_type =
        typename ::fit::callable_traits<Handler>::args::template at<
            base_type::next_arg_index>;
    static_assert(
        (std::is_same<error_arg_type, E>::value &&
         std::is_copy_constructible<error_arg_type>::value) ||
            std::is_same<error_arg_type, E&>::value ||
            std::is_same<error_arg_type, const E&>::value,
        "The provided handler's last argument was expected to be of type "
        "E&, const E&, or E (if the error is copy-constructible).  "
        "Please refer to the combinator's documentation for a list of "
        "supported handler function signatures.");

public:
    using result_type = typename base_type::result_type;

    explicit error_handler_invoker(Handler handler)
        : base_(std::move(handler)) {}

    result_type operator()(::fit::context& context, PriorResult& result) {
        return base_.template call<E&>(context, result.error());
    }

private:
    base_type base_;
};

// Specialization for void error.
template <typename Handler, typename PriorResult>
class error_handler_invoker<Handler, PriorResult, void> final {
    using base_type = context_adapter<Handler,
                                      typename PriorResult::value_type, void, 0>;

public:
    using result_type = typename base_type::result_type;

    explicit error_handler_invoker(Handler handler)
        : base_(std::move(handler)) {}

    result_type operator()(::fit::context& context, PriorResult& result) {
        return base_.template call<>(context);
    }

private:
    base_type base_;
};

// The continuation produced by |fit::promise::then()|.
template <typename PriorPromise, typename ResultHandler>
class then_continuation final {
    using invoker_type = ::fit::internal::result_handler_invoker<
        ResultHandler, typename PriorPromise::result_type>;

public:
    then_continuation(PriorPromise prior_promise, ResultHandler handler)
        : prior_(std::move(prior_promise)),
          invoker_(std::move(handler)) {}

    typename invoker_type::result_type operator()(::fit::context& context) {
        if (!prior_(context))
            return ::fit::pending();
        return invoker_(context, prior_.result());
    }

private:
    future_impl<PriorPromise> prior_;
    invoker_type invoker_;
};

// The continuation produced by |fit::promise::and_then()|.
template <typename PriorPromise, typename ValueHandler>
class and_then_continuation final {
    using invoker_type = ::fit::internal::value_handler_invoker<
        ValueHandler, typename PriorPromise::result_type>;

public:
    and_then_continuation(PriorPromise prior_promise, ValueHandler handler)
        : prior_(std::move(prior_promise)),
          invoker_(std::move(handler)) {}

    typename invoker_type::result_type operator()(::fit::context& context) {
        if (!prior_(context))
            return ::fit::pending();
        if (prior_.is_error())
            return prior_.take_error_result();
        return invoker_(context, prior_.result());
    }

private:
    future_impl<PriorPromise> prior_;
    invoker_type invoker_;
};

// The continuation produced by |fit::promise::or_else()|.
template <typename PriorPromise, typename ErrorHandler>
class or_else_continuation final {
    using invoker_type = ::fit::internal::error_handler_invoker<
        ErrorHandler, typename PriorPromise::result_type>;

public:
    or_else_continuation(PriorPromise prior_promise, ErrorHandler handler)
        : prior_(std::move(prior_promise)),
          invoker_(std::move(handler)) {}

    typename invoker_type::result_type operator()(::fit::context& context) {
        if (!prior_(context))
            return ::fit::pending();
        if (prior_.is_ok())
            return prior_.take_ok_result();
        return invoker_(context, prior_.result());
    }

private:
    future_impl<PriorPromise> prior_;
    invoker_type invoker_;
};

// The continuation produced by |fit::promise::inspect()|.
template <typename PriorPromise, typename InspectHandler>
class inspect_continuation final {
    using invoker_type = ::fit::internal::result_handler_invoker<
        InspectHandler, typename PriorPromise::result_type>;

public:
    inspect_continuation(PriorPromise prior_promise, InspectHandler handler)
        : prior_(std::move(prior_promise)),
          invoker_(std::move(handler)) {}

    typename PriorPromise::result_type operator()(::fit::context& context) {
        typename PriorPromise::result_type result = prior_(context);
        if (result)
            invoker_(context, result);
        return result;
    }

private:
    PriorPromise prior_;
    invoker_type invoker_;
};

// The continuation produced by |fit::promise::discard_result()|.
template <typename PriorPromise>
class discard_result_continuation final {
public:
    explicit discard_result_continuation(PriorPromise prior_promise)
        : prior_(std::move(prior_promise)) {}

    fit::result<> operator()(::fit::context& context) {
        if (!prior_(context))
            return ::fit::pending();
        return ::fit::ok();
    }

private:
    PriorPromise prior_;
};

// The continuation produced by |make_promise()|.
// This turns out to be equivalent to a context handler invoker.
template <typename PromiseHandler>
using promise_continuation = context_handler_invoker<PromiseHandler>;

// Returns true if all arguments are true or if there are none.
inline bool all_true() {
    return true;
}
template <typename... Ts>
inline bool all_true(bool value, Ts... values) {
    return value & all_true(values...);
}

// The continuation produced by |join_promises()|.
template <typename... Promises>
class join_continuation final {
public:
    explicit join_continuation(Promises... promises)
        : promises_(std::make_tuple(std::move(promises)...)) {}

    ::fit::result<std::tuple<typename Promises::result_type...>> operator()(
        ::fit::context& context) {
        return evaluate(context, std::index_sequence_for<Promises...>{});
    }

private:
    template <size_t... i>
    ::fit::result<std::tuple<typename Promises::result_type...>> evaluate(
        ::fit::context& context, std::index_sequence<i...>) {
        bool done = all_true(std::get<i>(promises_)(context)...);
        if (!done)
            return ::fit::pending();
        return ::fit::ok(std::make_tuple(std::get<i>(promises_).take_result()...));
    }

    std::tuple<future_impl<Promises>...> promises_;
};

} // namespace internal

template <typename PromiseHandler>
inline promise_impl<::fit::internal::promise_continuation<PromiseHandler>>
make_promise(PromiseHandler handler);

template <typename Continuation>
inline promise_impl<Continuation> make_promise_with_continuation(
    Continuation continuation);

} // namespace fit

#endif // LIB_FIT_PROMISE_INTERNAL_H_


<|start_filename|>arch/x64/sysroot/include/arpa/telnet.h<|end_filename|>
#pragma once

#define IAC 255
#define DONT 254
#define DO 253
#define WONT 252
#define WILL 251
#define SB 250
#define GA 249
#define EL 248
#define EC 247
#define AYT 246
#define AO 245
#define IP 244
#define BREAK 243
#define DM 242
#define NOP 241
#define SE 240
#define EOR 239
#define ABORT 238
#define SUSP 237
#define xEOF 236

#define SYNCH 242

#define telcmds                                                                        \
    ((char[][6]){                                                                      \
        "EOF", "SUSP", "ABORT", "EOR", "SE", "NOP", "DMARK", "BRK", "IP", "AO", "AYT", \
        "EC", "EL", "GA", "SB", "WILL", "WONT", "DO", "DONT", "IAC", 0})

#define TELCMD_FIRST xEOF
#define TELCMD_LAST IAC
#define TELCMD_OK(x) ((unsigned int)(x) <= TELCMD_LAST && (unsigned int)(x) >= TELCMD_FIRST)
#define TELCMD(x) telcmds[(x)-TELCMD_FIRST]

#define TELOPT_BINARY 0
#define TELOPT_ECHO 1
#define TELOPT_RCP 2
#define TELOPT_SGA 3
#define TELOPT_NAMS 4
#define TELOPT_STATUS 5
#define TELOPT_TM 6
#define TELOPT_RCTE 7
#define TELOPT_NAOL 8
#define TELOPT_NAOP 9
#define TELOPT_NAOCRD 10
#define TELOPT_NAOHTS 11
#define TELOPT_NAOHTD 12
#define TELOPT_NAOFFD 13
#define TELOPT_NAOVTS 14
#define TELOPT_NAOVTD 15
#define TELOPT_NAOLFD 16
#define TELOPT_XASCII 17
#define TELOPT_LOGOUT 18
#define TELOPT_BM 19
#define TELOPT_DET 20
#define TELOPT_SUPDUP 21
#define TELOPT_SUPDUPOUTPUT 22
#define TELOPT_SNDLOC 23
#define TELOPT_TTYPE 24
#define TELOPT_EOR 25
#define TELOPT_TUID 26
#define TELOPT_OUTMRK 27
#define TELOPT_TTYLOC 28
#define TELOPT_3270REGIME 29
#define TELOPT_X3PAD 30
#define TELOPT_NAWS 31
#define TELOPT_TSPEED 32
#define TELOPT_LFLOW 33
#define TELOPT_LINEMODE 34
#define TELOPT_XDISPLOC 35
#define TELOPT_OLD_ENVIRON 36
#define TELOPT_AUTHENTICATION 37 /* Authenticate */
#define TELOPT_ENCRYPT 38
#define TELOPT_NEW_ENVIRON 39
#define TELOPT_EXOPL 255

#define NTELOPTS (1 + TELOPT_NEW_ENVIRON)
#ifdef TELOPTS
char* telopts[NTELOPTS + 1] = {
    "BINARY",
    "ECHO",
    "RCP",
    "SUPPRESS GO AHEAD",
    "NAME",
    "STATUS",
    "TIMING MARK",
    "RCTE",
    "NAOL",
    "NAOP",
    "NAOCRD",
    "NAOHTS",
    "NAOHTD",
    "NAOFFD",
    "NAOVTS",
    "NAOVTD",
    "NAOLFD",
    "EXTEND ASCII",
    "LOGOUT",
    "BYTE MACRO",
    "DATA ENTRY TERMINAL",
    "SUPDUP",
    "SUPDUP OUTPUT",
    "SEND LOCATION",
    "TERMINAL TYPE",
    "END OF RECORD",
    "TACACS UID",
    "OUTPUT MARKING",
    "TTYLOC",
    "3270 REGIME",
    "X.3 PAD",
    "NAWS",
    "TSPEED",
    "LFLOW",
    "LINEMODE",
    "XDISPLOC",
    "OLD-ENVIRON",
    "AUTHENTICATION",
    "ENCRYPT",
    "NEW-ENVIRON",
    0,
};
#define TELOPT_FIRST TELOPT_BINARY
#define TELOPT_LAST TELOPT_NEW_ENVIRON
#define TELOPT_OK(x) ((unsigned int)(x) <= TELOPT_LAST)
#define TELOPT(x) telopts[(x)-TELOPT_FIRST]
#endif

#define TELQUAL_IS 0
#define TELQUAL_SEND 1
#define TELQUAL_INFO 2
#define TELQUAL_REPLY 2
#define TELQUAL_NAME 3

#define LFLOW_OFF 0
#define LFLOW_ON 1
#define LFLOW_RESTART_ANY 2
#define LFLOW_RESTART_XON 3

#define LM_MODE 1
#define LM_FORWARDMASK 2
#define LM_SLC 3

#define MODE_EDIT 0x01
#define MODE_TRAPSIG 0x02
#define MODE_ACK 0x04
#define MODE_SOFT_TAB 0x08
#define MODE_LIT_ECHO 0x10

#define MODE_MASK 0x1f

#define MODE_FLOW 0x0100
#define MODE_ECHO 0x0200
#define MODE_INBIN 0x0400
#define MODE_OUTBIN 0x0800
#define MODE_FORCE 0x1000

#define SLC_SYNCH 1
#define SLC_BRK 2
#define SLC_IP 3
#define SLC_AO 4
#define SLC_AYT 5
#define SLC_EOR 6
#define SLC_ABORT 7
#define SLC_EOF 8
#define SLC_SUSP 9
#define SLC_EC 10
#define SLC_EL 11
#define SLC_EW 12
#define SLC_RP 13
#define SLC_LNEXT 14
#define SLC_XON 15
#define SLC_XOFF 16
#define SLC_FORW1 17
#define SLC_FORW2 18

#define NSLC 18

#define SLC_NAMELIST                                                                               \
    "0", "SYNCH", "BRK", "IP", "AO", "AYT", "EOR", "ABORT", "EOF", "SUSP", "EC", "EL", "EW", "RP", \
        "LNEXT", "XON", "XOFF", "FORW1", "FORW2", 0,
#ifdef SLC_NAMES
char* slc_names[] = {SLC_NAMELIST};
#else
extern char* slc_names[];
#define SLC_NAMES SLC_NAMELIST
#endif

#define SLC_NAME_OK(x) ((unsigned int)(x) <= NSLC)
#define SLC_NAME(x) slc_names[x]

#define SLC_NOSUPPORT 0
#define SLC_CANTCHANGE 1
#define SLC_VARIABLE 2
#define SLC_DEFAULT 3
#define SLC_LEVELBITS 0x03

#define SLC_FUNC 0
#define SLC_FLAGS 1
#define SLC_VALUE 2

#define SLC_ACK 0x80
#define SLC_FLUSHIN 0x40
#define SLC_FLUSHOUT 0x20

#define OLD_ENV_VAR 1
#define OLD_ENV_VALUE 0
#define NEW_ENV_VAR 0
#define NEW_ENV_VALUE 1
#define ENV_ESC 2
#define ENV_USERVAR 3

#define AUTH_WHO_CLIENT 0
#define AUTH_WHO_SERVER 1
#define AUTH_WHO_MASK 1

#define AUTH_HOW_ONE_WAY 0
#define AUTH_HOW_MUTUAL 2
#define AUTH_HOW_MASK 2

#define AUTHTYPE_NULL 0
#define AUTHTYPE_KERBEROS_V4 1
#define AUTHTYPE_KERBEROS_V5 2
#define AUTHTYPE_SPX 3
#define AUTHTYPE_MINK 4
#define AUTHTYPE_CNT 5

#define AUTHTYPE_TEST 99

#ifdef AUTH_NAMES
char* authtype_names[] = {
    "NULL", "KERBEROS_V4", "KERBEROS_V5", "SPX", "MINK", 0,
};
#else
extern char* authtype_names[];
#endif

#define AUTHTYPE_NAME_OK(x) ((unsigned int)(x) < AUTHTYPE_CNT)
#define AUTHTYPE_NAME(x) authtype_names[x]

#define ENCRYPT_IS 0
#define ENCRYPT_SUPPORT 1
#define ENCRYPT_REPLY 2
#define ENCRYPT_START 3
#define ENCRYPT_END 4
#define ENCRYPT_REQSTART 5
#define ENCRYPT_REQEND 6
#define ENCRYPT_ENC_KEYID 7
#define ENCRYPT_DEC_KEYID 8
#define ENCRYPT_CNT 9

#define ENCTYPE_ANY 0
#define ENCTYPE_DES_CFB64 1
#define ENCTYPE_DES_OFB64 2
#define ENCTYPE_CNT 3

#ifdef ENCRYPT_NAMES
char* encrypt_names[] = {
    "IS", "SUPPORT", "REPLY", "START", "END", "REQUEST-START",
    "REQUEST-END", "ENC-KEYID", "DEC-KEYID", 0,
};
char* enctype_names[] = {
    "ANY", "DES_CFB64", "DES_OFB64", 0,
};
#else
extern char* encrypt_names[];
extern char* enctype_names[];
#endif

#define ENCRYPT_NAME_OK(x) ((unsigned int)(x) < ENCRYPT_CNT)
#define ENCRYPT_NAME(x) encrypt_names[x]

#define ENCTYPE_NAME_OK(x) ((unsigned int)(x) < ENCTYPE_CNT)
#define ENCTYPE_NAME(x) enctype_names[x]


<|start_filename|>pkg/fidl/include/lib/fidl/epitaph.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIDL_EPITAPH_H_
#define LIB_FIDL_EPITAPH_H_

#include <zircon/types.h>

__BEGIN_CDECLS

#ifdef __Fuchsia__

// Sends an epitaph with the given values down the channel.
// See https://fuchsia.googlesource.com/docs/+/master/development/languages/fidl/languages/c.md#fidl_epitaph_write
zx_status_t fidl_epitaph_write(zx_handle_t channel, zx_status_t error);

#endif // __Fuchsia__

__END_CDECLS

#endif // LIB_FIDL_EPITAPH_H_


<|start_filename|>arch/x64/sysroot/include/bits/aarch64/signal.h<|end_filename|>
#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
    defined(_GNU_SOURCE) || defined(_BSD_SOURCE)

#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#define MINSIGSTKSZ 6144
#define SIGSTKSZ 12288
#endif

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
typedef unsigned long greg_t;
typedef unsigned long gregset_t[34];

typedef struct {
    long double vregs[32];
    unsigned int fpsr;
    unsigned int fpcr;
} fpregset_t;
typedef struct sigcontext {
    unsigned long fault_address;
    unsigned long regs[31];
    unsigned long sp, pc, pstate;
    long double __reserved[256];
} mcontext_t;

#define FPSIMD_MAGIC 0x46508001
#define ESR_MAGIC 0x45535201
struct _aarch64_ctx {
    unsigned int magic;
    unsigned int size;
};
struct fpsimd_context {
    struct _aarch64_ctx head;
    unsigned int fpsr;
    unsigned int fpcr;
    long double vregs[32];
};
struct esr_context {
    struct _aarch64_ctx head;
    unsigned long esr;
};
#else
typedef struct { long double __regs[18 + 256]; } mcontext_t;
#endif

struct sigaltstack {
    void* ss_sp;
    int ss_flags;
    size_t ss_size;
};

typedef struct __ucontext {
    unsigned long uc_flags;
    struct ucontext* uc_link;
    stack_t uc_stack;
    sigset_t uc_sigmask;
    mcontext_t uc_mcontext;
} ucontext_t;

#define SA_NOCLDSTOP 1
#define SA_NOCLDWAIT 2
#define SA_SIGINFO 4
#define SA_ONSTACK 0x08000000
#define SA_RESTART 0x10000000
#define SA_NODEFER 0x40000000
#define SA_RESETHAND 0x80000000
#define SA_RESTORER 0x04000000

#endif

#define SIGHUP 1
#define SIGINT 2
#define SIGQUIT 3
#define SIGILL 4
#define SIGTRAP 5
#define SIGABRT 6
#define SIGIOT SIGABRT
#define SIGBUS 7
#define SIGFPE 8
#define SIGKILL 9
#define SIGUSR1 10
#define SIGSEGV 11
#define SIGUSR2 12
#define SIGPIPE 13
#define SIGALRM 14
#define SIGTERM 15
#define SIGSTKFLT 16
#define SIGCHLD 17
#define SIGCONT 18
#define SIGSTOP 19
#define SIGTSTP 20
#define SIGTTIN 21
#define SIGTTOU 22
#define SIGURG 23
#define SIGXCPU 24
#define SIGXFSZ 25
#define SIGVTALRM 26
#define SIGPROF 27
#define SIGWINCH 28
#define SIGIO 29
#define SIGPOLL 29
#define SIGPWR 30
#define SIGSYS 31
#define SIGUNUSED SIGSYS

#define _NSIG 65


<|start_filename|>pkg/fidl/include/lib/fidl/llcpp/decoded_message.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIDL_LLCPP_DECODED_MESSAGE_H_
#define LIB_FIDL_LLCPP_DECODED_MESSAGE_H_

#include <lib/fidl/coding.h>
#include <lib/fidl/llcpp/encoded_message.h>
#include <lib/fidl/llcpp/traits.h>
#include <type_traits>
#include <zircon/fidl.h>

namespace fidl {

// `DecodedMessage` manages a linearized FIDL message in decoded form.
// It takes care of releasing all handles which were not consumed
// (std::moved from the decoded FIDL struct) when it goes out of scope.
template <typename FidlType>
class DecodedMessage final {
    static_assert(IsFidlType<FidlType>::value, "Only FIDL types allowed here");
    static_assert(FidlType::MaxSize > 0, "Positive message size");

public:
    // Instantiates an empty message.
    // To populate this message, decode from an EncodedMessage object.
    DecodedMessage() = default;

    // Instantiates a DecodedMessage which points to a buffer region with caller-managed memory.
    // The buffer region is assumed to contain a linearized FIDL message with valid pointers.
    // This does not take ownership of that buffer region.
    // But it does take ownership of the handles within the buffer.
    DecodedMessage(BytePart bytes) :
        bytes_(std::move(bytes)) { }

    DecodedMessage(DecodedMessage&& other) = default;

    DecodedMessage& operator=(DecodedMessage&& other) = default;

    DecodedMessage(const DecodedMessage& other) = delete;

    DecodedMessage& operator=(const DecodedMessage& other) = delete;

    ~DecodedMessage() {
        CloseHandles();
    }

    // Keeps track of a new buffer region with caller-managed memory.
    // The buffer region is assumed to contain a linearized FIDL message with valid pointers.
    // This does not take ownership of that buffer region.
    // But it does take ownership of the handles within the buffer.
    void Reset(BytePart bytes) {
        CloseHandles();
        bytes_ = std::move(bytes);
    }

    // Consumes an encoded message object containing FIDL encoded bytes and handles.
    // The current buffer region in DecodedMessage is always released.
    // Uses the FIDL encoding tables to deserialize the message in-place.
    // If the message is invalid, discards the buffer and returns an error.
    zx_status_t DecodeFrom(EncodedMessage<FidlType>* msg, const char** out_error_msg) {
        // Clear any existing message.
        CloseHandles();
        bytes_ = BytePart();
        zx_status_t status = fidl_decode(FidlType::type,
                                         msg->bytes().data(), msg->bytes().actual(),
                                         msg->handles().data(), msg->handles().actual(),
                                         out_error_msg);
        // Clear out |msg| independent of success or failure
        BytePart bytes = msg->ReleaseBytesAndHandles();
        if (status == ZX_OK) {
            Reset(std::move(bytes));
        } else {
            Reset(BytePart());
        }
        return status;
    }

    // Serializes the content of the message in-place and stores the result
    // in |out_msg|. The message's contents are always consumed by this
    // operation, even in case of an error.
    zx_status_t EncodeTo(EncodedMessage<FidlType>* out_msg, const char** out_error_msg) {
        return out_msg->Initialize([this, &out_error_msg] (BytePart& msg_bytes,
                                                           HandlePart& msg_handles) {
            msg_bytes = std::move(bytes_);
            uint32_t actual_handles = 0;
            zx_status_t status = fidl_encode(FidlType::type,
                                             msg_bytes.data(), msg_bytes.actual(),
                                             msg_handles.data(), msg_handles.capacity(),
                                             &actual_handles, out_error_msg);
            msg_handles.set_actual(actual_handles);
            return status;
        });
    }

    // Accesses the FIDL message by reinterpreting the buffer pointer.
    // Returns nullptr if there is no message.
    FidlType* message() const {
        return reinterpret_cast<FidlType*>(bytes_.data());
    }

private:
    // Use the FIDL encoding tables for |FidlType| to walk the message and
    // destroy the handles it contains.
    void CloseHandles() {
#ifdef __Fuchsia__
        if (bytes_.data()) {
            fidl_close_handles(FidlType::type, bytes_.data(), bytes_.actual(), nullptr);
        }
#endif
    }

    // The contents of the decoded message.
    BytePart bytes_;
};

}  // namespace fidl

#endif // LIB_FIDL_LLCPP_DECODED_MESSAGE_H_


<|start_filename|>pkg/fidl/include/lib/fidl/cpp/vector_view.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIDL_CPP_VECTOR_VIEW_H_
#define LIB_FIDL_CPP_VECTOR_VIEW_H_

#include <zircon/fidl.h>

namespace fidl {

template<typename T>
class VectorView : public fidl_vector_t {
public:
    VectorView() : fidl_vector_t{} {}

    uint64_t count() const { return fidl_vector_t::count; }
    void set_count(uint64_t count) { fidl_vector_t::count = count; }

    const T* data() const { return static_cast<T*>(fidl_vector_t::data); }
    void set_data(T* data) { fidl_vector_t::data = data; }

    T* mutable_data() const { return static_cast<T*>(fidl_vector_t::data); }

    bool is_null() const { return fidl_vector_t::data == nullptr; }
    bool empty() const { return fidl_vector_t::count == 0; }

    const T& at(size_t offset) const { return data()[offset]; }
    T& at(size_t offset) { return mutable_data()[offset]; }

    const T& operator[](size_t offset) const { return at(offset); }
    T& operator[](size_t offset) { return at(offset); }

    T* begin() { return mutable_data(); }
    const T* begin() const { return data(); }
    const T* cbegin() const { return data(); }

    T* end() { return mutable_data() + count(); }
    const T* end() const { return data() + count(); }
    const T* cend() const { return data() + count(); }

    fidl_vector_t* impl() { return this; }
};

} // namespace fidl

#endif // LIB_FIDL_CPP_VECTOR_VIEW_H_


<|start_filename|>arch/x64/sysroot/include/netinet/icmp6.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <netinet/in.h>
#include <stdint.h>
#include <string.h>
#include <sys/types.h>

#define ICMP6_FILTER 1

#define ICMP6_FILTER_BLOCK 1
#define ICMP6_FILTER_PASS 2
#define ICMP6_FILTER_BLOCKOTHERS 3
#define ICMP6_FILTER_PASSONLY 4

struct icmp6_filter {
    uint32_t icmp6_filt[8];
};

struct icmp6_hdr {
    uint8_t icmp6_type;
    uint8_t icmp6_code;
    uint16_t icmp6_cksum;
    union {
        uint32_t icmp6_un_data32[1];
        uint16_t icmp6_un_data16[2];
        uint8_t icmp6_un_data8[4];
    } icmp6_dataun;
};

#define icmp6_data32 icmp6_dataun.icmp6_un_data32
#define icmp6_data16 icmp6_dataun.icmp6_un_data16
#define icmp6_data8 icmp6_dataun.icmp6_un_data8
#define icmp6_pptr icmp6_data32[0]
#define icmp6_mtu icmp6_data32[0]
#define icmp6_id icmp6_data16[0]
#define icmp6_seq icmp6_data16[1]
#define icmp6_maxdelay icmp6_data16[0]

#define ICMP6_DST_UNREACH 1
#define ICMP6_PACKET_TOO_BIG 2
#define ICMP6_TIME_EXCEEDED 3
#define ICMP6_PARAM_PROB 4

#define ICMP6_INFOMSG_MASK 0x80

#define ICMP6_ECHO_REQUEST 128
#define ICMP6_ECHO_REPLY 129
#define MLD_LISTENER_QUERY 130
#define MLD_LISTENER_REPORT 131
#define MLD_LISTENER_REDUCTION 132

#define ICMP6_DST_UNREACH_NOROUTE 0
#define ICMP6_DST_UNREACH_ADMIN 1
#define ICMP6_DST_UNREACH_BEYONDSCOPE 2
#define ICMP6_DST_UNREACH_ADDR 3
#define ICMP6_DST_UNREACH_NOPORT 4

#define ICMP6_TIME_EXCEED_TRANSIT 0
#define ICMP6_TIME_EXCEED_REASSEMBLY 1

#define ICMP6_PARAMPROB_HEADER 0
#define ICMP6_PARAMPROB_NEXTHEADER 1
#define ICMP6_PARAMPROB_OPTION 2

#define ICMP6_FILTER_WILLPASS(type, filterp) \
    ((((filterp)->icmp6_filt[(type) >> 5]) & (1 << ((type)&31))) == 0)

#define ICMP6_FILTER_WILLBLOCK(type, filterp) \
    ((((filterp)->icmp6_filt[(type) >> 5]) & (1 << ((type)&31))) != 0)

#define ICMP6_FILTER_SETPASS(type, filterp) \
    ((((filterp)->icmp6_filt[(type) >> 5]) &= ~(1 << ((type)&31))))

#define ICMP6_FILTER_SETBLOCK(type, filterp) \
    ((((filterp)->icmp6_filt[(type) >> 5]) |= (1 << ((type)&31))))

#define ICMP6_FILTER_SETPASSALL(filterp) memset(filterp, 0, sizeof(struct icmp6_filter));

#define ICMP6_FILTER_SETBLOCKALL(filterp) memset(filterp, 0xFF, sizeof(struct icmp6_filter));

#define ND_ROUTER_SOLICIT 133
#define ND_ROUTER_ADVERT 134
#define ND_NEIGHBOR_SOLICIT 135
#define ND_NEIGHBOR_ADVERT 136
#define ND_REDIRECT 137

struct nd_router_solicit {
    struct icmp6_hdr nd_rs_hdr;
};

#define nd_rs_type nd_rs_hdr.icmp6_type
#define nd_rs_code nd_rs_hdr.icmp6_code
#define nd_rs_cksum nd_rs_hdr.icmp6_cksum
#define nd_rs_reserved nd_rs_hdr.icmp6_data32[0]

struct nd_router_advert {
    struct icmp6_hdr nd_ra_hdr;
    uint32_t nd_ra_reachable;
    uint32_t nd_ra_retransmit;
};

#define nd_ra_type nd_ra_hdr.icmp6_type
#define nd_ra_code nd_ra_hdr.icmp6_code
#define nd_ra_cksum nd_ra_hdr.icmp6_cksum
#define nd_ra_curhoplimit nd_ra_hdr.icmp6_data8[0]
#define nd_ra_flags_reserved nd_ra_hdr.icmp6_data8[1]
#define ND_RA_FLAG_MANAGED 0x80
#define ND_RA_FLAG_OTHER 0x40
#define ND_RA_FLAG_HOME_AGENT 0x20
#define nd_ra_router_lifetime nd_ra_hdr.icmp6_data16[1]

struct nd_neighbor_solicit {
    struct icmp6_hdr nd_ns_hdr;
    struct in6_addr nd_ns_target;
};

#define nd_ns_type nd_ns_hdr.icmp6_type
#define nd_ns_code nd_ns_hdr.icmp6_code
#define nd_ns_cksum nd_ns_hdr.icmp6_cksum
#define nd_ns_reserved nd_ns_hdr.icmp6_data32[0]

struct nd_neighbor_advert {
    struct icmp6_hdr nd_na_hdr;
    struct in6_addr nd_na_target;
};

#define nd_na_type nd_na_hdr.icmp6_type
#define nd_na_code nd_na_hdr.icmp6_code
#define nd_na_cksum nd_na_hdr.icmp6_cksum
#define nd_na_flags_reserved nd_na_hdr.icmp6_data32[0]
#if __BYTE_ORDER == __BIG_ENDIAN
#define ND_NA_FLAG_ROUTER 0x80000000
#define ND_NA_FLAG_SOLICITED 0x40000000
#define ND_NA_FLAG_OVERRIDE 0x20000000
#else
#define ND_NA_FLAG_ROUTER 0x00000080
#define ND_NA_FLAG_SOLICITED 0x00000040
#define ND_NA_FLAG_OVERRIDE 0x00000020
#endif

struct nd_redirect {
    struct icmp6_hdr nd_rd_hdr;
    struct in6_addr nd_rd_target;
    struct in6_addr nd_rd_dst;
};

#define nd_rd_type nd_rd_hdr.icmp6_type
#define nd_rd_code nd_rd_hdr.icmp6_code
#define nd_rd_cksum nd_rd_hdr.icmp6_cksum
#define nd_rd_reserved nd_rd_hdr.icmp6_data32[0]

struct nd_opt_hdr {
    uint8_t nd_opt_type;
    uint8_t nd_opt_len;
};

#define ND_OPT_SOURCE_LINKADDR 1
#define ND_OPT_TARGET_LINKADDR 2
#define ND_OPT_PREFIX_INFORMATION 3
#define ND_OPT_REDIRECTED_HEADER 4
#define ND_OPT_MTU 5
#define ND_OPT_RTR_ADV_INTERVAL 7
#define ND_OPT_HOME_AGENT_INFO 8

struct nd_opt_prefix_info {
    uint8_t nd_opt_pi_type;
    uint8_t nd_opt_pi_len;
    uint8_t nd_opt_pi_prefix_len;
    uint8_t nd_opt_pi_flags_reserved;
    uint32_t nd_opt_pi_valid_time;
    uint32_t nd_opt_pi_preferred_time;
    uint32_t nd_opt_pi_reserved2;
    struct in6_addr nd_opt_pi_prefix;
};

#define ND_OPT_PI_FLAG_ONLINK 0x80
#define ND_OPT_PI_FLAG_AUTO 0x40
#define ND_OPT_PI_FLAG_RADDR 0x20

struct nd_opt_rd_hdr {
    uint8_t nd_opt_rh_type;
    uint8_t nd_opt_rh_len;
    uint16_t nd_opt_rh_reserved1;
    uint32_t nd_opt_rh_reserved2;
};

struct nd_opt_mtu {
    uint8_t nd_opt_mtu_type;
    uint8_t nd_opt_mtu_len;
    uint16_t nd_opt_mtu_reserved;
    uint32_t nd_opt_mtu_mtu;
};

struct mld_hdr {
    struct icmp6_hdr mld_icmp6_hdr;
    struct in6_addr mld_addr;
};

#define mld_type mld_icmp6_hdr.icmp6_type
#define mld_code mld_icmp6_hdr.icmp6_code
#define mld_cksum mld_icmp6_hdr.icmp6_cksum
#define mld_maxdelay mld_icmp6_hdr.icmp6_data16[0]
#define mld_reserved mld_icmp6_hdr.icmp6_data16[1]

#define ICMP6_ROUTER_RENUMBERING 138

struct icmp6_router_renum {
    struct icmp6_hdr rr_hdr;
    uint8_t rr_segnum;
    uint8_t rr_flags;
    uint16_t rr_maxdelay;
    uint32_t rr_reserved;
};

#define rr_type rr_hdr.icmp6_type
#define rr_code rr_hdr.icmp6_code
#define rr_cksum rr_hdr.icmp6_cksum
#define rr_seqnum rr_hdr.icmp6_data32[0]

#define ICMP6_RR_FLAGS_TEST 0x80
#define ICMP6_RR_FLAGS_REQRESULT 0x40
#define ICMP6_RR_FLAGS_FORCEAPPLY 0x20
#define ICMP6_RR_FLAGS_SPECSITE 0x10
#define ICMP6_RR_FLAGS_PREVDONE 0x08

struct rr_pco_match {
    uint8_t rpm_code;
    uint8_t rpm_len;
    uint8_t rpm_ordinal;
    uint8_t rpm_matchlen;
    uint8_t rpm_minlen;
    uint8_t rpm_maxlen;
    uint16_t rpm_reserved;
    struct in6_addr rpm_prefix;
};

#define RPM_PCO_ADD 1
#define RPM_PCO_CHANGE 2
#define RPM_PCO_SETGLOBAL 3

struct rr_pco_use {
    uint8_t rpu_uselen;
    uint8_t rpu_keeplen;
    uint8_t rpu_ramask;
    uint8_t rpu_raflags;
    uint32_t rpu_vltime;
    uint32_t rpu_pltime;
    uint32_t rpu_flags;
    struct in6_addr rpu_prefix;
};

#define ICMP6_RR_PCOUSE_RAFLAGS_ONLINK 0x20
#define ICMP6_RR_PCOUSE_RAFLAGS_AUTO 0x10

#if __BYTE_ORDER == __BIG_ENDIAN
#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME 0x80000000
#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME 0x40000000
#else
#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME 0x80
#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME 0x40
#endif

struct rr_result {
    uint16_t rrr_flags;
    uint8_t rrr_ordinal;
    uint8_t rrr_matchedlen;
    uint32_t rrr_ifid;
    struct in6_addr rrr_prefix;
};

#if __BYTE_ORDER == __BIG_ENDIAN
#define ICMP6_RR_RESULT_FLAGS_OOB 0x0002
#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN 0x0001
#else
#define ICMP6_RR_RESULT_FLAGS_OOB 0x0200
#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN 0x0100
#endif

struct nd_opt_adv_interval {
    uint8_t nd_opt_adv_interval_type;
    uint8_t nd_opt_adv_interval_len;
    uint16_t nd_opt_adv_interval_reserved;
    uint32_t nd_opt_adv_interval_ival;
};

struct nd_opt_home_agent_info {
    uint8_t nd_opt_home_agent_info_type;
    uint8_t nd_opt_home_agent_info_len;
    uint16_t nd_opt_home_agent_info_reserved;
    uint16_t nd_opt_home_agent_info_preference;
    uint16_t nd_opt_home_agent_info_lifetime;
};

#ifdef __cplusplus
}
#endif


<|start_filename|>pkg/fit/include/lib/fit/nullable.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIT_NULLABLE_H_
#define LIB_FIT_NULLABLE_H_

#include <assert.h>

#include <type_traits>
#include <utility>

#include "optional.h"

namespace fit {

// Determines whether a type can be compared with nullptr.
template <typename T, typename Comparable = bool>
struct is_comparable_with_null : public std::false_type {};
template <typename T>
struct is_comparable_with_null<T, decltype(std::declval<const T&>() == nullptr)>
    : public std::true_type {};

// Returns true if a value equals nullptr.
template <typename T, typename Comparable = bool>
struct is_null_predicate {
    constexpr bool operator()(const T& value) { return false; }
};
template <typename T>
struct is_null_predicate<T, decltype(std::declval<const T&>() == nullptr)> {
    constexpr bool operator()(const T& value) { return value == nullptr; }
};
template <typename T>
constexpr inline bool is_null(const T& value) {
    return is_null_predicate<T>()(value);
}

// Determines whether a type can be initialized, assigned, and compared
// with nullptr.
template <typename T>
struct is_nullable
    : public std::integral_constant<
          bool,
          std::is_constructible<T, decltype(nullptr)>::value &&
              std::is_assignable<T&, decltype(nullptr)>::value &&
              is_comparable_with_null<T>::value> {};
template <>
struct is_nullable<void> : public std::false_type {};

// Holds a value or nullptr.
//
// This class is similar to |std::optional<T>| except that it uses less
// storage when the value type can be initialized, assigned, and compared
// with nullptr.
//
// For example:
// - sizeof(fit::nullable<void*>) == sizeof(void*)
// - sizeof(std::optional<void*>) == sizeof(struct { bool; void*; })
// - sizeof(fit::nullable<int>) == sizeof(struct { bool; int; })
// - sizeof(std::optional<int>) == sizeof(struct { bool; int; })
template <typename T, bool = (is_nullable<T>::value &&
                              std::is_constructible<T, T&&>::value &&
                              std::is_assignable<T&, T&&>::value)>
class nullable final {
public:
    using value_type = T;

    constexpr nullable() = default;
    explicit constexpr nullable(decltype(nullptr)) {}
    explicit constexpr nullable(T value)
        : opt_(std::move(value)) {}
    nullable(const nullable& other) = default;
    nullable(nullable&& other) = default;
    ~nullable() = default;

    constexpr T& value() & { return opt_.value(); }
    constexpr const T& value() const& { return opt_.value(); }
    constexpr T&& value() && { return std::move(opt_.value()); }
    constexpr const T&& value() const&& { return std::move(opt_.value()); }

    template <typename U = T>
    constexpr T value_or(U&& default_value) const {
        return opt_.value_or(std::forward<U>(default_value));
    }

    constexpr T* operator->() { return &*opt_; }
    constexpr const T* operator->() const { return &*opt_; }
    constexpr T& operator*() { return *opt_; }
    constexpr const T& operator*() const { return *opt_; }

    constexpr bool has_value() const { return opt_.has_value(); }
    explicit constexpr operator bool() const { return has_value(); }

    nullable& operator=(const nullable& other) = default;
    nullable& operator=(nullable&& other) = default;

    nullable& operator=(decltype(nullptr)) {
        reset();
        return *this;
    }

    nullable& operator=(T value) {
        opt_ = std::move(value);
        return *this;
    }

    void reset() { opt_.reset(); }

    void swap(nullable& other) { opt_.swap(other.opt_); }

private:
    optional<T> opt_;
};

template <typename T>
class nullable<T, true> final {
public:
    using value_type = T;

    constexpr nullable()
        : value_(nullptr) {}
    explicit constexpr nullable(decltype(nullptr))
        : value_(nullptr) {}
    explicit constexpr nullable(T value)
        : value_(std::move(value)) {}
    nullable(const nullable& other) = default;
    nullable(nullable&& other)
        : value_(std::move(other.value_)) {
        other.value_ = nullptr;
    }
    ~nullable() = default;

    constexpr T& value() & {
        assert(has_value());
        return value_;
    }
    constexpr const T& value() const& {
        assert(has_value());
        return value_;
    }
    constexpr T&& value() && {
        assert(has_value());
        return std::move(value_);
    }
    constexpr const T&& value() const&& {
        assert(has_value());
        return std::move(value_);
    }

    template <typename U = T>
    constexpr T value_or(U&& default_value) const {
        return has_value() ? value_ : static_cast<T>(std::forward<U>(default_value));
    }

    constexpr T* operator->() { return &value_; }
    constexpr const T* operator->() const { return &value_; }
    constexpr T& operator*() { return value_; }
    constexpr const T& operator*() const { return value_; }

    constexpr bool has_value() const { return !(value_ == nullptr); }
    explicit constexpr operator bool() const { return has_value(); }

    nullable& operator=(const nullable& other) = default;
    nullable& operator=(nullable&& other) {
        if (&other == this)
            return *this;
        value_ = std::move(other.value_);
        other.value_ = nullptr;
        return *this;
    }

    nullable& operator=(decltype(nullptr)) {
        reset();
        return *this;
    }

    nullable& operator=(T value) {
        value_ = std::move(value);
        return *this;
    }

    void reset() { value_ = nullptr; }

    void swap(nullable& other) {
        using std::swap;
        swap(value_, other.value_);
    }

private:
    T value_;
};

template <typename T>
void swap(nullable<T>& a, nullable<T>& b) {
    a.swap(b);
}

template <typename T>
constexpr bool operator==(const nullable<T>& lhs, decltype(nullptr)) {
    return !lhs.has_value();
}
template <typename T>
constexpr bool operator!=(const nullable<T>& lhs, decltype(nullptr)) {
    return lhs.has_value();
}

template <typename T>
constexpr bool operator==(decltype(nullptr), const nullable<T>& rhs) {
    return !rhs.has_value();
}
template <typename T>
constexpr bool operator!=(decltype(nullptr), const nullable<T>& rhs) {
    return rhs.has_value();
}

template <typename T, typename U>
constexpr bool operator==(const nullable<T>& lhs, const nullable<U>& rhs) {
    return (lhs.has_value() == rhs.has_value()) && (!lhs.has_value() || *lhs == *rhs);
}
template <typename T, typename U>
constexpr bool operator!=(const nullable<T>& lhs, const nullable<U>& rhs) {
    return (lhs.has_value() != rhs.has_value()) || (lhs.has_value() && *lhs != *rhs);
}

template <typename T, typename U>
constexpr bool operator==(const nullable<T>& lhs, const U& rhs) {
    return (lhs.has_value() != is_null(rhs)) && (!lhs.has_value() || *lhs == rhs);
}
template <typename T, typename U>
constexpr bool operator!=(const nullable<T>& lhs, const U& rhs) {
    return (lhs.has_value() == is_null(rhs)) || (lhs.has_value() && *lhs != rhs);
}

template <typename T, typename U>
constexpr bool operator==(const T& lhs, const nullable<U>& rhs) {
    return (is_null(lhs) != rhs.has_value()) && (!rhs.has_value() || lhs == *rhs);
}
template <typename T, typename U>
constexpr bool operator!=(const T& lhs, const nullable<U>& rhs) {
    return (is_null(lhs) == rhs.has_value()) || (rhs.has_value() && lhs != *rhs);
}

} // namespace fit

#endif // LIB_FIT_NULLABLE_H_


<|start_filename|>arch/x64/sysroot/include/sys/utsname.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>

struct utsname {
    char sysname[65];
    char nodename[65];
    char release[65];
    char version[65];
    char machine[65];
#ifdef _GNU_SOURCE
    char domainname[65];
#else
    char __domainname[65];
#endif
};

int uname(struct utsname*);

#ifdef __cplusplus
}
#endif


<|start_filename|>arch/x64/sysroot/include/zircon/syscalls/definitions.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// This is a GENERATED file, see //zircon/system/host/abigen.
// The license governing this file can be found in the LICENSE file.

extern zx_time_t zx_clock_get(
    zx_clock_t clock_id) __LEAF_FN;

extern zx_time_t _zx_clock_get(
    zx_clock_t clock_id) __LEAF_FN;

extern zx_status_t zx_clock_get_new(
    zx_clock_t clock_id,
    zx_time_t* out) __NONNULL((2)) __LEAF_FN;

extern zx_status_t _zx_clock_get_new(
    zx_clock_t clock_id,
    zx_time_t* out) __NONNULL((2)) __LEAF_FN;

extern zx_time_t zx_clock_get_monotonic(
    void) __LEAF_FN;

extern zx_time_t _zx_clock_get_monotonic(
    void) __LEAF_FN;

extern zx_status_t zx_nanosleep(
    zx_time_t deadline) __LEAF_FN;

extern zx_status_t _zx_nanosleep(
    zx_time_t deadline) __LEAF_FN;

extern zx_ticks_t zx_ticks_get(
    void) __LEAF_FN;

extern zx_ticks_t _zx_ticks_get(
    void) __LEAF_FN;

extern zx_ticks_t zx_ticks_per_second(
    void) __LEAF_FN __CONST;

extern zx_ticks_t _zx_ticks_per_second(
    void) __LEAF_FN __CONST;

extern zx_time_t zx_deadline_after(
    zx_duration_t nanoseconds) __LEAF_FN;

extern zx_time_t _zx_deadline_after(
    zx_duration_t nanoseconds) __LEAF_FN;

extern zx_status_t zx_clock_adjust(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_clock_t clock_id,
    int64_t offset) __LEAF_FN;

extern zx_status_t _zx_clock_adjust(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_clock_t clock_id,
    int64_t offset) __LEAF_FN;

extern uint32_t zx_system_get_dcache_line_size(
    void) __LEAF_FN __CONST;

extern uint32_t _zx_system_get_dcache_line_size(
    void) __LEAF_FN __CONST;

extern uint32_t zx_system_get_num_cpus(
    void) __LEAF_FN __CONST;

extern uint32_t _zx_system_get_num_cpus(
    void) __LEAF_FN __CONST;

extern zx_status_t zx_system_get_version(
    char* version,
    size_t version_size) __LEAF_FN;

extern zx_status_t _zx_system_get_version(
    char* version,
    size_t version_size) __LEAF_FN;

extern uint64_t zx_system_get_physmem(
    void) __LEAF_FN;

extern uint64_t _zx_system_get_physmem(
    void) __LEAF_FN;

extern zx_status_t zx_system_get_features(
    uint32_t kind,
    ZX_SYSCALL_PARAM_ATTR(features) uint32_t* features) __NONNULL((2)) __LEAF_FN;

extern zx_status_t _zx_system_get_features(
    uint32_t kind,
    ZX_SYSCALL_PARAM_ATTR(features) uint32_t* features) __NONNULL((2)) __LEAF_FN;

extern zx_status_t zx_cache_flush(
    const void* addr,
    size_t size,
    uint32_t options) __LEAF_FN;

extern zx_status_t _zx_cache_flush(
    const void* addr,
    size_t size,
    uint32_t options) __LEAF_FN;

extern zx_status_t zx_handle_close(
    ZX_SYSCALL_PARAM_ATTR(handle_release_always) zx_handle_t handle) __LEAF_FN;

extern zx_status_t _zx_handle_close(
    ZX_SYSCALL_PARAM_ATTR(handle_release_always) zx_handle_t handle) __LEAF_FN;

extern zx_status_t zx_handle_close_many(
    const zx_handle_t* handles,
    size_t num_handles) __LEAF_FN;

extern zx_status_t _zx_handle_close_many(
    const zx_handle_t* handles,
    size_t num_handles) __LEAF_FN;

extern zx_status_t zx_handle_duplicate(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_rights_t rights,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_handle_duplicate(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_rights_t rights,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_handle_replace(
    ZX_SYSCALL_PARAM_ATTR(handle_release_always) zx_handle_t handle,
    zx_rights_t rights,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_handle_replace(
    ZX_SYSCALL_PARAM_ATTR(handle_release_always) zx_handle_t handle,
    zx_rights_t rights,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_object_wait_one(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_signals_t signals,
    zx_time_t deadline,
    zx_signals_t* observed) __LEAF_FN;

extern zx_status_t _zx_object_wait_one(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_signals_t signals,
    zx_time_t deadline,
    zx_signals_t* observed) __LEAF_FN;

extern zx_status_t zx_object_wait_many(
    zx_wait_item_t* items,
    size_t count,
    zx_time_t deadline) __LEAF_FN;

extern zx_status_t _zx_object_wait_many(
    zx_wait_item_t* items,
    size_t count,
    zx_time_t deadline) __LEAF_FN;

extern zx_status_t zx_object_wait_async(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port,
    uint64_t key,
    zx_signals_t signals,
    uint32_t options) __LEAF_FN;

extern zx_status_t _zx_object_wait_async(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port,
    uint64_t key,
    zx_signals_t signals,
    uint32_t options) __LEAF_FN;

extern zx_status_t zx_object_signal(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t clear_mask,
    uint32_t set_mask) __LEAF_FN;

extern zx_status_t _zx_object_signal(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t clear_mask,
    uint32_t set_mask) __LEAF_FN;

extern zx_status_t zx_object_signal_peer(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t clear_mask,
    uint32_t set_mask) __LEAF_FN;

extern zx_status_t _zx_object_signal_peer(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t clear_mask,
    uint32_t set_mask) __LEAF_FN;

extern zx_status_t zx_object_get_property(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t property,
    void* value,
    size_t value_size) __LEAF_FN;

extern zx_status_t _zx_object_get_property(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t property,
    void* value,
    size_t value_size) __LEAF_FN;

extern zx_status_t zx_object_set_property(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t property,
    const void* value,
    size_t value_size) __LEAF_FN;

extern zx_status_t _zx_object_set_property(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t property,
    const void* value,
    size_t value_size) __LEAF_FN;

extern zx_status_t zx_object_set_cookie(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t scope,
    uint64_t cookie) __LEAF_FN;

extern zx_status_t _zx_object_set_cookie(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t scope,
    uint64_t cookie) __LEAF_FN;

extern zx_status_t zx_object_get_cookie(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t scope,
    uint64_t* cookie) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_object_get_cookie(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t scope,
    uint64_t* cookie) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_object_get_info(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t topic,
    void* buffer,
    size_t buffer_size,
    size_t* actual_count,
    size_t* avail_count) __LEAF_FN;

extern zx_status_t _zx_object_get_info(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t topic,
    void* buffer,
    size_t buffer_size,
    size_t* actual_count,
    size_t* avail_count) __LEAF_FN;

extern zx_status_t zx_object_get_child(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint64_t koid,
    zx_rights_t rights,
    zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t _zx_object_get_child(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint64_t koid,
    zx_rights_t rights,
    zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t zx_object_set_profile(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t profile,
    uint32_t options) __LEAF_FN;

extern zx_status_t _zx_object_set_profile(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t profile,
    uint32_t options) __LEAF_FN;

extern zx_status_t zx_channel_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out0,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out1) __NONNULL((2, 3)) __LEAF_FN;

extern zx_status_t _zx_channel_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out0,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out1) __NONNULL((2, 3)) __LEAF_FN;

extern zx_status_t zx_channel_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    void* bytes,
    zx_handle_t* handles,
    uint32_t num_bytes,
    uint32_t num_handles,
    uint32_t* actual_bytes,
    uint32_t* actual_handles) __LEAF_FN;

extern zx_status_t _zx_channel_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    void* bytes,
    zx_handle_t* handles,
    uint32_t num_bytes,
    uint32_t num_handles,
    uint32_t* actual_bytes,
    uint32_t* actual_handles) __LEAF_FN;

extern zx_status_t zx_channel_read_etc(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    void* bytes,
    zx_handle_info_t* handles,
    uint32_t num_bytes,
    uint32_t num_handles,
    uint32_t* actual_bytes,
    uint32_t* actual_handles) __LEAF_FN;

extern zx_status_t _zx_channel_read_etc(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    void* bytes,
    zx_handle_info_t* handles,
    uint32_t num_bytes,
    uint32_t num_handles,
    uint32_t* actual_bytes,
    uint32_t* actual_handles) __LEAF_FN;

extern zx_status_t zx_channel_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    const void* bytes,
    uint32_t num_bytes,
    const zx_handle_t* handles,
    uint32_t num_handles) __LEAF_FN;

extern zx_status_t _zx_channel_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    const void* bytes,
    uint32_t num_bytes,
    const zx_handle_t* handles,
    uint32_t num_handles) __LEAF_FN;

extern zx_status_t zx_channel_call(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    zx_time_t deadline,
    const zx_channel_call_args_t* args,
    uint32_t* actual_bytes,
    uint32_t* actual_handles) __NONNULL((5, 6)) __LEAF_FN;

extern zx_status_t _zx_channel_call(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    zx_time_t deadline,
    const zx_channel_call_args_t* args,
    uint32_t* actual_bytes,
    uint32_t* actual_handles) __NONNULL((5, 6)) __LEAF_FN;

extern zx_status_t zx_socket_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out0,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out1) __NONNULL((2, 3)) __LEAF_FN;

extern zx_status_t _zx_socket_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out0,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out1) __NONNULL((2, 3)) __LEAF_FN;

extern zx_status_t zx_socket_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    const void* buffer,
    size_t buffer_size,
    size_t* actual) __LEAF_FN;

extern zx_status_t _zx_socket_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    const void* buffer,
    size_t buffer_size,
    size_t* actual) __LEAF_FN;

extern zx_status_t zx_socket_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    void* buffer,
    size_t buffer_size,
    size_t* actual) __LEAF_FN;

extern zx_status_t _zx_socket_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    void* buffer,
    size_t buffer_size,
    size_t* actual) __LEAF_FN;

extern zx_status_t zx_socket_share(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t socket_to_share) __LEAF_FN;

extern zx_status_t _zx_socket_share(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t socket_to_share) __LEAF_FN;

extern zx_status_t zx_socket_accept(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out_socket) __NONNULL((2)) __LEAF_FN;

extern zx_status_t _zx_socket_accept(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out_socket) __NONNULL((2)) __LEAF_FN;

extern zx_status_t zx_socket_shutdown(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options) __LEAF_FN;

extern zx_status_t _zx_socket_shutdown(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options) __LEAF_FN;

extern void zx_thread_exit(
    void) __LEAF_FN __NO_RETURN;

extern void _zx_thread_exit(
    void) __LEAF_FN __NO_RETURN;

extern zx_status_t zx_thread_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t process,
    const char* name,
    size_t name_size,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((5)) __LEAF_FN;

extern zx_status_t _zx_thread_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t process,
    const char* name,
    size_t name_size,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((5)) __LEAF_FN;

extern zx_status_t zx_thread_start(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vaddr_t thread_entry,
    zx_vaddr_t stack,
    uintptr_t arg1,
    uintptr_t arg2) __LEAF_FN;

extern zx_status_t _zx_thread_start(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vaddr_t thread_entry,
    zx_vaddr_t stack,
    uintptr_t arg1,
    uintptr_t arg2) __LEAF_FN;

extern zx_status_t zx_thread_read_state(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_thread_read_state(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_thread_write_state(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    const void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_thread_write_state(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    const void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_thread_set_priority(
    int32_t prio) __LEAF_FN;

extern zx_status_t _zx_thread_set_priority(
    int32_t prio) __LEAF_FN;

extern void zx_process_exit(
    int64_t retcode) __LEAF_FN __NO_RETURN;

extern void _zx_process_exit(
    int64_t retcode) __LEAF_FN __NO_RETURN;

extern zx_status_t zx_process_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t job,
    const char* name,
    size_t name_size,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* proc_handle,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* vmar_handle) __NONNULL((5, 6)) __LEAF_FN;

extern zx_status_t _zx_process_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t job,
    const char* name,
    size_t name_size,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* proc_handle,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* vmar_handle) __NONNULL((5, 6)) __LEAF_FN;

extern zx_status_t zx_process_start(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t thread,
    zx_vaddr_t entry,
    zx_vaddr_t stack,
    ZX_SYSCALL_PARAM_ATTR(handle_release_always) zx_handle_t arg1,
    uintptr_t arg2) __LEAF_FN;

extern zx_status_t _zx_process_start(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t thread,
    zx_vaddr_t entry,
    zx_vaddr_t stack,
    ZX_SYSCALL_PARAM_ATTR(handle_release_always) zx_handle_t arg1,
    uintptr_t arg2) __LEAF_FN;

extern zx_status_t zx_process_read_memory(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vaddr_t vaddr,
    void* buffer,
    size_t buffer_size,
    size_t* actual) __NONNULL((5)) __LEAF_FN;

extern zx_status_t _zx_process_read_memory(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vaddr_t vaddr,
    void* buffer,
    size_t buffer_size,
    size_t* actual) __NONNULL((5)) __LEAF_FN;

extern zx_status_t zx_process_write_memory(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vaddr_t vaddr,
    const void* buffer,
    size_t buffer_size,
    size_t* actual) __NONNULL((5)) __LEAF_FN;

extern zx_status_t _zx_process_write_memory(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vaddr_t vaddr,
    const void* buffer,
    size_t buffer_size,
    size_t* actual) __NONNULL((5)) __LEAF_FN;

extern zx_status_t zx_job_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t parent_job,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_job_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t parent_job,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_job_set_policy(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    uint32_t topic,
    const void* policy,
    uint32_t count) __LEAF_FN;

extern zx_status_t _zx_job_set_policy(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    uint32_t topic,
    const void* policy,
    uint32_t count) __LEAF_FN;

extern zx_status_t zx_task_bind_exception_port(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port,
    uint64_t key,
    uint32_t options) __LEAF_FN;

extern zx_status_t _zx_task_bind_exception_port(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port,
    uint64_t key,
    uint32_t options) __LEAF_FN;

extern zx_status_t zx_task_suspend(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* token) __NONNULL((2)) __LEAF_FN;

extern zx_status_t _zx_task_suspend(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* token) __NONNULL((2)) __LEAF_FN;

extern zx_status_t zx_task_suspend_token(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* token) __NONNULL((2)) __LEAF_FN;

extern zx_status_t _zx_task_suspend_token(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* token) __NONNULL((2)) __LEAF_FN;

extern zx_status_t zx_task_resume_from_exception(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port,
    uint32_t options) __LEAF_FN;

extern zx_status_t _zx_task_resume_from_exception(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port,
    uint32_t options) __LEAF_FN;

extern zx_status_t zx_task_kill(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t _zx_task_kill(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t zx_event_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((2)) __LEAF_FN;

extern zx_status_t _zx_event_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((2)) __LEAF_FN;

extern zx_status_t zx_eventpair_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out0,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out1) __NONNULL((2, 3)) __LEAF_FN;

extern zx_status_t _zx_eventpair_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out0,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out1) __NONNULL((2, 3)) __LEAF_FN;

extern zx_status_t zx_futex_wait(
    const zx_futex_t* value_ptr,
    zx_futex_t current_value,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t new_futex_owner,
    zx_time_t deadline) __LEAF_FN;

extern zx_status_t _zx_futex_wait(
    const zx_futex_t* value_ptr,
    zx_futex_t current_value,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t new_futex_owner,
    zx_time_t deadline) __LEAF_FN;

extern zx_status_t zx_futex_wake(
    const zx_futex_t* value_ptr,
    uint32_t count) __LEAF_FN;

extern zx_status_t _zx_futex_wake(
    const zx_futex_t* value_ptr,
    uint32_t count) __LEAF_FN;

extern zx_status_t zx_futex_requeue(
    const zx_futex_t* wake_ptr,
    uint32_t wake_count,
    zx_futex_t current_value,
    const zx_futex_t* requeue_ptr,
    uint32_t requeue_count,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t new_requeue_owner) __LEAF_FN;

extern zx_status_t _zx_futex_requeue(
    const zx_futex_t* wake_ptr,
    uint32_t wake_count,
    zx_futex_t current_value,
    const zx_futex_t* requeue_ptr,
    uint32_t requeue_count,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t new_requeue_owner) __LEAF_FN;

extern zx_status_t zx_futex_wake_single_owner(
    const zx_futex_t* value_ptr) __LEAF_FN;

extern zx_status_t _zx_futex_wake_single_owner(
    const zx_futex_t* value_ptr) __LEAF_FN;

extern zx_status_t zx_futex_requeue_single_owner(
    const zx_futex_t* wake_ptr,
    zx_futex_t current_value,
    const zx_futex_t* requeue_ptr,
    uint32_t requeue_count,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t new_requeue_owner) __LEAF_FN;

extern zx_status_t _zx_futex_requeue_single_owner(
    const zx_futex_t* wake_ptr,
    zx_futex_t current_value,
    const zx_futex_t* requeue_ptr,
    uint32_t requeue_count,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t new_requeue_owner) __LEAF_FN;

extern zx_status_t zx_futex_get_owner(
    const zx_futex_t* value_ptr,
    zx_koid_t* koid) __LEAF_FN;

extern zx_status_t _zx_futex_get_owner(
    const zx_futex_t* value_ptr,
    zx_koid_t* koid) __LEAF_FN;

extern zx_status_t zx_futex_wait_deprecated(
    const zx_futex_t* value_ptr,
    int32_t current_value,
    zx_time_t deadline) __LEAF_FN;

extern zx_status_t _zx_futex_wait_deprecated(
    const zx_futex_t* value_ptr,
    int32_t current_value,
    zx_time_t deadline) __LEAF_FN;

extern zx_status_t zx_futex_requeue_deprecated(
    const zx_futex_t* wake_ptr,
    uint32_t wake_count,
    int32_t current_value,
    const zx_futex_t* requeue_ptr,
    uint32_t requeue_count) __LEAF_FN;

extern zx_status_t _zx_futex_requeue_deprecated(
    const zx_futex_t* wake_ptr,
    uint32_t wake_count,
    int32_t current_value,
    const zx_futex_t* requeue_ptr,
    uint32_t requeue_count) __LEAF_FN;

extern zx_status_t zx_port_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((2)) __LEAF_FN;

extern zx_status_t _zx_port_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((2)) __LEAF_FN;

extern zx_status_t zx_port_queue(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    const zx_port_packet_t* packet) __LEAF_FN;

extern zx_status_t _zx_port_queue(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    const zx_port_packet_t* packet) __LEAF_FN;

extern zx_status_t zx_port_wait(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_time_t deadline,
    zx_port_packet_t* packet) __LEAF_FN;

extern zx_status_t _zx_port_wait(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_time_t deadline,
    zx_port_packet_t* packet) __LEAF_FN;

extern zx_status_t zx_port_cancel(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t source,
    uint64_t key) __LEAF_FN;

extern zx_status_t _zx_port_cancel(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t source,
    uint64_t key) __LEAF_FN;

extern zx_status_t zx_timer_create(
    uint32_t options,
    zx_clock_t clock_id,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_timer_create(
    uint32_t options,
    zx_clock_t clock_id,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_timer_set(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_time_t deadline,
    zx_duration_t slack) __LEAF_FN;

extern zx_status_t _zx_timer_set(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_time_t deadline,
    zx_duration_t slack) __LEAF_FN;

extern zx_status_t zx_timer_cancel(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t _zx_timer_cancel(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t zx_vmo_create(
    uint64_t size,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_vmo_create(
    uint64_t size,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_vmo_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    void* buffer,
    uint64_t offset,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_vmo_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    void* buffer,
    uint64_t offset,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_vmo_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    const void* buffer,
    uint64_t offset,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_vmo_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    const void* buffer,
    uint64_t offset,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_vmo_get_size(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint64_t* size) __NONNULL((2)) __LEAF_FN;

extern zx_status_t _zx_vmo_get_size(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint64_t* size) __NONNULL((2)) __LEAF_FN;

extern zx_status_t zx_vmo_set_size(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint64_t size) __LEAF_FN;

extern zx_status_t _zx_vmo_set_size(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint64_t size) __LEAF_FN;

extern zx_status_t zx_vmo_op_range(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t op,
    uint64_t offset,
    uint64_t size,
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_vmo_op_range(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t op,
    uint64_t offset,
    uint64_t size,
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_vmo_clone(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    uint64_t offset,
    uint64_t size,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((5)) __LEAF_FN;

extern zx_status_t _zx_vmo_clone(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    uint64_t offset,
    uint64_t size,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((5)) __LEAF_FN;

extern zx_status_t zx_vmo_set_cache_policy(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t cache_policy) __LEAF_FN;

extern zx_status_t _zx_vmo_set_cache_policy(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t cache_policy) __LEAF_FN;

extern zx_status_t zx_vmo_replace_as_executable(
    ZX_SYSCALL_PARAM_ATTR(handle_release_always) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmex,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_vmo_replace_as_executable(
    ZX_SYSCALL_PARAM_ATTR(handle_release_always) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmex,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_vmar_allocate_old(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t parent_vmar,
    uint64_t offset,
    uint64_t size,
    uint32_t map_flags,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* child_vmar,
    zx_vaddr_t* child_addr) __NONNULL((5, 6)) __LEAF_FN;

extern zx_status_t _zx_vmar_allocate_old(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t parent_vmar,
    uint64_t offset,
    uint64_t size,
    uint32_t map_flags,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* child_vmar,
    zx_vaddr_t* child_addr) __NONNULL((5, 6)) __LEAF_FN;

extern zx_status_t zx_vmar_map_old(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint64_t vmar_offset,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmo,
    uint64_t vmo_offset,
    uint64_t len,
    uint32_t map_flags,
    zx_vaddr_t* mapped_addr) __NONNULL((7)) __LEAF_FN;

extern zx_status_t _zx_vmar_map_old(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint64_t vmar_offset,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmo,
    uint64_t vmo_offset,
    uint64_t len,
    uint32_t map_flags,
    zx_vaddr_t* mapped_addr) __NONNULL((7)) __LEAF_FN;

extern zx_status_t zx_vmar_protect_old(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vaddr_t addr,
    uint64_t len,
    uint32_t prot_flags) __LEAF_FN;

extern zx_status_t _zx_vmar_protect_old(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vaddr_t addr,
    uint64_t len,
    uint32_t prot_flags) __LEAF_FN;

extern zx_status_t zx_vmar_allocate(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t parent_vmar,
    zx_vm_option_t options,
    uint64_t offset,
    uint64_t size,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* child_vmar,
    zx_vaddr_t* child_addr) __NONNULL((5, 6)) __LEAF_FN;

extern zx_status_t _zx_vmar_allocate(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t parent_vmar,
    zx_vm_option_t options,
    uint64_t offset,
    uint64_t size,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* child_vmar,
    zx_vaddr_t* child_addr) __NONNULL((5, 6)) __LEAF_FN;

extern zx_status_t zx_vmar_destroy(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t _zx_vmar_destroy(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t zx_vmar_map(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vm_option_t options,
    uint64_t vmar_offset,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmo,
    uint64_t vmo_offset,
    uint64_t len,
    zx_vaddr_t* mapped_addr) __NONNULL((7)) __LEAF_FN;

extern zx_status_t _zx_vmar_map(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vm_option_t options,
    uint64_t vmar_offset,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmo,
    uint64_t vmo_offset,
    uint64_t len,
    zx_vaddr_t* mapped_addr) __NONNULL((7)) __LEAF_FN;

extern zx_status_t zx_vmar_unmap(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vaddr_t addr,
    uint64_t len) __LEAF_FN;

extern zx_status_t _zx_vmar_unmap(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vaddr_t addr,
    uint64_t len) __LEAF_FN;

extern zx_status_t zx_vmar_protect(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vm_option_t options,
    zx_vaddr_t addr,
    uint64_t len) __LEAF_FN;

extern zx_status_t _zx_vmar_protect(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_vm_option_t options,
    zx_vaddr_t addr,
    uint64_t len) __LEAF_FN;

extern void zx_cprng_draw(
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern void _zx_cprng_draw(
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_cprng_add_entropy(
    const void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_cprng_add_entropy(
    const void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_fifo_create(
    size_t elem_count,
    size_t elem_size,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out0,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out1) __NONNULL((4, 5)) __LEAF_FN;

extern zx_status_t _zx_fifo_create(
    size_t elem_count,
    size_t elem_size,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out0,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out1) __NONNULL((4, 5)) __LEAF_FN;

extern zx_status_t zx_fifo_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    size_t elem_size,
    void* data,
    size_t count,
    size_t* actual_count) __LEAF_FN;

extern zx_status_t _zx_fifo_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    size_t elem_size,
    void* data,
    size_t count,
    size_t* actual_count) __LEAF_FN;

extern zx_status_t zx_fifo_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    size_t elem_size,
    const void* data,
    size_t count,
    size_t* actual_count) __LEAF_FN;

extern zx_status_t _zx_fifo_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    size_t elem_size,
    const void* data,
    size_t count,
    size_t* actual_count) __LEAF_FN;

extern zx_status_t zx_profile_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t root_job,
    const zx_profile_info_t* profile,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_profile_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t root_job,
    const zx_profile_info_t* profile,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_vmar_unmap_handle_close_thread_exit(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmar_handle,
    zx_vaddr_t addr,
    size_t size,
    ZX_SYSCALL_PARAM_ATTR(handle_release) zx_handle_t close_handle) __LEAF_FN;

extern zx_status_t _zx_vmar_unmap_handle_close_thread_exit(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmar_handle,
    zx_vaddr_t addr,
    size_t size,
    ZX_SYSCALL_PARAM_ATTR(handle_release) zx_handle_t close_handle) __LEAF_FN;

extern void zx_futex_wake_handle_close_thread_exit(
    const zx_futex_t* value_ptr,
    uint32_t count,
    int32_t new_value,
    ZX_SYSCALL_PARAM_ATTR(handle_release) zx_handle_t handle) __LEAF_FN __NO_RETURN;

extern void _zx_futex_wake_handle_close_thread_exit(
    const zx_futex_t* value_ptr,
    uint32_t count,
    int32_t new_value,
    ZX_SYSCALL_PARAM_ATTR(handle_release) zx_handle_t handle) __LEAF_FN __NO_RETURN;

extern zx_status_t zx_log_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t len,
    const void* buffer,
    uint32_t options) __LEAF_FN;

extern zx_status_t _zx_log_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t len,
    const void* buffer,
    uint32_t options) __LEAF_FN;

extern zx_status_t zx_log_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t len,
    void* buffer,
    uint32_t options) __LEAF_FN;

extern zx_status_t _zx_log_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t len,
    void* buffer,
    uint32_t options) __LEAF_FN;

extern zx_status_t zx_debuglog_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_debuglog_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_debuglog_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    const void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_debuglog_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    const void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_debuglog_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_debuglog_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_ktrace_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    void* data,
    uint32_t offset,
    size_t data_size,
    size_t* actual) __NONNULL((5)) __LEAF_FN;

extern zx_status_t _zx_ktrace_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    void* data,
    uint32_t offset,
    size_t data_size,
    size_t* actual) __NONNULL((5)) __LEAF_FN;

extern zx_status_t zx_ktrace_control(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t action,
    uint32_t options,
    void* ptr) __LEAF_FN;

extern zx_status_t _zx_ktrace_control(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t action,
    uint32_t options,
    void* ptr) __LEAF_FN;

extern zx_status_t zx_ktrace_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t id,
    uint32_t arg0,
    uint32_t arg1) __LEAF_FN;

extern zx_status_t _zx_ktrace_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t id,
    uint32_t arg0,
    uint32_t arg1) __LEAF_FN;

extern zx_status_t zx_mtrace_control(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    uint32_t action,
    uint32_t options,
    void* ptr,
    size_t ptr_size) __LEAF_FN;

extern zx_status_t _zx_mtrace_control(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    uint32_t action,
    uint32_t options,
    void* ptr,
    size_t ptr_size) __LEAF_FN;

extern zx_status_t zx_debug_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    char* buffer,
    size_t* buffer_size) __LEAF_FN;

extern zx_status_t _zx_debug_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    char* buffer,
    size_t* buffer_size) __LEAF_FN;

extern zx_status_t zx_debug_write(
    const char* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_debug_write(
    const char* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_debug_send_command(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    const char* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_debug_send_command(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    const char* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_interrupt_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t src_obj,
    uint32_t src_num,
    uint32_t options,
    zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t _zx_interrupt_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t src_obj,
    uint32_t src_num,
    uint32_t options,
    zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t zx_interrupt_bind(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port,
    uint64_t key,
    uint32_t options) __LEAF_FN;

extern zx_status_t _zx_interrupt_bind(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port,
    uint64_t key,
    uint32_t options) __LEAF_FN;

extern zx_status_t zx_interrupt_wait(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_time_t* out_timestamp) __LEAF_FN;

extern zx_status_t _zx_interrupt_wait(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_time_t* out_timestamp) __LEAF_FN;

extern zx_status_t zx_interrupt_destroy(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t _zx_interrupt_destroy(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t zx_interrupt_ack(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t _zx_interrupt_ack(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t zx_interrupt_trigger(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    zx_time_t timestamp) __LEAF_FN;

extern zx_status_t _zx_interrupt_trigger(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    zx_time_t timestamp) __LEAF_FN;

extern zx_status_t zx_interrupt_bind_vcpu(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vcpu,
    uint32_t options) __LEAF_FN;

extern zx_status_t _zx_interrupt_bind_vcpu(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vcpu,
    uint32_t options) __LEAF_FN;

extern zx_status_t zx_ioports_request(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint16_t io_addr,
    uint32_t len) __LEAF_FN;

extern zx_status_t _zx_ioports_request(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint16_t io_addr,
    uint32_t len) __LEAF_FN;

extern zx_status_t zx_vmo_create_contiguous(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t bti,
    size_t size,
    uint32_t alignment_log2,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t _zx_vmo_create_contiguous(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t bti,
    size_t size,
    uint32_t alignment_log2,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t zx_vmo_create_physical(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    zx_paddr_t paddr,
    size_t size,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t _zx_vmo_create_physical(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    zx_paddr_t paddr,
    size_t size,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t zx_iommu_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint32_t type,
    const void* desc,
    size_t desc_size,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((5)) __LEAF_FN;

extern zx_status_t _zx_iommu_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint32_t type,
    const void* desc,
    size_t desc_size,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((5)) __LEAF_FN;

extern zx_status_t zx_bti_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t iommu,
    uint32_t options,
    uint64_t bti_id,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t _zx_bti_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t iommu,
    uint32_t options,
    uint64_t bti_id,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t zx_bti_pin(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmo,
    uint64_t offset,
    uint64_t size,
    zx_paddr_t* addrs,
    size_t addrs_count,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* pmt) __NONNULL((8)) __LEAF_FN;

extern zx_status_t _zx_bti_pin(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmo,
    uint64_t offset,
    uint64_t size,
    zx_paddr_t* addrs,
    size_t addrs_count,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* pmt) __NONNULL((8)) __LEAF_FN;

extern zx_status_t zx_bti_release_quarantine(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t _zx_bti_release_quarantine(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t zx_pmt_unpin(
    ZX_SYSCALL_PARAM_ATTR(handle_release_always) zx_handle_t handle) __LEAF_FN;

extern zx_status_t _zx_pmt_unpin(
    ZX_SYSCALL_PARAM_ATTR(handle_release_always) zx_handle_t handle) __LEAF_FN;

extern zx_status_t zx_framebuffer_get_info(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint32_t* format,
    uint32_t* width,
    uint32_t* height,
    uint32_t* stride) __NONNULL((2, 3, 4, 5)) __LEAF_FN;

extern zx_status_t _zx_framebuffer_get_info(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint32_t* format,
    uint32_t* width,
    uint32_t* height,
    uint32_t* stride) __NONNULL((2, 3, 4, 5)) __LEAF_FN;

extern zx_status_t zx_framebuffer_set_range(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmo,
    uint32_t len,
    uint32_t format,
    uint32_t width,
    uint32_t height,
    uint32_t stride) __LEAF_FN;

extern zx_status_t _zx_framebuffer_set_range(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t vmo,
    uint32_t len,
    uint32_t format,
    uint32_t width,
    uint32_t height,
    uint32_t stride) __LEAF_FN;

extern zx_status_t zx_pci_get_nth_device(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t index,
    zx_pcie_device_info_t* out_info,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out_handle) __NONNULL((3, 4)) __LEAF_FN;

extern zx_status_t _zx_pci_get_nth_device(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t index,
    zx_pcie_device_info_t* out_info,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out_handle) __NONNULL((3, 4)) __LEAF_FN;

extern zx_status_t zx_pci_enable_bus_master(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    bool enable) __LEAF_FN;

extern zx_status_t _zx_pci_enable_bus_master(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    bool enable) __LEAF_FN;

extern zx_status_t zx_pci_reset_device(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t _zx_pci_reset_device(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle) __LEAF_FN;

extern zx_status_t zx_pci_config_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint16_t offset,
    size_t width,
    uint32_t* out_val) __LEAF_FN;

extern zx_status_t _zx_pci_config_read(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint16_t offset,
    size_t width,
    uint32_t* out_val) __LEAF_FN;

extern zx_status_t zx_pci_config_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint16_t offset,
    size_t width,
    uint32_t val) __LEAF_FN;

extern zx_status_t _zx_pci_config_write(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint16_t offset,
    size_t width,
    uint32_t val) __LEAF_FN;

extern zx_status_t zx_pci_cfg_pio_rw(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint8_t bus,
    uint8_t dev,
    uint8_t func,
    uint8_t offset,
    uint32_t* val,
    size_t width,
    bool write) __LEAF_FN;

extern zx_status_t _zx_pci_cfg_pio_rw(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint8_t bus,
    uint8_t dev,
    uint8_t func,
    uint8_t offset,
    uint32_t* val,
    size_t width,
    bool write) __LEAF_FN;

extern zx_status_t zx_pci_get_bar(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t bar_num,
    zx_pci_bar_t* out_bar,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out_handle) __NONNULL((4)) __LEAF_FN;

extern zx_status_t _zx_pci_get_bar(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t bar_num,
    zx_pci_bar_t* out_bar,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out_handle) __NONNULL((4)) __LEAF_FN;

extern zx_status_t zx_pci_map_interrupt(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    int32_t which_irq,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out_handle) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_pci_map_interrupt(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    int32_t which_irq,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out_handle) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_pci_query_irq_mode(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t mode,
    uint32_t* out_max_irqs) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_pci_query_irq_mode(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t mode,
    uint32_t* out_max_irqs) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_pci_set_irq_mode(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t mode,
    uint32_t requested_irq_count) __LEAF_FN;

extern zx_status_t _zx_pci_set_irq_mode(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t mode,
    uint32_t requested_irq_count) __LEAF_FN;

extern zx_status_t zx_pci_init(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    const zx_pci_init_arg_t* init_buf,
    uint32_t len) __LEAF_FN;

extern zx_status_t _zx_pci_init(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    const zx_pci_init_arg_t* init_buf,
    uint32_t len) __LEAF_FN;

extern zx_status_t zx_pci_add_subtract_io_range(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    bool mmio,
    uint64_t base,
    uint64_t len,
    bool add) __LEAF_FN;

extern zx_status_t _zx_pci_add_subtract_io_range(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    bool mmio,
    uint64_t base,
    uint64_t len,
    bool add) __LEAF_FN;

extern zx_status_t zx_pc_firmware_tables(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_paddr_t* acpi_rsdp,
    zx_paddr_t* smbios) __NONNULL((2, 3)) __LEAF_FN;

extern zx_status_t _zx_pc_firmware_tables(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_paddr_t* acpi_rsdp,
    zx_paddr_t* smbios) __NONNULL((2, 3)) __LEAF_FN;

extern zx_status_t zx_smc_call(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    const zx_smc_parameters_t* parameters,
    zx_smc_result_t* out_smc_result) __NONNULL((3)) __LEAF_FN;

extern zx_status_t _zx_smc_call(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    const zx_smc_parameters_t* parameters,
    zx_smc_result_t* out_smc_result) __NONNULL((3)) __LEAF_FN;

extern zx_status_t zx_resource_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t parent_rsrc,
    uint32_t options,
    uint64_t base,
    size_t size,
    const char* name,
    size_t name_size,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* resource_out) __NONNULL((7)) __LEAF_FN;

extern zx_status_t _zx_resource_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t parent_rsrc,
    uint32_t options,
    uint64_t base,
    size_t size,
    const char* name,
    size_t name_size,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* resource_out) __NONNULL((7)) __LEAF_FN;

extern zx_status_t zx_guest_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* guest_handle,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* vmar_handle) __NONNULL((3, 4)) __LEAF_FN;

extern zx_status_t _zx_guest_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* guest_handle,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* vmar_handle) __NONNULL((3, 4)) __LEAF_FN;

extern zx_status_t zx_guest_set_trap(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    zx_vaddr_t addr,
    size_t size,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port_handle,
    uint64_t key) __LEAF_FN;

extern zx_status_t _zx_guest_set_trap(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    zx_vaddr_t addr,
    size_t size,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port_handle,
    uint64_t key) __LEAF_FN;

extern zx_status_t zx_vcpu_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t guest,
    uint32_t options,
    zx_vaddr_t entry,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t _zx_vcpu_create(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t guest,
    uint32_t options,
    zx_vaddr_t entry,
    ZX_SYSCALL_PARAM_ATTR(handle_acquire) zx_handle_t* out) __NONNULL((4)) __LEAF_FN;

extern zx_status_t zx_vcpu_resume(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_port_packet_t* packet) __NONNULL((2)) __LEAF_FN;

extern zx_status_t _zx_vcpu_resume(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    zx_port_packet_t* packet) __NONNULL((2)) __LEAF_FN;

extern zx_status_t zx_vcpu_interrupt(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t vector) __LEAF_FN;

extern zx_status_t _zx_vcpu_interrupt(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t vector) __LEAF_FN;

extern zx_status_t zx_vcpu_read_state(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_vcpu_read_state(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_vcpu_write_state(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    const void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_vcpu_write_state(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t handle,
    uint32_t kind,
    const void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_system_mexec(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t kernel_vmo,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t bootimage_vmo) __LEAF_FN;

extern zx_status_t _zx_system_mexec(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t kernel_vmo,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t bootimage_vmo) __LEAF_FN;

extern zx_status_t zx_system_mexec_payload_get(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t _zx_system_mexec_payload_get(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    void* buffer,
    size_t buffer_size) __LEAF_FN;

extern zx_status_t zx_system_powerctl(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint32_t cmd,
    const zx_system_powerctl_arg_t* arg) __LEAF_FN;

extern zx_status_t _zx_system_powerctl(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t resource,
    uint32_t cmd,
    const zx_system_powerctl_arg_t* arg) __LEAF_FN;

extern zx_status_t zx_pager_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(pager) zx_handle_t* out_pager) __NONNULL((2)) __LEAF_FN;

extern zx_status_t _zx_pager_create(
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(pager) zx_handle_t* out_pager) __NONNULL((2)) __LEAF_FN;

extern zx_status_t zx_pager_create_vmo(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t pager,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port,
    uint64_t key,
    uint64_t size,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(out_pager_vmo) zx_handle_t* out_pager_vmo) __NONNULL((6)) __LEAF_FN;

extern zx_status_t _zx_pager_create_vmo(
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t pager,
    ZX_SYSCALL_PARAM_ATTR(handle_use) zx_handle_t port,
    uint64_t key,
    uint64_t size,
    uint32_t options,
    ZX_SYSCALL_PARAM_ATTR(out_pager_vmo) zx_handle_t* out_pager_vmo) __NONNULL((6)) __LEAF_FN;

extern zx_status_t zx_syscall_test_0(
    void) __LEAF_FN;

extern zx_status_t _zx_syscall_test_0(
    void) __LEAF_FN;

extern zx_status_t zx_syscall_test_1(
    int a) __LEAF_FN;

extern zx_status_t _zx_syscall_test_1(
    int a) __LEAF_FN;

extern zx_status_t zx_syscall_test_2(
    int a,
    int b) __LEAF_FN;

extern zx_status_t _zx_syscall_test_2(
    int a,
    int b) __LEAF_FN;

extern zx_status_t zx_syscall_test_3(
    int a,
    int b,
    int c) __LEAF_FN;

extern zx_status_t _zx_syscall_test_3(
    int a,
    int b,
    int c) __LEAF_FN;

extern zx_status_t zx_syscall_test_4(
    int a,
    int b,
    int c,
    int d) __LEAF_FN;

extern zx_status_t _zx_syscall_test_4(
    int a,
    int b,
    int c,
    int d) __LEAF_FN;

extern zx_status_t zx_syscall_test_5(
    int a,
    int b,
    int c,
    int d,
    int e) __LEAF_FN;

extern zx_status_t _zx_syscall_test_5(
    int a,
    int b,
    int c,
    int d,
    int e) __LEAF_FN;

extern zx_status_t zx_syscall_test_6(
    int a,
    int b,
    int c,
    int d,
    int e,
    int f) __LEAF_FN;

extern zx_status_t _zx_syscall_test_6(
    int a,
    int b,
    int c,
    int d,
    int e,
    int f) __LEAF_FN;

extern zx_status_t zx_syscall_test_7(
    int a,
    int b,
    int c,
    int d,
    int e,
    int f,
    int g) __LEAF_FN;

extern zx_status_t _zx_syscall_test_7(
    int a,
    int b,
    int c,
    int d,
    int e,
    int f,
    int g) __LEAF_FN;

extern zx_status_t zx_syscall_test_8(
    int a,
    int b,
    int c,
    int d,
    int e,
    int f,
    int g,
    int h) __LEAF_FN;

extern zx_status_t _zx_syscall_test_8(
    int a,
    int b,
    int c,
    int d,
    int e,
    int f,
    int g,
    int h) __LEAF_FN;

extern zx_status_t zx_syscall_test_wrapper(
    int a,
    int b,
    int c) __LEAF_FN;

extern zx_status_t _zx_syscall_test_wrapper(
    int a,
    int b,
    int c) __LEAF_FN;




<|start_filename|>arch/x64/sysroot/include/zircon/device/ioctl-wrapper.h<|end_filename|>
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

#include <zircon/compiler.h>
#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>

__BEGIN_CDECLS

extern ssize_t fdio_ioctl(int fd, int op, const void* in_buf, size_t in_len, void* out_buf, size_t out_len);

#define IOCTL_WRAPPER(name, op) \
static inline ssize_t name(int fd) {             \
    return fdio_ioctl(fd, op, NULL, 0, NULL, 0); \
}

#define IOCTL_WRAPPER_IN(name, op, type) \
static inline ssize_t name(int fd, const type* in) {     \
    return fdio_ioctl(fd, op, in, in ? sizeof(*in) : 0, NULL, 0); \
}

#define IOCTL_WRAPPER_VARIN(name, op, type) \
static inline ssize_t name(int fd, const type* in, size_t in_len) { \
    return fdio_ioctl(fd, op, in, in_len, NULL, 0);                  \
}

#define IOCTL_WRAPPER_OUT(name, op, type) \
static inline ssize_t name(int fd, type* out) {            \
    return fdio_ioctl(fd, op, NULL, 0, out, out ? sizeof(*out) : 0); \
}

#define IOCTL_WRAPPER_VAROUT(name, op, type) \
static inline ssize_t name(int fd, type* out, size_t out_len) { \
    return fdio_ioctl(fd, op, NULL, 0, out, out_len);           \
}

#define IOCTL_WRAPPER_INOUT(name, op, intype, outtype) \
static inline ssize_t name(int fd, const intype* in, outtype* out) { \
    return fdio_ioctl(fd, op, in, in ? sizeof(*in) : 0, out, out ? sizeof(*out) : 0);   \
}

#define IOCTL_WRAPPER_VARIN_OUT(name, op, intype, outtype) \
static inline ssize_t name(int fd, const intype* in, size_t in_len, outtype* out) { \
    return fdio_ioctl(fd, op, in, in_len, out, out ? sizeof(*out) : 0);                       \
}

#define IOCTL_WRAPPER_IN_VAROUT(name, op, intype, outtype) \
static inline ssize_t name(int fd, const intype* in, outtype* out, size_t out_len) { \
    return fdio_ioctl(fd, op, in, in ? sizeof(*in) : 0, out, out_len);                        \
}

#define IOCTL_WRAPPER_VARIN_VAROUT(name, op, intype, outtype) \
static inline ssize_t name(int fd, const intype* in, size_t in_len, outtype* out, size_t out_len) { \
    return fdio_ioctl(fd, op, in, in_len, out, out_len);                                            \
}

__END_CDECLS


<|start_filename|>arch/x64/sysroot/include/zircon/syscalls/system.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

#include <zircon/types.h>

__BEGIN_CDECLS

// Commands used by zx_system_powerctl()
#define ZX_SYSTEM_POWERCTL_ENABLE_ALL_CPUS              1u
#define ZX_SYSTEM_POWERCTL_DISABLE_ALL_CPUS_BUT_PRIMARY 2u
#define ZX_SYSTEM_POWERCTL_ACPI_TRANSITION_S_STATE      3u
#define ZX_SYSTEM_POWERCTL_X86_SET_PKG_PL1              4u
#define ZX_SYSTEM_POWERCTL_REBOOT                       5u
#define ZX_SYSTEM_POWERCTL_REBOOT_BOOTLOADER            6u
#define ZX_SYSTEM_POWERCTL_REBOOT_RECOVERY              7u
#define ZX_SYSTEM_POWERCTL_SHUTDOWN                     8u

typedef struct zx_system_powerctl_arg {
    union {
        struct {
            uint8_t target_s_state; // Value between 1 and 5 indicating which S-state
            uint8_t sleep_type_a; // Value from ACPI VM (SLP_TYPa)
            uint8_t sleep_type_b; // Value from ACPI VM (SLP_TYPb)
        } acpi_transition_s_state;
        struct {
            uint32_t power_limit; // PL1 value in milliwatts
            uint32_t time_window; // PL1 time window in microseconds
            uint8_t clamp;        // PL1 clamping enable
            uint8_t enable;       // PL1 enable
        } x86_power_limit;
    };
} zx_system_powerctl_arg_t;

__END_CDECLS


<|start_filename|>pkg/fidl/validating.cpp<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <lib/fidl/coding.h>

#include <stdalign.h>
#include <stdint.h>
#include <stdlib.h>

#include <lib/fidl/internal.h>
#include <zircon/assert.h>
#include <zircon/compiler.h>

#include "buffer_walker.h"

// TODO(kulakowski) Design zx_status_t error values.

namespace {

class FidlValidator final : public fidl::internal::BufferWalker<FidlValidator, false, false> {
    typedef fidl::internal::BufferWalker<FidlValidator, false, false> Super;

public:
    FidlValidator(const fidl_type_t* type, const void* bytes, uint32_t num_bytes,
                  uint32_t num_handles, const char** out_error_msg)
        : Super(type), bytes_(static_cast<const uint8_t*>(bytes)), num_bytes_(num_bytes),
          num_handles_(num_handles), out_error_msg_(out_error_msg) {}

    void Walk() {
        Super::Walk();
        if (status_ == ZX_OK && handle_idx() != num_handles()) {
            SetError("message did not contain the specified number of handles");
            return;
        }
    }

    const uint8_t* bytes() const { return bytes_; }
    uint32_t num_bytes() const { return num_bytes_; }
    uint32_t num_handles() const { return num_handles_; }

    bool ValidateOutOfLineStorageClaim(const void* a, const void* b) {
        return true;
    }

    void UnclaimedHandle(const zx_handle_t* out_handle) {}
    void ClaimedHandle(const zx_handle_t* out_handle, uint32_t idx) {}

    template <class T>
    void UpdatePointer(const T* const* p, const T* v) {}

    PointerState GetPointerState(const void* ptr) const {
        return static_cast<PointerState>(*static_cast<const uintptr_t*>(ptr));
    }
    HandleState GetHandleState(zx_handle_t p) const {
        return static_cast<HandleState>(p);
    }

    void SetError(const char* error_msg) {
        status_ = ZX_ERR_INVALID_ARGS;
        if (out_error_msg_ != nullptr) {
            *out_error_msg_ = error_msg;
        }
    }

    zx_status_t status() const { return status_; }

private:
    // Message state passed in to the constructor.
    const uint8_t* const bytes_;
    const uint32_t num_bytes_;
    const uint32_t num_handles_;
    const char** const out_error_msg_;
    zx_status_t status_ = ZX_OK;
};

} // namespace

zx_status_t fidl_validate(const fidl_type_t* type, const void* bytes, uint32_t num_bytes,
                          uint32_t num_handles, const char** out_error_msg) {
    FidlValidator validator(type, bytes, num_bytes, num_handles, out_error_msg);
    validator.Walk();
    return validator.status();
}

zx_status_t fidl_validate_msg(const fidl_type_t* type, const fidl_msg_t* msg,
                              const char** out_error_msg) {
    return fidl_validate(type, msg->bytes, msg->num_bytes, msg->num_handles,
                         out_error_msg);
}


<|start_filename|>pkg/fidl/handle_closing.cpp<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.


#include <limits>
#include <stdalign.h>
#include <stdint.h>
#include <stdlib.h>

#include <lib/fidl/coding.h>

#ifdef __Fuchsia__

#include <lib/fidl/internal.h>
#include <zircon/assert.h>
#include <zircon/compiler.h>
#include <zircon/syscalls.h>

#include "buffer_walker.h"

namespace {

class FidlHandleCloser final : public fidl::internal::BufferWalker<FidlHandleCloser, true, true> {
    typedef fidl::internal::BufferWalker<FidlHandleCloser, true, true> Super;

public:
    FidlHandleCloser(const fidl_type_t* type, void* bytes, uint32_t num_bytes,
                     const char** out_error_msg)
        : Super(type), bytes_(static_cast<uint8_t*>(bytes)), num_bytes_(num_bytes),
          out_error_msg_(out_error_msg) {}

    void Walk() {
        Super::Walk();
    }

    uint8_t* bytes() const { return bytes_; }
    uint32_t num_bytes() const { return num_bytes_; }
    uint32_t num_handles() const { return std::numeric_limits<uint32_t>::max(); }

    bool ValidateOutOfLineStorageClaim(const void* a, void* b) {
        return true;
    }

    void UnclaimedHandle(zx_handle_t* out_handle) {
        // This will never happen since we are returning numeric_limits::max() in num_handles.
        // We want to claim (close) all the handles.
        ZX_DEBUG_ASSERT(false);
    }

    void ClaimedHandle(zx_handle_t* out_handle, uint32_t idx) {
        if (*out_handle != ZX_HANDLE_INVALID) {
            zx_handle_close(*out_handle);
        }
        *out_handle = ZX_HANDLE_INVALID;
    }

    template <class T>
    void UpdatePointer(T* const* p, T* v) {}

    PointerState GetPointerState(const void* ptr) const {
        return *static_cast<const uintptr_t*>(ptr) == 0
               ? PointerState::ABSENT
               : PointerState::PRESENT;
    }

    HandleState GetHandleState(zx_handle_t p) const {
        // Treat all handles as present to keep the buffer walker going.
        return HandleState::PRESENT;
    }

    void SetError(const char* error_msg) {
        status_ = ZX_ERR_INVALID_ARGS;
        if (out_error_msg_ != nullptr) {
            *out_error_msg_ = error_msg;
        }
    }

    zx_status_t status() const { return status_; }

private:
    // Message state passed in to the constructor.
    uint8_t* const bytes_;
    const uint32_t num_bytes_;
    const char** const out_error_msg_;
    zx_status_t status_ = ZX_OK;
};

} // namespace

#endif  // __Fuchsia__

zx_status_t fidl_close_handles(const fidl_type_t* type, void* bytes, uint32_t num_bytes,
                               const char** out_error_msg) {
#if __Fuchsia__
    FidlHandleCloser handle_closer(type, bytes, num_bytes, out_error_msg);
    handle_closer.Walk();
    return handle_closer.status();
#else
    return ZX_OK;  // there can't be any handles on the host
#endif
}

zx_status_t fidl_close_handles_msg(const fidl_type_t* type, const fidl_msg_t* msg,
                                   const char** out_error_msg) {
    return fidl_close_handles(type, msg->bytes, msg->num_bytes, out_error_msg);
}



<|start_filename|>arch/x64/sysroot/include/netinet/in_systm.h<|end_filename|>
#pragma once

#include <stdint.h>

typedef uint16_t n_short;
typedef uint32_t n_long, n_time;


<|start_filename|>pkg/zx/include/lib/zx/vmar.h<|end_filename|>
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_ZX_VMAR_H_
#define LIB_ZX_VMAR_H_

#include <lib/zx/object.h>
#include <lib/zx/vmo.h>
#include <zircon/process.h>

namespace zx {

// A wrapper for handles to VMARs.  Note that vmar::~vmar() does not execute
// vmar::destroy(), it just closes the handle.
class vmar : public object<vmar> {
public:
    static constexpr zx_obj_type_t TYPE = ZX_OBJ_TYPE_VMAR;

    constexpr vmar() = default;

    explicit vmar(zx_handle_t value) : object(value) {}

    explicit vmar(handle&& h) : object(h.release()) {}

    vmar(vmar&& other) : vmar(other.release()) {}

    vmar& operator=(vmar&& other) {
        reset(other.release());
        return *this;
    }

    zx_status_t map(size_t vmar_offset, const vmo& vmo_handle, uint64_t vmo_offset,
                    size_t len, zx_vm_option_t options, uintptr_t* ptr) const {
        return zx_vmar_map(get(), options, vmar_offset, vmo_handle.get(), vmo_offset, len, ptr);
    }

    zx_status_t unmap(uintptr_t address, size_t len) const {
        return zx_vmar_unmap(get(), address, len);
    }

    zx_status_t protect(uintptr_t address, size_t len, zx_vm_option_t prot) const {
        return zx_vmar_protect(get(), prot, address, len);
    }

    zx_status_t destroy() const {
        return zx_vmar_destroy(get());
    }

    zx_status_t allocate(size_t offset, size_t size, uint32_t flags,
                         vmar* child, uintptr_t* child_addr) const;

    static inline unowned<vmar> root_self() {
        return unowned<vmar>(zx_vmar_root_self());
    }
};

using unowned_vmar = unowned<vmar>;

} // namespace zx

#endif  // LIB_ZX_VMAR_H_


<|start_filename|>pkg/fidl/include/lib/fidl/coding.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIDL_CODING_H_
#define LIB_FIDL_CODING_H_

#include <zircon/compiler.h>
#include <zircon/fidl.h>
#include <zircon/types.h>

__BEGIN_CDECLS

// The maximum recursion depth the fidl encoder or decoder will
// perform. Each nested aggregate type (structs, unions, arrays, or
// vectors) counts as one step in the recursion depth.
#define FIDL_RECURSION_DEPTH 32

// See https://fuchsia.googlesource.com/docs/+/master/development/languages/fidl/languages/c.md#fidl_encode-fidl_encode_msg
zx_status_t fidl_encode(const fidl_type_t* type, void* bytes, uint32_t num_bytes,
                        zx_handle_t* handles, uint32_t max_handles,
                        uint32_t* out_actual_handles, const char** out_error_msg);
zx_status_t fidl_encode_msg(const fidl_type_t* type, fidl_msg_t* msg,
                            uint32_t* out_actual_handles, const char** out_error_msg);

// See https://fuchsia.googlesource.com/docs/+/master/development/languages/fidl/languages/c.md#fidl_decode-fidl_decode_msg
zx_status_t fidl_decode(const fidl_type_t* type, void* bytes, uint32_t num_bytes,
                        const zx_handle_t* handles, uint32_t num_handles,
                        const char** error_msg_out);
zx_status_t fidl_decode_msg(const fidl_type_t* type, fidl_msg_t* msg,
                            const char** out_error_msg);

// Validates an encoded message against the given |type|.
//
// The |bytes| are not modified.
zx_status_t fidl_validate(const fidl_type_t* type, const void* bytes, uint32_t num_bytes,
                          uint32_t num_handles, const char** error_msg_out);
zx_status_t fidl_validate_msg(const fidl_type_t* type, const fidl_msg_t* msg,
                              const char** out_error_msg);

// Traverses a linearized FIDL message, closing all handles within it.
// This function is a no-op on host side.
//
// Handle values in |bytes| are replaced with ZX_HANDLE_INVALID.
zx_status_t fidl_close_handles(const fidl_type_t* type, void* bytes, uint32_t num_bytes,
                               const char** out_error_msg);
zx_status_t fidl_close_handles_msg(const fidl_type_t* type, const fidl_msg_t* msg,
                                   const char** out_error_msg);

// Stores the name of a fidl type into the provided buffer.
// Truncates the name if it is too long to fit into the buffer.
// Returns the number of characters written into the buffer.
//
// Note: This function does not write a trailing NUL.
size_t fidl_format_type_name(const fidl_type_t* type,
                             char* buffer, size_t capacity);

__END_CDECLS

#endif // LIB_FIDL_CODING_H_


<|start_filename|>dart/fuchsia_modular/lib/src/proposal/proposal.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:fidl_fuchsia_modular/fidl_async.dart' as fuchsia_modular;
import 'package:meta/meta.dart';

import 'internal/_proposal_listener_impl.dart';

/// The [Proposal] class is an extension to the [fuchsia_modular.Proposal].
///
/// [Proposal]s are objects which can be submitted to the proposal publisher.
/// The proposal publisher can then make recommendations to the user about
/// actions that can be taken to enhance their user experience.
class Proposal extends fuchsia_modular.Proposal {
  /// Creates a [Proposal] object. The [id] and [headline] are both required and
  /// must not be empty. If provided, the [onProposalAccepted] function will be
  /// invoked when the proposal has been accepted by the user. Proposal
  /// affinities and story commands can be added after the proposal is created
  /// and before the proposal is submitted to the proposal publisher.
  Proposal({
    @required String id,
    @required String headline,
    String storyName,
    double confidence = 0.0,
    bool wantsRichSuggestion = false,
    String subheadline,
    String details,
    List<fuchsia_modular.SuggestionDisplayImage> icons,
    fuchsia_modular.SuggestionDisplayImage image,
    fuchsia_modular.AnnoyanceType annoyance =
        fuchsia_modular.AnnoyanceType.none,
    int color = 0x000000,
    void Function(String, String) onProposalAccepted,
  })  : assert(id != null && id.isNotEmpty),
        assert(headline != null && headline.isNotEmpty),
        super(
          id: id,
          storyName: storyName,
          affinity: [],
          onSelected: [],
          confidence: confidence,
          wantsRichSuggestion: wantsRichSuggestion,
          display: fuchsia_modular.SuggestionDisplay(
            headline: headline,
            subheadline: subheadline,
            details: details,
            color: color,
            icons: icons,
            image: image,
            annoyance: annoyance,
          ),
          listener: onProposalAccepted != null
              ? fuchsia_modular.ProposalListenerBinding()
                  .wrap(ProposalListenerImpl(onProposalAccepted))
              : null,
        );

  /// Restricts the proposal to appear only when the module identified by
  /// [moduleName] within the story identified by [storyName] is focused.
  void addModuleAffinity(String moduleName, String storyName) => affinity.add(
        fuchsia_modular.ProposalAffinity.withModuleAffinity(
          fuchsia_modular.ModuleAffinity(
            storyName: storyName,
            moduleName: [moduleName],
          ),
        ),
      );

  /// Restricts the proposal to appear only when the story identified by
  /// [storyName] is focused.
  void addStoryAffinity(String storyName) => affinity.add(
        fuchsia_modular.ProposalAffinity.withStoryAffinity(
          fuchsia_modular.StoryAffinity(storyName: storyName),
        ),
      );

  /// Adds a [fuchsia_modular.StoryCommand] to execute when the proposal is
  /// selected.
  void addStoryCommand(fuchsia_modular.StoryCommand command) =>
      addStoryCommands([command]);

  /// Adds a List of [fuchsia_modular.StoryCommand]s to execute when the
  /// proposal is selected.
  void addStoryCommands(List<fuchsia_modular.StoryCommand> commands) =>
      onSelected.addAll(commands);
}


<|start_filename|>pkg/async_loop/loop.c<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef _ALL_SOURCE
#define _ALL_SOURCE // Enables thrd_create_with_name in <threads.h>.
#endif
#include <lib/async-loop/loop.h>

#include <assert.h>
#include <stdatomic.h>
#include <stdlib.h>

#include <zircon/assert.h>
#include <zircon/listnode.h>
#include <zircon/syscalls.h>
#include <zircon/syscalls/hypervisor.h>

#include <lib/async/default.h>
#include <lib/async/exception.h>
#include <lib/async/receiver.h>
#include <lib/async/task.h>
#include <lib/async/trap.h>
#include <lib/async/wait.h>

// The port wait key associated with the dispatcher's control messages.
#define KEY_CONTROL (0u)

static zx_time_t async_loop_now(async_dispatcher_t* dispatcher);
static zx_status_t async_loop_begin_wait(async_dispatcher_t* dispatcher, async_wait_t* wait);
static zx_status_t async_loop_cancel_wait(async_dispatcher_t* dispatcher, async_wait_t* wait);
static zx_status_t async_loop_post_task(async_dispatcher_t* dispatcher, async_task_t* task);
static zx_status_t async_loop_cancel_task(async_dispatcher_t* dispatcher, async_task_t* task);
static zx_status_t async_loop_queue_packet(async_dispatcher_t* dispatcher, async_receiver_t* receiver,
                                           const zx_packet_user_t* data);
static zx_status_t async_loop_set_guest_bell_trap(
    async_dispatcher_t* dispatcher, async_guest_bell_trap_t* trap,
    zx_handle_t guest, zx_vaddr_t addr, size_t length);
static zx_status_t async_loop_bind_exception_port(async_dispatcher_t* async,
                                                  async_exception_t* exception);
static zx_status_t async_loop_unbind_exception_port(async_dispatcher_t* async,
                                                    async_exception_t* exception);
static zx_status_t async_loop_resume_from_exception(async_dispatcher_t* async,
                                                    async_exception_t* exception,
                                                    zx_handle_t task,
                                                    uint32_t options);

static const async_ops_t async_loop_ops = {
    .version = ASYNC_OPS_V2,
    .reserved = 0,
    .v1 = {
        .now = async_loop_now,
        .begin_wait = async_loop_begin_wait,
        .cancel_wait = async_loop_cancel_wait,
        .post_task = async_loop_post_task,
        .cancel_task = async_loop_cancel_task,
        .queue_packet = async_loop_queue_packet,
        .set_guest_bell_trap = async_loop_set_guest_bell_trap,
    },
    .v2 = {
        .bind_exception_port = async_loop_bind_exception_port,
        .unbind_exception_port = async_loop_unbind_exception_port,
        .resume_from_exception = async_loop_resume_from_exception,
    },
};

typedef struct thread_record {
    list_node_t node;
    thrd_t thread;
} thread_record_t;

const async_loop_config_t kAsyncLoopConfigAttachToThread = {
    .make_default_for_current_thread = true};
const async_loop_config_t kAsyncLoopConfigNoAttachToThread = {
    .make_default_for_current_thread = false};

typedef struct async_loop {
    async_dispatcher_t dispatcher; // must be first (the loop inherits from async_dispatcher_t)
    async_loop_config_t config; // immutable
    zx_handle_t port; // immutable
    zx_handle_t timer; // immutable

    _Atomic async_loop_state_t state;
    atomic_uint active_threads; // number of active dispatch threads

    mtx_t lock; // guards the lists and the dispatching tasks flag
    bool dispatching_tasks; // true while the loop is busy dispatching tasks
    list_node_t wait_list; // most recently added first
    list_node_t task_list; // pending tasks, earliest deadline first
    list_node_t due_list; // due tasks, earliest deadline first
    list_node_t thread_list; // earliest created thread first
    list_node_t exception_list; // most recently added first
} async_loop_t;

static zx_status_t async_loop_run_once(async_loop_t* loop, zx_time_t deadline);
static zx_status_t async_loop_dispatch_wait(async_loop_t* loop, async_wait_t* wait,
                                            zx_status_t status, const zx_packet_signal_t* signal);
static zx_status_t async_loop_dispatch_tasks(async_loop_t* loop);
static void async_loop_dispatch_task(async_loop_t* loop, async_task_t* task,
                                     zx_status_t status);
static zx_status_t async_loop_dispatch_packet(async_loop_t* loop, async_receiver_t* receiver,
                                              zx_status_t status, const zx_packet_user_t* data);
static zx_status_t async_loop_dispatch_guest_bell_trap(async_loop_t* loop,
                                                       async_guest_bell_trap_t* trap,
                                                       zx_status_t status,
                                                       const zx_packet_guest_bell_t* bell);
static zx_status_t async_loop_dispatch_exception(async_loop_t* loop,
                                                 async_exception_t* exception,
                                                 zx_status_t status,
                                                 const zx_port_packet_t* report);
static void async_loop_wake_threads(async_loop_t* loop);
static void async_loop_insert_task_locked(async_loop_t* loop, async_task_t* task);
static void async_loop_restart_timer_locked(async_loop_t* loop);
static void async_loop_invoke_prologue(async_loop_t* loop);
static void async_loop_invoke_epilogue(async_loop_t* loop);

static_assert(sizeof(list_node_t) <= sizeof(async_state_t),
              "async_state_t too small");

#define TO_NODE(type, ptr) ((list_node_t*)&ptr->state)
#define FROM_NODE(type, ptr) ((type*)((char*)(ptr)-offsetof(type, state)))

static inline list_node_t* wait_to_node(async_wait_t* wait) {
    return TO_NODE(async_wait_t, wait);
}

static inline async_wait_t* node_to_wait(list_node_t* node) {
    return FROM_NODE(async_wait_t, node);
}

static inline list_node_t* task_to_node(async_task_t* task) {
    return TO_NODE(async_task_t, task);
}

static inline async_task_t* node_to_task(list_node_t* node) {
    return FROM_NODE(async_task_t, node);
}

static inline list_node_t* exception_to_node(async_exception_t* exception) {
    return TO_NODE(async_exception_t, exception);
}

static inline async_exception_t* node_to_exception(list_node_t* node) {
    return FROM_NODE(async_exception_t, node);
}

zx_status_t async_loop_create(const async_loop_config_t* config, async_loop_t** out_loop) {
    ZX_DEBUG_ASSERT(out_loop);
    ZX_DEBUG_ASSERT(config != NULL);

    async_loop_t* loop = calloc(1u, sizeof(async_loop_t));
    if (!loop)
        return ZX_ERR_NO_MEMORY;
    atomic_init(&loop->state, ASYNC_LOOP_RUNNABLE);
    atomic_init(&loop->active_threads, 0u);

    loop->dispatcher.ops = &async_loop_ops;
    loop->config = *config;
    mtx_init(&loop->lock, mtx_plain);
    list_initialize(&loop->wait_list);
    list_initialize(&loop->task_list);
    list_initialize(&loop->due_list);
    list_initialize(&loop->thread_list);
    list_initialize(&loop->exception_list);

    zx_status_t status = zx_port_create(0u, &loop->port);
    if (status == ZX_OK)
        status = zx_timer_create(0u, ZX_CLOCK_MONOTONIC, &loop->timer);
    if (status == ZX_OK) {
        status = zx_object_wait_async(loop->timer, loop->port, KEY_CONTROL,
                                      ZX_TIMER_SIGNALED,
                                      ZX_WAIT_ASYNC_REPEATING);
    }
    if (status == ZX_OK) {
        *out_loop = loop;
        if (loop->config.make_default_for_current_thread) {
            ZX_DEBUG_ASSERT(async_get_default_dispatcher() == NULL);
            async_set_default_dispatcher(&loop->dispatcher);
        }
    } else {
        loop->config.make_default_for_current_thread = false;
        async_loop_destroy(loop);
    }
    return status;
}

void async_loop_destroy(async_loop_t* loop) {
    ZX_DEBUG_ASSERT(loop);

    async_loop_shutdown(loop);

    zx_handle_close(loop->port);
    zx_handle_close(loop->timer);
    mtx_destroy(&loop->lock);
    free(loop);
}

void async_loop_shutdown(async_loop_t* loop) {
    ZX_DEBUG_ASSERT(loop);

    async_loop_state_t prior_state =
        atomic_exchange_explicit(&loop->state, ASYNC_LOOP_SHUTDOWN,
                                 memory_order_acq_rel);
    if (prior_state == ASYNC_LOOP_SHUTDOWN)
        return;

    async_loop_wake_threads(loop);
    async_loop_join_threads(loop);

    list_node_t* node;
    while ((node = list_remove_head(&loop->wait_list))) {
        async_wait_t* wait = node_to_wait(node);
        async_loop_dispatch_wait(loop, wait, ZX_ERR_CANCELED, NULL);
    }
    while ((node = list_remove_head(&loop->due_list))) {
        async_task_t* task = node_to_task(node);
        async_loop_dispatch_task(loop, task, ZX_ERR_CANCELED);
    }
    while ((node = list_remove_head(&loop->task_list))) {
        async_task_t* task = node_to_task(node);
        async_loop_dispatch_task(loop, task, ZX_ERR_CANCELED);
    }
    while ((node = list_remove_head(&loop->exception_list))) {
        async_exception_t* exception = node_to_exception(node);
        async_loop_dispatch_exception(loop, exception, ZX_ERR_CANCELED, NULL);
    }

    if (loop->config.make_default_for_current_thread) {
        ZX_DEBUG_ASSERT(async_get_default_dispatcher() == &loop->dispatcher);
        async_set_default_dispatcher(NULL);
    }
}

zx_status_t async_loop_run(async_loop_t* loop, zx_time_t deadline, bool once) {
    ZX_DEBUG_ASSERT(loop);

    zx_status_t status;
    atomic_fetch_add_explicit(&loop->active_threads, 1u, memory_order_acq_rel);
    do {
        status = async_loop_run_once(loop, deadline);
    } while (status == ZX_OK && !once);
    atomic_fetch_sub_explicit(&loop->active_threads, 1u, memory_order_acq_rel);
    return status;
}

zx_status_t async_loop_run_until_idle(async_loop_t* loop) {
    zx_status_t status = async_loop_run(loop, 0, false);
    if (status == ZX_ERR_TIMED_OUT) {
        status = ZX_OK;
    }
    return status;
}

static zx_status_t async_loop_run_once(async_loop_t* loop, zx_time_t deadline) {
    async_loop_state_t state = atomic_load_explicit(&loop->state, memory_order_acquire);
    if (state == ASYNC_LOOP_SHUTDOWN)
        return ZX_ERR_BAD_STATE;
    if (state != ASYNC_LOOP_RUNNABLE)
        return ZX_ERR_CANCELED;

    zx_port_packet_t packet;
    zx_status_t status = zx_port_wait(loop->port, deadline, &packet);
    if (status != ZX_OK)
        return status;

    if (packet.key == KEY_CONTROL) {
        // Handle wake-up packets.
        if (packet.type == ZX_PKT_TYPE_USER)
            return ZX_OK;

        // Handle task timer expirations.
        if (packet.type == ZX_PKT_TYPE_SIGNAL_REP &&
            packet.signal.observed & ZX_TIMER_SIGNALED) {
            return async_loop_dispatch_tasks(loop);
        }
    } else {
        // Handle wait completion packets.
        if (packet.type == ZX_PKT_TYPE_SIGNAL_ONE) {
            async_wait_t* wait = (void*)(uintptr_t)packet.key;
            mtx_lock(&loop->lock);
            list_delete(wait_to_node(wait));
            mtx_unlock(&loop->lock);
            return async_loop_dispatch_wait(loop, wait, packet.status, &packet.signal);
        }

        // Handle queued user packets.
        if (packet.type == ZX_PKT_TYPE_USER) {
            async_receiver_t* receiver = (void*)(uintptr_t)packet.key;
            return async_loop_dispatch_packet(loop, receiver, packet.status, &packet.user);
        }

        // Handle guest bell trap packets.
        if (packet.type == ZX_PKT_TYPE_GUEST_BELL) {
            async_guest_bell_trap_t* trap = (void*)(uintptr_t)packet.key;
            return async_loop_dispatch_guest_bell_trap(
                loop, trap, packet.status, &packet.guest_bell);
        }

        // Handle exception packets.
        if (ZX_PKT_IS_EXCEPTION(packet.type)) {
            async_exception_t* exception = (void*)(uintptr_t)packet.key;
            return async_loop_dispatch_exception(loop, exception, packet.status,
                                                 &packet);
        }
    }

    ZX_DEBUG_ASSERT(false);
    return ZX_ERR_INTERNAL;
}

async_dispatcher_t* async_loop_get_dispatcher(async_loop_t* loop) {
    // Note: The loop's implementation inherits from async_t so we can upcast to it.
    return (async_dispatcher_t*)loop;
}

async_loop_t* async_loop_from_dispatcher(async_dispatcher_t* async) {
    return (async_loop_t*)async;
}

static zx_status_t async_loop_dispatch_guest_bell_trap(async_loop_t* loop,
                                                       async_guest_bell_trap_t* trap,
                                                       zx_status_t status,
                                                       const zx_packet_guest_bell_t* bell) {
    async_loop_invoke_prologue(loop);
    trap->handler((async_dispatcher_t*)loop, trap, status, bell);
    async_loop_invoke_epilogue(loop);
    return ZX_OK;
}

static zx_status_t async_loop_dispatch_wait(async_loop_t* loop, async_wait_t* wait,
                                            zx_status_t status, const zx_packet_signal_t* signal) {
    async_loop_invoke_prologue(loop);
    wait->handler((async_dispatcher_t*)loop, wait, status, signal);
    async_loop_invoke_epilogue(loop);
    return ZX_OK;
}

static zx_status_t async_loop_dispatch_tasks(async_loop_t* loop) {
    // Dequeue and dispatch one task at a time in case an earlier task wants
    // to cancel a later task which has also come due.  At most one thread
    // can dispatch tasks at any given moment (to preserve serial ordering).
    // Timer restarts are suppressed until we run out of tasks to dispatch.
    mtx_lock(&loop->lock);
    if (!loop->dispatching_tasks) {
        loop->dispatching_tasks = true;

        // Extract all of the tasks that are due into |due_list| for dispatch
        // unless we already have some waiting from a previous iteration which
        // we would like to process in order.
        list_node_t* node;
        if (list_is_empty(&loop->due_list)) {
            zx_time_t due_time = async_loop_now((async_dispatcher_t*)loop);
            list_node_t* tail = NULL;
            list_for_every(&loop->task_list, node) {
                if (node_to_task(node)->deadline > due_time)
                    break;
                tail = node;
            }
            if (tail) {
                list_node_t* head = loop->task_list.next;
                loop->task_list.next = tail->next;
                tail->next->prev = &loop->task_list;
                loop->due_list.next = head;
                head->prev = &loop->due_list;
                loop->due_list.prev = tail;
                tail->next = &loop->due_list;
            }
        }

        // Dispatch all due tasks.  Note that they might be canceled concurrently
        // so we need to grab the lock during each iteration to fetch the next
        // item from the list.
        while ((node = list_remove_head(&loop->due_list))) {
            mtx_unlock(&loop->lock);

            // Invoke the handler.  Note that it might destroy itself.
            async_task_t* task = node_to_task(node);
            async_loop_dispatch_task(loop, task, ZX_OK);

            mtx_lock(&loop->lock);
            async_loop_state_t state = atomic_load_explicit(&loop->state, memory_order_acquire);
            if (state != ASYNC_LOOP_RUNNABLE)
                break;
        }

        loop->dispatching_tasks = false;
        async_loop_restart_timer_locked(loop);
    }
    mtx_unlock(&loop->lock);
    return ZX_OK;
}

static void async_loop_dispatch_task(async_loop_t* loop,
                                     async_task_t* task,
                                     zx_status_t status) {
    // Invoke the handler.  Note that it might destroy itself.
    async_loop_invoke_prologue(loop);
    task->handler((async_dispatcher_t*)loop, task, status);
    async_loop_invoke_epilogue(loop);
}

static zx_status_t async_loop_dispatch_packet(async_loop_t* loop, async_receiver_t* receiver,
                                              zx_status_t status, const zx_packet_user_t* data) {
    // Invoke the handler.  Note that it might destroy itself.
    async_loop_invoke_prologue(loop);
    receiver->handler((async_dispatcher_t*)loop, receiver, status, data);
    async_loop_invoke_epilogue(loop);
    return ZX_OK;
}

static zx_status_t async_loop_dispatch_exception(async_loop_t* loop,
                                                 async_exception_t* exception,
                                                 zx_status_t status,
                                                 const zx_port_packet_t* report) {
    // Invoke the handler.  Note that it might destroy itself.
    async_loop_invoke_prologue(loop);
    exception->handler((async_dispatcher_t*)loop, exception, status, report);
    async_loop_invoke_epilogue(loop);
    return ZX_OK;
}

void async_loop_quit(async_loop_t* loop) {
    ZX_DEBUG_ASSERT(loop);

    async_loop_state_t expected_state = ASYNC_LOOP_RUNNABLE;
    if (!atomic_compare_exchange_strong_explicit(&loop->state, &expected_state,
                                                 ASYNC_LOOP_QUIT,
                                                 memory_order_acq_rel, memory_order_acquire))
        return;

    async_loop_wake_threads(loop);
}

static void async_loop_wake_threads(async_loop_t* loop) {
    // Queue enough packets to awaken all active threads.
    // This is safe because any new threads which join the pool first increment the
    // active thread count then check the loop state, so the count we observe here
    // cannot be less than the number of threads which might be blocked in |port_wait|.
    // Issuing too many packets is also harmless.
    uint32_t n = atomic_load_explicit(&loop->active_threads, memory_order_acquire);
    for (uint32_t i = 0u; i < n; i++) {
        zx_port_packet_t packet = {
            .key = KEY_CONTROL,
            .type = ZX_PKT_TYPE_USER,
            .status = ZX_OK};
        zx_status_t status = zx_port_queue(loop->port, &packet);
        ZX_ASSERT_MSG(status == ZX_OK, "zx_port_queue: status=%d", status);
    }
}

zx_status_t async_loop_reset_quit(async_loop_t* loop) {
    ZX_DEBUG_ASSERT(loop);

    // Ensure that there are no active threads before resetting the quit state.
    // This check is inherently racy but not dangerously so.  It's mainly a
    // sanity check for client code so we can make a stronger statement about
    // how |async_loop_reset_quit()| is supposed to be used.
    uint32_t n = atomic_load_explicit(&loop->active_threads, memory_order_acquire);
    if (n != 0)
        return ZX_ERR_BAD_STATE;

    async_loop_state_t expected_state = ASYNC_LOOP_QUIT;
    if (atomic_compare_exchange_strong_explicit(&loop->state, &expected_state,
                                                ASYNC_LOOP_RUNNABLE,
                                                memory_order_acq_rel, memory_order_acquire)) {
        return ZX_OK;
    }

    async_loop_state_t state = atomic_load_explicit(&loop->state, memory_order_acquire);
    if (state == ASYNC_LOOP_RUNNABLE)
        return ZX_OK;
    return ZX_ERR_BAD_STATE;
}

async_loop_state_t async_loop_get_state(async_loop_t* loop) {
    ZX_DEBUG_ASSERT(loop);

    return atomic_load_explicit(&loop->state, memory_order_acquire);
}

zx_time_t async_loop_now(async_dispatcher_t* dispatcher) {
    return zx_clock_get_monotonic();
}

static zx_status_t async_loop_begin_wait(async_dispatcher_t* async, async_wait_t* wait) {
    async_loop_t* loop = (async_loop_t*)async;
    ZX_DEBUG_ASSERT(loop);
    ZX_DEBUG_ASSERT(wait);

    if (atomic_load_explicit(&loop->state, memory_order_acquire) == ASYNC_LOOP_SHUTDOWN)
        return ZX_ERR_BAD_STATE;

    mtx_lock(&loop->lock);

    zx_status_t status = zx_object_wait_async(
        wait->object, loop->port, (uintptr_t)wait, wait->trigger, ZX_WAIT_ASYNC_ONCE);
    if (status == ZX_OK) {
        list_add_head(&loop->wait_list, wait_to_node(wait));
    } else {
        ZX_ASSERT_MSG(status == ZX_ERR_ACCESS_DENIED,
                      "zx_object_wait_async: status=%d", status);
    }

    mtx_unlock(&loop->lock);
    return status;
}

static zx_status_t async_loop_cancel_wait(async_dispatcher_t* async, async_wait_t* wait) {
    async_loop_t* loop = (async_loop_t*)async;
    ZX_DEBUG_ASSERT(loop);
    ZX_DEBUG_ASSERT(wait);

    // Note: We need to process cancelations even while the loop is being
    // destroyed in case the client is counting on the handler not being
    // invoked again past this point.

    mtx_lock(&loop->lock);

    // First, confirm that the wait is actually pending.
    list_node_t* node = wait_to_node(wait);
    if (!list_in_list(node)) {
        mtx_unlock(&loop->lock);
        return ZX_ERR_NOT_FOUND;
    }

    // Next, cancel the wait.  This may be racing with another thread that
    // has read the wait's packet but not yet dispatched it.  So if we fail
    // to cancel then we assume we lost the race.
    zx_status_t status = zx_port_cancel(loop->port, wait->object,
                                        (uintptr_t)wait);
    if (status == ZX_OK) {
        list_delete(node);
    } else {
        ZX_ASSERT_MSG(status == ZX_ERR_NOT_FOUND,
                      "zx_port_cancel: status=%d", status);
    }

    mtx_unlock(&loop->lock);
    return status;
}

static zx_status_t async_loop_post_task(async_dispatcher_t* async, async_task_t* task) {
    async_loop_t* loop = (async_loop_t*)async;
    ZX_DEBUG_ASSERT(loop);
    ZX_DEBUG_ASSERT(task);

    if (atomic_load_explicit(&loop->state, memory_order_acquire) == ASYNC_LOOP_SHUTDOWN)
        return ZX_ERR_BAD_STATE;

    mtx_lock(&loop->lock);

    async_loop_insert_task_locked(loop, task);
    if (!loop->dispatching_tasks &&
        task_to_node(task)->prev == &loop->task_list) {
        // Task inserted at head.  Earliest deadline changed.
        async_loop_restart_timer_locked(loop);
    }

    mtx_unlock(&loop->lock);
    return ZX_OK;
}

static zx_status_t async_loop_cancel_task(async_dispatcher_t* async, async_task_t* task) {
    async_loop_t* loop = (async_loop_t*)async;
    ZX_DEBUG_ASSERT(loop);
    ZX_DEBUG_ASSERT(task);

    // Note: We need to process cancelations even while the loop is being
    // destroyed in case the client is counting on the handler not being
    // invoked again past this point.  Also, the task we're removing here
    // might be present in the dispatcher's |due_list| if it is pending
    // dispatch instead of in the loop's |task_list| as usual.  The same
    // logic works in both cases.

    mtx_lock(&loop->lock);
    list_node_t* node = task_to_node(task);
    if (!list_in_list(node)) {
        mtx_unlock(&loop->lock);
        return ZX_ERR_NOT_FOUND;
    }

    // Determine whether the head task was canceled and following task has
    // a later deadline.  If so, we will bump the timer along to that deadline.
    bool must_restart = !loop->dispatching_tasks &&
                        node->prev == &loop->task_list &&
                        node->next != &loop->task_list &&
                        node_to_task(node->next)->deadline > task->deadline;
    list_delete(node);
    if (must_restart)
        async_loop_restart_timer_locked(loop);

    mtx_unlock(&loop->lock);
    return ZX_OK;
}

static zx_status_t async_loop_queue_packet(async_dispatcher_t* async, async_receiver_t* receiver,
                                           const zx_packet_user_t* data) {
    async_loop_t* loop = (async_loop_t*)async;
    ZX_DEBUG_ASSERT(loop);
    ZX_DEBUG_ASSERT(receiver);

    if (atomic_load_explicit(&loop->state, memory_order_acquire) == ASYNC_LOOP_SHUTDOWN)
        return ZX_ERR_BAD_STATE;

    zx_port_packet_t packet = {
        .key = (uintptr_t)receiver,
        .type = ZX_PKT_TYPE_USER,
        .status = ZX_OK};
    if (data)
        packet.user = *data;
    return zx_port_queue(loop->port, &packet);
}

static zx_status_t async_loop_set_guest_bell_trap(
    async_dispatcher_t* async, async_guest_bell_trap_t* trap,
    zx_handle_t guest, zx_vaddr_t addr, size_t length) {
    async_loop_t* loop = (async_loop_t*)async;
    ZX_DEBUG_ASSERT(loop);
    ZX_DEBUG_ASSERT(trap);

    if (atomic_load_explicit(&loop->state, memory_order_acquire) == ASYNC_LOOP_SHUTDOWN)
        return ZX_ERR_BAD_STATE;

    zx_status_t status = zx_guest_set_trap(guest, ZX_GUEST_TRAP_BELL, addr,
                                           length, loop->port, (uintptr_t)trap);
    if (status != ZX_OK) {
        ZX_ASSERT_MSG(status == ZX_ERR_ACCESS_DENIED ||
                          status == ZX_ERR_ALREADY_EXISTS ||
                          status == ZX_ERR_INVALID_ARGS ||
                          status == ZX_ERR_OUT_OF_RANGE ||
                          status == ZX_ERR_WRONG_TYPE,
                      "zx_guest_set_trap: status=%d", status);
    }
    return status;
}

static zx_status_t async_loop_bind_exception_port(async_dispatcher_t* async,
                                                  async_exception_t* exception) {
    async_loop_t* loop = (async_loop_t*)async;
    ZX_DEBUG_ASSERT(loop);
    ZX_DEBUG_ASSERT(exception);

    if (atomic_load_explicit(&loop->state, memory_order_acquire) == ASYNC_LOOP_SHUTDOWN)
        return ZX_ERR_BAD_STATE;

    mtx_lock(&loop->lock);

    uint64_t key = (uintptr_t)(void*) exception;
    zx_status_t status = zx_task_bind_exception_port(exception->task, loop->port,
                                                     key, exception->options);
    if (status == ZX_OK) {
        list_add_head(&loop->exception_list, exception_to_node(exception));
    }

    mtx_unlock(&loop->lock);
    return status;
}

static zx_status_t async_loop_unbind_exception_port(async_dispatcher_t* async,
                                                    async_exception_t* exception) {
    async_loop_t* loop = (async_loop_t*)async;
    ZX_DEBUG_ASSERT(loop);
    ZX_DEBUG_ASSERT(exception);

    // Note: We need to process unbindings even while the loop is being
    // destroyed in case the client is counting on the handler not being
    // invoked again past this point.

    mtx_lock(&loop->lock);

    // First, confirm that the port is actually bound.
    list_node_t* node = exception_to_node(exception);
    if (!list_in_list(node)) {
        mtx_unlock(&loop->lock);
        return ZX_ERR_NOT_FOUND;
    }

    uint64_t key = (uintptr_t)(void*) exception;
    zx_status_t status = zx_task_bind_exception_port(exception->task,
                                                     ZX_HANDLE_INVALID, key, 0);

    if (status == ZX_OK) {
        list_delete(node);
    }

    mtx_unlock(&loop->lock);
    return status;
}

static zx_status_t async_loop_resume_from_exception(async_dispatcher_t* async,
                                                    async_exception_t* exception,
                                                    zx_handle_t task,
                                                    uint32_t options) {
    async_loop_t* loop = (async_loop_t*)async;
    ZX_DEBUG_ASSERT(loop);
    ZX_DEBUG_ASSERT(exception);

    if (atomic_load_explicit(&loop->state, memory_order_acquire) == ASYNC_LOOP_SHUTDOWN)
        return ZX_ERR_BAD_STATE;

    return zx_task_resume_from_exception(task, loop->port, options);
}

static void async_loop_insert_task_locked(async_loop_t* loop, async_task_t* task) {
    // TODO(ZX-976): We assume that tasks are inserted in quasi-monotonic order and
    // that insertion into the task queue will typically take no more than a few steps.
    // If this assumption proves false and the cost of insertion becomes a problem, we
    // should consider using a more efficient representation for maintaining order.
    list_node_t* node;
    for (node = loop->task_list.prev; node != &loop->task_list; node = node->prev) {
        if (task->deadline >= node_to_task(node)->deadline)
            break;
    }
    list_add_after(node, task_to_node(task));
}

static void async_loop_restart_timer_locked(async_loop_t* loop) {
    zx_time_t deadline;
    if (list_is_empty(&loop->due_list)) {
        list_node_t* head = list_peek_head(&loop->task_list);
        if (!head)
            return;
        async_task_t* task = node_to_task(head);
        deadline = task->deadline;
        if (deadline == ZX_TIME_INFINITE)
            return;
    } else {
        // Fire now.
        deadline = 0ULL;
    }

    zx_status_t status = zx_timer_set(loop->timer, deadline, 0);
    ZX_ASSERT_MSG(status == ZX_OK, "zx_timer_set: status=%d", status);
}

static void async_loop_invoke_prologue(async_loop_t* loop) {
    if (loop->config.prologue)
        loop->config.prologue(loop, loop->config.data);
}

static void async_loop_invoke_epilogue(async_loop_t* loop) {
    if (loop->config.epilogue)
        loop->config.epilogue(loop, loop->config.data);
}

static int async_loop_run_thread(void* data) {
    async_loop_t* loop = (async_loop_t*)data;
    async_set_default_dispatcher(&loop->dispatcher);
    async_loop_run(loop, ZX_TIME_INFINITE, false);
    return 0;
}

zx_status_t async_loop_start_thread(async_loop_t* loop, const char* name, thrd_t* out_thread) {
    ZX_DEBUG_ASSERT(loop);

    // This check is inherently racy.  The client should not be racing shutdown
    // with attemps to start new threads.  This is mainly a sanity check.
    async_loop_state_t state = atomic_load_explicit(&loop->state, memory_order_acquire);
    if (state == ASYNC_LOOP_SHUTDOWN)
        return ZX_ERR_BAD_STATE;

    thread_record_t* rec = calloc(1u, sizeof(thread_record_t));
    if (!rec)
        return ZX_ERR_NO_MEMORY;

    if (thrd_create_with_name(&rec->thread, async_loop_run_thread, loop, name) != thrd_success) {
        free(rec);
        return ZX_ERR_NO_MEMORY;
    }

    mtx_lock(&loop->lock);
    list_add_tail(&loop->thread_list, &rec->node);
    mtx_unlock(&loop->lock);

    if (out_thread)
        *out_thread = rec->thread;
    return ZX_OK;
}

void async_loop_join_threads(async_loop_t* loop) {
    ZX_DEBUG_ASSERT(loop);

    mtx_lock(&loop->lock);
    for (;;) {
        thread_record_t* rec = (thread_record_t*)list_remove_head(&loop->thread_list);
        if (!rec)
            break;

        mtx_unlock(&loop->lock);
        thrd_t thread = rec->thread;
        free(rec);
        int result = thrd_join(thread, NULL);
        ZX_DEBUG_ASSERT(result == thrd_success);
        mtx_lock(&loop->lock);
    }
    mtx_unlock(&loop->lock);
}


<|start_filename|>dart/fuchsia_logger/lib/src/internal/_log_writer.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:logging/logging.dart';
import 'package:meta/meta.dart';

/// A concrete implementation of [LogWriter] which sends logs to
/// the fuchsia system logger. This log writer will buffer logs until
/// a connection has been established at which time it will send all
/// the buffered logs.
class FuchsiaLogWriter extends LogWriter {
  /// Constructor
  FuchsiaLogWriter({@required Logger logger})
      : assert(logger != null),
        super(
          logger: logger,
          shouldBufferLogs: true,
        ) {
    _connectToSysLogger();
  }

  void _connectToSysLogger() {
    // TODO(MS-2258) connect to the system logger
    _startListening(_onMessage);
  }

  @override
  // TODO(MS-2259) send logs to system logger
  void _onMessage(_LogMessage message) => throw UnimplementedError();
}

/// The base class for which log writers will inherit from. This class is
/// used to pipe logs from the onRecord stream
abstract class LogWriter {
  List<String> _globalTags = const [];

  StreamController<_LogMessage> _controller;

  /// If set to true, this method will include the stack trace
  /// in each log record so we can later extract out the call site.
  /// This is a heavy operation and should be used with caution.
  bool forceShowCodeLocation = false;

  /// Constructor
  LogWriter({
    @required Logger logger,
    bool shouldBufferLogs = false,
  }) : assert(logger != null) {
    void Function(_LogMessage) onMessageFunc;

    if (shouldBufferLogs) {
      // create single subscription stream controller so that we buffer calls to the
      // stream while we connect to the logger. This avoids dropping logs that
      // come in while we wait.
      _controller = StreamController<_LogMessage>();

      onMessageFunc = _controller.add;
    } else {
      onMessageFunc = _onMessage;
    }
    logger.onRecord.listen(
        (record) => onMessageFunc(_messageFromRecord(record)),
        onDone: () => _controller?.close());
  }

  /// The global tags to add to each log record.
  set globalTags(List<String> tags) => _globalTags = _verifyGlobalTags(tags);

  /// Remaps the level string to the ones used in FTL.
  String _getLevelString(Level level) {
    if (level == null) {
      return null;
    }

    if (level == Level.FINE) {
      return 'VLOG(1)';
    } else if (level == Level.FINER) {
      return 'VLOG(2)';
    } else if (level == Level.FINEST) {
      return 'VLOG(3)';
    } else if (level == Level.SEVERE) {
      return 'ERROR';
    } else if (level == Level.SHOUT) {
      return 'FATAL';
    } else {
      return level.toString();
    }
  }

  _LogMessage _messageFromRecord(LogRecord record) => _LogMessage(
        record: record,
        tags: _globalTags,
        callSiteTrace: forceShowCodeLocation ? StackTrace.current : null,
      );

  void _onMessage(_LogMessage message);

  void _startListening(void Function(_LogMessage) onMessage) =>
      _controller.stream.listen(_onMessage);

  List<String> _verifyGlobalTags(List<String> incomingTags) {
    //TODO(MS-2261) need to verify the incoming global tags
    return incomingTags;
  }

  //ignore: unused_element
  String _codeLocationFromStackTrace(StackTrace stackTrace) {
    // TODO(MS-2260) need to extract out the call site from the stack trace
    return '';
  }
}

/// A concrete implementation of [LogWriter] which prints the logs to stdout.
class StdoutLogWriter extends LogWriter {
  /// Constructor
  StdoutLogWriter({@required Logger logger})
      : assert(logger != null),
        super(
          logger: logger,
          shouldBufferLogs: false,
        );

  @override
  void _onMessage(_LogMessage message) {
    final scopes = [
      _getLevelString(message.record.level),
    ];

    if (message.record.loggerName.isNotEmpty) {
      scopes.add(message.record.loggerName);
    }
    // if (message.codeLocation != null) {
    // scopes.add(message.codeLocation);
    // }
    message.tags.forEach(scopes.add);
    String scopesString = scopes.join(':');
    if (message.record.error != null) {
      print(
          '[$scopesString] ${message.record.message}: ${message.record.error}');
    } else {
      print('[$scopesString] ${message.record.message}');
    }

    if (message.record.stackTrace != null) {
      print('${message.record.stackTrace}');
    }
  }
}

/// A wrapper around [LogRecord] which appends additional data. This
/// is what is sent to the log writer when a record is received.
class _LogMessage {
  /// The initial log record
  final LogRecord record;

  /// Any additional tags to append to the record.
  final List<String> tags;

  /// The stack trace at the call site. This is not to be confused with
  /// the stack trace in the [record] which is a stack trace that is being
  /// logged. This variable is used to later extract the code location
  /// to include in the message.
  final StackTrace callSiteTrace;

  _LogMessage({this.record, this.tags, this.callSiteTrace});
}


<|start_filename|>pkg/fdio/include/lib/fdio/private.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

#include <zircon/compiler.h>
#include <zircon/types.h>
#include <stdint.h>

__BEGIN_CDECLS;

// WARNING: These APIs are subject to change

// __fdio_cleanpath cleans an input path, placing the output
// in out, which is a buffer of at least "PATH_MAX" bytes.
//
// 'outlen' returns the length of the path placed in out, and 'is_dir'
// is set to true if the returned path must be a directory.
zx_status_t __fdio_cleanpath(const char* in, char* out, size_t* outlen, bool* is_dir);

__END_CDECLS;


<|start_filename|>dart/fuchsia_modular/lib/src/module/embedded_module.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:fidl/fidl.dart';
import 'package:fidl_fuchsia_modular/fidl_async.dart' as fidl;
import 'package:fidl_fuchsia_ui_viewsv1token/fidl_async.dart' as views_fidl;
import 'package:meta/meta.dart';

/// The result of calling [Module#embedModule] on the Module.
///
/// This object contains a reference to a [fidl.ModuleController]
/// as well as a [views_fidl.ViewOwner] object. The combination of
/// these objects can be used to embed the new module's view into
/// your own view hierarchy.
class EmbeddedModule {
  /// The moduleController which can be used to control the embedded module.
  final fidl.ModuleController moduleController;

  /// A handle to the view owner object. This handle can be used to connect
  /// to the modules view to render its contents to screen.
  final InterfaceHandle<views_fidl.ViewOwner> viewOwner;

  /// Constructor
  EmbeddedModule({
    @required this.moduleController,
    @required this.viewOwner,
  })  : assert(moduleController != null),
        assert(viewOwner != null);
}


<|start_filename|>arch/x64/sysroot/include/sys/signalfd.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <fcntl.h>
#include <stdint.h>

#define __NEED_sigset_t

#include <bits/alltypes.h>

#define SFD_CLOEXEC O_CLOEXEC
#define SFD_NONBLOCK O_NONBLOCK

int signalfd(int, const sigset_t*, int);

struct signalfd_siginfo {
    uint32_t ssi_signo;
    int32_t ssi_errno;
    int32_t ssi_code;
    uint32_t ssi_pid;
    uint32_t ssi_uid;
    int32_t ssi_fd;
    uint32_t ssi_tid;
    uint32_t ssi_band;
    uint32_t ssi_overrun;
    uint32_t ssi_trapno;
    int32_t ssi_status;
    int32_t ssi_int;
    uint64_t ssi_ptr;
    uint64_t ssi_utime;
    uint64_t ssi_stime;
    uint64_t ssi_addr;
    uint16_t ssi_addr_lsb;
    uint8_t pad[128 - 12 * 4 - 4 * 8 - 2];
};

#ifdef __cplusplus
}
#endif


<|start_filename|>arch/x64/sysroot/include/dlfcn.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>

#define RTLD_LAZY 1
#define RTLD_NOW 2
#define RTLD_NOLOAD 4
#define RTLD_NODELETE 4096
#define RTLD_GLOBAL 256
#define RTLD_LOCAL 0

#define RTLD_NEXT ((void*)-1)
#define RTLD_DEFAULT ((void*)0)

#define RTLD_DI_LINKMAP 2

int dlclose(void*);
char* dlerror(void);
void* dlopen(const char*, int);
void* dlsym(void* __restrict, const char* __restrict);

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
typedef struct {
    const char* dli_fname;
    void* dli_fbase;
    const char* dli_sname;
    void* dli_saddr;
} Dl_info;
int dladdr(const void*, Dl_info*);
int dlinfo(void*, int, void*);
#endif

#ifdef __cplusplus
}
#endif


<|start_filename|>arch/x64/sysroot/include/netinet/in.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>
#include <inttypes.h>
#include <sys/socket.h>

typedef uint16_t in_port_t;
typedef uint32_t in_addr_t;
struct in_addr {
    in_addr_t s_addr;
};

struct sockaddr_in {
    sa_family_t sin_family;
    in_port_t sin_port;
    struct in_addr sin_addr;
    uint8_t sin_zero[8];
};

struct in6_addr {
    union {
        uint8_t __s6_addr[16];
        uint16_t __s6_addr16[8];
        uint32_t __s6_addr32[4];
    } __in6_union;
};
#define s6_addr __in6_union.__s6_addr
#define s6_addr16 __in6_union.__s6_addr16
#define s6_addr32 __in6_union.__s6_addr32

struct sockaddr_in6 {
    sa_family_t sin6_family;
    in_port_t sin6_port;
    uint32_t sin6_flowinfo;
    struct in6_addr sin6_addr;
    uint32_t sin6_scope_id;
};

struct ipv6_mreq {
    struct in6_addr ipv6mr_multiaddr;
    unsigned ipv6mr_interface;
};

#define INADDR_ANY ((in_addr_t)0x00000000)
#define INADDR_BROADCAST ((in_addr_t)0xffffffff)
#define INADDR_NONE ((in_addr_t)0xffffffff)
#define INADDR_LOOPBACK ((in_addr_t)0x7f000001)

#define INADDR_UNSPEC_GROUP ((in_addr_t)0xe0000000)
#define INADDR_ALLHOSTS_GROUP ((in_addr_t)0xe0000001)
#define INADDR_ALLRTRS_GROUP ((in_addr_t)0xe0000002)
#define INADDR_MAX_LOCAL_GROUP ((in_addr_t)0xe00000ff)

#define IN6ADDR_ANY_INIT                                       \
    {                                                          \
        {                                                      \
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } \
        }                                                      \
    }
#define IN6ADDR_LOOPBACK_INIT                                  \
    {                                                          \
        {                                                      \
            { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } \
        }                                                      \
    }

extern const struct in6_addr in6addr_any, in6addr_loopback;

#undef INET_ADDRSTRLEN
#undef INET6_ADDRSTRLEN
#define INET_ADDRSTRLEN 16
#define INET6_ADDRSTRLEN 46

uint32_t htonl(uint32_t);
uint16_t htons(uint16_t);
uint32_t ntohl(uint32_t);
uint16_t ntohs(uint16_t);

#define IPPROTO_IP 0
#define IPPROTO_HOPOPTS 0
#define IPPROTO_ICMP 1
#define IPPROTO_IGMP 2
#define IPPROTO_IPIP 4
#define IPPROTO_TCP 6
#define IPPROTO_EGP 8
#define IPPROTO_PUP 12
#define IPPROTO_UDP 17
#define IPPROTO_IDP 22
#define IPPROTO_TP 29
#define IPPROTO_DCCP 33
#define IPPROTO_IPV6 41
#define IPPROTO_ROUTING 43
#define IPPROTO_FRAGMENT 44
#define IPPROTO_RSVP 46
#define IPPROTO_GRE 47
#define IPPROTO_ESP 50
#define IPPROTO_AH 51
#define IPPROTO_ICMPV6 58
#define IPPROTO_NONE 59
#define IPPROTO_DSTOPTS 60
#define IPPROTO_MTP 92
#define IPPROTO_BEETPH 94
#define IPPROTO_ENCAP 98
#define IPPROTO_PIM 103
#define IPPROTO_COMP 108
#define IPPROTO_SCTP 132
#define IPPROTO_MH 135
#define IPPROTO_UDPLITE 136
#define IPPROTO_MPLS 137
#define IPPROTO_RAW 255
#define IPPROTO_MAX 256

#define IN6_IS_ADDR_UNSPECIFIED(a)                                                       \
    (((uint32_t*)(a))[0] == 0 && ((uint32_t*)(a))[1] == 0 && ((uint32_t*)(a))[2] == 0 && \
     ((uint32_t*)(a))[3] == 0)

#define IN6_IS_ADDR_LOOPBACK(a)                                                          \
    (((uint32_t*)(a))[0] == 0 && ((uint32_t*)(a))[1] == 0 && ((uint32_t*)(a))[2] == 0 && \
     ((uint8_t*)(a))[12] == 0 && ((uint8_t*)(a))[13] == 0 && ((uint8_t*)(a))[14] == 0 && \
     ((uint8_t*)(a))[15] == 1)

#define IN6_IS_ADDR_MULTICAST(a) (((uint8_t*)(a))[0] == 0xff)

#define IN6_IS_ADDR_LINKLOCAL(a) \
    ((((uint8_t*)(a))[0]) == 0xfe && (((uint8_t*)(a))[1] & 0xc0) == 0x80)

#define IN6_IS_ADDR_SITELOCAL(a) \
    ((((uint8_t*)(a))[0]) == 0xfe && (((uint8_t*)(a))[1] & 0xc0) == 0xc0)

#define IN6_IS_ADDR_V4MAPPED(a)                                                         \
    (((uint32_t*)(a))[0] == 0 && ((uint32_t*)(a))[1] == 0 && ((uint8_t*)(a))[8] == 0 && \
     ((uint8_t*)(a))[9] == 0 && ((uint8_t*)(a))[10] == 0xff && ((uint8_t*)(a))[11] == 0xff)

#define IN6_IS_ADDR_V4COMPAT(a)                                                          \
    (((uint32_t*)(a))[0] == 0 && ((uint32_t*)(a))[1] == 0 && ((uint32_t*)(a))[2] == 0 && \
     ((uint8_t*)(a))[15] > 1)

#define IN6_IS_ADDR_MC_NODELOCAL(a) \
    (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t*)(a))[1] & 0xf) == 0x1))

#define IN6_IS_ADDR_MC_LINKLOCAL(a) \
    (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t*)(a))[1] & 0xf) == 0x2))

#define IN6_IS_ADDR_MC_SITELOCAL(a) \
    (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t*)(a))[1] & 0xf) == 0x5))

#define IN6_IS_ADDR_MC_ORGLOCAL(a) (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t*)(a))[1] & 0xf) == 0x8))

#define IN6_IS_ADDR_MC_GLOBAL(a) (IN6_IS_ADDR_MULTICAST(a) && ((((uint8_t*)(a))[1] & 0xf) == 0xe))

#define __ARE_4_EQUAL(a, b) \
    (!((0 [a] - 0 [b]) | (1 [a] - 1 [b]) | (2 [a] - 2 [b]) | (3 [a] - 3 [b])))
#define IN6_ARE_ADDR_EQUAL(a, b) __ARE_4_EQUAL((const uint32_t*)(a), (const uint32_t*)(b))

#define IN_CLASSA(a) ((((in_addr_t)(a)) & 0x80000000) == 0)
#define IN_CLASSA_NET 0xff000000
#define IN_CLASSA_NSHIFT 24
#define IN_CLASSA_HOST (0xffffffff & ~IN_CLASSA_NET)
#define IN_CLASSA_MAX 128
#define IN_CLASSB(a) ((((in_addr_t)(a)) & 0xc0000000) == 0x80000000)
#define IN_CLASSB_NET 0xffff0000
#define IN_CLASSB_NSHIFT 16
#define IN_CLASSB_HOST (0xffffffff & ~IN_CLASSB_NET)
#define IN_CLASSB_MAX 65536
#define IN_CLASSC(a) ((((in_addr_t)(a)) & 0xe0000000) == 0xc0000000)
#define IN_CLASSC_NET 0xffffff00
#define IN_CLASSC_NSHIFT 8
#define IN_CLASSC_HOST (0xffffffff & ~IN_CLASSC_NET)
#define IN_CLASSD(a) ((((in_addr_t)(a)) & 0xf0000000) == 0xe0000000)
#define IN_MULTICAST(a) IN_CLASSD(a)
#define IN_EXPERIMENTAL(a) ((((in_addr_t)(a)) & 0xe0000000) == 0xe0000000)
#define IN_BADCLASS(a) ((((in_addr_t)(a)) & 0xf0000000) == 0xf0000000)

#define IN_LOOPBACKNET 127

#define IP_TOS 1
#define IP_TTL 2
#define IP_HDRINCL 3
#define IP_OPTIONS 4
#define IP_ROUTER_ALERT 5
#define IP_RECVOPTS 6
#define IP_RETOPTS 7
#define IP_PKTINFO 8
#define IP_PKTOPTIONS 9
#define IP_PMTUDISC 10
#define IP_MTU_DISCOVER 10
#define IP_RECVERR 11
#define IP_RECVTTL 12
#define IP_RECVTOS 13
#define IP_MTU 14
#define IP_FREEBIND 15
#define IP_IPSEC_POLICY 16
#define IP_XFRM_POLICY 17
#define IP_PASSSEC 18
#define IP_TRANSPARENT 19
#define IP_ORIGDSTADDR 20
#define IP_RECVORIGDSTADDR IP_ORIGDSTADDR
#define IP_MINTTL 21
#define IP_NODEFRAG 22
#define IP_CHECKSUM 23
#define IP_BIND_ADDRESS_NO_PORT 24
#define IP_MULTICAST_IF 32
#define IP_MULTICAST_TTL 33
#define IP_MULTICAST_LOOP 34
#define IP_ADD_MEMBERSHIP 35
#define IP_DROP_MEMBERSHIP 36
#define IP_UNBLOCK_SOURCE 37
#define IP_BLOCK_SOURCE 38
#define IP_ADD_SOURCE_MEMBERSHIP 39
#define IP_DROP_SOURCE_MEMBERSHIP 40
#define IP_MSFILTER 41
#define IP_MULTICAST_ALL 49
#define IP_UNICAST_IF 50

#define IP_RECVRETOPTS IP_RETOPTS

#define IP_PMTUDISC_DONT 0
#define IP_PMTUDISC_WANT 1
#define IP_PMTUDISC_DO 2
#define IP_PMTUDISC_PROBE 3
#define IP_PMTUDISC_INTERFACE 4
#define IP_PMTUDISC_OMIT 5

#define IP_DEFAULT_MULTICAST_TTL 1
#define IP_DEFAULT_MULTICAST_LOOP 1
#define IP_MAX_MEMBERSHIPS 20

struct ip_opts {
    struct in_addr ip_dst;
    char ip_opts[40];
};

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)

#define MCAST_JOIN_GROUP 42
#define MCAST_BLOCK_SOURCE 43
#define MCAST_UNBLOCK_SOURCE 44
#define MCAST_LEAVE_GROUP 45
#define MCAST_JOIN_SOURCE_GROUP 46
#define MCAST_LEAVE_SOURCE_GROUP 47
#define MCAST_MSFILTER 48

#define MCAST_EXCLUDE 0
#define MCAST_INCLUDE 1

struct ip_mreq {
    struct in_addr imr_multiaddr;
    struct in_addr imr_interface;
};

struct ip_mreqn {
    struct in_addr imr_multiaddr;
    struct in_addr imr_address;
    int imr_ifindex;
};

struct ip_mreq_source {
    struct in_addr imr_multiaddr;
    struct in_addr imr_interface;
    struct in_addr imr_sourceaddr;
};

struct ip_msfilter {
    struct in_addr imsf_multiaddr;
    struct in_addr imsf_interface;
    uint32_t imsf_fmode;
    uint32_t imsf_numsrc;
    struct in_addr imsf_slist[1];
};
#define IP_MSFILTER_SIZE(numsrc) \
    (sizeof(struct ip_msfilter) - sizeof(struct in_addr) + (numsrc) * sizeof(struct in_addr))

struct group_req {
    uint32_t gr_interface;
    struct sockaddr_storage gr_group;
};

struct group_source_req {
    uint32_t gsr_interface;
    struct sockaddr_storage gsr_group;
    struct sockaddr_storage gsr_source;
};

struct group_filter {
    uint32_t gf_interface;
    struct sockaddr_storage gf_group;
    uint32_t gf_fmode;
    uint32_t gf_numsrc;
    struct sockaddr_storage gf_slist[1];
};
#define GROUP_FILTER_SIZE(numsrc)                                    \
    (sizeof(struct group_filter) - sizeof(struct sockaddr_storage) + \
     (numsrc) * sizeof(struct sockaddr_storage))

struct in_pktinfo {
    int ipi_ifindex;
    struct in_addr ipi_spec_dst;
    struct in_addr ipi_addr;
};

struct in6_pktinfo {
    struct in6_addr ipi6_addr;
    unsigned ipi6_ifindex;
};

struct ip6_mtuinfo {
    struct sockaddr_in6 ip6m_addr;
    uint32_t ip6m_mtu;
};
#endif

#define IPV6_ADDRFORM 1
#define IPV6_2292PKTINFO 2
#define IPV6_2292HOPOPTS 3
#define IPV6_2292DSTOPTS 4
#define IPV6_2292RTHDR 5
#define IPV6_2292PKTOPTIONS 6
#define IPV6_CHECKSUM 7
#define IPV6_2292HOPLIMIT 8
#define IPV6_NEXTHOP 9
#define IPV6_AUTHHDR 10
#define IPV6_UNICAST_HOPS 16
#define IPV6_MULTICAST_IF 17
#define IPV6_MULTICAST_HOPS 18
#define IPV6_MULTICAST_LOOP 19
#define IPV6_JOIN_GROUP 20
#define IPV6_LEAVE_GROUP 21
#define IPV6_ROUTER_ALERT 22
#define IPV6_MTU_DISCOVER 23
#define IPV6_MTU 24
#define IPV6_RECVERR 25
#define IPV6_V6ONLY 26
#define IPV6_JOIN_ANYCAST 27
#define IPV6_LEAVE_ANYCAST 28
#define IPV6_IPSEC_POLICY 34
#define IPV6_XFRM_POLICY 35
#define IPV6_HDRINCL 36

#define IPV6_RECVPKTINFO 49
#define IPV6_PKTINFO 50
#define IPV6_RECVHOPLIMIT 51
#define IPV6_HOPLIMIT 52
#define IPV6_RECVHOPOPTS 53
#define IPV6_HOPOPTS 54
#define IPV6_RTHDRDSTOPTS 55
#define IPV6_RECVRTHDR 56
#define IPV6_RTHDR 57
#define IPV6_RECVDSTOPTS 58
#define IPV6_DSTOPTS 59
#define IPV6_RECVPATHMTU 60
#define IPV6_PATHMTU 61
#define IPV6_DONTFRAG 62
#define IPV6_RECVTCLASS 66
#define IPV6_TCLASS 67
#define IPV6_AUTOFLOWLABEL 70
#define IPV6_ADDR_PREFERENCES 72
#define IPV6_MINHOPCOUNT 73
#define IPV6_ORIGDSTADDR 74
#define IPV6_RECVORIGDSTADDR IPV6_ORIGDSTADDR
#define IPV6_TRANSPARENT 75
#define IPV6_UNICAST_IF 76

#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP
#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP
#define IPV6_RXHOPOPTS IPV6_HOPOPTS
#define IPV6_RXDSTOPTS IPV6_DSTOPTS

#define IPV6_PMTUDISC_DONT 0
#define IPV6_PMTUDISC_WANT 1
#define IPV6_PMTUDISC_DO 2
#define IPV6_PMTUDISC_PROBE 3
#define IPV6_PMTUDISC_INTERFACE 4
#define IPV6_PMTUDISC_OMIT 5

#define IPV6_PREFER_SRC_TMP 0x0001
#define IPV6_PREFER_SRC_PUBLIC 0x0002
#define IPV6_PREFER_SRC_PUBTMP_DEFAULT 0x0100
#define IPV6_PREFER_SRC_COA 0x0004
#define IPV6_PREFER_SRC_HOME 0x0400
#define IPV6_PREFER_SRC_CGA 0x0008
#define IPV6_PREFER_SRC_NONCGA 0x0800

#define IPV6_RTHDR_LOOSE 0
#define IPV6_RTHDR_STRICT 1

#define IPV6_RTHDR_TYPE_0 0

#ifdef __cplusplus
}
#endif


<|start_filename|>pkg/fidl/include/lib/fidl/llcpp/encoded_message.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIDL_LLCPP_ENCODED_MESSAGE_H_
#define LIB_FIDL_LLCPP_ENCODED_MESSAGE_H_

#include <algorithm>
#include <cstdint>
#include <iterator>
#include <lib/fidl/cpp/message_part.h>
#include <lib/fidl/llcpp/traits.h>
#include <lib/fit/traits.h>
#include <type_traits>
#include <utility>
#include <zircon/fidl.h>

#ifdef __Fuchsia__
#include <zircon/syscalls.h>
#endif

namespace fidl {

// Holds an encoded FIDL message, that is, a byte array plus a handle table.
//
// The bytes part points to an external caller-managed buffer, while the handles part
// is owned by this class. Any handles will be closed upon destruction.
// This class is aware of the upper bound on the number of handles
// in a message, such that its size can be adjusted to fit the demands
// of a specific FIDL type.
//
// Because this class does not own the underlying message buffer, the caller
// must make sure the lifetime of this class does not extend over that of the buffer.
template <typename FidlType>
class EncodedMessage final {
    static_assert(IsFidlType<FidlType>::value, "Only FIDL types allowed here");
    static_assert(FidlType::MaxSize > 0, "Positive message size");

public:
    // Instantiates an empty buffer with no bytes or handles.
    EncodedMessage() = default;

    EncodedMessage(EncodedMessage&& other) noexcept {
        if (this != &other) {
            MoveImpl(std::move(other));
        }
    }

    EncodedMessage& operator=(EncodedMessage&& other) noexcept {
        if (this != &other) {
            MoveImpl(std::move(other));
        }
        return *this;
    }

    EncodedMessage(const EncodedMessage& other) = delete;

    EncodedMessage& operator=(const EncodedMessage& other) = delete;

    // Instantiates an EncodedMessage which points to a buffer region with caller-managed memory.
    // It does not take ownership of that buffer region.
    // Also initializes an empty handles part.
    EncodedMessage(BytePart bytes) :
        bytes_(std::move(bytes)) { }

    ~EncodedMessage() {
        CloseHandles();
    }

    // Takes ownership of the contents of the message.
    // The bytes and handle parts will become empty, while the existing bytes part is returned.
    // The caller is responsible for having transferred the handles elsewhere
    // before calling this method.
    BytePart ReleaseBytesAndHandles() {
        handles_.set_actual(0);
        BytePart return_bytes = std::move(bytes_);
        return return_bytes;
    }

    const BytePart& bytes() const { return bytes_; }

    const HandlePart& handles() const { return handles_; }

    // Clears the contents of the EncodedMessage then invokes Callback
    // to initialize the EncodedMessage in-place then returns the callback's
    // result.
    //
    // |callback| is a callable object whose arguments are (BytePart&, HandlePart&).
    template <typename Callback>
    decltype(auto) Initialize(Callback callback) {
        static_assert(
            fit::callable_traits<Callback>::args::size == 2 &&
            std::is_same<
                BytePart&,
                typename fit::template callable_traits<Callback>::args::template at<0>>::value &&
            std::is_same<
                HandlePart&,
                typename fit::template callable_traits<Callback>::args::template at<1>>::value,
            "Callback signature must be: T(BytePart&, HandlePart&).");
        bytes_ = BytePart();
        CloseHandles();
        return callback(bytes_, handles_);
    }

private:
    void CloseHandles() {
        if (handles_.actual() > 0) {
#ifdef __Fuchsia__
            zx_handle_close_many(handles_.data(), handles_.actual());
#else
            // How did we have handles if not on Fuchsia? Something bad happened...
            assert(false);
#endif
            handles_.set_actual(0);
        }
    }

    void MoveImpl(EncodedMessage&& other) noexcept {
        CloseHandles();
        bytes_ = std::move(other.bytes_);
        // copy handles from |other|
        memcpy(handle_storage_, other.handle_storage_,
            other.handles_.actual() * sizeof(zx_handle_t));
        // release handles in |other|
        handles_.set_actual(other.handles().actual());
        other.handles_.set_actual(0);
    }

    BytePart bytes_;
    zx_handle_t handle_storage_[FidlType::MaxNumHandles];
    HandlePart handles_{handle_storage_, FidlType::MaxNumHandles};
};

}

#endif  // LIB_FIDL_LLCPP_ENCODED_MESSAGE_H_


<|start_filename|>dart/fuchsia_modular/lib/module.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/// A collection of utilities simplifying module interactions
export 'src/module/embedded_module.dart';
export 'src/module/intent.dart';
export 'src/module/intent_handler.dart';
export 'src/module/module.dart';
export 'src/module/module_state_exception.dart';
export 'src/module/noop_intent_handler.dart';


<|start_filename|>arch/x64/sysroot/include/zircon/hw/usb-audio.h<|end_filename|>
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

// clang-format off

#include <zircon/compiler.h>
#include <zircon/types.h>

__BEGIN_CDECLS;

////////////////////////////////////////////////////
//
// General Audio interface constants
//
////////////////////////////////////////////////////

// audio interface subclasses
#define USB_SUBCLASS_AUDIO_CONTROL              0x01
#define USB_SUBCLASS_AUDIO_STREAMING            0x02
#define USB_SUBCLASS_MIDI_STREAMING             0x03

// audio class specific descriptor types
#define USB_AUDIO_CS_DEVICE                     0x21
#define USB_AUDIO_CS_CONFIGURATION              0x22
#define USB_AUDIO_CS_STRING                     0x23
#define USB_AUDIO_CS_INTERFACE                  0x24
#define USB_AUDIO_CS_ENDPOINT                   0x25

////////////////////////////////////////////////////
//
// Audio Control interface constants
//
////////////////////////////////////////////////////

// audio class specific AC interface descriptor subtypes
#define USB_AUDIO_AC_HEADER                     0x01
#define USB_AUDIO_AC_INPUT_TERMINAL             0x02
#define USB_AUDIO_AC_OUTPUT_TERMINAL            0x03
#define USB_AUDIO_AC_MIXER_UNIT                 0x04
#define USB_AUDIO_AC_SELECTOR_UNIT              0x05
#define USB_AUDIO_AC_FEATURE_UNIT               0x06
#define USB_AUDIO_AC_PROCESSING_UNIT            0x07
#define USB_AUDIO_AC_EXTENSION_UNIT             0x08

// processing unit process types
#define USB_AUDIO_UP_DOWN_MIX_PROCESS           0x01
#define USB_AUDIO_DOLBY_PROLOGIC_PROCESS        0x02
#define USB_AUDIO_3D_STEREO_EXTENDER_PROCESS    0x03
#define USB_AUDIO_REVERBERATION_PROCESS         0x04
#define USB_AUDIO_CHORUS_PROCESS                0x05
#define USB_AUDIO_DYN_RANGE_COMP_PROCESS        0x06

// audio class specific endpoint descriptor subtypes
#define USB_AUDIO_EP_GENERAL                    0x01

// audio class specific request codes
#define USB_AUDIO_SET_CUR                       0x01
#define USB_AUDIO_GET_CUR                       0x81
#define USB_AUDIO_SET_MIN                       0x02
#define USB_AUDIO_GET_MIN                       0x82
#define USB_AUDIO_SET_MAX                       0x03
#define USB_AUDIO_GET_MAX                       0x83
#define USB_AUDIO_SET_RES                       0x04
#define USB_AUDIO_GET_RES                       0x84
#define USB_AUDIO_SET_MEM                       0x05
#define USB_AUDIO_GET_MEM                       0x85
#define USB_AUDIO_GET_STAT                      0xFF

// terminal control selectors
#define USB_AUDIO_COPY_PROTECT_CONTROL          0x01

// feature unit control selectors
#define USB_AUDIO_MUTE_CONTROL                  0x01
#define USB_AUDIO_VOLUME_CONTROL                0x02
#define USB_AUDIO_BASS_CONTROL                  0x03
#define USB_AUDIO_MID_CONTROL                   0x04
#define USB_AUDIO_TREBLE_CONTROL                0x05
#define USB_AUDIO_GRAPHIC_EQUALIZER_CONTROL     0x06
#define USB_AUDIO_AUTOMATIC_GAIN_CONTROL        0x07
#define USB_AUDIO_DELAY_CONTROL                 0x08
#define USB_AUDIO_BASS_BOOST_CONTROL            0x09
#define USB_AUDIO_LOUDNESS_CONTROL              0x0A

// feature unit control support bitmasks
#define USB_AUDIO_FU_BMA_MUTE                   (1u << 0u)
#define USB_AUDIO_FU_BMA_VOLUME                 (1u << 1u)
#define USB_AUDIO_FU_BMA_BASS                   (1u << 2u)
#define USB_AUDIO_FU_BMA_MID                    (1u << 3u)
#define USB_AUDIO_FU_BMA_TREBLE                 (1u << 4u)
#define USB_AUDIO_FU_BMA_GRAPHIC_EQUALIZER      (1u << 5u)
#define USB_AUDIO_FU_BMA_AUTOMATIC_GAIN         (1u << 6u)
#define USB_AUDIO_FU_BMA_DELAY                  (1u << 7u)
#define USB_AUDIO_FU_BMA_BASS_BOOST             (1u << 8u)
#define USB_AUDIO_FU_BMA_LOUDNESS               (1u << 9u)

// up/down mix processing unit control selectors
#define USB_AUDIO_UD_ENABLE_CONTROL             0x01
#define USB_AUDIO_UD_MODE_SELECT_CONTROL        0x02
#define USB_AUDIO_UD_MODE_SELECT_CONTROL        0x02

// Dolby Prologic processing unit control selectors
#define USB_AUDIO_DP_ENABLE_CONTROL             0x01
#define USB_AUDIO_DP_MODE_SELECT_CONTROL        0x02

// 3D stereo extender processing unit control selectors
#define USB_AUDIO_3D_ENABLE_CONTROL             0x01
#define USB_AUDIO_SPACIOUSNESS_CONTROL          0x03

// reverberation processing unit control selectors
#define USB_AUDIO_RV_ENABLE_CONTROL             0x01
#define USB_AUDIO_REVERB_LEVEL_CONTROL          0x02
#define USB_AUDIO_REVERB_TIME_CONTROL           0x03
#define USB_AUDIO_REVERB_FEEDBACK_CONTROL       0x04

// chorus processing unit control selectors
#define USB_AUDIO_CH_ENABLE_CONTROL             0x01
#define USB_AUDIO_CHORUS_LEVEL_CONTROL          0x02
#define USB_AUDIO_CHORUS_RATE_CONTROL           0x03
#define USB_AUDIO_CHORUS_DEPTH_CONTROL          0x04

// dynamic range compressor processing unit control selectors
#define USB_AUDIO_DR_ENABLE_CONTROL             0x01
#define USB_AUDIO_COMPRESSION_RATE_CONTROL      0x02
#define USB_AUDIO_MAXAMPL_CONTROL               0x03
#define USB_AUDIO_THRESHOLD_CONTROL             0x04
#define USB_AUDIO_ATTACK_TIME                   0x05
#define USB_AUDIO_RELEASE_TIME                  0x06

// extension unit control selectors
#define USB_AUDIO_XU_ENABLE_CONTROL             0x01

// endpoint control selectors
#define USB_AUDIO_SAMPLING_FREQ_CONTROL         0x01
#define USB_AUDIO_PITCH_CONTROL                 0x02

// USB audio terminal types
#define USB_AUDIO_TERMINAL_USB_UNDEFINED                0x0100
#define USB_AUDIO_TERMINAL_USB_STREAMING                0x0101
#define USB_AUDIO_TERMINAL_USB_VENDOR                   0x01FF
#define USB_AUDIO_TERMINAL_INPUT_UNDEFINED              0x0200
#define USB_AUDIO_TERMINAL_MICROPHONE                   0x0201
#define USB_AUDIO_TERMINAL_DESKTOP_MICROPHONE           0x0202
#define USB_AUDIO_TERMINAL_PERSONAL_MICROPHONE          0x0203
#define USB_AUDIO_TERMINAL_OMNI_DIRECTIONAL_MICROPHONE  0x0204
#define USB_AUDIO_TERMINAL_MICROPHONE_ARRAY             0x0205
#define USB_AUDIO_TERMINAL_PROCESSING_MICROPHONE_ARRAY  0x0206
#define USB_AUDIO_TERMINAL_OUTPUT_UNDEFINED             0x0300
#define USB_AUDIO_TERMINAL_SPEAKER                      0x0301
#define USB_AUDIO_TERMINAL_HEADPHONES                   0x0302
#define USB_AUDIO_TERMINAL_HEAD_MOUNTED_DISPLAY_AUDIO   0x0303
#define USB_AUDIO_TERMINAL_DESKTOP_SPEAKER              0x0304
#define USB_AUDIO_TERMINAL_ROOM_SPEAKER                 0x0305
#define USB_AUDIO_TERMINAL_COMMUNICATION_SPEAKER        0x0306
#define USB_AUDIO_TERMINAL_LOW_FREQ_EFFECTS_SPEAKER     0x0307
#define USB_AUDIO_TERMINAL_BIDIRECTIONAL_UNDEFINED      0x0400
#define USB_AUDIO_TERMINAL_HANDSET                      0x0401
#define USB_AUDIO_TERMINAL_HEADSET                      0x0402
#define USB_AUDIO_TERMINAL_SPEAKERPHONE                 0x0403
#define USB_AUDIO_TERMINAL_ECHO_SUPPRESSING_SPEAKERPHONE 0x0404
#define USB_AUDIO_TERMINAL_ECHO_CANCELING_SPEAKERPHONE  0x0405
#define USB_AUDIO_TERMINAL_TELEPHONY_UNDEFINED          0x0500
#define USB_AUDIO_TERMINAL_PHONE_LINE                   0x0501
#define USB_AUDIO_TERMINAL_TELEPHONE                    0x0502
#define USB_AUDIO_TERMINAL_DOWN_LINE_PHONE              0x0503
#define USB_AUDIO_TERMINAL_EXTERNAL_UNDEFINED           0x0600
#define USB_AUDIO_TERMINAL_ANALOG_CONNECTOR             0x0601
#define USB_AUDIO_TERMINAL_DIGITAL_AUDIO_INTERFACE      0x0602
#define USB_AUDIO_TERMINAL_LINE_CONNECTOR               0x0603
#define USB_AUDIO_TERMINAL_LEGACY_AUDIO_CONNECTOR       0x0604
#define USB_AUDIO_TERMINAL_SPDIF_INTERFACE              0x0605
#define USB_AUDIO_TERMINAL_1394_DA_STREAM               0x0606
#define USB_AUDIO_TERMINAL_1394_DV_STREAM_SOUNDTRACK    0x0607
#define USB_AUDIO_TERMINAL_EMBEDDED_UNDEFINED           0x0700
#define USB_AUDIO_TERMINAL_LEVEL_CALIBRATION_NOISE_SOURCE 0x0701
#define USB_AUDIO_TERMINAL_EQUALIZATION_NOISE           0x0702
#define USB_AUDIO_TERMINAL_CD_PLAYER                    0x0703
#define USB_AUDIO_TERMINAL_DAT                          0x0704
#define USB_AUDIO_TERMINAL_DCC                          0x0705
#define USB_AUDIO_TERMINAL_MINI_DISK                    0x0706
#define USB_AUDIO_TERMINAL_ANALOG_TAPE                  0x0707
#define USB_AUDIO_TERMINAL_PHONOGRAPH                   0x0708
#define USB_AUDIO_TERMINAL_VCR_AUDIO                    0x0709
#define USB_AUDIO_TERMINAL_VIDEO_DISK_AUDIO             0x070A
#define USB_AUDIO_TERMINAL_DVD_AUDIO                    0x070B
#define USB_AUDIO_TERMINAL_TV_TUNER_AUDIO               0x070C
#define USB_AUDIO_TERMINAL_SATELLITE_RECEIVER_AUDIO     0x070D
#define USB_AUDIO_TERMINAL_CABLE_TUNER_AUDIO            0x070E
#define USB_AUDIO_TERMINAL_DSS_AUDIO                    0x070F
#define USB_AUDIO_TERMINAL_RADIO_RECEIVER               0x0710
#define USB_AUDIO_TERMINAL_RADIO_TRANSMITTER            0x0711
#define USB_AUDIO_TERMINAL_MULTI_TRACK_RECORDER         0x0712
#define USB_AUDIO_TERMINAL_SYNTHESIZER                  0x0713

////////////////////////////////////////////////////
//
// Audio streaming interface constants
//
////////////////////////////////////////////////////

// Audio stream class-specific AS interface descriptor subtypes
#define USB_AUDIO_AS_GENERAL                    0x01
#define USB_AUDIO_AS_FORMAT_TYPE                0x02
#define USB_AUDIO_AS_FORMAT_SPECIFIC            0x03

// wFormatTag values present in the class specific AS header
// Defined in Section A.1 of USB Device Class Definition for Audio Data Formats
#define USB_AUDIO_AS_FT_TYPE_I_UNDEFINED        0x0000
#define USB_AUDIO_AS_FT_PCM                     0x0001
#define USB_AUDIO_AS_FT_PCM8                    0x0002
#define USB_AUDIO_AS_FT_IEEE_FLOAT              0x0003
#define USB_AUDIO_AS_FT_ALAW                    0x0004
#define USB_AUDIO_AS_FT_MULAW                   0x0005
#define USB_AUDIO_AS_FT_TYPE_II_UNDEFINED       0x1000
#define USB_AUDIO_AS_FT_MPEG                    0x1001
#define USB_AUDIO_AS_FT_AC3                     0x1002
#define USB_AUDIO_AS_FT_TYPE_III_UNDEFINED      0x2000
#define USB_AUDIO_AS_FT_IEC1937_AC3             0x2001
#define USB_AUDIO_AS_FT_IEC1937_MPEG1_L1        0x2002
#define USB_AUDIO_AS_FT_IEC1937_MPEG1_L23       0x2003
#define USB_AUDIO_AS_FT_IEC1937_MPEG2_EXT       0x2004
#define USB_AUDIO_AS_FT_IEC1937_MPEG2_L1_LS     0x2005
#define USB_AUDIO_AS_FT_IEC1937_MPEG2_L23_LS    0x2006

// Audio stream class-specific format-specific types
#define USB_AUDIO_FORMAT_TYPE_UNDEFINED         0x00
#define USB_AUDIO_FORMAT_TYPE_I                 0x01
#define USB_AUDIO_FORMAT_TYPE_II                0x02
#define USB_AUDIO_FORMAT_TYPE_III               0x03

////////////////////////////////////////////////////
//
// MIDI streaming interface constants
//
////////////////////////////////////////////////////

// MIDI class specific MS interface descriptor subtypes
#define USB_MIDI_MS_HEADER                      0x01
#define USB_MIDI_IN_JACK                        0x02
#define USB_MIDI_OUT_JACK                       0x03
#define USB_MIDI_ELEMENT                        0x04

// MIDI class specific MS endpoint descriptor subtypes
#define USB_MIDI_MS_GENERAL                     0x01

// MIDI IN and OUT jack types
#define USB_MIDI_JACK_EMBEDDED                  0x01
#define USB_MIDI_JACK_INTERNAL                  0x02

// MIDI endpoint control selectors
#define USB_MIDI_ASSOCIATION_CONTROL            0x01


// Top level header structure shared by all USB audio descriptors.
//
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;
} __PACKED usb_audio_desc_header;

// Audio Control Interface descriptor definitions
//
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AC_HEADER
    uint16_t bcdADC;
    uint16_t wTotalLength;
    uint8_t bInCollection;
    uint8_t baInterfaceNr[];
} __PACKED usb_audio_ac_header_desc;

// Common header structure shared by all unit and terminal descriptors found in
// an Audio Control interface descriptor.
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AC_.*_(TERMINAL|UNIT)
    uint8_t bID;
} __PACKED usb_audio_ac_ut_desc;

// Common header structure shared by all terminal descriptors found in an Audio
// Control interface descriptor.
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AC_(INPUT|OUTPUT)_TERMINAL
    uint8_t bTerminalID;
    uint16_t wTerminalType;
    uint8_t bAssocTerminal;
} __PACKED usb_audio_ac_terminal_desc;

typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AC_INPUT_TERMINAL
    uint8_t bTerminalID;
    uint16_t wTerminalType;
    uint8_t bAssocTerminal;
    uint8_t bNrChannels;
    uint16_t wChannelConfig;
    uint8_t iChannelNames;
    uint8_t iTerminal;
} __PACKED usb_audio_ac_input_terminal_desc;

typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AC_OUTPUT_TERMINAL
    uint8_t bTerminalID;
    uint16_t wTerminalType;
    uint8_t bAssocTerminal;
    uint8_t bSourceID;
    uint8_t iTerminal;
} __PACKED usb_audio_ac_output_terminal_desc;

// Note: Mixer unit descriptors contain two inlined variable length arrays, each
// with descriptor data following them.  They are therefor described using 3
// structure definitions which are logically concatenated, but separated by the
// inline arrays.
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AC_MIXER_UNIT
    uint8_t bUnitID;
    uint8_t bNrInPins;
    uint8_t baSourceID[];
} __PACKED usb_audio_ac_mixer_unit_desc_0;

typedef struct {
    uint8_t bNrChannels;
    uint16_t wChannelConfig;
    uint8_t iChannelNames;
    uint8_t bmControls[];
} __PACKED usb_audio_ac_mixer_unit_desc_1;

typedef struct {
    uint8_t iMixer;
} __PACKED usb_audio_ac_mixer_unit_desc_2;

// Note: Selector unit descriptors contain an inlined variable length array with
// descriptor data following it.  They are therefor described using 2 structure
// definitions which are logically concatenated, but separated by the inline
// array.
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AC_SELECTOR_UNIT
    uint8_t bUnitID;
    uint8_t bNrInPins;
    uint8_t baSourceID[];
} __PACKED usb_audio_ac_selector_unit_desc_0;

typedef struct {
    uint8_t iSelector;
} __PACKED usb_audio_ac_selector_unit_desc_1;

// Note: Feature unit descriptors contain an inlined variable length array with
// descriptor data following it.  They are therefor described using 2 structure
// definitions which are logically concatenated, but separated by the inline
// array.
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AC_FEATURE_UNIT
    uint8_t bUnitID;
    uint8_t bSourceID;
    uint8_t bControlSize;
    uint8_t bmaControls[];
} __PACKED usb_audio_ac_feature_unit_desc_0;

typedef struct {
    uint8_t iFeature;
} __PACKED usb_audio_ac_feature_unit_desc_1;

// Note: Processing unit descriptors contain two inlined variable length arrays,
// each with descriptor data following them.  They are therefor described using
// 3 structure definitions which are logically concatinated, but separated by
// the inline arrays.
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AC_PROCESSING_UNIT
    uint8_t bUnitID;
    uint16_t wProcessType;
    uint8_t bNrInPins;
    uint8_t baSourceID[];
} __PACKED usb_audio_ac_processing_unit_desc_0;

typedef struct {
    uint8_t bNrChannels;
    uint16_t wChannelConfig;
    uint8_t iChannelNames;
    uint8_t bControlSize;
    uint8_t bmControls[];
} __PACKED usb_audio_ac_processing_unit_desc_1;

typedef struct {
    uint8_t iProcessing;
    // Note: The Process-specific control structure follows this with the
    // structure type determined by wProcessType
    // TODO(johngro) : Define the process specific control structures.  As of
    // the 1.0 revision of the USB audio spec, the types to be defined are...
    //
    // ** Up/Down-mix
    // ** Dolby Prologic
    // ** 3D-Stereo Extender
    // ** Reverberation
    // ** Chorus
    // ** Dynamic Range Compressor
} __PACKED usb_audio_ac_processing_unit_desc_2;

// Note: Extension unit descriptors contain two inlined variable length arrays,
// each with descriptor data following them.  They are therefor described using
// 3 structure definitions which are logically concatenated, but separated by
// the inline arrays.
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AC_EXTENSION_UNIT
    uint8_t bUnitID;
    uint16_t wExtensionCode;
    uint8_t bNrInPins;
    uint8_t baSourceID[];
} __PACKED usb_audio_ac_extension_unit_desc_0;

typedef struct {
    uint8_t bNrChannels;
    uint16_t wChannelConfig;
    uint8_t iChannelNames;
    uint8_t bControlSize;
    uint8_t bmControls[];
} __PACKED usb_audio_ac_extension_unit_desc_1;

typedef struct {
    uint8_t iExtension;
} __PACKED usb_audio_ac_extension_unit_desc_2;

// Audio Streaming Interface descriptor definitions
//
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AS_GENERAL
    uint8_t bTerminalLink;
    uint8_t bDelay;
    uint16_t wFormatTag;
} __PACKED usb_audio_as_header_desc;

typedef struct {
    uint8_t freq[3];            // 24 bit unsigned integer, little-endian
} __PACKED usb_audio_as_samp_freq;

// Common header used by all format type descriptors
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AS_FORMAT_TYPE
    uint8_t bFormatType;
} __PACKED usb_audio_as_format_type_hdr;

typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_AUDIO_AS_FORMAT_TYPE
    uint8_t bFormatType;            // USB_AUDIO_FORMAT_TYPE_I
    uint8_t bNrChannels;
    uint8_t bSubFrameSize;
    uint8_t bBitResolution;
    uint8_t bSamFreqType;           // number of sampling frequencies
    usb_audio_as_samp_freq tSamFreq[]; // list of sampling frequencies (3 bytes each)
} __PACKED usb_audio_as_format_type_i_desc;

typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_ENDPOINT
    uint8_t bDescriptorSubtype;     // USB_AUDIO_EP_GENERAL
    uint8_t bmAttributes;
    uint8_t bLockDelayUnits;
    uint16_t wLockDelay;
} __PACKED usb_audio_as_isoch_ep_desc;

// MIDI Streaming Interface descriptor definitions
//
typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_MIDI_MS_HEADER
    uint16_t bcdMSC;
    uint16_t wTotalLength;
} __PACKED usb_midi_ms_header_desc;

typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_MIDI_IN_JACK
    uint8_t bJackType;
    uint8_t bJackID;
    uint8_t iJack;
} __PACKED usb_midi_ms_in_jack_desc;

typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_INTERFACE
    uint8_t bDescriptorSubtype;     // USB_MIDI_OUT_JACK
    uint8_t bJackType;
    uint8_t bJackID;
    uint8_t bNrInputPins;
    uint8_t baSourceID;
    uint8_t baSourcePin;
} __PACKED usb_midi_ms_out_jack_desc;

typedef struct {
    uint8_t bLength;
    uint8_t bDescriptorType;        // USB_AUDIO_CS_ENDPOINT
    uint8_t bDescriptorSubtype;     // USB_MIDI_MS_GENERAL
    uint8_t bNumEmbMIDIJack;
    uint8_t baAssocJackID[];
} __PACKED usb_midi_ms_endpoint_desc;

__END_CDECLS;


<|start_filename|>dart/fuchsia_modular/lib/src/service_connection/agent_service_connection.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:fidl/fidl.dart';
import 'package:fidl_fuchsia_modular/fidl_async.dart' as fidl_modular;
import 'package:fidl_fuchsia_sys/fidl_async.dart' as fidl_sys;
import 'package:fuchsia_logger/logger.dart';
import 'package:fuchsia_services/services.dart' as fuchsia_services;

import '../internal/_component_context.dart';

/// Connect to the service specified by [serviceProxy] and implemented by the
/// agent with [agentUrl].
///
/// The agent will be launched if it's not already running.
void connectToAgentService<T>(
  String agentUrl,
  AsyncProxy<T> serviceProxy,
) {
  if (agentUrl == null || agentUrl.isEmpty) {
    throw Exception(
        'agentUrl must not be null or empty in call to connectToAgentService');
  }
  if (serviceProxy == null) {
    throw Exception(
        'serviceProxy must not be null in call to connectToAgentService');
  }

  final serviceProviderProxy = fidl_sys.ServiceProviderProxy();
  final agentControllerProxy = fidl_modular.AgentControllerProxy();

  // Creates an interface request and binds one of the channels. Binding this
  // channel prior to connecting to the agent allows the developer to make
  // proxy calls without awaiting for the connection to actually establish.
  final serviceProxyRequest = serviceProxy.ctrl.request();

  // Connect to the agent with agentUrl
  getComponentContext()
      .connectToAgent(
    agentUrl,
    serviceProviderProxy.ctrl.request(),
    agentControllerProxy.ctrl.request(),
  )
      .then((_) {
    // Connect to the service
    fuchsia_services
        .connectToService(
      serviceProviderProxy,
      serviceProxy.ctrl.$serviceName,
      serviceProxy.ctrl.$interfaceName,
      serviceProxyRequest,
    )
        .then((_) {
      // Close agent controller when the service proxy is closed
      serviceProxy.ctrl.whenClosed.then((_) {
        log.info('Service proxy [${serviceProxy.ctrl.$serviceName}] is closed. '
            'Closing the associated AgentControllerProxy.');
        agentControllerProxy.ctrl.close();
      });

      // Close all unnecessary bindings
      serviceProviderProxy.ctrl.close();
    });
  }).catchError((e) {
    serviceProviderProxy.ctrl.close();
    agentControllerProxy.ctrl.close();
    serviceProxyRequest.close();
    throw e;
  });
}


<|start_filename|>arch/x64/sysroot/include/utime.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#define __NEED_time_t

#include <bits/alltypes.h>

struct utimbuf {
    time_t actime;
    time_t modtime;
};

int utime(const char*, const struct utimbuf*);

#ifdef __cplusplus
}
#endif


<|start_filename|>arch/x64/sysroot/include/strings.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#define __NEED_size_t
#define __NEED_locale_t
#include <bits/alltypes.h>

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) || defined(_POSIX_SOURCE) || \
    (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE + 0 < 200809L) ||            \
    (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE + 0 < 700)
int bcmp(const void*, const void*, size_t);
void bcopy(const void*, void*, size_t);
void bzero(void*, size_t);
char* index(const char*, int);
char* rindex(const char*, int);
#endif

#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
int ffs(int);
int ffsl(long);
int ffsll(long long);
#endif

int strcasecmp(const char*, const char*);
int strncasecmp(const char*, const char*, size_t);

int strcasecmp_l(const char*, const char*, locale_t);
int strncasecmp_l(const char*, const char*, size_t, locale_t);

#ifdef __cplusplus
}
#endif


<|start_filename|>dart/fuchsia_modular/lib/src/entity/entity.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:meta/meta.dart';
import 'package:uuid/uuid.dart';

import 'entity_codec.dart';
import 'internal/_link_entity.dart';

/// An [Entity] provides a mechanism for communicating
/// data between compoonents.
///
/// Note: this is a preliminary API that is likely to change.
@experimental
abstract class Entity<T> {
  /// Creates an entity that will live for the scope of this story.
  /// The entity that is created will be backed by the framework and
  /// can be treated as if it was received from any other entity provider.
  factory Entity({
    @required EntityCodec<T> codec,
  }) {
    // This is temporary and go away when we remove link entities.
    final linkName = Uuid().v4().toString();
    return LinkEntity<T>(linkName: linkName, codec: codec);
  }

  /// Returns the data stored in the entity.
  Future<T> getData();

  /// Writes the object stored in value
  Future<void> write(T object);

  /// Watches the entity for updates.
  ///
  /// An new value will be added to the stream whenever
  /// the entity is updated.
  ///
  /// The returned stream is a single subscription stream
  /// which, when closed, will close the underlying fidl
  /// connection.
  Stream<T> watch();
}

/// An exception which is thrown when an Entity does not
/// support a given type.
class EntityTypeException implements Exception {
  /// The unsuported type.
  final String type;

  /// Create a new [EntityTypeException].
  EntityTypeException(this.type);

  @override
  String toString() =>
      'EntityTypeError: type "$type" is not available for Entity';
}


<|start_filename|>pkg/sync/include/lib/sync/completion.h<|end_filename|>
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_SYNC_COMPLETION_H_
#define LIB_SYNC_COMPLETION_H_

#include <zircon/compiler.h>
#include <zircon/types.h>

__BEGIN_CDECLS

typedef struct sync_completion {
    zx_futex_t futex;

#ifdef __cplusplus
    sync_completion()
        : futex(0) {}
#endif
} sync_completion_t;

#if !defined(__cplusplus)
#define SYNC_COMPLETION_INIT ((sync_completion_t){0})
#endif

// Returns ZX_ERR_TIMED_OUT if timeout elapses, and ZX_OK if woken by
// a call to sync_completion_signal or if the completion has already been
// signaled.
zx_status_t sync_completion_wait(sync_completion_t* completion, zx_duration_t timeout);

// Returns ZX_ERR_TIMED_OUT if deadline elapses, and ZX_OK if woken by
// a call to sync_completion_signal or if the completion has already been
// signaled.
zx_status_t sync_completion_wait_deadline(sync_completion_t* completion, zx_time_t deadline);

// Awakens all waiters on the completion, and marks it as
// signaled. Waits after this call but before a reset of the
// completion will also see the signal and immediately return.
void sync_completion_signal(sync_completion_t* completion);

// Marks the completion as signaled, but doesn't awaken all waiters
// right away. Instead, all waiters are requeued to the |futex|.
// Waits after this call but before a reset of the
// completion will also see the signal and immediately return.
//
// Intended to be used by libsync internally, e.g. the condition variable
// implementation.
void sync_completion_signal_requeue(sync_completion_t* completion, zx_futex_t* futex);

// Resets the completion's signaled state to unsignaled.
void sync_completion_reset(sync_completion_t* completion);

__END_CDECLS

#endif // LIB_SYNC_COMPLETION_H_


<|start_filename|>dart/fuchsia_modular/lib/entity_codec.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/// The base class for implementing typed codecs for structured entity values.
library entity_codec;


<|start_filename|>arch/x64/sysroot/include/arpa/inet.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>
#include <netinet/in.h>

uint32_t htonl(uint32_t);
uint16_t htons(uint16_t);
uint32_t ntohl(uint32_t);
uint16_t ntohs(uint16_t);

in_addr_t inet_addr(const char*);
in_addr_t inet_network(const char*);
char* inet_ntoa(struct in_addr);
int inet_pton(int, const char* __restrict, void* __restrict);
const char* inet_ntop(int, const void* __restrict, char* __restrict, socklen_t);

int inet_aton(const char*, struct in_addr*);
struct in_addr inet_makeaddr(in_addr_t, in_addr_t);
in_addr_t inet_lnaof(struct in_addr);
in_addr_t inet_netof(struct in_addr);

#undef INET_ADDRSTRLEN
#undef INET6_ADDRSTRLEN
#define INET_ADDRSTRLEN 16
#define INET6_ADDRSTRLEN 46

#ifdef __cplusplus
}
#endif


<|start_filename|>dart/fuchsia_modular/lib/src/entity/entity_codec.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:meta/meta.dart';

/// The [EntityCodec] is a typed [Codec] which translates
/// entity data between the [Uint8List] wire format and a
/// dart object.
///
/// [EntityCodec]s have a specific semantic type and encoding
/// which allow them to operate with the entity system.
abstract class EntityCodec<T> extends Codec<T, Uint8List> {
  /// The semantic type of the entity which this codec supports.
  /// This type will be used when requesting entities from the
  /// framework.
  final String type;

  /// The encoding that this [EntityCodec] knows how to encode/decode data
  final String encoding;

  /// The default constructor.
  const EntityCodec({
    @required this.type,
    @required this.encoding,
  })  : assert(type != null),
        assert(encoding != null);
}

/// A [Codec] used for handling the the automatic translation to and from an
/// Entity's source data to the specified Dart type [T].
class SimpleEntityCodec<T> extends EntityCodec<T> {
  final _EntityEncoder<T> _encoder;
  final _EntityDecoder<T> _decoder;

  /// Create a new [EntityCodec].
  SimpleEntityCodec({
    @required String type,
    @required String encoding,
    @required _EncodeEntity<T> encode,
    @required _DecodeEntity<T> decode,
  })  : assert(type != null),
        assert(encoding != null),
        assert(encode != null),
        assert(decode != null),
        _encoder = _EntityEncoder<T>(encode),
        _decoder = _EntityDecoder<T>(decode),
        super(type: type, encoding: encoding);

  @override
  _EntityEncoder<T> get encoder => _encoder;

  @override
  _EntityDecoder<T> get decoder => _decoder;
}

typedef _EncodeEntity<T> = Uint8List Function(T value);

class _EntityEncoder<T> extends Converter<T, Uint8List> {
  final _EncodeEntity<T> encode;

  const _EntityEncoder(this.encode);

  @override
  Uint8List convert(T source) {
    return encode(source);
  }
}

typedef _DecodeEntity<T> = T Function(Uint8List data);

class _EntityDecoder<T> extends Converter<Uint8List, T> {
  final _DecodeEntity<T> decode;

  const _EntityDecoder(this.decode);

  @override
  T convert(Uint8List data) => decode(data);

  @override
  Stream<T> bind(Stream<Uint8List> source) {
    _EntityDecoderSink<T> map(EventSink<T> out) =>
        new _EntityDecoderSink<T>(out, this);

    return new Stream<T>.eventTransformed(source, map);
  }
}

/// Entity data [String]s in, [T] out.
class _EntityDecoderSink<T> extends EventSink<Uint8List> {
  /// The [EventSink] that values are decoded into. Errors generated by the
  /// decoder are also added to [out].
  final EventSink<T> out;

  /// The decoder to used to convert the source ([Stream<String>]) events.
  final _EntityDecoder<T> decoder;

  /// Create an instance of [_EntityDecoderSink], usually via the
  /// [Stream#eventTransformed] constructor.
  _EntityDecoderSink(this.out, this.decoder);

  @override
  void add(Uint8List data) {
    try {
      T value = decoder.decode(data);
      out.add(value);
    } on Object catch (err, stackTrace) {
      addError(err, stackTrace);
    }
  }

  @override
  void addError(Object e, [StackTrace s]) => out.addError(e, s);

  @override
  void close() => out.close();
}


<|start_filename|>arch/x64/sysroot/include/netdb.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>
#include <netinet/in.h>

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#define __NEED_size_t
#include <bits/alltypes.h>
#endif

struct addrinfo {
    int ai_flags;
    int ai_family;
    int ai_socktype;
    int ai_protocol;
    socklen_t ai_addrlen;
    struct sockaddr* ai_addr;
    char* ai_canonname;
    struct addrinfo* ai_next;
};

#define IPPORT_RESERVED 1024

#define AI_PASSIVE 0x01
#define AI_CANONNAME 0x02
#define AI_NUMERICHOST 0x04
#define AI_V4MAPPED 0x08
#define AI_ALL 0x10
#define AI_ADDRCONFIG 0x20
#define AI_NUMERICSERV 0x400

#define NI_NUMERICHOST 0x01
#define NI_NUMERICSERV 0x02
#define NI_NOFQDN 0x04
#define NI_NAMEREQD 0x08
#define NI_DGRAM 0x10
#define NI_NUMERICSCOPE 0x100

#define EAI_BADFLAGS -1
#define EAI_NONAME -2
#define EAI_AGAIN -3
#define EAI_FAIL -4
#define EAI_FAMILY -6
#define EAI_SOCKTYPE -7
#define EAI_SERVICE -8
#define EAI_MEMORY -10
#define EAI_SYSTEM -11
#define EAI_OVERFLOW -12

int getaddrinfo(const char* __restrict, const char* __restrict, const struct addrinfo* __restrict,
                struct addrinfo** __restrict);
void freeaddrinfo(struct addrinfo*);
int getnameinfo(const struct sockaddr* __restrict, socklen_t, char* __restrict, socklen_t,
                char* __restrict, socklen_t, int);
const char* gai_strerror(int);

/* Legacy functions follow (marked OBsolete in SUS) */

struct netent {
    char* n_name;
    char** n_aliases;
    int n_addrtype;
    uint32_t n_net;
};

struct hostent {
    char* h_name;
    char** h_aliases;
    int h_addrtype;
    int h_length;
    char** h_addr_list;
};
#define h_addr h_addr_list[0]

struct servent {
    char* s_name;
    char** s_aliases;
    int s_port;
    char* s_proto;
};

struct protoent {
    char* p_name;
    char** p_aliases;
    int p_proto;
};

void sethostent(int);
void endhostent(void);
struct hostent* gethostent(void);

void setnetent(int);
void endnetent(void);
struct netent* getnetent(void);
struct netent* getnetbyaddr(uint32_t, int);
struct netent* getnetbyname(const char*);

void setservent(int);
void endservent(void);
struct servent* getservent(void);
struct servent* getservbyname(const char*, const char*);
struct servent* getservbyport(int, const char*);

void setprotoent(int);
void endprotoent(void);
struct protoent* getprotoent(void);
struct protoent* getprotobyname(const char*);
struct protoent* getprotobynumber(int);

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE) || defined(_POSIX_SOURCE) || \
    (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE + 0 < 200809L) ||            \
    (defined(_XOPEN_SOURCE) && _XOPEN_SOURCE + 0 < 700)
struct hostent* gethostbyname(const char*);
struct hostent* gethostbyaddr(const void*, socklen_t, int);
int* __h_errno_location(void);
#define h_errno (*__h_errno_location())
#define HOST_NOT_FOUND 1
#define TRY_AGAIN 2
#define NO_RECOVERY 3
#define NO_DATA 4
#define NO_ADDRESS NO_DATA
#endif

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
void herror(const char*);
const char* hstrerror(int);
int gethostbyname_r(const char*, struct hostent*, char*, size_t, struct hostent**, int*);
int gethostbyname2_r(const char*, int, struct hostent*, char*, size_t, struct hostent**, int*);
struct hostent* gethostbyname2(const char*, int);
int gethostbyaddr_r(const void*, socklen_t, int, struct hostent*, char*, size_t, struct hostent**,
                    int*);
int getservbyport_r(int, const char*, struct servent*, char*, size_t, struct servent**);
int getservbyname_r(const char*, const char*, struct servent*, char*, size_t, struct servent**);
#define EAI_NODATA -5
#define EAI_ADDRFAMILY -9
#define EAI_INPROGRESS -100
#define EAI_CANCELED -101
#define EAI_NOTCANCELED -102
#define EAI_ALLDONE -103
#define EAI_INTR -104
#define EAI_IDN_ENCODE -105
#define NI_MAXHOST 255
#define NI_MAXSERV 32
#endif

#ifdef __cplusplus
}
#endif


<|start_filename|>pkg/fit/include/lib/fit/promise.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIT_PROMISE_H_
#define LIB_FIT_PROMISE_H_

#include <assert.h>

#include <tuple>
#include <type_traits>
#include <utility>

#include "function.h"
#include "promise_internal.h"
#include "result.h"
#include "variant.h"

namespace fit {

// A |fit::promise| is a building block for asynchronous control flow that
// wraps an asynchronous task in the form of a "continuation" that is
// repeatedly invoked by an executor until it produces a result.
//
// Additional asynchronous tasks can be chained onto the promise using
// a variety of combinators such as |then()|.
//
// Use |fit::make_promise()| to create a promise.
// Use |fit::future| to more conveniently hold a promise or its result.
// Use |fit::pending_task| to wrap a promise as a pending task for execution.
// Use |fit::executor| to execute a pending task.
// See examples below.
//
// Always look to the future; never look back.
//
// SYNOPSIS
//
// |V| is the type of value produced when the completes successfully.
// Defaults to |void|.
//
// |E| is the type of error produced when the completes with an error.
// Defaults to |void|.
//
// Class members are documented in |fit::promise_impl|.
//
// CHAINING PROMISES USING COMBINATORS
//
// Promises can be chained together using combinators such as |then()|
// which consume the original promise(s) and return a new combined promise.
//
// For example, the |then()| combinator returns a promise that has the effect
// of asynchronously awaiting completion of the prior promise (the instance
// upon which |then()| was called) then delivering its result to a handler
// function.
//
// Available combinators defined in this library:
//
//    |then()|: run a handler when prior promise completes
//    |and_then()|: run a handler when prior promise completes successfully
//    |or_else()|: run a handler when prior promise completes with an error
//    |inspect()|: examine result of prior promise
//    |discard_result()|: discard result and unconditionally return
//                        fit::result<> when prior promise completes
//    |wrap_with()|: applies a wrapper to the promise
//    |box()|: wraps the promise's continuation into a |fit::function|
//    |fit::join_promises()|: await multiple promises, once they all complete
//                            return a tuple of their results
//
// You can also create your own custom combinators by crafting new
// types of continuations.
//
// CONTINUATIONS AND HANDLERS
//
// Internally, |fit::promise| wraps a continuation (a kind of callable
// object) that holds the state of the asynchronous task and provides a
// means for making progress through repeated invocation.
//
// A promise's continuation is generated through the use of factories
// such as |make_promise()| and combinators such as |then()|.  Most of
// these functions accept a client-supplied "handler" (another kind
// of callable object, often a lambda expression) which performs the actual
// computations.
//
// Continuations have a very regular interface: they always accept a
// |fit::context&| argument and return a |fit::result|.  Conversely, handlers
// have a very flexible interface: clients can provide them in many forms
// all of which are documented by the individual functions which consume them.
// It's pretty easy to use: the library takes care of wrapping client-supplied
// handlers of all supported forms into the continuations it uses internally.
//
// THEORY OF OPERATION
//
// On its own, a promise is "inert"; it only makes progress in response to
// actions taken by its owner.  The state of the promise never changes
// spontaneously or concurrently.
//
// Typically, a promise is executed by wrapping it into a |fit::pending_task|
// and scheduling it for execution using |fit::executor::schedule_task()|.
// A promise's |operator(fit::context&)| can also be invoked directly by its owner
// from within the scope of another task (this is used to implement combinators
// and futures) though the principle is the same.
//
// |fit::executor| is an abstract class that encapsulates a strategy for
// executing tasks.  The executor is responsible for invoking each tasks's
// continuation until the task returns a non-pending result, indicating that
// the task has been completed.
//
// The method of execution and scheduling of each continuation call is left
// to the discretion of each executor implementation.  Typical executor
// implementations may dispatch tasks on an event-driven message loop or on
// a thread pool.  Developers are responsible for selecting appropriate
// executor implementations for their programs.
//
// During each invocation, the executor passes the continuation an execution
// context object represented by a subclass of |fit::context|.  The continuation
// attempts to make progress then returns a value of type |fit::result| to
// indicate whether it completed successfully (signaled by |fit::ok()|),
// failed with an error (signaled by |fit::error()|, or was unable to complete
// the task during that invocation (signaled by |fit::pending()|).
// For example, a continuation may be unable to complete the task if it must
// asynchronously await completion of an I/O or IPC operation before it
// can proceed any further.
//
// If the continuation was unable to complete the task during its invocation,
// it may to call |fit::context::suspend_task()| to acquire a
// |fit::suspended_task| object.  The continuation then arranges for the
// task to be resumed asynchronously (with |fit::suspended_task::resume_task()|)
// once it becomes possible for the promise to make forward progress again.
// Finally, the continuation returns returns |fit::pending()| to indicate to
// the executor that it was unable to complete the task during that invocation.
//
// When the executor receives a pending result from a task's continuation,
// it moves the task into a table of suspended tasks.  A suspended task
// is considered abandoned if has not been resume and all remaining
// |fit::suspended_task| handles representing it have been dropped.
// When a task is abandoned, the executor removes it from its table of
// suspended tasks and destroys the task because it is not possible for the task
// to be resumed or to make progress from that state.
//
// See also |fit::single_threaded_executor| for a simple executor implementation.
//
// BOXED AND UNBOXED PROMISES
//
// To make combination and execution as efficient as possible, the promises
// returned by |fit::make_promise| and by combinators are parameterized by
// complicated continuation types that are hard to describe, often consisting of
// nested templates and lambdas.  These are referred to as "unboxed"
// promises.  In contrast, "boxed" promises are parameterized by a
// a |fit::function| that hides (or "erases") the type of the continuation
// thereby yielding type that is easier to describe.
//
// You can recognize boxed and unboxed promises by their types.
// Here are two examples:
//
// - A boxed promise type: `fit::promise<void, void>` which is an alias for
//  `fit::promise_impl<void, void, std::function<fit::result<void, void>>`.
// - An unboxed promise type: `fit::promise_impl<void, void,
//   fit::internal::then_continuation<...something unintelligible...>>`
//
// Although boxed promises are easier to manipulate, they may cause the
// continuation to be allocated on the heap.  Chaining boxed promises can
// result in multiple allocations being produced.
//
// Conversely, unboxed promises have full type information.  Not only does
// this defer heap allocation but it also makes it easier for the C++
// compiler to fuse a chains of unboxed promises together into a single
// object that is easier to optimize.
//
// Unboxed promises can be boxed by assigning them to a boxed promise
// type (such as |fit::promise<>|) or using the |box()| combinator.
//
// As a rule of thumb, always defer boxing of promises until it is necessary
// to transport them using a simpler type.
//
// Do this: (chaining as a single expression performs at most one heap allocation)
//
//     fit::promise<> f = fit::make_promise([] { ... });
//         .then([](fit::result<> result) { ... });
//         .and_then([] { ... });
//
// Or this: (still only performs at most one heap allocation)
//
//     auto f = fit::make_promise([] { ... });
//     auto g = f.then([](fit::result<> result) { ... });
//     auto h = g.and_then([] { ... });
//     fit::promise<> boxed_h = h;
//
// But don't do this: (incurs up to three heap allocations due to eager boxing)
//
//     fit::promise<> f = fit::make_promise([] { ... });
//     fit::promise<> g = f.then([](fit::result<> result) { ... });
//     fit::promise<> h = g.and_then([] { ... });
//
// SINGLE OWNERSHIP MODEL
//
// Promises have single-ownership semantics.  This means that there
// can only be at most one reference to the task represented by its
// continuation along with any state held by that continuation.
//
// When a combinator is applied to a promise, ownership of its continuation
// is transferred to the combined promise, leaving the original promise
// in an "empty" state without a continuation.  Note that it is an error
// to attempt to invoke an empty promise (will assert at runtime).
//
// This model greatly simplifies reasoning about object lifetime.
// If a promise goes out of scope without completing its task, the task
// is considered "abandoned", causing all associated state to be destroyed.
//
// Note that a promise may capture references to other objects whose lifetime
// differs from that of the promise.  It is the responsibility of the promise
// to ensure reachability of the objects whose reference it captures such
// as by using reference counted pointers, weak pointers, or other appropriate
// mechanisms to ensure memory safety.
//
// THREADING MODEL
//
// Promise objects are not thread-safe themselves.  You cannot call their
// methods concurrently (or re-entrantly).  However, promises can safely
// be moved to other threads and executed there (unless their continuation
// requires thread affinity for some reason but that's beyond the scope
// of this document).
//
// This property of being thread-independent, combined with the single
// ownership model, greatly simplifies the implementation of thread pool
// based executors.
//
// RESULT RETENTION AND FIT::FUTURES
//
// A promise's continuation can only be executed to completion once.
// After it completes, it cannot be run again.
//
// This method of execution is very efficient; the promise's result is returned
// directly to its invoker; it is not copied or retained within the promise
// object itself.  It is entirely the caller's responsibility to decide how to
// consume or retain the result if need be.
//
// For example, the caller can move the promise into a |fit::future| to
// more conveniently hold either the promise or its result upon completion.
//
// CLARIFICATION OF NOMENCLATURE
//
// In this library, the words "promise" and "future" have the following
// definitions:
//
// - A *promise* holds the function that performs an asynchronous task.
//   It is the means to produce a value.
// - A *future* holds the value produced by an asynchronous task or a
//   promise to produce that value if the task has not yet completed.
//   It is a proxy for a value that is to be computed.
//
// Be aware that other libraries may use these terms slightly differently.
//
// For more information about the theory of futures and promises, see
// https://en.wikipedia.org/wiki/Futures_and_promises.
//
// COMPARISON WITH STD::FUTURE
//
// |std::future| provides a mechanism for running asynchronous tasks
// and awaiting their results on other threads.  Waiting can be performed
// either by blocking the waiting thread or by polling the future.
// The manner in which tasks are scheduled and executed is entirely
// controlled by the C++ standard library and offers limited control
// to developers.
//
// |fit::promise| and |fit::future| provide a mechanism for running asynchronous
// tasks, chaining additional tasks using combinators, and awaiting their
// results.  An executor is responsible for suspending tasks awaiting
// results of other tasks and is at liberty to run other tasks on the
// same thread rather than blocking.  In addition, developers can create custom
// executors to implement their own policies for running tasks.
//
// Decoupling awaiting from blocking makes |fit::promise| quite versatile.
// |fit::promise| can also interoperate with other task dispatching mechanisms
// (including |std::future|) using adapters such as |fit::bridge|.
//
// EXAMPLE
//
// - https://fuchsia.googlesource.com/zircon/+/master/system/utest/fit/examples/promise_example1.cpp
// - https://fuchsia.googlesource.com/zircon/+/master/system/utest/fit/examples/promise_example2.cpp
//
template <typename V = void, typename E = void>
using promise = promise_impl<function<result<V, E>(fit::context&)>>;

// Promise implementation details.
// See |fit::promise| documentation for more information.
template <typename Continuation>
class promise_impl final {
    static_assert(
        ::fit::internal::is_continuation<Continuation>::value,
        "Continuation type is invalid.  A continuation is a callable object "
        "with this signature: fit::result<V, E>(fit::context&).");

    using state_type = nullable<Continuation>;

public:
    // The type of callable object held by the promise.
    // Its signature is: result_type(fit::context&).
    using continuation_type = Continuation;

    // The promise's result type.
    // Equivalent to fit::result<value_type, error_type>.
    using result_type = typename ::fit::internal::continuation_traits<
        Continuation>::result_type;

    // The type of value produced when the promise completes successfully.
    // May be void.
    using value_type = typename result_type::value_type;

    // The type of value produced when the promise completes with an error.
    // May be void.
    using error_type = typename result_type::error_type;

    // Creates an empty promise without a continuation.
    // A continuation must be assigned before the promise can be used.
    promise_impl() = default;
    explicit promise_impl(decltype(nullptr)) {}

    // Creates a promise with a continuation.
    // If |continuation| equals nullptr then the promise is empty.
    explicit promise_impl(continuation_type continuation)
        : state_(std::move(continuation)) {}

    // Converts from a promise holding a continuation that is assignable to
    // to this promise's continuation type.
    //
    // This is typically used to create a promise with a boxed continuation
    // type (such as |fit::function|) from an unboxed promise produced by
    // |fit::make_promise| or by combinators.
    //
    // EXAMPLE
    //
    //     // f is a promise_impl with a complicated unboxed type
    //     auto f = fit::make_promise([] { ... });
    //
    //     // g wraps f's continuation
    //     fit::promise<> g = std::move(f);
    //
    template <typename OtherContinuation,
              typename = std::enable_if_t<
                  std::is_constructible<continuation_type,
                                        OtherContinuation&&>::value>>
    promise_impl(promise_impl<OtherContinuation> other)
        : state_(other.state_.has_value()
                     ? state_type(continuation_type(std::move(*other.state_)))
                     : state_type()) {}

    // Creates a promise by taking the continuation from another promise,
    // leaving the other promise empty.
    promise_impl(promise_impl&& other) = default;

    // Destroys the promise, releasing its continuation.
    ~promise_impl() = default;

    // Returns true if the promise is non-empty (has a valid continuation).
    explicit operator bool() const { return state_.has_value(); }

    // Invokes the promise's continuation.
    //
    // This method should be called by an executor to evaluate the promise.
    // If the result's state is |result_state::pending| then the executor
    // is responsible for arranging to invoke the promise's continuation
    // again once it determines that it is possible to make progress
    // towards completion of the promise encapsulated within the promise.
    //
    // Once the continuation returns a result with status |result_state::ok|
    // or |result_state::error|, the promise is assigned an empty continuation.
    //
    // Asserts that the promise is non-empty.
    result_type operator()(context& context) {
        assert(state_.has_value());
        result_type result = (*state_)(context);
        if (!result.is_pending())
            state_.reset();
        return result;
    }

    // Takes the promise's continuation, leaving it in an empty state.
    // Asserts that the promise is non-empty.
    continuation_type take_continuation() {
        assert(state_.has_value());
        auto continuation = std::move(state_.value());
        state_.reset();
        return continuation;
    }

    // Assigns the promise by taking the continuation from another promise,
    // leaving the other promise empty.
    promise_impl& operator=(promise_impl&& other) = default;

    // Discards the promise's continuation, leaving it empty.
    promise_impl& operator=(decltype(nullptr)) {
        state_.reset();
        return *this;
    }

    // Assigns the promise's continuation.
    promise_impl& operator=(continuation_type continuation) {
        state_ = std::move(continuation);
        return *this;
    }

    // Swaps the promises' continuations.
    void swap(promise_impl& other) {
        using std::swap;
        swap(state_, other.state_);
    }

    // Returns an unboxed promise which invokes the specified handler
    // function after this promise completes (successfully or unsuccessfully),
    // passing its result.
    //
    // The received result's state is guaranteed to be either
    // |fit::result_state::ok| or |fit::result_state::error|, never
    // |fit::result_state::pending|.
    //
    // |handler| is a callable object (such as a lambda) which consumes the
    // result of this promise and returns a new result with any value type
    // and error type.  Must not be null.
    //
    // The handler must return one of the following types:
    // - void
    // - fit::result<new_value_type, new_error_type>
    // - fit::ok<new_value_type>
    // - fit::error<new_error_type>
    // - fit::pending
    // - fit::promise<new_value_type, new_error_type>
    // - any callable or unboxed promise with the following signature:
    //   fit::result<new_value_type, new_error_type>(fit::context&)
    //
    // The handler must accept one of the following argument lists:
    // - (result_type)
    // - (result_type&)
    // - (const result_type&)
    // - (fit::context&, result_type)
    // - (fit::context&, result_type&)
    // - (fit::context&, const result_type&)
    //
    // Asserts that the promise is non-empty.
    // This method consumes the promise's continuation, leaving it empty.
    //
    // EXAMPLE
    //
    //     auto f = fit::make_promise(...)
    //         .then([] (fit::result<int, std::string> result)
    //                   -> fit::result<std::string, void> {
    //             if (result.is_ok()) {
    //                 printf("received value: %d\n", result.value());
    //                 if (result.value() % 15 == 0)
    //                     return ::fit::ok("fizzbuzz");
    //                 if (result.value() % 3 == 0)
    //                     return ::fit::ok("fizz");
    //                 if (result.value() % 5 == 0)
    //                     return ::fit::ok("buzz");
    //                 return ::fit::ok(std::to_string(result.value()));
    //             } else {
    //                 printf("received error: %s\n", result.error().c_str());
    //                 return ::fit::error();
    //             }
    //         })
    //         .then(...);
    //
    template <typename ResultHandler>
    promise_impl<::fit::internal::then_continuation<promise_impl, ResultHandler>>
    then(ResultHandler handler) {
        static_assert(is_callable<ResultHandler>::value,
                      "ResultHandler must be a callable object.");

        assert(!is_null(handler));
        assert(state_.has_value());
        return make_promise_with_continuation(
            ::fit::internal::then_continuation<promise_impl, ResultHandler>(
                std::move(*this), std::move(handler)));
    }

    // Returns an unboxed promise which invokes the specified handler
    // function after this promise completes successfully, passing its
    // resulting value.
    //
    // |handler| is a callable object (such as a lambda) which consumes the
    // result of this promise and returns a new result with any value type
    // but the same error type.  Must not be null.
    //
    // The handler must return one of the following types:
    // - void
    // - fit::result<new_value_type, error_type>
    // - fit::ok<new_value_type>
    // - fit::error<error_type>
    // - fit::pending
    // - fit::promise<new_value_type, error_type>
    // - any callable or unboxed promise with the following signature:
    //   fit::result<new_value_type, error_type>(fit::context&)
    //
    // The handler must accept one of the following argument lists:
    // - (value_type)
    // - (value_type&)
    // - (const value_type&)
    // - (fit::context&, value_type)
    // - (fit::context&, value_type&)
    // - (fit::context&, const value_type&)
    //
    // Asserts that the promise is non-empty.
    // This method consumes the promise's continuation, leaving it empty.
    //
    // EXAMPLE
    //
    //     auto f = fit::make_promise(...)
    //         .and_then([] (int value) {
    //             printf("received value: %d\n", value);
    //             if (value % 15 == 0)
    //                 return ::fit::ok("fizzbuzz");
    //             if (value % 3 == 0)
    //                 return ::fit::ok("fizz");
    //             if (value % 5 == 0)
    //                 return ::fit::ok("buzz");
    //             return ::fit::ok(std::to_string(value));
    //         })
    //         .then(...);
    //
    template <typename ValueHandler>
    promise_impl<::fit::internal::and_then_continuation<promise_impl, ValueHandler>>
    and_then(ValueHandler handler) {
        static_assert(is_callable<ValueHandler>::value,
                      "ValueHandler must be a callable object.");

        assert(!is_null(handler));
        assert(state_.has_value());
        return make_promise_with_continuation(
            ::fit::internal::and_then_continuation<promise_impl, ValueHandler>(
                std::move(*this), std::move(handler)));
    }

    // Returns an unboxed promise which invokes the specified handler
    // function after this promise completes with an error, passing its
    // resulting error.
    //
    // |handler| is a callable object (such as a lambda) which consumes the
    // result of this promise and returns a new result with any error type
    // but the same value type.  Must not be null.
    //
    // The handler must return one of the following types:
    // - void
    // - fit::result<value_type, new_error_type>
    // - fit::ok<value_type>
    // - fit::error<new_error_type>
    // - fit::pending
    // - fit::promise<value_type, new_error_type>
    // - any callable or unboxed promise with the following signature:
    //   fit::result<value_type, new_error_type>(fit::context&)
    //
    // The handler must accept one of the following argument lists:
    // - (error_type)
    // - (error_type&)
    // - (const error_type&)
    // - (fit::context&, error_type)
    // - (fit::context&, error_type&)
    // - (fit::context&, const error_type&)
    //
    // Asserts that the promise is non-empty.
    // This method consumes the promise's continuation, leaving it empty.
    //
    // EXAMPLE
    //
    //     auto f = fit::make_promise(...)
    //         .or_else([] (std::string error) {
    //             printf("received error: %s\n", error.c_str());
    //             return ::fit::error();
    //         })
    //         .then(...);
    //
    template <typename ErrorHandler>
    promise_impl<::fit::internal::or_else_continuation<promise_impl, ErrorHandler>>
    or_else(ErrorHandler handler) {
        static_assert(is_callable<ErrorHandler>::value,
                      "ErrorHandler must be a callable object.");

        assert(!is_null(handler));
        assert(state_.has_value());
        return make_promise_with_continuation(
            ::fit::internal::or_else_continuation<promise_impl, ErrorHandler>(
                std::move(*this), std::move(handler)));
    }

    // Returns an unboxed promise which invokes the specified handler
    // function after this promise completes (successfully or unsuccessfully),
    // passing it the promise's result then delivering the result onwards
    // to the next promise once the handler returns.
    //
    // The handler receive a copy, const reference, or non-const reference
    // depending on the signature of the handler's last argument.
    //
    // - Copies and const references are especially useful for inspecting a
    //   result mid-stream without modification, such as printing it for
    //   debugging.
    // - Non-const references are especially useful for synchronously
    //   modifying a result mid-stream, such as clamping its bounds or
    //   injecting a default value.
    //
    // |handler| is a callable object (such as a lambda) which can examine
    // or modify the incoming result.  Unlike |then()|, the handler does
    // not need to propagate the result onwards.  Must not be null.
    //
    // The handler must return one of the following types:
    // - void
    //
    // The handler must accept one of the following argument lists:
    // - (result_type)
    // - (result_type&)
    // - (const result_type&)
    // - (fit::context&, result_type)
    // - (fit::context&, result_type&)
    // - (fit::context&, const result_type&)
    //
    // Asserts that the promise is non-empty.
    // This method consumes the promise's continuation, leaving it empty.
    //
    // EXAMPLE
    //
    //     auto f = fit::make_promise(...)
    //         .inspect([] (const fit::result<int, std::string>& result) {
    //             if (result.is_ok())
    //                 printf("received value: %d\n", result.value());
    //             else
    //                 printf("received error: %s\n", result.error().c_str());
    //         })
    //         .then(...);
    //
    template <typename InspectHandler>
    promise_impl<::fit::internal::inspect_continuation<promise_impl, InspectHandler>>
    inspect(InspectHandler handler) {
        static_assert(is_callable<InspectHandler>::value,
                      "InspectHandler must be a callable object.");
        static_assert(std::is_void<typename callable_traits<
                          InspectHandler>::return_type>::value,
                      "InspectHandler must return void.");

        assert(!is_null(handler));
        assert(state_.has_value());
        return make_promise_with_continuation(
            ::fit::internal::inspect_continuation<promise_impl, InspectHandler>(
                std::move(*this), std::move(handler)));
    }

    // Returns an unboxed promise which discards the result of this promise
    // once it completes, thereby always producing a successful result of
    // type fit::result<void, void> regardless of whether this promise
    // succeeded or failed.
    //
    // Asserts that the promise is non-empty.
    // This method consumes the promise's continuation, leaving it empty.
    //
    // EXAMPLE
    //
    //     auto f = fit::make_promise(...)
    //         .discard_result()
    //         .then(...);
    //
    promise_impl<::fit::internal::discard_result_continuation<promise_impl>>
    discard_result() {
        assert(state_.has_value());
        return make_promise_with_continuation(
            ::fit::internal::discard_result_continuation<promise_impl>(
                std::move(*this)));
    }

    // Applies a |wrapper| to the promise.  Invokes the wrapper's |wrap()|
    // method, passes the promise to the wrapper by value followed by any
    // additional |args| passed to |wrap_with()|, then returns the wrapper's
    // result.
    //
    // |Wrapper| is a type that implements a method called |wrap()| which
    // accepts a promise as its argument and produces a wrapped result of
    // any type, such as another promise.
    //
    // Asserts that the promise is non-empty.
    // This method consumes the promise's continuation, leaving it empty.
    //
    // EXAMPLE
    //
    // In this example, |fit::sequencer| is a wrapper type that imposes
    // FIFO execution order onto a sequence of wrapped promises.
    //
    //     // This wrapper type is intended to be applied to
    //     // a sequence of promises so we store it in a variable.
    //     fit::sequencer seq;
    //
    //     // This task consists of some amount of work that must be
    //     // completed sequentially followed by other work that can
    //     // happen in any order.  We use |wrap_with()| to wrap the
    //     // sequential work with the sequencer.
    //     fit::promise<> perform_complex_task() {
    //         return fit::make_promise([] { /* do sequential work */ })
    //             .then([] (fit::result<> result) { /* this will also be wrapped */ })
    //             .wrap_with(seq)
    //             .then([] (fit::result<> result) { /* do more work */ });
    //     }
    //
    // This example can also be written without using |wrap_with()|.
    // The behavior is equivalent but the syntax may seem more awkward.
    //
    //     fit::sequencer seq;
    //
    //     promise<> perform_complex_task() {
    //         return seq.wrap(
    //                 fit::make_promise([] { /* sequential work */ })
    //             ).then([] (fit::result<> result) { /* more work */ });
    //     }
    //
    template <typename Wrapper, typename... Args>
    decltype(auto) wrap_with(Wrapper& wrapper, Args... args) {
        assert(state_.has_value());
        return wrapper.wrap(std::move(*this),
                            std::forward<Args>(args)...);
    }

    // Wraps the promise's continuation into a |fit::function|.
    //
    // A boxed promise is easier to store and pass around than the unboxed
    // promises produced by |fit::make_promise()| and combinators, though boxing
    // may incur a heap allocation.
    //
    // It is a good idea to defer boxing the promise until after all
    // desired combinators have been applied to prevent unnecessary heap
    // allocation during intermediate states of the promise's construction.
    //
    // Returns an empty promise if this promise is empty.
    // This method consumes the promise's continuation, leaving it empty.
    //
    // EXAMPLE
    //
    //     // f's is a fit::promise_impl<> whose continuation contains an
    //     // anonymous type (the lambda)
    //     auto f = fit::make_promise([] {});
    //
    //     // g's type will be fit::promise<> due to boxing
    //     auto boxed_f = f.box();
    //
    //     // alternately, we can get exactly the same effect by assigning
    //     // the unboxed promise to a variable of a named type instead of
    //     // calling box()
    //     fit::promise<> boxed_f = std::move(f);
    //
    promise_impl<function<result_type(context&)>> box() {
        return std::move(*this);
    }

    promise_impl(const promise_impl&) = delete;
    promise_impl& operator=(const promise_impl&) = delete;

private:
    template <typename>
    friend class promise_impl;

    state_type state_;
};

template <typename Continuation>
void swap(promise_impl<Continuation>& a,
          promise_impl<Continuation>& b) {
    a.swap(b);
}

template <typename Continuation>
bool operator==(const promise_impl<Continuation>& f,
                decltype(nullptr)) {
    return !f;
}
template <typename Continuation>
bool operator==(decltype(nullptr),
                const promise_impl<Continuation>& f) {
    return !f;
}
template <typename Continuation>
bool operator!=(const promise_impl<Continuation>& f,
                decltype(nullptr)) {
    return !!f;
}
template <typename Continuation>
bool operator!=(decltype(nullptr),
                const promise_impl<Continuation>& f) {
    return !!f;
}

// Makes a promise containing the specified continuation.
//
// This function is used for making a promises given a callable object
// that represents a valid continuation type.  In contrast,
// |fit::make_promise()| supports a wider range of types and should be
// preferred in most situations.
//
// |Continuation| is a callable object with the signature
// fit::result<V, E>(fit::context&).
template <typename Continuation>
inline promise_impl<Continuation> make_promise_with_continuation(
    Continuation continuation) {
    return promise_impl<Continuation>(std::move(continuation));
}

// Returns an unboxed promise that wraps the specified handler.
// The type of the promise's result is inferred from the handler's result.
//
// |handler| is a callable object (such as a lambda.  Must not be null.
//
// The handler must return one of the following types:
// - void
// - fit::result<value_type, error_type>
// - fit::ok<value_type>
// - fit::error<error_type>
// - fit::pending
// - fit::promise<value_type, error_type>
// - any callable or unboxed promise with the following signature:
//   fit::result<value_type, error_type>(fit::context&)
//
// The handler must accept one of the following argument lists:
// - ()
// - (fit::context&)
//
// See documentation of |fit::promise| for more information.
//
// SYNOPSIS
//
// |Handler| is the handler function type.  It is typically inferred by the
// compiler from the |handler| argument.
//
// EXAMPLE
//
//     enum class weather_type { sunny, glorious, cloudy, eerie, ... };
//
//     weather_type look_outside() { ... }
//     void wait_for_tomorrow(fit::suspended_task task) {
//         ... arrange to call task.resume_task() tomorrow ...
//     }
//
//     fit::promise<weather_type, std::string> wait_for_good_weather(int max_days) {
//         return fit::make_promise([days_left = max_days] (fit::context context&) mutable
//                             -> fit::result<int, std::string> {
//             weather_type weather = look_outside();
//             if (weather == weather_type::sunny || weather == weather_type::glorious)
//                 return fit::ok(weather);
//             if (days_left > 0) {
//                 wait_for_tomorrow(context.suspend_task());
//                 return fit::pending();
//             }
//             days_left--;
//             return fit::error("nothing but grey skies");
//         });
//     }
//
//     auto f = wait_for_good_weather(7)
//         .and_then([] (weather_type weather) { ... })
//         .or_else([] (std::string error) { ... });
//
template <typename PromiseHandler>
inline promise_impl<::fit::internal::context_handler_invoker<PromiseHandler>>
make_promise(PromiseHandler handler) {
    static_assert(is_callable<PromiseHandler>::value,
                  "PromiseHandler must be a callable object.");

    assert(!is_null(handler));
    return make_promise_with_continuation(
        ::fit::internal::promise_continuation<PromiseHandler>(
            std::move(handler)));
}

// Jointly evaluates zero or more promises.
// Returns a promise that produces a std::tuple<> containing the result
// of each promise once they all complete.
//
// EXAMPLE
//
//     auto get_random_number() {
//         return fit::make_promise([] { return rand() % 10 });
//     }
//
//     auto get_random_product() {
//         auto f = get_random_number();
//         auto g = get_random_number();
//         return fit::join_promises(std::move(f), std::move(g))
//             .and_then([] (std::tuple<fit::result<int>, fit::result<int>> results) {
//                 return fit::ok(results.get<0>.value() + results.get<1>.value());
//             });
//     }
//
template <typename... Promises>
inline promise_impl<::fit::internal::join_continuation<Promises...>>
join_promises(Promises... promises) {
    return make_promise_with_continuation(
        ::fit::internal::join_continuation<Promises...>(std::move(promises)...));
}

// Describes the status of a future.
enum class future_state {
    // The future neither holds a result nor a promise that could produce a result.
    // An empty future cannot make progress until a promise or result is assigned to it.
    empty,
    // The future holds a promise that may eventually produce a result but
    // it currently doesn't have a result.  The future's promise must be
    // invoked in order to make progress from this state.
    pending,
    // The future holds a successful result.
    ok,
    // The future holds an error result.
    error
};

// A |fit::future| holds onto a |fit::promise| until it has completed then
// provides access to its |fit::result|.
//
// SYNOPSIS
//
// |V| is the type of value produced when the completes successfully.
// Defaults to |void|.
//
// |E| is the type of error produced when the completes with an error.
// Defaults to |void|.
//
// THEORY OF OPERATION
//
// A future has a single owner who is responsible for setting its promise
// or result and driving its execution.  Unlike |fit::promise|, a future retains
// the result produced by completion of its asynchronous task.  Result retention
// eases the implementation of combined tasks that need to await the results
// of other tasks before proceeding.
//
// See the example for details.
//
// A future can be in one of four states, depending on whether it holds...
// - a successful result: |fit::future_state::ok|
// - an error result: |fit::future_state::error|
// - a promise that may eventually produce a result: |fit::future_state::pending|
// - neither: |fit::future_state_empty|
//
// On its own, a future is "inert"; it only makes progress in response to
// actions taken by its owner.  The state of the future never changes
// spontaneously or concurrently.
//
// When the future's state is |fit::future_state::empty|, its owner is
// responsible for setting the future's promise or result thereby moving the
// future into the pending or ready state.
//
// When the future's state is |fit::future_state::pending|, its owner is
// responsible for calling the future's |operator()| to invoke the promise.
// If the promise completes and returns a result, the future will transition
// to the ok or error state according to the result.  The promise itself will
// then be destroyed since it has fulfilled its purpose.
//
// When the future's state is |fit::future_state::ok|, its owner is responsible
// for consuming the stored value using |value()|, |take_value()|,
// |result()|, |take_result()|, or |take_ok_result()|.
//
// When the future's state is |fit::future_state::error|, its owner is
// responsible for consuming the stored error using |error()|, |take_error()|,
// |result()|, |take_result()|, or |take_error_result()|.
//
// See also |fit::promise| for more information about promises and their
// execution.
//
// EXAMPLE
//
// - https://fuchsia.googlesource.com/zircon/+/master/system/utest/fit/examples/promise_example2.cpp
template <typename V = void, typename E = void>
using future = future_impl<promise<V, E>>;

// Future implementation details.
// See |fit::future| documentation for more information.
template <typename Promise>
class future_impl final {
public:
    // The type of promise held by the future.
    using promise_type = Promise;

    // The promise's result type.
    // Equivalent to fit::result<value_type, error_type>.
    using result_type = typename Promise::result_type;

    // The type of value produced when the promise completes successfully.
    // May be void.
    using value_type = typename Promise::value_type;

    // The type of value produced when the promise completes with an error.
    // May be void.
    using error_type = typename Promise::error_type;

    // Creates a future in the empty state.
    future_impl() = default;
    future_impl(decltype(nullptr)) {}

    // Creates a future and assigns a promise to compute its result.
    // If the promise is empty, the future enters the empty state.
    // Otherwise the future enters the pending state.
    explicit future_impl(promise_type promise) {
        if (promise) {
            state_.template emplace<1>(std::move(promise));
        }
    }

    // Creates a future and assigns its result.
    // If the result is pending, the future enters the empty state.
    // Otherwise the future enters the ok or error state.
    explicit future_impl(result_type result) {
        if (result) {
            state_.template emplace<2>(std::move(result));
        }
    }

    // Moves from another future, leaving the other one in an empty state.
    future_impl(future_impl&& other)
        : state_(std::move(other.state_)) {
        other.state_.template emplace<0>();
    }

    // Destroys the promise, releasing its promise and result (if any).
    ~future_impl() = default;

    // Returns the state of the future: empty, pending, ok, or error.
    future_state state() const {
        switch (state_.index()) {
        case 0:
            return future_state::empty;
        case 1:
            return future_state::pending;
        case 2:
            return state_.template get<2>().is_ok()
                       ? future_state::ok
                       : future_state::error;
        }
        __builtin_unreachable();
    }

    // Returns true if the future's state is not |fit::future_state::empty|:
    // it either holds a result or holds a promise that can be invoked to make
    // progress towards obtaining a result.
    explicit operator bool() const { return !is_empty(); }

    // Returns true if the future's state is |fit::future_state::empty|:
    // it does not hold a result or a promise so it cannot make progress.
    bool is_empty() const { return state() == fit::future_state::empty; }

    // Returns true if the future's state is |fit::future_state::pending|:
    // it does not hold a result yet but it does hold a promise that can be invoked
    // to make progress towards obtaining a result.
    bool is_pending() const { return state() == fit::future_state::pending; }

    // Returns true if the future's state is |fit::future_state::ok|:
    // it holds a value that can be retrieved using |value()|, |take_value()|,
    // |result()|, |take_result()|, or |take_ok_result()|.
    bool is_ok() const { return state() == fit::future_state::ok; }

    // Returns true if the future's state is |fit::future_state::error|:
    // it holds an error that can be retrieved using |error()|, |take_error()|,
    // |result()|, |take_result()|, or |take_error_result()|.
    bool is_error() const { return state() == fit::future_state::error; }

    // Returns true if the future's state is either |fit::future_state::ok| or
    // |fit::future_state::error|.
    bool is_ready() const { return state_.index() == 2; }

    // Evaluates the future and returns true if its result is ready.
    // Asserts that the future is not empty.
    //
    // If the promise completes and returns a result, the future will transition
    // to the ok or error state according to the result.  The promise itself will
    // then be destroyed since it has fulfilled its purpose.
    bool operator()(fit::context& context) {
        switch (state_.index()) {
        case 0:
            return false;
        case 1: {
            result_type result = state_.template get<1>()(context);
            if (!result)
                return false;
            state_.template emplace<2>(std::move(result));
            return true;
        }
        case 2:
            return true;
        }
        __builtin_unreachable();
    }

    // Gets a reference to the future's promise.
    // Asserts that the future's state is |fit::future_state::pending|.
    const promise_type& promise() const {
        assert(is_pending());
        return state_.template get<1>();
    }

    // Takes the future's promise, leaving it in an empty state.
    // Asserts that the future's state is |fit::future_state::pending|.
    promise_type take_promise() {
        assert(is_pending());
        auto promise = std::move(state_.template get<1>());
        state_.template emplace<0>();
        return promise;
    }

    // Gets a reference to the future's result.
    // Asserts that the future's state is |fit::future_state::ok| or
    // |fit::future_state::error|.
    result_type& result() {
        assert(is_ready());
        return state_.template get<2>();
    }
    const result_type& result() const {
        assert(is_ready());
        return state_.template get<2>();
    }

    // Takes the future's result, leaving it in an empty state.
    // Asserts that the future's state is |fit::future_state::ok| or
    // |fit::future_state::error|.
    result_type take_result() {
        assert(is_ready());
        auto result = std::move(state_.template get<2>());
        state_.template emplace<0>();
        return result;
    }

    // Gets a reference to the future's value.
    // Asserts that the future's state is |fit::future_state::ok|.
    template <typename R = value_type,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    R& value() {
        assert(is_ok());
        return state_.template get<2>().value();
    }
    template <typename R = value_type,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    const R& value() const {
        assert(is_ok());
        return state_.template get<2>().value();
    }

    // Takes the future's value, leaving it in an empty state.
    // Asserts that the future's state is |fit::future_state::ok|.
    template <typename R = value_type,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    R take_value() {
        assert(is_ok());
        auto value = state_.template get<2>().take_value();
        state_.template emplace<0>();
        return value;
    }
    ok_result<value_type> take_ok_result() {
        assert(is_ok());
        auto result = state_.template get<2>().take_ok_result();
        state_.template emplace<0>();
        return result;
    }

    // Gets a reference to the future's error.
    // Asserts that the future's state is |fit::future_state::error|.
    template <typename R = error_type,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    R& error() {
        assert(is_error());
        return state_.template get<2>().error();
    }
    template <typename R = error_type,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    const R& error() const {
        assert(is_error());
        return state_.template get<2>().error();
    }

    // Takes the future's error, leaving it in an empty state.
    // Asserts that the future's state is |fit::future_state::error|.
    template <typename R = error_type,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    R take_error() {
        assert(is_error());
        auto error = state_.template get<2>().take_error();
        state_.template emplace<0>();
        return error;
    }
    error_result<error_type> take_error_result() {
        assert(is_error());
        auto result = state_.template get<2>().take_error_result();
        state_.template emplace<0>();
        return result;
    }

    // Move assigns from another future, leaving the other one in an empty state.
    future_impl& operator=(future_impl&& other) = default;

    // Discards the future's promise and result, leaving it empty.
    future_impl& operator=(decltype(nullptr)) {
        state_.template emplace<0>();
        return *this;
    }

    // Assigns a promise to compute the future's result.
    // If the promise is empty, the future enters the empty state.
    // Otherwise the future enters the pending state.
    future_impl& operator=(promise_type promise) {
        if (promise) {
            state_.template emplace<1>(std::move(promise));
        } else {
            state_.template emplace<0>();
        }
        return *this;
    }

    // Assigns the future's result.
    // If the result is pending, the future enters the empty state.
    // Otherwise the future enters the ok or error state.
    future_impl& operator=(result_type result) {
        if (result) {
            state_.template emplace<2>(std::move(result));
        } else {
            state_.template emplace<0>();
        }
        return *this;
    }

    // Swaps the futures' contents.
    void swap(future_impl& other) {
        using std::swap;
        swap(state_, other.state_);
    }

    future_impl(const future_impl&) = delete;
    future_impl& operator=(const future_impl&) = delete;

private:
    ::fit::internal::variant<::fit::internal::monostate,
                             promise_type, result_type>
        state_;
};

template <typename Promise>
void swap(future_impl<Promise>& a, future_impl<Promise>& b) {
    a.swap(b);
}

template <typename Promise>
bool operator==(const future_impl<Promise>& f, decltype(nullptr)) {
    return !f;
}
template <typename Promise>
bool operator==(decltype(nullptr), const future_impl<Promise>& f) {
    return !f;
}
template <typename Promise>
bool operator!=(const future_impl<Promise>& f, decltype(nullptr)) {
    return !!f;
}
template <typename Promise>
bool operator!=(decltype(nullptr), const future_impl<Promise>& f) {
    return !!f;
}

// Makes a future containing the specified promise.
template <typename Promise>
future_impl<Promise> make_future(Promise promise) {
    return future_impl<Promise>(std::move(promise));
}

// A pending task holds a |fit::promise| that can be scheduled to run on
// a |fit::executor| using |fit::executor::schedule_task()|.
//
// An executor repeatedly invokes a pending task until it returns true,
// indicating completion.  Note that the promise's resulting value or error
// is discarded since it is not meaningful to the executor.  If you need
// to consume the result, use a combinator such as |fit::pending::then()|
// to capture it prior to wrapping the promise into a pending task.
//
// See documentation of |fit::promise| for more information.
class pending_task final {
public:
    // The type of promise held by this task.
    using promise_type = promise<void, void>;

    // Creates an empty pending task without a promise.
    pending_task() = default;

    // Creates a pending task that wraps an already boxed promise that returns
    // |fit::result<void, void>|.
    pending_task(promise_type promise)
        : promise_(std::move(promise)) {}

    // Creates a pending task that wraps any kind of promise, boxed or unboxed,
    // regardless of its result type and with any context that is assignable
    // from this task's context type.
    template <typename Continuation>
    pending_task(promise_impl<Continuation> promise)
        : promise_(promise ? promise.discard_result().box() : promise_type()) {}

    pending_task(pending_task&&) = default;
    pending_task& operator=(pending_task&&) = default;

    // Destroys the pending task, releasing its promise.
    ~pending_task() = default;

    // Returns true if the pending task is non-empty (has a valid promise).
    explicit operator bool() const { return !!promise_; }

    // Evaluates the pending task.
    // If the task completes (returns a non-pending result), the task reverts
    // to an empty state (because the promise it holds has reverted to an empty
    // state) and returns true.
    // It is an error to invoke this method if the pending task is empty.
    bool operator()(fit::context& context) {
        return !promise_(context).is_pending();
    }

    // Extracts the pending task's promise.
    promise_type take_promise() {
        return std::move(promise_);
    }

    pending_task(const pending_task&) = delete;
    pending_task& operator=(const pending_task&) = delete;

private:
    promise_type promise_;
};

// Execution context for an asynchronous task, such as a |fit::promise|,
// |fit::future|, or |fit::pending_task|.
//
// When a |fit::executor| executes a task, it provides the task with an
// execution context which enables the task to communicate with the
// executor and manage its own lifecycle.  Specialized executors may subclass
// |fit::context| and offer additional methods beyond those which are
// defined here, such as to provide access to platform-specific features
// supported by the executor.
//
// The context provided to a task is only valid within the scope of a single
// invocation; the task must not retain a reference to the context across
// invocations.
//
// See documentation of |fit::promise| for more information.
class context {
public:
    // Gets the executor that is running the task, never null.
    virtual class executor* executor() const = 0;

    // Obtains a handle that can be used to resume the task after it has been
    // suspended.
    //
    // Clients should call this method before returning |fit::pending()| from
    // the task.  See documentation on |fit::executor|.
    virtual suspended_task suspend_task() = 0;

    // Converts this context to a derived context type.
    template <typename Context,
              typename = std::enable_if_t<std::is_base_of<context, Context>::value>>
    Context& as() & {
        // TODO(CP-163): We should perform a run-time type check here rather
        // than blindly casting.  That's why this method exists.
        return static_cast<Context&>(*this);
    }

protected:
    virtual ~context() = default;
};

// An abstract interface for executing asynchronous tasks, such as promises,
// represented by |fit::pending_task|.
//
// EXECUTING TASKS
//
// An executor evaluates its tasks incrementally.  During each iteration
// of the executor's main loop, it invokes the next task from its ready queue.
//
// If the task returns true, then the task is deemed to have completed.
// The executor removes the tasks from its queue and destroys it since there
// it nothing left to do.
//
// If the task returns false, then the task is deemed to have voluntarily
// suspended itself pending some event that it is awaiting.  Prior to
// returning, the task should acquire at least one |fit::suspended_task|
// handle from its execution context using |fit::context::suspend_task()|
// to provide a means for the task to be resumed once it can make forward
// progress again.
//
// Once the suspended task is resumed with |fit::suspended_task::resume()|, it
// is moved back to the ready queue and it will be invoked again during a later
// iteration of the executor's loop.
//
// If all |fit::suspended_task| handles for a given task are destroyed without
// the task ever being resumed then the task is also destroyed since there
// would be no way for the task to be resumed from suspension.  We say that
// such a task has been "abandoned".
//
// The executor retains single-ownership of all active and suspended tasks.
// When the executor is destroyed, all of its remaining tasks are also
// destroyed.
//
// Please read |fit::promise| for a more detailed explanation of the
// responsibilities of tasks and executors.
//
// NOTES FOR IMPLEMENTORS
//
// This interface is designed to support a variety of different executor
// implementations.  For example, one implementation might run its tasks on
// a single thread whereas another might dispatch them on an event-driven
// message loop or use a thread pool.
//
// See also |fit::single_threaded_executor| for a concrete implementation.
class executor {
public:
    // Destroys the executor along with all of its remaining scheduled tasks
    // that have yet to complete.
    virtual ~executor() = default;

    // Schedules a task for eventual execution by the executor.
    //
    // This method is thread-safe.
    virtual void schedule_task(pending_task task) = 0;
};

// Represents a task that is awaiting resumption.
//
// This object has RAII semantics.  If the task is not resumed by at least
// one holder of its |suspended_task| handles, then it will be destroyed
// by the executor since it is no longer possible for the task to make
// progress.  The task is said have been "abandoned".
//
// See documentation of |fit::executor| for more information.
class suspended_task final {
public:
    // A handle that grants the capability to resume a suspended task.
    // Each issued ticket must be individually resolved.
    using ticket = uint64_t;

    // The resolver mechanism implements a lightweight form of reference
    // counting for tasks that have been suspended.
    //
    // When a suspended task is created in a non-empty state, it receives
    // a pointer to a resolver interface and a ticket.  The ticket is
    // a one-time-use handle that represents the task that was suspended
    // and provides a means to resume it.  The |suspended_task| class ensures
    // that every ticket is precisely accounted for.
    //
    // When |suspended_task::resume_task()| is called on an instance with
    // a valid ticket, the resolver's |resolve_ticket()| method is invoked
    // passing the ticket's value along with *true* to resume the task.  This
    // operation consumes the ticket so the |suspended_task| transitions to
    // an empty state.  The ticket and resolver cannot be used again by
    // this |suspended_task| instance.
    //
    // Similarly, when |suspended_task::reset()| is called on an instance with
    // a valid ticket or when the task goes out of scope on such an instance,
    // the resolver's |resolve_ticket()| method is invoked but this time passes
    // *false* to not resume the task.  As before, the ticket is consumed.
    //
    // Finally, when the |suspended_task| is copied, its ticket is duplicated
    // using |duplicate_ticket()| resulting in two tickets, both of which
    // must be individually resolved.
    //
    // Resuming a task that has already been resumed has no effect.
    // Conversely, a task is considered "abandoned" if all of its tickets
    // have been resolved without it ever being resumed.  See documentation
    // of |fit::promise| for more information.
    //
    // The methods of this class are safe to call from any thread, including
    // threads that may not be managed by the task's executor.
    class resolver {
    public:
        // Duplicates the provided ticket, returning a new ticket.
        // Note: The new ticket may have the same numeric value as the
        //       original ticket but should be considered a distinct instance
        //       that must be separately resolved.
        virtual ticket duplicate_ticket(ticket ticket) = 0;

        // Consumes the provided ticket, optionally resuming its associated task.
        // The provided ticket must not be used again.
        virtual void resolve_ticket(ticket ticket, bool resume_task) = 0;

    protected:
        virtual ~resolver() = default;
    };

    suspended_task()
        : resolver_(nullptr), ticket_(0) {}

    suspended_task(resolver* resolver, ticket ticket)
        : resolver_(resolver), ticket_(ticket) {}

    suspended_task(const suspended_task& other);
    suspended_task(suspended_task&& other);

    // Releases the task without resumption.
    //
    // Does nothing if this object does not hold a ticket.
    ~suspended_task();

    // Returns true if this object holds a ticket for a suspended task.
    explicit operator bool() const { return resolver_ != nullptr; }

    // Asks the task's executor to resume execution of the suspended task
    // if it has not already been resumed or completed.  Also releases
    // the task's ticket as a side-effect.
    //
    // Clients should call this method when it is possible for the task to
    // make progress; for example, because some event the task was
    // awaiting has occurred.  See documentation on |fit::executor|.
    //
    // Does nothing if this object does not hold a ticket.
    void resume_task() { resolve(true); }

    // Releases the suspended task without resumption.
    //
    // Does nothing if this object does not hold a ticket.
    void reset() { resolve(false); }

    suspended_task& operator=(const suspended_task& other);
    suspended_task& operator=(suspended_task&& other);

private:
    void resolve(bool resume_task);

    resolver* resolver_;
    ticket ticket_;
};

} // namespace fit

#endif // LIB_FIT_PROMISE_H_


<|start_filename|>arch/x64/sysroot/include/netinet/igmp.h<|end_filename|>
#pragma once

#include <netinet/in.h>
#include <stdint.h>

struct igmp {
    uint8_t igmp_type;
    uint8_t igmp_code;
    uint16_t igmp_cksum;
    struct in_addr igmp_group;
};

#define IGMP_MINLEN 8

#define IGMP_MEMBERSHIP_QUERY 0x11
#define IGMP_V1_MEMBERSHIP_REPORT 0x12
#define IGMP_V2_MEMBERSHIP_REPORT 0x16
#define IGMP_V2_LEAVE_GROUP 0x17

#define IGMP_DVMRP 0x13
#define IGMP_PIM 0x14
#define IGMP_TRACE 0x15

#define IGMP_MTRACE_RESP 0x1e
#define IGMP_MTRACE 0x1f

#define IGMP_MAX_HOST_REPORT_DELAY 10
#define IGMP_TIMER_SCALE 10

#define IGMP_DELAYING_MEMBER 1
#define IGMP_IDLE_MEMBER 2
#define IGMP_LAZY_MEMBER 3
#define IGMP_SLEEPING_MEMBER 4
#define IGMP_AWAKENING_MEMBER 5

#define IGMP_v1_ROUTER 1
#define IGMP_v2_ROUTER 2

#define IGMP_HOST_MEMBERSHIP_QUERY IGMP_MEMBERSHIP_QUERY
#define IGMP_HOST_MEMBERSHIP_REPORT IGMP_V1_MEMBERSHIP_REPORT
#define IGMP_HOST_NEW_MEMBERSHIP_REPORT IGMP_V2_MEMBERSHIP_REPORT
#define IGMP_HOST_LEAVE_MESSAGE IGMP_V2_LEAVE_GROUP


<|start_filename|>pkg/fidl/encoding.cpp<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <lib/fidl/coding.h>

#include <stdalign.h>
#include <stdint.h>
#include <stdlib.h>

#include <lib/fidl/internal.h>
#include <zircon/assert.h>
#include <zircon/compiler.h>

#ifdef __Fuchsia__
#include <zircon/syscalls.h>
#endif

#include "buffer_walker.h"

#include <stdio.h>

// TODO(kulakowski) Design zx_status_t error values.

namespace {

class FidlEncoder final : public fidl::internal::BufferWalker<FidlEncoder, true, true> {
    typedef fidl::internal::BufferWalker<FidlEncoder, true, true> Super;

public:
    FidlEncoder(const fidl_type_t* type, void* bytes, uint32_t num_bytes, zx_handle_t* handles,
                uint32_t num_handles, uint32_t* out_actual_handles, const char** out_error_msg)
        : Super(type), bytes_(static_cast<uint8_t*>(bytes)), num_bytes_(num_bytes),
          handles_(handles), num_handles_(num_handles), out_actual_handles_(out_actual_handles),
          out_error_msg_(out_error_msg) {}

    void Walk() {
        if (handles_ == nullptr && num_handles_ != 0u) {
            SetError("Cannot provide non-zero handle count and null handle pointer");
            return;
        }
        if (out_actual_handles_ == nullptr) {
            SetError("Cannot encode with null out_actual_handles");
            return;
        }
        Super::Walk();
        if (status_ == ZX_OK) {
            *out_actual_handles_ = handle_idx();
        }
    }

    uint8_t* bytes() const { return bytes_; }
    uint32_t num_bytes() const { return num_bytes_; }
    uint32_t num_handles() const { return num_handles_; }

    bool ValidateOutOfLineStorageClaim(const void* a, const void* b) {
        return a == b;
    }

    void UnclaimedHandle(zx_handle_t* out_handle) {
#ifdef __Fuchsia__
        // Return value intentionally ignored: this is best-effort cleanup.
        zx_handle_close(*out_handle);
#endif
    }
    void ClaimedHandle(zx_handle_t* out_handle, uint32_t idx) {
        assert(out_handle != nullptr);
        handles_[idx] = *out_handle;
        *out_handle = FIDL_HANDLE_PRESENT;
    }

    PointerState GetPointerState(const void* ptr) const {
        return *static_cast<const uintptr_t*>(ptr) == 0
                   ? PointerState::ABSENT
                   : PointerState::PRESENT;
    }
    HandleState GetHandleState(zx_handle_t p) const {
        return p == ZX_HANDLE_INVALID
                   ? HandleState::ABSENT
                   : HandleState::PRESENT;
    }

    template <class T>
    void UpdatePointer(T** p, T* v) {
        assert(*p == v);
        assert(v != nullptr);
        *p = reinterpret_cast<T*>(FIDL_ALLOC_PRESENT);
    }

    void SetError(const char* error_msg) {
        if (status_ != ZX_OK) {
            return;
        }
        status_ = ZX_ERR_INVALID_ARGS;
        if (out_error_msg_ != nullptr) {
            *out_error_msg_ = error_msg;
        }
#ifdef __Fuchsia__
        if (handles_) {
            // Return value intentionally ignored: this is best-effort cleanup.
            zx_handle_close_many(handles_, num_handles());
        }
#endif
    }

    zx_status_t status() const { return status_; }

private:
    // Message state passed in to the constructor.
    uint8_t* const bytes_;
    const uint32_t num_bytes_;
    zx_handle_t* const handles_;
    const uint32_t num_handles_;
    uint32_t* const out_actual_handles_;
    const char** const out_error_msg_;
    zx_status_t status_ = ZX_OK;
};

} // namespace

zx_status_t fidl_encode(const fidl_type_t* type, void* bytes, uint32_t num_bytes,
                        zx_handle_t* handles, uint32_t max_handles, uint32_t* out_actual_handles,
                        const char** out_error_msg) {
    FidlEncoder encoder(type, bytes, num_bytes, handles, max_handles, out_actual_handles,
                        out_error_msg);
    encoder.Walk();
    return encoder.status();
}

zx_status_t fidl_encode_msg(const fidl_type_t* type, fidl_msg_t* msg,
                            uint32_t* out_actual_handles, const char** out_error_msg) {
    return fidl_encode(type, msg->bytes, msg->num_bytes, msg->handles, msg->num_handles,
                       out_actual_handles, out_error_msg);
}


<|start_filename|>arch/x64/sysroot/include/stdlib.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>
#include <bits/null.h>

#define __NEED_size_t
#define __NEED_wchar_t

#include <bits/alltypes.h>

int atoi(const char*);
long atol(const char*);
long long atoll(const char*);
double atof(const char*);

float strtof(const char* __restrict, char** __restrict);
double strtod(const char* __restrict, char** __restrict);
long double strtold(const char* __restrict, char** __restrict);

long strtol(const char* __restrict, char** __restrict, int);
unsigned long strtoul(const char* __restrict, char** __restrict, int);
long long strtoll(const char* __restrict, char** __restrict, int);
unsigned long long strtoull(const char* __restrict, char** __restrict, int);

int rand(void);
void srand(unsigned);

void* malloc(size_t);
void* calloc(size_t, size_t);
void* realloc(void*, size_t);
void free(void*);
void* aligned_alloc(size_t alignment, size_t size);

_Noreturn void abort(void);
int atexit(void (*)(void));
_Noreturn void exit(int);
_Noreturn void _Exit(int);
int at_quick_exit(void (*)(void));
_Noreturn void quick_exit(int);

char* getenv(const char*);

int system(const char*);

void* bsearch(const void*, const void*, size_t, size_t, int (*)(const void*, const void*));
void qsort(void*, size_t, size_t, int (*)(const void*, const void*));

int abs(int);
long labs(long);
long long llabs(long long);

typedef struct { int quot, rem; } div_t;
typedef struct { long quot, rem; } ldiv_t;
typedef struct { long long quot, rem; } lldiv_t;

div_t div(int, int);
ldiv_t ldiv(long, long);
lldiv_t lldiv(long long, long long);

int mblen(const char*, size_t);
int mbtowc(wchar_t* __restrict, const char* __restrict, size_t);
int wctomb(char*, wchar_t);
size_t mbstowcs(wchar_t* __restrict, const char* __restrict, size_t);
size_t wcstombs(char* __restrict, const wchar_t* __restrict, size_t);

#define EXIT_FAILURE 1
#define EXIT_SUCCESS 0

size_t __ctype_get_mb_cur_max(void);
#define MB_CUR_MAX (__ctype_get_mb_cur_max())

#define RAND_MAX (0x7fffffff)

#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
    defined(_GNU_SOURCE) || defined(_BSD_SOURCE)

#define WNOHANG 1
#define WUNTRACED 2

#define WEXITSTATUS(s) (((s)&0xff00) >> 8)
#define WTERMSIG(s) ((s)&0x7f)
#define WSTOPSIG(s) WEXITSTATUS(s)
#define WIFEXITED(s) (!WTERMSIG(s))
#define WIFSTOPPED(s) ((short)((((s)&0xffff) * 0x10001) >> 8) > 0x7f00)
#define WIFSIGNALED(s) (((s)&0xffff) - 1U < 0xffu)

int posix_memalign(void**, size_t, size_t);
int setenv(const char*, const char*, int);
int unsetenv(const char*);
int mkstemp(char*);
int mkostemp(char*, int);
char* mkdtemp(char*);
int getsubopt(char**, char* const*, char**);
int rand_r(unsigned*);

#endif

#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
char* realpath(const char* __restrict, char* __restrict);
long int random(void);
void srandom(unsigned int);
char* initstate(unsigned int, char*, size_t);
char* setstate(char*);
int putenv(char*);
int posix_openpt(int);
int grantpt(int);
int unlockpt(int);
char* ptsname(int);
char* l64a(long);
long a64l(const char*);
void setkey(const char*);
double drand48(void);
double erand48(unsigned short[3]);
long int lrand48(void);
long int nrand48(unsigned short[3]);
long mrand48(void);
long jrand48(unsigned short[3]);
void srand48(long);
unsigned short* seed48(unsigned short[3]);
void lcong48(unsigned short[7]);
#endif

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#include <alloca.h>
char* mktemp(char*);
int mkstemps(char*, int);
int mkostemps(char*, int, int);
void* valloc(size_t);
void* memalign(size_t, size_t);
int clearenv(void);
#define WCOREDUMP(s) ((s)&0x80)
#define WIFCONTINUED(s) ((s) == 0xffff)
#endif

#ifdef _GNU_SOURCE
int ptsname_r(int, char*, size_t);
char* ecvt(double, int, int*, int*);
char* fcvt(double, int, int*, int*);
char* gcvt(double, int, char*);
#endif

#ifdef __cplusplus
}
#endif


<|start_filename|>arch/x64/sysroot/include/termios.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>

#define __NEED_pid_t

#include <bits/alltypes.h>

typedef unsigned char cc_t;
typedef unsigned int speed_t;
typedef unsigned int tcflag_t;

#define NCCS 32

#include <bits/termios.h>

speed_t cfgetospeed(const struct termios*);
speed_t cfgetispeed(const struct termios*);
int cfsetospeed(struct termios*, speed_t);
int cfsetispeed(struct termios*, speed_t);

int tcgetattr(int, struct termios*);
int tcsetattr(int, int, const struct termios*);

int tcsendbreak(int, int);
int tcdrain(int);
int tcflush(int, int);
int tcflow(int, int);

pid_t tcgetsid(int);

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
void cfmakeraw(struct termios*);
int cfsetspeed(struct termios*, speed_t);
#endif

#ifdef __cplusplus
}
#endif


<|start_filename|>arch/x64/sysroot/include/ftw.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>
#include <sys/stat.h>

#define FTW_F 1
#define FTW_D 2
#define FTW_DNR 3
#define FTW_NS 4
#define FTW_SL 5
#define FTW_DP 6
#define FTW_SLN 7

#define FTW_PHYS 1
#define FTW_MOUNT 2
#define FTW_CHDIR 4
#define FTW_DEPTH 8

struct FTW {
    int base;
    int level;
};

int ftw(const char*, int (*)(const char*, const struct stat*, int), int);
int nftw(const char*, int (*)(const char*, const struct stat*, int, struct FTW*), int, int);

#ifdef __cplusplus
}
#endif


<|start_filename|>arch/x64/sysroot/include/zircon/device/ramdisk.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

#include <limits.h>
#include <zircon/boot/image.h>
#include <zircon/device/ioctl.h>
#include <zircon/device/ioctl-wrapper.h>
#include <zircon/types.h>

#define IOCTL_RAMDISK_CONFIG \
    IOCTL(IOCTL_KIND_DEFAULT, IOCTL_FAMILY_RAMDISK, 1)
#define IOCTL_RAMDISK_CONFIG_VMO \
    IOCTL(IOCTL_KIND_SET_HANDLE, IOCTL_FAMILY_RAMDISK, 4)
#define IOCTL_RAMDISK_UNLINK \
    IOCTL(IOCTL_KIND_DEFAULT, IOCTL_FAMILY_RAMDISK, 2)
#define IOCTL_RAMDISK_SET_FLAGS \
    IOCTL(IOCTL_KIND_DEFAULT, IOCTL_FAMILY_RAMDISK, 3)
#define IOCTL_RAMDISK_WAKE_UP \
    IOCTL(IOCTL_KIND_DEFAULT, IOCTL_FAMILY_RAMDISK, 4)
#define IOCTL_RAMDISK_SLEEP_AFTER \
    IOCTL(IOCTL_KIND_DEFAULT, IOCTL_FAMILY_RAMDISK, 5)
#define IOCTL_RAMDISK_GET_BLK_COUNTS \
    IOCTL(IOCTL_KIND_DEFAULT, IOCTL_FAMILY_RAMDISK, 6)

// Ramdisk-specific flags
#define RAMDISK_FLAG_RESUME_ON_WAKE 0xFF000001

typedef struct ramdisk_ioctl_config {
    uint64_t blk_size;
    uint64_t blk_count;
    uint8_t type_guid[ZBI_PARTITION_GUID_LEN];
} ramdisk_ioctl_config_t;

typedef struct ramdisk_ioctl_config_response {
    char name[NAME_MAX + 1];
} ramdisk_ioctl_config_response_t;

typedef struct ramdisk_blk_counts {
    uint64_t received;
    uint64_t successful;
    uint64_t failed;
} ramdisk_blk_counts_t;

// ssize_t ioctl_ramdisk_config(int fd, const ramdisk_ioctl_config_t* in,
//                              ramdisk_ioctl_config_response_t* out);
IOCTL_WRAPPER_INOUT(ioctl_ramdisk_config, IOCTL_RAMDISK_CONFIG, ramdisk_ioctl_config_t,
                    ramdisk_ioctl_config_response_t);

// ssize_t ioctl_ramdisk_config_vmo(int fd, const zx_handle_t* in,
//                                  ramdisk_ioctl_config_response_t* out);
IOCTL_WRAPPER_INOUT(ioctl_ramdisk_config_vmo, IOCTL_RAMDISK_CONFIG_VMO,
                    zx_handle_t, ramdisk_ioctl_config_response_t);

// ssize_t ioctl_ramdisk_unlink(int fd);
IOCTL_WRAPPER(ioctl_ramdisk_unlink, IOCTL_RAMDISK_UNLINK);

// ssize_t ioctl_ramdisk_set_flags(int fd, uint32_t* in);
// The flags to set match block_info_t.flags. This is intended to simulate the behavior
// of other block devices, so it should be used only for tests.
IOCTL_WRAPPER_IN(ioctl_ramdisk_set_flags, IOCTL_RAMDISK_SET_FLAGS, uint32_t);

// ssize_t ioctl_ramdisk_wake_up(int fd);
// "Wakes" the ramdisk, if it was sleeping.
// Transactions are no longer expected to fail after this point, and the ramdisk will not sleep
// again until the next call to SLEEP_AFTER.
// This will reset the current transaction count.
IOCTL_WRAPPER(ioctl_ramdisk_wake_up, IOCTL_RAMDISK_WAKE_UP);

// ssize_t ioctl_ramdisk_sleep_after(int fd, uint64_t* in);
// Tell the ramdisk to "sleep" after |in| blocks have been written successfully.
// After this point, all incoming transactions will fail.
// This will reset the current block count.
// NOTE! Use caution with RAMDISK_FLAG_RESUME_ON_WAKE set; sleeping with this flags will cause I/O
// to block indefinitely until another call invokes |ioctl_ramdisk_wake_up|.
IOCTL_WRAPPER_IN(ioctl_ramdisk_sleep_after, IOCTL_RAMDISK_SLEEP_AFTER, uint64_t);

// ssize_t ioctl_ramdisk_get_blk_counts(int fd, ramdisk_blk_counts_t* out);
// Retrieve the number of received, successful, and failed block writes since the last call to
// sleep/wake.
IOCTL_WRAPPER_OUT(ioctl_ramdisk_get_blk_counts, IOCTL_RAMDISK_GET_BLK_COUNTS, ramdisk_blk_counts_t);


<|start_filename|>pkg/fidl/include/lib/fidl/llcpp/traits.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIDL_LLCPP_TRAITS_H_
#define LIB_FIDL_LLCPP_TRAITS_H_

#include <lib/zx/object.h>
#include <stdint.h>
#include <type_traits>
#include <zircon/fidl.h>

// Defines type traits used in the low-level C++ binding.
//
// The contracts of a FIDL type |T| are as follows:
//
// |IsFidlType<T>| resolves to std::true_type.
// |IsFidlMessage<T>| resolves to std::true_type iff |T| is a transactional message.
// |T::MaxNumHandles| is an uint32_t specifying the upper bound on the number of contained handles.
// |T::MaxSize| is an uint32_t specifying the upper bound on the message byte size.
//              It is std::numeric_limits<uint32_t>::max() if |T| is unbounded.
// |T::type| is a fidl_type_t* pointing to the corresponding encoding table, if any.
//

namespace fidl {

// A type trait that indicates whether the given type is a request/response type
// i.e. has a FIDL message header.
template <typename T> struct IsFidlMessage : public std::false_type {};

// Code-gen will explicitly conform the generated FIDL transactional messages to IsFidlMessage.

// A type trait that indicates whether the given type is allowed to appear in
// generated binding APIs and can be encoded/decoded.
// As a start, all handle types are supported.
template <typename T> struct IsFidlType :
    public std::is_base_of<zx::object_base, T> {};

// clang-format off
// Specialize for primitives
template <> struct IsFidlType<bool> : public std::true_type {};
template <> struct IsFidlType<uint8_t> : public std::true_type {};
template <> struct IsFidlType<uint16_t> : public std::true_type {};
template <> struct IsFidlType<uint32_t> : public std::true_type {};
template <> struct IsFidlType<uint64_t> : public std::true_type {};
template <> struct IsFidlType<int8_t> : public std::true_type {};
template <> struct IsFidlType<int16_t> : public std::true_type {};
template <> struct IsFidlType<int32_t> : public std::true_type {};
template <> struct IsFidlType<int64_t> : public std::true_type {};
template <> struct IsFidlType<float> : public std::true_type {};
template <> struct IsFidlType<double> : public std::true_type {};
// clang-format on

// String
class StringView;
template <> struct IsFidlType<StringView> : public std::true_type {};

// Vector (conditional on element)
template <typename E> class VectorView;
template <typename E>
struct IsFidlType<VectorView<E>> : public IsFidlType<E> {};

// Code-gen will explicitly conform the generated FIDL structures to IsFidlType.

}  // namespace fidl

#endif // LIB_FIDL_LLCPP_TRAITS_H_


<|start_filename|>dart/fidl/lib/src/enum.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

abstract class Enum {
  const Enum();

  int get value;
}

typedef EnumFactory<T> = T Function(int value);


<|start_filename|>pkg/fit/include/lib/fit/result.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIT_RESULT_H_
#define LIB_FIT_RESULT_H_

#include <assert.h>

#include <new>
#include <type_traits>
#include <utility>

#include "traits.h"
#include "variant.h"

namespace fit {

// Represents the intermediate state of a result that has not yet completed.
struct pending_result final {};

// Returns an value that represents a pending result.
constexpr inline pending_result pending() {
    return pending_result{};
}

// Represents the result of a successful task.
template <typename V = void>
struct ok_result final {
    using value_type = V;

    explicit constexpr ok_result(V value)
        : value(std::move(value)) {}

    V value;
};
template <>
struct ok_result<void> {
    using value_type = void;
};

// Wraps the result of a successful task as an |ok_result<T>|.
template <typename V>
constexpr inline ok_result<V> ok(V value) {
    return ok_result<V>(std::move(value));
}
constexpr inline ok_result<> ok() {
    return ok_result<>{};
}

// Represents the result of a failed task.
template <typename E = void>
struct error_result final {
    using error_type = E;

    explicit constexpr error_result(E error)
        : error(std::move(error)) {}

    E error;
};
template <>
struct error_result<void> {
    using error_type = void;
};

// Wraps the result of a failed task as an |error_result<T>|.
template <typename E>
constexpr inline error_result<E> error(E error) {
    return error_result<E>(std::move(error));
}
constexpr inline error_result<> error() {
    return error_result<>{};
}

// Describes the status of a task's result.
enum class result_state {
    // The task is still in progress.
    pending,
    // The task completed successfully.
    ok,
    // The task failed.
    error
};

// Represents the result of a task which may have succeeded, failed,
// or still be in progress.
//
// Use |fit::pending()|, |fit::ok<T>()|, or |fit::error<T>| to initialize
// the result.
//
// |V| is the type of value produced when the completes successfully.
// Defaults to |void|.
//
// |E| is the type of error produced when the completes with an error.
// Defaults to |void|.
//
// EXAMPLE:
//
// fit::result<int, std::string> divide(int dividend, int divisor) {
//     if (divisor == 0)
//         return fit::error<std::string>("divide by zero");
//     return fit::ok(dividend / divisor);
// }
//
// int try_divide(int dividend, int divisor) {
//     auto result = divide(dividend, divisor);
//     if (result.is_ok()) {
//         printf("%d / %d = %d\n", dividend, divisor, result.value());
//         return result.value();
//     }
//     printf("%d / %d: ERROR %s\n", dividend, divisor, result.error().c_str());
//     return -999;
// }
//
// EXAMPLE WITH VOID RESULT VALUE AND ERROR:
//
// fit::result<> open(std::string secret) {
//     printf("guessing \"%s\"\n", secret.c_str());
//     if (secret == "sesame") {
//         return fit::ok();
//         puts("yes!");
//     }
//     puts("no.");
//     return fit::error();
// }
//
// bool guess_combination() {
//     return open("friend") || open("sesame") || open("I give up");
// }
template <typename V = void, typename E = void>
class result final {
public:
    using value_type = V;
    using error_type = E;

    // Creates a pending result.
    constexpr result() = default;
    constexpr result(pending_result) {}

    // Creates an ok result.
    constexpr result(ok_result<V> result)
        : state_(::fit::internal::in_place_index<1>, std::move(result)) {}
    template <typename OtherV,
              typename = std::enable_if_t<std::is_constructible<V, OtherV>::value>>
    constexpr result(ok_result<OtherV> other)
        : state_(::fit::internal::in_place_index<1>,
                 fit::ok<V>(std::move(other.value))) {}

    // Creates an error result.
    constexpr result(error_result<E> result)
        : state_(::fit::internal::in_place_index<2>, std::move(result)) {}
    template <typename OtherE,
              typename = std::enable_if_t<std::is_constructible<E, OtherE>::value>>
    constexpr result(error_result<OtherE> other)
        : state_(::fit::internal::in_place_index<2>,
                 fit::error<E>(std::move(other.error))) {}

    // Copies another result (if copyable).
    result(const result& other) = default;

    // Moves from another result, leaving the other one in a pending state.
    result(result&& other)
        : state_(std::move(other.state_)) {
        other.reset();
    }

    ~result() = default;

    // Returns the state of the task's result: pending, ok, or error.
    constexpr result_state state() const {
        return static_cast<result_state>(state_.index());
    }

    // Returns true if the result is not pending.
    constexpr explicit operator bool() const {
        return !is_pending();
    }

    // Returns true if the task is still in progress.
    constexpr bool is_pending() const {
        return state() == result_state::pending;
    }

    // Returns true if the task succeeded.
    constexpr bool is_ok() const {
        return state() == result_state::ok;
    }

    // Returns true if the task failed.
    constexpr bool is_error() const {
        return state() == result_state::error;
    }

    // Gets the result's value.
    // Asserts that the result's state is |fit::result_state::ok|.
    template <typename R = V,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    constexpr R& value() {
        return state_.template get<1>().value;
    }
    template <typename R = V,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    constexpr const R& value() const {
        return state_.template get<1>().value;
    }

    // Takes the result's value, leaving it in a pending state.
    // Asserts that the result's state is |fit::result_state::ok|.
    template <typename R = V,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    R take_value() {
        auto value = std::move(state_.template get<1>().value);
        reset();
        return value;
    }
    ok_result<V> take_ok_result() {
        auto result = std::move(state_.template get<1>());
        reset();
        return result;
    }

    // Gets a reference to the result's error.
    // Asserts that the result's state is |fit::result_state::error|.
    template <typename R = E,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    constexpr R& error() {
        return state_.template get<2>().error;
    }
    template <typename R = E,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    constexpr const R& error() const {
        return state_.template get<2>().error;
    }

    // Takes the result's error, leaving it in a pending state.
    // Asserts that the result's state is |fit::result_state::error|.
    template <typename R = E,
              typename = std::enable_if_t<!std::is_void<R>::value>>
    R take_error() {
        auto error = std::move(state_.template get<2>().error);
        reset();
        return error;
    }
    error_result<E> take_error_result() {
        auto result = std::move(state_.template get<2>());
        reset();
        return result;
    }

    // Assigns from another result (if copyable).
    result& operator=(const result& other) = default;

    // Moves from another result, leaving the other one in a pending state.
    result& operator=(result&& other) {
        state_ = std::move(other.state_);
        other.reset();
        return *this;
    }

private:
    void reset() { state_.template emplace<0>(); }

    ::fit::internal::variant<
        ::fit::internal::monostate, ok_result<V>, error_result<E>>
        state_;
};

} // namespace fit

#endif // LIB_FIT_RESULT_H_


<|start_filename|>arch/x64/sysroot/include/zircon/syscalls/debug.h<|end_filename|>
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef ZIRCON_SYSCALLS_DEBUG_
#define ZIRCON_SYSCALLS_DEBUG_

#include <stdint.h>
#include <zircon/compiler.h>

__BEGIN_CDECLS

#if defined(__x86_64__)

// Value for ZX_THREAD_STATE_GENERAL_REGS on x86-64 platforms.
typedef struct zx_thread_state_general_regs {
    uint64_t rax;
    uint64_t rbx;
    uint64_t rcx;
    uint64_t rdx;
    uint64_t rsi;
    uint64_t rdi;
    uint64_t rbp;
    uint64_t rsp;
    uint64_t r8;
    uint64_t r9;
    uint64_t r10;
    uint64_t r11;
    uint64_t r12;
    uint64_t r13;
    uint64_t r14;
    uint64_t r15;
    uint64_t rip;
    uint64_t rflags;
} zx_thread_state_general_regs_t;

// Value for ZX_THREAD_STATE_FP_REGS on x64. Holds x87 and MMX state.
typedef struct zx_thread_state_fp_regs {
    uint16_t fcw; // Control word.
    uint16_t fsw; // Status word.
    uint8_t ftw;  // Tag word.
    uint8_t reserved;
    uint16_t fop; // Opcode.
    uint64_t fip; // Instruction pointer.
    uint64_t fdp; // Data pointer.

    // The x87/MMX state. For x87 the each "st" entry has the low 80 bits used for the register
    // contents. For MMX, the low 64 bits are used. The higher bits are unused.
    __ALIGNED(16)
    struct {
        uint64_t low;
        uint64_t high;
    } st[8];
} zx_thread_state_fp_regs_t;

// Value for ZX_THREAD_STATE_VECTOR_REGS on x64. Holds SSE and AVX registers.
//
// Setting vector registers will only work for threads that have previously executed an
// instruction using the corresponding register class.
typedef struct zx_thread_state_vector_regs {
    // When only 16 registers are supported (pre-AVX-512), zmm[16-31] will be 0.
    // YMM registers (256 bits) are v[0-4], XMM registers (128 bits) are v[0-2].
    struct {
        uint64_t v[8];
    } zmm[32];

    // AVX-512 opmask registers. Will be 0 unless AVX-512 is supported.
    uint64_t opmask[8];

    // SIMD control and status register.
    uint32_t mxcsr;
} zx_thread_state_vector_regs_t;

// Value for ZX_THREAD_STATE_DEBUG_REGS on x64 platforms.
typedef struct zx_thread_state_debug_regs {
  uint64_t dr[4];
  // DR4 and D5 are not used.
  uint64_t dr6;         // Status register.
  uint64_t dr7;         // Control register.
  // TODO(donosoc): These values are deprecated but are still used by zxdb. We debine both values
  //                in order to do a soft transition. Delete these values once zxdb has made the
  //                update.
  uint64_t dr6_status;  // Status register.
  uint64_t dr7_control; // Control register.
} zx_thread_state_debug_regs_t;

#elif defined(__aarch64__)

// Value for ZX_THREAD_STATE_GENERAL_REGS on ARM64 platforms.
typedef struct zx_thread_state_general_regs {
    uint64_t r[30];
    uint64_t lr;
    uint64_t sp;
    uint64_t pc;
    uint64_t cpsr;
} zx_thread_state_general_regs_t;

// Value for ZX_THREAD_STATE_FP_REGS on ARM64 platforms.
// This is unused because vector state is used for all floating point on ARM64.
typedef struct zx_thread_state_fp_regs {
    // Avoids sizing differences for empty structs between C and C++.
    uint32_t unused;
} zx_thread_state_fp_regs_t;

// Value for ZX_THREAD_STATE_VECTOR_REGS on ARM64 platforms.
typedef struct zx_thread_state_vector_regs {
    uint32_t fpcr;
    uint32_t fpsr;
    struct {
        uint64_t low;
        uint64_t high;
    } v[32];
} zx_thread_state_vector_regs_t;

// ARMv8-A provides 2 to 16 hardware breakpoint registers.
// The number is obtained by the BRPs field in the EDDFR register.
#define AARCH64_MAX_HW_BREAKPOINTS 16
// ARMv8-A provides 2 to 16 watchpoint breakpoint registers.
// The number is obtained by the WRPs field in the EDDFR register.
#define AARCH64_MAX_HW_WATCHPOINTS 16

// Value for XZ_THREAD_STATE_DEBUG_REGS for ARM64 platforms.
typedef struct zx_thread_state_debug_regs {
  struct {
    uint64_t dbgbvr;      //  HW Breakpoint Value register.
    uint32_t dbgbcr;      //  HW Breakpoint Control register.
  } hw_bps[AARCH64_MAX_HW_BREAKPOINTS];
  // Number of HW Breakpoints in the platform.
  // Will be set on read and ignored on write.
  uint8_t hw_bps_count;
  struct {
    uint64_t dbgwvr;      // HW Watchpoint Value register.
    uint32_t dbgwcr;      // HW Watchpoint Control register.
  } hw_wps[AARCH64_MAX_HW_WATCHPOINTS];
  // Number of HW Watchpoints in the platform.
  // Will be set on read and ignored on write.
  uint8_t hw_wps_count;
} zx_thread_state_debug_regs_t;

#endif

// Value for ZX_THREAD_STATE_SINGLE_STEP. The value can be 0 (not single-stepping), or 1
// (single-stepping). Other values will give ZX_ERR_INVALID_ARGS.
typedef uint32_t zx_thread_state_single_step_t;

// Values for ZX_THREAD_X86_REGISTER_FS and ZX_THREAD_X86_REGISTER_GS;
typedef uint64_t zx_thread_x86_register_fs_t;
typedef uint64_t zx_thread_x86_register_gs_t;

// Possible values for "kind" in zx_thread_read_state and zx_thread_write_state.
typedef uint32_t zx_thread_state_topic_t;
#define ZX_THREAD_STATE_GENERAL_REGS  ((uint32_t)0) // zx_thread_state_general_regs_t value.
#define ZX_THREAD_STATE_FP_REGS       ((uint32_t)1) // zx_thread_state_fp_regs_t value.
#define ZX_THREAD_STATE_VECTOR_REGS   ((uint32_t)2) // zx_thread_state_vector_regs_t value.
#define ZX_THREAD_STATE_DEBUG_REGS    ((uint32_t)4) // zx_thread_state_debug_regs_t value.
#define ZX_THREAD_STATE_SINGLE_STEP   ((uint32_t)5) // zx_thread_state_single_step_t value.
#define ZX_THREAD_X86_REGISTER_FS     ((uint32_t)6) // zx_thread_x86_register_fs_t value.
#define ZX_THREAD_X86_REGISTER_GS     ((uint32_t)7) // zx_thread_x86_register_gs_t value.

__END_CDECLS

#endif // ZIRCON_SYSCALLS_DEBUG_


<|start_filename|>pkg/fidl/buffer_walker.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

namespace fidl {
namespace internal {

// Some assumptions about data type layout.
static_assert(offsetof(fidl_string_t, size) == 0u, "");
static_assert(offsetof(fidl_string_t, data) == 8u, "");

static_assert(offsetof(fidl_vector_t, count) == 0u, "");
static_assert(offsetof(fidl_vector_t, data) == 8u, "");

static_assert(ZX_HANDLE_INVALID == FIDL_HANDLE_ABSENT, "");

template <bool kConst, class U>
struct SetPtrConst;

template <class U>
struct SetPtrConst<false, U> {
    typedef U* type;
};

template <class U>
struct SetPtrConst<true, U> {
    typedef const U* type;
};

// Walks over a FIDL buffer and validates/encodes/decodes it per-Derived.
//
// kMutating controls whether this deals with mutable bytes or immutable bytes
// (validation wants immutable, encode/decode wants mutable)
//
// kContinueAfterErrors controls whether parsing is continued upon failure (encode needs this to
// see all available handles).
//
// Derived should offer the following methods:
//
//   const? uint8_t* bytes() - returns the start of the buffer of bytes
//   uint32_t num_bytes() - returns the number of bytes in said buffer
//   uint32_t num_handles() - returns the number of handles that are claimable
//   bool ValidateOutOfLineStorageClaim(const void* a, const void* b)
//      - returns true if a legally points to b
//   void UnclaimedHandle(zx_handle_t*) - notes that a handle was skipped
//   void ClaimedHandle(zx_handle_t*, uint32_t idx) - notes that a handle was claimed
//   PointerState GetPointerState(const void* ptr) - returns whether a pointer is present or not
//   HandleState GetHandleState(zx_handle_t) - returns if a handle is present or not
//   void UpdatePointer(T**p, T*v) - mutates a pointer representation for a present pointer
//   void SetError(const char* error_msg) - flags that an error occurred
template <class Derived, bool kMutating, bool kContinueAfterErrors>
class BufferWalker {
public:
    explicit BufferWalker(const fidl_type* type)
        : type_(type) {}

    void Walk() {
        // The first decode is special. It must be a struct or a table.
        // We need to know the size of the first element to compute the start of
        // the out-of-line allocations.

        if (type_ == nullptr) {
            SetError("Cannot decode a null fidl type");
            return;
        }

        if (bytes() == nullptr) {
            SetError("Cannot decode null bytes");
            return;
        }

        switch (type_->type_tag) {
        case fidl::kFidlTypeStruct:
            if (num_bytes() < type_->coded_struct.size) {
                SetError("Message size is smaller than expected");
                return;
            }
            out_of_line_offset_ = static_cast<uint32_t>(fidl::FidlAlign(type_->coded_struct.size));
            break;
        case fidl::kFidlTypeTable:
            if (num_bytes() < sizeof(fidl_vector_t)) {
                SetError("Message size is smaller than expected");
                return;
            }
            out_of_line_offset_ = static_cast<uint32_t>(fidl::FidlAlign(sizeof(fidl_vector_t)));
            break;
        default:
            SetError("Message must be a struct or a table");
            return;
        }

        Push(Frame::DoneSentinel());
        Push(Frame(type_, 0u));

// Macro to insert the relevant goop required to support two control flows here:
// one where we keep reading after error, and another where we return immediately.
// No runtime overhead thanks to if constexpr magic.
#define FIDL_POP_AND_CONTINUE_OR_RETURN \
    if (kContinueAfterErrors) {         \
        Pop();                          \
        continue;                       \
    } else {                            \
        return;                         \
    }

        for (;;) {
            Frame* frame = Peek();

            switch (frame->state) {
            case Frame::kStateStruct: {
                const uint32_t field_index = frame->NextStructField();
                if (field_index == frame->struct_state.field_count) {
                    Pop();
                    continue;
                }
                const fidl::FidlField& field = frame->struct_state.fields[field_index];
                const fidl_type_t* field_type = field.type;
                const uint32_t field_offset = frame->offset + field.offset;
                if (!Push(Frame(field_type, field_offset))) {
                    SetError("recursion depth exceeded processing struct");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                continue;
            }
            case Frame::kStateStructPointer: {
                switch (GetPointerState(TypedAt<void>(frame->offset))) {
                case PointerState::PRESENT:
                    break;
                case PointerState::ABSENT:
                    Pop();
                    continue;
                default:
                    SetError("Tried to decode a bad struct pointer");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                auto struct_ptr_ptr = TypedAt<void*>(frame->offset);
                if (!ClaimOutOfLineStorage(frame->struct_pointer_state.struct_type->size,
                                           *struct_ptr_ptr, &frame->offset)) {
                    SetError("message wanted to store too large of a nullable struct");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                UpdatePointer(struct_ptr_ptr, TypedAt<void>(frame->offset));
                const fidl::FidlCodedStruct* coded_struct = frame->struct_pointer_state.struct_type;
                *frame = Frame(coded_struct, frame->offset);
                continue;
            }
            case Frame::kStateTable: {
                if (frame->field == 0u) {
                    auto envelope_vector_ptr = TypedAt<fidl_vector_t>(frame->offset);
                    switch (GetPointerState(&envelope_vector_ptr->data)) {
                    case PointerState::PRESENT:
                        break;
                    case PointerState::ABSENT:
                        SetError("Table data cannot be absent");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    default:
                        SetError("message tried to decode a non-present vector");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    }
                    uint32_t size;
                    if (mul_overflow(envelope_vector_ptr->count, 2 * sizeof(uint64_t), &size)) {
                        SetError("integer overflow calculating table size");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    }
                    if (!ClaimOutOfLineStorage(size, envelope_vector_ptr->data, &frame->offset)) {
                        SetError("message wanted to store too large of a table");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    }
                    UpdatePointer(&envelope_vector_ptr->data, TypedAt<void>(frame->offset));
                    frame->field = 1;
                    frame->table_state.known_index = 0;
                    frame->table_state.present_count = static_cast<uint32_t>(envelope_vector_ptr->count);
                    frame->table_state.end_offset = out_of_line_offset_;
                    frame->table_state.end_handle = handle_idx_;
                    continue;
                }
                if (frame->table_state.end_offset != out_of_line_offset_) {
                    SetError("Table field was mis-sized");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                if (frame->table_state.end_handle != handle_idx_) {
                    SetError("Table handles were mis-sized");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                if (frame->field > frame->table_state.present_count) {
                    Pop();
                    continue;
                }
                const fidl::FidlTableField* known_field = nullptr;
                if (frame->table_state.known_index < frame->table_state.field_count) {
                    const fidl::FidlTableField* field =
                        &frame->table_state.fields[frame->table_state.known_index];
                    if (field->ordinal == frame->field) {
                        known_field = field;
                        frame->table_state.known_index++;
                    }
                }
                const uint32_t tag_offset = static_cast<uint32_t>(
                    frame->offset + (frame->field - 1) * 2 * sizeof(uint64_t));
                const uint32_t data_offset = static_cast<uint32_t>(
                    tag_offset + sizeof(uint64_t));
                const uint64_t packed_sizes = *TypedAt<uint64_t>(tag_offset);
                frame->field++;
                switch (GetPointerState(TypedAt<void>(data_offset))) {
                case PointerState::PRESENT:
                    if (packed_sizes != 0)
                        break; // expected

                    SetError("Table envelope has present data pointer, but no data, and no handles");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                case PointerState::ABSENT:
                    if (packed_sizes == 0)
                        continue; // skip

                    SetError("Table envelope has absent data pointer, yet has data and/or handles");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                default:
                    SetError("Table envelope has bad data pointer");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                uint32_t offset;
                uint32_t handles;
                const uint32_t table_bytes = static_cast<uint32_t>(packed_sizes & 0xffffffffu);
                const uint32_t table_handles = static_cast<uint32_t>(packed_sizes >> 32);
                if (add_overflow(out_of_line_offset_, table_bytes, &offset) || offset > num_bytes()) {
                    SetError("integer overflow decoding table field");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                if (add_overflow(handle_idx_, table_handles, &handles) ||
                    handles > num_handles()) {
                    SetError("integer overflow decoding table handles");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                frame->table_state.end_offset = offset;
                frame->table_state.end_handle = handles;
                if (known_field != nullptr) {
                    const fidl_type_t* field_type = known_field->type;
                    uint32_t field_offset;
                    if (!ClaimOutOfLineStorage(TypeSize(field_type), TypedAt<void*>(data_offset), &field_offset)) {
                        SetError("table wanted too many bytes in field");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    }
                    UpdatePointer(TypedAt<void*>(data_offset), TypedAt<void>(field_offset));
                    if (!Push(Frame(field_type, field_offset))) {
                        SetError("recursion depth exceeded decoding table");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    }
                } else {
                    // Table data will not be processed: discard it.
                    uint32_t field_offset;
                    if (!ClaimOutOfLineStorage(table_bytes, TypedAt<void*>(data_offset), &field_offset)) {
                        SetError("table wanted too many bytes in field");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    }
                    UpdatePointer(TypedAt<void*>(data_offset), TypedAt<void>(field_offset));
                    for (uint32_t i = 0; i < table_handles; i++) {
                        if (!ClaimHandle(nullptr)) {
                            SetError("expected handle not present");
                            FIDL_POP_AND_CONTINUE_OR_RETURN;
                        }
                    }
                }
                continue;
            }
            case Frame::kStateTablePointer: {
                switch (GetPointerState(TypedAt<void>(frame->offset))) {
                case PointerState::PRESENT:
                    break;
                case PointerState::ABSENT:
                    Pop();
                    continue;
                default:
                    SetError("Tried to decode a bad table pointer");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                auto table_ptr_ptr = TypedAt<void*>(frame->offset);
                if (!ClaimOutOfLineStorage(sizeof(fidl_vector_t), *table_ptr_ptr, &frame->offset)) {
                    SetError("message wanted to store too large of a nullable table");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                UpdatePointer(table_ptr_ptr, TypedAt<void>(frame->offset));
                const fidl::FidlCodedTable* coded_table = frame->table_pointer_state.table_type;
                *frame = Frame(coded_table, frame->offset);
                continue;
            }
            case Frame::kStateUnion: {
                fidl_union_tag_t union_tag = *TypedAt<fidl_union_tag_t>(frame->offset);
                if (union_tag >= frame->union_state.type_count) {
                    SetError("Tried to decode a bad union discriminant");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                const fidl_type_t* member = frame->union_state.types[union_tag];
                if (!member) {
                    Pop();
                    continue;
                }
                frame->offset += frame->union_state.data_offset;
                *frame = Frame(member, frame->offset);
                continue;
            }
            case Frame::kStateUnionPointer: {
                auto union_ptr_ptr = TypedAt<fidl_union_tag_t*>(frame->offset);
                switch (GetPointerState(TypedAt<void>(frame->offset))) {
                case PointerState::PRESENT:
                    break;
                case PointerState::ABSENT:
                    Pop();
                    continue;
                default:
                    SetError("Tried to decode a bad union pointer");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                if (!ClaimOutOfLineStorage(frame->union_pointer_state.union_type->size, *union_ptr_ptr,
                                           &frame->offset)) {
                    SetError("message wanted to store too large of a nullable union");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                UpdatePointer(union_ptr_ptr, TypedAt<fidl_union_tag_t>(frame->offset));
                const fidl::FidlCodedUnion* coded_union = frame->union_pointer_state.union_type;
                *frame = Frame(coded_union, frame->offset);
                continue;
            }
            case Frame::kStateArray: {
                const uint32_t element_offset = frame->NextArrayOffset();
                if (element_offset == frame->array_state.array_size) {
                    Pop();
                    continue;
                }
                const fidl_type_t* element_type = frame->array_state.element;
                const uint32_t offset = frame->offset + element_offset;
                if (!Push(Frame(element_type, offset))) {
                    SetError("recursion depth exceeded decoding array");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                continue;
            }
            case Frame::kStateString: {
                auto string_ptr = TypedAt<fidl_string_t>(frame->offset);
                // The string storage may be Absent for nullable strings and must
                // otherwise be Present. No other values are allowed.
                switch (GetPointerState(&string_ptr->data)) {
                case PointerState::PRESENT:
                    break;
                case PointerState::ABSENT:
                    if (!frame->string_state.nullable) {
                        SetError("message tried to decode an absent non-nullable string");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    }
                    if (string_ptr->size != 0u) {
                        SetError("message tried to decode an absent string of non-zero length");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    }
                    Pop();
                    continue;
                default:
                    SetError(
                        "message tried to decode a string that is neither present nor absent");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                uint64_t bound = frame->string_state.max_size;
                uint64_t size = string_ptr->size;
                if (size > bound) {
                    SetError("message tried to decode too large of a bounded string");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                uint32_t string_data_offset = 0u;
                if (!ClaimOutOfLineStorage(static_cast<uint32_t>(size), string_ptr->data, &string_data_offset)) {
                    SetError("decoding a string overflowed buffer");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                UpdatePointer(&string_ptr->data, TypedAt<char>(string_data_offset));
                Pop();
                continue;
            }
            case Frame::kStateHandle: {
                auto handle_ptr = TypedAt<zx_handle_t>(frame->offset);
                // The handle storage may be Absent for nullable handles and must
                // otherwise be Present. No other values are allowed.
                switch (GetHandleState(*handle_ptr)) {
                case HandleState::ABSENT:
                    if (frame->handle_state.nullable) {
                        Pop();
                        continue;
                    }
                    SetError("message tried to decode a non-present handle");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                case HandleState::PRESENT:
                    if (!ClaimHandle(handle_ptr)) {
                        SetError("message decoded too many handles");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    }
                    Pop();
                    continue;
                default:
                    // The value at the handle was garbage.
                    SetError("message tried to decode a garbage handle");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
            }
            case Frame::kStateVector: {
                auto vector_ptr = TypedAt<fidl_vector_t>(frame->offset);
                // The vector storage may be Absent for nullable vectors and must
                // otherwise be Present. No other values are allowed.
                switch (GetPointerState(&vector_ptr->data)) {
                case PointerState::PRESENT:
                    break;
                case PointerState::ABSENT:
                    if (!frame->vector_state.nullable) {
                        SetError("message tried to decode an absent non-nullable vector");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    }
                    if (vector_ptr->count != 0u) {
                        SetError("message tried to decode an absent vector of non-zero elements");
                        FIDL_POP_AND_CONTINUE_OR_RETURN;
                    }
                    Pop();
                    continue;
                default:
                    SetError("message tried to decode a non-present vector");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                if (vector_ptr->count > frame->vector_state.max_count) {
                    SetError("message tried to decode too large of a bounded vector");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                uint32_t size;
                if (mul_overflow(vector_ptr->count, frame->vector_state.element_size, &size)) {
                    SetError("integer overflow calculating vector size");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                if (!ClaimOutOfLineStorage(size, vector_ptr->data, &frame->offset)) {
                    SetError("message wanted to store too large of a vector");
                    FIDL_POP_AND_CONTINUE_OR_RETURN;
                }
                UpdatePointer(&vector_ptr->data, TypedAt<void>(frame->offset));
                if (frame->vector_state.element) {
                    // Continue by decoding the vector elements as an array.
                    *frame = Frame(frame->vector_state.element, size,
                                   frame->vector_state.element_size, frame->offset);
                } else {
                    // If there is no element type pointer, there is
                    // nothing to decode in the vector secondary
                    // payload. So just continue.
                    Pop();
                }
                continue;
            }
            case Frame::kStateDone: {
                if (out_of_line_offset_ != num_bytes()) {
                    SetError("message did not decode all provided bytes");
                }
                return;
            }
            }
        }

#undef FIDL_POP_AND_CONTINUE_OR_RETURN
    }

protected:
    void SetError(const char* error_msg) {
        derived()->SetError(error_msg);
    }

    template <typename T>
    typename SetPtrConst<!kMutating, T>::type TypedAt(uint32_t offset) const {
        return reinterpret_cast<typename SetPtrConst<!kMutating, T>::type>(bytes() + offset);
    }

    enum class PointerState : uintptr_t {
        PRESENT = FIDL_ALLOC_PRESENT,
        ABSENT = FIDL_ALLOC_ABSENT,
        INVALID = 1 // *OR* *ANY* non PRESENT/ABSENT value.
    };

    enum class HandleState : zx_handle_t {
        PRESENT = FIDL_HANDLE_PRESENT,
        ABSENT = FIDL_HANDLE_ABSENT,
        INVALID = 1 // *OR* *ANY* non PRESENT/ABSENT value.
    };

    uint32_t handle_idx() const { return handle_idx_; }

private:
    Derived* derived() {
        return static_cast<Derived*>(this);
    }

    const Derived* derived() const {
        return static_cast<const Derived*>(this);
    }

    // Returns a pointer to the bytes in the message.
    auto bytes() const {
        return derived()->bytes();
    }

    // Returns the number of bytes in the message.
    auto num_bytes() const {
        return derived()->num_bytes();
    }

    // Returns the number of handles in the message (encoding: the max number of handles in the message).
    auto num_handles() const {
        return derived()->num_handles();
    }

    // Returns PRESENT/ABSENT/INVALID for a given pointer value.
    PointerState GetPointerState(const void* ptr) const {
        return derived()->GetPointerState(ptr);
    }

    // Returns PRESENT/ABSENT/INVALID for a given handle value.
    HandleState GetHandleState(zx_handle_t p) const {
        return derived()->GetHandleState(p);
    }

    // If required: mutate a pointer to the dual representation.
    template <class T2, class T1>
    void UpdatePointer(T2 p, T1 v) {
        derived()->UpdatePointer(p, v);
    }

    // Returns true when a handle was claimed, and false when the
    // handles are exhausted.
    template <class ZxHandleTPointer>
    bool ClaimHandle(ZxHandleTPointer out_handle) {
        if (handle_idx_ == num_handles()) {
            derived()->UnclaimedHandle(out_handle);
            return false;
        }
        derived()->ClaimedHandle(out_handle, handle_idx_);
        ++handle_idx_;
        return true;
    }

    // Returns true when the buffer space is claimed, and false when
    // the requested claim is too large for bytes_.
    bool ClaimOutOfLineStorage(uint32_t size, const void* storage, uint32_t* out_offset) {
        if (!derived()->ValidateOutOfLineStorageClaim(storage, &bytes()[out_of_line_offset_])) {
            return false;
        }

        // We have to manually maintain alignment here. For example, a pointer
        // to a struct that is 4 bytes still needs to advance the next
        // out-of-line offset by 8 to maintain the aligned-to-FIDL_ALIGNMENT
        // property.
        static constexpr uint32_t mask = FIDL_ALIGNMENT - 1;
        uint32_t offset = out_of_line_offset_;
        if (add_overflow(offset, size, &offset) ||
            add_overflow(offset, mask, &offset)) {
            return false;
        }
        offset &= ~mask;

        if (offset > num_bytes()) {
            return false;
        }
        *out_offset = out_of_line_offset_;
        out_of_line_offset_ = offset;
        return true;
    }

    uint32_t TypeSize(const fidl_type_t* type) {
        switch (type->type_tag) {
        case fidl::kFidlTypeStructPointer:
        case fidl::kFidlTypeTablePointer:
        case fidl::kFidlTypeUnionPointer:
            return sizeof(uint64_t);
        case fidl::kFidlTypeHandle:
            return sizeof(zx_handle_t);
        case fidl::kFidlTypeStruct:
            return type->coded_struct.size;
        case fidl::kFidlTypeTable:
            return sizeof(fidl_vector_t);
        case fidl::kFidlTypeUnion:
            return type->coded_union.size;
        case fidl::kFidlTypeString:
            return sizeof(fidl_string_t);
        case fidl::kFidlTypeArray:
            return type->coded_array.array_size;
        case fidl::kFidlTypeVector:
            return sizeof(fidl_vector_t);
        }
        abort();
        return 0;
    }

    // Functions that manipulate the decoding stack frames.
    struct Frame {
        Frame(const fidl_type_t* fidl_type, uint32_t offset)
            : offset(offset) {
            switch (fidl_type->type_tag) {
            case fidl::kFidlTypeStruct:
                state = kStateStruct;
                struct_state.fields = fidl_type->coded_struct.fields;
                struct_state.field_count = fidl_type->coded_struct.field_count;
                break;
            case fidl::kFidlTypeStructPointer:
                state = kStateStructPointer;
                struct_pointer_state.struct_type = fidl_type->coded_struct_pointer.struct_type;
                break;
            case fidl::kFidlTypeTable:
                state = kStateTable;
                table_state.fields = fidl_type->coded_table.fields;
                table_state.field_count = fidl_type->coded_table.field_count;
                table_state.present_count = 0;
                break;
            case fidl::kFidlTypeTablePointer:
                state = kStateTablePointer;
                table_pointer_state.table_type = fidl_type->coded_table_pointer.table_type;
                break;
            case fidl::kFidlTypeUnion:
                state = kStateUnion;
                union_state.types = fidl_type->coded_union.types;
                union_state.type_count = fidl_type->coded_union.type_count;
                union_state.data_offset = fidl_type->coded_union.data_offset;
                break;
            case fidl::kFidlTypeUnionPointer:
                state = kStateUnionPointer;
                union_pointer_state.union_type = fidl_type->coded_union_pointer.union_type;
                break;
            case fidl::kFidlTypeArray:
                state = kStateArray;
                array_state.element = fidl_type->coded_array.element;
                array_state.array_size = fidl_type->coded_array.array_size;
                array_state.element_size = fidl_type->coded_array.element_size;
                break;
            case fidl::kFidlTypeString:
                state = kStateString;
                string_state.max_size = fidl_type->coded_string.max_size;
                string_state.nullable = fidl_type->coded_string.nullable;
                break;
            case fidl::kFidlTypeHandle:
                state = kStateHandle;
                handle_state.nullable = fidl_type->coded_handle.nullable;
                break;
            case fidl::kFidlTypeVector:
                state = kStateVector;
                vector_state.element = fidl_type->coded_vector.element;
                vector_state.max_count = fidl_type->coded_vector.max_count;
                vector_state.element_size = fidl_type->coded_vector.element_size;
                vector_state.nullable = fidl_type->coded_vector.nullable;
                break;
            }
        }

        Frame(const fidl::FidlCodedStruct* coded_struct, uint32_t offset)
            : offset(offset) {
            state = kStateStruct;
            struct_state.fields = coded_struct->fields;
            struct_state.field_count = coded_struct->field_count;
        }

        Frame(const fidl::FidlCodedTable* coded_table, uint32_t offset)
            : offset(offset) {
            state = kStateStruct;
            table_state.fields = coded_table->fields;
            table_state.field_count = coded_table->field_count;
        }

        Frame(const fidl::FidlCodedUnion* coded_union, uint32_t offset)
            : offset(offset) {
            state = kStateUnion;
            union_state.types = coded_union->types;
            union_state.type_count = coded_union->type_count;
            union_state.data_offset = coded_union->data_offset;
        }

        Frame(const fidl_type_t* element, uint32_t array_size, uint32_t element_size,
              uint32_t offset)
            : offset(offset) {
            state = kStateArray;
            array_state.element = element;
            array_state.array_size = array_size;
            array_state.element_size = element_size;
        }

        // The default constructor does nothing when initializing the stack of frames.
        Frame() {}

        static Frame DoneSentinel() {
            Frame frame;
            frame.state = kStateDone;
            return frame;
        }

        uint32_t NextStructField() {
            ZX_DEBUG_ASSERT(state == kStateStruct);

            uint32_t current = field;
            field += 1;
            return current;
        }

        uint32_t NextArrayOffset() {
            ZX_DEBUG_ASSERT(state == kStateArray);

            uint32_t current = field;
            field += array_state.element_size;
            return current;
        }

        enum : int {
            kStateStruct,
            kStateStructPointer,
            kStateTable,
            kStateTablePointer,
            kStateUnion,
            kStateUnionPointer,
            kStateArray,
            kStateString,
            kStateHandle,
            kStateVector,

            kStateDone,
        } state;
        // A byte offset into bytes_;
        uint32_t offset;

        // This is a subset of the information recorded in the
        // fidl_type structures needed for decoding state. For
        // example, struct sizes do not need to be present here.
        union {
            struct {
                const fidl::FidlField* fields;
                uint32_t field_count;
            } struct_state;
            struct {
                const fidl::FidlCodedStruct* struct_type;
            } struct_pointer_state;
            struct {
                const fidl::FidlTableField* fields;
                uint32_t known_index;
                uint32_t field_count;
                uint32_t present_count;
                uint32_t end_offset;
                uint32_t end_handle;
            } table_state;
            struct {
                const fidl::FidlCodedTable* table_type;
            } table_pointer_state;
            struct {
                const fidl_type_t* const* types;
                uint32_t type_count;
                uint32_t data_offset;
            } union_state;
            struct {
                const fidl::FidlCodedUnion* union_type;
            } union_pointer_state;
            struct {
                const fidl_type_t* element;
                uint32_t array_size;
                uint32_t element_size;
            } array_state;
            struct {
                uint32_t max_size;
                bool nullable;
            } string_state;
            struct {
                bool nullable;
            } handle_state;
            struct {
                const fidl_type* element;
                uint32_t max_count;
                uint32_t element_size;
                bool nullable;
            } vector_state;
        };

        uint32_t field = 0u;
    };

    // Returns true on success and false on recursion overflow.
    bool Push(Frame frame) {
        if (depth_ == FIDL_RECURSION_DEPTH) {
            return false;
        }
        decoding_frames_[depth_] = frame;
        ++depth_;
        return true;
    }

    void Pop() {
        ZX_DEBUG_ASSERT(depth_ != 0u);
        --depth_;
    }

    Frame* Peek() {
        ZX_DEBUG_ASSERT(depth_ != 0u);
        return &decoding_frames_[depth_ - 1];
    }

    // Message state passed in to the constructor.
    const fidl_type_t* const type_;

    // Internal state.
    uint32_t handle_idx_ = 0u;
    uint32_t out_of_line_offset_ = 0u;

    // Decoding stack state.
    uint32_t depth_ = 0u;
    Frame decoding_frames_[FIDL_RECURSION_DEPTH];
};

} // namespace internal
} // namespace fidl


<|start_filename|>pkg/fidl_cpp_base/include/lib/fidl/cpp/traits.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef LIB_FIDL_CPP_TRAITS_H_
#define LIB_FIDL_CPP_TRAITS_H_

#include <stdint.h>

#include <type_traits>

namespace fidl {

// A type trait that indiciates whether the given type is a primitive FIDL
// type.
template <typename T>
struct IsPrimitive : public std::false_type {};

// clang-format off
template <> struct IsPrimitive<bool> : public std::true_type {};
template <> struct IsPrimitive<uint8_t> : public std::true_type {};
template <> struct IsPrimitive<uint16_t> : public std::true_type {};
template <> struct IsPrimitive<uint32_t> : public std::true_type {};
template <> struct IsPrimitive<uint64_t> : public std::true_type {};
template <> struct IsPrimitive<int8_t> : public std::true_type {};
template <> struct IsPrimitive<int16_t> : public std::true_type {};
template <> struct IsPrimitive<int32_t> : public std::true_type {};
template <> struct IsPrimitive<int64_t> : public std::true_type {};
template <> struct IsPrimitive<float> : public std::true_type {};
template <> struct IsPrimitive<double> : public std::true_type {};
// clang-format on

}  // namespace fidl

#endif  // LIB_FIDL_CPP_TRAITS_H_


<|start_filename|>dart/fuchsia_services/lib/src/startup_context.dart<|end_filename|>
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:fidl_fuchsia_sys/fidl_async.dart' as fidl;
import 'package:meta/meta.dart';
import 'package:zircon/zircon.dart';
import 'package:fidl/fidl.dart';
import 'package:fuchsia/fuchsia.dart';

import 'service_provider_impl.dart';

/// The [StartupContext] holds references to the services and connections
/// that the component was launched with. Authors can get use the startup
/// context to access useful information for connecting to other components
/// and interacting with the framework.
class StartupContext {
  static StartupContext _context;

  /// The connection to the [fidl.Environment] proxy.
  final fidl.Environment environment;

  /// The connection to the [fidl.Launcher] proxy.
  final fidl.Launcher launcher;

  /// The [fidl.ServiceProvider] which can be used to connect to
  /// the services exposed to the component on launch.
  final fidl.ServiceProvider environmentServices;

  /// The service provider which can be used to expose outgoing services
  final ServiceProviderImpl outgoingServices;

  /// Creates a new instance of [StartupContext].
  ///
  /// See [StartupContext.fromStartupInfo].
  StartupContext({
    @required this.environment,
    @required this.launcher,
    @required this.environmentServices,
    @required this.outgoingServices,
  })  : assert(environment != null),
        assert(launcher != null),
        assert(environmentServices != null),
        assert(outgoingServices != null);

  /// Returns the [StartupContext] cached instance associated with the
  /// currently running component.
  ///
  /// Authors should use this method of obtaining the [StartupContext] instead
  /// of instantiating one on their own as it will bind and connect to all the
  /// underlying services for them.
  factory StartupContext.fromStartupInfo() {
    if (_context != null) {
      return _context;
    }

    final environmentProxy = fidl.EnvironmentProxy();
    final launcherProxy = fidl.LauncherProxy();
    final environmentServicesProxy = fidl.ServiceProviderProxy();
    final outgoingServicesImpl = ServiceProviderImpl();

    _context = StartupContext(
      environment: environmentProxy,
      launcher: launcherProxy,
      environmentServices: environmentServicesProxy,
      outgoingServices: outgoingServicesImpl,
    );

    final Handle environmentHandle = MxStartupInfo.takeEnvironment();
    if (environmentHandle != null) {
      environmentProxy
        ..ctrl
            .bind(InterfaceHandle<fidl.Environment>(Channel(environmentHandle)))
        ..getLauncher(launcherProxy.ctrl.request())
        ..getServices(environmentServicesProxy.ctrl.request());
    }

    final Handle outgoingServicesHandle = MxStartupInfo.takeOutgoingServices();
    if (outgoingServicesHandle != null) {
      outgoingServicesImpl.bind(InterfaceRequest<fidl.ServiceProvider>(
          Channel(outgoingServicesHandle)));
    }

    return _context;
  }
}


<|start_filename|>dart/fidl/lib/src/types.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:convert';
import 'dart:typed_data';

import 'package:zircon/zircon.dart';

import 'codec.dart';
import 'enum.dart';
import 'error.dart';
import 'interface.dart';
import 'struct.dart';
import 'table.dart';
import 'union.dart';

// ignore_for_file: public_member_api_docs
// ignore_for_file: always_specify_types

void _throwIfNotNullable(bool nullable) {
  if (!nullable) {
    throw new FidlError('Found null for a non-nullable type');
  }
}

void _throwIfExceedsLimit(int count, int limit) {
  if (limit != null && count > limit) {
    throw new FidlError(
        'Found an object wth $count elements. Limited to $limit.');
  }
}

void _throwIfCountMismatch(int count, int expectedCount) {
  if (count != expectedCount) {
    throw new FidlError(
        'Found an array of count $count. Expected $expectedCount.');
  }
}

void _throwIfNotZero(int value) {
  if (value != 0) {
    throw new FidlError('Expected zero, got: $value');
  }
}

void _copyInt8(ByteData data, Int8List value, int offset) {
  final int count = value.length;
  for (int i = 0; i < count; ++i) {
    data.setInt8(offset + i, value[i]);
  }
}

void _copyUint8(ByteData data, Uint8List value, int offset) {
  final int count = value.length;
  for (int i = 0; i < count; ++i) {
    data.setUint8(offset + i, value[i]);
  }
}

void _copyInt16(ByteData data, Int16List value, int offset) {
  final int count = value.length;
  const int stride = 2;
  for (int i = 0; i < count; ++i) {
    data.setInt16(offset + i * stride, value[i], Endian.little);
  }
}

void _copyUint16(ByteData data, Uint16List value, int offset) {
  final int count = value.length;
  const int stride = 2;
  for (int i = 0; i < count; ++i) {
    data.setUint16(offset + i * stride, value[i], Endian.little);
  }
}

void _copyInt32(ByteData data, Int32List value, int offset) {
  final int count = value.length;
  const int stride = 4;
  for (int i = 0; i < count; ++i) {
    data.setInt32(offset + i * stride, value[i], Endian.little);
  }
}

void _copyUint32(ByteData data, Uint32List value, int offset) {
  final int count = value.length;
  const int stride = 4;
  for (int i = 0; i < count; ++i) {
    data.setUint32(offset + i * stride, value[i], Endian.little);
  }
}

void _copyInt64(ByteData data, Int64List value, int offset) {
  final int count = value.length;
  const int stride = 8;
  for (int i = 0; i < count; ++i) {
    data.setInt64(offset + i * stride, value[i], Endian.little);
  }
}

void _copyUint64(ByteData data, Uint64List value, int offset) {
  final int count = value.length;
  const int stride = 8;
  for (int i = 0; i < count; ++i) {
    data.setUint64(offset + i * stride, value[i], Endian.little);
  }
}

void _copyFloat32(ByteData data, Float32List value, int offset) {
  final int count = value.length;
  const int stride = 4;
  for (int i = 0; i < count; ++i) {
    data.setFloat32(offset + i * stride, value[i], Endian.little);
  }
}

void _copyFloat64(ByteData data, Float64List value, int offset) {
  final int count = value.length;
  const int stride = 8;
  for (int i = 0; i < count; ++i) {
    data.setFloat64(offset + i * stride, value[i], Endian.little);
  }
}

String _convertFromUTF8(Uint8List bytes) {
  try {
    return const Utf8Decoder().convert(bytes);
  } on FormatException {
    throw FidlError('Received a string with invalid UTF8: $bytes');
  }
}

Uint8List _convertToUTF8(String string) {
  return new Uint8List.fromList(const Utf8Encoder().convert(string));
}

const int kAllocAbsent = 0;
const int kAllocPresent = 0xFFFFFFFFFFFFFFFF;
const int kHandleAbsent = 0;
const int kHandlePresent = 0xFFFFFFFF;

abstract class FidlType<T> {
  const FidlType({this.encodedSize});

  final int encodedSize;

  void encode(Encoder encoder, T value, int offset);
  T decode(Decoder decoder, int offset);

  void encodeArray(Encoder encoder, List<T> value, int offset) {
    final int count = value.length;
    final int stride = encodedSize;
    for (int i = 0; i < count; ++i) {
      encode(encoder, value[i], offset + i * stride);
    }
  }

  List<T> decodeArray(Decoder decoder, int count, int offset) {
    final List<T> list = new List<T>(count);
    for (int i = 0; i < count; ++i) {
      list[i] = decode(decoder, offset + i * encodedSize);
    }
    return list;
  }
}

class BoolType extends FidlType<bool> {
  const BoolType() : super(encodedSize: 1);

  @override
  void encode(Encoder encoder, bool value, int offset) {
    encoder.encodeBool(value, offset);
  }

  @override
  bool decode(Decoder decoder, int offset) => decoder.decodeBool(offset);
}

class StatusType extends Int32Type {
  const StatusType();
}

class Int8Type extends FidlType<int> {
  const Int8Type() : super(encodedSize: 1);

  @override
  void encode(Encoder encoder, int value, int offset) {
    encoder.encodeInt8(value, offset);
  }

  @override
  int decode(Decoder decoder, int offset) => decoder.decodeInt8(offset);

  @override
  void encodeArray(Encoder encoder, List<int> value, int offset) {
    _copyInt8(encoder.data, value, offset);
  }

  @override
  List<int> decodeArray(Decoder decoder, int count, int offset) {
    return decoder.data.buffer.asInt8List(offset, count);
  }
}

class Int16Type extends FidlType<int> {
  const Int16Type() : super(encodedSize: 2);

  @override
  void encode(Encoder encoder, int value, int offset) {
    encoder.encodeInt16(value, offset);
  }

  @override
  int decode(Decoder decoder, int offset) => decoder.decodeInt16(offset);

  @override
  void encodeArray(Encoder encoder, List<int> value, int offset) {
    _copyInt16(encoder.data, value, offset);
  }

  @override
  List<int> decodeArray(Decoder decoder, int count, int offset) {
    return decoder.data.buffer.asInt16List(offset, count);
  }
}

class Int32Type extends FidlType<int> {
  const Int32Type() : super(encodedSize: 4);

  @override
  void encode(Encoder encoder, int value, int offset) {
    encoder.encodeInt32(value, offset);
  }

  @override
  int decode(Decoder decoder, int offset) => decoder.decodeInt32(offset);

  @override
  void encodeArray(Encoder encoder, List<int> value, int offset) {
    _copyInt32(encoder.data, value, offset);
  }

  @override
  List<int> decodeArray(Decoder decoder, int count, int offset) {
    return decoder.data.buffer.asInt32List(offset, count);
  }
}

class Int64Type extends FidlType<int> {
  const Int64Type() : super(encodedSize: 8);

  @override
  void encode(Encoder encoder, int value, int offset) {
    encoder.encodeInt64(value, offset);
  }

  @override
  int decode(Decoder decoder, int offset) => decoder.decodeInt64(offset);

  @override
  void encodeArray(Encoder encoder, List<int> value, int offset) {
    _copyInt64(encoder.data, value, offset);
  }

  @override
  List<int> decodeArray(Decoder decoder, int count, int offset) {
    return decoder.data.buffer.asInt64List(offset, count);
  }
}

class Uint8Type extends FidlType<int> {
  const Uint8Type() : super(encodedSize: 1);

  @override
  void encode(Encoder encoder, int value, int offset) {
    encoder.encodeUint8(value, offset);
  }

  @override
  int decode(Decoder decoder, int offset) => decoder.decodeUint8(offset);

  @override
  void encodeArray(Encoder encoder, List<int> value, int offset) {
    _copyUint8(encoder.data, value, offset);
  }

  @override
  List<int> decodeArray(Decoder decoder, int count, int offset) {
    return decoder.data.buffer.asUint8List(offset, count);
  }
}

class Uint16Type extends FidlType<int> {
  const Uint16Type() : super(encodedSize: 2);

  @override
  void encode(Encoder encoder, int value, int offset) {
    encoder.encodeUint16(value, offset);
  }

  @override
  int decode(Decoder decoder, int offset) => decoder.decodeUint16(offset);

  @override
  void encodeArray(Encoder encoder, List<int> value, int offset) {
    _copyUint16(encoder.data, value, offset);
  }

  @override
  List<int> decodeArray(Decoder decoder, int count, int offset) {
    return decoder.data.buffer.asUint16List(offset, count);
  }
}

class Uint32Type extends FidlType<int> {
  const Uint32Type() : super(encodedSize: 4);

  @override
  void encode(Encoder encoder, int value, int offset) {
    encoder.encodeUint32(value, offset);
  }

  @override
  int decode(Decoder decoder, int offset) => decoder.decodeUint32(offset);

  @override
  void encodeArray(Encoder encoder, List<int> value, int offset) {
    _copyUint32(encoder.data, value, offset);
  }

  @override
  List<int> decodeArray(Decoder decoder, int count, int offset) {
    return decoder.data.buffer.asUint32List(offset, count);
  }
}

class Uint64Type extends FidlType<int> {
  const Uint64Type() : super(encodedSize: 8);

  @override
  void encode(Encoder encoder, int value, int offset) {
    encoder.encodeUint64(value, offset);
  }

  @override
  int decode(Decoder decoder, int offset) => decoder.decodeUint64(offset);

  @override
  void encodeArray(Encoder encoder, List<int> value, int offset) {
    _copyUint64(encoder.data, value, offset);
  }

  @override
  List<int> decodeArray(Decoder decoder, int count, int offset) {
    return decoder.data.buffer.asUint64List(offset, count);
  }
}

class Float32Type extends FidlType<double> {
  const Float32Type() : super(encodedSize: 4);

  @override
  void encode(Encoder encoder, double value, int offset) {
    encoder.encodeFloat32(value, offset);
  }

  @override
  double decode(Decoder decoder, int offset) => decoder.decodeFloat32(offset);

  @override
  void encodeArray(Encoder encoder, List<double> value, int offset) {
    _copyFloat32(encoder.data, value, offset);
  }

  @override
  List<double> decodeArray(Decoder decoder, int count, int offset) {
    return decoder.data.buffer.asFloat32List(offset, count);
  }
}

class Float64Type extends FidlType<double> {
  const Float64Type() : super(encodedSize: 8);

  @override
  void encode(Encoder encoder, double value, int offset) {
    encoder.encodeFloat64(value, offset);
  }

  @override
  double decode(Decoder decoder, int offset) => decoder.decodeFloat64(offset);

  @override
  void encodeArray(Encoder encoder, List<double> value, int offset) {
    _copyFloat64(encoder.data, value, offset);
  }

  @override
  List<double> decodeArray(Decoder decoder, int count, int offset) {
    return decoder.data.buffer.asFloat64List(offset, count);
  }
}

void _validateEncodedHandle(int encoded, bool nullable) {
  if (encoded == kHandleAbsent) {
    _throwIfNotNullable(nullable);
  } else if (encoded == kHandlePresent) {
    // Nothing to validate.
  } else {
    throw new FidlError('Invalid handle encoding: $encoded.');
  }
}

void _encodeHandle(Encoder encoder, Handle value, int offset, bool nullable) {
  int encoded =
      (value != null && value.isValid) ? kHandlePresent : kHandleAbsent;
  _validateEncodedHandle(encoded, nullable);
  encoder.encodeUint32(encoded, offset);
  if (encoded == kHandlePresent) {
    encoder.addHandle(value);
  }
}

Handle _decodeHandle(Decoder decoder, int offset, bool nullable) {
  final int encoded = decoder.decodeUint32(offset);
  _validateEncodedHandle(encoded, nullable);
  return encoded == kHandlePresent
      ? decoder.claimHandle()
      : new Handle.invalid();
}

// TODO(pascallouis): By having _HandleWrapper exported, we could DRY this code
// by simply having an AbstractHandleType<H extend HandleWrapper<H>> and having
// the encoding / decoding once, with the only specialization on a per-type
// basis being construction.
// Further, if each HandleWrapper were to offer a static ctor function to invoke
// their constrctors, could be called directly.
// We could also explore having a Handle be itself a subtype of HandleWrapper
// to further standardize handling of handles.

class HandleType extends FidlType<Handle> {
  const HandleType({
    this.nullable,
  }) : super(encodedSize: 4);

  final bool nullable;

  @override
  void encode(Encoder encoder, Handle value, int offset) {
    _encodeHandle(encoder, value, offset, nullable);
  }

  @override
  Handle decode(Decoder decoder, int offset) =>
      _decodeHandle(decoder, offset, nullable);
}

class ChannelType extends FidlType<Channel> {
  const ChannelType({
    this.nullable,
  }) : super(encodedSize: 4);

  final bool nullable;

  @override
  void encode(Encoder encoder, Channel value, int offset) {
    _encodeHandle(encoder, value?.handle, offset, nullable);
  }

  @override
  Channel decode(Decoder decoder, int offset) =>
      new Channel(_decodeHandle(decoder, offset, nullable));
}

class SocketType extends FidlType<Socket> {
  const SocketType({
    this.nullable,
  }) : super(encodedSize: 4);

  final bool nullable;

  @override
  void encode(Encoder encoder, Socket value, int offset) {
    _encodeHandle(encoder, value?.handle, offset, nullable);
  }

  @override
  Socket decode(Decoder decoder, int offset) =>
      new Socket(_decodeHandle(decoder, offset, nullable));
}

class VmoType extends FidlType<Vmo> {
  const VmoType({
    this.nullable,
  }) : super(encodedSize: 4);

  final bool nullable;

  @override
  void encode(Encoder encoder, Vmo value, int offset) {
    _encodeHandle(encoder, value?.handle, offset, nullable);
  }

  @override
  Vmo decode(Decoder decoder, int offset) =>
      new Vmo(_decodeHandle(decoder, offset, nullable));
}

class InterfaceHandleType<T> extends FidlType<InterfaceHandle<T>> {
  const InterfaceHandleType({
    this.nullable,
  }) : super(encodedSize: 4);

  final bool nullable;

  @override
  void encode(Encoder encoder, InterfaceHandle<T> value, int offset) {
    _encodeHandle(encoder, value?.channel?.handle, offset, nullable);
  }

  @override
  InterfaceHandle<T> decode(Decoder decoder, int offset) {
    final Handle handle = _decodeHandle(decoder, offset, nullable);
    return new InterfaceHandle<T>(handle.isValid ? new Channel(handle) : null);
  }
}

class InterfaceRequestType<T> extends FidlType<InterfaceRequest<T>> {
  const InterfaceRequestType({
    this.nullable,
  }) : super(encodedSize: 4);

  final bool nullable;

  @override
  void encode(Encoder encoder, InterfaceRequest<T> value, int offset) {
    _encodeHandle(encoder, value?.channel?.handle, offset, nullable);
  }

  @override
  InterfaceRequest<T> decode(Decoder decoder, int offset) {
    final Handle handle = _decodeHandle(decoder, offset, nullable);
    return new InterfaceRequest<T>(handle.isValid ? new Channel(handle) : null);
  }
}

class StringType extends FidlType<String> {
  const StringType({
    this.maybeElementCount,
    this.nullable,
  }) : super(encodedSize: 16);

  final int maybeElementCount;
  final bool nullable;

  // See fidl_string_t.

  @override
  void encode(Encoder encoder, String value, int offset) {
    validate(value);
    if (value == null) {
      encoder
        ..encodeUint64(0, offset) // size
        ..encodeUint64(kAllocAbsent, offset + 8); // data
      return null;
    }
    final Uint8List bytes = _convertToUTF8(value);
    final int size = bytes.lengthInBytes;
    encoder
      ..encodeUint64(size, offset) // size
      ..encodeUint64(kAllocPresent, offset + 8); // data
    int childOffset = encoder.alloc(size);
    _copyUint8(encoder.data, bytes, childOffset);
  }

  @override
  String decode(Decoder decoder, int offset) {
    final int size = decoder.decodeUint64(offset);
    final int data = decoder.decodeUint64(offset + 8);
    validateEncoded(size, data);
    if (data == kAllocAbsent) {
      return null;
    }
    final Uint8List bytes =
        decoder.data.buffer.asUint8List(decoder.claimMemory(size), size);
    return _convertFromUTF8(bytes);
  }

  void validate(String value) {
    if (value == null) {
      _throwIfNotNullable(nullable);
      return;
    }
    _throwIfExceedsLimit(value.length, maybeElementCount);
  }

  void validateEncoded(int size, int data) {
    if (data == kAllocAbsent) {
      _throwIfNotNullable(nullable);
      _throwIfNotZero(size);
    } else if (data == kAllocPresent) {
      _throwIfExceedsLimit(size, maybeElementCount);
    } else {
      throw new FidlError('Invalid string encoding: $data.');
    }
  }
}

class PointerType<T> extends FidlType<T> {
  const PointerType({
    this.element,
  }) : super(encodedSize: 8);

  final FidlType element;

  @override
  void encode(Encoder encoder, T value, int offset) {
    if (value == null) {
      encoder.encodeUint64(kAllocAbsent, offset);
    } else {
      encoder.encodeUint64(kAllocPresent, offset);
      int childOffset = encoder.alloc(element.encodedSize);
      element.encode(encoder, value, childOffset);
    }
  }

  @override
  T decode(Decoder decoder, int offset) {
    final int data = decoder.decodeUint64(offset);
    validateEncoded(data);
    if (data == kAllocAbsent) {
      return null;
    }
    return element.decode(decoder, decoder.claimMemory(element.encodedSize));
  }

  void validateEncoded(int encoded) {
    if (encoded != kAllocAbsent && encoded != kAllocPresent) {
      throw new FidlError('Invalid pointer encoding: $encoded.');
    }
  }
}

class MemberType<T> extends FidlType<T> {
  const MemberType({
    this.type,
    this.offset,
  });

  final FidlType type;
  final int offset;

  @override
  void encode(Encoder encoder, T value, int base) {
    type.encode(encoder, value, base + offset);
  }

  @override
  T decode(Decoder decoder, int base) => type.decode(decoder, base + offset);
}

class StructType<T extends Struct> extends FidlType<T> {
  const StructType({
    int encodedSize,
    this.members,
    this.ctor,
  }) : super(encodedSize: encodedSize);

  final List<MemberType> members;
  final StructFactory<T> ctor;

  @override
  void encode(Encoder encoder, T value, int offset) {
    final int count = members.length;
    final List<Object> values = value.$fields;
    if (values.length != count) {
      throw new FidlError(
          'Unexpected number of members for $T. Expected $count. Got ${values.length}');
    }
    for (int i = 0; i < count; ++i) {
      members[i].encode(encoder, values[i], offset);
    }
  }

  @override
  T decode(Decoder decoder, int offset) {
    final int argc = members.length;
    final List<Object> argv = new List<Object>(argc);
    for (int i = 0; i < argc; ++i) {
      argv[i] = members[i].decode(decoder, offset);
    }
    return ctor(argv);
  }
}

const int _kEnvelopeSize = 16;

class TableType<T extends Table> extends FidlType<T> {
  const TableType({
    int encodedSize,
    this.members,
    this.ctor,
  }) : super(encodedSize: encodedSize);

  final Map<int, FidlType> members;
  final TableFactory<T> ctor;

  @override
  void encode(Encoder encoder, T value, int offset) {
    // Determining max ordinal.
    int maxOrdinal = 0;
    value.$fields.forEach((ordinal, field) {
      if (!members.containsKey(ordinal)) {
        throw new FidlError('Cannot encode unknown table member with ordinal: $ordinal');
      }
      if (field != null) {
        if (maxOrdinal < ordinal)
          maxOrdinal = ordinal;
      }
    });

    // Header.
    encoder
      ..encodeUint64(maxOrdinal, offset)
      ..encodeUint64(kAllocPresent, offset + 8);

    // Early exit on empty table.
    if (maxOrdinal == 0)
      return;

    // Sizing
    int envelopeOffset = encoder.alloc(maxOrdinal * _kEnvelopeSize);

    // Envelopes, and fields.
    for (int ordinal = 1; ordinal <= maxOrdinal; ordinal++) {
      final field = value.$fields[ordinal];
      final fieldPresent = field != null;
      if (fieldPresent) {
        final fieldType = members[ordinal];
        int numHandles = encoder.countHandles();
        final fieldOffset = encoder.alloc(fieldType.encodedSize);
        fieldType.encode(encoder, field, fieldOffset);
        numHandles = encoder.countHandles() - numHandles;
        final numBytes = encoder.nextOffset() - fieldOffset;

        encoder
          ..encodeUint32(numBytes, envelopeOffset)
          ..encodeUint32(numHandles, envelopeOffset + 4)
          ..encodeUint64(kAllocPresent, envelopeOffset + 8);
      } else {
        encoder
          ..encodeUint64(0, envelopeOffset)
          ..encodeUint64(kAllocAbsent, envelopeOffset + 8);
      }
      envelopeOffset += _kEnvelopeSize;
    }
  }

  @override
  T decode(Decoder decoder, int offset) {
    // Header.
    final int maxOrdinal = decoder.decodeUint64(offset);
    final int data = decoder.decodeUint64(offset + 8);
    switch (data) {
      case kAllocPresent:
        break; // good
      case kAllocAbsent:
        throw new FidlError('Unexpected null reference');
      default:
        throw new FidlError('Bad reference encoding');
    }

    // Early exit on empty table.
    if (maxOrdinal == 0) {
      return ctor({});
    }

    // Offsets.
    int envelopeOffset = decoder.claimMemory(maxOrdinal * _kEnvelopeSize);

    // Envelopes, and fields.
    final Map<int, dynamic> argv = {};
    for (int ordinal = 1; ordinal <= maxOrdinal; ordinal++) {
      final numBytes = decoder.decodeUint32(envelopeOffset);
      final numHandles = decoder.decodeUint32(envelopeOffset + 4);
      final fieldPresent = decoder.decodeUint64(envelopeOffset + 8);
      envelopeOffset += _kEnvelopeSize;
      switch (fieldPresent) {
        case kAllocPresent:
          final fieldKnown = members.containsKey(ordinal);
          if (fieldKnown) {
            final fieldType = members[ordinal];
            final fieldOffset = decoder.claimMemory(fieldType.encodedSize);
            final claimedHandles = decoder.countClaimedHandles();
            final field = fieldType.decode(decoder, fieldOffset);
            final numBytesConsumed = decoder.nextOffset() - fieldOffset;
            final numHandlesConsumed = decoder.countClaimedHandles() - claimedHandles;
            if (numBytes != numBytesConsumed)
              throw new FidlError('Table field was mis-sized');
            if (numHandles != numHandlesConsumed)
              throw new FidlError('Table handles were mis-sized');
            argv[ordinal] = field;
          } else {
            decoder.claimMemory(numBytes);
            for (int i = 0; i < numHandles; i++) {
              final handle = decoder.claimHandle();
              try {
                handle.close();
                // ignore: avoid_catches_without_on_clauses
              } catch (e) {
                // best effort
              }
            }
          }
          break;
        case kAllocAbsent:
          // TODO(FIDL-237): We should check that numBytes and numHandles
          // are 0, and reject messages where this is not the case. This
          // requires all other bindings from properly memseting to 0
          // all bytes of the buffer.
          break;
        default:
          throw new FidlError('Bad reference encoding');
      }
    }

    return ctor(argv);
  }
}

class UnionType<T extends Union> extends FidlType<T> {
  const UnionType({
    int encodedSize,
    this.members,
    this.ctor,
  }) : super(encodedSize: encodedSize);

  final List<MemberType> members;
  final UnionFactory<T> ctor;

  @override
  void encode(Encoder encoder, T value, int offset) {
    final int index = value.$index;
    if (index < 0 || index >= members.length)
      throw new FidlError('Bad union tag index: $index');
    encoder.encodeUint32(index, offset);
    members[index].encode(encoder, value.$data, offset);
  }

  @override
  T decode(Decoder decoder, int offset) {
    final int index = decoder.decodeUint32(offset);
    if (index < 0 || index >= members.length)
      throw new FidlError('Bad union tag index: $index');
    return ctor(index, members[index].decode(decoder, offset));
  }
}

class EnumType<T extends Enum> extends FidlType<T> {
  const EnumType({
    this.type,
    this.ctor,
  });

  final FidlType<int> type;
  final EnumFactory<T> ctor;

  @override
  int get encodedSize => type.encodedSize;

  @override
  void encode(Encoder encoder, T value, int offset) {
    type.encode(encoder, value.value, offset);
  }

  @override
  T decode(Decoder decoder, int offset) {
    return ctor(type.decode(decoder, offset));
  }
}

class MethodType extends FidlType<Null> {
  const MethodType({
    this.request,
    this.response,
    this.name,
  });

  final List<MemberType> request;
  final List<MemberType> response;
  final String name;

  @override
  void encode(Encoder encoder, Null value, int offset) {
    throw new FidlError('Cannot encode a method.');
  }

  @override
  Null decode(Decoder decoder, int offset) {
    throw new FidlError('Cannot decode a method.');
  }
}

class VectorType<T extends List> extends FidlType<T> {
  const VectorType({
    this.element,
    this.maybeElementCount,
    this.nullable,
  }) : super(encodedSize: 16);

  final FidlType element;
  final int maybeElementCount;
  final bool nullable;

  @override
  void encode(Encoder encoder, T value, int offset) {
    validate(value);
    if (value == null) {
      encoder
        ..encodeUint64(0, offset) // count
        ..encodeUint64(kAllocAbsent, offset + 8); // data
    } else {
      final int count = value.length;
      encoder
        ..encodeUint64(count, offset) // count
        ..encodeUint64(kAllocPresent, offset + 8); // data
      int childOffset = encoder.alloc(count * element.encodedSize);
      element.encodeArray(encoder, value, childOffset);
    }
  }

  @override
  T decode(Decoder decoder, int offset) {
    final int count = decoder.decodeUint64(offset);
    final int data = decoder.decodeUint64(offset + 8);
    validateEncoded(count, data);
    if (data == kAllocAbsent) {
      return null;
    }
    final int base = decoder.claimMemory(count * element.encodedSize);
    return element.decodeArray(decoder, count, base);
  }

  void validate(T value) {
    if (value == null) {
      _throwIfNotNullable(nullable);
      return;
    }
    _throwIfExceedsLimit(value.length, maybeElementCount);
  }

  void validateEncoded(int count, int data) {
    if (data == kAllocAbsent) {
      _throwIfNotNullable(nullable);
      _throwIfNotZero(count);
    } else if (data == kAllocPresent) {
      _throwIfExceedsLimit(count, maybeElementCount);
    } else {
      throw new FidlError('Invalid vector encoding: $data.');
    }
  }
}

class ArrayType<T extends List> extends FidlType<T> {
  const ArrayType({
    this.element,
    this.elementCount,
  });

  final FidlType element;
  final int elementCount;

  @override
  int get encodedSize => elementCount * element.encodedSize;

  @override
  void encode(Encoder encoder, T value, int offset) {
    validate(value);
    element.encodeArray(encoder, value, offset);
  }

  @override
  T decode(Decoder decoder, int offset) {
    return element.decodeArray(decoder, elementCount, offset);
  }

  void validate(T value) {
    _throwIfCountMismatch(value.length, elementCount);
  }
}


<|start_filename|>dart/zircon/lib/src/vmo.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

part of zircon;

// ignore_for_file: public_member_api_docs

class Vmo extends _HandleWrapper<Vmo> {
  Vmo(Handle handle) : super(handle);

  GetSizeResult getSize() {
    if (handle == null) {
      return const GetSizeResult(ZX.ERR_INVALID_ARGS);
    }

    return System.vmoGetSize(handle);
  }

  int setSize(int size) {
    if (handle == null || size < 0) {
      return ZX.ERR_INVALID_ARGS;
    }

    return System.vmoSetSize(handle, size);
  }

  int write(ByteData data, [int vmoOffset = 0]) {
    if (handle == null) {
      return ZX.ERR_INVALID_ARGS;
    }

    return System.vmoWrite(handle, vmoOffset, data);
  }

  ReadResult read(int numBytes, [int vmoOffset = 0]) {
    if (handle == null) {
      return const ReadResult(ZX.ERR_INVALID_ARGS);
    }

    return System.vmoRead(handle, vmoOffset, numBytes);
  }

  /// Maps the Vmo into the process's root vmar, and returns it as a typed data
  /// array.
  ///
  /// The returned [Uint8List] is read-only. Attempts to write to it will
  /// result in an UnsupportedError exception.
  Uint8List map() {
    if (handle == null) {
      const int status = ZX.ERR_INVALID_ARGS;
      throw new ZxStatusException(status, getStringForStatus(status));
    }
    MapResult r = System.vmoMap(handle);
    if (r.status != ZX.OK) {
      throw new ZxStatusException(r.status, getStringForStatus(r.status));
    }
    return new UnmodifiableUint8ListView(r.data);
  }
}

class SizedVmo extends Vmo {
  final int _size;

  SizedVmo(Handle handle, this._size) : super(handle);

  /// Uses fdio_get_vmo_clone() to get a VMO for the file at `path` in the
  /// current Isolate's namespace.
  ///
  /// The returned Vmo is read-only.
  factory SizedVmo.fromFile(String path) {
    FromFileResult r = System.vmoFromFile(path);
    if (r.status != ZX.OK) {
      throw new ZxStatusException(r.status, getStringForStatus(r.status));
    }
    return new SizedVmo(r.handle, r.numBytes);
  }

  /// Constructs a VMO using the given [bytes]. The returned Vmo is read-only.
  factory SizedVmo.fromUint8List(Uint8List bytes) {
    HandleResult r = System.vmoCreate(bytes.length);
    if (r.status != ZX.OK) {
      throw new ZxStatusException(r.status, getStringForStatus(r.status));
    }
    return new SizedVmo(r.handle, bytes.length)
      ..write(bytes.buffer.asByteData());
  }

  /// Size of the Vmo in bytes.
  int get size => _size;
}


<|start_filename|>dart/fuchsia_services/lib/src/environment_service_connection.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:fidl/fidl.dart';

import 'service_connection.dart';
import 'startup_context.dart';

/// Connects to the environment service specified by [serviceProxy].
///
/// Environment services are services that are implemented by the framework
/// itself.
void connectToEnvironmentService<T>(AsyncProxy<T> serviceProxy) {
  if (serviceProxy == null) {
    throw Exception(
        'serviceProxy must not be null in call to connectToEnvironmentService');
  }
  // Creates an interface request and binds one of the channels. Binding this
  // channel prior to connecting to the agent allows the developer to make
  // proxy calls without awaiting for the connection to actually establish.
  final serviceProxyRequest = serviceProxy.ctrl.request();

  connectToService(
    StartupContext.fromStartupInfo().environmentServices,
    serviceProxy.ctrl.$serviceName,
    serviceProxy.ctrl.$interfaceName,
    serviceProxyRequest,
  ).catchError((e) {
    serviceProxyRequest.close();
    throw e;
  });
}


<|start_filename|>arch/x64/sysroot/include/values.h<|end_filename|>
#pragma once

#include <limits.h>

#define CHARBITS (sizeof(char) * 8)
#define SHORTBITS (sizeof(short) * 8)
#define INTBITS (sizeof(int) * 8)
#define LONGBITS (sizeof(long) * 8)
#define PTRBITS (sizeof(char*) * 8)
#define DOUBLEBITS (sizeof(double) * 8)
#define FLOATBITS (sizeof(float) * 8)

#define MINSHORT SHRT_MIN
#define MININT INT_MIN
#define MINLONG LONG_MIN

#define MAXSHORT SHRT_MAX
#define MAXINT INT_MAX
#define MAXLONG LONG_MAX

#define HIBITS MINSHORT
#define HIBITL MINLONG

#include <float.h>

#define MAXDOUBLE DBL_MAX
#undef MAXFLOAT
#define MAXFLOAT FLT_MAX
#define MINDOUBLE DBL_MIN
#define MINFLOAT FLT_MIN
#define DMINEXP DBL_MIN_EXP
#define FMINEXP FLT_MIN_EXP
#define DMAXEXP DBL_MAX_EXP
#define FMAXEXP FLT_MAX_EXP

#define BITSPERBYTE CHAR_BIT


<|start_filename|>arch/x64/sysroot/include/wordexp.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>

#define __NEED_size_t

#include <bits/alltypes.h>

#define WRDE_DOOFFS 1
#define WRDE_APPEND 2
#define WRDE_NOCMD 4
#define WRDE_REUSE 8
#define WRDE_SHOWERR 16
#define WRDE_UNDEF 32

typedef struct {
    size_t we_wordc;
    char** we_wordv;
    size_t we_offs;
} wordexp_t;

#define WRDE_NOSYS -1
#define WRDE_NOSPACE 1
#define WRDE_BADCHAR 2
#define WRDE_BADVAL 3
#define WRDE_CMDSUB 4
#define WRDE_SYNTAX 5

int wordexp(const char* __restrict, wordexp_t* __restrict, int);
void wordfree(wordexp_t*);

#ifdef __cplusplus
}
#endif


<|start_filename|>dart/fuchsia_modular/lib/src/module/internal/_module_impl.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:fidl/fidl.dart';
import 'package:fidl_fuchsia_modular/fidl_async.dart' as fidl;
import 'package:fidl_fuchsia_ui_viewsv1token/fidl_async.dart' as views_fidl;
import 'package:fuchsia_modular/lifecycle.dart';
import 'package:meta/meta.dart';

import '../embedded_module.dart';
import '../intent.dart';
import '../intent_handler.dart';
import '../module.dart';
import '../module_state_exception.dart';
import '_intent_handler_impl.dart';
import '_module_context.dart';

/// A concrete implementation of the [Module] interface. This class
/// is not intended to be used directly by authors but instead should
/// be used by the [Module] factory constructor.
class ModuleImpl implements Module {
  /// Holds a reference to the already registered intent handler
  IntentHandler _intentHandler;

  /// The intent handler host which will proxy intents to the registered
  /// intent handler
  // ignore: unused_field
  IntentHandlerImpl _intentHandlerImpl;

  /// Returns the [fidl.ModuleContext] for the running module.
  /// This variable should not be used directly. Use the
  /// [getContext()] method instead
  fidl.ModuleContext _moduleContext;

  /// The default constructor for this instance.
  ///
  /// the [moduleContext] is an optional parameter that
  /// can be supplied to override the default module context.
  /// This is mainly useful in testing scenarios.
  ModuleImpl({
    @required IntentHandlerImpl intentHandlerImpl,
    Lifecycle lifecycle,
    fidl.ModuleContext moduleContext,
  })  : _moduleContext = moduleContext,
        assert(intentHandlerImpl != null) {
    (lifecycle ??= Lifecycle()).addTerminateListener(_terminate);
    _intentHandlerImpl = intentHandlerImpl
      ..onHandleIntent = _proxyIntentToIntentHandler;
  }

  @override
  Future<fidl.ModuleController> addModuleToStory({
    @required String name,
    @required fidl.Intent intent,
    fidl.SurfaceRelation surfaceRelation = const fidl.SurfaceRelation(
      arrangement: fidl.SurfaceArrangement.copresent,
      dependency: fidl.SurfaceDependency.dependent,
      emphasis: 0.5,
    ),
  }) async {
    if (name == null || name.isEmpty) {
      throw ArgumentError.value(
          name, 'name', 'addModuleToStory should be called with a valid name');
    }
    if (intent == null) {
      throw ArgumentError.notNull('intent');
    }

    final moduleControllerProxy = fidl.ModuleControllerProxy();

    fidl.StartModuleStatus status = await _getContext().addModuleToStory(
        name, intent, moduleControllerProxy.ctrl.request(), surfaceRelation);

    _validateStartModuleStatus(status, name, intent);

    return moduleControllerProxy;
  }

  @override
  Future<EmbeddedModule> embedModule({
    @required String name,
    @required fidl.Intent intent,
  }) async {
    if (name == null || name.isEmpty) {
      throw ArgumentError.value(
          name, 'name', 'embedModule should be called with a valid name');
    }
    if (intent == null) {
      throw ArgumentError.notNull('intent');
    }

    final moduleController = fidl.ModuleControllerProxy();
    final viewOwner = new InterfacePair<views_fidl.ViewOwner>();
    final status = await _getContext().embedModule(
        name, intent, moduleController.ctrl.request(), viewOwner.passRequest());

    _validateStartModuleStatus(status, name, intent);

    return EmbeddedModule(
        moduleController: moduleController, viewOwner: viewOwner.passHandle());
  }

  @override
  void registerIntentHandler(IntentHandler intentHandler) {
    if (_intentHandler != null) {
      throw ModuleStateException(
          'Intent handler registration failed because a handler is already '
          'registered.');
    }

    _intentHandler = intentHandler;
  }

  @override
  void requestFocus() {
    _getContext().requestFocus();
  }

  @override
  void removeSelfFromStory() {
    _getContext().removeSelfFromStory();
  }

  fidl.ModuleContext _getContext() => _moduleContext ??= getModuleContext();

  void _proxyIntentToIntentHandler(Intent intent) {
    if (_intentHandler == null) {
      throw ModuleStateException(
          'Module received an intent but no intent handler was registered to '
          'receive it. If you do not intend to handle intents but you still '
          'need to use the module functionality register a NoopIntentHandler '
          'to explicitly declare that you will not handle the intent.');
    }
    _intentHandler.handleIntent(intent);
  }

  Future<void> _terminate() async {
    _intentHandler = null;
  }

  // any necessary cleanup should be done in this method.
  void _validateStartModuleStatus(
      fidl.StartModuleStatus status, String name, fidl.Intent intent) {
    switch (status) {
      case fidl.StartModuleStatus.success:
        break;
      case fidl.StartModuleStatus.noModulesFound:
        throw ModuleResolutionException(
            'no modules found for intent [$intent]');
        break;
      default:
        throw ModuleStateException(
            'unknown start module status [$status] for intent [$intent]');
    }
  }
}

/// When Module resolution fails.
class ModuleResolutionException implements Exception {
  /// Information about the failure.
  final String message;

  /// Create a new [ModuleResolutionException].
  ModuleResolutionException(this.message);
}


<|start_filename|>arch/x64/sysroot/include/bits/null.h<|end_filename|>
// Copyright 2017 The Fuchsia Authors
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT

#pragma once

// The compiler's <stddef.h> defines NULL without defining anything
// else if __need_NULL is defined first.
#define __need_NULL
#include <stddef.h>


<|start_filename|>pkg/fdio/include/lib/fdio/util.h<|end_filename|>
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

#include <zircon/types.h>
#include <zircon/compiler.h>
#include <stdint.h>
#include <unistd.h>

__BEGIN_CDECLS

// These routines are "internal" to fdio but used by some companion
// code like userboot and devmgr

typedef struct fdio fdio_t;

// Utilities to help assemble handles for a new process
// may return up to FDIO_MAX_HANDLES
zx_status_t fdio_clone_cwd(zx_handle_t* handles, uint32_t* types);
zx_status_t fdio_clone_fd(int fd, int newfd, zx_handle_t* handles, uint32_t* types);
zx_status_t fdio_transfer_fd(int fd, int newfd, zx_handle_t* handles, uint32_t* types);

// Attempt to create an fdio fd from some handles and their associated types,
// as returned from fdio_transfer_fd.
//
// Can only create fds around:
// - Remote IO objects
// - Pipes
// - Connected sockets
//
// This function transfers ownership of handles to the fd on success, and
// closes them on failure.
zx_status_t fdio_create_fd(zx_handle_t* handles, uint32_t* types, size_t hcount, int* fd_out);

// attempt to install a fdio in the unistd fd table
// if fd >= 0, request a specific fd, and starting_fd is ignored
// if fd < 0, request the first available fd >= starting_fd
// returns fd on success
// the fdio must have been upref'd on behalf of the fdtab first
int fdio_bind_to_fd(fdio_t* io, int fd, int starting_fd);

// attempt to detach an fdio_t from the fd table
// returns ZX_ERR_INVALID_ARGS if fd is out of range or doesn't exist
// returns ZX_ERR_UNAVAILABLE if the fd is busy or has been dup'd
// returns fdio_t via io_out with refcount 1 on success
zx_status_t fdio_unbind_from_fd(int fd, fdio_t** io_out);

// If this fd represents a "service" (an rpc channel speaking
// an unknown fidl protocol or a fuchsia.io.* protocol),
// this call will return ZX_OK and return the underlying handle.
// On both success and failure, the fd is effectively closed.
//
// ZX_ERR_NOT_SUPPORTED is returned if this fd does not represent
// a FIDL transport
//
// ZX_ERR_UNAVAILABLE is returned if this fd has been dup()'d and
// duplicates are sharing the FIDL transport
zx_status_t fdio_get_service_handle(int fd, zx_handle_t* out);

// creates a do-nothing fdio_t
fdio_t* fdio_null_create(void);

// Wraps a channel with an fdio_t using remote io.
// Takes ownership of h and e.
fdio_t* fdio_remote_create(zx_handle_t h, zx_handle_t event);

// creates a fdio that wraps a log object
// this will allocate a per-thread buffer (on demand) to assemble
// entire log-lines and flush them on newline or buffer full.
fdio_t* fdio_logger_create(zx_handle_t);

typedef struct zxio_storage zxio_storage_t;

// Creates an |fdio_t| that is backed by a |zxio_t|.
//
// The |zxio_t| is initialized with a null ops table. The |zxio_storage_t| for
// the |zxio_t| is returned via |out_storage|. The client can re-initialize the
// |zxio_storage_t| to customize the behavior of the |zxio_t|.
//
// To bind the |fdio_t| to a file descriptor, use |fdio_bind_to_fd|.
//
// Upon failure, returns NULL.
fdio_t* fdio_zxio_create(zxio_storage_t** out_storage);

// Attempt to connect a channel to a named service.
// On success the channel is connected.  On failure
// an error is returned and the handle is closed.
zx_status_t fdio_service_connect(const char* svcpath, zx_handle_t h);

// Attempt to connect a channel to a named service relative to dir.
// On success the channel is connected.  On failure
// an error is returned and the handle is closed.
zx_status_t fdio_service_connect_at(zx_handle_t dir, const char* path, zx_handle_t h);

// Same as |fdio_service_connect|, but allows the passing of flags.
zx_status_t fdio_open(const char* path, uint32_t zxflags, zx_handle_t h);

// Same as |fdio_service_connect_at, but allows the passing of flags.
zx_status_t fdio_open_at(zx_handle_t dir, const char* path, uint32_t zxflags, zx_handle_t h);

// Attempt to clone a service handle by doing a pipelined
// CLONE operation, returning the new channel endpoint,
// or ZX_HANDLE_INVALID.
zx_handle_t fdio_service_clone(zx_handle_t h);

// Attempt to clone a service handle by doing a pipelined
// CLONE operation, using the provided serving channel.
// On success srv is bound to a clone of h.  On failure
// an error is returned and srv is closed.
// Takes ownership of srv.
zx_status_t fdio_service_clone_to(zx_handle_t h, zx_handle_t srv);

__END_CDECLS


<|start_filename|>arch/x64/sysroot/include/sys/sendfile.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>
#include <unistd.h>

ssize_t sendfile(int, int, off_t*, size_t);

#ifdef __cplusplus
}
#endif


<|start_filename|>arch/x64/sysroot/include/zircon/driver/binding.h<|end_filename|>
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

#include <assert.h>
#include <zircon/compiler.h>
#include <stdalign.h>
#include <stddef.h>
#include <stdint.h>

__BEGIN_CDECLS;

// COAABBBB VVVVVVVV  Condition Opcode paramA paramB Value

#define OP_ABORT  0x0 // if (cond) return no-match
#define OP_MATCH  0x1 // if (cond) return match
#define OP_GOTO   0x2 // if (cond) advance to next LABEL(paramA)
#define OP_SET    0x3 // if (cond) flags |= paramA
#define OP_CLEAR  0x4 // if (cond) flags &= (~paramA)
#define OP_LABEL  0x5 // no-op, labels line with paramA

#define COND_AL   0x0 // true
#define COND_EQ   0x1 // bind(paramB) == Value
#define COND_NE   0x2 // bind(paramB) != Value
#define COND_GT   0x3 // bind(paramB) > Value
#define COND_LT   0x4 // bind(paramB) < Value
#define COND_GE   0x5 // bind(paramB) >= Value
#define COND_LE   0x6 // bind(paramB) <= Value
#define COND_MASK 0x7 // (bind(paramB) & Value) != 0
#define COND_BITS 0x8 // (bind(paramB) & Value) == Value

// branches are forward-only
// branches always go to the first matching LABEL
// branches that cannot find a matching LABEL are treated as ABORTs
// there is an implied unconditional ABORT after the last instruction
// flags are initially zero, may be set/cleared with SET/CLEAR
// flags may be tested by comparison against BIND_FLAGS

#define BINDINST(c,o,a,b,v) \
    { (((c)&0xF)<<28)|(((o)&0xF)<<24)|(((a)&0xFF)<<16)|((b)&0xFFFF),(v) }

#define BINDINST_CC(n) ((n) >> 28)
#define BINDINST_OP(n) (((n) >> 24) & 0xF)
#define BINDINST_PA(n) (((n) >> 16) & 0xFF)
#define BINDINST_PB(n) ((n) & 0xFFFF)

#define BI_ABORT()            BINDINST(COND_AL,OP_ABORT,0,0,0)
#define BI_MATCH()            BINDINST(COND_AL,OP_MATCH,0,0,0)
#define BI_GOTO(n)            BINDINST(COND_AL,OP_GOTO,n,0,0)
#define BI_SET(f)             BINDINST(COND_AL,OP_SET,f,0,0)
#define BI_CLEAR(f)           BINDINST(COND_AL,OP_CLEAR,f,0,0)
#define BI_LABEL(n)           BINDINST(COND_AL,OP_LABEL,n,0,0)

#define BI_ABORT_IF(c,b,v)    BINDINST(COND_##c,OP_ABORT,0,b,v)
#define BI_MATCH_IF(c,b,v)    BINDINST(COND_##c,OP_MATCH,0,b,v)
#define BI_GOTO_IF(c,b,v,n)   BINDINST(COND_##c,OP_GOTO,n,b,v)
#define BI_SET_IF(c,b,v,f)    BINDINST(COND_##c,OP_SET,f,b,v)
#define BI_CLEAR_IF(c,b,v,f)  BINDINST(COND_##c,OP_CLEAR,f,b,v)

// for drivers that only want to be bound on user request
#define BI_ABORT_IF_AUTOBIND  BI_ABORT_IF(NE, BIND_AUTOBIND, 0)

// global binding variables at 0x00XX
#define BIND_FLAGS            0x0000 // value of the flags register
#define BIND_PROTOCOL         0x0001 // primary protcol of the device
#define BIND_AUTOBIND         0x0002 // if this is an automated bind/load

// pci binding variables at 0x01XX
#define BIND_PCI_VID          0x0100
#define BIND_PCI_DID          0x0101
#define BIND_PCI_CLASS        0x0102
#define BIND_PCI_SUBCLASS     0x0103
#define BIND_PCI_INTERFACE    0x0104
#define BIND_PCI_REVISION     0x0105
#define BIND_PCI_BDF_ADDR     0x0106

// pci binding variable utils
#define BIND_PCI_BDF_PACK(bus, dev, func) \
    ((((uint32_t)(bus)  & 0xFF) << 8) |   \
     (((uint32_t)(dev)  & 0x1F) << 3) |   \
      ((uint32_t)(func) & 0x07))

#define BIND_PCI_BDF_UNPACK_BUS(bdf) (((uint32_t)(bdf) >> 8) & 0xFF)
#define BIND_PCI_BDF_UNPACK_DEV(bdf) (((uint32_t)(bdf) >> 3) & 0x1F)
#define BIND_PCI_BDF_UNPACK_FUNC(bdf) ((uint32_t)(bdf) & 0x07)

// usb binding variables at 0x02XX
// these are used for both ZX_PROTOCOL_USB and ZX_PROTOCOL_USB_FUNCTION
#define BIND_USB_VID          0x0200
#define BIND_USB_PID          0x0201
#define BIND_USB_CLASS        0x0202
#define BIND_USB_SUBCLASS     0x0203
#define BIND_USB_PROTOCOL     0x0204

// Platform bus binding variables at 0x03XX
#define BIND_PLATFORM_DEV_VID 0x0300
#define BIND_PLATFORM_DEV_PID 0x0301
#define BIND_PLATFORM_DEV_DID 0x0302
#define BIND_PLATFORM_PROTO   0x0303

// ACPI binding variables at 0x04XX
// The _HID is a 7- or 8-byte string. Because a bind property is 32-bit, use 2
// properties to bind using the _HID. They are encoded in big endian order for
// human readability. In the case of 7-byte _HID's, the 8th-byte shall be 0.
#define BIND_ACPI_HID_0_3      0x0400 // char 0-3
#define BIND_ACPI_HID_4_7      0x0401 // char 4-7
// The _CID may be a valid HID value or a bus-specific string. The ACPI bus
// driver only publishes those that are valid HID values.
#define BIND_ACPI_CID_0_3      0x0402 // char 0-3
#define BIND_ACPI_CID_4_7      0x0403 // char 4-7

// Intel HDA Codec binding variables at 0x05XX
#define BIND_IHDA_CODEC_VID         0x0500
#define BIND_IHDA_CODEC_DID         0x0501
#define BIND_IHDA_CODEC_MAJOR_REV   0x0502
#define BIND_IHDA_CODEC_MINOR_REV   0x0503
#define BIND_IHDA_CODEC_VENDOR_REV  0x0504
#define BIND_IHDA_CODEC_VENDOR_STEP 0x0505

// Serial binding variables at 0x06XX
#define BIND_SERIAL_CLASS           0x0600
#define BIND_SERIAL_VID             0x0601
#define BIND_SERIAL_PID             0x0602

// NAND binding variables at 0x07XX
#define BIND_NAND_CLASS             0x0700

// Bluetooth binding variables at 0x08XX
#define BIND_BT_GATT_SVC_UUID16     0x0800
// 128-bit UUID is split across 4 32-bit unsigned ints
#define BIND_BT_GATT_SVC_UUID128_1     0x0801
#define BIND_BT_GATT_SVC_UUID128_2     0x0802
#define BIND_BT_GATT_SVC_UUID128_3     0x0803
#define BIND_BT_GATT_SVC_UUID128_4     0x0804

// SDIO binding variables at 0x09XX
#define BIND_SDIO_VID             0x0900
#define BIND_SDIO_PID             0x0901

// I2C binding variables at 0x0AXX
#define BIND_I2C_CLASS            0x0A00

// TEMPORARY binding variables at 0xfXX
// I2C_ADDR is a temporary way to bind the i2c touchscreen on the Acer12. This
// binding will eventually be made via some sort of ACPI device enumeration.
#define BIND_I2C_ADDR         0x0f00

typedef struct zx_bind_inst {
    uint32_t op;
    uint32_t arg;
} zx_bind_inst_t;

typedef struct zx_device_prop {
    uint16_t id;
    uint16_t reserved;
    uint32_t value;
} zx_device_prop_t;

// simple example
#if 0
zx_bind_inst_t i915_binding[] = {
    BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_PCI),
    BI_ABORT_IF(NE, BIND_PCI_VID, 0x8086),
    BI_MATCH_IF(EQ, BIND_PCI_DID, 0x1616), // broadwell
    BI_MATCH_IF(EQ, BIND_PCI_DID, 0x1916), // skylake
    BI_ABORT(),
};
#endif

#define ZIRCON_NOTE_NAME "Zircon"
#define ZIRCON_NOTE_DRIVER 0x31565244 // DRV1

typedef struct {
    // Elf64_Nhdr fields:
    uint32_t namesz;
    uint32_t descsz;
    uint32_t type;
    // ELF note name.  namesz is the exact size of the name (including '\0'),
    // but the storage size is always rounded up to a multiple of 4 bytes.
    char name[(sizeof(ZIRCON_NOTE_NAME) + 3) & -4];
} zircon_driver_note_header_t;

#define ZIRCON_DRIVER_NOTE_HEADER_INIT(object) {        \
        /* .namesz = */ sizeof(ZIRCON_NOTE_NAME),              \
        /* .descsz = */ (sizeof(object) -                       \
                         sizeof(zircon_driver_note_header_t)), \
        /* .type = */ ZIRCON_NOTE_DRIVER,                      \
        /* .name = */ ZIRCON_NOTE_NAME,                        \
    }

typedef struct {
    // See flag bits below.
    uint32_t flags;

    // Driver Metadata
    uint32_t bindcount;
    uint32_t reserved0;
    char name[32];
    char vendor[16];
    char version[16];

    // Driver Bind Program follows
} zircon_driver_note_payload_t;

// Flag bits in the driver note:

// Driver is built with `-fsanitize=address` and can only be loaded into a
// devhost that supports the ASan runtime.
#define ZIRCON_DRIVER_NOTE_FLAG_ASAN (1u << 0)

#define ZIRCON_DRIVER_NOTE_PAYLOAD_INIT(Driver,VendorName,Version,BindCount) \
    {                                                               \
        /* .flags = */ ZIRCON_DRIVER_NOTE_FLAGS,                    \
        /* .bindcount = */ (BindCount),                             \
        /* .reserved0 = */ 0,                                       \
        /* .name = */ #Driver,                                      \
        /* .vendor = */ VendorName,                                 \
        /* .version = */ Version,                                   \
    }

#define ZIRCON_DRIVER_NOTE_FLAGS \
    (__has_feature(address_sanitizer) ? ZIRCON_DRIVER_NOTE_FLAG_ASAN : 0)

typedef struct {
    zircon_driver_note_header_t header;
    zircon_driver_note_payload_t payload;
} zircon_driver_note_t;

static_assert(offsetof(zircon_driver_note_t, payload) ==
              sizeof(zircon_driver_note_header_t),
              "alignment snafu?");

// Without this, ASan will add redzone padding after the object, which
// would make it invalid ELF note format.
#if __has_feature(address_sanitizer)
# define ZIRCON_DRIVER_NOTE_ASAN __attribute__((no_sanitize("address")))
#else
# define ZIRCON_DRIVER_NOTE_ASAN
#endif

// GCC has a quirk about how '__attribute__((visibility("default")))'
// (__EXPORT here) works for const variables in C++.  The attribute has no
// effect when used on the definition of a const variable, and GCC gives a
// warning/error about that.  The attribute must appear on the "extern"
// declaration of the variable instead.

// We explicitly align the note to 4 bytes.  That's its natural alignment
// anyway, but the compilers sometimes like to over-align as an
// optimization while other tools sometimes like to complain if SHT_NOTE
// sections are over-aligned (since this could result in padding being
// inserted that makes it violate the ELF note format).  Standard C11
// doesn't permit alignas(...) on a type but we could use __ALIGNED(4) on
// all the types (i.e. GNU __attribute__ syntax instead of C11 syntax).
// But the alignment of the types is not actually the issue: it's the
// compiler deciding to over-align the individual object regardless of its
// type's alignment, so we have to explicitly set the alignment of the
// object to defeat any compiler default over-alignment.

#define ZIRCON_DRIVER_BEGIN(Driver,Ops,VendorName,Version,BindCount) \
zx_driver_rec_t __zircon_driver_rec__ __EXPORT = {\
    /* .ops = */ &(Ops),\
    /* .driver = */ NULL,\
    /* .log_flags = */ 7, /* DDK_LOG_ERROR | DDK_LOG_WARN | DDK_LOG_INFO */\
};\
extern const struct zircon_driver_note __zircon_driver_note__ __EXPORT;\
alignas(4) __SECTION(".note.zircon.driver." #Driver) ZIRCON_DRIVER_NOTE_ASAN \
const struct zircon_driver_note {\
    zircon_driver_note_t note;\
    zx_bind_inst_t binding[BindCount];\
} __zircon_driver_note__ = {\
    /* .note = */{\
        ZIRCON_DRIVER_NOTE_HEADER_INIT(__zircon_driver_note__),\
        ZIRCON_DRIVER_NOTE_PAYLOAD_INIT(Driver,VendorName,Version,BindCount),\
    },\
    /* .binding = */ {

#define ZIRCON_DRIVER_END(Driver) }};

//TODO: if we moved the Ops from the BEGIN() to END() macro we
//      could add a zircon_driver_note_t* to the zx_driver_rec_t,
//      define it in END(), and have only one symbol to dlsym()
//      when loading drivers

__END_CDECLS;


<|start_filename|>pkg/fdio/include/lib/fdio/io.h<|end_filename|>
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

#include <limits.h>
#include <poll.h>
#include <stdbool.h>
#include <unistd.h> // for ssize_t

#include <zircon/types.h>
#include <zircon/compiler.h>

#include <lib/fdio/limits.h>

// flag on handle args in processargs
// instructing that this fd should be dup'd to 0/1/2
// and be used for all of stdio
#define FDIO_FLAG_USE_FOR_STDIO 0x8000

// events for fdio_wait_fd()
#define FDIO_EVT_READABLE POLLIN
#define FDIO_EVT_WRITABLE POLLOUT
#define FDIO_EVT_ERROR POLLERR
#define FDIO_EVT_PEER_CLOSED POLLRDHUP
#define FDIO_EVT_ALL (POLLIN | POLLOUT | POLLERR | POLLRDHUP)

__BEGIN_CDECLS

// wait until one or more events are pending
zx_status_t fdio_wait_fd(int fd, uint32_t events, uint32_t* pending, zx_time_t deadline);

// create a fd that works with wait APIs (epoll, select, etc.) from a handle
// and expected signals (signals_in/signals_out correspond to POLLIN/POLLOUT
// events respectively). The handle will be closed when the fd is closed, unless
// shared_handle is true.
int fdio_handle_fd(zx_handle_t h, zx_signals_t signals_in, zx_signals_t signals_out, bool shared_handle);

// invoke a raw fdio ioctl
ssize_t fdio_ioctl(int fd, int op, const void* in_buf, size_t in_len, void* out_buf, size_t out_len);

// create a pipe, installing one half in a fd, returning the other
// for transport to another process
zx_status_t fdio_pipe_half(zx_handle_t* handle, uint32_t* type);

// Get a read-only VMO containing the whole contents of the file.
// This function creates a clone of the underlying VMO when possible, falling
// back to eagerly reading the contents into a freshly-created VMO.
zx_status_t fdio_get_vmo_copy(int fd, zx_handle_t* out_vmo);

// Gets a read-only VMO containing a clone of the underlying VMO.
// This function will fail rather than copying the contents if it cannot clone.
zx_status_t fdio_get_vmo_clone(int fd, zx_handle_t* out_vmo);

// Get a read-only handle to the exact VMO used by the file system server to
// represent the file. This function fails if the server does not have an exact
// VMO representation of the file (e.g., if fdio_get_vmo would need to copy
// or clone data into a new VMO).
zx_status_t fdio_get_vmo_exact(int fd, zx_handle_t* out_vmo);

__END_CDECLS


<|start_filename|>arch/x64/sysroot/include/fcntl.h<|end_filename|>
#pragma once

#ifdef __cplusplus
extern "C" {
#endif

#include <features.h>

#define __NEED_off_t
#define __NEED_pid_t
#define __NEED_mode_t

#ifdef _GNU_SOURCE
#define __NEED_size_t
#define __NEED_ssize_t
#define __NEED_struct_iovec
#endif

#include <bits/alltypes.h>

struct flock {
    short l_type;
    short l_whence;
    off_t l_start;
    off_t l_len;
    pid_t l_pid;
};

int creat(const char*, mode_t);
int fcntl(int, int, ...);
int open(const char*, int, ...);
int openat(int, const char*, int, ...);
int posix_fadvise(int, off_t, off_t, int);
int posix_fallocate(int, off_t, off_t);

#define O_SEARCH O_PATH
#define O_EXEC O_PATH

// clang-format off
#define O_ACCMODE          (03 | O_SEARCH)
#define O_RDONLY            00
#define O_WRONLY            01
#define O_RDWR              02

// Flags which align with ZXIO_FS_*
// system/ulib/fdio/unistd.c asserts that these flags are aligned
// with the ZXIO_FS_* versions.
#define O_CREAT     0x00010000
#define O_EXCL      0x00020000
#define O_TRUNC     0x00040000
#define O_DIRECTORY 0x00080000
#define O_APPEND    0x00100000
#define O_PATH      0x00400000
#ifdef _ALL_SOURCE
#define O_NOREMOTE  0x00200000
#define O_ADMIN     0x00000004
#define O_PIPELINE  0x80000000
#endif

// Flags which do not align with ZXIO_FS_*
#define O_NONBLOCK  0x00000010
#define O_DSYNC     0x00000020
#define O_SYNC      (0x00000040 | O_DSYNC)
#define O_RSYNC     O_SYNC
#define O_NOFOLLOW  0x00000080
#define O_CLOEXEC   0x00000100
#define O_NOCTTY    0x00000200
#define O_ASYNC     0x00000400
#define O_DIRECT    0x00000800
#define O_LARGEFILE 0x00001000
#define O_NOATIME   0x00002000
#define O_TMPFILE   0x00004000

// clang-format on

#define O_NDELAY O_NONBLOCK

#define F_DUPFD 0
#define F_GETFD 1
#define F_SETFD 2
#define F_GETFL 3
#define F_SETFL 4

#define F_GETLK 5
#define F_SETLK 6
#define F_SETLKW 7

#define F_SETOWN 8
#define F_GETOWN 9
#define F_SETSIG 10
#define F_GETSIG 11

#define F_SETOWN_EX 15
#define F_GETOWN_EX 16

#define F_GETOWNER_UIDS 17

#define F_OFD_GETLK 36
#define F_OFD_SETLK 37
#define F_OFD_SETLKW 38

#define F_DUPFD_CLOEXEC 1030

#define F_RDLCK 0
#define F_WRLCK 1
#define F_UNLCK 2

#define FD_CLOEXEC 1

#define AT_FDCWD (-100)
#define AT_SYMLINK_NOFOLLOW 0x100
#define AT_REMOVEDIR 0x200
#define AT_SYMLINK_FOLLOW 0x400
#define AT_EACCESS 0x200

#define POSIX_FADV_NORMAL 0
#define POSIX_FADV_RANDOM 1
#define POSIX_FADV_SEQUENTIAL 2
#define POSIX_FADV_WILLNEED 3
#define POSIX_FADV_DONTNEED 4
#define POSIX_FADV_NOREUSE 5

#undef SEEK_SET
#undef SEEK_CUR
#undef SEEK_END
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2

#ifndef S_IRUSR
#define S_ISUID 04000
#define S_ISGID 02000
#define S_ISVTX 01000
#define S_IRUSR 0400
#define S_IWUSR 0200
#define S_IXUSR 0100
#define S_IRWXU 0700
#define S_IRGRP 0040
#define S_IWGRP 0020
#define S_IXGRP 0010
#define S_IRWXG 0070
#define S_IROTH 0004
#define S_IWOTH 0002
#define S_IXOTH 0001
#define S_IRWXO 0007
#endif

#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
#define AT_NO_AUTOMOUNT 0x800
#define AT_EMPTY_PATH 0x1000

#define FAPPEND O_APPEND
#define FFSYNC O_FSYNC
#define FASYNC O_ASYNC
#define FNONBLOCK O_NONBLOCK
#define FNDELAY O_NDELAY

#define F_OK 0
#define R_OK 4
#define W_OK 2
#define X_OK 1
#define F_ULOCK 0
#define F_LOCK 1
#define F_TLOCK 2
#define F_TEST 3

#define F_SETLEASE 1024
#define F_GETLEASE 1025
#define F_NOTIFY 1026
#define F_CANCELLK 1029
#define F_SETPIPE_SZ 1031
#define F_GETPIPE_SZ 1032
#define F_ADD_SEALS 1033
#define F_GET_SEALS 1034

#define F_SEAL_SEAL 0x0001
#define F_SEAL_SHRINK 0x0002
#define F_SEAL_GROW 0x0004
#define F_SEAL_WRITE 0x0008

#define DN_ACCESS 0x00000001
#define DN_MODIFY 0x00000002
#define DN_CREATE 0x00000004
#define DN_DELETE 0x00000008
#define DN_RENAME 0x00000010
#define DN_ATTRIB 0x00000020
#define DN_MULTISHOT 0x80000000

int lockf(int, int, off_t);
#endif

#if defined(_GNU_SOURCE)
#define F_OWNER_TID 0
#define F_OWNER_PID 1
#define F_OWNER_PGRP 2
#define F_OWNER_GID 2
struct f_owner_ex {
    int type;
    pid_t pid;
};
#define FALLOC_FL_KEEP_SIZE 1
#define FALLOC_FL_PUNCH_HOLE 2
#define SYNC_FILE_RANGE_WAIT_BEFORE 1
#define SYNC_FILE_RANGE_WRITE 2
#define SYNC_FILE_RANGE_WAIT_AFTER 4
#define SPLICE_F_MOVE 1
#define SPLICE_F_NONBLOCK 2
#define SPLICE_F_MORE 4
#define SPLICE_F_GIFT 8
int fallocate(int, int, off_t, off_t);
#define fallocate64 fallocate
ssize_t readahead(int, off_t, size_t);
int sync_file_range(int, off_t, off_t, unsigned);
ssize_t vmsplice(int, const struct iovec*, size_t, unsigned);
ssize_t splice(int, off_t*, int, off_t*, size_t, unsigned);
ssize_t tee(int, int, size_t, unsigned);
#define loff_t off_t
#endif

#ifdef __cplusplus
}
#endif


<|start_filename|>dart/fidl/lib/src/union.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'hash_codes.dart';

abstract class Union {
  const Union();

  int get $index;
  Object get $data;

  @override
  int get hashCode => deepHash([$index, $data]);

  @override
  bool operator ==(dynamic other) {
    if (identical(this, other)) {
      return true;
    }
    if (runtimeType != other.runtimeType) {
      return false;
    }
    final Union otherUnion = other;
    if ($index != otherUnion.$index) {
      return false;
    }
    if ($data is Iterable) {
      return deepEquals($data, otherUnion.$data);
    } else {
      return $data == otherUnion.$data;
    }
  }
}

typedef UnionFactory<T> = T Function(int index, Object data);


<|start_filename|>dart/fuchsia_services/lib/src/service_connection.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:fidl/fidl.dart';
import 'package:fidl_fuchsia_sys/fidl_async.dart' as fidl_sys;

/// Connects to the specified service using the given [serviceProvider].
///
/// It is recommended to not use this method directly but rather to use the
/// connectToEnvironmentService method or a higher level method instead.
Future<void> connectToService<T>(
  fidl_sys.ServiceProvider serviceProvider,
  String serviceName,
  String interfaceName,
  InterfaceRequest<T> interfaceRequest,
) async {
  if (serviceName == null) {
    throw Exception("$interfaceName's "
        'proxyServiceController.\$serviceName must not be null. Check the FIDL '
        'file for a missing [Discoverable]');
  }

  return serviceProvider.connectToService(
      serviceName, interfaceRequest.passChannel());
}


<|start_filename|>dart/fuchsia_modular/lib/src/proposal/internal/_proposal_listener_impl.dart<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:fidl_fuchsia_modular/fidl_async.dart' as fuchsia_modular;

/// A class which implements the [fuchsia_modular.ProposalListener] interface
/// and calls a callback when the proposal is accepted.
class ProposalListenerImpl implements fuchsia_modular.ProposalListener {
  final void Function(String, String) _onProposalAccepted;

  /// The default constructor
  ProposalListenerImpl(this._onProposalAccepted);

  @override
  Future<void> onProposalAccepted(String proposalId, String storyId) async {
    if (_onProposalAccepted != null) {
      _onProposalAccepted(proposalId, storyId);
    }
  }
}


<|start_filename|>arch/x64/sysroot/include/zircon/boot/driver-config.h<|end_filename|>
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#pragma once

#include <zircon/compiler.h>
#include <stdint.h>

// BOOTDATA_KERNEL_DRIVER bootdata types
#define KDRV_ARM_PSCI           0x49435350  // 'PSCI'
#define KDRV_ARM_GIC_V2         0x32434947  // 'GIC2'
#define KDRV_ARM_GIC_V3         0x33434947  // 'GIC3'
#define KDRV_ARM_GENERIC_TIMER  0x4D495441  // 'ATIM'
#define KDRV_PL011_UART         0x55304C50  // 'PL0U'
#define KDRV_AMLOGIC_UART       0x554C4D41  // 'AMLU'
#define KDRV_NXP_IMX_UART       0x55584D49  // 'IMXU'
#define KDRV_MT8167_UART        0x5538544D  // 'MT8U'
#define KDRV_HISILICON_POWER    0x4F505348  // 'HSPO'
#define KDRV_AMLOGIC_HDCP       0x484C4D41  // 'AMLH'

// kernel driver struct that can be used for simple drivers
// used by KDRV_PL011_UART, KDRV_AMLOGIC_UART and KDRV_NXP_IMX_UART
typedef struct {
    uint64_t mmio_phys;
    uint32_t irq;
} dcfg_simple_t;

// for KDRV_MT8167_UART
typedef struct {
    uint64_t soc_mmio_phys;
    uint64_t uart_mmio_phys;
    uint32_t irq;
} dcfg_soc_uart_t;

// for KDRV_ARM_PSCI
typedef struct {
    bool use_hvc;
    uint64_t shutdown_args[3];
    uint64_t reboot_args[3];
    uint64_t reboot_bootloader_args[3];
    uint64_t reboot_recovery_args[3];
} dcfg_arm_psci_driver_t;

// for KDRV_ARM_GIC_V2
typedef struct {
    uint64_t mmio_phys;
    uint64_t msi_frame_phys;
    uint64_t gicd_offset;
    uint64_t gicc_offset;
    uint64_t gich_offset;
    uint64_t gicv_offset;
    uint32_t ipi_base;
    bool optional;
    bool use_msi;
} dcfg_arm_gicv2_driver_t;

// for KDRV_ARM_GIC_V3
typedef struct {
    uint64_t mmio_phys;
    uint64_t gicd_offset;
    uint64_t gicr_offset;
    uint64_t gicr_stride;
    uint64_t mx8_gpr_phys;
    uint32_t ipi_base;
    bool optional;
} dcfg_arm_gicv3_driver_t;

// for KDRV_ARM_GENERIC_TIMER
typedef struct {
    uint32_t irq_phys;
    uint32_t irq_virt;
    uint32_t irq_sphys;
    uint32_t freq_override;
} dcfg_arm_generic_timer_driver_t;

// for KDRV_HISILICON_POWER
typedef struct {
    uint64_t sctrl_phys;
    uint64_t pmu_phys;
} dcfg_hisilicon_power_driver_t;

// for KDRV_AMLOGIC_HDCP
typedef struct {
    uint64_t preset_phys;
    uint64_t hiu_phys;
    uint64_t hdmitx_phys;
} dcfg_amlogic_hdcp_driver_t;
