repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
MistEO/meojson
include/json.h
<filename>include/json.h #pragma once #include "json_parser.h" #include "json_value.h" #include "json_object.h" #include "json_array.h" #include "json_exception.h"
MistEO/meojson
include/json_array.h
#pragma once #include <string> #include <vector> #include <initializer_list> namespace json { class value; class array { public: using raw_array = std::vector<value>; using iterator = raw_array::iterator; using const_iterator = raw_array::const_iterator; using reverse_iterator = raw_array::reverse_iterator; using const_reverse_iterator = raw_array::const_reverse_iterator; array() = default; array(const array& rhs) = default; array(array&& rhs) noexcept = default; array(const raw_array& arr); array(raw_array&& arr) noexcept; array(std::initializer_list<raw_array::value_type> init_list); template<typename ArrayType> array(ArrayType arr) { static_assert( std::is_constructible<json::value, typename ArrayType::value_type>::value, "Parameter can't be used to construct a json::value"); for (auto&& ele : arr) { _array_data.emplace_back(std::move(ele)); } } ~array() noexcept = default; bool empty() const noexcept { return _array_data.empty(); } size_t size() const noexcept { return _array_data.size(); } bool exist(size_t pos) const { return _array_data.size() < pos; } const value& at(size_t pos) const; const std::string to_string() const; const std::string format(std::string shift_str = " ", size_t basic_shift_count = 0) const; const bool get(size_t pos, bool default_value) const; const int get(size_t pos, int default_value) const; const long get(size_t pos, long default_value) const; const unsigned long get(size_t pos, unsigned default_value) const; const long long get(size_t pos, long long default_value) const; const unsigned long long get(size_t pos, unsigned long long default_value) const; const float get(size_t pos, float default_value) const; const double get(size_t pos, double default_value) const; const long double get(size_t pos, long double default_value) const; const std::string get(size_t pos, std::string default_value) const; const std::string get(size_t pos, const char* default_value) const; template <typename... Args> decltype(auto) emplace_back(Args &&... args) { static_assert( std::is_constructible<raw_array::value_type, Args...>::value, "Parameter can't be used to construct a raw_array::value_type"); return _array_data.emplace_back(std::forward<Args>(args)...); } void clear() noexcept; // void earse(size_t pos); iterator begin() noexcept; iterator end() noexcept; const_iterator begin() const noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; reverse_iterator rbegin() noexcept; reverse_iterator rend() noexcept; const_reverse_iterator rbegin() const noexcept; const_reverse_iterator rend() const noexcept; const_reverse_iterator crbegin() const noexcept; const_reverse_iterator crend() const noexcept; const value& operator[](size_t pos) const; value& operator[](size_t pos); array& operator=(const array&) = default; array& operator=(array&&) noexcept = default; // const raw_array &raw_data() const; private: raw_array _array_data; }; std::ostream& operator<<(std::ostream& out, const array& arr); } // namespace json
MistEO/meojson
include/json_object.h
#pragma once #include <string> #include <unordered_map> #include <initializer_list> #include "json_value.h" namespace json { class object { public: using raw_object = std::unordered_map<std::string, value>; using iterator = raw_object::iterator; using const_iterator = raw_object::const_iterator; object() = default; object(const object& rhs) = default; object(object&& rhs) = default; object(const raw_object& raw_obj); object(raw_object&& raw_obj); object(std::initializer_list<raw_object::value_type> init_list); template<typename MapType> object(MapType map) { static_assert( std::is_constructible<raw_object::value_type, typename MapType::value_type>::value, "Parameter can't be used to construct a json::object::raw_object::value_type"); for (auto&& ele : map) { _object_data.emplace(std::move(ele)); } } ~object() = default; bool empty() const noexcept { return _object_data.empty(); } size_t size() const noexcept { return _object_data.size(); } bool exist(const std::string& key) const { return _object_data.find(key) != _object_data.cend(); } const value& at(const std::string& key) const; const std::string to_string() const; const std::string format(std::string shift_str = " ", size_t basic_shift_count = 0) const; const bool get(const std::string& key, bool default_value) const; const int get(const std::string& key, int default_value) const; const long get(const std::string& key, long default_value) const; const unsigned long get(const std::string& key, unsigned default_value) const; const long long get(const std::string& key, long long default_value) const; const unsigned long long get(const std::string& key, unsigned long long default_value) const; const float get(const std::string& key, float default_value) const; const double get(const std::string& key, double default_value) const; const long double get(const std::string& key, long double default_value) const; const std::string get(const std::string& key, std::string default_value) const; const std::string get(const std::string& key, const char* default_value) const; template <typename... Args> decltype(auto) emplace(Args &&... args) { static_assert( std::is_constructible<raw_object::value_type, Args...>::value, "Parameter can't be used to construct a raw_object::value_type"); return _object_data.emplace(std::forward<Args>(args)...); } void clear() noexcept; bool earse(const std::string& key); iterator begin() noexcept; iterator end() noexcept; const_iterator begin() const noexcept; const_iterator end() const noexcept; const_iterator cbegin() const noexcept; const_iterator cend() const noexcept; value& operator[](const std::string& key); value& operator[](std::string&& key); object& operator=(const object&) = default; object& operator=(object&&) = default; // const raw_object &raw_data() const; private: raw_object _object_data; }; std::ostream& operator<<(std::ostream& out, const json::object& obj); } // namespace json
MistEO/meojson
include/json_aux.h
<filename>include/json_aux.h #pragma once #include <string> #include "json_value.h" namespace json { static std::string unescape_string(std::string&& str) { std::string replace_str; std::string escape_str = std::move(str); for (size_t pos = 0; pos < escape_str.size(); ++pos) { switch (escape_str[pos]) { case '\"': replace_str = R"(\")"; break; case '\\': replace_str = R"(\\)"; break; case '\b': replace_str = R"(\b)"; break; case '\f': replace_str = R"(\f)"; break; case '\n': replace_str = R"(\n)"; break; case '\r': replace_str = R"(\r)"; break; case '\t': replace_str = R"(\t)"; break; default: continue; break; } escape_str.replace(pos, 1, replace_str); ++pos; } return escape_str; } static std::string unescape_string(const std::string& str) { return unescape_string(std::string(str)); } static std::string escape_string(std::string&& str) { std::string escape_str = std::move(str); for (size_t pos = 0; pos + 1 < escape_str.size(); ++pos) { if (escape_str[pos] != '\\') { continue; } std::string replace_str; switch (escape_str[pos + 1]) { case '"': replace_str = "\""; break; case '\\': replace_str = "\\"; break; case 'b': replace_str = "\b"; break; case 'f': replace_str = "\f"; break; case 'n': replace_str = "\n"; break; case 'r': replace_str = "\r"; break; case 't': replace_str = "\t"; break; default: return std::string(); break; } escape_str.replace(pos, 2, replace_str); } return escape_str; } static std::string escape_string(const std::string& str) { return escape_string(std::string(str)); } }
MistEO/meojson
include/json_value.h
<reponame>MistEO/meojson<filename>include/json_value.h<gh_stars>10-100 #pragma once #include <string> #include <ostream> // #include <iostream> #include <memory> namespace json { enum class value_type : char { Invalid, Null, Boolean, String, Number, Array, Object, NUM_T }; class array; class object; class value { using unique_array = std::unique_ptr<array>; using unique_object = std::unique_ptr<object>; public: value(); value(const value& rhs); value(value&& rhs) noexcept; value(bool b); value(int num); value(unsigned num); value(long num); value(unsigned long num); value(long long num); value(unsigned long long num); value(float num); value(double num); value(long double num); value(const char* str); value(const std::string& str); value(std::string&& str); value(const array& arr); value(array&& arr); // value(std::initializer_list<value> init_list); // for array value(const object& obj); value(object&& obj); // error: conversion from ‘<brace-enclosed initializer list>’ to ‘json::value’ is ambiguous // value(std::initializer_list<std::pair<std::string, value>> init_list); // for object // Constructed from raw data template <typename... Args> value(value_type type, Args &&...args) : _type(type), _raw_data(std::forward<Args>(args)...) { static_assert( std::is_constructible<std::string, Args...>::value, "Parameter can't be used to construct a std::string"); } // Prohibit conversion of other types to value template <typename T> value(T) = delete; ~value(); bool valid() const noexcept { return _type != value_type::Invalid ? true : false; } bool empty() const noexcept { return (_type == value_type::Null && _raw_data.compare("null") == 0) ? true : false; } bool is_null() const noexcept { return empty(); } bool is_number() const noexcept { return _type == value_type::Number; } bool is_boolean() const noexcept { return _type == value_type::Boolean; } bool is_string() const noexcept { return _type == value_type::String; } bool is_array() const noexcept { return _type == value_type::Array; } bool is_object() const noexcept { return _type == value_type::Object; } bool exist(const std::string& key) const; bool exist(size_t pos) const; value_type type() const noexcept { return _type; } const value& at(size_t pos) const; const value& at(const std::string& key) const; template <typename Type> decltype(auto) get(const std::string& key, Type default_value) const { return is_object() ? as_object().get(key, default_value) : default_value; } template <typename Type> decltype(auto) get(size_t pos, Type default_value) const { return is_array() ? as_array().get(pos, default_value) : default_value; } const bool as_boolean() const; const int as_integer() const; // const unsigned as_unsigned() const; const long as_long() const; const unsigned long as_unsigned_long() const; const long long as_long_long() const; const unsigned long long as_unsigned_long_long() const; const float as_float() const; const double as_double() const; const long double as_long_double() const; const std::string as_string() const; const array& as_array() const; const object& as_object() const; array& as_array(); object& as_object(); // return raw string const std::string to_string() const; const std::string format(std::string shift_str = " ", size_t basic_shift_count = 0) const; value& operator=(const value& rhs); value& operator=(value&&) noexcept; const value& operator[](size_t pos) const; value& operator[](size_t pos); value& operator[](const std::string& key); value& operator[](std::string&& key); //explicit operator bool() const noexcept { return valid(); } explicit operator bool() const { return as_boolean(); } explicit operator int() const { return as_integer(); } explicit operator long() const { return as_long(); } explicit operator unsigned long() const { return as_unsigned_long(); } explicit operator long long() const { return as_long_long(); } explicit operator unsigned long long() const { return as_unsigned_long_long(); } explicit operator float() const { return as_float(); } explicit operator double() const { return as_double(); } explicit operator long double() const { return as_long_double(); } explicit operator std::string() const { return as_string(); } private: template <typename T> static std::unique_ptr<T> copy_unique_ptr(const std::unique_ptr<T>& t) { return t == nullptr ? nullptr : std::make_unique<T>(*t); } value_type _type = value_type::Null; std::string _raw_data = "null"; // If the value_type is Object or Array, the _raw_data will be a empty string. unique_array _array_ptr; unique_object _object_ptr; }; const value invalid_value(); std::ostream& operator<<(std::ostream& out, const value& val); // std::istream &operator>>(std::istream &in, value &val); } // namespace json
MistEO/meojson
include/json_parser.h
<filename>include/json_parser.h #pragma once #include <string> #include <optional> namespace json { class value; class object; class array; enum class value_type : char; class parser { public: ~parser() noexcept = default; static std::optional<value> parse(const std::string& content); private: parser( const std::string::const_iterator& cbegin, const std::string::const_iterator& cend) noexcept : _cur(cbegin), _end(cend) {} std::optional<value> parse(); value parse_value(); value parse_null(); value parse_boolean(); value parse_number(); // parse and return a json::value whose type is value_type::String value parse_string(); value parse_array(); value parse_object(); // parse and return a std::string std::optional<std::string> parse_stdstring(); bool skip_whitespace() noexcept; bool skip_digit() noexcept; private: std::string::const_iterator _cur; std::string::const_iterator _end; }; std::optional<value> parse(const std::string& content); } // namespace json
PucklaMotzer09/3DEngine
include/Vertex3D.h
#ifndef VERTEX_H #define VERTEX_H #include "OBJLoader.h" #include "Vector2.h" #include "Vector3.h" #include <GL/glew.h> namespace Johnny { /*! \brief A class which stores Vertex data for a 3D mesh * */ class Vertex3D { public: Vertex3D(); ~Vertex3D(); static const int SIZE; //!< The size of the Vertex in bytes static void setVertexAttribPointer(); //!< Sets the vertex attributes for a Shader Vector3f pos; //!< The position of the Vertex3D Vector3f normal; //!< The normal of the Vertex3D Vector2f uv; //!< The uv coordinates / texture coordinates of the Vertex3D }; } // namespace Johnny #endif
PucklaMotzer09/3DEngine
include/Vector3.h
#pragma once #include "Vector4.h" #include <GL/glew.h> #include <cmath> #include <iostream> namespace Johnny { template <class T> class Vector3; template <class T> Vector3<T> operator+(const Vector3<T> &, const Vector3<T> &); template <class T> Vector3<T> operator-(const Vector3<T> &, const Vector3<T> &); template <class T> Vector3<T> operator*(const Vector3<T> &, const Vector3<T> &); template <class T> Vector3<T> operator*(const Vector3<T> &, const T &); template <class T> Vector3<T> operator/(const Vector3<T> &, const Vector3<T> &); template <class T> Vector3<T> operator-(const Vector3<T> &); template <class T> std::ostream &operator<<(std::ostream &, const Vector3<T> &); /*! \brief A class which represents a value with three dimensions * \param T The type of the elements of the Vector3 */ template <class T> class Vector3 { public: Vector3() = default; /*! \brief Creates a new Vector3 * \param x The x value of the new Vector3 * \param y The y value of the new Vector3 * \param z The z value of the new Vector3 */ Vector3(const T &x, const T &y, const T &z); /*! \brief Copies a Vector3 * \param v The Vector3 to copy */ Vector3(const Vector3 &v); /*! \brief Converts a Vector4 to a Vector3 * \param v The Vector4 to convert * * It converts the Vector4 through dividing each element by the w component */ Vector3(const Vector4<T> &v); union { T x = 0; //!< The x value of the Vector3 if it is used as a position T r; //!< The x value of the Vector3 if it is used as a color T width; //!< The x value of the Vector3 if it is used as dimensions }; union { T y = 0; //!< The y value of the Vector3 if it is used as a position T g; //!< The y value of the Vector3 if it is used as a color T height; //!< The y value of the Vector3 if it is used as dimensions }; union { T z = 0; //!< The z value of the Vector3 if it is used as a position T b; //!< The z value of the Vector3 if it is used as a color T depth; //!< The z value of the Vector3 if it is used as dimensions }; /*! \param squared Wether the result should be the squared length or not * \return The length of the Vector3 */ T length(bool squared = false) const; /*! \brief Normalises a Vector3 * \return A reference to this object */ Vector3 &normalise(); /*! \brief Normalises a Vector3 * \return The normalised Vector3 * * It ismeant to be used when you want to normalise a temporary Vector3 */ Vector3 normaliseConst() const; /*! \brief Adds a Vector3 to this object * \param v The Vector3 to add * \return A reference to this object */ Vector3 &add(const Vector3 &v); /*! \brief Subtracts a Vector3 from this object * \param v The Vector3 to subtract * \return A refreence to this object */ Vector3 &subtract(const Vector3 &v); /*! \brief Multiplies each element of the Vector3 which each other * \param v The Vector3 for the multiplication * \return A reference to this object */ Vector3 &multiply(const Vector3 &v); /*! \brief Multiplies this vector with a scalar * \param s The scalar to multiply * \return A reference to the object */ Vector3 &multiply(const T &s); /*! \brief Divides each element of the Vector3 by the corresponding element of * the other Vector2 \param v The other Vector3 for the division \return A * reference to the object */ Vector3 &divide(const Vector3 &v); /*! \brief Divides each element by a scalar * \param s The scalar for the division * \return A reference to the object */ Vector3 &divide(const T &s); /*! \brief Calculates the cross product of this Vector3 and another Vector3 * \param v The other Vector3 for the cross product * \return The cross product of this Vector3 and the other Vector3 */ Vector3 cross(const Vector3 &v); /*! \brief Calculates the dot product with this Vector3 and another one * \param v The other Vector3 of the dot product * \return The calculated dot product */ T dot(const Vector3 &v); /*! \brief Calculates the distance between this Vector3 and another Vector3 * \param v The other Vector3 for the calculation * \param squared Wether the result should be the squared distance * \return The distance between this Vector3 and the other Vector3 */ T distance(const Vector3 &v, bool squared = false) const; Vector3 &operator+=(const Vector3 &); Vector3 &operator-=(const Vector3 &); Vector3 &operator*=(const Vector3 &); Vector3 &operator*=(const T &); Vector3 &operator/=(const Vector3 &); Vector3 &operator=(const Vector4<T> &); T &operator[](unsigned int); friend Vector3<T> operator+<>(const Vector3<T> &, const Vector3<T> &); friend Vector3<T> operator-<>(const Vector3<T> &, const Vector3<T> &); friend Vector3<T> operator*<>(const Vector3<T> &, const Vector3<T> &); friend Vector3<T> operator*<>(const Vector3<T> &, const T &); friend Vector3<T> operator/<>(const Vector3<T> &, const Vector3<T> &); friend Vector3<T> operator-<>(const Vector3<T> &); friend std::ostream &operator<<<>(std::ostream &, const Vector3<T> &); }; template <class T> Vector3<T>::Vector3(const T &x, const T &y, const T &z) { this->x = x; this->y = y; this->z = z; } template <class T> Vector3<T>::Vector3(const Vector3 &v) { x = v.x; y = v.y; z = v.z; } template <class T> Vector3<T>::Vector3(const Vector4<T> &v) { x = v.x / v.w; y = v.y / v.w; z = v.z / v.w; } template <class T> T Vector3<T>::length(bool squared) const { if (squared) return x * x + y * y + z * z; else return sqrt(x * x + y * y + z * z); } template <class T> Vector3<T> &Vector3<T>::normalise() { T Length = length(); x /= Length; y /= Length; z /= Length; return *this; } template <class T> Vector3<T> Vector3<T>::normaliseConst() const { return Vector3<T>(*this).normalise(); } template <class T> Vector3<T> &Vector3<T>::add(const Vector3<T> &v) { x += v.x; y += v.y; z += v.z; return *this; } template <class T> Vector3<T> &Vector3<T>::subtract(const Vector3<T> &v) { x -= v.x; y -= v.y; z -= v.z; return *this; } template <class T> Vector3<T> &Vector3<T>::multiply(const Vector3<T> &v) { x *= v.x; y *= v.y; z *= v.z; return *this; } template <class T> Vector3<T> &Vector3<T>::multiply(const T &s) { x *= s; y *= s; z *= s; return *this; } template <class T> Vector3<T> &Vector3<T>::divide(const Vector3<T> &v) { x /= v.x; y /= v.y; z /= v.z; return *this; } template <class T> Vector3<T> &Vector3<T>::divide(const T &s) { x /= s; y /= s; z /= s; return *this; } template <class T> Vector3<T> Vector3<T>::cross(const Vector3<T> &v) { Vector3<T> v1(*this); v1.x = y * v.z - z * v.y; v1.y = z * v.x - x * v.z; v1.z = x * v.y - y * v.x; return v1; } template <class T> T Vector3<T>::dot(const Vector3<T> &v) { return x * v.x + y * v.y + z * v.z; } template <class T> T Vector3<T>::distance(const Vector3<T> &v, bool squared) const { Vector3<T> v1(v); v1.subtract(*this); return v1.length(squared); } template <class T> Vector3<T> &Vector3<T>::operator+=(const Vector3<T> &v2) { return add(v2); } template <class T> Vector3<T> &Vector3<T>::operator-=(const Vector3<T> &v2) { return subtract(v2); } template <class T> Vector3<T> &Vector3<T>::operator*=(const Vector3<T> &v2) { return multiply(v2); } template <class T> Vector3<T> &Vector3<T>::operator*=(const T &s) { return multiply(s); } template <class T> Vector3<T> &Vector3<T>::operator/=(const Vector3<T> &v2) { return divide(v2); } template <class T> Vector3<T> operator+(const Vector3<T> &v1, const Vector3<T> &v2) { return Vector3<T>(v1).add(v2); } template <class T> Vector3<T> operator-(const Vector3<T> &v1, const Vector3<T> &v2) { return Vector3<T>(v1).subtract(v2); } template <class T> Vector3<T> operator*(const Vector3<T> &v1, const Vector3<T> &v2) { return Vector3<T>(v1).multiply(v2); } template <class T> Vector3<T> operator*(const Vector3<T> &v, const T &s) { return Vector3<T>(v).multiply(s); } template <class T> Vector3<T> operator/(const Vector3<T> &v1, const Vector3<T> &v2) { return Vector3<T>(v1).divide(v2); } template <class T> Vector3<T> operator-(const Vector3<T> &v) { Vector3<T> v1(v); return v1.multiply((T)-1); } template <class T> std::ostream &operator<<(std::ostream &os, const Vector3<T> &v) { os << "(" << v.x << ";" << v.y << ";" << v.z << ")"; return os; } template <class T> Vector3<T> &Vector3<T>::operator=(const Vector4<T> &v2) { *this = Vector3<T>(v2); return *this; } template <class T> T &Vector3<T>::operator[](unsigned int i) { switch (i) { case 0: return x; case 1: return y; case 2: return z; default: throw "operator[] unsigned int must be 0,1,2"; break; } } typedef Vector3<GLfloat> Vector3f; typedef Vector3<GLdouble> Vector3d; typedef Vector3<GLint> Vector3i; } // namespace Johnny
PucklaMotzer09/3DEngine
include/RenderUtil.h
<reponame>PucklaMotzer09/3DEngine<filename>include/RenderUtil.h #pragma once #include <SDL2/SDL.h> #include <string> #define ERROR_OUT(func, errorText) \ if (func < 0) \ Johnny::LogManager::error( \ std::string(errorText) + \ MainClass::getInstance()->getFramework()->getError()) namespace Johnny { /*! \brief A class which handles some basic OpenGL stuff DEPRECATED * */ class RenderUtil { public: RenderUtil(); ~RenderUtil(); /*! \brief Clears the screen with the clear color * */ static void clearScreen(); /*! \brief Initialises OpenGL * \param r The r value of the clear color * \param g The g value of the clear color * \param b The b value of the clear color * \param a The a value of the clear color */ static bool initGraphics(float r = 0.0f, float g = 0.0f, float b = 0.0f, float a = 0.0f); /*! \brief initialises the OpenGL variables for the window * */ static void initWindow(); /*! \brief Swaps the buffers of a window * \param w The window which should be swapped */ static void swapWindow(SDL_Window *w); /*! \return The OpenGL version string * */ static std::string getOpenGLVersion(); }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/CubeMap3D.h
#pragma once #include "../include/Texture.h" #include <string> namespace Johnny { class ResourceManager; class TextureData; /*! \brief This is a CubeMapTexture * */ class CubeMap3D : public Texture { public: /*! \brief Creates a new CubeMap3D from files * \param top The filepath of the texture used for the top plane * \param bottom The filepath of the texture used for the bottom plane * \param left The filepath of the texture used for the left plane * \param right The filepath of the texture used for the right plane * \param front The filepath of the texture used for the front plane * \param back The filepath of the texture used for the back plane * \param res The resource manager form which to load the texturefiles */ CubeMap3D(const std::string &top, const std::string &bottom, const std::string &left, const std::string &right, const std::string &front, const std::string &back, ResourceManager *res); /*! \brief Creates a new CubeMap3D from TextureDatas * \param top The TextureData of the texture used for the top plane * \param bottom The TextureData of the texture used for the bottom plane * \param left The TextureData of the texture used for the left plane * \param right The TextureData of the texture used for the right plane * \param front The TextureData of the texture used for the front plane * \param back The TextureData of the texture used for the back plane */ CubeMap3D(TextureData *top, TextureData *bottom, TextureData *left, TextureData *right, TextureData *front, TextureData *back); }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/Matrix3.h
#pragma once #include "../include/Matrix4.h" #include "../include/Vector2.h" #include "../include/Vector3.h" #include "../include/mathematics_functions.h" #include <GL/glew.h> #include <iostream> #include <string> #define MAT3_GET(r, c) (r + c * 3) namespace Johnny { template <class T> class Matrix3; template <class T> Matrix3<T> operator*(const Matrix3<T> &, const Matrix3<T> &); template <class T> Matrix3<T> operator*(const Matrix3<T> &, const T &); template <class T> std::ostream &operator<<(std::ostream &, const Matrix3<T> &); template <class T> Vector3<T> operator*(const Matrix3<T> &, const Vector3<T> &); template <class T> Vector2<T> operator*(const Matrix3<T> &, const Vector2<T> &); /*! \brief A class which represents a 3x3 matrix * \param T The type of which the elements of the matrix should be */ template <class T> class Matrix3 { public: /*! \brief Creates an identity 3x3 matrix * \return The newly created 3x3 identity matrix */ static Matrix3 identity(); /*! \brief Creates a 3x3 translation matrix * \param x How much to translate on the x-Axis * \param y How much to translate on the y-Axis * \return The newly created 3x3 translation matrix */ static Matrix3 translate(const T &x, const T &y); /*! \brief Creates a 3x3 translation matrix * \param v The vector on which to translate * \return The newly created translation matrix */ static Matrix3 translate(const Vector2<T> &v); /*! \brief Creates a 3x3 rotation matrix * \param rot How much to rotate on the z-Axis in degrees * \return The newly created 3x3 rotation matrix */ static Matrix3 rotate(const T &rot); /*! \brief Creates a 3x3 scale matrix * \param x The scaling factor of the x-Axis * \param y The scaling factor of the y-Axis * \return The newly created 3x3 scale matrix */ static Matrix3 scale(const T &x, const T &y); /*! \brief Creates a 3x3 scale matrix * \param v The scaling vector * \return The newly created 3x3 scale matrix */ static Matrix3 scale(const Vector2<T> &v); /*! \brief Creates a 3x3 worldview matrix * \param pos The position of the viewer * \param zoom How much is zoomed in * \param The rotation of the viewer in degrees * \return The newly created 3x3 worldview matrix */ static Matrix3 camera(const Vector2<T> &pos, const T &zoom, const T &rot); /*! \brief Creates a 3x3 worldview matrix * \param pos The position of the viewer * \param middle The point to which the viewer looks * \param up The direction vector which defines where up is * \return The newly created worldview matrix */ static Matrix3 lookAt(const Vector3<T> &pos, const Vector3<T> &middle, const Vector3<T> &up); Matrix3() = default; /*! \brief Creates a new 3x3 matrix * \param d The value of the diagonal values */ Matrix3(const T &d); /*! \brief The copy constructor * \param mat The 3x3 matrix to copy from */ Matrix3(const Matrix3 &mat); union { T values[3 * 3]; //!< The elements of the 3x3 matrix as an array Vector3<T> columns[3]; //!< The elements of the 3x3 matrix as columns }; /*! \brief Multiplies a 3x3 matrix with this matrix * \param mat The 3x3 matrix to multiply with * \return A reference to this matrix */ Matrix3 &multiply(const Matrix3 &mat); /*! \brief Multiplies this matrix with a scalar * \param The scalar to multiply with * \return A reference of this matrix */ Matrix3 &multiply(const T &s); /*! \brief Multiplies this matrix with a Vector3<T> * \param v The vector to multiply with * \return The resulting Vector3<T> of the multiplication */ Vector3<T> multiply(const Vector3<T> &v) const; /*! \brief Prints the 3x3 matrix to the console * */ void print(); Matrix3 &operator*=(const Matrix3 &); Matrix3 &operator*=(const T &); Vector3<T> &operator[](unsigned int); friend Matrix3<T> operator*<>(const Matrix3<T> &, const Matrix3<T> &); friend Matrix3<T> operator*<>(const Matrix3<T> &, const T &); friend Vector3<T> operator*<>(const Matrix3<T> &, const Vector3<T> &); friend Vector2<T> operator*<>(const Matrix3<T> &, const Vector2<T> &); friend std::ostream &operator<<<>(std::ostream &, const Matrix3<T> &); }; template <class T> Matrix3<T> Matrix3<T>::identity() { return Matrix3(1); } template <class T> Matrix3<T> Matrix3<T>::translate(const T &x, const T &y) { Matrix3<T> mat(1); mat.values[MAT3_GET(0, 2)] = x; mat.values[MAT3_GET(1, 2)] = y; return mat; } template <class T> Matrix3<T> Matrix3<T>::translate(const Vector2<T> &v) { return translate(v.x, v.y); } template <class T> Matrix3<T> Matrix3<T>::rotate(const T &angle) { Matrix3<T> mat(1); T sina = (T)sin((double)toRadians(angle)); T cosa = (T)cos((double)toRadians(angle)); mat.values[MAT3_GET(0, 0)] = cosa; mat.values[MAT3_GET(1, 1)] = cosa; mat.values[MAT3_GET(1, 0)] = sina; mat.values[MAT3_GET(0, 1)] = -sina; return mat; } template <class T> Matrix3<T> Matrix3<T>::scale(const T &x, const T &y) { Matrix3<T> mat(1); mat.values[MAT3_GET(0, 0)] = x; mat.values[MAT3_GET(1, 1)] = y; return mat; } template <class T> Matrix3<T> Matrix3<T>::scale(const Vector2<T> &v) { return scale(v.x, v.y); } template <class T> Matrix3<T> Matrix3<T>::camera(const Vector2<T> &position, const T &zoom, const T &rotation) { return rotate(rotation) * scale(zoom, zoom) * translate(position * (T)-1); } template <class T> Matrix3<T> Matrix3<T>::lookAt(const Vector3<T> &position, const Vector3<T> &middle, const Vector3<T> &up) { // Src: // https://github.com/TheCherno/Sparky/blob/master/Sparky-core/src/sp/maths/mat4.cpp Matrix3<T> result(1); Vector3<T> f = (middle - position); f.normalise(); Vector3<T> up1 = up; up1.normalise(); Vector3<T> s = f.cross(up); Vector3<T> u = s.cross(f); result.values[0 + 0 * 3] = s.x; result.values[0 + 1 * 3] = s.y; result.values[0 + 2 * 3] = s.z; result.values[1 + 0 * 3] = u.x; result.values[1 + 1 * 3] = u.y; result.values[1 + 2 * 3] = u.z; result.values[2 + 0 * 3] = -f.x; result.values[2 + 1 * 3] = -f.y; result.values[2 + 2 * 3] = -f.z; return result * translate(-position.x, -position.y); } template <class T> Matrix3<T>::Matrix3(const T &v) { for (unsigned int i = 0; i < 9; i++) { values[i] = 0; } values[MAT3_GET(0, 0)] = v; values[MAT3_GET(1, 1)] = v; values[MAT3_GET(2, 2)] = v; } template <class T> Matrix3<T>::Matrix3(const Matrix3<T> &mat) { for (unsigned int i = 0; i < 9; i++) values[i] = mat.values[i]; } template <class T> Matrix3<T> &Matrix3<T>::multiply(const Matrix3<T> &mat) { T sum[3]; for (unsigned int r = 0; r < 3; r++) { for (unsigned int c = 0; c < 3; c++) { sum[c] = 0; for (unsigned int i = 0; i < 3; i++) { sum[c] += values[MAT3_GET(r, i)] * mat.values[MAT3_GET(i, c)]; } } for (unsigned int i = 0; i < 3; i++) { values[MAT3_GET(r, i)] = sum[i]; } } return *this; } template <class T> Matrix3<T> &Matrix3<T>::multiply(const T &v) { for (unsigned int i = 0; i < 9; i++) { values[i] *= v; } } template <class T> Vector3<T> Matrix3<T>::multiply(const Vector3<T> &v) const { Vector3<T> v1(v); v1.x = values[MAT3_GET(0, 0)] * v.x + values[MAT3_GET(0, 1)] * v.y + values[MAT3_GET(0, 2)] * v.z; v1.y = values[MAT3_GET(1, 0)] * v.x + values[MAT3_GET(1, 1)] * v.y + values[MAT3_GET(1, 2)] * v.z; v1.z = values[MAT3_GET(2, 0)] * v.x + values[MAT3_GET(2, 1)] * v.y + values[MAT3_GET(2, 2)] * v.z; return v1; } template <class T> inline void Matrix3<T>::print() { std::cout << *this; } template <class T> Matrix3<T> &Matrix3<T>::operator*=(const Matrix3<T> &mat2) { return multiply(mat2); } template <class T> Matrix3<T> &Matrix3<T>::operator*=(const T &v) { return multiply(v); } template <class T> Vector3<T> &Matrix3<T>::operator[](unsigned int i) { return columns[i]; } template <class T> Matrix3<T> operator*(const Matrix3<T> &mat1, const Matrix3<T> &mat2) { return Matrix3<T>(mat1).multiply(mat2); } template <class T> Matrix3<T> operator*(const Matrix3<T> &mat, const T &v) { return Matrix3<T>(mat).multiply(v); } template <class T> Vector2<T> operator*(const Matrix3<T> &mat, const Vector2<T> &v) { Vector3<T> v1(mat * Vector3<T>(v.x, v.y, 1)); return Vector2<T>(v1.x / v1.z, v1.y / v1.z); } template <class T> Vector3<T> operator*(const Matrix3<T> &mat, const Vector3<T> &v) { return mat.multiply(v); } template <class T> std::ostream &operator<<(std::ostream &os, const Matrix3<T> &mat) { for (unsigned int r = 0; r < 3; r++) { os << "[ "; for (unsigned int c = 0; c < 3; c++) { os << mat.values[MAT3_GET(r, c)] << " "; } os << "]" << std::endl; } return os; } typedef Matrix3<GLfloat> Matrix3f; typedef Matrix3<GLdouble> Matrix3d; typedef Matrix3<GLint> Matrix3i; } // namespace Johnny
PucklaMotzer09/3DEngine
include/PhysicsSprite2D.h
<reponame>PucklaMotzer09/3DEngine #ifndef PHYSICS_SPRITE_H #define PHYSICS_SPRITE_H #include "../include/Sprite2D.h" #include <box2d/box2d.h> namespace Johnny { class Texture; /*! \brief A class which represents a b2Body as a Sprite2D * */ class PhysicsSprite2D : public Sprite2D { public: /*! \brief Creates a new PhysicsSprite2D * \param body The body of the new PhysicsSprite2D */ PhysicsSprite2D(b2Body *body = nullptr); /*! \brief Creates a new PhysicsSprite2D * \param file The file path of the Texture of the new PhysicsSprite2D * \param body The b2Body of the new PhysicsSprite2D */ PhysicsSprite2D(const std::string &file, b2Body *body = nullptr); /*! \brief Creates a new PhysicsSprite2D * \param texture The Texture of the new PhysicsSprite2D * \param body The b2Body of the new PhysicsSprite2D */ PhysicsSprite2D(Texture *texture, b2Body *body = nullptr); virtual ~PhysicsSprite2D(); /*! \brief The init method * * * It is overriding the method from Sprite2D */ virtual bool init() override; /*! \brief The m_update method * * * It is overriding the method from Sprite2D */ virtual bool m_update() override; /*! \brief The m_quit method * * * It is overriding the method from m_quit */ virtual void m_quit() override; /*! \return The b2Body of the PhysicsSprite2D * */ b2Body *getBody() { return m_body; } /*! \return If the PhysicsSprite2D should be destroyed if it moves out of the * physics world * */ bool getAutomaticDestroy() { return m_automaticDestroy; } /*! \return The offset that applies to the attaching of the Sprite2D to the * b2Body * */ const Vector2f &getOffset() const { return m_offset; } /*! \brief Sets the body of the PhysicsSprite2D * \param body The b2Body to set */ void setBody(b2Body *body) { m_body = body; body->GetUserData().pointer = reinterpret_cast<uintptr_t>(this); } /*! \brief Sets if the PhysicsSprite2D should be destroyed if it moves out of * the physics world \param b The bool value to set m_automaticDestroy */ void setAutomaticDestroy(bool b) { m_automaticDestroy = b; } /*! \brief Sets the offset which applies to the attaching of the Sprite2D to * the b2Body \param v The offset to set */ void setOffset(const Vector2f &v) { m_offset = v; } /*! \brief Gets called when the b2Body of the PhysicsSprite2D begins colliding * with another b2Body \param c The b2Contact of the collision \param f1 The * b2Fixture of the PhysicsSprite2D \param f2 The b2Fixture of the other * b2Body it collides with \param spr The other PhysicsSprite2D, if the body * is not attached to a PhysicsSprite2D it is nullptr */ virtual void BeginContact(b2Contact *c, b2Fixture *f1, b2Fixture *f2, PhysicsSprite2D *spr) {} /*! \brief Gets called when the b2Body of the PhysicsSprite2D ends colliding * with another b2Body \param c The b2Contact of the collision \param f1 The * b2Fixture of the Physics \param f2 The b2Fixture of the other b2Body \param * spr The other PhysicsSprite2D, if the body is not attached to a * PhysicsSprite2D it is nullptr */ virtual void EndContact(b2Contact *c, b2Fixture *f1, b2Fixture *f2, PhysicsSprite2D *spr) {} /*! \brief Gets called every time the PhysicsSprite2D is colliding with * another b2Body \param c The b2Contact of the collision \param f1 The * b2Fixture of the PhysicsSprite2D \param f2 The b2Fixture of the other * b2Body \param m The b2Manifold of the collision \param spr The other * PhysicsSprite2D, if the body is not attached to a PhysicsSprite2D it is * nullptr */ virtual void PreSolve(b2Contact *c, b2Fixture *f1, b2Fixture *f2, const b2Manifold *m, PhysicsSprite2D *spr) {} /*! \brief Gets called every time the PhysicsSprite2D is colliding with * another b2Body after PreSolve \param c The b2Contact of the collision * \param f1 The b2Fixture of the PhysicsSprite2D * \param f2 The b2Fixture of the other b2Body * \param ci The b2ContactImpulse of the collision * \param spr The other PhysicsSprite2D, if the body is not attached to a * PhysicsSprite2D it is nullptr */ virtual void PostSolve(b2Contact *c, b2Fixture *f1, b2Fixture *f2, const b2ContactImpulse *ci, PhysicsSprite2D *spr) {} protected: bool m_automaticDestroy = true; //!< Defines if the PhysicsSprite2D should be destroyed if it moves //!< out of the physics world Vector2f m_offset; //!< The offset of the PhysicsSprite2D with which it gets //!< attached to the b2Body in pixel coordinates private: /*! \brief Gets called every frame and connects the b2Body with the Sprite2D * */ virtual void attachBodyToSprite(); b2Body *m_body = nullptr; //!< The b2Body of the PhysicsSprite2D }; } // namespace Johnny #endif
PucklaMotzer09/3DEngine
include/JoystickListener.h
#ifndef JOYSTICKLISTENER_H #define JOYSTICKLISTENER_H #include "Events.h" #include "JoystickListenerEnums.h" #include <map> #include <vector> namespace Johnny { class JoystickListener; /*! \brief A Listener class which catches button input and axis movement of a * controller * */ class AxisButtonListener { public: virtual ~AxisButtonListener() {} /*! \brief Gets called when a stick or a trigger gets moved * \param e A struct which holds information about the event */ virtual void onAxisMotion(const ControllerAxisEvent &e) = 0; /*! \brief Gets called when a button is pressed * \param e A struct which holds information about the event */ virtual void onButtonDown(const ControllerButtonEvent &e) = 0; /*! \brief Gets called when a button is released * \param e A struct which holds information about the event */ virtual void onButtonUp(const ControllerButtonEvent &e) = 0; /*! \brief Sets the JoystickListener of the object * \param jl The JoystickListener to set */ void setListener(JoystickListener *jl); /*! \brief Detaches the AxisButtonListener from the parent JoystickListener * */ void detach(); protected: JoystickListener *m_listener = nullptr; //!< The JoystickListener of the object }; /*! \brief A Listener class which listens to controllers connecting and * disconnecting * */ class ConnectionListener { public: virtual ~ConnectionListener(); /*! \brief Gets called when a controller connects * \param e A struct which holds infotmation about the event */ virtual void onConnect(const ControllerDeviceEvent &e) = 0; /*! \brief Gets called when a controller disconnects * \param e A struct which holds information about the event */ virtual void onDisconnect(const ControllerDeviceEvent &e) = 0; /*! \brief Sets the JoystickListener of the object * \param jl The JoystickListener to set */ void setListener(JoystickListener *jl); protected: JoystickListener *m_listener; //!< The JoystickListener of the object }; class JoystickManager; /*! \brief The main JoystickListener class which fetches all ControllerInputs * */ class JoystickListener { public: JoystickListener(); virtual ~JoystickListener(); /*! \brief Sets the JoystickManager * \param jm The JoystickManager to set */ void setManager(JoystickManager *jm); /*! \return The JoystickManager of the object * */ JoystickManager *getManager() { return m_manager; } /*! \brief Gets called when a axsis or trigger of a controller is moved * \param e A struct which holds information about the event */ void onAxisMotion(const ControllerAxisEvent &e); /*! \brief Gets called when a button of a controller is pressed * \param e A struct which holds information about the event */ void onButtonDown(const ControllerButtonEvent &e); /*! \brief Gets called when a button of a controller is released * \param e A struct which holds information about the event */ void onButtonUp(const ControllerButtonEvent &e); /*! \brief Gets called when a controller connects * \param e A struct which holds information about the event */ void onConnect(const ControllerDeviceEvent &e); /*! \brief Gets called when a controller disconnects * \param e A struct which holds information about the event */ void onDisconnect(const ControllerDeviceEvent &e); /*! \brief Attaches a AxisButtonListener to a specific controller id * \param abl The listener to attach * \param id The id to which the listener gets attached */ void addListener(AxisButtonListener *abl, int id); /*! \brief Attaches a ConnectionListener * \param cl The listener to attach */ void addListener(ConnectionListener *cl); /*! \brief Remove a AxisButtonListener from this listener * \param abl The listener to remove */ void removeListener(AxisButtonListener *abl); /*! \brief Removes a ConnectionListener from this listener * \param cl The listener to remove */ void removeListener(ConnectionListener *cl); protected: JoystickManager *m_manager = nullptr; //!< The JoystickManager of the object private: std::map<int, std::vector<AxisButtonListener *>> m_abLis; //!< The map which holds all AxisButtonListeners with the //!< specific ids std::vector<ConnectionListener *> m_conLis; //!< The vector which holds all ConnectionListeners }; /*! \brief A Iterator which iterates over the m_abLis map * */ typedef std::map<int, std::vector<AxisButtonListener *>>::iterator AbIterator; } // namespace Johnny #endif // JOYSTICKLISTENER_H
PucklaMotzer09/3DEngine
include/Entity3D.h
<reponame>PucklaMotzer09/3DEngine<gh_stars>0 #pragma once #include "../include/Actor.h" #include "../include/Transform3D.h" #include <string> namespace Johnny { class Model3D; class Shader; class Mesh3D; /*! \brief Thes represents a model as a Actor * */ class Entity3D : public Actor, public TransformableObject3D { public: /*! \brief Creates a new Entity3D * \param file The file from which to load the model * */ Entity3D(const std::string &file); /*! \brief Creates a new Entity3D * \param mesh The mesh which is used for rendering */ Entity3D(Mesh3D *mesh); /*! \brief Creates a new Entity3D * \param model The model which is used for rendering */ Entity3D(Model3D *model); ~Entity3D(); /*! \brief The init method * * * It is overriding the method of Actor */ virtual bool init() override; /*! \brief The update method * * * It is overriding the method of Actor */ virtual bool update() override; /*! \brief The render method * * * It is overriding the method of Actor */ virtual bool render() override; /*! \brief The quit method * * * It is overriding the method of Actor */ virtual void quit() override; /*! \brief Sets the model of the object * \param m The model to set */ void setModel(Model3D *m) { m_model = m; } /*! \return The model of the object * */ Model3D *getModel() { return m_model; } private: std::string m_fileName = ""; //!< The file name of the model to load Model3D *m_model = nullptr; //!< The model }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/Settings.h
<reponame>PucklaMotzer09/3DEngine<filename>include/Settings.h #pragma once #include <GL/glew.h> namespace Johnny { class MainClass; /*! \brief A enum which stores all names of the settings which can be adjusted * */ enum SettingName { VSYNC, //!< The name of the setting that specifys if vsync should be activated MSAA, //!< The name of the setting that specifys if multisampling should be //!< applied MSAA_SAMPLES, //!< The name of the setting that sepcifys the number of //!< multisampling samples SPRITE2D_FILTERING, //!< The name of the setting that specifys which method to //!< use for filtering for Sprite2Ds BACK_BUFFER_FILTERING //!< The name of the settings that specifys which method //!< to use for filtering for the back buffer }; /*! \brief A class which handles all settings * */ class Settings { public: friend class MainClass; /*! \brief Sets a setting with type of integer * \param s The name of the setting to adjust * \param i The new value * \return true if it worked and false otherwhise */ static bool seti(SettingName s, int i); /*! \brief Sets a setting with type of bool * \param s The name of the setting to adjust * \param b The new value * \return true if it worked and false otherwhise */ static bool setb(SettingName s, bool b); /*! \brief Gets a setting with type of bool * \param s The name of the setting to get the value from * \return the value of the setting or false if the setting doesn't is a bool * or doesn't exist */ static bool getb(SettingName s); /*! \brief Gets a setting width type of integer * \param s The name of the setting to get the value from * \return The value of the setting or 0 if the setting isn't a integer or * the setting doesn't exist */ static int geti(SettingName s); private: static bool m_vsync; //!< The value of VSYNC static bool m_msaa; //!< The value of MSAA static int m_msaa_samples; //!< The value of MSAA_SAMPLES static GLenum m_sprite2D_filtering; //!< The value of SPRITE2D_FILTERING static GLenum m_back_buffer_filtering; //!< The value of BACK_BUFFER_FILTERING static bool m_initialized; //!< true if the MainClass has been initialize }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/Johnny.h
#ifndef JOHNNY_H #define JOHNNY_H #include "Actor.h" #include "Camera2D.h" #include "Camera3D.h" #include "Colors.h" #include "ContactListener.h" #include "CubeMap3D.h" #include "DebugMovement2D.h" #include "DebugMovement3D.h" #include "Defines.h" #include "Entity3D.h" #include "FrameBuffer.h" #include "Geometry.h" #include "InputManager.h" #include "JoystickListener.h" #include "JoystickManager.h" #include "Light3D.h" #include "LogManager.h" #include "MainClass.h" #include "Mesh3D.h" #include "Model3D.h" #include "OBJLoader.h" #include "Physics2D.h" #include "PhysicsSprite2D.h" #include "RenderBuffer.h" #include "RenderManager.h" #include "RenderTexture.h" #include "RenderUtil.h" #include "ResourceManager.h" #include "Settings.h" #include "Shader.h" #include "ShaderUpdater.h" #include "ShadowMap3D.h" #include "Skybox.h" #include "Sprite2D.h" #include "TextActor2D.h" #include "Texture.h" #include "TiledMap.h" #include "Timer.h" #include "Transform2D.h" #include "Transform3D.h" #include "Tween.h" #include "Vertex3D.h" #include "Window.h" #include "mathematics.h" #include "operators.h" #endif
PucklaMotzer09/3DEngine
include/Matrix4.h
<reponame>PucklaMotzer09/3DEngine #pragma once #include "../include/Vector3.h" #include "../include/Vector4.h" #include "../include/operators.h" #include <iostream> #include <string> #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES 1 #endif #include "../include/mathematics_functions.h" #define MAT4_GET(r, c) (r + c * 4) #define INIT_IDENTITY = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1} namespace Johnny { template <class T> class Matrix4; template <class T> Matrix4<T> operator*(const Matrix4<T> &, const Matrix4<T> &); template <class T> Matrix4<T> operator*(const Matrix4<T> &, const T &); template <class T> Vector4<T> operator*(const Matrix4<T> &, const Vector4<T> &); template <class T> std::ostream &operator<<(std::ostream &, const Matrix4<T> &); /*! \brief A class which represents a 4x4 matrix * \param T The type of the elements of the matrix */ template <class T> class Matrix4 { public: /*! \brief Creates a 4x4 identity matrix * \return The newly created 4x4 identity matrix */ static Matrix4 identity(); /*! \brief Creates a 4x4 perspective projection matrix * \param fov The field of view of the projection in degrees * \param aspect The aspect ratio * \param far The far plane where geometry clips * \param near The near plane where geometry clips * \return The newly created 4x4 perspective projection matrix */ static Matrix4 perspective(const T &fov, const T &aspect, const T &far, const T &near); /*! \brief Creates a 4x4 orthographic projection matrix * \param top The top plane * \param bottom The bottom plane * \param right The right plane * \param left The left plane * \param far The far plane * \param near The near plane * \return The newly created 4x4 orthographic projection matrix */ static Matrix4 orthographic(const T &top, const T &bottom, const T &right, const T &left, const T &far, const T &near); /*! \brief Creates a 4x4 worldview matrix * \param position The position of the viewer * \param middle The point on which the viewer looks * \param up The direction vector which defines the up direction * \return The newly created 4x4 worldview matrix */ static Matrix4 lookAt(const Vector3<T> &position, const Vector3<T> &middle, const Vector3<T> &up); /*! \brief Creates a 4x4 translation matrix * \param x How mauch to translate on the x-Axis * \param y How much to translate on the y-Axis * \param z How much to translate on the z-Axis * \return The newly created 4x4 translation matrix */ static Matrix4 translate(const T &x, const T &y, const T &z); /*! \brief Creates a 4x4 translation matrix * \param v The translation vector * \return The newly created 4x4 translation matrix */ static Matrix4 translate(const Vector3<T> &v); /*! \brief Creates a 4x4 rotation matrix * \param angle How much degrees to rotate * \param axis The axis on which to rotate * \return The newly created 4x4 rotation matrix */ static Matrix4 rotate(const T &angle, const Vector3<T> &axis); /*! \brief Creates a 4x4 scale matrix * \param x How much to scale on the x-Axis * \param y How much to scale on the y-Axis * \param z How much to scale on the z-Axis * \return The newly created 4x4 scale matrix */ static Matrix4 scale(const T &x, const T &y, const T &z); /*! \brief Creates a 4x4 scale matrix * \param v The scale vector * \return The newly created 4x4 scale matrix */ static Matrix4 scale(const Vector3<T> &v); Matrix4() = default; /*! \brief Creates a new 4x4 matrix * \param d The value of all diagonal values */ Matrix4(const T &d); /*! \brief The copy constructor * \param mat The matrix from which to copy */ Matrix4(const Matrix4 &mat); union { T values[4 * 4] INIT_IDENTITY; //!< The elements of the matrix as an array Vector4<T> columns[4]; //!< The elements of the matrix as an array of columns }; /*! \brief Multiplies this matrix with another one * \param mat The matrix to multiply with * \return A reference to this matrix */ Matrix4 &multiply(const Matrix4 &mat); /*! \brief Multiplies this matrix with a scalar * \param s The scalar to multiply with * \return A reference to this matrix */ Matrix4 &multiply(const T &s); /*! \brief Multiplies this matrix with a Vector4<T> * \param v The vector to multiply with * \return The resulting Vector4<T> */ Vector4<T> multiply(const Vector4<T> &v) const; /*! \brief Prints this matrix to the console * */ void print(); Matrix4 &operator*=(const Matrix4 &); Matrix4 &operator*=(const T &); Vector4<T> &operator[](unsigned int); friend Matrix4<T> operator*<>(const Matrix4<T> &, const Matrix4<T> &); friend Matrix4<T> operator*<>(const Matrix4<T> &, const T &); friend Vector4<T> operator*<>(const Matrix4<T> &, const Vector4<T> &); friend std::ostream &operator<<<>(std::ostream &, const Matrix4<T> &); }; template <class T> Matrix4<T> Matrix4<T>::identity() { return Matrix4(1); } template <class T> Matrix4<T> Matrix4<T>::perspective(const T &fov, const T &aspect, const T &far, const T &near) { Matrix4<T> mat(1); T tanFovHalf = (T)tan((double)(toRadians(fov) / (T)2)); mat.values[MAT4_GET(0, 0)] = (T)1 / (aspect * tanFovHalf); mat.values[MAT4_GET(1, 1)] = (T)1 / tanFovHalf; mat.values[MAT4_GET(2, 2)] = -((far + near) / (far - near)); mat.values[MAT4_GET(2, 3)] = -((2 * far * near) / (far - near)); mat.values[MAT4_GET(3, 2)] = -1; mat.values[MAT4_GET(3, 3)] = 0; return mat; } template <class T> Matrix4<T> Matrix4<T>::orthographic(const T &top, const T &bottom, const T &right, const T &left, const T &far, const T &near) { Matrix4<T> mat(1); mat.values[MAT4_GET(0, 0)] = (T)2 / (right - left); mat.values[MAT4_GET(1, 1)] = (T)2 / (top - bottom); mat.values[MAT4_GET(2, 2)] = (T)-2 / (far - near); mat.values[MAT4_GET(0, 3)] = -((right + left) / (right - left)); mat.values[MAT4_GET(1, 3)] = -((top + bottom) / (top - bottom)); mat.values[MAT4_GET(2, 3)] = -((far + near) / (far - near)); return mat; } template <class T> Matrix4<T> Matrix4<T>::lookAt(const Vector3<T> &position, const Vector3<T> &middle, const Vector3<T> &up) { // Src: // https://github.com/TheCherno/Sparky/blob/master/Sparky-core/src/sp/maths/mat4.cpp /*Matrix4<T> Result(1); Vector3<T> f = Vector3<T>(middle - position).normalise(); Vector3<T> s = f.cross(up); Vector3<T> u = s.cross(f); Result.values[0 + 0 * 4] = s.x; Result.values[1 + 0 * 4] = s.y; Result.values[2 + 0 * 4] = s.z; Result.values[0 + 1 * 4] = u.x; Result.values[1 + 1 * 4] = u.y; Result.values[2 + 1 * 4] = u.z; Result.values[0 + 2 * 4] = f.x; Result.values[1 + 2 * 4] = f.y; Result.values[2 + 2 * 4] = f.z; Result.values[0 + 3 * 4] = -position.x; Result.values[1 + 3 * 4] = -position.y; Result.values[2 + 3 * 4] = -position.z; * tvec3<T, P> const f(normalize(center - eye)); tvec3<T, P> const s(normalize(cross(f, up))); tvec3<T, P> const u(cross(s, f)); tmat4x4<T, P> Result(1); Result[0][0] = s.x; Result[1][0] = s.y; Result[2][0] = s.z; Result[0][1] = u.x; Result[1][1] = u.y; Result[2][1] = u.z; Result[0][2] =-f.x; Result[1][2] =-f.y; Result[2][2] =-f.z; Result[3][0] =-dot(s, eye); Result[3][1] =-dot(u, eye); Result[3][2] = dot(f, eye); return Result;*/ Vector3<T> f = Vector3<T>(middle - position).normalise(); Vector3<T> s = f.cross(up).normalise(); Vector3<T> u = s.cross(f); Matrix4<T> Result(1); Result.values[MAT4_GET(0, 0)] = s.x; Result.values[MAT4_GET(0, 1)] = s.y; Result.values[MAT4_GET(0, 2)] = s.z; Result.values[MAT4_GET(1, 0)] = u.x; Result.values[MAT4_GET(1, 1)] = u.y; Result.values[MAT4_GET(1, 2)] = u.z; Result.values[MAT4_GET(2, 0)] = -f.x; Result.values[MAT4_GET(2, 1)] = -f.y; Result.values[MAT4_GET(2, 2)] = -f.z; Result.values[MAT4_GET(0, 3)] = -s.dot(position); Result.values[MAT4_GET(1, 3)] = -u.dot(position); Result.values[MAT4_GET(2, 3)] = f.dot(position); return Result; return Result; } template <class T> Matrix4<T> Matrix4<T>::translate(const T &x, const T &y, const T &z) { Matrix4<T> mat(1); mat.values[MAT4_GET(0, 3)] = x; mat.values[MAT4_GET(1, 3)] = y; mat.values[MAT4_GET(2, 3)] = z; return mat; } template <class T> Matrix4<T> Matrix4<T>::translate(const Vector3<T> &v) { return translate(v.x, v.y, v.z); } template <class T> Matrix4<T> Matrix4<T>::rotate(const T &angle, const Vector3<T> &v) { // Src: // https://github.com/TheCherno/Sparky/blob/master/Sparky-core/src/sp/maths/mat4.cpp /*Matrix4<T> result(1); T r = toRadians(angle); T c = (T)cos((double)r); T s = (T)sin((double)r); T omc = (T)1 - c; T x = axis.x; T y = axis.y; T z = axis.z; result.values[0 + 0 * 4] = x * x * omc + c; result.values[0 + 1 * 4] = y * x * omc + z * s; result.values[0 + 2 * 4] = x * z * omc - y * s; result.values[1 + 0 * 4] = x * y * omc - z * s; result.values[1 + 1 * 4] = y * y * omc + c; result.values[1 + 2 * 4] = y * z * omc + x * s; result.values[2 + 0 * 4] = x * z * omc + y * s; result.values[2 + 1 * 4] = y * z * omc - x * s; result.values[2 + 2 * 4] = z * z * omc + c; return result;*/ const T a = toRadians(angle); const T c = cos(a); const T s = sin(a); Vector3<T> axis(v); axis.normalise(); Vector3<T> temp(axis * (T(1) - c)); Matrix4<T> Rotate(1); Rotate.values[MAT4_GET(0, 0)] = c + temp.x * axis.x; Rotate.values[MAT4_GET(1, 0)] = temp.x * axis.y + s * axis.z; Rotate.values[MAT4_GET(2, 0)] = temp.x * axis.z - s * axis.y; Rotate.values[MAT4_GET(0, 1)] = temp.y * axis.x - s * axis.z; Rotate.values[MAT4_GET(1, 1)] = c + temp.y * axis.y; Rotate.values[MAT4_GET(2, 1)] = temp.y * axis.z + s * axis.x; Rotate.values[MAT4_GET(0, 2)] = temp.z * axis.x + s * axis.y; Rotate.values[MAT4_GET(1, 2)] = temp.z * axis.y - s * axis.x; Rotate.values[MAT4_GET(2, 2)] = c + temp.z * axis.z; /*Matrix4<T> Result(0); Result[0] = m[0] * Rotate[0][0] + m[1] * Rotate[0][1] + m[2] * Rotate[0][2]; Result[1] = m[0] * Rotate[1][0] + m[1] * Rotate[1][1] + m[2] * Rotate[1][2]; Result[2] = m[0] * Rotate[2][0] + m[1] * Rotate[2][1] + m[2] * Rotate[2][2]; Result[3] = m[3];*/ return Rotate; } template <class T> Matrix4<T> Matrix4<T>::scale(const T &x, const T &y, const T &z) { Matrix4<T> mat(1); mat.values[MAT4_GET(0, 0)] = x; mat.values[MAT4_GET(1, 1)] = y; mat.values[MAT4_GET(2, 2)] = z; return mat; } template <class T> Matrix4<T> Matrix4<T>::scale(const Vector3<T> &v) { return scale(v.x, v.y, v.z); } template <class T> Matrix4<T>::Matrix4(const T &v) { for (unsigned int i = 0; i < 16; i++) { values[i] = 0; } values[MAT4_GET(0, 0)] = v; values[MAT4_GET(1, 1)] = v; values[MAT4_GET(2, 2)] = v; values[MAT4_GET(3, 3)] = v; } template <class T> Matrix4<T>::Matrix4(const Matrix4<T> &mat) { for (unsigned int i = 0; i < 16; i++) values[i] = mat.values[i]; } template <class T> Matrix4<T> &Matrix4<T>::multiply(const Matrix4<T> &mat) { T sum[4]; for (unsigned int r = 0; r < 4; r++) { for (unsigned int c = 0; c < 4; c++) { sum[c] = 0; for (unsigned int i = 0; i < 4; i++) { sum[c] += values[MAT4_GET(r, i)] * mat.values[MAT4_GET(i, c)]; } } for (unsigned int i = 0; i < 4; i++) { values[MAT4_GET(r, i)] = sum[i]; } } return *this; } template <class T> Matrix4<T> &Matrix4<T>::multiply(const T &v) { for (unsigned int i = 0; i < 16; i++) { values[i] *= v; } } template <class T> Vector4<T> Matrix4<T>::multiply(const Vector4<T> &v) const { Vector4<T> v1(v); v1.x = values[MAT4_GET(0, 0)] * v.x + values[MAT4_GET(0, 1)] * v.y + values[MAT4_GET(0, 2)] * v.z + values[MAT4_GET(0, 3)] * v.w; v1.y = values[MAT4_GET(1, 0)] * v.x + values[MAT4_GET(1, 1)] * v.y + values[MAT4_GET(1, 2)] * v.z + values[MAT4_GET(1, 3)] * v.w; v1.z = values[MAT4_GET(2, 0)] * v.x + values[MAT4_GET(2, 1)] * v.y + values[MAT4_GET(2, 2)] * v.z + values[MAT4_GET(2, 3)] * v.w; v1.w = values[MAT4_GET(3, 0)] * v.x + values[MAT4_GET(3, 1)] * v.y + values[MAT4_GET(3, 2)] * v.z + values[MAT4_GET(3, 3)] * v.w; return v1; } template <class T> inline void Matrix4<T>::print() { std::cout << *this; } template <class T> Matrix4<T> &Matrix4<T>::operator*=(const Matrix4<T> &mat2) { return multiply(mat2); } template <class T> Matrix4<T> &Matrix4<T>::operator*=(const T &v) { return multiply(v); } template <class T> Vector4<T> &Matrix4<T>::operator[](unsigned int i) { return columns[i]; } template <class T> Matrix4<T> operator*(const Matrix4<T> &mat1, const Matrix4<T> &mat2) { return Matrix4<T>(mat1).multiply(mat2); } template <class T> Matrix4<T> operator*(const Matrix4<T> &mat, const T &v) { return Matrix4<T>(mat).multiply(v); } template <class T> Vector4<T> operator*(const Matrix4<T> &mat, const Vector4<T> &v) { return mat.multiply(v); } template <class T> std::ostream &operator<<(std::ostream &os, const Matrix4<T> &mat) { for (unsigned int r = 0; r < 4; r++) { os << "[ "; for (unsigned int c = 0; c < 4; c++) { os << mat.values[MAT4_GET(r, c)] << " "; } os << "]" << std::endl; } return os; } typedef Matrix4<GLfloat> Matrix4f; typedef Matrix4<GLdouble> Matrix4d; typedef Matrix4<GLint> Matrix4i; } // namespace Johnny
PucklaMotzer09/3DEngine
include/operators.h
#ifndef OPERATORS_H_INCLUDED #define OPERATORS_H_INCLUDED #include <string> extern const std::string operator+(const std::string &, int); extern const std::string operator+(int, const std::string &); extern const std::string operator+(const std::string &, const double &); extern const std::string operator+(const double &, const std::string &); extern const std::string operator+(const std::string &, const float &); extern const std::string operator+(const float &, const std::string &); #endif // OPERATORS_H_INCLUDED
PucklaMotzer09/3DEngine
include/mathematics_functions.h
#pragma once #ifndef _USE_MATH_DEFINES #define _USE_MATH_DEFINES 1 #endif #include <algorithm> #include <cmath> #include <cstdlib> #include <math.h> #include <vector> namespace Johnny { /*! \brief Converts degrees into radians * \param degrees The value in degrees * \return The value in radians */ template <class T> inline T toRadians(const T &degrees) { return degrees / (T)180 * (T)M_PI; } /*! \brief Converts radians into degrees * \param radians The value in radians * \return The value in degrees */ template <class T> inline T toDegrees(const T &radians) { return radians * (T)180 / (T)M_PI; } /*! \brief Gets the absolute value of a number * \param d The value to get the absolute from * \param The absolute value of d */ template <class T> inline double abs(const T &d) { return d < (T)0 ? -d : d; } /*! \brief Gets a random value in a given range * \param min The minimum value * \param max The maximum value * \return A random value between min and max */ inline int getRand(int min, int max) { return rand() % (max - min + 1) + (min); } /*! \param percent The amount of percent in which the return value should be * true \return true if a random value between 1 and 100 <= percent */ inline bool luck(int percent) { return getRand(1, 100) <= percent; } /*! \brief Gets an elements of an array for a given coordinate * \param vars The array to fetch the element from * \param x The x coordinate of the element * \param y The y coordinate of the element * \param w The width of the 2D array * \return The element at the given coordinate */ template <class T> inline T get(const std::vector<T> &vars, int x, int y, int w) { return vars[y * w + x]; } /*! \brief Checks if a given value is inside a given array * \param vars The array to check * \param var The variable to check * \return true if the variable is inside the array and false if not */ template <class T, class D> inline bool contains(const std::vector<T> &vars, const D &var) { return std::find(vars.begin(), vars.end(), var) != vars.end(); } /*! \brief Swaps two variables with each other * \param var1 The one variable for the swap * \param var2 The other variable for the swap */ template <class T> inline void swap(T var1, T var2) { T temp = var1; var1 = var2; var2 = temp; } /*! \brief Reverses a given array * \param vars The array to reverse */ template <class T> inline void reverse(const std::vector<T> &vars) { int j = 0; for (int i = (int)vars.size() - 1; i > j; i--) { swap(vars[i], vars[j]); j++; } } /*! \param var The array from which to get the size * \return The number of elements of an array */ template <class T> inline int sizeOfArray(T var[]) { return sizeof(var) / sizeof(*var); } /*! \brief clamps a value between to given boundaries * \param var The variable to clamp * \param min The minimum boundary * \param max The maximum boundary * \return if var>max then max if var<min then min else var */ template <class T> inline T clamp(const T &var, const T &min, const T &max) { return (var > max ? max : (var < min ? min : var)); } } // namespace Johnny
PucklaMotzer09/3DEngine
include/Skybox.h
<filename>include/Skybox.h #pragma once #include "../include/Actor.h" #include "ShaderUpdater.h" #include "Vector3.h" #include <GL/glew.h> #include <string> namespace Johnny { class CubeMap3D; class Shader; /*! \brief The ShaderUpdater for the Skybox * */ class SkyboxShaderUpdater : public ShaderUpdater { public: SkyboxShaderUpdater(Shader *s) : ShaderUpdater(s) {} ~SkyboxShaderUpdater() {} void setUniforms(Skybox *, const unsigned int index = 0) override; void setUniforms(Lighting3D *, const unsigned int index = 0) override {} void setUniforms(Camera3D *, const unsigned int index = 0) override; }; /*! \brief A Vertex which is used for the SkyboxMesh * */ class SkyboxVertex { public: Vector3f position; //!< Position of the SkyboxVertex }; /*! \brief The mesh wich is used for the Skybox * */ class SkyboxMesh { public: SkyboxMesh(); ~SkyboxMesh(); /*! \brief Adds vertices to the buffer * \param vertices An array SkyboxVertices to add * \param size The number of vertices to add */ void addVertices(SkyboxVertex *vertices, unsigned int size); /*! \brief Renders the SkyboxMesh * */ void render(); private: GLuint m_vbo = 0; //!< The name of the vertex buffer GLuint m_vao = 0; //!< The vertex arrray object of the SkyboxMesh GLsizei m_numVertices = 0; //!< The number of vertices in the buffer }; /*! \brief An enum which consists of the planes of the Skybox * */ enum SkyboxTex { SKY_RIGHT = 0, SKY_LEFT = 1, SKY_TOP = 2, SKY_BOTTOM = 3, SKY_FRONT = 4, SKY_BACK = 5 }; /*! \brief A class which represents a box which is around the player and has no * view translation * */ class Skybox : public Actor { public: friend class SkyboxShaderUpdater; /*! \brief Deletes the SkyboxMesh and SkyboxShader * */ static void clear(); Skybox(); ~Skybox(); /*! \brief The init method * * * It is overriding the method from Actor */ bool init() override; /*! \brief The update method * * * It is overriding the method from Actor */ bool update() override; /*! \brief The render method * * * It is overriding the method from Actor */ bool render() override; /*! \brief The quit method * * * It is overriding the method from Actor */ void quit() override; /*! \brief Sets the texture file of a plane of the Skybox * \param plane Which plane to set the file for * \param file The file path of the texture relateive to res/textures */ void setTexture(short plane, const std::string &file); private: static Shader *SKYBOX_SHADER; //!< The Shader which is used for rendering the Skybox static SkyboxMesh *SKYBOX_MESH; //!< The Mesh which is used for rendering the Skybox CubeMap3D *m_cubeMap = nullptr; //!< The CubeMap3D which stores the texture planes std::string m_textures[6]; //!< The file paths od the texture planes bool m_texturesSet = false; //!< true if any texture has been set and false otherwhise }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/Window.h
#ifndef Window_H #define Window_H #include "../include/Actor.h" #include "../include/Vector2.h" #include <GL/glew.h> #include <SDL2/SDL_stdinc.h> #include <SDL2/SDL_video.h> namespace Johnny { class MainClass; class Texture; class TextureData; class Framework; /*! \brief A class which represents a window on a screen * */ class Window { public: Window(void *handle); virtual ~Window(); /*! \brief Sets the Window into fullscreen mode or windowed mode * \param full if true the Window goes into fullscreen or stays in * fullscreen, if false the Window goes into windowed mode or stays in * windowed mode \param flags The flags for the fullscreen transition */ void setFullscreen(bool full = true, bool desktop = true); /*! \brief Sets the window into borderless mode * \param border if true the window switches into borderless mode or stays in * borderless mode */ void setBorderless(bool border = true); /*! \brief Sets the title of the Window * \param title The title of the Window */ void setTitle(const std::string &title); /*! \brief Sets the resolution of the Window * \param res The new resolution */ void setResolution(const Vector2i &res); /*! \brief Sets the resolution of the Window * \param w The new width of the Window in pixels * \param h The new height of the Window in pixels */ void setResolution(int w, int h); /*! \brief Sets the position of the Window on the screen * \param pos The new position */ void setPosition(const Vector2i &pos); /*! \brief Sets the position of the Window on the screen * \param x The new x position * \param y The new y position */ void setPosition(int x, int y); /*! \brief Sets the icon of the Window * \param tex The texture to use as icon * \param target The target to which the Texture should be bound * \param format The pixel format of the Texture * \param type The type in which the pixel channels of the Texture are stored */ void setIcon(Texture *tex, GLenum target = GL_TEXTURE_2D, GLenum format = GL_RGBA, GLenum type = GL_UNSIGNED_BYTE); /*! \brief Sets the icon of the Window * \param tex The TextureData to use as icon */ void setIcon(TextureData *tex); /*! \return The resolution of the Window * */ const Vector2i getResolution(); /*! \brief Checks if the Window is borderless * \return true if the Window is borderless and false otherwhise */ bool isBorderless(); /*! \brief Checks if the Window is in fullscreen * \return true if the Window is in fullscreen and false otherwhise */ bool isFullscreen(); void setHandle(void *handle) { m_handle = handle; } void *getHandle() { return m_handle; } bool swap(); private: MainClass *m_mainClass = nullptr; //!< The MainClass which was passed through the constructor Vector2i m_res; //!< The resolution of the Window void *m_handle = nullptr; //!< The handle of the window of the framework }; } // namespace Johnny #endif // Window_H
PucklaMotzer09/3DEngine
include/SDLFramework.h
#ifndef SDLFRAMEWORK_H #define SDLFRAMEWORK_H #include "Events.h" #include "Framework.h" #include <SDL2/SDL.h> namespace Johnny { class SDLFramework : public Framework { public: bool init(FrameworkInitFlags flags) override; bool quit() override; bool initWindow() override; bool initGraphics() override; bool createOpenGLContext() override; Window *createWindow(const std::string &title, unsigned int x, unsigned int y, unsigned int w, unsigned int h, WindowFlags flags) override; bool swapWindow(Window *window) override; bool destroyWindow(Window *window) override; std::string getError() override; bool pollEvent() override; ; bool setWindowTitle(Window *window, const std::string &title) override; bool setWindowResolution(Window *window, const Vector2i &res) override; bool setWindowPosition(Window *window, const Vector2i &pos) override; bool setWindowFullscreen(Window *window, bool fullscreen = true, bool desktop = true) override; bool setWindowBorderless(Window *window, bool borderless = true) override; bool setWindowIcon(Window *window, Texture *tex, GLenum target = GL_TEXTURE_2D, GLenum format = GL_RGBA, GLenum type = GL_UNSIGNED_BYTE) override; bool setWindowIcon(Window *window, TextureData *texdata) override; std::string getWindowTitle(Window *window) override; Vector2i getWindowResolution(Window *window) override; Vector2i getScreenResolution() override; bool isWindowFullscreen(Window *window) override; bool isWindowBorderless(Window *window) override; int getControllerID(void *handle) override; bool isSameController(void *handle1, void *handle2) override; void *openController(int id) override; void closeController(void *handle) override; bool isAttachedController(void *handle) override; void lockAndHideCursor() override; void hideCursor() override; void showCursor() override; bool isCursorHidden() override; private: Uint32 initFlagsToSDLFlags(FrameworkInitFlags flags); Uint32 windowFlagsToSDLFlags(WindowFlags flags); EventType toJohnnyEventType(unsigned int type); WindowEventType toJohnnyWindowEventType(Uint8 id); void toJohnnyEvent(const SDL_Event &e, Event *event); SDL_Event m_event; }; } // namespace Johnny #endif
PucklaMotzer09/3DEngine
include/Timer.h
<gh_stars>0 #pragma once #include <SDL2/SDL2_framerate.h> #include <chrono> #define NO_FPS_LOCK -1 using namespace std; using namespace chrono; namespace Johnny { /*! \brief A class for measuring time, smoothing the timestep and locking the * framerate * */ class Timer { public: Timer(); ~Timer(); /*! \brief Sets the value which will be multiplied on the delta time * \param d The value which will be used for the multiplication */ void setTimeScale(double d) { m_timeScale = d; } /*! \brief Defines on which FPS it should lock or if it shouldn't lock the * framerate \param The frame rate to lock */ void setMaxFPS(int maxFPS); /*#ifdef _WIN32 float getDeltaTimeInSeconds() const { return (float)(m_realDeltaTimeInSeconds*m_timeScale); } #else*/ /*! \return The time between the last frame and this frame but smoothed over * multiple frames * */ float getDeltaTimeInSeconds() const { return (float)(m_smoothDeltaTimeInSeconds * m_timeScale); } //#endif /*! \return The frames per second * */ double getFPS() const { return m_fps; } /*! \return The frame rate on which it should lock * */ int getMaxFPS() { return m_maxFPS; } /*! \brief Starts the time measurment * */ void startTimeMeasure(); /*! \brief Ends the time measurement, calculates the smoothed delta time and * locks the frame rate \return The frames per second */ int endTimeMeasure(); private: int m_maxFPS = 60; //!< The FPS at which it should lock double m_timeScale = 1.0; //!< The value which will be multiplied onto the delta time double calculateMeanDeltaTime(); //!< Caclulates the average of the last frames void takeAwayHighestAndLowestDts(); //!< Takes away the two hightest and //!< lowest delta times from the array void moveDeltaTimesOneIndexDown(); //!< Shifts the delta times one index down //!< on the array int getDeltaTimesSize(); //!< Gets the number of frame times saved in the //!< array void copyRealTimesToSmoothTimes(); //!< Copies the measured delta times array //!< into the smoothed delta times array int m_realDeltaTimeSize = 0; //!< The number of real delta times measured void setNum(double &, int &); //!< Sets a number double m_realDeltaTimeInSeconds = 0.0; //!< The delta time measured double m_smoothDeltaTimeInSeconds = 0.0; //!< The delta time smoothed by the calculations double m_realDeltaTimes[11] = { -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}; //!< The array of real measured delta times double m_smoothDeltaTimes[11] = { -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0}; //!< The array of smoothed delta times double m_FPSes[3]; //!< The frames per second of the last frames double m_fps = 0.0; //!< The fps averaged over the last three frames int m_lastFrame = 0; //!< The number of the last frame double m_time = 0.0; //!< The time high_resolution_clock::time_point m_startTime; //!< A high_resolution clock for measuring the time high_resolution_clock::time_point m_endTime; //!< A high_resolution clock for measuring the time #ifdef MAX_FPS_LOCK double m_timeForMaxFPS = 0.0; high_resolution_clock::time_point m_startTimeForMaxFPS; high_resolution_clock::time_point m_endTimeForMaxFPS; duration<double, micro> m_deltaClockTimeForMaxFPS; #endif duration<double, micro> m_deltaClockTime; //!< A duration for measuring the time FPSmanager m_fpsManager; //!< The FPSManager which locks the frame rate }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/Sprite2D.h
#pragma once #include "Actor.h" #include "Geometry.h" #include "Texture.h" #include "Tween.h" #include <string> namespace Johnny { class TiledMap; /*! \brief A class which represents a Texture as an Actor * */ class Sprite2D : public Actor, public TweenableObject2D { public: friend class TiledMap; Sprite2D(); /*! \brief Creates a new Sprite2D * \param file The file path of the Texture for the sprite relative to * res/textures */ Sprite2D(const std::string &file); /*! \brief Creates a new Sprite2D * \param tex The Texture for the new Sprite2D */ Sprite2D(Texture *tex); ~Sprite2D(); /*! \brief The init method * * * It is overriding the method from Actor */ virtual bool init() override; /*! \brief The update method * * * It is overriding the method from Actor */ virtual bool update() override; /*! \brief The render method * * * It is overriding the method from Actor */ virtual bool render() override; /*! \brief The quit method * * * It is overriding the method from Actor */ virtual void quit() override; /*! \brief Sets the Texture of the Sprite2D * \param tex The Texture to set */ void setTexture(Texture *tex); /*! \brief Sets the source region of the Sprite2D which defines what to use * from the texture for rendering \param region The TextureRegion to set */ void setSrcRegion(const TextureRegion &region); /*! \brief Sets the draw size of the Sprite2D which defines how big the * Texture should be rendered in pixels \param v A vector to set the size */ void setDrawSize(const Vector2f &v); /*! \brief Sets the draw size of the Sprite2D which defines how big the * Texture should be rendered in pixels \param width The width which defines * how big the Texture should be drawn \param height The height which defines * how big the Texture should be drawn */ void setDrawSize(GLfloat width, GLfloat height); /*! \brief Sets the depth of the Sprite2D * \param depth The depth to set [-INT_MAX;INT_MAX] * * Objects with a smaller depth value are rendered above */ void setDepth(int depth) { m_depth = depth; } /*! \return The Texture of the Sprite2D * */ Texture *getTexture() { return m_texture; } /*! \return The source region which defines what to draw from the Texture * */ const TextureRegion &getSrcRegion() const { return m_srcRegion; } /*! \return The size with which the Sprite2D will be drawn * */ Vector2f getDrawSize() const; /*! \return The draw size multiplied with the scale * */ Vector2f getActualSize() const; /*! \return The Bounding Box of the Sprite2D * */ Rectangle<GLfloat> getBoundingBox(); /*! \return The depth of the object * */ const int &getDepth() const { return m_depth; } /*! \brief Checks if this Sprite2D intersects with another Sprite2D * \param spr The Sprite2D to check * \return true if they intersect and false otherwhise */ bool intersects(Sprite2D *spr); /*! \brief Checks if this Sprite2D intersects with a position on the world * \param pos The position to check * \return true if they intersect and false otherwhise */ bool intersects(const Vector2f &pos); /*! \brief Checks if this Sprite2D intersects with a rectangle * \param rect The Rectangle to check * \return true if they intersect and false otherwhise */ bool intersects(const Rectangle<GLfloat> &rect); protected: Texture *m_texture = nullptr; //!< The Texture of the Sprite2D TextureRegion m_srcRegion; //!< The source region which defines what to use //!< from the Texture /*! \brief The depth of the Sprite2D * * * Objects with a smaller depth value are rendered above */ int m_depth = 0; private: std::string m_fileName = ""; //!< The file pathof the Texture Vector2f m_drawScale; //!< The scale which gets multiplied when rendering }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/MainClass.h
<gh_stars>0 #ifndef MAINCLASS_H #define MAINCLASS_H #include "Actor.h" #include "Colors.h" #include "Events.h" #include "Framework.h" #include "InputManager.h" #include "Timer.h" #include "Vector2.h" #include "Window.h" #include <GL/glew.h> #include <SDL2/SDL2_framerate.h> #include <SDL2/SDL_events.h> #include <SDL2/SDL_mixer.h> #include <SDL2/SDL_pixels.h> #include <chrono> #define NO_FPS_LOCK -1 using namespace std::chrono; namespace Johnny { class Lighting3D; class RenderManager; class Mesh3D; class FrameBuffer; class RenderBuffer; class Texture; class Skybox; class Timer; class Camera3D; class Camera2D; class ResourceManager; class JoystickManager; class Physics2D; /*! \brief A enum with all flags to determine what should be initialised * */ enum InitFlags { INIT_3D = 1 >> 0, //!< Initialises everything for 3D rendering INIT_2D = 1 << 1, //!< Initialises everything for 2D rendering JOYSTICK = 1 << 2, //!< Initialises the JoystickManager to capture controller inputs PHYSICS_3D = 1 << 3, //!< Initialises the Physics3D (will be ignored) PHYSICS_2D = 1 << 4, //!< Initialises the Physics2D AUDIO = 1 << 5, //!< Initialises audio output (will be ignored) EVERYTHING = ~0 //!< Initialises everything }; /*! \brief The main or root class where the application starts * * * This class handles all base things such as the initialisation. */ class MainClass : public Actor { public: /*! \brief Creates a new MainClass * \param initFlags Ore'd together InitFlags to determine what will be * initialised \param title The title of the Window which will be created * \param width The width of the Window in pixels * \param height The height of the Window in pixels * \param windowFlags The flags which will be used for the Window * initialisation (this value will be ore'd together with SDL_WINDOW_SHOWN | * SDL_WINDOW_OPENGL) */ MainClass(unsigned int initFlags = 0, const std::string &title = "New Window", unsigned int width = NORM_W, unsigned int height = NORM_H, WindowFlags windowFlags = 0); virtual ~MainClass(); /*! \brief Starts the engine. * Should be called in the main function * */ void run(); /*! \brief Sets the ambient light for all 3D lighting equations * \param color The color of the ambient light */ void setAmbientLight3D(const Colorb &color); /*! \brief Sets the resolution of the application (NOT the window resolutions) * \param v The resolution to set */ void setNativeRes(const Vector2f &v); /*! \brief Sets the background color which will be used to clear the screen * \param color The background color to set */ void setBackgroundColor(const Colorb &color); /*! \brief Renders every Actor with the given Shader DEPRECATED * \param s The Shader with which everything should be rendered */ void renderSceneForShadowMap(Shader *s); /*! \return The instance of the MainClass * */ static MainClass *getInstance() { return instance; } /*! \return The InputManager of the object * */ InputManager *getInputManager() { return m_inputManager; } /*! \return The ResourceManager of the object * */ ResourceManager *getResourceManager() { return m_resourceManager; } /*! \return The Window of the object * */ Window *getWindow() { return m_window; } /*! \return The JoystickManager of the object * */ JoystickManager *getJoystickManager() { return m_joystickManager; } /*! \return The Lighting3D of the object * */ Lighting3D *getLighting3D() { return m_lighting3D; } /*! \return The RenderManager of the object * */ RenderManager *getRenderManager() { return m_renderManager; } /*! \return The back buffer of the object which is the texture to which * everything will be drawn and which will then be drawn to the screen * */ FrameBuffer *getBackBuffer() { return m_frameBufferMulti; } /*! \return The back buffer mesh of the object which is the mesh which will be * drawn to the screen with the back buffer on it * */ Mesh3D *getBackBufferMesh() { return m_frameBufferMesh; } /*! \return The Skybox of the object * */ Skybox *getSkybox() { return m_skybox; } /*! \return The Timer of the object which measures the frame time * */ Timer *getTimer() { return m_timer; } /*! \return The Physics2D of the object which handles all 2D physics related * things * */ Physics2D *getPhysics2D() { return m_physics2D; } /*! \return The Framwork of the object which handles framework based stuff * */ Framework *getFramework() { return m_framework; } /*! \return The Camera3D of the object * */ Camera3D *getCamera3D(); /*! \return The Camera2D of the object * */ Camera2D *getCamera2D(); /*! \return Native_Resolution.x / Window_Resolution.x * */ float getScaleW() const { return m_scaleW; } /*! \return Native_Resolution.y / Window_Resolution.y * */ float getScaleH() const { return m_scaleH; } /*! \return The resolution of the back buffer * */ const Vector2f &getNativeRes() const { return m_nativeResolution; } /*! \return The background color of the object which will be used to clear the * screen * */ const Colorb &getBackgroundColor() const { return m_backgroundColor; } /*! \return The ambient Light * */ const Colorb &getAmbientLight3D() const; /*! \brief The render function * * * It is overriding the method from Actor */ virtual bool render() override; /*! \brief The update function * * * It is overriding the method from Actor */ virtual bool update() override; /*! \brief The m_update function * * * It is overriding the method from Actor */ virtual bool m_update() override; /*! \brief Gets called when the Window resizes * \param width The new width of the Window * \param height The new height of the Window */ virtual void onResize(unsigned int width, unsigned int height); /*! \brief Gets called when the Window switches to fullscreen or switches to * windowed mode \param full true if the window switches to fullscreen * otherwise false */ virtual void onFullscreen(bool full); protected: /*! \brief The quit method * * * It is overriding the method from Actor */ virtual void quit() override = 0; /*! \brief The init method * * * It is overriding the method from Actor */ virtual bool init() override = 0; /*! \brief Gets called every frame to poll the events * */ virtual bool pollEvents(); /*! \brief Gets called always when an event occoured * \param e The event that happened */ virtual bool pollEvent(const Event &e); InputManager *m_inputManager = nullptr; //!< The InputManager of the object ResourceManager *m_resourceManager = nullptr; //!< The ResourceManager of the object Window *m_window = nullptr; //!< The Window of the object Camera3D *m_camera3D = nullptr; //!< The Camera3D of the object Camera2D *m_camera2D = nullptr; //!< The Camera2D of the object JoystickManager *m_joystickManager = nullptr; //!< The JoystickManager of the object Lighting3D *m_lighting3D = nullptr; //!< The Lighting3D of the object RenderManager *m_renderManager = nullptr; //!< The RenderManager of the object Skybox *m_skybox = nullptr; //!< The Skybox of the object Timer *m_timer = nullptr; //!< The Timer of the object Physics2D *m_physics2D = nullptr; //!< The Physics2D of the object Framework *m_framework = nullptr; //!< The Framework of the object private: static MainClass *instance; //!< The instance of the MainClass /*! \brief Gets called when m_initFlags contains InitFlags::INIT_3D and * initialises all 3D rendering related things * */ void init3D(); /*! \brief Gets called when m_initFlags contains InitFlags::INIT_2D and * initialises all 2D rendering related things * */ void init2D(); /*! \brief Gets called when m_initFlags contains InitFlags::JOYSTICK and * initialises the JoystickManager * */ void activateJoystick(); /*! \brief Gets called after the engine has initialised * */ void afterInit(); /*! \brief Handles quitting for internal porpuses * */ void m_quit(); /*! \brief Contains the main loop of the engine * */ void mainLoop(); /*! \brief Handles initialising for internal porpuses * */ void m_init(); Mesh3D *m_frameBufferMesh = nullptr; //!< The Mesh which will be drawn on the //!< screen with the back buffer on it FrameBuffer *m_frameBufferMulti = nullptr; //!< The FrameBuffer which is used to draw to the back buffer FrameBuffer *m_frameBuffer = nullptr; //!< The FrameBuffer which will be used to draw to the screen RenderBuffer *m_renderBufferMulti = nullptr; //!< The RenderBuffer which will be attached to //!< m_frameBufferMulti for depth rendering RenderBuffer *m_renderBuffer = nullptr; //!< The RenderBuffer which will be attached to m_frameBuffer for //!< depth rendering Texture *m_frameBufferTexMulti = nullptr; //!< The Texture which will be attached to m_frameBufferMulti for //!< color rendering Texture *m_frameBufferTex = nullptr; //!< The Texture which will be attached //!< to m_frameBuffer for color rendering std::string m_windowTitle; //!< The title of the Window which was passed //!< through the constructor unsigned int m_windowWidth; //!< The width of the Window which was passed //!< through the constructor in pixels unsigned int m_windowHeight; //!< The height of the Window which was passed //!< through the constructor in pixels float m_scaleW; //!< Native_Resolution.x / Window_Resolution.x float m_scaleH; //!< Native_Resolution.y / Window_Resolution.y GLint m_viewportOffsetX = 0; //!< The x offset of the back buffer on the screen GLint m_viewportOffsetY = 0; //!< The y offset of the back buffer on the screen Colorb m_backgroundColor; //!< The bakground color which will be used to clear //!< the screen Vector2f m_nativeResolution; //!< The resolution of the back buffer WindowFlags m_initWindowFlags = 0; //!< The windowFlags which were passed through the constructor unsigned int m_initFlags = 0; //!< The initFlags which were passed through the constructor }; } // namespace Johnny #endif // MAINCLASS_H
PucklaMotzer09/3DEngine
include/Vector2.h
#pragma once #include "../include/mathematics_functions.h" #include <GL/glew.h> #include <cmath> #include <iostream> namespace Johnny { template <class T> class Vector2; template <class T> const Vector2<T> operator+(const Vector2<T> &, const Vector2<T> &); template <class T> const Vector2<T> operator-(const Vector2<T> &, const Vector2<T> &); template <class T> const Vector2<T> operator*(const Vector2<T> &, const Vector2<T> &); template <class T> const Vector2<T> operator*(const Vector2<T> &, const T &); template <class T> const Vector2<T> operator/(const Vector2<T> &, const Vector2<T> &); template <class T> const Vector2<T> operator/(const Vector2<T> &, const T &); template <class T> std::ostream &operator<<(std::ostream &, const Vector2<T> &); /*! \brief A class which represents a value with two dimensions * \param T The type of the elements of the Vector2 */ template <class T> class Vector2 { public: Vector2() = default; /*! \brief Creates a new Vector2 * \param x The x value of the new Vector2 * \param y The y value of the new Vector2 */ Vector2(const T &x, const T &y); /*! \brief Copies a Vector2 * \param v The Vector2 to copy */ Vector2(const Vector2 &v); union { T x = 0; //!< The x value of the Vector2 if it is used as a position T r; //!< The x value of the Vector2 if it is used as a color T width; //!< The x value of the Vector2 if it is used as dimensions }; union { T y = 0; //!< The y value of the Vector2 if it is used as a position T g; //!< The y value of the Vector2 if it is used as a color T height; //!< The y value of the Vector2 if it is used as dimensions }; /*! \param squared Wether the result should be the squared length or not * \return The length of the Vector2 */ T length(bool squared = false) const; /*! \brief Normalises a Vector2 * \return A reference to this object */ Vector2 &normalise(); /*! \brief Adds a Vector2 to this object * \param v The Vector2 to add * \return A reference to this object */ Vector2 &add(const Vector2 &v); /*! \brief Subtracts a Vector2 from this object * \param v The Vector2 to subtract * \return A refreence to this object */ Vector2 &subtract(const Vector2 &v); /*! \brief Multiplies each element of the Vector2 which each other * \param v The Vector2 for the multiplication * \return A reference to this object */ Vector2 &multiply(const Vector2 &v); /*! \brief Multiplies this vector with a scalar * \param s The scalar to multiply * \return A reference to the object */ Vector2 &multiply(const T &s); /*! \brief Divides each element of the Vector2 by the corresponding element of * the other Vector2 \param v The other Vector2 for the division \return A * reference to the object */ Vector2 &divide(const Vector2 &v); /*! \brief Divides each element by a scalar * \param s The scalar for the division * \return A reference to the object */ Vector2 &divide(const T &s); /*! \return The angle between the positive x-Axis and the Vector2 * */ T angle() const; /*! \brief Calculates the dot product with this Vector2 and another one * \param v The other Vector2 of the dot product * \return The calculated dot product */ T dot(const Vector2 &v) const; /*! \brief Calculates the distance between this Vector2 and another Vector2 * \param v The other Vector2 for the calculation * \param squared Wether the result should be the squared distance * \return The distance between this Vector2 and the other Vector2 */ T distance(const Vector2 &v, bool squared = false) const; Vector2 &operator+=(const Vector2 &); Vector2 &operator-=(const Vector2 &); Vector2 &operator*=(const Vector2 &); Vector2 &operator/=(const Vector2 &); Vector2 &operator*=(const T &); Vector2 &operator/=(const T &); friend const Vector2<T> operator+<>(const Vector2<T> &, const Vector2<T> &); friend const Vector2<T> operator-<>(const Vector2<T> &, const Vector2<T> &); friend const Vector2<T> operator*<>(const Vector2<T> &, const Vector2<T> &); friend const Vector2<T> operator*<>(const Vector2<T> &, const T &); friend const Vector2<T> operator/<>(const Vector2<T> &, const Vector2<T> &); friend const Vector2<T> operator/<>(const Vector2<T> &, const T &); friend std::ostream &operator<<<>(std::ostream &, const Vector2<T> &); }; template <class T> Vector2<T>::Vector2(const T &x, const T &y) { this->x = x; this->y = y; } template <class T> Vector2<T>::Vector2(const Vector2<T> &v) { x = v.x; y = v.y; } template <class T> T Vector2<T>::length(bool squared) const { if (squared) return x * x + y * y; else return sqrt(x * x + y * y); } template <class T> Vector2<T> &Vector2<T>::normalise() { T Length = length(); x /= Length; y /= Length; return *this; } template <class T> Vector2<T> &Vector2<T>::add(const Vector2<T> &v) { x += v.x; y += v.y; return *this; } template <class T> Vector2<T> &Vector2<T>::subtract(const Vector2<T> &v) { x -= v.x; y -= v.y; return *this; } template <class T> Vector2<T> &Vector2<T>::multiply(const Vector2<T> &v) { x *= v.x; y *= v.y; return *this; } template <class T> Vector2<T> &Vector2<T>::multiply(const T &s) { x *= s; y *= s; return *this; } template <class T> Vector2<T> &Vector2<T>::divide(const Vector2<T> &v) { x /= v.x; y /= v.y; return *this; } template <class T> Vector2<T> &Vector2<T>::divide(const T &s) { x /= s; y /= s; return *this; } template <class T> T Vector2<T>::angle() const { T _angle = -(T)toDegrees(atan2(y, x)); if (_angle < (T)0 && _angle > (T)-180) { _angle = (T)360 + _angle; } return _angle; } template <class T> T Vector2<T>::dot(const Vector2<T> &v) const { return x * v.x + y * v.y; } template <class T> T Vector2<T>::distance(const Vector2<T> &v, bool squared) const { Vector2<T> v1(v); v1.subtract(*this); return v1.length(squared); } template <class T> Vector2<T> &Vector2<T>::operator+=(const Vector2<T> &v2) { return add(v2); } template <class T> Vector2<T> &Vector2<T>::operator-=(const Vector2<T> &v2) { return subtract(v2); } template <class T> Vector2<T> &Vector2<T>::operator*=(const Vector2<T> &v2) { return multiply(v2); } template <class T> Vector2<T> &Vector2<T>::operator/=(const Vector2<T> &v2) { return divide(v2); } template <class T> Vector2<T> &Vector2<T>::operator*=(const T &s) { x *= s; y *= s; return *this; } template <class T> Vector2<T> &Vector2<T>::operator/=(const T &s) { x /= s; y /= s; return *this; } template <class T> const Vector2<T> operator+(const Vector2<T> &v1, const Vector2<T> &v2) { return Vector2<T>(v1).add(v2); } template <class T> const Vector2<T> operator-(const Vector2<T> &v1, const Vector2<T> &v2) { return Vector2<T>(v1).subtract(v2); } template <class T> const Vector2<T> operator*(const Vector2<T> &v1, const Vector2<T> &v2) { return Vector2<T>(v1).multiply(v2); } template <class T> const Vector2<T> operator*(const Vector2<T> &v, const T &s) { return Vector2<T>(v).multiply(s); } template <class T> const Vector2<T> operator/(const Vector2<T> &v1, const Vector2<T> &v2) { return Vector2<T>(v1).divide(v2); } template <class T> const Vector2<T> operator/(const Vector2<T> &v, const T &s) { return Vector2<T>(v).divide(s); } template <class T> std::ostream &operator<<(std::ostream &os, const Vector2<T> &v) { os << "(" << v.x << ";" << v.y << ")"; return os; } typedef Vector2<GLfloat> Vector2f; typedef Vector2<GLdouble> Vector2d; typedef Vector2<GLint> Vector2i; } // namespace Johnny
PucklaMotzer09/3DEngine
include/Defines.h
#ifndef JOHNNY_DEFINES_H #define JOHNNY_DEFINES_H #define JOHNNY_RES (m_mainClass->getResourceManger()) #define JOHNNY_NATIVE_RES (m_mainClass->getNativeRes()) #define JOHNNY_NATIVE_RES_WIDTH (JOHNNY_NATIVE_RES.width) #define JOHNNY_NATIVE_RES_HEIGHT (JOHNNY_NATIVE_RES.height) #define JOHNNY_SKY (m_mainClass->getSkybox()) #define JOHNNY_DT (m_mainClass->getTimer()->getDeltaTimeInSeconds()) #define JOHNNY_INPUT (m_mainClass->getInputManager()) #define JOHNNY_JOY (m_mainClass->getJoystickManager()) #define JOHNNY_JOY_LIS (m_mainClass->getJoystickManager()->getListener()) #endif
PucklaMotzer09/3DEngine
include/ShaderUpdater.h
<filename>include/ShaderUpdater.h<gh_stars>0 #ifndef SHADER_UPDATER_H #define SHADER_UPDATER_H #include "Geometry.h" namespace Johnny { class Shader; class Mesh3D; class Model3D; class Lighting3D; class Camera3D; class Transform3D; class Material; class Entity3D; class Sprite2D; class Skybox; class Transform2D; class Texture; /*! \brief A class which is used to update the uniforms of a Shader * */ class ShaderUpdater { public: static const unsigned int TRANSFORM_NORMAL; //!< The index to indicate that a normal transform //!< should be loaded static const unsigned int TRANSFORM_CAMERA; //!< The index to indicate that a camera transformed //!< transform should be loaded static const unsigned int TRANSFORM_WORLD; //!< The index to indicate that a world transform should //!< be loaded; /*! \brief Creates a new ShaderUpdater * \param s The shader which should be updated */ ShaderUpdater(Shader *s); virtual ~ShaderUpdater(); /*! \brief Gets called every frame before anything is rendered * */ virtual void update() {} /*! \brief Gets called every time a Mesh3D gets rendered * \param mesh The Mesh3D which should be rendered * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(Mesh3D *mesh, const unsigned int index = 0); /*! \brief Gets called every time a Model3D gets rendered * \param model The Model3D which should be rendered * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(Model3D *model, const unsigned int index = 0); /*! \brief Sets the uniforms for a Lighting3D * \param light The Lighting3D to set the uniforms for * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(Lighting3D *light, const unsigned int index = 0); /*! \brief Sets the uniforms for a Camera3D * \param cam The Camera3D to set the uniforms for * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(Camera3D *cam, const unsigned int index = 0); /*! \brief Sets the uniforms for a Transform3D * \param transform The Transform3D to set the uniforms for * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(Transform3D *transform, const unsigned int index = 0); /*! \brief Sets the uniforms for a Material * \param mat The Material to set the uniforms for * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(Material *mat, const unsigned int index = 0); /*! \brief Sets the uniforms for a Transform2D * \param transform The Transform2D to set the uniforms for * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(Transform2D *transform, const unsigned int index = 0) {} /*! \brief Sets the uniforms for a TextureRegion * \param region The TextureRegion to set the uniforms for * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(TextureRegion *region, const unsigned int index = 0) {} /*! \brief Gets called every time a Textrue gets rendered (unsused) * \param tex The tex which should be rendered * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(Texture *tex, const unsigned int index = 0) {} /*! \brief Gets called every time a Entity3D gets rendered * \param ent The Entity3D which should be rendered * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(Entity3D *ent, const unsigned int index = 0); /*! \brief Gets called every time a Sprite2D gets rendered * \param spr The Sprite2D which should be rendered * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(Sprite2D *spr, const unsigned int index = 0) {} /*! \brief Gets called every time a Skybox gets rendered * \param sky The Skybox which should be rendered * \param index The index of the function to make it possible to use multiple * versions of the function */ virtual void setUniforms(Skybox *sky, const unsigned int index = 0) {} protected: Shader *m_shader = nullptr; //!< The Shader which should be updated }; } // namespace Johnny #endif
PucklaMotzer09/3DEngine
include/Geometry.h
<filename>include/Geometry.h<gh_stars>0 #pragma once #include "Vector2.h" #include <ostream> namespace Johnny { template <class T> class Rectangle; template <class T> std::ostream &operator<<(std::ostream &, const Rectangle<T> &); /*! \brief A class which represents a rectangle * \param T The type of the x,y,width,height values */ template <class T> class Rectangle { public: /*! \brief Creates a new rectangle * with x=0,y=0,width=0,height=0 * */ Rectangle(); /*! \brief Creates a new rectangle * \param x The x value of the new rectangle * \param y The y value of the new rectangle * \param width The width value of the new rectangle * \param height The height value of the new rectangle */ Rectangle(const T &x, const T &y, const T &width, const T &height); /*! \brief Creates a new rectangle * \param pos The position of the new rectangle x=pos.x,y=pos.y * \param size The size of the new rectangle * width=size.width,height=size.height */ Rectangle(const Vector2<T> &pos, const Vector2<T> &size); ~Rectangle(); /*! \return The area of the rectangle * */ T area(); T x = 0; //!< The x coordinate of the position of the rectangle T y = 0; //!< The y coordinate of the position of the rectangle union { T width = 0; //!< The width of the rectangle T w; }; union { T height = 0; //!< The height of the rectangle T h; }; bool intersects(const Rectangle<T> &rect) const; friend std::ostream &operator<<<>(std::ostream &, const Rectangle<T> &); }; template <class T> Rectangle<T>::Rectangle() : Rectangle<T>(0, 0, 0, 0) {} template <class T> Rectangle<T>::Rectangle(const T &_x, const T &_y, const T &_width, const T &_height) : x(_x), y(_y), width(_width), height(_height) {} template <class T> Rectangle<T>::Rectangle(const Vector2<T> &pos, const Vector2<T> &_size) : x(pos.x), y(pos.y), width(_size.x), height(_size.y) {} template <class T> Rectangle<T>::~Rectangle() {} template <class T> T Rectangle<T>::area() { return width * height; } template <class T> bool Rectangle<T>::intersects(const Rectangle<T> &rect) const { return rect.x < x + width && rect.x + rect.width > x && rect.y < y + height && rect.y + rect.height > y; } template <class T> std::ostream &operator<<(std::ostream &os, const Rectangle<T> &r) { os << "(" << r.x << ";" << r.y << ";" << r.width << ";" << r.height << ")"; return os; } /*! \brief Defines a rectangle on a texture * */ typedef Rectangle<GLint> TextureRegion; } // namespace Johnny
PucklaMotzer09/3DEngine
include/Model3D.h
<reponame>PucklaMotzer09/3DEngine<filename>include/Model3D.h #pragma once #include "../include/Transform3D.h" #include <assimp/scene.h> #include <vector> namespace Johnny { class ResourceManager; class Mesh3D; class Shader; /*! \brief A class which represents a 3D model which consists of an array of * Mesh3Ds * */ class Model3D { public: /*! \brief Creates a Model3D from a aiNode * \param node The aiNode from which to get the data * \param scene The scene to which the node belongs * \param switchYandZ Defines wether to switch the y and z coordinates of the * vertex positions */ Model3D(aiNode *node, const aiScene *scene, bool switchYandZ); Model3D(); ~Model3D(); /*! \brief Adds a Mesh3D to the array * \param mesh The mesh to add */ void addMesh(Mesh3D *mesh); /*! \brief Loads the materials of the meshes * \param res The ResourceManager from which to load the materials */ void loadTextures(ResourceManager *res); /*! \brief Renders the model to the currently active frame buffer * \param s The Shader to which the mesh data should be loaded */ void render(Shader *s); /*! \return The array of meshes * */ const std::vector<Mesh3D *> &getMeshes() { return m_meshes; } /*! \return The transform loaded from the aiNode * */ const Transform3D &getTransform() const { return m_transform; } const std::string &getName() const { return m_name; } private: std::vector<Mesh3D *> m_meshes; //!< The array of meshes Transform3D m_transform; //!< The transform loaded from the aiNode std::string m_name = "NONE"; //!< The name of the model }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/Framework.h
<reponame>PucklaMotzer09/3DEngine #ifndef FRAMEWORK_H #define FRAMEWORK_H #include "Events.h" #include "JoystickListener.h" #include "Vector2.h" #include <GL/glew.h> #define ERROR_OUT(func, errorText) \ if (func < 0) \ Johnny::LogManager::error( \ std::string(errorText) + \ MainClass::getInstance()->getFramework()->getError()) namespace Johnny { typedef unsigned int WindowFlags; typedef unsigned int FrameworkInitFlags; enum FlagsWindow : WindowFlags { Fullscreen = 1 << 0, Fullscreen_Desktop = 1 << 1, OpenGL = 1 << 2, Shown = 1 << 3, Hidden = 1 << 4, Borderless = 1 << 5, Resizeable = 1 << 6, Minimized = 1 << 7, Maximized = 1 << 8, Input_Grapped = 1 << 9, Input_Focus = 1 << 10, Mouse_Focus = 1 << 11, Foreign = 1 << 12, Allow_HighDPI = 1 << 13, Mouse_Capture = 1 << 14, Always_On_Top = 1 << 15, Skip_Taskbar = 1 << 16, Utility = 1 << 17, Tooltip = 1 << 18, Popup_Menu = 1 << 19 }; enum FlagsInitFramework : FrameworkInitFlags { Measure_Time = 1 << 0, Audio = 1 << 1, Events = 1 << 6, Video = 1 << 2 | Events, Joystick = 1 << 3 | Events, Haptic = 1 << 4, GameController = 1 << 5 | Joystick, NoParachute = 1 << 7, Everything = Measure_Time | Audio | Video | Joystick | Haptic | GameController | Events | NoParachute }; enum class Frameworks { SDL, GLFW }; class Window; class Texture; class TextureData; class Event; class Framework { public: static Framework *createFramework(Frameworks fw); virtual bool init(FrameworkInitFlags flags) = 0; virtual bool quit() = 0; virtual bool initWindow() = 0; virtual bool initGraphics() = 0; virtual bool createOpenGLContext() = 0; /*! \brief Creates a new Window * \param title The title of the Window * \param x The x position on the screen of the Window * \param y The y position on the screen of the Window * \param w The width of the Window in pixels * \param h The height of the Window in pixels * \param flags The WindowFlags for the Window which define different things * like the resizability */ virtual Window *createWindow(const std::string &title, unsigned int x, unsigned int y, unsigned int w, unsigned int h, WindowFlags flags) = 0; virtual bool swapWindow(Window *window) = 0; virtual bool destroyWindow(Window *window) = 0; virtual std::string getError() = 0; virtual bool pollEvent() = 0; virtual bool setWindowTitle(Window *window, const std::string &title) = 0; virtual bool setWindowResolution(Window *window, const Vector2i &res) = 0; virtual bool setWindowPosition(Window *window, const Vector2i &pos) = 0; virtual bool setWindowFullscreen(Window *window, bool fullscreen = true, bool desktop = true) = 0; virtual bool setWindowBorderless(Window *window, bool borderless = true) = 0; virtual bool setWindowIcon(Window *window, Texture *tex, GLenum target = GL_TEXTURE_2D, GLenum format = GL_RGBA, GLenum type = GL_UNSIGNED_BYTE) = 0; virtual bool setWindowIcon(Window *window, TextureData *texdata) = 0; virtual std::string getWindowTitle(Window *window) = 0; virtual Vector2i getWindowResolution(Window *window) = 0; virtual Vector2i getScreenResolution() = 0; virtual bool isWindowFullscreen(Window *window) = 0; virtual bool isWindowBorderless(Window *window) = 0; virtual int getControllerID(void *handle) = 0; virtual bool isSameController(void *handle1, void *handle2) = 0; virtual void *openController(int id) = 0; virtual void closeController(void *handle) = 0; virtual bool isAttachedController(void *handle) = 0; virtual void lockAndHideCursor() = 0; virtual void hideCursor() = 0; virtual void showCursor() = 0; virtual bool isCursorHidden() = 0; Event event; }; } // namespace Johnny #endif
PucklaMotzer09/3DEngine
include/RenderTexture.h
#include "Geometry.h" #include "Texture.h" #include <GL/glew.h> namespace Johnny { class FrameBuffer; class Camera2D; /*! \brief A Texture that is attached to a FrameBuffer for easy to use render to * Texture * */ class RenderTexture : public Texture { public: /*! \brief Creates a new RenderTexture * \param width The width of the new RenderTexture * \param height The height of the new RenderTexture * \param filtering The filter technique which will be used for sampling from * the texture \param target The target to which the new RenderTexture will be * bound \param format The format of the pixels of the new RenderTexture * \param type The type of the new RenderTexture with which the pixels are * stored */ RenderTexture(GLsizei width, GLsizei height, GLenum filtering = GL_LINEAR, GLenum target = GL_TEXTURE_2D, GLenum format = GL_RGBA, GLenum type = GL_UNSIGNED_BYTE); ~RenderTexture(); /*! \brief Binds the FrameBuffer and ajusts the viewport * */ void target(); /*! \brief Unbinds the FrameBuffer and reajusts the viewport * */ void untarget(); /*! \brief Renders the Texture of the RenderTexture * \param position The position where to render in pixels * \param scale The scale with which the Texture will be rendered * \param rotation The rotation with which the Texture will be rendered * \param cam The Camera2D in which view the Texture should be transformed * (if nullptr no view transformation will be apllied) \param srcRegion The * TextureRegion which defines what to take from the Texture (if nullptr * {0,0,width,height} will be used) \param bindShader Defines whether to bind * the Texture2DShader \param target The target to which the Texture should be * bound */ void render(const Vector2f &position, const Vector2f &scale = Vector2f(1.0f, 1.0f), GLfloat rotation = 0.0f, const Camera2D *cam = nullptr, const TextureRegion *srcRegion = nullptr, bool bindShader = true, GLenum target = GL_TEXTURE_2D); /*! \return Tthe FrameBuffer of the RenderTexture * */ FrameBuffer *getFrameBuffer() { return m_frameBuffer; } private: FrameBuffer *m_frameBuffer = nullptr; //!< The FrameBuffer of the RenderTexture }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/Shader.h
<reponame>PucklaMotzer09/3DEngine #pragma once #include "Geometry.h" #include "Matrix3.h" #include "Matrix4.h" #include "ShaderUpdater.h" #include "Vector2.h" #include "Vector3.h" #include "Vector4.h" #include <GL/glew.h> #include <map> #include <string> #include <vector> namespace Johnny { /*! \brief A enum which represents the types of the values of a UniformBuffer * */ enum UBOTypes { FLOAT, INT, VEC2, VEC3, VEC4, MAT2, MAT3, MAT4, ARRAY_FLOAT, ARRAY_INT, ARRAY_VEC2, ARRAY_VEC3, ARRAY_VEC4, ARRAY_MAT2, ARRAY_MAT3, ARRAY_MAT4 }; /*! \brief Gets the size of a UBOTypes in the uniform buffer object in bytes * \param type The type to get the size from * \param arraySize The size of the array variable * \return The size of the type in bytes */ inline GLsizei getSize(UBOTypes type, unsigned int arraySize) { switch (type) { case FLOAT: return sizeof(GLfloat); case INT: return sizeof(GLint); case VEC2: return 2 * sizeof(GLfloat); case VEC3: return 4 * sizeof(GLfloat); case VEC4: return 4 * sizeof(GLfloat); case MAT2: return 2 * 16; case MAT3: return 3 * 16; case MAT4: return 4 * 16; case ARRAY_MAT2: return arraySize * 2 * 16; case ARRAY_MAT3: return arraySize * 3 * 16; case ARRAY_MAT4: return arraySize * 4 * 16; default: return arraySize * 16; } } /*! \brief A class which represents a uniform buffer object * */ class UniformBuffer { public: UniformBuffer(); ~UniformBuffer(); /*! \brief Adds a definition of a variable to determine the size of the buffer * \param type The type of the variable */ void addVariable(UBOTypes type); /*! \brief Adds a definition of an array to determine the size of the buffer * \param type The type of the array (must begin with ARRAY_) * \param size The number of elements in the array */ void addArray(UBOTypes type, unsigned int size); /*! \brief Maps the UniformBuffer * */ void map(); /*! \brief Unmaps the UniformBuffer * */ void unmap(); /*! \brief Sets a variable of the UniformBuffer after it has been mapped * \param type The type of the variable * \param index The howmany variable of that type * \param data The contents of the variable */ void setVariable(UBOTypes type, unsigned int index, GLvoid *data); /*! \brief Creates the buffer (Should be called after the addVariable calls * and before map and setVariable) \param bindingPoint The buffer uniform * buffer binding point to bind the buffer to */ void createBuffer(GLuint bindingPoint); /*! \return The size of the buffer in bytes * */ GLsizei getBufferSize() const { return m_bufferSize; } private: /*! \brief Actually sets the variable * \param type The type of the variable * \param offset The offset in the buffer in bytes * \param data The content of the variable * \param arraySize The number of elements in the array if type is a type of * array */ void m_setVariable(UBOTypes type, GLsizei offset, GLvoid *data, unsigned int arraySize); GLuint m_buffer = 0; //!< The name of the uniform buffer std::vector<UBOTypes> m_types; //!< The array which stores all types of all variables std::map<unsigned int, unsigned int> m_arraySizes; //!< The map which stores all array sizes of all array //!< variables GLbyte *m_data = nullptr; //!< The pointer which is used for writeing to the buffer GLvoid *m_bufferMap = nullptr; //!< The pointer which is used for mapping GLsizei m_bufferSize = 0; //!< The size of the buffer in bytes }; /*! \brief A class which represents a shader program * */ class Shader { public: Shader(); ~Shader(); /*! \brief Adds a fragment shader to the Shader * \param contents The source code of the fragment shader */ void addFragmentShader(const std::string &contents); /*! \brief Adds a vertex shader to the Shader * \param contents The source code of the vertex shader */ void addVertexShader(const std::string &contents); /*! \brief Adds a geometry shader to the Shader * \param contents The source code of the geometry shader */ void addGeometryShader(const std::string &contents); /*! \brief Links the Shader (should be called after the add**Shader calls) * */ void link(); /*! \brief Binds the shader program * */ void bind(); /*! \brief Attaches a uniform block to a specific binding point * \param name The name of the uniform block * \param bindingPoint The binding point to attach to */ void attachUniformBuffer(const std::string &name, GLuint bindingPoint); /*! \brief Stores the uniform location of the uniform with the given name * \param name The name of the ubiform to store the location * \param endifNotThere Defines if a error message should be printed of the * uniform wasn't found \return true if the uniform was found and false * otherwhise */ bool addUniform(const std::string &name, bool endIfNOtThere = true); /*! \brief Sets the value of a uniform in the shader * \param name The name of the uniform * \param value The value of the uniform */ void setUniform(const std::string &name, GLint value); /*! \brief Sets the value of a uniform in the shader * \param name The name of the uniform * \param value The value of the uniform */ void setUniform(const std::string &name, GLfloat value); /*! \brief Sets the value of a uniform in the shader * \param name The name of the uniform * \param value The value of the uniform */ void setUniform(const std::string &name, const Vector2f &value); /*! \brief Sets the value of a uniform in the shader * \param name The name of the uniform * \param value The value of the uniform */ void setUniform(const std::string &name, const Vector2i &value); /*! \brief Sets the value of a uniform in the shader * \param name The name of the uniform * \param value The value of the uniform */ void setUniform(const std::string &name, const Vector3f &value); /*! \brief Sets the value of a uniform in the shader * \param name The name of the uniform * \param value The value of the uniform */ void setUniform(const std::string &name, const Vector4f &value); /*! \brief Sets the value of a uniform in the shader * \param name The name of the uniform * \param value The value of the uniform */ void setUniform(const std::string &name, const TextureRegion &value); /*! \brief Sets the value of a uniform in the shader * \param name The name of the uniform * \param value The value of the uniform */ void setUniform(const std::string &name, const Matrix4f &value); /*! \brief Sets the value of a uniform in the shader * \param name The name of the uniform * \param value The value of the uniform */ void setUniform(const std::string &name, const Matrix3f &value); /*! \brief Defines a vertex attribute * \param name The name of the vertex attribute * \param index The index of the vertex attribute */ void addAttribute(const std::string &name, GLint index); /*! \brief Defines if this Shader is a Shader used for rendering to a * ShadowMap3D DEPRECATED \param b The bool value */ void setShadowMap(bool b) { m_shadowMap = b; } /*! \return The name of the shader program * */ GLuint getProgram() { return m_program; } /*! \return If the SHader is used for rendering to a ShadowMap3D DEPRECATED * */ bool isShadowMap() const { return m_shadowMap; } /*! \brief Sets the ShaderUpdater of the Shader * \param T the type of ShaderUpater */ template <class T> void setShaderUpdater(); /*! \return The ShaderUpdater of the Shader * */ ShaderUpdater *getShaderUpdater() { return m_shaderUpdater; } private: /*! \brief Actually adds a shader source to the shader program * \param text The source code of a shader * \param type The type of shader */ void addProgram(const std::string &text, GLuint type); /*! \param name The name of the uniform * \return The location of the uniform or INT_MAX if the uniform wasn't found */ GLuint getUniformLocation(const std::string &name); /*! \return The index of a uniform block by name * \param name The name of The uniform block */ GLuint getUniformBlockIndex(const std::string &name); std::map<std::string, GLuint> m_uniforms; //!< The map where all uniform locations are stored GLuint m_program = 0; //!< The name of the shader program GLuint m_vert = 0; //!< The name of the vertex shader GLuint m_frag = 0; //!< The name of the fragment shader GLuint m_geo = 0; //!< The name of the geometry shader bool m_shadowMap = false; //!< Defines if the Shader is used for rendering to //!< ShadowMap3D DEPRECATED std::map<std::string, GLuint> m_uniformBlockIndices; //!< The map where every uniform block indices are //!< stored ShaderUpdater *m_shaderUpdater = nullptr; //!< The ShaderUpdater of the Shader }; template <class T> inline void Shader::setShaderUpdater() { m_shaderUpdater = new T(this); } } // namespace Johnny
PucklaMotzer09/3DEngine
include/DebugMovement2D.h
#pragma once #include "Actor.h" namespace Johnny { /*! \brief A class which adds a small 2D DebugCameraMovement to the application * like camera scrolling, zooming and rotating * */ class DebugMovement2D : public Actor { public: /*! \brief Creates a new DebugMovement2D * \param moveSpeed The speed with which the camera scrolls [pixel/s] * \param zoomSpeed The speed with which the camera zooms [n/s] * \param ratoteSpeed The speed with which the camera rotates [degree/s] */ DebugMovement2D(float moveSpeed = 100.0f, float zoomSpeed = 0.4f, float rotateSpeed = 10.0f); ~DebugMovement2D(); /*! \brief The update method * * * It is overriding the method from Actor */ bool update() override; private: float m_moveSpeed = 100.0f; //!< The speed with which the camera scrolls [pixel/s] float m_zoomSpeed = 0.4f; //!< The speed with which the camera zooms [n/s] float m_rotateSpeed = 10.0f; //!< The speed with which the camera rotates [degree/s] }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/LogManager.h
<reponame>PucklaMotzer09/3DEngine #ifndef LOGMANAGER_H #define LOGMANAGER_H #include <ctime> #include <string> extern void shutdownProgram(); namespace Johnny { /*! \brief A class which handles logging * */ class LogManager { public: LogManager(); virtual ~LogManager(); /*! \brief Sets the file where the logs should go to * \param file The file to set */ static void setFile(const char *file) { m_file = file; } /*! \brief Logs some text to the console and a file * \param text The text which will be logged * \param withTime Defines wether the date and time should be included in the * log \param newLine Defines wether there should be a new line placed after * the log */ static void log(const std::string &text, bool withTime = true, bool newLine = true); /*! \brief Logs a number to the console and a file * \param i The number which will be logged * \param withTime Defines wether the date and time should be included in the * log \param newLine Defines wether there should be a new line placed after * the log */ static void log(int i, bool withTime = true, bool newLine = true); /*! \brief Logs the text as an error * \param text The text which will be logged * \param withTime Defines wether the date and time should be included in the * log \param newLine Defines wether there should be a new line placed after * the log \param messageBox Defines wether there should be a MessageBox * opened with the error contents */ static void error(const std::string &text, bool withTime = true, bool newLine = true, bool messageBox = true); private: /*! \return The current time in format HH:MM:SS * */ static const std::string getTime(); /*! \return The current Date in format DD:MM:YYYY * */ static const std::string getDay(); /*! \brief Creates a MessageBox which will be used for error logging * \param msg The message which will be written * \return The id of the button pressed (0=Continue, 1=Shutdown) */ static int createMessageBox(const std::string &msg); static const char *m_file; //!< The relative or absolute path of the file //!< where the logs go to static time_t m_timer; //!< Is used to determine the time and the date static struct tm *m_tm; //!< Is used to determine the time and the date }; } // namespace Johnny #endif // LOGMANAGER_H
PucklaMotzer09/3DEngine
include/Transform2D.h
#pragma once #include "Matrix3.h" #include "Vector2.h" #include <GL/glew.h> #include <vector> namespace Johnny { class Camera2D; /*! \brief A class for calculating a transformation matrix * */ class Transform2D { public: Transform2D(); /*! \brief Creates a new Transform2D * \param translation The translation of the new Transform2D * \param rotation The rotation of the new Transform2D * \param scale The scale of the new Transform2D */ Transform2D(const Vector2f &translation, const GLfloat &rotation, const Vector2f &scale); ~Transform2D(); /*! \return The translation of the Transform2D * */ const Vector2f &getTranslation() const { return m_translation; } /*! \return The rotation of the Transform2D * */ const GLfloat &getRotation() const { return m_rotation; } /*! \return The scale of the Transform2D * */ const Vector2f &getScale() const { return m_scale; } /*! \brief Sets the translation of the Transform2D * \param translation The translation to set */ void setTranslation(const Vector2f &translation) { m_translation = translation; } /*! \brief Sets the rotation of the Transform2D * \param rotation The rotation to set */ void setRotation(const GLfloat &rotation) { m_rotation = rotation; } /*! \brief Sets the scale of the Transform2D * \param scale The scale to set */ void setScale(const Vector2f &scale) { m_scale = scale; } /*! \brief Sets the translation of the Transform2D * \param transX The x translation to set * \param transY The y translation to set */ void setTranslation(const GLfloat &transX, const GLfloat &transY) { m_translation = Vector2f(transX, transY); } /*! \brief Sets the scale of the Transform2D * \param scaleX The x scale to set * \param scaleY The y scale to set */ void setScale(const GLfloat &scaleX, const GLfloat &scaleY) { m_scale = Vector2f(scaleX, scaleY); } /*! \return The modelworld transformation matrix * */ Matrix3f getTransformation() const; /*! \return The modelworldview matrix * \param cam The Camera2D to use for the view */ Matrix3f getProjectedTransformation(const Camera2D *cam) const; private: Vector2f m_translation; //!< The translation of the Transform2D GLfloat m_rotation; //!< The rotation of the Transformr2D Vector2f m_scale; //!< The scale of the Tranform2D }; /*! \brief A class which represents a object with a Transform2D * */ class TransformableObject2D { public: /*! \return The center of the coordinate system relative the center of the * screen (will be multiplied onto the viewport size) * */ static const Vector2f &getCenter(); /*! \return Wether the y-Axis is flipped in this coordinate system * */ static bool getYAxisFlipped(); /*! \return Wether the x-Yxis is dlipped int this coordinate system * */ static bool getXAxisFlipped(); /*! \return The size of the viewport you are currently rendering to * */ static const Vector2f &getViewportSize(); /*! \brief Sets the center of the coordinate system * \param center The center to set relative to the center of the screen (will * be multiplied to onto the viewport size, internal use only) */ static void setCenter(const Vector2f &center); /*! \brief Sets wether the y-Axis is flipped in this coordinate system * \param b The coresponding bool value */ static void setYAxisFlipped(bool b); /*! \brief Sets wether the x-Axis is flipped in this scoordinate system * \param b The coresponding bool value */ static void setXAxisFlipped(bool b); /*! \brief Sets the size of the viewport * \param view The viewport to set */ static void setViewportSize(const Vector2f &view); /*! \brief Converts a vector into the coordinate system * \param v The vector to convert * \param viewport The viewport which will be used for the calculation (if * x=-1.0f && y-1.0f the viewport of the class will be used) */ static Vector2f toCoords(const Vector2f &v, const Vector2f &viewport = Vector2f(-1.0f, -1.0f)); /*! \brief Converts a vector into the coordinate system * \param v The vector to convert * \param x Wether the x-Axis should be flipped * \param y Wether the y-Axis should be flipped */ static Vector2f toCoords(const Vector2f &v, bool x, bool y); /*! \brief Converts a vector from the coordinate system * \param v The vector to convert * \param viewport The viewport which will be used for the calculation (if * x=-1.0f && y-1.0f the viewport of the class will be used) */ static Vector2f fromCoords(const Vector2f &, const Vector2f &viewport = Vector2f(-1.0f, -1.0f)); /*! \brief Converts a vector from the coordinate system * \param v The vector to convert * \param x Wether the x-Axis should be flipped * \param y Wether the y-Axis should be flipped */ static Vector2f fromCoords(const Vector2f &, bool, bool); static bool centerSet; //!< Wether the center has been defined TransformableObject2D(); virtual ~TransformableObject2D(); /*! \brief Sets the position of the object * \param v The position in the converted coordinate system */ virtual void setPosition(const Vector2f &v); /*! \brief Sets the position of the object * \param x The x position in the converted coordinate system * \param y The y position in the converted coordinate system */ virtual void setPosition(const GLfloat &x, const GLfloat &y); /*! \brief Sets the rotation of the object * \param rot The rotation to set in degress */ virtual void setRotation(const GLfloat &rot); /*! \brief Sets the scale of the object * \param scale The scale to set */ virtual void setScale(const Vector2f &scale); /*! \brief Sets the scale of the object * \param x The x scale of the object * \param y The y scale of the object */ virtual void setScale(const GLfloat &x, const GLfloat &y); /*! \brief Adds a vector to the position * \param v The vector to add */ virtual void addPosition(const Vector2f &v); /*! \brief Adds a vector to the position * \param x The x value of the vector to add * \param y The y value of the vector to add */ virtual void addPosition(const GLfloat &x, const GLfloat &y); /*! \brief Adds a value to the rotation * \param x The rotation to add */ virtual void addRotation(const GLfloat &x) { setRotation(m_transform.getRotation() + x); } /*! \brief Adds a vector to the scale * \param v The vector to add to the scale */ virtual void addScale(const Vector2f &v); /*! \brief Adds a vector to the scale * \param x The x value of the vector to add * \param y The y value of the vector to add */ virtual void addScale(const GLfloat &x, const GLfloat &y); /*! \return The position of the object * */ virtual Vector2f getPosition() const; /*! \return The rotation of the object on degrees * */ virtual const GLfloat &getRotation() const { return m_transform.getRotation(); } /*! \return The scale of the object * */ virtual const Vector2f &getScale() const { return m_transform.getScale(); } /*! \return The Transform2D of the object * */ Transform2D &getTransform() { return m_transform; } protected: /*! \brief Sets the size of the object * \param v The size to set */ virtual void setSize(const Vector2f &v); /*! \brief Sets the size of the object * \param x The x size to set * \param y The y size to set */ virtual void setSize(GLfloat x, GLfloat y) { setSize(Vector2f(x, y)); } /*! \return The size of the object * */ virtual const Vector2f &getSize() const { return m_size; } Transform2D m_transform; //!< The Transform2D of the object Vector2f m_size; //!< The size of the object bool m_affectedByCenter = true; //!< Defines wether the object is centered not //!< in the center of the screen private: static Vector2f center; //!< The center of the coordinate system (relative to //!< the center of the screen) static Vector2f viewportSize; //!< The size of the viewport static bool yAxisFlipped; //!< Defines wether the y-Axis is flipped in the //!< coordinate system static bool xAxisFlipped; //!< Defines wether the x-Axis is flipped in the //!< coordinate system static std::vector<TransformableObject2D *> objects; //!< An array with all TransformableObject2Ds }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/JoystickListenerEnums.h
#ifndef JOYSTICKLISTENERENUMS_H #define JOYSTICKLISTENERENUMS_H namespace Johnny { /*! \brief A enum which consists of all Buttons of a controller * */ enum Buttons { UP = 11, DOWN = 12, LEFT = 13, RIGHT = 14, START = 6, SELECT = 4, L3 = 7, R3 = 8, L1 = 9, R1 = 10, CROSS = 0, CIRCLE = 1, SQUARE = 2, TRIANGLE = 3, BACK = SELECT, LS = L3, RS = R3, LB = L1, RB = R1, A = CROSS, B = CIRCLE, X = SQUARE, Y = TRIANGLE }; /*!\brief A enum which consists of the sticks and triggers of a controller * */ enum Axis { LEFT_STICK_X = 0, LEFT_STICK_Y = 1, RIGHT_STICK_X = 2, RIGHT_STICK_Y = 3, L2 = 4, R2 = 5, LT = L2, RT = R2 }; } // namespace Johnny #endif
PucklaMotzer09/3DEngine
include/Vector4.h
<gh_stars>0 #pragma once #include <GL/glew.h> #include <cmath> #include <iostream> namespace Johnny { template <class T> class Vector4; template <class T> const Vector4<T> operator+(const Vector4<T> &, const Vector4<T> &); template <class T> const Vector4<T> operator-(const Vector4<T> &, const Vector4<T> &); template <class T> const Vector4<T> operator*(const Vector4<T> &, const Vector4<T> &); template <class T> const Vector4<T> operator/(const Vector4<T> &, const Vector4<T> &); template <class T> std::ostream &operator<<(std::ostream &, const Vector4<T> &); /*! \brief A class which represents a value with four dimensions * \param T The type of the elements of the Vector4 */ template <class T> class Vector4 { public: Vector4() = default; /*! \brief Creates a new Vector4 * \param x The x value of the new Vector4 * \param y The y value of the new Vector4 * \param z The z value of the new Vector4 * \param w The w value of the new Vector4 */ Vector4(const T &x, const T &y, const T &z, const T &w); /*! \brief Copies a Vector4 * \param v The Vector4 to copy */ Vector4(const Vector4 &v); union { T x = 0; //!< The x value of the Vector4 if it is used as a position T r; //!< The x value of the Vector4 if it is used as a color T width; //!< The x value of the Vector4 if it is used as dimensions }; union { T y = 0; //!< The y value of the Vector4 if it is used as a position T g; //!< The y value of the Vector4 if it is used as a color T height; //!< The y value of the Vector4 if it is used as dimensions }; union { T z = 0; //!< The z value of the Vector4 if it is used as a position T b; //!< The z value of the Vector4 if it is used as a color T depth; //!< The z value of the Vector4 if it is used as dimensions }; union { T w = 0; //!< The w value of the Vector4 if it i used as a position T a; //!< The w value of the Vector4 if it i used as a color T time; //!< The w value of the Vector4 if it i used as dimensions }; /*! \param squared Wether the result should be the squared length or not * \return The length of the Vector4 */ T length(bool squared = false) const; /*! \brief Normalises a Vector4 * \return A reference to this object */ Vector4 &normalise(); /*! \brief Adds a Vector4 to this object * \param v The Vector4 to add * \return A reference to this object */ Vector4 &add(const Vector4 &v); /*! \brief Subtracts a Vector4 from this object * \param v The Vector4 to subtract * \return A refreence to this object */ Vector4 &subtract(const Vector4 &v); /*! \brief Multiplies each element of the Vector4 which each other * \param v The Vector4 for the multiplication * \return A reference to this object */ Vector4 &multiply(const Vector4 &v); /*! \brief Multiplies this vector with a scalar * \param s The scalar to multiply * \return A reference to the object */ Vector4 &multiply(const T &s); /*! \brief Divides each element of the Vector4 by the corresponding element of * the other Vector4 \param v The other Vector4 for the division \return A * reference to the object */ Vector4 &divide(const Vector4 &v); /*! \brief Divides each element by a scalar * \param s The scalar for the division * \return A reference to the object */ Vector4 &divide(const T &s); /*! \brief Calculates the distance between this Vector4 and another Vector4 * \param v The other Vector4 for the calculation * \param squared Wether the result should be the squared distance * \return The distance between this Vector4 and the other Vector4 */ T distance(const Vector4 &v, bool squared = false) const; Vector4 &operator+=(const Vector4 &); Vector4 &operator-=(const Vector4 &); Vector4 &operator*=(const Vector4 &); Vector4 &operator/=(const Vector4 &); T &operator[](unsigned int); friend const Vector4<T> operator+<>(const Vector4<T> &, const Vector4<T> &); friend const Vector4<T> operator-<>(const Vector4<T> &, const Vector4<T> &); friend const Vector4<T> operator*<>(const Vector4<T> &, const Vector4<T> &); friend const Vector4<T> operator/<>(const Vector4<T> &, const Vector4<T> &); friend std::ostream &operator<<<>(std::ostream &, const Vector4<T> &); }; template <class T> Vector4<T>::Vector4(const T &x, const T &y, const T &z, const T &w) { this->x = x; this->y = y; this->z = z; this->w = w; } template <class T> Vector4<T>::Vector4(const Vector4<T> &v) { x = v.x; y = v.y; z = v.z; w = v.w; } template <class T> T Vector4<T>::length(bool squared) const { if (squared) return x * x + y * y + z * z + w * w; else return sqrt(x * x + y * y + z * z + w * w); } template <class T> Vector4<T> &Vector4<T>::normalise() { T Length = length(); x /= Length; y /= Length; z /= Length; w /= Length; return *this; } template <class T> Vector4<T> &Vector4<T>::add(const Vector4<T> &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; } template <class T> Vector4<T> &Vector4<T>::subtract(const Vector4<T> &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; } template <class T> Vector4<T> &Vector4<T>::multiply(const Vector4<T> &v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; } template <class T> Vector4<T> &Vector4<T>::multiply(const T &s) { x *= s; y *= s; z *= s; w *= s; return *this; } template <class T> Vector4<T> &Vector4<T>::divide(const Vector4 &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; } template <class T> Vector4<T> &Vector4<T>::divide(const T &s) { x /= s; y /= s; z /= s; w /= s; return *this; } template <class T> T Vector4<T>::distance(const Vector4<T> &v, bool squared) const { Vector4 v1(v); v1.subtract(*this); return v1.length(squared); } template <class T> Vector4<T> &Vector4<T>::operator+=(const Vector4<T> &v2) { return add(v2); } template <class T> Vector4<T> &Vector4<T>::operator-=(const Vector4<T> &v2) { return subtract(v2); } template <class T> Vector4<T> &Vector4<T>::operator*=(const Vector4<T> &v2) { return multiply(v2); } template <class T> Vector4<T> &Vector4<T>::operator/=(const Vector4<T> &v2) { return divide(v2); } template <class T> T &Vector4<T>::operator[](unsigned int i) { switch (i) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; default: throw "operator[] unsigned int must be 0,1,2,3"; } } template <class T> const Vector4<T> operator+(const Vector4<T> &v1, const Vector4<T> &v2) { return Vector4<T>(v1).add(v2); } template <class T> const Vector4<T> operator-(const Vector4<T> &v1, const Vector4<T> &v2) { return Vector4<T>(v1).subtract(v2); } template <class T> const Vector4<T> operator*(const Vector4<T> &v1, const Vector4<T> &v2) { return Vector4<T>(v1).multiply(v2); } template <class T> const Vector4<T> operator/(const Vector4<T> &v1, const Vector4<T> &v2) { return Vector4<T>(v1).divide(v2); } template <class T> std::ostream &operator<<(std::ostream &os, const Vector4<T> &v) { os << "(" << v.x << ";" << v.y << ";" << v.z << ";" << v.w << ")"; return os; } typedef Vector4<GLfloat> Vector4f; typedef Vector4<GLdouble> Vector4d; typedef Vector4<GLint> Vector4i; } // namespace Johnny
PucklaMotzer09/3DEngine
include/FrameBuffer.h
<gh_stars>0 #pragma once #include <GL/glew.h> namespace Johnny { class Texture; class RenderBuffer; /*! \brief a object-oriented implementation of a frame buffer object * to make it easier to use * */ class FrameBuffer { public: FrameBuffer(); ~FrameBuffer(); /*! \brief Attaches a texture to the frame buffer object * \param tex The texture to add * \param attachment The attachment to add the texture to * \param target The target to which the frame buffer object should be bound * \param textureTarget The target to which the texture should be bound */ void addTexture(Texture *tex, GLuint attachment = GL_COLOR_ATTACHMENT0, GLenum target = GL_FRAMEBUFFER, GLenum textureTarget = GL_TEXTURE_2D); /*! \brief Attaches a render buffer the frame buffer object * \param rb The render buffer to attach * \param attachment The attachment to add the render buffer to * \param target The target to which the frame buffer object should be bound */ void addRenderBuffer(RenderBuffer *rb, GLuint attachment = GL_DEPTH_STENCIL_ATTACHMENT, GLenum target = GL_FRAMEBUFFER); /*! \brief Checks if the frame buffer object is completed * \param target The target to which the frame buffer object should be bound * \return Wether the frame buffer object is completed */ bool checkStatus(GLenum target = GL_FRAMEBUFFER); /*! \brief Binds the frame buffer object * \param target The target to which the frame buffer object should be bound */ void bind(GLenum target = GL_FRAMEBUFFER); /*! \brief Unbinds the frame buffer object * \param target The target which should be unbound */ void unbind(GLenum target = GL_FRAMEBUFFER); /*! \brief Blits this frame buffer on another one * \param f The frame buffer on which this frame buffer should be blitted * \param sx0 The x coordinate of the rectangle from which to take from this * frame buffer \param sy0 The y coordinate of the rectangle from which to * take from this frame buffer \param sx1 The width of the rectangle from * which to take from this frame buffer \param sy1 The height of the rectangle * from which to take from this frame buffer \param dx0 The x coordinate of * the rectangle on which to blit on the other frame buffer \param dy0 The y * coordinate of the rectangle on which to blit on the other frame buffer * \param dx1 The width of the rectangle on which to blit on the other frame * bufferr \param dy1 The height of the rectangle on which to blit on the * other frame buffer \param mask Which mask to blit \param filter Defines how * the pixels should be filtered */ void blit(FrameBuffer *f, GLint sx0, GLint sy0, GLint sx1, GLint sy1, GLint dx0, GLint dy0, GLint dx1, GLint dy1, GLbitfield mask = GL_COLOR_BUFFER_BIT, GLenum filter = GL_LINEAR); /*! \return The name of the frame buffer object * */ GLuint getBuffer() { return m_fbo; } private: GLuint m_fbo = 0; //!< The name of the frame buffer object }; } // namespace Johnny
PucklaMotzer09/3DEngine
include/JoystickManager.h
#ifndef JOYSTCKMANAGER_H #define JOYSTCKMANAGER_H #include "Events.h" #include <vector> namespace Johnny { class JoystickListener; /*! \brief The class which manages all controller specific things * */ class JoystickManager { public: JoystickManager(); virtual ~JoystickManager(); /*! \brief Polls the controller events * \param e The event from which to poll */ void pollEvents(const Event &e); /*! \brief Updates the JoystickManager * */ void update(); /*! \brief Sets the JoystickListener * \param jl The JoystickListener to set */ void setListener(JoystickListener *jl); /*! \brief Adds a controller to the vector * \param gc The controller to add */ void addController(void *gc); /*! \brief Removes a controller from the vector * \param gc The controller to remove */ void removeController(void *gc); /*! \brief Removes a controller with an index from the vector * \param index The index of te controller */ void removeController(int index); /*! \return A vector with all SDL_GameController handles of the connected * controllers * */ std::vector<void *> &getControllers() { return m_controllers; } /*! \return The currently attached JoystickListener * */ JoystickListener *getListener() { return m_listener; } private: JoystickListener *m_listener = nullptr; //!< The JoystickListener of the object std::vector<void *> m_controllers; //!< The vector which holds the controllers }; } // namespace Johnny #endif // JOYSTCKMANAGER_H
alem-147/xv6-public
sysproc.c
<filename>sysproc.c<gh_stars>0 #include "types.h" #include "x86.h" #include "defs.h" #include "date.h" #include "param.h" #include "memlayout.h" #include "mmu.h" #include "proc.h" int sys_fork(void) { return fork(); } int sys_exit(void) { int exit_status; argint(0, &exit_status); //cprintf("exiting with status %d\n",exit_status); exit(exit_status); return 0; // not reached } int sys_wait(void) { char *stat_loc; //arg ptr requires char ptr int child_pid; argptr(0,&stat_loc,32); // grab arg ptr passed into syscall child_pid = wait((int *)stat_loc); //cprintf("I waited for my child with pid: %d",child_pid); return child_pid; } int sys_kill(void) { int pid; if(argint(0, &pid) < 0) return -1; return kill(pid); } int sys_getpid(void) { return myproc()->pid; } int sys_sbrk(void) { int addr; int n; if(argint(0, &n) < 0) return -1; addr = myproc()->sz; if(growproc(n) < 0) return -1; return addr; } int sys_sleep(void) { int n; uint ticks0; if(argint(0, &n) < 0) return -1; acquire(&tickslock); ticks0 = ticks; while(ticks - ticks0 < n){ if(myproc()->killed){ release(&tickslock); return -1; } sleep(&ticks, &tickslock); } release(&tickslock); return 0; } // return how many clock tick interrupts have occurred // since start. int sys_uptime(void) { uint xticks; acquire(&tickslock); xticks = ticks; release(&tickslock); return xticks; } int sys_waitpid(void) { int pid, options; char* status; argint(0,&pid); argptr(1,&status,32); argint(2,&options); return waitpid(pid,(int*)status,options); }
alem-147/xv6-public
mytests.c
#include "types.h" #include "stat.h" #include "user.h" #define NULL 0 /* exit must return an exit status on all user programs lets do some forking to confirm the proccess are exiting with the proper exit statuses */ void exittest1(int status) { int pid,n; int fork_count = 3; printf(1,"I am the parent proccess, process 0\n"); if (!(pid = fork())) { // parent goes past, child enters int process_count = 1; printf(1,"I am the child proccess, process 1\n"); for( n=0;n<fork_count;n++) { process_count++; int pid = fork(); if(pid) { wait(&status); } else { printf(1,"I am the Gchild proccess, process %d\n",process_count); exit(process_count); } } wait(&status); exit(1); } wait(&status); exit(0); } /* wait must be able to pass the exit status of its child to a pointer! lets see if we can do that */ void waittest(void) { int stat; if (fork() == 0) { // this should make stat = 82 exit(82); } else { wait(&stat); } printf(1,"my childs exit status was %d. I am a good waiter\n",stat); } /* must handle options of WNOHANG and 0 for options must check status passed must check that specific pid returned how to test if not our child */ void waitpidtest(void) { int i,stat; int fork_ret; int cpid; // fork 6 children for(i=0; i<6;i = i +1) { fork_ret = fork(); if(fork_ret == 0) { // for some reason ref pid[_] in any way breaks the loop printf(1, "hi im child number: %d\n",i); int exit_stat = 100 + i; exit(exit_stat); //exit right away } cpid = waitpid(fork_ret,&stat,0); printf(1,"child with pid: %d, exited with status: %d\n",cpid, stat); } } void waitpidtest1(void) { int i,stat; int fork_ret; int cpid; // fork 6 children for(i=0; i<6;i = i +1) { fork_ret = fork(); if(fork_ret == 0) { // for some reason ref pid[_] in any way breaks the loop printf(1, "hi im child number: %d\n",i); int exit_stat = 100 + i; exit(exit_stat); //exit right away } } cpid = waitpid(6,&stat,0);//note the pids will range for 4 to 10 printf(1,"child with pid: %d, exited with status: %d\n",cpid, stat); cpid = waitpid(8,&stat,0);//note the pids will range for 4 to 10 printf(1,"child with pid: %d, exited with status: %d\n",cpid, stat); //clean up the rest of the processes int has_children = 1; while(has_children != -1) { has_children = wait(NULL); } } int main() { //exittest1(NULL); // waittest(); //waitpidtest(); waitpidtest1(); exit(0); }
Lupus/libevfibers
include/evfibers/fiber.h
<gh_stars>100-1000 /******************************************************************** Copyright 2013 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ********************************************************************/ /** \mainpage About libevfibers * * \section intro_sec Introduction * * libevfibers is a small C fiber library that uses libev based event loop and * libcoro based coroutine context switching. As libcoro alone is barely enough * to do something useful, this project aims at building a complete fiber API * around it while leveraging libev's high performance and flexibility. * * You may ask why yet another fiber library, there are GNU Pth, State threads, * etc. When I was looking at their API, I found it being too restrictive: you * cannot use other event loop. For GNU Pth it's solely select based * implementation, as for state threads --- they provide several * implementations including poll, epoll, select though event loop is hidden * underneath the public API and is not usable directly. I found another * approach more sensible, namely: just put fiber layer on top of well-known * and robust event loop implementation. Marc Lehmann already provided all the * necessary to do the job: event loop library libev with coroutine library * libcoro. * * So what's so cool about fibers? Fibers are user-space threads. User-space * means that context switching from one fiber to an other fiber takes no * effort from the kernel. There are different ways to achieve this, but it's * not relevant here since libcoro already does all the dirty job. At top level * you have a set of functions that execute on private stacks that do not * intersect. Whenever such function is going to do some blocking operation, * i.e. socket read, it calls fiber library wrapper, that asks event loop to * transfer execution to this function whenever some data arrives, then it * yields execution to other fiber. From the function's point of view it runs * in exclusive mode and blocks on all operations, but really other such * functions execute while this one is waiting. Typically most of them are * waiting for something and event loop dispatches the events. * * This approach helps a lot. Imagine that you have some function that requires * 3 events. In classic asynchronous model you will have to arrange your * function in 3 callbacks and register them in the event loop. On the other * hand having one function waiting for 3 events in ``blocking'' fashion is * both more readable and maintainable. * * Then why use event loop when you have fancy callback-less fiber wrappers? * Sometimes you just need a function that will set a flag in some object when * a timer times out. Creating a fiber solely for this simple task is a bit * awkward. * * libevfibers allows you to use fiber style wrappers for blocking operations * as well as fall back to usual event loop style programming when you need it. * * \section install_sec Installation * * \subsection requirements_ssec Requirements * * To build this documentation properly you need to have * [doxygen](http://www.stack.nl/~dimitri/doxygen) version >= 1.8 since it used * markdown. * * To build libevfibers you need the following packages: * - [cmake](http://www.cmake.org) * * CMake is a build system used to assemble this project. * - [libev](http://software.schmorp.de/pkg/libev.html) development files * * Well-known and robust event loop. * - [valgrind](http://valgrind.org) development files * * libevfibers makes use of client requests in valgrind to register stacks. * - [Check](http://check.sourceforge.net) unit testing framework * * Strictly it's not a requirement, but you better run unit tests before * installation. * * You don't need libcoro installed as it's part of source tree and will build * along with libevfibers. * * As far as runtime dependencies concerned, the following is required: * - [libev](http://software.schmorp.de/pkg/libev.html) runtime files * * For debian-based distributions users (i.e. Ubuntu) you can use the following * command to install all the dependencies: * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.sh} * sudo apt-get install cmake libev-dev valgrind check * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * \subsection building_ssec Building * * Once you have all required packages installed you may proceed with building. * Roughly it's done as follows: * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.sh} * git clone https://code.google.com/p/libevfibers * cd libevfibers/ * mkdir build * cd build/ * cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo .. * make * sudo make install * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * \subsection building_deb_ssec Building debian package * If you are running debian-based distribution, it will be more useful to * build a debian package and install it. * * The following actions will bring you there: * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.sh} * git clone https://code.google.com/p/libevfibers * cd libevfibers/ * dpkg-buildpackage * sudo dpkg -i ../libevfibers?_*_*.deb ../libevfibers-dev_*_*.deb * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * * \section contributors_sec Contributors * libevfibers was written and designed by <NAME>. * * <NAME> contributed some patches, a lot of criticism and ideas. */ #ifndef _FBR_FIBER_H_ #define _FBR_FIBER_H_ /** * @file evfibers/fiber.h * This file contains all client-visible API functions for working with fibers. */ #ifdef __cplusplus extern "C" { #endif #include <unistd.h> #include <stdarg.h> #include <stddef.h> #include <string.h> #include <stdint.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/queue.h> #include <assert.h> #include <ev.h> #include <evfibers/config.h> /** * Maximum allowed level of fbr_transfer nesting within fibers. */ #define FBR_CALL_STACK_SIZE 16 /** * Default stack size for a fiber of 64 KB. */ #define FBR_STACK_SIZE (64 * 1024) /* 64 KB */ /** * @def fbr_assert * Fiber version of classic assert. */ #ifdef NDEBUG #define fbr_assert(context, expr) ((void)(0)) #else #define fbr_assert(context, expr) \ do { \ __typeof__(expr) ex = (expr); \ if (ex) \ (void)(0); \ else { \ fbr_dump_stack(context, fbr_log_e); \ __assert_fail(__STRING(expr), __FILE__, __LINE__, __ASSERT_FUNCTION); \ } \ } while (0) #endif /** * Just for convenience we have container_of macro here. * * Nothing specific. You can find the same one in the linux kernel tree. */ #define fbr_container_of(ptr, type, member) ({ \ const typeof( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member) ); \ }) struct fbr_context_private; struct fbr_logger; struct fbr_id_s { uint64_t g; void *p; } __attribute__((packed)); /** * Fiber ID type. * * For you it's just an opaque type. */ typedef struct fbr_id_s fbr_id_t; extern const fbr_id_t FBR_ID_NULL; static inline int fbr_id_eq(fbr_id_t a, fbr_id_t b) { return a.p == b.p && a.g == b.g; } static inline int fbr_id_isnull(fbr_id_t a) { return fbr_id_eq(a, FBR_ID_NULL); } /** * Error codes used within the library. * * These constants are returned via f_errno member of fbr_context struct. * @see fbr_context * @see fbr_strerror */ enum fbr_error_code { FBR_SUCCESS = 0, FBR_EINVAL, FBR_ENOFIBER, FBR_ESYSTEM, FBR_EBUFFERMMAP, FBR_ENOKEY, FBR_EPROTOBUF, FBR_EBUFFERNOSPACE, FBR_EEIO, }; /** * Library context structure, should be initialized before any other library * calls will be performed. * @see fbr_init * @see fbr_destroy * @see fbr_strerror */ struct fbr_context { struct fbr_context_private *__p; /*!< pointer to internal context structure */ enum fbr_error_code f_errno; /*!< context wide error code */ struct fbr_logger *logger; /*!< current logger */ }; /** * Utility macro for context parameter used in function prototypes. */ #define FBR_P struct fbr_context *fctx /** * Same as FBR_P but with unused attribute. */ #define FBR_PU __attribute__((unused)) FBR_P /** * Same as FBR_P, but with comma afterwards for use in functions that accept * more that one parameter (which itself is the context pointer). */ #define FBR_P_ FBR_P, /** * Same as FBR_P_ but unused attribute. */ #define FBR_PU_ __attribute__((unused)) FBR_P_ /** * Utility macro for context parameter passing when calling fbr_* functions. */ #define FBR_A fctx /** * Same as FBR_A, but with comma afterwards for invocations of functions that * require more that one parameter (which itself is the context pointer). */ #define FBR_A_ FBR_A, /** * Fiber's ``main'' function type. * Fiber main function takes only one parameter --- the context. If you need to * pass more context information, you shall embed fbr_context into any * structure of your choice and calculate the base pointer using container_of * macro. * @see FBR_P * @see fbr_context */ typedef void (*fbr_fiber_func_t)(FBR_P_ void *_arg); /** * (DEPRECATED) Destructor function type for the memory allocated in a fiber. * @param [in] ptr memory pointer for memory to be destroyed * @param [in] context user data pointer passed via fbr_alloc_set_destructor * * One can attach a destructor to a piece of memory allocated in a fiber. It * will be called whenever memory is freed with original pointer allocated * along with a user context pointer passed to it. * @see fbr_alloc * @see fbr_free * @see fbr_alloc_set_destructor */ typedef void (*fbr_alloc_destructor_func_t)(FBR_P_ void *ptr, void *context); /** * Logging levels. * @see fbr_logger * @see fbr_context */ enum fbr_log_level { FBR_LOG_ERROR = 0, FBR_LOG_WARNING, FBR_LOG_NOTICE, FBR_LOG_INFO, FBR_LOG_DEBUG }; struct fbr_logger; /** * Logger function type. * @param [in] logger currently configured logger * @param [in] level log level of message * @param [in] format printf-compatible format string * @param [in] ap variadic argument list * This function should log the message if log level suits the one configured * in a non-blocking manner (i.e. it should not synchronously write it to * disk). * @see fbr_logger * @see fbr_log_func_t */ typedef void (*fbr_log_func_t)(FBR_P_ struct fbr_logger *logger, enum fbr_log_level level, const char *format, va_list ap); /** * Logger utility function type. * @param [in] format printf-compatible format string * * This function wraps logger function invocation. * @see fbr_logger * @see fbr_log_func_t */ typedef void (*fbr_logutil_func_t)(FBR_P_ const char *format, ...); /** * Logger structure. * @see fbr_logger * @see fbr_context */ struct fbr_logger { fbr_log_func_t logv; /*!< Function pointer that represents the logger */ enum fbr_log_level level; /*!< Current log level */ void *data; /*!< User data pointer */ }; /** * Convenient function to test if certain log level will actually be logged. * * Useful when you need to perform some processing before logging. Wrapping * your processing in ``if'' statement based on this macros' result can perform * the processing only if its result will get logged. */ static inline int fbr_need_log(FBR_P_ enum fbr_log_level level) { return level <= fctx->logger->level; } /** * Convenient function to set current log level. */ static inline void fbr_set_log_level(FBR_P_ enum fbr_log_level desired_level) { fctx->logger->level = desired_level; } /** * Type of events supported by the library. * @see fbr_ev_wait */ enum fbr_ev_type { FBR_EV_WATCHER = 1, /*!< libev watcher event */ FBR_EV_MUTEX, /*!< fbr_mutex event */ FBR_EV_COND_VAR, /*!< fbr_cond_var event */ FBR_EV_EIO, /*!< libeio event */ }; struct fbr_ev_base; /** * Destructor function type. * @param [in] arg user-defined data argument * * This function gets called when containing fiber dies or destructor is * removed with call flag set to 1. * @see fbr_destructor * @see fbr_log_func_t */ typedef void (*fbr_destructor_func_t)(FBR_P_ void *arg); /** * Destructor structure. * * This structure holds information required for destruction. As it's defined * in public interface, it may be used as stack-allocatable destructor (it's * used internally the same way). * * Stack-allocated destructor might be useful if one has some resource (e.g. * file descriptor), which needs to be destructed in some way, and it's * lifespan continues across several fbr_* calls. While being in some library * call, a fiber may be reclaimed, but it's stack remains intact until * reclaimed. Destructor is called before the stack becomes dangerous to use * and guarantees resource destruction. * * User is supposed to fill in the func and arg fields. * @see fbr_destructor_func_t * @see fbr_destructor_add * @see fbr_destructor_remove */ struct fbr_destructor { fbr_destructor_func_t func; /*!< destructor function */ void *arg; /*!< destructor function argument (optional) */ TAILQ_ENTRY(fbr_destructor) entries; //Private int active; //Private }; #define FBR_DESTRUCTOR_INITIALIZER { \ .func = NULL, \ .arg = NULL, \ .active = 0, \ }; struct fbr_id_tailq; struct fbr_id_tailq_i { /* Private structure */ fbr_id_t id; struct fbr_ev_base *ev; TAILQ_ENTRY(fbr_id_tailq_i) entries; struct fbr_destructor dtor; struct fbr_id_tailq *head; }; TAILQ_HEAD(fbr_id_tailq, fbr_id_tailq_i); /** * Base struct for all events. * * All other event structures ``inherit'' this one by inclusion of it as * ev_base member. * @see fbr_ev_upcast * @see fbr_ev_wait */ struct fbr_ev_base { enum fbr_ev_type type; /*!< type of the event */ fbr_id_t id; /*!< id of a fiber that is waiting for this event */ int arrived; /*!< flag indicating that this event has arrived */ struct fbr_context *fctx; //Private void *data; //Private struct fbr_id_tailq_i item; //Private }; /** * Convenience macro to save some typing. * * Allows you to cast fbr_ev_base to some other event struct via * fbr_container_of magic. * @see fbr_container_of * @see fbr_ev_base */ #define fbr_ev_upcast(ptr, type_no_struct) \ fbr_container_of(ptr, struct type_no_struct, ev_base) /** * libev watcher event. * * This event struct can represent any libev watcher which should be * initialized and started. You can safely pass NULL as a callback for the * watcher since the library sets up it's own callback. * @see fbr_ev_upcast * @see fbr_ev_wait */ struct fbr_ev_watcher { ev_watcher *w; /*!< libev watcher */ struct fbr_ev_base ev_base; }; /** * fbr_mutex event. * * This event struct can represent mutex aquisition waiting. * @see fbr_ev_upcast * @see fbr_ev_wait */ struct fbr_ev_mutex { struct fbr_mutex *mutex; /*!< mutex we're interested in */ struct fbr_ev_base ev_base; }; /** * fbr_cond_var event. * * This event struct can represent conditional variable waiting. * @see fbr_ev_upcast * @see fbr_ev_wait */ struct fbr_ev_cond_var { struct fbr_cond_var *cond; /*!< conditional variable we're interested in */ struct fbr_mutex *mutex; /*!< mutex to protect conditional variable*/ struct fbr_ev_base ev_base; }; /** * Mutex structure. * * This structure represent a mutex. * @see fbr_mutex_init * @see fbr_mutex_destroy */ struct fbr_mutex { fbr_id_t locked_by; struct fbr_id_tailq pending; TAILQ_ENTRY(fbr_mutex) entries; }; /** * Conditional variable structure. * * This structure represent a conditional variable. * @see fbr_mutex_init * @see fbr_mutex_destroy */ struct fbr_cond_var { struct fbr_mutex *mutex; struct fbr_id_tailq waiting; }; /** * Virtual ring buffer implementation. * * Low-level data structure implemented using memory mappings of the same * physical pages to provide no-copy overhead efficient ring buffer * imlementation. * @see fbr_vrb_init * @see fbr_vrb_destroy */ struct fbr_vrb { void *mem_ptr; size_t mem_ptr_size; void *lower_ptr; void *upper_ptr; size_t ptr_size; void *data_ptr; void *space_ptr; }; /** * Inter-fiber communication pipe. * * This structure represent a communication pipe between two (or more) fibers. * * Higher level wrapper around fbr_vrb. * @see fbr_buffer_init * @see fbr_buffer_destroy * @see struct fbr_vrb */ struct fbr_buffer { struct fbr_vrb vrb; size_t prepared_bytes; size_t waiting_bytes; struct fbr_cond_var committed_cond; struct fbr_mutex write_mutex; struct fbr_cond_var bytes_freed_cond; struct fbr_mutex read_mutex; }; struct fbr_mq; /** * Fiber-local data key. * * @see fbr_key_create * @see fbr_key_delete * @see fbr_key_get_data * @see fbr_key_set_data */ typedef unsigned int fbr_key_t; /** * Maximum numbef of fiber-local keys allowed. */ #define FBR_MAX_KEY 64 /** * Adds destructor to fiber list. * @param [in] dtor destructor to register * * This function registers a destructor. User must guarantee that destructor * object stays alive until fiber is reclaimed or destructor is removed, * whichever comes first. * @see fbr_destructor */ void fbr_destructor_add(FBR_P_ struct fbr_destructor *dtor); /** * Removes destructor from fiber list. * @param [in] dtor destructor to unregister * @param [in] call flag indicating if destructor needs to be called * * This function unregisters a destructor. User may specify a flag for * destructor function to be called. * @see fbr_destructor */ void fbr_destructor_remove(FBR_P_ struct fbr_destructor *dtor, int call); /** * Initializes a destructor. * @param [in] dtor destructor to initialize * * This function should be called before a newly allocated destructor is used. * Alternatively you may use FBR_DESTRUCTOR_INITIALIZER macro as a initializing * value upon declaration. * @see fbr_destructor */ static inline void fbr_destructor_init(struct fbr_destructor *dtor) { memset(dtor, 0x00, sizeof(*dtor)); } /** * Initializer for libev watcher event. * * This functions properly initializes fbr_ev_watcher struct. You should not do * it manually. * @see fbr_ev_watcher * @see fbr_ev_wait */ void fbr_ev_watcher_init(FBR_P_ struct fbr_ev_watcher *ev, ev_watcher *w); /** * Initializer for mutex event. * * This functions properly initializes fbr_ev_mutex struct. You should not do * it manually. * @see fbr_ev_mutex * @see fbr_ev_wait */ void fbr_ev_mutex_init(FBR_P_ struct fbr_ev_mutex *ev, struct fbr_mutex *mutex); /** * Initializer for conditional variable event. * * This functions properly initializes fbr_ev_cond_var struct. You should not do * it manually. * @see fbr_ev_cond_var * @see fbr_ev_wait */ void fbr_ev_cond_var_init(FBR_P_ struct fbr_ev_cond_var *ev, struct fbr_cond_var *cond, struct fbr_mutex *mutex); /** * Event awaiting function (one event only wrapper). * @param [in] one the event base pointer of the event to wait for * @returns 0 on success, -1 upon error * * This functions wraps fbr_ev_wait passing only one event to it. * @see fbr_ev_base * @see fbr_ev_wait */ int fbr_ev_wait_one(FBR_P_ struct fbr_ev_base *one); /** * Event awaiting function (generic one). * @param [in] events array of event base pointers * @returns the number of events arrived or -1 upon error * * This function waits until any event from events array arrives. Only one * event can arrive at a time. It returns a pointer to the same event that was * passed in events array. * @see fbr_ev_base * @see fbr_ev_wait_one */ int fbr_ev_wait(FBR_P_ struct fbr_ev_base *events[]); /** * Event awaiting function with timeout. * @param [in] events array of event base pointers * @param [in] timeout in seconds to wait for the events * @returns the number of events arrived or -1 upon error * * This function is a convenient wrapper around fbr_ev_wait, it just creates a * timer watcher and makes new events array with the timer watcher included. * Timer event is not counted in the number of returned events. * @see fbr_ev_wait */ int fbr_ev_wait_to(FBR_P_ struct fbr_ev_base *events[], ev_tstamp timeout); /** * Transfer of fiber context to another fiber. * @param [in] to callee id * @returns 0 on success, -1 on failure with f_errno set. * * This function transfers the execution context to other fiber. It returns as * soon as the called fiber yields. In case of error it returns immediately. * @see fbr_yield */ int fbr_transfer(FBR_P_ fbr_id_t to); /** * Initializes the library context. * @param [in] fctx pointer to the user allocated fbr_context. * @param [in] loop pointer to the user supplied libev loop. * * It's user's responsibility to allocate fbr_context structure and create and * run the libev event loop. * @see fbr_context * @see fbr_destroy */ void fbr_init(struct fbr_context *fctx, struct ev_loop *loop); /** * Destroys the library context. * All created fibers are reclaimed and all of the memory is freed. Stopping * the event loop is user's responsibility. * @see fbr_context * @see fbr_init * @see fbr_reclaim */ void fbr_destroy(FBR_P); /** * Enables/Disables backtrace capturing. * @param [in] enabled are backtraces enabled? * * The library tries to capture backtraces at certain points which may help * when debugging obscure problems. For example it captures the backtrace * whenever a fiber is reclaimed and when one tries to call it dumps out the * backtrace showing where was it reclaimed. But these cost quite a bit of cpu * and are disabled by default. */ void fbr_enable_backtraces(FBR_P, int enabled); /** * Analog of strerror but for the library errno. * @param [in] code Error code to describe * @see fbr_context * @see fbr_error_code */ const char *fbr_strerror(FBR_P_ enum fbr_error_code code); /** * Utility log wrapper. * * Wraps logv function of type fbr_log_func_t located in fbr_logger with log * level of FBR_LOG_ERROR. Follows printf semantics of format string and * variadic argument list. * @see fbr_context * @see fbr_logger * @see fbr_log_func_t * @see fbr_logutil_func_t */ void fbr_log_e(FBR_P_ const char *format, ...) __attribute__ ((format (printf, 2, 3))); /** * Utility log wrapper. * * Wraps logv function of type fbr_log_func_t located in fbr_logger with log * level of FBR_LOG_WARNING. Follows printf semantics of format string and * variadic argument list. * @see fbr_context * @see fbr_logger * @see fbr_log_func_t * @see fbr_logutil_func_t */ void fbr_log_w(FBR_P_ const char *format, ...) __attribute__ ((format (printf, 2, 3))); /** * Utility log wrapper. * * Wraps logv function of type fbr_log_func_t located in fbr_logger with log * level of FBR_LOG_NOTICE. Follows printf semantics of format string and * variadic argument list. * @see fbr_context * @see fbr_logger * @see fbr_log_func_t * @see fbr_logutil_func_t */ void fbr_log_n(FBR_P_ const char *format, ...) __attribute__ ((format (printf, 2, 3))); /** * Utility log wrapper. * * Wraps logv function of type fbr_log_func_t located in fbr_logger with log * level of FBR_LOG_INFO. Follows printf semantics of format string and * variadic argument list. * @see fbr_context * @see fbr_logger * @see fbr_log_func_t * @see fbr_logutil_func_t */ void fbr_log_i(FBR_P_ const char *format, ...) __attribute__ ((format (printf, 2, 3))); /** * Utility log wrapper. * * Wraps logv function of type fbr_log_func_t located in fbr_logger with log * level of FBR_LOG_DEBUG. Follows printf semantics of format string and * variadic argument list. * @see fbr_context * @see fbr_logger * @see fbr_log_func_t * @see fbr_logutil_func_t */ void fbr_log_d(FBR_P_ const char *format, ...) __attribute__ ((format (printf, 2, 3))); /** * Maximum length of fiber's name. */ #define FBR_MAX_FIBER_NAME 64 /** * Creates a new fiber. * @param [in] name fiber name, used for identification it * backtraces, etc. * @param [in] func function used as a fiber's ``main''. * @param [in] stack_size stack size (0 for default). * @param [in] arg user supplied argument to a fiber. * @return Pointer to the created fiber. * * The created fiber is not running in any shape or form, it's just created and * is ready to be launched. * * Stack is anonymously mmaped so it should not occupy all the required space * straight away. Adjust stack size only when you know what you are doing! * * Allocated stacks are registered as stacks via valgrind client request * mechanism, so it's generally valgrind friendly and should not cause any * noise. * * Fibers are organized in a tree. Child nodes are attached to a parent * whenever the parent is creating them. This tree is used primarily for * automatic reclaim of child fibers. * @see fbr_reclaim * @see fbr_disown * @see fbr_parent */ fbr_id_t fbr_create(FBR_P_ const char *name, fbr_fiber_func_t func, void *arg, size_t stack_size); /** * Retrieve a name of the fiber. * @param [in] id identificator of a fiber * @return pointer to charater buffer or NULL on error * * The name is located in the statically allocated buffer of size * FBR_MAX_FIBER_NAME. * * Don't try to free it! * * @see fbr_create * @see fbr_set_name */ const char *fbr_get_name(FBR_P_ fbr_id_t id); /** * Sets a name for the fiber. * @param [in] id identificator of a fiber * @param [in] name new name for a fiber * @return 0 on success, -1 on error. * * The name is located in the statically allocated buffer of size * FBR_MAX_FIBER_NAME. If your name does not fit, it will be trimmed. * * @see fbr_get_name */ int fbr_set_name(FBR_P_ fbr_id_t id, const char *name); /** * Changes parent of current fiber. * @param [in] parent new parent fiber * @returns -1 on error with f_errno set, 0 upon success * * This function allows you to change fiber's parent. You needs to pass valid * id or 0 to indicate the root fiber. * * This might be useful when some fiber A creates another fiber B that should * survive it's parent being reclaimed, or vice versa, some fiber A needs to be * reclaimed with fiber B albeit B is not A's parent. * * Root fiber is reclaimed only when library context is destroyed. * @see fbr_create * @see fbr_destroy */ int fbr_disown(FBR_P_ fbr_id_t parent); /** * Find out current fiber's parent. * @returns current fiber's parent * * This function allows you to find out what fiber is considered to be parent * for the current one. * @see fbr_create * @see fbr_disown */ fbr_id_t fbr_parent(FBR_P); /** * Reclaims a fiber. * @param [in] fiber fiber pointer * @returns -1 on error with f_errno set, 0 upon success * * Fibers are never destroyed, but reclaimed. Reclamation frees some resources * like call lists and memory pools immediately while keeping fiber structure * itself and its stack as is. Reclaimed fiber is prepended to the reclaimed * fiber list and will be served as a new one whenever next fbr_create is * called. Fiber is prepended because it is warm in terms of cpu cache and its * use might be faster than any other fiber in the list. * * When you have some reclaimed fibers in the list, reclaiming and creating are * generally cheap operations. * * This function takes action immediately unless the target fiber has blocked * the reclaim by fbr_set_noreclaim (in this case fbr_reclaim will block and * wait for fbr_set_reclaim to be called). */ int fbr_reclaim(FBR_P_ fbr_id_t fiber); /** * Allows a fiber to be reclaimed. * @param [in] fiber fiber pointer * @returns -1 on error with f_errno set, 0 upon success * * The opposite of fbr_set_noreclaim. Enables the fiber to be reclaimed and * returns the control flow to the caller (i.e. the fiber will not be * immediately reclaimed). * fbr_want_reclaim can be used to check if reclaim of the fiber was requested * so as to cooperate nicely and return from the fiber or call fbr_reclaim on * fbr_self. * * @see fbr_want_reclaim */ int fbr_set_reclaim(FBR_P_ fbr_id_t fiber); /** * Blocks a fiber from being reclaimed. * @param [in] fiber fiber pointer * @returns -1 on error with f_errno set, 0 upon success * * After this call the fiber will not be reclaimed until explicitly allowed by * fbr_set_reclaim. Nesting of such blocks is allowed as long as * fbr_set_reclaim and fbr_set_noreclaim are called the same number of times. * * @see fbr_set_reclaim */ int fbr_set_noreclaim(FBR_P_ fbr_id_t fiber); /** * Checks if reclaim requests are pending. * @param [in] fiber fiber pointer * @returns -1 on error with f_errno set, 0 if no pending reclaim requests, 1 * if there are pending requests * * This function can be used to check if there are pending reclaim requests. It * can return 1 only when fuber is out of any (nested) no reclaim blocks. * * @see fbr_set_noreclaim */ int fbr_want_reclaim(FBR_P_ fbr_id_t fiber); /** * Tests if given fiber is reclaimed. * @param [in] fiber fiber pointer * @return 1 if fiber is reclaimed, 0 otherwise */ int fbr_is_reclaimed(FBR_P_ fbr_id_t fiber); /** * Returns id of current fiber. * @return fbr_id_t of current fiber being executed. */ fbr_id_t fbr_self(FBR_P); /** * Fiber-local key creation. * * This created a new unique key and stores it in key. */ int fbr_key_create(FBR_P_ fbr_key_t *key); /** * Fiber-local key deletion. * This explicitly destroys a key. */ int fbr_key_delete(FBR_P_ fbr_key_t key); /** * Sets fiber-local key data. * This stores a value under a key. */ int fbr_key_set(FBR_P_ fbr_id_t id, fbr_key_t key, void *value); /** * Gets fiber-local key data. * This retrieves the value under a key. */ void *fbr_key_get(FBR_P_ fbr_id_t id, fbr_key_t key); /** * Yields execution to other fiber. * * When a fiber is waiting for some incoming event --- it should yield. This * will pop current fiber from the fiber stack and transfer the execution * context to the next fiber from the stack making that fiber a new current * one. * * It loops through all fibers subscribed to specified multicast group id. * @see fbr_transfer */ void fbr_yield(FBR_P); /** * Yields execution to other fiber returning the execution at the next event * loop run. * * Useful inside of some busy loop with lots of iterations to play nicely with * other fibers which might start starving on the execution time. * @see fbr_yield * @see fbr_transfer */ void fbr_cooperate(FBR_P); /** * (DEPRECATED) Allocates memory in current fiber's pool. * @param [in] size size of the requested memory block * @return allocated memory chunk * * When a fiber is reclaimed, this memory will be freed. Prior to that a * destructor will be called if any specified. * @see fbr_calloc * @see fbr_alloc_set_destructor * @see fbr_alloc_destructor_func_t * @see fbr_free */ void *fbr_alloc(FBR_P_ size_t size); /** * (DEPRECATED) Sets destructor for a memory chunk. * @param [in] ptr address of a memory chunk * @param [in] func destructor function * @param [in] context user supplied context pointer * * Setting new destructor simply changes it without calling old one or queueing * them. * * You can allocate 0 sized memory chunk and never free it just for the purpose * of calling destructor with some context when fiber is reclaimed. This way * you can for example close some file descriptors or do some other required * cleanup. * @see fbr_alloc * @see fbr_free */ void fbr_alloc_set_destructor(FBR_P_ void *ptr, fbr_alloc_destructor_func_t func, void *context); /** * (DEPRECATED) Allocates a set of initialized objects in fiber's pool. * @param [in] nmemb number of members * @param [in] size size of a single member * @return zero-filled allocated memory chunk * * Same as fbr_alloc called with nmemb multiplied by size. * @see fbr_alloc * @see fbr_free */ void *fbr_calloc(FBR_P_ unsigned int nmemb, size_t size); /** * (DEPRECATED) Explicitly frees allocated memory chunk. * @param [in] ptr chunk address * * Explicitly frees a fiber pool chunk calling the destructor if any. * @see fbr_alloc * @see fbr_calloc * @see fbr_alloc_set_destructor */ void fbr_free(FBR_P_ void *ptr); /** * (DEPRECATED) Explicitly frees allocated memory chunk. * @param [in] ptr chunk address * * Explicitly frees a fiber pool chunk without calling the destructor. * @see fbr_alloc * @see fbr_calloc * @see fbr_alloc_set_destructor */ void fbr_free_nd(FBR_P_ void *ptr); /** * Utility function to make file descriptor non-blocking. * @param [in] fd file descriptor to make non-blocking * @returns -1 on error with f_errno set, 0 upon success * * In case of failure FBR_ESYSTEM is set as f_errno ans user should consult * system errno for details. * */ int fbr_fd_nonblock(FBR_P_ int fd); /** * Fiber friendly connect wrapper. * @param [in] sockfd - socket file descriptor * @param [in] addr - pointer to struct sockaddr, containing connection details * @param [in] length of struct sockaddr * @return zero on success, -1 in case of error and errno set * * Connect wrapper, that connects the socket referred to by the file * descriptor sockfd to the address specified by addr. * starting at buf. Calling fiber will be blocked until sockfd is connected or * error is occured * * Possible errno values are described in connect man page. The only special case * is EINPROGRESS which is handled internally. */ int fbr_connect(FBR_P_ int sockfd, const struct sockaddr *addr, socklen_t addrlen); /** * Fiber friendly connect wrapper with timeout. * @param [in] sockfd - socket file descriptor * @param [in] addr - pointer to struct sockaddr, containing connection details * @param [in] length of struct sockaddr * @param [in] timeout in seconds to wait for events * @return zero on success, -1 in case of error and errno set * * Connect wrapper, that connects the socket referred to by the file * descriptor sockfd to the address specified by addr. * starting at buf. Calling fiber will be blocked until sockfd is connected or * either timeout or error occurs * * Possible errno values are described in connect man page. The are special cases: * EINPROGRESS is handled internally; ETIMEDOUT is returned in case of timeout. */ int fbr_connect_wto(FBR_P_ int sockfd, const struct sockaddr *addr, socklen_t addrlen, ev_tstamp timeout); /** * Fiber friendly libc read wrapper. * @param [in] fd file descriptor to read from * @param [in] buf pointer to some user-allocated buffer * @param [in] count maximum number of bytes to read * @return number of bytes read on success, -1 in case of error and errno set * * Attempts to read up to count bytes from file descriptor fd into the buffer * starting at buf. Calling fiber will be blocked until something arrives at * fd. * * Possible errno values are described in read man page. * * @see fbr_read_all * @see fbr_readline */ ssize_t fbr_read(FBR_P_ int fd, void *buf, size_t count); /** * Fiber friendly libc read wrapper with timeout. * @param [in] fd file descriptor to read from * @param [in] buf pointer to some user-allocated buffer * @param [in] count maximum number of bytes to read * @param [in] timeout in seconds to wait for events * @return number of bytes read on success, -1 in case of error and errno set * * Attempts to read up to count bytes from file descriptor fd into the buffer * starting at buf. Calling fiber will be blocked until something arrives at * fd or timeout occurs. * * Possible errno values are described in read man page. The only special case * is ETIMEDOUT, which is returned to the caller when timeout occurs. * * @see fbr_read_all * @see fbr_readline */ ssize_t fbr_read_wto(FBR_P_ int fd, void *buf, size_t count, ev_tstamp timeout); /** * Even more fiber friendly libc read wrapper. * @param [in] fd file descriptor to read from * @param [in] buf pointer to some user-allocated buffer * @param [in] count desired number of bytes to read * @return number of bytes read on success, -1 in case of error and errno set * * Attempts to read exactly count bytes from file descriptor fd into the buffer * starting at buf. Calling fiber will be blocked until the required amount of * data or EOF arrive at fd. If latter occurs too early returned number of * bytes will be less that required. * * Possible errno values are described in read man page. * * @see fbr_read * @see fbr_read_line */ ssize_t fbr_read_all(FBR_P_ int fd, void *buf, size_t count); /** * Even more fiber friendly libc read wrapper with timeout. * @param [in] fd file descriptor to read from * @param [in] buf pointer to some user-allocated buffer * @param [in] count desired number of bytes to read * @param [in] timeout in seconds to wait for events * @return number of bytes read on success, -1 in case of error and errno set * * Attempts to read exactly count bytes from file descriptor fd into the buffer * starting at buf. Calling fiber will be blocked for timeout number of seconds, or * the required amount of data arrives, or EOF is got at fd. If latter occurs too * early, returned number of bytes will be less that required. * * Possible errno values are described in read man page. Errno is set to ETIMEDOUT * when timeout occurs. * * @see fbr_read * @see fbr_readline */ ssize_t fbr_read_all_wto(FBR_P_ int fd, void *buf, size_t count, ev_tstamp timeout); /** * Utility function to read a line. * @param [in] fd file descriptor to read from * @param [in] buffer pointer to some user-allocated buffer * @param [in] n maximum number of bytes to read * @return number of bytes read on success, -1 in case of error and errno set * * Attempts to read at most count bytes from file descriptor fd into the buffer * starting at buf, but stops if newline is encountered. Calling fiber will be * blocked until the required amount of data, EOF or newline arrive at fd. * * Possible errno values are described in read man page. * * @see fbr_read * @see fbr_read_all */ ssize_t fbr_readline(FBR_P_ int fd, void *buffer, size_t n); /** * Fiber friendly libc write wrapper. * @param [in] fd file descriptor to write to * @param [in] buf pointer to some user-allocated buffer * @param [in] count maximum number of bytes to write * @return number of bytes written on success, -1 in case of error and errno set * * Attempts to write up to count bytes to file descriptor fd from the buffer * starting at buf. Calling fiber will be blocked until the data is written. * * Possible errno values are described in write man page. * * @see fbr_write_all */ ssize_t fbr_write(FBR_P_ int fd, const void *buf, size_t count); /** * Fiber friendly libc write wrapper with timeout. * @param [in] fd file descriptor to write to * @param [in] buf pointer to some user-allocated buffer * @param [in] count maximum number of bytes to write * @param [in] timeout in seconds to wait for events * @return number of bytes written on success, -1 in case of error and errno set * * Attempts to write up to count bytes to file descriptor fd from the buffer * starting at buf. Calling fiber will be blocked until the data is written * or timeout occurs. * * Possible errno values are described in write man page. * ETIMEDOUT is returned in case of timeout. * * @see fbr_write_all_wto */ ssize_t fbr_write_wto(FBR_P_ int fd, const void *buf, size_t count, ev_tstamp timeout); /** * Even more fiber friendly libc write wrapper. * @param [in] fd file descriptor to write to * @param [in] buf pointer to some user-allocated buffer * @param [in] count desired number of bytes to write * @return number of bytes read on success, -1 in case of error and errno set * * Attempts to write exactly count bytes to file descriptor fd from the buffer * starting at buf. Calling fiber will be blocked until the required amount of * data is written to fd. * * Possible errno values are described in write man page. * * @see fbr_write */ ssize_t fbr_write_all(FBR_P_ int fd, const void *buf, size_t count); /** * Even more fiber friendly libc write wrapper with timeout. * @param [in] fd file descriptor to write to * @param [in] buf pointer to some user-allocated buffer * @param [in] count desired number of bytes to write * @param [in] timeout in seconds to wait for events * @return number of bytes read on success, -1 in case of error and errno set * * Attempts to write exactly count bytes to file descriptor fd from the buffer * starting at buf. Calling fiber will be blocked until the required amount of * data is written to fd or timeout occurs. * * Possible errno values are described in write man page. * * @see fbr_write_wto */ ssize_t fbr_write_all_wto(FBR_P_ int fd, const void *buf, size_t count, ev_tstamp timeout); /** * Fiber friendly libc recvfrom wrapper. * @param [in] sockfd file descriptor to read from * @param [in] buf pointer to some user-allocated buffer * @param [in] len maximum number of bytes to read * @param [in] flags just flags, see man recvfrom for details * @param [in] src_addr source address * @param [in] addrlen size of src_addr * @return number of bytes read on success, -1 in case of error and errno set * * This function is used to receive messages from a socket. * * Possible errno values are described in recvfrom man page. * */ ssize_t fbr_recvfrom(FBR_P_ int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen); /** * Fiber friendly libc recv wrapper. * @param [in] sockfd file descriptor to read from * @param [in] buf pointer to some user-allocated buffer * @param [in] len maximum number of bytes to read * @param [in] flags just flags, see man recvfrom for details * @return number of bytes read on success, -1 in case of error and errno set * * This function is used to receive messages from a socket. * * Possible errno values are described in recv man page. */ ssize_t fbr_recv(FBR_P_ int sockfd, void *buf, size_t len, int flags); /** * Fiber friendly libc sendto wrapper. * @param [in] sockfd file descriptor to write to * @param [in] buf pointer to some user-allocated buffer * @param [in] len maximum number of bytes to write * @param [in] flags just flags, see man sendto for details * @param [in] dest_addr destination address * @param [in] addrlen size of dest_addr * @return number of bytes written on success, -1 in case of error and errno set * * This function is used to send messages to a socket. * * Possible errno values are described in sendto man page. * */ ssize_t fbr_sendto(FBR_P_ int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen); /** * * Fiber friendly libc send wrapper. * @param [in] sockfd file descriptor to write to * @param [in] buf pointer to some user-allocated buffer * @param [in] len maximum number of bytes to write * @param [in] flags just flags, see man sendto for details * @return number of bytes written on success, -1 in case of error and errno set * * This function is used to send messages to a socket. */ ssize_t fbr_send(FBR_P_ int sockfd, const void *buf, size_t len, int flags); /** * Fiber friendly libc accept wrapper. * @param [in] sockfd file descriptor to accept on * @param [in] addr client address * @param [in] addrlen size of addr * @return client socket fd on success, -1 in case of error and errno set * * This function is used to accept a connection on a listening socket. * * Possible errno values are described in accept man page. * */ int fbr_accept(FBR_P_ int sockfd, struct sockaddr *addr, socklen_t *addrlen); /** * Puts current fiber to sleep. * @param [in] seconds maximum number of seconds to sleep * @return number of seconds actually being asleep * * This function is used to put current fiber into sleep. It will wake up after * the desired time has passed or earlier if some other fiber has called it. */ ev_tstamp fbr_sleep(FBR_P_ ev_tstamp seconds); /** * Waits for an async libev event. * @param [in] w ev_async watcher (initialized by caller) * * This function will cause the calling fiber to wait until an * ev_async_send() has been triggered on the specified ev_async watcher. */ void fbr_async_wait(FBR_P_ ev_async *w); /** * Prints fiber call stack to stderr. * * useful while debugging obscure fiber call problems. */ void fbr_dump_stack(FBR_P_ fbr_logutil_func_t log); /** * Initializes a mutex. * @param [in] mutex a mutex structure to initialize * * Mutexes are helpful when your fiber has a critical code section including * several fbr_* calls. In this case execution of multiple copies of your fiber * may get mixed up. * * @see fbr_mutex_lock * @see fbr_mutex_trylock * @see fbr_mutex_unlock * @see fbr_mutex_destroy */ void fbr_mutex_init(FBR_P_ struct fbr_mutex *mutex); /** * Locks a mutex. * @param [in] mutex pointer to a mutex * * Attempts to lock a mutex. If mutex is already locked then the calling fiber * is suspended until the mutex is eventually freed. * * @see fbr_mutex_init * @see fbr_mutex_trylock * @see fbr_mutex_unlock * @see fbr_mutex_destroy */ void fbr_mutex_lock(FBR_P_ struct fbr_mutex *mutex); /** * Tries to locks a mutex. * @param [in] mutex pointer to a mutex * @return 1 if lock was successful, 0 otherwise * * Attempts to lock a mutex. Returns immediately despite of locking being * successful or not. * * @see fbr_mutex_init * @see fbr_mutex_lock * @see fbr_mutex_unlock * @see fbr_mutex_destroy */ int fbr_mutex_trylock(FBR_P_ struct fbr_mutex *mutex); /** * Unlocks a mutex. * @param [in] mutex pointer to a mutex * * Unlocks the given mutex. An other fiber that is waiting for it (if any) will * be called upon next libev loop iteration. * * @see fbr_mutex_init * @see fbr_mutex_lock * @see fbr_mutex_trylock * @see fbr_mutex_destroy */ void fbr_mutex_unlock(FBR_P_ struct fbr_mutex *mutex); /** * Destroys a mutex. * @param [in] mutex pointer to mutex * * Frees used resources. It does not unlock the mutex. * * @see fbr_mutex_init * @see fbr_mutex_lock * @see fbr_mutex_unlock * @see fbr_mutex_trylock */ void fbr_mutex_destroy(FBR_P_ struct fbr_mutex *mutex); /** * Initializes a conditional variable. * * Conditional variable is useful primitive for fiber synchronisation. A set of * fibers may be waiting until certain condition is met. Another fiber can * trigger this condition for one or all waiting fibers. * * @see fbr_cond_destroy * @see fbr_cond_wait * @see fbr_cond_broadcast * @see fbr_cond_signal */ void fbr_cond_init(FBR_P_ struct fbr_cond_var *cond); /** * Destroys a conditional variable. * * This just frees used resources. No signals are sent to waiting fibers. * * @see fbr_cond_init * @see fbr_cond_wait * @see fbr_cond_broadcast * @see fbr_cond_signal */ void fbr_cond_destroy(FBR_P_ struct fbr_cond_var *cond); /** * Waits until condition is met. * * Current fiber is suspended until a signal is sent via fbr_cond_signal or * fbr_cond_broadcast to the corresponding conditional variable. * * A mutex must be acquired by the calling fiber prior to waiting for a * condition. Internally mutex is released and reacquired again before * returning. Upon successful return calling fiber will hold the mutex. * * @see fbr_cond_init * @see fbr_cond_destroy * @see fbr_cond_broadcast * @see fbr_cond_signal */ int fbr_cond_wait(FBR_P_ struct fbr_cond_var *cond, struct fbr_mutex *mutex); /** * Broadcasts a signal to all fibers waiting for condition. * * All fibers waiting for a condition will be added to run queue (and will * eventually be run, one per event loop iteration). * * @see fbr_cond_init * @see fbr_cond_destroy * @see fbr_cond_wait * @see fbr_cond_signal */ void fbr_cond_broadcast(FBR_P_ struct fbr_cond_var *cond); /** * Signals to first fiber waiting for a condition. * * Exactly one fiber (first one) waiting for a condition will be added to run * queue (and will eventually be run, one per event loop iteration). * * @see fbr_cond_init * @see fbr_cond_destroy * @see fbr_cond_wait * @see fbr_cond_signal */ void fbr_cond_signal(FBR_P_ struct fbr_cond_var *cond); /** * Initializes memory mappings. * @param [in] vrb a pointer to fbr_vrb * @param [in] size length of the data * @param [in] file_pattern file name patterm for underlying mmap storage * @returns 0 on succes, -1 on error. * * This function mmaps adjacent virtual memory regions of required size which * correspond to the same physical memory region. Also it adds two page-sized * regions on the left and on the right with PROT_NONE access as a guards. * * It does mmaps on the same file, which is unlinked and closed afterwards, so * it will not pollute file descriptor space of a process and the filesystem. * * @see struct fbr_vrb * @see fbr_vrb_destroy */ int fbr_vrb_init(struct fbr_vrb *vrb, size_t size, const char *file_pattern); /** * Destroys mappings. * @param [in] vrb a pointer to fbr_vrb * * This function unmaps all the mappings done by fbr_vrb_init. * * @see fbr_vrb_init */ void fbr_vrb_destroy(struct fbr_vrb *vrb); /** * Retrieves data length. * @param [in] vrb a pointer to fbr_vrb * @returns length of the data area. * * @see struct fbr_vrb */ static inline size_t fbr_vrb_data_len(struct fbr_vrb *vrb) { return (char *) vrb->space_ptr - (char *) vrb->data_ptr; } /** * Retrieves space length. * @param [in] vrb a pointer to fbr_vrb * @returns length of the space area. * * @see struct fbr_vrb */ static inline size_t fbr_vrb_space_len(struct fbr_vrb *vrb) { return (char *) vrb->data_ptr + vrb->ptr_size - (char *) vrb->space_ptr; } /** * Retrieves total buffer capacity. * @param [in] vrb a pointer to fbr_vrb * @returns maximum length of data this vrb can hold. * * @see struct fbr_vrb */ static inline size_t fbr_vrb_capacity(struct fbr_vrb *vrb) { return vrb->ptr_size; } /** * Retrieves space area pointer. * @param [in] vrb a pointer to fbr_vrb * @returns pointer to the start of space area. * * @see struct fbr_vrb */ static inline void *fbr_vrb_space_ptr(struct fbr_vrb *vrb) { return vrb->space_ptr; } /** * Retrieves data area pointer. * @param [in] vrb a pointer to fbr_vrb * @returns pointer to the start of data area. * * @see struct fbr_vrb */ static inline void *fbr_vrb_data_ptr(struct fbr_vrb *vrb) { return vrb->data_ptr; } /** * Give data to a vrb. * @param [in] vrb a pointer to fbr_vrb * @param [in] size length of the data * @returns 0 on succes, -1 on error. * * This function marks size bytes of space area as data starting from the * beginning of space area. It's your responsibility to fill those area with * the actual data. * * @see struct fbr_vrb * @see fbr_vrb_take */ static inline int fbr_vrb_give(struct fbr_vrb *vrb, size_t size) { if (size > fbr_vrb_space_len(vrb)) return -1; vrb->space_ptr += size; return 0; } /** * Take data from a vrb. * @param [in] vrb a pointer to fbr_vrb * @param [in] size length of the data * @returns 0 on succes, -1 on error. * * This function marks size bytes of data area as space starting from the * beginning of data area. It's your responsibility to drop any references to * the region as it might be overwritten later. * * @see struct fbr_vrb * @see fbr_vrb_give */ static inline int fbr_vrb_take(struct fbr_vrb *vrb, size_t size) { if (size > fbr_vrb_data_len(vrb)) return -1; vrb->data_ptr += size; if (vrb->data_ptr >= vrb->upper_ptr) { vrb->data_ptr -= vrb->ptr_size; vrb->space_ptr -= vrb->ptr_size; } return 0; } /** * Resets a vrb. * @param [in] vrb a pointer to fbr_vrb * * This function resets data and space pointers to their initial value, * efficiently marking vrb as empty. * * @see struct fbr_vrb */ static inline void fbr_vrb_reset(struct fbr_vrb *vrb) { vrb->data_ptr = vrb->lower_ptr; vrb->space_ptr = vrb->lower_ptr; } /* Private function */ int fbr_vrb_resize_do(struct fbr_vrb *vrb, size_t new_size, const char *file_pattern); /** * Resizes a vrb. * @param [in] vrb a pointer to fbr_vrb * @param [in] new_size new length of the data * @param [in] file_pattern file name patterm for underlying mmap storage * @returns 0 on succes, -1 on error. * * This function does new mappings and copies the data over. Old mappings will * be destroyed and all pointers to old data will be invalid after this * operation. * * @see struct fbr_vrb * @see fbr_vrb_init */ static inline int fbr_vrb_resize(struct fbr_vrb *vrb, size_t new_size, const char *file_pattern) { struct fbr_vrb tmp; int rv; if (fbr_vrb_capacity(vrb) >= new_size) return 0; memcpy(&tmp, vrb, sizeof(tmp)); rv = fbr_vrb_init(vrb, new_size, file_pattern); if (rv) { memcpy(vrb, &tmp, sizeof(tmp)); return rv; } memcpy(fbr_vrb_space_ptr(vrb), fbr_vrb_data_ptr(&tmp), fbr_vrb_data_len(&tmp)); fbr_vrb_give(vrb, fbr_vrb_data_len(&tmp)); fbr_vrb_destroy(&tmp); return 0; } /** * Initializes a circular buffer with pipe semantics. * @param [in] buffer fbr_buffer structure to initialize * @param [in] size size hint for the buffer * @returns 0 on succes, -1 upon failure with f_errno set. * * This allocates a buffer with pipe semantics: you can write into it and later * read what you have written. The buffer will occupy size rounded up to page * size in physical memory, while occupying twice this size in virtual process * memory due to usage of two mirrored adjacent mmaps. */ int fbr_buffer_init(FBR_P_ struct fbr_buffer *buffer, size_t size); /** * Amount of bytes filled with data. * @param [in] buffer a pointer to fbr_buffer * @returns number of bytes written to the buffer * * This function can be used to check if fbr_buffer_read_address will block. * @see fbr_buffer_free_bytes */ static inline size_t fbr_buffer_bytes(FBR_PU_ struct fbr_buffer *buffer) { return fbr_vrb_data_len(&buffer->vrb); } /** * Amount of free bytes. * @param [in] buffer a pointer to fbr_buffer * @returns number of free bytes in the buffer * * This function can be used to check if fbr_buffer_alloc_prepare will block. * @see fbr_buffer_bytes */ static inline size_t fbr_buffer_free_bytes(FBR_PU_ struct fbr_buffer *buffer) { return fbr_vrb_space_len(&buffer->vrb); } /** * Total capacity of a buffer. * @param [in] buffer a pointer to fbr_buffer * @returns maximum number of bytes the buffer may contain. * * This function may return total capacity larger that originally requested due * to size being rounded up to be a multiple of page size. * @see fbr_buffer_bytes * @see fbr_buffer_free_bytes */ static inline size_t fbr_buffer_size(FBR_PU_ struct fbr_buffer *buffer) { return fbr_vrb_capacity(&buffer->vrb); } /** * Pointer to the start of ``space'' memory area. * @param [in] buffer a pointer to fbr_buffer * @returns pointer to space memory region start. * * This function returns a pointer to the start of free memory area inside the * buffer. * * You may use this function in case you have a fbr_buffer, that is not used as * an inter-fiber communication mechanism but only as a local circular data * buffer. * * Mixing space_ptr/data_ptr/give/take API with mutex-protected transactional * API might lead to corruption and is not recommended unless you know what you * are doing. * @see fbr_buffer_data_ptr * @see fbr_buffer_give * @see fbr_buffer_take */ static inline void *fbr_buffer_space_ptr(FBR_PU_ struct fbr_buffer *buffer) { return fbr_vrb_space_ptr(&buffer->vrb); } /** * Pointer to the start of ``data'' memory area. * @param [in] buffer a pointer to fbr_buffer * @returns pointer to data memory region start. * * This function returns a pointer to the start of data memory area inside the * buffer. * * You may use this function in case you have a fbr_buffer, that is not used as * an inter-fiber communication mechanism but only as a local circular data * buffer. * * Mixing space_ptr/data_ptr/give/take API with mutex-protected transactional * API might lead to corruption and is not recommended unless you know what you * are doing. * @see fbr_buffer_data_ptr * @see fbr_buffer_give * @see fbr_buffer_take */ static inline void *fbr_buffer_data_ptr(FBR_PU_ struct fbr_buffer *buffer) { return fbr_vrb_data_ptr(&buffer->vrb); } /** * Resets a buffer. * @param [in] buffer a pointer to fbr_buffer * * This function resets space and data pointers of the buffer to it's start, * which results in whole buffer being marked as space. * * This function does not affect the state of mutexes and conditional * variables, so using it while the buffer is in use by multiple fibers in not * safe. * * @see fbr_buffer_init * @see fbr_buffer_destroy */ static inline void fbr_buffer_reset(FBR_PU_ struct fbr_buffer *buffer) { fbr_vrb_reset(&buffer->vrb); } /** * Destroys a circular buffer. * @param [in] buffer a pointer to fbr_buffer to free * * This unmaps all mmaped memory for the buffer. It does not do any fancy stuff * like waiting until buffer is empty etc., it just frees it. */ void fbr_buffer_destroy(FBR_P_ struct fbr_buffer *buffer); /** * Prepares a chunk of memory to be committed to buffer. * @param [in] buffer a pointer to fbr_buffer * @param [in] size required size * @returns pointer to memory reserved for commit. * * This function reserves a chunk of memory (or waits until there is one * available, blocking current fiber) and returns pointer to it. * * A fiber trying to reserve a chunk of memory after some other fiber already * reserved it leads to the former fiber being blocked until the latter one * commits or aborts. * @see fbr_buffer_alloc_commit * @see fbr_buffer_alloc_abort */ void *fbr_buffer_alloc_prepare(FBR_P_ struct fbr_buffer *buffer, size_t size); /** * Commits a chunk of memory to the buffer. * @param [in] buffer a pointer to fbr_buffer * * This function commits a chunk of memory previously reserved. * @see fbr_buffer_alloc_prepare * @see fbr_buffer_alloc_abort */ void fbr_buffer_alloc_commit(FBR_P_ struct fbr_buffer *buffer); /** * Aborts a chunk of memory in the buffer. * @param [in] buffer a pointer to fbr_buffer * * This function aborts prepared chunk of memory previously reserved. It will * not be committed and the next fiber may reuse it for it's own purposes. * @see fbr_buffer_alloc_prepare * @see fbr_buffer_alloc_commit */ void fbr_buffer_alloc_abort(FBR_P_ struct fbr_buffer *buffer); /** * Aborts a chunk of memory in the buffer. * @param [in] buffer a pointer to fbr_buffer * @param [in] size number of bytes required * @returns read address containing size bytes * * This function reserves (or waits till data is available, blocking current * fiber) a chunk of memory for reading. While a chunk of memory is reserved * for reading no other fiber can read from this buffer blocking until current * read is advanced or discarded. * @see fbr_buffer_read_advance * @see fbr_buffer_read_discard */ void *fbr_buffer_read_address(FBR_P_ struct fbr_buffer *buffer, size_t size); /** * Confirms a read of chunk of memory in the buffer. * @param [in] buffer a pointer to fbr_buffer * * This function confirms that bytes obtained with fbr_buffer_read_address are * read and no other fiber will be able to read them. * @see fbr_buffer_read_address * @see fbr_buffer_read_discard */ void fbr_buffer_read_advance(FBR_P_ struct fbr_buffer *buffer); /** * Discards a read of chunk of memory in the buffer. * @param [in] buffer a pointer to fbr_buffer * * This function discards bytes obtained with fbr_buffer_read_address. Next * fiber trying to read something from a buffer may obtain those bytes. * @see fbr_buffer_read_address * @see fbr_buffer_read_advance */ void fbr_buffer_read_discard(FBR_P_ struct fbr_buffer *buffer); /** * Resizes the buffer. * @param [in] buffer a pointer to fbr_buffer * @param [in] size a new buffer length * @returns 0 on success, -1 on error. * * This function allocates new memory mapping of sufficient size and copies the * content of a buffer into it. Old mapping is destroyed. * * This operation is expensive and involves several syscalls, so it is * beneficiary to allocate a buffer of siffucuent size from the start. * * This function acquires both read and write mutex, and may block until read * or write operation has finished. * @see fbr_buffer_reset */ int fbr_buffer_resize(FBR_P_ struct fbr_buffer *buffer, size_t size); /** * Helper function, returning read conditional variable. * @param [in] buffer a pointer to fbr_buffer * @returns read conditional variable */ static inline struct fbr_cond_var *fbr_buffer_cond_read(FBR_PU_ struct fbr_buffer *buffer) { return &buffer->committed_cond; } /** * Helper function, returning write conditional variable. * @param [in] buffer a pointer to fbr_buffer * @returns write conditional variable */ static inline struct fbr_cond_var *fbr_buffer_cond_write(FBR_PU_ struct fbr_buffer *buffer) { return &buffer->bytes_freed_cond; } /** * Helper function, which waits until read is possible. * @param [in] buffer a pointer to fbr_buffer * @param [in] size required read size * @returns 1 to be while friendly * * This function is useful when you need to wait for data to arrive on a buffer * in a while loop. */ static inline int fbr_buffer_wait_read(FBR_P_ struct fbr_buffer *buffer, size_t size) { struct fbr_mutex mutex; int retval; fbr_mutex_init(FBR_A_ &mutex); fbr_mutex_lock(FBR_A_ &mutex); while (fbr_buffer_bytes(FBR_A_ buffer) < size) { retval = fbr_cond_wait(FBR_A_ &buffer->committed_cond, &mutex); assert(0 == retval); (void)retval; } fbr_mutex_unlock(FBR_A_ &mutex); fbr_mutex_destroy(FBR_A_ &mutex); return 1; } /** * Helper function, which test if read is possible. * @param [in] buffer a pointer to fbr_buffer * @param [in] size required read size * @returns 1 if read is possible, 0 otherwise * * This function is useful when you need to test if you can read some data from * the buffer without blocking. */ static inline int fbr_buffer_can_read(FBR_P_ struct fbr_buffer *buffer, size_t size) { return fbr_buffer_bytes(FBR_A_ buffer) >= size; } /** * Helper function, which waits until write is possible. * @param [in] buffer a pointer to fbr_buffer * @param [in] size required write size * @returns 1 to be while friendly * * This function is useful when you need to wait for free space on a buffer * in a while loop. */ static inline int fbr_buffer_wait_write(FBR_P_ struct fbr_buffer *buffer, size_t size) { struct fbr_mutex mutex; int retval; fbr_mutex_init(FBR_A_ &mutex); fbr_mutex_lock(FBR_A_ &mutex); while (fbr_buffer_free_bytes(FBR_A_ buffer) < size) { retval = fbr_cond_wait(FBR_A_ &buffer->bytes_freed_cond, &mutex); assert(0 == retval); (void)retval; } fbr_mutex_unlock(FBR_A_ &mutex); fbr_mutex_destroy(FBR_A_ &mutex); return 1; } /** * Helper function, which test if write is possible. * @param [in] buffer a pointer to fbr_buffer * @param [in] size required write size * @returns 1 if write is possible, 0 otherwise * * This function is useful when you need to test if you can write some data to * the buffer without blocking. */ static inline int fbr_buffer_can_write(FBR_P_ struct fbr_buffer *buffer, size_t size) { return fbr_buffer_free_bytes(FBR_A_ buffer) >= size; } struct fbr_mq *fbr_mq_create(FBR_P_ size_t size, int flags); void fbr_mq_push(struct fbr_mq *mq, void *obj); int fbr_mq_try_push(struct fbr_mq *mq, void *obj); void fbr_mq_wait_push(struct fbr_mq *mq); void *fbr_mq_pop(struct fbr_mq *mq); int fbr_mq_try_pop(struct fbr_mq *mq, void **obj); void fbr_mq_wait_pop(struct fbr_mq *mq); void fbr_mq_clear(struct fbr_mq *mq, int wake_up_writers); void fbr_mq_destroy(struct fbr_mq *mq); /** * Gets fiber user data pointer. * @param [in] id fiber id * @returns user data pointer on success, NULL on failure with f_errno set * * This function allows you to retrieve user data pointer. * @see fbr_set_user_data */ void *fbr_get_user_data(FBR_P_ fbr_id_t id); /** * Sets fiber user data pointer. * @param [in] id fiber id * @param [in] data pointer to user data * @returns 0 on success, -1 upon failure with f_errno set * * This function allows you to extend fiber with some user structure. * @see fbr_get_user_data */ int fbr_set_user_data(FBR_P_ fbr_id_t id, void *data); /** * Implementation of popen() with redirection of all descriptors --- stdin, * stdout and stderr. * @param [in] filename as in execve(2) * @param [in] argv as in execve(2) * @param [in] envp as in execve(2) * @param [in] working_dir if not NULL, child process will be launched with * working directory set to working_dir * @param [in] stdin_w_ptr if not NULL, a new write-only file descriptor mapped * to child STDIN will be written at the provided address * @param [in] stdout_r_ptr if not NULL, a new read-only file descriptor mapped * to child STDOUT will be written at the provided address * @param [in] stderr_r_ptr if not NULL, a new read-only file descriptor mapped * to child STDERR will be written at the provided address * @returns the pid of the launched process or -1 upon error * * If any of the file descriptor pointers are NULLs, fbr_popen3 will use read or * write file descriptor for /dev/null instead. */ pid_t fbr_popen3(FBR_P_ const char *filename, char *const argv[], char *const envp[], const char *working_dir, int *stdin_w_ptr, int *stdout_r_ptr, int *stderr_r_ptr); /** * Convenience wrapper for fbr_popen3() without stderr redirection. * @param [in] filename as in execve(2) * @param [in] argv as in execve(2) * @param [in] envp as in execve(2) * @param [in] working_dir if not NULL, child process will be launched with * working directory set to working_dir * @param [in] stdin_w_ptr if not NULL, a new write-only file descriptor mapped * to child STDIN will be written at the provided address * @param [in] stdout_r_ptr if not NULL, a new read-only file descriptor mapped * to child STDOUT will be written at the provided address * @returns the pid of the launched process or -1 upon error * * If any of the file descriptor pointers are NULLs, fbr_popen3 will use read or * write file descriptor for /dev/null instead. * * @see fbr_popen3 */ static inline pid_t fbr_popen2(FBR_P_ const char *filename, char *const argv[], char *const envp[], const char *working_dir, int *stdin_w_ptr, int *stdout_r_ptr) { return fbr_popen3(FBR_A_ filename, argv, envp, working_dir, stdin_w_ptr, stdout_r_ptr, NULL); } /** * Convenience wrapper for fbr_popen3() without any descriptors being * redirected. * @param [in] filename as in execve(2) * @param [in] argv as in execve(2) * @param [in] envp as in execve(2) * @param [in] working_dir if not NULL, child process will be launched with * working directory set to working_dir * @returns the pid of the launched process or -1 upon error * * @see fbr_popen3 */ static inline pid_t fbr_popen0(FBR_P_ const char *filename, char *const argv[], char *const envp[], const char *working_dir) { return fbr_popen3(FBR_A_ filename, argv, envp, working_dir, NULL, NULL, NULL); } /** * Waits for child process to finish. * @param [in] pid is the PID of the process to wait for * @returns the process exit/trace status caused by rpid (see your systems * waitpid and sys/wait.h documentation for details) * * This function is basically a fiber wrapper for ev_child watcher. It's worth * reading the libev documentation for ev_child to fully understand the * limitations. */ int fbr_waitpid(FBR_P_ pid_t pid); int fbr_system(FBR_P_ const char *filename, char *const argv[], char *const envp[], const char *working_dir); #ifdef __cplusplus } #endif #endif
Lupus/libevfibers
include/evfibers/eio.h
<gh_stars>100-1000 /******************************************************************** Copyright 2013 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ********************************************************************/ #ifndef _FBR_EIO_H_ #define _FBR_EIO_H_ /** * @file evfibers/eio.h * This file contains API for libeio fiber wrappers. * * Wrapper functions are not documented as they clone the libeio prototypes and * their documenting would result in useless copy'n'paste here. libeio * documentation can be used as a reference on this functions. The only * difference is that first argument in the wrappers is always fiber context, * and eio_cb and data pointer are passed internally, and so are not present in * the prototypes. */ #ifdef __cplusplus extern "C" { #endif #include <evfibers/config.h> #ifndef FBR_EIO_ENABLED # error "This build of libevfibers lacks support for libeio" #endif #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/statvfs.h> #ifdef FBR_USE_EMBEDDED_EIO #include <evfibers/libeio_embedded.h> #else #include <eio.h> #endif #include <evfibers/fiber.h> /** * eio custom callback function type. */ typedef eio_ssize_t (*fbr_eio_custom_func_t)(void *data); /** * eio event. * * This event struct can represent an eio event. * @see fbr_ev_upcast * @see fbr_ev_wait */ struct fbr_ev_eio { eio_req *req; /*!< the libeio request itself */ fbr_eio_custom_func_t custom_func; void *custom_arg; struct fbr_ev_base ev_base; }; /** * Initializer for eio event. * * This functions properly initializes fbr_ev_eio struct. You should not do * it manually. * @see fbr_ev_eio * @see fbr_ev_wait */ void fbr_ev_eio_init(FBR_P_ struct fbr_ev_eio *ev, eio_req *req); /** * Initialization routine for libeio fiber wrapper. * * This functions initializes libeio and sets up the necessary glue code to * interact with libev (and in turn libevfibers). * * Must be called only once, uses EV_DEFAULT event loop internally, but any * fiber scheduler can interact with libeio independently. * @see fbr_ev_eio * @see fbr_ev_wait */ void fbr_eio_init(); int fbr_eio_open(FBR_P_ const char *path, int flags, mode_t mode, int pri); int fbr_eio_truncate(FBR_P_ const char *path, off_t offset, int pri); int fbr_eio_chown(FBR_P_ const char *path, uid_t uid, gid_t gid, int pri); int fbr_eio_chmod(FBR_P_ const char *path, mode_t mode, int pri); int fbr_eio_mkdir(FBR_P_ const char *path, mode_t mode, int pri); int fbr_eio_rmdir(FBR_P_ const char *path, int pri); int fbr_eio_unlink(FBR_P_ const char *path, int pri); int fbr_eio_utime(FBR_P_ const char *path, eio_tstamp atime, eio_tstamp mtime, int pri); int fbr_eio_mknod(FBR_P_ const char *path, mode_t mode, dev_t dev, int pri); int fbr_eio_link(FBR_P_ const char *path, const char *new_path, int pri); int fbr_eio_symlink(FBR_P_ const char *path, const char *new_path, int pri); int fbr_eio_rename(FBR_P_ const char *path, const char *new_path, int pri); int fbr_eio_mlock(FBR_P_ void *addr, size_t length, int pri); int fbr_eio_close(FBR_P_ int fd, int pri); int fbr_eio_sync(FBR_P_ int pri); int fbr_eio_fsync(FBR_P_ int fd, int pri); int fbr_eio_fdatasync(FBR_P_ int fd, int pri); int fbr_eio_futime(FBR_P_ int fd, eio_tstamp atime, eio_tstamp mtime, int pri); int fbr_eio_ftruncate(FBR_P_ int fd, off_t offset, int pri); int fbr_eio_fchmod(FBR_P_ int fd, mode_t mode, int pri); int fbr_eio_fchown(FBR_P_ int fd, uid_t uid, gid_t gid, int pri); int fbr_eio_dup2(FBR_P_ int fd, int fd2, int pri); ssize_t fbr_eio_seek(FBR_P_ int fd, off_t offset, int whence, int pri); ssize_t fbr_eio_read(FBR_P_ int fd, void *buf, size_t length, off_t offset, int pri); ssize_t fbr_eio_write(FBR_P_ int fd, void *buf, size_t length, off_t offset, int pri); int fbr_eio_mlockall(FBR_P_ int flags, int pri); int fbr_eio_msync(FBR_P_ void *addr, size_t length, int flags, int pri); int fbr_eio_readlink(FBR_P_ const char *path, char *buf, size_t size, int pri); int fbr_eio_realpath(FBR_P_ const char *path, char *buf, size_t size, int pri); int fbr_eio_stat(FBR_P_ const char *path, EIO_STRUCT_STAT *statdata, int pri); int fbr_eio_lstat(FBR_P_ const char *path, EIO_STRUCT_STAT *statdata, int pri); int fbr_eio_fstat(FBR_P_ int fd, EIO_STRUCT_STAT *statdata, int pri); int fbr_eio_statvfs(FBR_P_ const char *path, EIO_STRUCT_STATVFS *statdata, int pri); int fbr_eio_fstatvfs(FBR_P_ int fd, EIO_STRUCT_STATVFS *statdata, int pri); int fbr_eio_readahead(FBR_P_ int fd, off_t offset, size_t length, int pri); int fbr_eio_sendfile(FBR_P_ int out_fd, int in_fd, off_t in_offset, size_t length, int pri); int fbr_eio_readahead(FBR_P_ int fd, off_t offset, size_t length, int pri); int fbr_eio_syncfs(FBR_P_ int fd, int pri); int fbr_eio_sync_file_range(FBR_P_ int fd, off_t offset, size_t nbytes, unsigned int flags, int pri); int fbr_eio_fallocate(FBR_P_ int fd, int mode, off_t offset, off_t len, int pri); eio_ssize_t fbr_eio_custom(FBR_P_ fbr_eio_custom_func_t func, void *data, int pri); #ifdef __cplusplus } #endif #endif
Lupus/libevfibers
bench/condvar.c
/******************************************************************** Copyright 2013 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ********************************************************************/ #include <stdio.h> #include <string.h> #include <limits.h> #include <sys/stat.h> #include <unistd.h> #include <ev.h> #include <errno.h> #include <evfibers_private/fiber.h> struct fiber_arg { struct fbr_mutex mutex1; struct fbr_cond_var cond1; int cond1_set; struct fbr_mutex mutex2; struct fbr_cond_var cond2; int cond2_set; size_t count; }; static void cond_fiber1(FBR_P_ void *_arg) { struct fiber_arg *arg = _arg; for (;;) { arg->cond1_set = 1; fbr_cond_signal(FBR_A_ &arg->cond1); while (0 == arg->cond2_set) { fbr_mutex_lock(FBR_A_ &arg->mutex2); fbr_cond_wait(FBR_A_ &arg->cond2, &arg->mutex2); fbr_mutex_unlock(FBR_A_ &arg->mutex2); } arg->cond2_set = 0; arg->count++; } } static void cond_fiber2(FBR_P_ void *_arg) { struct fiber_arg *arg = _arg; for (;;) { arg->cond2_set = 1; fbr_cond_signal(FBR_A_ &arg->cond2); while (0 == arg->cond1_set) { fbr_mutex_lock(FBR_A_ &arg->mutex1); fbr_cond_wait(FBR_A_ &arg->cond1, &arg->mutex1); fbr_mutex_unlock(FBR_A_ &arg->mutex1); } arg->cond1_set = 0; arg->count++; } } static void stats_fiber(FBR_P_ void *_arg) { struct fiber_arg *arg = _arg; size_t last; size_t diff; int count = 0; int max_samples = 100; for (;;) { last = arg->count; fbr_sleep(FBR_A_ 1.0); diff = arg->count - last; printf("%zd\n", diff); if (count++ > max_samples) { ev_break(fctx->__p->loop, EVBREAK_ALL); } } } int main() { struct fbr_context context; fbr_id_t fiber1, fiber2, fiber_stats; int retval; (void)retval; struct fiber_arg arg = { .count = 0 }; fbr_init(&context, EV_DEFAULT); fbr_mutex_init(&context, &arg.mutex1); fbr_mutex_init(&context, &arg.mutex2); fbr_cond_init(&context, &arg.cond1); fbr_cond_init(&context, &arg.cond2); fiber1 = fbr_create(&context, "fiber1", cond_fiber1, &arg, 0); assert(!fbr_id_isnull(fiber1)); retval = fbr_transfer(&context, fiber1); assert(0 == retval); fiber2 = fbr_create(&context, "fiber2", cond_fiber2, &arg, 0); assert(!fbr_id_isnull(fiber2)); retval = fbr_transfer(&context, fiber2); assert(0 == retval); fiber_stats = fbr_create(&context, "fiber_stats", stats_fiber, &arg, 0); assert(!fbr_id_isnull(fiber_stats)); retval = fbr_transfer(&context, fiber_stats); assert(0 == retval); ev_run(EV_DEFAULT, 0); fbr_cond_destroy(&context, &arg.cond1); fbr_cond_destroy(&context, &arg.cond2); fbr_mutex_destroy(&context, &arg.mutex1); fbr_mutex_destroy(&context, &arg.mutex2); fbr_destroy(&context); return 0; }
Lupus/libevfibers
src/fiber.c
/******************************************************************** Copyright 2013 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ********************************************************************/ #include <evfibers/config.h> #include <sys/mman.h> #include <fcntl.h> #include <libgen.h> #include <assert.h> #include <errno.h> #include <stdio.h> #include <string.h> #include <strings.h> #include <err.h> #ifdef HAVE_VALGRIND_H #include <valgrind/valgrind.h> #else #define RUNNING_ON_VALGRIND (0) #define VALGRIND_STACK_REGISTER(a,b) (void)0 #endif #ifdef FBR_EIO_ENABLED #include <evfibers/eio.h> #endif #include <evfibers_private/fiber.h> #ifndef LIST_FOREACH_SAFE #define LIST_FOREACH_SAFE(var, head, field, next_var) \ for ((var) = ((head)->lh_first); \ (var) && ((next_var) = ((var)->field.le_next), 1); \ (var) = (next_var)) #endif #ifndef TAILQ_FOREACH_SAFE #define TAILQ_FOREACH_SAFE(var, head, field, next_var) \ for ((var) = ((head)->tqh_first); \ (var) ? ({ (next_var) = ((var)->field.tqe_next); 1; }) \ : 0; \ (var) = (next_var)) #endif #define ENSURE_ROOT_FIBER do { \ assert(fctx->__p->sp->fiber == &fctx->__p->root); \ } while (0) #define CURRENT_FIBER (fctx->__p->sp->fiber) #define CURRENT_FIBER_ID (fbr_id_pack(CURRENT_FIBER)) #define CALLED_BY_ROOT ((fctx->__p->sp - 1)->fiber == &fctx->__p->root) #define unpack_transfer_errno(value, ptr, id) \ do { \ if (-1 == fbr_id_unpack(fctx, ptr, id)) \ return (value); \ } while (0) #define return_success(value) \ do { \ fctx->f_errno = FBR_SUCCESS; \ return (value); \ } while (0) #define return_error(value, code) \ do { \ fctx->f_errno = (code); \ return (value); \ } while (0) const fbr_id_t FBR_ID_NULL = {0, NULL}; static const char default_buffer_pattern[] = "/dev/shm/fbr_buffer.XXXXXXXXX"; static fbr_id_t fbr_id_pack(struct fbr_fiber *fiber) { return (struct fbr_id_s){.g = fiber->id, .p = fiber}; } static int fbr_id_unpack(FBR_P_ struct fbr_fiber **ptr, fbr_id_t id) { struct fbr_fiber *fiber = id.p; if (fiber->id != id.g) return_error(-1, FBR_ENOFIBER); if (ptr) *ptr = id.p; return 0; } static void pending_async_cb(EV_P_ ev_async *w, _unused_ int revents) { struct fbr_context *fctx; struct fbr_id_tailq_i *item; fctx = (struct fbr_context *)w->data; int retval; ENSURE_ROOT_FIBER; if (TAILQ_EMPTY(&fctx->__p->pending_fibers)) { ev_async_stop(EV_A_ &fctx->__p->pending_async); return; } item = TAILQ_FIRST(&fctx->__p->pending_fibers); assert(item->head == &fctx->__p->pending_fibers); /* item shall be removed from the queue by a destructor, which shall be * set by the procedure demanding delayed execution. Destructor * guarantees removal upon the reclaim of fiber. */ ev_async_send(EV_A_ &fctx->__p->pending_async); retval = fbr_transfer(FBR_A_ item->id); if (-1 == retval && FBR_ENOFIBER != fctx->f_errno) { fbr_log_e(FBR_A_ "libevfibers: unexpected error trying to call" " a fiber by id: %s", fbr_strerror(FBR_A_ fctx->f_errno)); } } static void *allocate_in_fiber(FBR_P_ size_t size, struct fbr_fiber *in) { struct mem_pool *pool_entry; pool_entry = malloc(size + sizeof(struct mem_pool)); if (NULL == pool_entry) { fbr_log_e(FBR_A_ "libevfibers: unable to allocate %zu bytes\n", size + sizeof(struct mem_pool)); abort(); } pool_entry->ptr = pool_entry; pool_entry->destructor = NULL; pool_entry->destructor_context = NULL; LIST_INSERT_HEAD(&in->pool, pool_entry, entries); return pool_entry + 1; } static void stdio_logger(FBR_P_ struct fbr_logger *logger, enum fbr_log_level level, const char *format, va_list ap) { struct fbr_fiber *fiber; FILE* stream; char *str_level; ev_tstamp tstamp; if (level > logger->level) return; fiber = CURRENT_FIBER; switch (level) { case FBR_LOG_ERROR: str_level = "ERROR"; stream = stderr; break; case FBR_LOG_WARNING: str_level = "WARNING"; stream = stdout; break; case FBR_LOG_NOTICE: str_level = "NOTICE"; stream = stdout; break; case FBR_LOG_INFO: str_level = "INFO"; stream = stdout; break; case FBR_LOG_DEBUG: str_level = "DEBUG"; stream = stdout; break; default: str_level = "?????"; stream = stdout; break; } tstamp = ev_now(fctx->__p->loop); fprintf(stream, "%.6f %-7s %-16s ", tstamp, str_level, fiber->name); vfprintf(stream, format, ap); fprintf(stream, "\n"); } void fbr_init(FBR_P_ struct ev_loop *loop) { struct fbr_fiber *root; struct fbr_logger *logger; char *buffer_pattern; fctx->__p = malloc(sizeof(struct fbr_context_private)); LIST_INIT(&fctx->__p->reclaimed); LIST_INIT(&fctx->__p->root.children); LIST_INIT(&fctx->__p->root.pool); TAILQ_INIT(&fctx->__p->root.destructors); TAILQ_INIT(&fctx->__p->pending_fibers); root = &fctx->__p->root; strncpy(root->name, "root", FBR_MAX_FIBER_NAME - 1); fctx->__p->last_id = 0; root->id = fctx->__p->last_id++; coro_create(&root->ctx, NULL, NULL, NULL, 0); logger = allocate_in_fiber(FBR_A_ sizeof(struct fbr_logger), root); logger->logv = stdio_logger; logger->level = FBR_LOG_NOTICE; fctx->logger = logger; fctx->__p->sp = fctx->__p->stack; fctx->__p->sp->fiber = root; fctx->__p->backtraces_enabled = 1; fill_trace_info(FBR_A_ &fctx->__p->sp->tinfo); fctx->__p->loop = loop; fctx->__p->pending_async.data = fctx; fctx->__p->backtraces_enabled = 0; memset(&fctx->__p->key_free_mask, 0xFF, sizeof(fctx->__p->key_free_mask)); ev_async_init(&fctx->__p->pending_async, pending_async_cb); buffer_pattern = getenv("FBR_BUFFER_FILE_PATTERN"); if (buffer_pattern) fctx->__p->buffer_file_pattern = buffer_pattern; else fctx->__p->buffer_file_pattern = default_buffer_pattern; } const char *fbr_strerror(_unused_ FBR_P_ enum fbr_error_code code) { switch (code) { case FBR_SUCCESS: return "Success"; case FBR_EINVAL: return "Invalid argument"; case FBR_ENOFIBER: return "No such fiber"; case FBR_ESYSTEM: return "System error, consult system errno"; case FBR_EBUFFERMMAP: return "Failed to mmap two adjacent regions"; case FBR_ENOKEY: return "Fiber-local key does not exist"; case FBR_EPROTOBUF: return "Protobuf unpacking error"; case FBR_EBUFFERNOSPACE: return "Not enough space in the buffer"; case FBR_EEIO: return "libeio request error"; } return "Unknown error"; } void fbr_log_e(FBR_P_ const char *format, ...) { va_list ap; va_start(ap, format); (*fctx->logger->logv)(FBR_A_ fctx->logger, FBR_LOG_ERROR, format, ap); va_end(ap); } void fbr_log_w(FBR_P_ const char *format, ...) { va_list ap; va_start(ap, format); (*fctx->logger->logv)(FBR_A_ fctx->logger, FBR_LOG_WARNING, format, ap); va_end(ap); } void fbr_log_n(FBR_P_ const char *format, ...) { va_list ap; va_start(ap, format); (*fctx->logger->logv)(FBR_A_ fctx->logger, FBR_LOG_NOTICE, format, ap); va_end(ap); } void fbr_log_i(FBR_P_ const char *format, ...) { va_list ap; va_start(ap, format); (*fctx->logger->logv)(FBR_A_ fctx->logger, FBR_LOG_INFO, format, ap); va_end(ap); } void fbr_log_d(FBR_P_ const char *format, ...) { va_list ap; va_start(ap, format); (*fctx->logger->logv)(FBR_A_ fctx->logger, FBR_LOG_DEBUG, format, ap); va_end(ap); } void id_tailq_i_set(_unused_ FBR_P_ struct fbr_id_tailq_i *item, struct fbr_fiber *fiber) { item->id = fbr_id_pack(fiber); item->ev = NULL; } static void reclaim_children(FBR_P_ struct fbr_fiber *fiber) { struct fbr_fiber *f; LIST_FOREACH(f, &fiber->children, entries.children) { fbr_reclaim(FBR_A_ fbr_id_pack(f)); } } static void fbr_free_in_fiber(_unused_ FBR_P_ _unused_ struct fbr_fiber *fiber, void *ptr, int destructor); void fbr_destroy(FBR_P) { struct fbr_fiber *fiber, *x; struct mem_pool *p, *x2; reclaim_children(FBR_A_ &fctx->__p->root); LIST_FOREACH_SAFE(p, &fctx->__p->root.pool, entries, x2) { fbr_free_in_fiber(FBR_A_ &fctx->__p->root, p + 1, 1); } LIST_FOREACH_SAFE(fiber, &fctx->__p->reclaimed, entries.reclaimed, x) { free(fiber->stack); free(fiber); } free(fctx->__p); } void fbr_enable_backtraces(FBR_P_ int enabled) { if (enabled) fctx->__p->backtraces_enabled = 1; else fctx->__p->backtraces_enabled = 0; } static void cancel_ev(_unused_ FBR_P_ struct fbr_ev_base *ev) { fbr_destructor_remove(FBR_A_ &ev->item.dtor, 1 /* call it */); } static void post_ev(_unused_ FBR_P_ struct fbr_fiber *fiber, struct fbr_ev_base *ev) { assert(NULL != fiber->ev.waiting); fiber->ev.arrived = 1; ev->arrived = 1; } /* This callback should't be called if watcher has been stopped properly */ static void ev_abort_cb(_unused_ EV_P_ ev_watcher *w, _unused_ int event) { (void)event; fprintf(stderr, "libevfibers: libev callback called for pending " "watcher (%p), which is no longer being awaited via " "fbr_ev_wait()", w); abort(); } static void ev_watcher_cb(_unused_ EV_P_ ev_watcher *w, _unused_ int event) { struct fbr_fiber *fiber; struct fbr_ev_watcher *ev = w->data; struct fbr_context *fctx = ev->ev_base.fctx; int retval; ENSURE_ROOT_FIBER; retval = fbr_id_unpack(FBR_A_ &fiber, ev->ev_base.id); if (-1 == retval) { fbr_log_e(FBR_A_ "libevfibers: fiber is about to be called by" " the watcher callback, but it's id is not valid: %s", fbr_strerror(FBR_A_ fctx->f_errno)); abort(); } post_ev(FBR_A_ fiber, &ev->ev_base); retval = fbr_transfer(FBR_A_ fbr_id_pack(fiber)); assert(0 == retval); } static void fbr_free_in_fiber(_unused_ FBR_P_ _unused_ struct fbr_fiber *fiber, void *ptr, int destructor) { struct mem_pool *pool_entry = NULL; if (NULL == ptr) return; pool_entry = (struct mem_pool *)ptr - 1; if (pool_entry->ptr != pool_entry) { fbr_log_e(FBR_A_ "libevfibers: address %p does not look like " "fiber memory pool entry", ptr); if (!RUNNING_ON_VALGRIND) abort(); } LIST_REMOVE(pool_entry, entries); if (destructor && pool_entry->destructor) pool_entry->destructor(FBR_A_ ptr, pool_entry->destructor_context); free(pool_entry); } static void fiber_cleanup(FBR_P_ struct fbr_fiber *fiber) { struct mem_pool *p, *x; struct fbr_destructor *dtor; /* coro_destroy(&fiber->ctx); */ LIST_REMOVE(fiber, entries.children); TAILQ_FOREACH(dtor, &fiber->destructors, entries) { dtor->func(FBR_A_ dtor->arg); } LIST_FOREACH_SAFE(p, &fiber->pool, entries, x) { fbr_free_in_fiber(FBR_A_ fiber, p + 1, 1); } } static void filter_fiber_stack(FBR_P_ struct fbr_fiber *fiber) { struct fbr_stack_item *sp; for (sp = fctx->__p->stack; sp < fctx->__p->sp; sp++) { if (sp->fiber == fiber) { memmove(sp, sp + 1, (fctx->__p->sp - sp) * sizeof(*sp)); fctx->__p->sp--; } } } static int do_reclaim(FBR_P_ struct fbr_fiber *fiber) { #if 0 struct fbr_fiber *f; #endif fill_trace_info(FBR_A_ &fiber->reclaim_tinfo); reclaim_children(FBR_A_ fiber); fiber_cleanup(FBR_A_ fiber); fiber->id = fctx->__p->last_id++; #if 0 LIST_FOREACH(f, &fctx->__p->reclaimed, entries.reclaimed) { assert(f != fiber); } #endif LIST_INSERT_HEAD(&fctx->__p->reclaimed, fiber, entries.reclaimed); filter_fiber_stack(FBR_A_ fiber); if (CURRENT_FIBER == fiber) fbr_yield(FBR_A); return_success(0); } int fbr_reclaim(FBR_P_ fbr_id_t id) { struct fbr_fiber *fiber; struct fbr_mutex mutex; int retval; unpack_transfer_errno(-1, &fiber, id); fbr_mutex_init(FBR_A_ &mutex); fbr_mutex_lock(FBR_A_ &mutex); while (fiber->no_reclaim > 0) { fiber->want_reclaim = 1; assert("Attempt to reclaim self while no_reclaim is set would" " block forever" && fiber != CURRENT_FIBER); if (-1 == fbr_id_unpack(FBR_A_ NULL, id) && FBR_ENOFIBER == fctx->f_errno) return_success(0); retval = fbr_cond_wait(FBR_A_ &fiber->reclaim_cond, &mutex); assert(0 == retval); (void)retval; } fbr_mutex_unlock(FBR_A_ &mutex); fbr_mutex_destroy(FBR_A_ &mutex); if (-1 == fbr_id_unpack(FBR_A_ NULL, id) && FBR_ENOFIBER == fctx->f_errno) return_success(0); return do_reclaim(FBR_A_ fiber); } int fbr_set_reclaim(FBR_P_ fbr_id_t id) { struct fbr_fiber *fiber; unpack_transfer_errno(-1, &fiber, id); fiber->no_reclaim--; if (0 == fiber->no_reclaim) fbr_cond_broadcast(FBR_A_ &fiber->reclaim_cond); return_success(0); } int fbr_set_noreclaim(FBR_P_ fbr_id_t id) { struct fbr_fiber *fiber; unpack_transfer_errno(-1, &fiber, id); fiber->no_reclaim++; return_success(0); } int fbr_want_reclaim(FBR_P_ fbr_id_t id) { struct fbr_fiber *fiber; unpack_transfer_errno(-1, &fiber, id); if (fiber->no_reclaim > 0) /* If we're in noreclaim block of any depth, always return 0 */ return 0; return_success(fiber->want_reclaim); } int fbr_is_reclaimed(_unused_ FBR_P_ fbr_id_t id) { if (0 == fbr_id_unpack(FBR_A_ NULL, id)) return 0; return 1; } fbr_id_t fbr_self(FBR_P) { return CURRENT_FIBER_ID; } static int do_reclaim(FBR_P_ struct fbr_fiber *fiber); static void call_wrapper(FBR_P) { int retval; struct fbr_fiber *fiber = CURRENT_FIBER; fiber->func(FBR_A_ fiber->func_arg); retval = do_reclaim(FBR_A_ fiber); assert(0 == retval); (void)retval; fbr_yield(FBR_A); assert(NULL); } enum ev_action_hint { EV_AH_OK = 0, EV_AH_ARRIVED, EV_AH_EINVAL }; static void item_dtor(_unused_ FBR_P_ void *arg) { struct fbr_id_tailq_i *item = arg; if (item->head) { TAILQ_REMOVE(item->head, item, entries); } } static enum ev_action_hint prepare_ev(FBR_P_ struct fbr_ev_base *ev) { struct fbr_ev_watcher *e_watcher; struct fbr_ev_mutex *e_mutex; struct fbr_ev_cond_var *e_cond; struct fbr_id_tailq_i *item = &ev->item; ev->arrived = 0; ev->item.dtor.func = item_dtor; ev->item.dtor.arg = item; fbr_destructor_add(FBR_A_ &ev->item.dtor); switch (ev->type) { case FBR_EV_WATCHER: e_watcher = fbr_ev_upcast(ev, fbr_ev_watcher); if (!ev_is_active(e_watcher->w)) { fbr_destructor_remove(FBR_A_ &ev->item.dtor, 0 /* call it */); return EV_AH_EINVAL; } e_watcher->w->data = e_watcher; ev_set_cb(e_watcher->w, ev_watcher_cb); break; case FBR_EV_MUTEX: e_mutex = fbr_ev_upcast(ev, fbr_ev_mutex); if (fbr_id_isnull(e_mutex->mutex->locked_by)) { e_mutex->mutex->locked_by = CURRENT_FIBER_ID; return EV_AH_ARRIVED; } id_tailq_i_set(FBR_A_ item, CURRENT_FIBER); item->ev = ev; ev->data = item; TAILQ_INSERT_TAIL(&e_mutex->mutex->pending, item, entries); item->head = &e_mutex->mutex->pending; break; case FBR_EV_COND_VAR: e_cond = fbr_ev_upcast(ev, fbr_ev_cond_var); if (e_cond->mutex && fbr_id_isnull(e_cond->mutex->locked_by)) { fbr_destructor_remove(FBR_A_ &ev->item.dtor, 0 /* call it */); return EV_AH_EINVAL; } id_tailq_i_set(FBR_A_ item, CURRENT_FIBER); item->ev = ev; ev->data = item; TAILQ_INSERT_TAIL(&e_cond->cond->waiting, item, entries); item->head = &e_cond->cond->waiting; if (e_cond->mutex) fbr_mutex_unlock(FBR_A_ e_cond->mutex); break; case FBR_EV_EIO: #ifdef FBR_EIO_ENABLED /* NOP */ #else fbr_log_e(FBR_A_ "libevfibers: libeio support is not compiled"); abort(); #endif break; } return EV_AH_OK; } static void finish_ev(FBR_P_ struct fbr_ev_base *ev) { struct fbr_ev_cond_var *e_cond; struct fbr_ev_watcher *e_watcher; fbr_destructor_remove(FBR_A_ &ev->item.dtor, 1 /* call it */); switch (ev->type) { case FBR_EV_COND_VAR: e_cond = fbr_ev_upcast(ev, fbr_ev_cond_var); if (e_cond->mutex) fbr_mutex_lock(FBR_A_ e_cond->mutex); break; case FBR_EV_WATCHER: e_watcher = fbr_ev_upcast(ev, fbr_ev_watcher); ev_set_cb(e_watcher->w, ev_abort_cb); break; case FBR_EV_MUTEX: /* NOP */ break; case FBR_EV_EIO: #ifdef FBR_EIO_ENABLED /* NOP */ #else fbr_log_e(FBR_A_ "libevfibers: libeio support is not compiled"); abort(); #endif break; } } static void watcher_timer_dtor(_unused_ FBR_P_ void *_arg) { struct ev_timer *w = _arg; ev_timer_stop(fctx->__p->loop, w); } int fbr_ev_wait_to(FBR_P_ struct fbr_ev_base *events[], ev_tstamp timeout) { size_t size; ev_timer timer; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; struct fbr_ev_base **new_events; struct fbr_ev_base **ev_pptr; int n_events; ev_timer_init(&timer, NULL, timeout, 0.); ev_timer_start(fctx->__p->loop, &timer); fbr_ev_watcher_init(FBR_A_ &watcher, (struct ev_watcher *)&timer); dtor.func = watcher_timer_dtor; dtor.arg = &timer; fbr_destructor_add(FBR_A_ &dtor); size = 0; for (ev_pptr = events; NULL != *ev_pptr; ev_pptr++) size++; new_events = alloca((size + 2) * sizeof(void *)); memcpy(new_events, events, size * sizeof(void *)); new_events[size] = &watcher.ev_base; new_events[size + 1] = NULL; n_events = fbr_ev_wait(FBR_A_ new_events); fbr_destructor_remove(FBR_A_ &dtor, 1 /* Call it? */); if (n_events < 0) return n_events; if (watcher.ev_base.arrived) n_events--; return n_events; } int fbr_ev_wait(FBR_P_ struct fbr_ev_base *events[]) { struct fbr_fiber *fiber = CURRENT_FIBER; enum ev_action_hint hint; int num = 0; int i; fiber->ev.arrived = 0; fiber->ev.waiting = events; for (i = 0; NULL != events[i]; i++) { hint = prepare_ev(FBR_A_ events[i]); switch (hint) { case EV_AH_OK: break; case EV_AH_ARRIVED: fiber->ev.arrived = 1; events[i]->arrived = 1; break; case EV_AH_EINVAL: return_error(-1, FBR_EINVAL); } } while (0 == fiber->ev.arrived) fbr_yield(FBR_A); for (i = 0; NULL != events[i]; i++) { if (events[i]->arrived) { num++; finish_ev(FBR_A_ events[i]); } else cancel_ev(FBR_A_ events[i]); } return_success(num); } int fbr_ev_wait_one(FBR_P_ struct fbr_ev_base *one) { struct fbr_fiber *fiber = CURRENT_FIBER; enum ev_action_hint hint; struct fbr_ev_base *events[] = {one, NULL}; fiber->ev.arrived = 0; fiber->ev.waiting = events; hint = prepare_ev(FBR_A_ one); switch (hint) { case EV_AH_OK: break; case EV_AH_ARRIVED: goto finish; case EV_AH_EINVAL: return_error(-1, FBR_EINVAL); } while (0 == fiber->ev.arrived) fbr_yield(FBR_A); finish: finish_ev(FBR_A_ one); return 0; } int fbr_ev_wait_one_wto(FBR_P_ struct fbr_ev_base *one, ev_tstamp timeout) { int n_events; struct fbr_ev_base *events[] = {one, NULL, NULL}; ev_timer timer; struct fbr_ev_watcher twatcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_timer_init(&timer, NULL, timeout, 0.); ev_timer_start(fctx->__p->loop, &timer); fbr_ev_watcher_init(FBR_A_ &twatcher, (struct ev_watcher *)&timer); dtor.func = watcher_timer_dtor; dtor.arg = &timer; fbr_destructor_add(FBR_A_ &dtor); events[1] = &twatcher.ev_base; n_events = fbr_ev_wait(FBR_A_ events); fbr_destructor_remove(FBR_A_ &dtor, 1 /* Call it? */); if (n_events > 0 && events[0]->arrived) return 0; errno = ETIMEDOUT; return -1; } int fbr_transfer(FBR_P_ fbr_id_t to) { struct fbr_fiber *callee; struct fbr_fiber *caller = fctx->__p->sp->fiber; unpack_transfer_errno(-1, &callee, to); fctx->__p->sp++; fctx->__p->sp->fiber = callee; fill_trace_info(FBR_A_ &fctx->__p->sp->tinfo); coro_transfer(&caller->ctx, &callee->ctx); return_success(0); } void fbr_yield(FBR_P) { struct fbr_fiber *callee; struct fbr_fiber *caller; assert("Attempt to yield in a root fiber" && fctx->__p->sp->fiber != &fctx->__p->root); callee = fctx->__p->sp->fiber; caller = (--fctx->__p->sp)->fiber; coro_transfer(&callee->ctx, &caller->ctx); } int fbr_fd_nonblock(FBR_P_ int fd) { int flags, s; flags = fcntl(fd, F_GETFL, 0); if (flags == -1) return_error(-1, FBR_ESYSTEM); flags |= O_NONBLOCK; s = fcntl(fd, F_SETFL, flags); if (s == -1) return_error(-1, FBR_ESYSTEM); return_success(0); } static void ev_base_init(FBR_P_ struct fbr_ev_base *ev, enum fbr_ev_type type) { memset(ev, 0x00, sizeof(*ev)); ev->type = type; ev->id = CURRENT_FIBER_ID; ev->fctx = fctx; } void fbr_ev_watcher_init(FBR_P_ struct fbr_ev_watcher *ev, ev_watcher *w) { ev_base_init(FBR_A_ &ev->ev_base, FBR_EV_WATCHER); ev->w = w; } static void watcher_io_dtor(_unused_ FBR_P_ void *_arg) { struct ev_io *w = _arg; ev_io_stop(fctx->__p->loop, w); } int fbr_connect(FBR_P_ int sockfd, const struct sockaddr *addr, socklen_t addrlen) { ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; int r; socklen_t len; r = connect(sockfd, addr, addrlen); if ((-1 == r) && (EINPROGRESS != errno)) return -1; ev_io_init(&io, NULL, sockfd, EV_WRITE); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); fbr_ev_wait_one(FBR_A_ &watcher.ev_base); len = sizeof(r); if (-1 == getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&r, &len)) { r = -1; } else if ( 0 != r ) { errno = r; r = -1; } fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return r; } int fbr_connect_wto(FBR_P_ int sockfd, const struct sockaddr *addr, socklen_t addrlen, ev_tstamp timeout) { ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; int r, rc; socklen_t len; r = connect(sockfd, addr, addrlen); if ((-1 == r) && (EINPROGRESS != errno)) return -1; ev_io_init(&io, NULL, sockfd, EV_WRITE); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); rc = fbr_ev_wait_one_wto(FBR_A_ &watcher.ev_base, timeout); if (0 == rc) { len = sizeof(r); if (-1 == getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&r, &len)) { r = -1; } else if ( 0 != r ) { errno = r; r = -1; } } else { r = -1; errno = ETIMEDOUT; } fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return r; } ssize_t fbr_read(FBR_P_ int fd, void *buf, size_t count) { ssize_t r; ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_io_init(&io, NULL, fd, EV_READ); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); fbr_ev_wait_one(FBR_A_ &watcher.ev_base); fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); do { r = read(fd, buf, count); } while (-1 == r && EINTR == errno); ev_io_stop(fctx->__p->loop, &io); return r; } ssize_t fbr_read_wto(FBR_P_ int fd, void *buf, size_t count, ev_tstamp timeout) { ssize_t r = 0; ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; int rc = 0; ev_io_init(&io, NULL, fd, EV_READ); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); rc = fbr_ev_wait_one_wto(FBR_A_ &watcher.ev_base, timeout); fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); if (0 == rc) { do { r = read(fd, buf, count); } while (-1 == r && EINTR == errno); } ev_io_stop(fctx->__p->loop, &io); return r; } ssize_t fbr_read_all(FBR_P_ int fd, void *buf, size_t count) { ssize_t r; size_t done = 0; ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_io_init(&io, NULL, fd, EV_READ); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); while (count != done) { next: fbr_ev_wait_one(FBR_A_ &watcher.ev_base); for (;;) { r = read(fd, buf + done, count - done); if (-1 == r) { switch (errno) { case EINTR: continue; case EAGAIN: goto next; default: goto error; } } break; } if (0 == r) break; done += r; } fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return (ssize_t)done; error: fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return -1; } ssize_t fbr_read_all_wto(FBR_P_ int fd, void *buf, size_t count, ev_tstamp timeout) { ssize_t r; size_t done = 0; ev_io io; struct fbr_ev_watcher watcher, twatcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; struct fbr_destructor dtor2 = FBR_DESTRUCTOR_INITIALIZER; struct fbr_ev_base *events[] = {NULL, NULL, NULL}; ev_timer timer; ev_io_init(&io, NULL, fd, EV_READ); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); events[0] = &watcher.ev_base; ev_timer_init(&timer, NULL, timeout, 0.); ev_timer_start(fctx->__p->loop, &timer); fbr_ev_watcher_init(FBR_A_ &twatcher, (struct ev_watcher *)&timer); dtor2.func = watcher_timer_dtor; dtor2.arg = &timer; fbr_destructor_add(FBR_A_ &dtor2); events[1] = &twatcher.ev_base; while (count != done) { next: fbr_ev_wait(FBR_A_ events); if (events[1]->arrived) goto error; for (;;) { r = read(fd, buf + done, count - done); if (-1 == r) { switch (errno) { case EINTR: continue; case EAGAIN: goto next; default: goto error; } } break; } if (0 == r) break; done += r; } fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); fbr_destructor_remove(FBR_A_ &dtor2, 0 /* Call it? */); ev_timer_stop(fctx->__p->loop, &timer); ev_io_stop(fctx->__p->loop, &io); return (ssize_t)done; error: fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); fbr_destructor_remove(FBR_A_ &dtor2, 0 /* Call it? */); ev_timer_stop(fctx->__p->loop, &timer); ev_io_stop(fctx->__p->loop, &io); return -1; } ssize_t fbr_readline(FBR_P_ int fd, void *buffer, size_t n) { ssize_t num_read; size_t total_read; char *buf; char ch; if (n <= 0 || buffer == NULL) { errno = EINVAL; return -1; } buf = buffer; total_read = 0; for (;;) { num_read = fbr_read(FBR_A_ fd, &ch, 1); if (num_read == -1) { if (errno == EINTR) continue; else return -1; } else if (num_read == 0) { if (total_read == 0) return 0; else break; } else { if (total_read < n - 1) { total_read++; *buf++ = ch; } if (ch == '\n') break; } } *buf = '\0'; return total_read; } ssize_t fbr_write(FBR_P_ int fd, const void *buf, size_t count) { ssize_t r; ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_io_init(&io, NULL, fd, EV_WRITE); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); fbr_ev_wait_one(FBR_A_ &watcher.ev_base); do { r = write(fd, buf, count); } while (-1 == r && EINTR == errno); fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return r; } ssize_t fbr_write_wto(FBR_P_ int fd, const void *buf, size_t count, ev_tstamp timeout) { ssize_t r = 0; int rc; ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_io_init(&io, NULL, fd, EV_WRITE); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); rc = fbr_ev_wait_one_wto(FBR_A_ &watcher.ev_base, timeout); if (0 == rc) { do { r = write(fd, buf, count); } while (-1 == r && EINTR == errno); } fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return r; } ssize_t fbr_write_all(FBR_P_ int fd, const void *buf, size_t count) { ssize_t r; size_t done = 0; ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_io_init(&io, NULL, fd, EV_WRITE); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); while (count != done) { next: fbr_ev_wait_one(FBR_A_ &watcher.ev_base); for (;;) { r = write(fd, buf + done, count - done); if (-1 == r) { switch (errno) { case EINTR: continue; case EAGAIN: goto next; default: goto error; } } break; } done += r; } fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return (ssize_t)done; error: fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return -1; } ssize_t fbr_write_all_wto(FBR_P_ int fd, const void *buf, size_t count, ev_tstamp timeout) { ssize_t r; size_t done = 0; ev_io io; struct fbr_ev_watcher watcher, twatcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; struct fbr_destructor dtor2 = FBR_DESTRUCTOR_INITIALIZER; struct fbr_ev_base *events[] = {NULL, NULL, NULL}; ev_timer timer; ev_io_init(&io, NULL, fd, EV_WRITE); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); events[0] = &watcher.ev_base; ev_timer_init(&timer, NULL, timeout, 0.); ev_timer_start(fctx->__p->loop, &timer); fbr_ev_watcher_init(FBR_A_ &twatcher, (struct ev_watcher *)&timer); dtor2.func = watcher_timer_dtor; dtor2.arg = &timer; fbr_destructor_add(FBR_A_ &dtor2); events[1] = &twatcher.ev_base; while (count != done) { next: fbr_ev_wait(FBR_A_ events); if (events[1]->arrived) { errno = ETIMEDOUT; goto error; } for (;;) { r = write(fd, buf + done, count - done); if (-1 == r) { switch (errno) { case EINTR: continue; case EAGAIN: goto next; default: goto error; } } break; } done += r; } fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); fbr_destructor_remove(FBR_A_ &dtor2, 0 /* Call it? */); ev_timer_stop(fctx->__p->loop, &timer); ev_io_stop(fctx->__p->loop, &io); return (ssize_t)done; error: fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); fbr_destructor_remove(FBR_A_ &dtor2, 0 /* Call it? */); ev_timer_stop(fctx->__p->loop, &timer); ev_io_stop(fctx->__p->loop, &io); return -1; } ssize_t fbr_recvfrom(FBR_P_ int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_io_init(&io, NULL, sockfd, EV_READ); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); fbr_ev_wait_one(FBR_A_ &watcher.ev_base); fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return recvfrom(sockfd, buf, len, flags, src_addr, addrlen); } ssize_t fbr_recv(FBR_P_ int sockfd, void *buf, size_t len, int flags) { ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_io_init(&io, NULL, sockfd, EV_READ); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); fbr_ev_wait_one(FBR_A_ &watcher.ev_base); fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return recv(sockfd, buf, len, flags); } ssize_t fbr_sendto(FBR_P_ int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen) { ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_io_init(&io, NULL, sockfd, EV_WRITE); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); fbr_ev_wait_one(FBR_A_ &watcher.ev_base); fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return sendto(sockfd, buf, len, flags, dest_addr, addrlen); } ssize_t fbr_send(FBR_P_ int sockfd, const void *buf, size_t len, int flags) { ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_io_init(&io, NULL, sockfd, EV_WRITE); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); fbr_ev_wait_one(FBR_A_ &watcher.ev_base); fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return send(sockfd, buf, len, flags); } int fbr_accept(FBR_P_ int sockfd, struct sockaddr *addr, socklen_t *addrlen) { int r; ev_io io; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_io_init(&io, NULL, sockfd, EV_READ); ev_io_start(fctx->__p->loop, &io); dtor.func = watcher_io_dtor; dtor.arg = &io; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&io); fbr_ev_wait_one(FBR_A_ &watcher.ev_base); do { r = accept(sockfd, addr, addrlen); } while (-1 == r && EINTR == errno); fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_io_stop(fctx->__p->loop, &io); return r; } ev_tstamp fbr_sleep(FBR_P_ ev_tstamp seconds) { ev_timer timer; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_tstamp expected = ev_now(fctx->__p->loop) + seconds; ev_timer_init(&timer, NULL, seconds, 0.); ev_timer_start(fctx->__p->loop, &timer); dtor.func = watcher_timer_dtor; dtor.arg = &timer; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&timer); fbr_ev_wait_one(FBR_A_ &watcher.ev_base); fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_timer_stop(fctx->__p->loop, &timer); return max(0., expected - ev_now(fctx->__p->loop)); } static void watcher_async_dtor(FBR_P_ void *_arg) { struct ev_async *w = _arg; ev_async_stop(fctx->__p->loop, w); } void fbr_async_wait(FBR_P_ ev_async *w) { struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; dtor.func = watcher_async_dtor; dtor.arg = w; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)w); fbr_ev_wait_one(FBR_A_ &watcher.ev_base); fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_async_stop(fctx->__p->loop, w); return; } static unsigned get_page_size() { static unsigned sz; long retval; if (sz > 0) return sz; retval = sysconf(_SC_PAGESIZE); if (0 > retval) { fprintf(stderr, "libevfibers: sysconf(_SC_PAGESIZE): %s", strerror(errno)); abort(); } sz = retval; return sz; } static size_t round_up_to_page_size(size_t size) { unsigned sz = get_page_size(); size_t remainder; remainder = size % sz; if (remainder == 0) return size; return size + sz - remainder; } fbr_id_t fbr_create(FBR_P_ const char *name, fbr_fiber_func_t func, void *arg, size_t stack_size) { struct fbr_fiber *fiber; if (!LIST_EMPTY(&fctx->__p->reclaimed)) { fiber = LIST_FIRST(&fctx->__p->reclaimed); LIST_REMOVE(fiber, entries.reclaimed); } else { fiber = malloc(sizeof(struct fbr_fiber)); memset(fiber, 0x00, sizeof(struct fbr_fiber)); if (0 == stack_size) stack_size = FBR_STACK_SIZE; stack_size = round_up_to_page_size(stack_size); fiber->stack = malloc(stack_size); if (NULL == fiber->stack) err(EXIT_FAILURE, "malloc failed"); fiber->stack_size = stack_size; (void)VALGRIND_STACK_REGISTER(fiber->stack, fiber->stack + stack_size); fbr_cond_init(FBR_A_ &fiber->reclaim_cond); fiber->id = fctx->__p->last_id++; } coro_create(&fiber->ctx, (coro_func)call_wrapper, FBR_A, fiber->stack, fiber->stack_size); LIST_INIT(&fiber->children); LIST_INIT(&fiber->pool); TAILQ_INIT(&fiber->destructors); strncpy(fiber->name, name, FBR_MAX_FIBER_NAME - 1); fiber->func = func; fiber->func_arg = arg; LIST_INSERT_HEAD(&CURRENT_FIBER->children, fiber, entries.children); fiber->parent = CURRENT_FIBER; fiber->no_reclaim = 0; fiber->want_reclaim = 0; return fbr_id_pack(fiber); } int fbr_disown(FBR_P_ fbr_id_t parent_id) { struct fbr_fiber *fiber, *parent; if (!fbr_id_isnull(parent_id)) unpack_transfer_errno(-1, &parent, parent_id); else parent = &fctx->__p->root; fiber = CURRENT_FIBER; LIST_REMOVE(fiber, entries.children); LIST_INSERT_HEAD(&parent->children, fiber, entries.children); fiber->parent = parent; return_success(0); } fbr_id_t fbr_parent(FBR_P) { struct fbr_fiber *fiber = CURRENT_FIBER; if (fiber->parent == &fctx->__p->root) return FBR_ID_NULL; return fbr_id_pack(fiber->parent); } void *fbr_calloc(FBR_P_ unsigned int nmemb, size_t size) { void *ptr; fprintf(stderr, "libevfibers: fbr_calloc is deprecated\n"); ptr = allocate_in_fiber(FBR_A_ nmemb * size, CURRENT_FIBER); memset(ptr, 0x00, nmemb * size); return ptr; } void *fbr_alloc(FBR_P_ size_t size) { fprintf(stderr, "libevfibers: fbr_alloc is deprecated\n"); return allocate_in_fiber(FBR_A_ size, CURRENT_FIBER); } void fbr_alloc_set_destructor(_unused_ FBR_P_ void *ptr, fbr_alloc_destructor_func_t func, void *context) { struct mem_pool *pool_entry; fprintf(stderr, "libevfibers:" " fbr_alloc_set_destructor is deprecated\n"); pool_entry = (struct mem_pool *)ptr - 1; pool_entry->destructor = func; pool_entry->destructor_context = context; } void fbr_free(FBR_P_ void *ptr) { fprintf(stderr, "libevfibers: fbr_free is deprecated\n"); fbr_free_in_fiber(FBR_A_ CURRENT_FIBER, ptr, 1); } void fbr_free_nd(FBR_P_ void *ptr) { fprintf(stderr, "libevfibers: fbr_free_nd is deprecated\n"); fbr_free_in_fiber(FBR_A_ CURRENT_FIBER, ptr, 0); } void fbr_dump_stack(FBR_P_ fbr_logutil_func_t log) { struct fbr_stack_item *ptr = fctx->__p->sp; (*log)(FBR_A_ "%s", "Fiber call stack:"); (*log)(FBR_A_ "%s", "-------------------------------"); while (ptr >= fctx->__p->stack) { (*log)(FBR_A_ "fiber_call: %p\t%s", ptr->fiber, ptr->fiber->name); print_trace_info(FBR_A_ &ptr->tinfo, log); (*log)(FBR_A_ "%s", "-------------------------------"); ptr--; } } static void transfer_later(FBR_P_ struct fbr_id_tailq_i *item) { int was_empty; was_empty = TAILQ_EMPTY(&fctx->__p->pending_fibers); TAILQ_INSERT_TAIL(&fctx->__p->pending_fibers, item, entries); item->head = &fctx->__p->pending_fibers; if (was_empty && !TAILQ_EMPTY(&fctx->__p->pending_fibers)) { ev_async_start(fctx->__p->loop, &fctx->__p->pending_async); } ev_async_send(fctx->__p->loop, &fctx->__p->pending_async); } static void transfer_later_tailq(FBR_P_ struct fbr_id_tailq *tailq) { int was_empty; struct fbr_id_tailq_i *item; TAILQ_FOREACH(item, tailq, entries) { item->head = &fctx->__p->pending_fibers; } was_empty = TAILQ_EMPTY(&fctx->__p->pending_fibers); TAILQ_CONCAT(&fctx->__p->pending_fibers, tailq, entries); if (was_empty && !TAILQ_EMPTY(&fctx->__p->pending_fibers)) { ev_async_start(fctx->__p->loop, &fctx->__p->pending_async); } ev_async_send(fctx->__p->loop, &fctx->__p->pending_async); } void fbr_ev_mutex_init(FBR_P_ struct fbr_ev_mutex *ev, struct fbr_mutex *mutex) { ev_base_init(FBR_A_ &ev->ev_base, FBR_EV_MUTEX); ev->mutex = mutex; } void fbr_mutex_init(_unused_ FBR_P_ struct fbr_mutex *mutex) { mutex->locked_by = FBR_ID_NULL; TAILQ_INIT(&mutex->pending); } void fbr_mutex_lock(FBR_P_ struct fbr_mutex *mutex) { struct fbr_ev_mutex ev; assert(!fbr_id_eq(mutex->locked_by, CURRENT_FIBER_ID) && "Mutex is already locked by current fiber"); fbr_ev_mutex_init(FBR_A_ &ev, mutex); fbr_ev_wait_one(FBR_A_ &ev.ev_base); assert(fbr_id_eq(mutex->locked_by, CURRENT_FIBER_ID)); } int fbr_mutex_trylock(FBR_P_ struct fbr_mutex *mutex) { if (fbr_id_isnull(mutex->locked_by)) { mutex->locked_by = CURRENT_FIBER_ID; return 1; } return 0; } void fbr_mutex_unlock(FBR_P_ struct fbr_mutex *mutex) { struct fbr_id_tailq_i *item, *x; struct fbr_fiber *fiber = NULL; assert(fbr_id_eq(mutex->locked_by, CURRENT_FIBER_ID) && "Can't unlock the mutex, locked by another fiber"); if (TAILQ_EMPTY(&mutex->pending)) { mutex->locked_by = FBR_ID_NULL; return; } TAILQ_FOREACH_SAFE(item, &mutex->pending, entries, x) { assert(item->head == &mutex->pending); TAILQ_REMOVE(&mutex->pending, item, entries); if (-1 == fbr_id_unpack(FBR_A_ &fiber, item->id)) { fbr_log_e(FBR_A_ "libevfibers: unexpected error trying" " to find a fiber by id: %s", fbr_strerror(FBR_A_ fctx->f_errno)); continue; } break; } mutex->locked_by = item->id; assert(!fbr_id_isnull(mutex->locked_by)); post_ev(FBR_A_ fiber, item->ev); transfer_later(FBR_A_ item); } void fbr_mutex_destroy(_unused_ FBR_P_ _unused_ struct fbr_mutex *mutex) { /* Since mutex is stack allocated now, this efffeectively turns into * NOOP. But we might consider adding some cleanup in the future. */ } void fbr_ev_cond_var_init(FBR_P_ struct fbr_ev_cond_var *ev, struct fbr_cond_var *cond, struct fbr_mutex *mutex) { ev_base_init(FBR_A_ &ev->ev_base, FBR_EV_COND_VAR); ev->cond = cond; ev->mutex = mutex; } void fbr_cond_init(_unused_ FBR_P_ struct fbr_cond_var *cond) { cond->mutex = NULL; TAILQ_INIT(&cond->waiting); } void fbr_cond_destroy(_unused_ FBR_P_ _unused_ struct fbr_cond_var *cond) { /* Since condvar is stack allocated now, this efffeectively turns into * NOOP. But we might consider adding some cleanup in the future. */ } int fbr_cond_wait(FBR_P_ struct fbr_cond_var *cond, struct fbr_mutex *mutex) { struct fbr_ev_cond_var ev; if (mutex && fbr_id_isnull(mutex->locked_by)) return_error(-1, FBR_EINVAL); fbr_ev_cond_var_init(FBR_A_ &ev, cond, mutex); fbr_ev_wait_one(FBR_A_ &ev.ev_base); return_success(0); } void fbr_cond_broadcast(FBR_P_ struct fbr_cond_var *cond) { struct fbr_id_tailq_i *item; struct fbr_fiber *fiber; if (TAILQ_EMPTY(&cond->waiting)) return; TAILQ_FOREACH(item, &cond->waiting, entries) { if(-1 == fbr_id_unpack(FBR_A_ &fiber, item->id)) { assert(FBR_ENOFIBER == fctx->f_errno); continue; } post_ev(FBR_A_ fiber, item->ev); } transfer_later_tailq(FBR_A_ &cond->waiting); } void fbr_cond_signal(FBR_P_ struct fbr_cond_var *cond) { struct fbr_id_tailq_i *item; struct fbr_fiber *fiber; if (TAILQ_EMPTY(&cond->waiting)) return; item = TAILQ_FIRST(&cond->waiting); if(-1 == fbr_id_unpack(FBR_A_ &fiber, item->id)) { assert(FBR_ENOFIBER == fctx->f_errno); return; } post_ev(FBR_A_ fiber, item->ev); assert(item->head == &cond->waiting); TAILQ_REMOVE(&cond->waiting, item, entries); transfer_later(FBR_A_ item); } int fbr_vrb_init(struct fbr_vrb *vrb, size_t size, const char *file_pattern) { int fd = -1; size_t sz = get_page_size(); size = (size ? round_up_to_page_size(size) : sz); void *ptr = MAP_FAILED; char *temp_name = NULL; mode_t old_umask; const mode_t secure_umask = 077; temp_name = strdup(file_pattern); if (!temp_name) return -1; //fctx->__p->vrb_file_pattern); vrb->mem_ptr_size = size * 2 + sz * 2; vrb->mem_ptr = mmap(NULL, vrb->mem_ptr_size, PROT_NONE, FBR_MAP_ANON_FLAG | MAP_PRIVATE, -1, 0); if (MAP_FAILED == vrb->mem_ptr) goto error; vrb->lower_ptr = vrb->mem_ptr + sz; vrb->upper_ptr = vrb->lower_ptr + size; vrb->ptr_size = size; vrb->data_ptr = vrb->lower_ptr; vrb->space_ptr = vrb->lower_ptr; old_umask = umask(0); umask(secure_umask); fd = mkstemp(temp_name); umask(old_umask); if (0 >= fd) goto error; if (0 > unlink(temp_name)) goto error; free(temp_name); temp_name = NULL; if (0 > ftruncate(fd, size)) goto error; ptr = mmap(vrb->lower_ptr, vrb->ptr_size, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED, fd, 0); if (MAP_FAILED == ptr) goto error; if (ptr != vrb->lower_ptr) goto error; ptr = mmap(vrb->upper_ptr, vrb->ptr_size, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_SHARED, fd, 0); if (MAP_FAILED == ptr) goto error; if (ptr != vrb->upper_ptr) goto error; close(fd); return 0; error: if (MAP_FAILED != ptr) munmap(ptr, size); if (0 < fd) close(fd); if (vrb->mem_ptr) munmap(vrb->mem_ptr, vrb->mem_ptr_size); if (temp_name) free(temp_name); return -1; } int fbr_buffer_init(FBR_P_ struct fbr_buffer *buffer, size_t size) { int rv; rv = fbr_vrb_init(&buffer->vrb, size, fctx->__p->buffer_file_pattern); if (rv) return_error(-1, FBR_EBUFFERMMAP); buffer->prepared_bytes = 0; buffer->waiting_bytes = 0; fbr_cond_init(FBR_A_ &buffer->committed_cond); fbr_cond_init(FBR_A_ &buffer->bytes_freed_cond); fbr_mutex_init(FBR_A_ &buffer->write_mutex); fbr_mutex_init(FBR_A_ &buffer->read_mutex); return_success(0); } void fbr_vrb_destroy(struct fbr_vrb *vrb) { munmap(vrb->upper_ptr, vrb->ptr_size); munmap(vrb->lower_ptr, vrb->ptr_size); munmap(vrb->mem_ptr, vrb->mem_ptr_size); } void fbr_buffer_destroy(FBR_P_ struct fbr_buffer *buffer) { fbr_vrb_destroy(&buffer->vrb); fbr_mutex_destroy(FBR_A_ &buffer->read_mutex); fbr_mutex_destroy(FBR_A_ &buffer->write_mutex); fbr_cond_destroy(FBR_A_ &buffer->committed_cond); fbr_cond_destroy(FBR_A_ &buffer->bytes_freed_cond); } void *fbr_buffer_alloc_prepare(FBR_P_ struct fbr_buffer *buffer, size_t size) { if (size > fbr_buffer_size(FBR_A_ buffer)) return_error(NULL, FBR_EINVAL); fbr_mutex_lock(FBR_A_ &buffer->write_mutex); while (buffer->prepared_bytes > 0) fbr_cond_wait(FBR_A_ &buffer->committed_cond, &buffer->write_mutex); assert(0 == buffer->prepared_bytes); buffer->prepared_bytes = size; while (fbr_buffer_free_bytes(FBR_A_ buffer) < size) fbr_cond_wait(FBR_A_ &buffer->bytes_freed_cond, &buffer->write_mutex); return fbr_buffer_space_ptr(FBR_A_ buffer); } void fbr_buffer_alloc_commit(FBR_P_ struct fbr_buffer *buffer) { fbr_vrb_give(&buffer->vrb, buffer->prepared_bytes); buffer->prepared_bytes = 0; fbr_cond_signal(FBR_A_ &buffer->committed_cond); fbr_mutex_unlock(FBR_A_ &buffer->write_mutex); } void fbr_buffer_alloc_abort(FBR_P_ struct fbr_buffer *buffer) { buffer->prepared_bytes = 0; fbr_cond_signal(FBR_A_ &buffer->committed_cond); fbr_mutex_unlock(FBR_A_ &buffer->write_mutex); } void *fbr_buffer_read_address(FBR_P_ struct fbr_buffer *buffer, size_t size) { int retval; if (size > fbr_buffer_size(FBR_A_ buffer)) return_error(NULL, FBR_EINVAL); fbr_mutex_lock(FBR_A_ &buffer->read_mutex); while (fbr_buffer_bytes(FBR_A_ buffer) < size) { retval = fbr_cond_wait(FBR_A_ &buffer->committed_cond, &buffer->read_mutex); assert(0 == retval); (void)retval; } buffer->waiting_bytes = size; return_success(fbr_buffer_data_ptr(FBR_A_ buffer)); } void fbr_buffer_read_advance(FBR_P_ struct fbr_buffer *buffer) { fbr_vrb_take(&buffer->vrb, buffer->waiting_bytes); fbr_cond_signal(FBR_A_ &buffer->bytes_freed_cond); fbr_mutex_unlock(FBR_A_ &buffer->read_mutex); } void fbr_buffer_read_discard(FBR_P_ struct fbr_buffer *buffer) { fbr_mutex_unlock(FBR_A_ &buffer->read_mutex); } int fbr_buffer_resize(FBR_P_ struct fbr_buffer *buffer, size_t size) { int rv; fbr_mutex_lock(FBR_A_ &buffer->read_mutex); fbr_mutex_lock(FBR_A_ &buffer->write_mutex); rv = fbr_vrb_resize(&buffer->vrb, size, fctx->__p->buffer_file_pattern); fbr_mutex_unlock(FBR_A_ &buffer->write_mutex); fbr_mutex_unlock(FBR_A_ &buffer->read_mutex); if (rv) return_error(-1, FBR_EBUFFERMMAP); return_success(0); } struct fbr_mq *fbr_mq_create(FBR_P_ size_t size, int flags) { struct fbr_mq *mq; mq = calloc(1, sizeof(*mq)); mq->fctx = fctx; mq->max = size + 1; /* One element is always unused */ mq->rb = calloc(mq->max, sizeof(void *)); mq->flags = flags; fbr_cond_init(FBR_A_ &mq->bytes_available_cond); fbr_cond_init(FBR_A_ &mq->bytes_freed_cond); return mq; } void fbr_mq_clear(struct fbr_mq *mq, int wake_up_writers) { memset(mq->rb, 0x00, mq->max * sizeof(void *)); mq->head = 0; mq->tail = 0; if (wake_up_writers) fbr_cond_signal(mq->fctx, &mq->bytes_available_cond); } void fbr_mq_push(struct fbr_mq *mq, void *obj) { unsigned next; while ((next = ((mq->head + 1) % mq->max )) == mq->tail) fbr_cond_wait(mq->fctx, &mq->bytes_freed_cond, NULL); mq->rb[mq->head] = obj; mq->head = next; fbr_cond_signal(mq->fctx, &mq->bytes_available_cond); } int fbr_mq_try_push(struct fbr_mq *mq, void *obj) { unsigned next = mq->head + 1; if (next >= mq->max) next = 0; /* Circular buffer is full */ if (next == mq->tail) return -1; mq->rb[mq->head] = obj; mq->head = next; fbr_cond_signal(mq->fctx, &mq->bytes_available_cond); return 0; } void fbr_mq_wait_push(struct fbr_mq *mq) { while (((mq->head + 1) % mq->max) == mq->tail) fbr_cond_wait(mq->fctx, &mq->bytes_freed_cond, NULL); } static void *mq_do_pop(struct fbr_mq *mq) { void *obj; unsigned next; obj = mq->rb[mq->tail]; mq->rb[mq->tail] = NULL; next = mq->tail + 1; if (next >= mq->max) next = 0; mq->tail = next; fbr_cond_signal(mq->fctx, &mq->bytes_freed_cond); return obj; } void *fbr_mq_pop(struct fbr_mq *mq) { /* if the head isn't ahead of the tail, we don't have any elements */ while (mq->head == mq->tail) fbr_cond_wait(mq->fctx, &mq->bytes_available_cond, NULL); return mq_do_pop(mq); } int fbr_mq_try_pop(struct fbr_mq *mq, void **obj) { /* if the head isn't ahead of the tail, we don't have any elements */ if (mq->head == mq->tail) return -1; *obj = mq_do_pop(mq); return 0; } void fbr_mq_wait_pop(struct fbr_mq *mq) { /* if the head isn't ahead of the tail, we don't have any elements */ while (mq->head == mq->tail) fbr_cond_wait(mq->fctx, &mq->bytes_available_cond, NULL); } void fbr_mq_destroy(struct fbr_mq *mq) { fbr_cond_destroy(mq->fctx, &mq->bytes_freed_cond); fbr_cond_destroy(mq->fctx, &mq->bytes_available_cond); free(mq->rb); free(mq); } void *fbr_get_user_data(FBR_P_ fbr_id_t id) { struct fbr_fiber *fiber; unpack_transfer_errno(NULL, &fiber, id); return_success(fiber->user_data); } int fbr_set_user_data(FBR_P_ fbr_id_t id, void *data) { struct fbr_fiber *fiber; unpack_transfer_errno(-1, &fiber, id); fiber->user_data = data; return_success(0); } void fbr_destructor_add(FBR_P_ struct fbr_destructor *dtor) { struct fbr_fiber *fiber = CURRENT_FIBER; TAILQ_INSERT_TAIL(&fiber->destructors, dtor, entries); dtor->active = 1; } void fbr_destructor_remove(FBR_P_ struct fbr_destructor *dtor, int call) { struct fbr_fiber *fiber = CURRENT_FIBER; if (0 == dtor->active) return; TAILQ_REMOVE(&fiber->destructors, dtor, entries); if (call) dtor->func(FBR_A_ dtor->arg); dtor->active = 0; } static inline int wrap_ffsll(uint64_t val) { /* TODO: Add some check for the existance of this builtin */ return __builtin_ffsll(val); } static inline int is_key_registered(FBR_P_ fbr_key_t key) { return 0 == (fctx->__p->key_free_mask & (1 << key)); } static inline void register_key(FBR_P_ fbr_key_t key) { fctx->__p->key_free_mask &= ~(1ULL << key); } static inline void unregister_key(FBR_P_ fbr_key_t key) { fctx->__p->key_free_mask |= (1 << key); } int fbr_key_create(FBR_P_ fbr_key_t *key_ptr) { fbr_key_t key = wrap_ffsll(fctx->__p->key_free_mask) - 1; assert(key < FBR_MAX_KEY); register_key(FBR_A_ key); *key_ptr = key; return_success(0); } int fbr_key_delete(FBR_P_ fbr_key_t key) { if (!is_key_registered(FBR_A_ key)) return_error(-1, FBR_ENOKEY); unregister_key(FBR_A_ key); return_success(0); } int fbr_key_set(FBR_P_ fbr_id_t id, fbr_key_t key, void *value) { struct fbr_fiber *fiber; unpack_transfer_errno(-1, &fiber, id); if (!is_key_registered(FBR_A_ key)) return_error(-1, FBR_ENOKEY); fiber->key_data[key] = value; return_success(0); } void *fbr_key_get(FBR_P_ fbr_id_t id, fbr_key_t key) { struct fbr_fiber *fiber; unpack_transfer_errno(NULL, &fiber, id); if (!is_key_registered(FBR_A_ key)) return_error(NULL, FBR_ENOKEY); return fiber->key_data[key]; } const char *fbr_get_name(FBR_P_ fbr_id_t id) { struct fbr_fiber *fiber; unpack_transfer_errno(NULL, &fiber, id); return_success(fiber->name); } int fbr_set_name(FBR_P_ fbr_id_t id, const char *name) { struct fbr_fiber *fiber; unpack_transfer_errno(-1, &fiber, id); strncpy(fiber->name, name, FBR_MAX_FIBER_NAME - 1); return_success(0); } static int make_pipe(FBR_P_ int *r, int*w) { int fds[2]; int retval; retval = pipe(fds); if (-1 == retval) return_error(-1, FBR_ESYSTEM); *r = fds[0]; *w = fds[1]; return_success(0); } pid_t fbr_popen3(FBR_P_ const char *filename, char *const argv[], char *const envp[], const char *working_dir, int *stdin_w_ptr, int *stdout_r_ptr, int *stderr_r_ptr) { pid_t pid; int stdin_r = -1, stdin_w = -1; int stdout_r = -1, stdout_w = -1; int stderr_r = -1, stderr_w = -1; int devnull = -1; int retval; retval = (stdin_w_ptr ? make_pipe(FBR_A_ &stdin_r, &stdin_w) : 0); if (retval) goto error; retval = (stdout_r_ptr ? make_pipe(FBR_A_ &stdout_r, &stdout_w) : 0); if (retval) goto error; retval = (stderr_r_ptr ? make_pipe(FBR_A_ &stderr_r, &stderr_w) : 0); if (retval) goto error; pid = fork(); if (-1 == pid) goto error; if (0 == pid) { /* Child */ ev_break(EV_DEFAULT, EVBREAK_ALL); if (stdin_w_ptr) { retval = close(stdin_w); if (-1 == retval) goto error; retval = dup2(stdin_r, STDIN_FILENO); if (-1 == retval) goto error; } else { devnull = open("/dev/null", O_RDONLY); if (-1 == retval) goto error; retval = dup2(devnull, STDIN_FILENO); if (-1 == retval) goto error; retval = close(devnull); if (-1 == retval) goto error; } if (stdout_r_ptr) { retval = close(stdout_r); if (-1 == retval) goto error; retval = dup2(stdout_w, STDOUT_FILENO); if (-1 == retval) goto error; } else { devnull = open("/dev/null", O_WRONLY); if (-1 == retval) goto error; retval = dup2(devnull, STDOUT_FILENO); if (-1 == retval) goto error; retval = close(devnull); if (-1 == retval) goto error; } if (stderr_r_ptr) { retval = close(stderr_r); if (-1 == retval) goto error; retval = dup2(stderr_w, STDERR_FILENO); if (-1 == retval) goto error; } else { devnull = open("/dev/null", O_WRONLY); if (-1 == retval) goto error; retval = dup2(devnull, STDERR_FILENO); if (-1 == retval) goto error; retval = close(devnull); if (-1 == retval) goto error; } if (working_dir) { retval = chdir(working_dir); if (-1 == retval) goto error; } retval = execve(filename, argv, envp); if (-1 == retval) goto error; errx(EXIT_FAILURE, "execve failed without error code"); } /* Parent */ if (stdin_w_ptr) { retval = close(stdin_r); if (-1 == retval) goto error; retval = fbr_fd_nonblock(FBR_A_ stdin_w); if (retval) goto error; } if (stdout_r_ptr) { retval = close(stdout_w); if (-1 == retval) goto error; retval = fbr_fd_nonblock(FBR_A_ stdout_r); if (retval) goto error; } if (stderr_r_ptr) { retval = close(stderr_w); if (-1 == retval) goto error; retval = fbr_fd_nonblock(FBR_A_ stderr_r); if (retval) goto error; } fbr_log_d(FBR_A_ "child pid %d has been launched", pid); if (stdin_w_ptr) *stdin_w_ptr = stdin_w; if (stdout_r_ptr) *stdout_r_ptr = stdout_r; if (stderr_r_ptr) *stderr_r_ptr = stderr_r; return pid; error: if (0 <= devnull) close(devnull); if (0 <= stdin_r) close(stdin_r); if (0 <= stdin_w) close(stdin_w); if (0 <= stdout_r) close(stdout_r); if (0 <= stdout_w) close(stdout_w); if (0 <= stderr_r) close(stderr_r); if (0 <= stderr_w) close(stderr_w); return_error(-1, FBR_ESYSTEM); } static void watcher_child_dtor(_unused_ FBR_P_ void *_arg) { struct ev_child *w = _arg; ev_child_stop(fctx->__p->loop, w); } int fbr_waitpid(FBR_P_ pid_t pid) { struct ev_child child; struct fbr_ev_watcher watcher; struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; ev_child_init(&child, NULL, pid, 0.); ev_child_start(fctx->__p->loop, &child); dtor.func = watcher_child_dtor; dtor.arg = &child; fbr_destructor_add(FBR_A_ &dtor); fbr_ev_watcher_init(FBR_A_ &watcher, (ev_watcher *)&child); fbr_ev_wait_one(FBR_A_ &watcher.ev_base); fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); ev_child_stop(fctx->__p->loop, &child); return_success(child.rstatus); } int fbr_system(FBR_P_ const char *filename, char *const argv[], char *const envp[], const char *working_dir) { pid_t pid; int retval; pid = fork(); if (-1 == pid) return_error(-1, FBR_ESYSTEM); if (0 == pid) { /* Child */ ev_break(EV_DEFAULT, EVBREAK_ALL); if (working_dir) { retval = chdir(working_dir); if (-1 == retval) err(EXIT_FAILURE, "chdir"); } retval = execve(filename, argv, envp); if (-1 == retval) err(EXIT_FAILURE, "execve"); errx(EXIT_FAILURE, "execve failed without error code"); } /* Parent */ fbr_log_d(FBR_A_ "child pid %d has been launched", pid); return fbr_waitpid(FBR_A_ pid); } #ifdef FBR_EIO_ENABLED static struct ev_loop *eio_loop; static ev_idle repeat_watcher; static ev_async ready_watcher; /* idle watcher callback, only used when eio_poll */ /* didn't handle all results in one call */ static void repeat(EV_P_ ev_idle *w, _unused_ int revents) { if (eio_poll () != -1) ev_idle_stop(EV_A_ w); } /* eio has some results, process them */ static void ready(EV_P_ _unused_ ev_async *w, _unused_ int revents) { if (eio_poll() == -1) ev_idle_start(EV_A_ &repeat_watcher); } /* wake up the event loop */ static void want_poll() { ev_async_send(eio_loop, &ready_watcher); } void fbr_eio_init() { if (NULL != eio_loop) { fprintf(stderr, "libevfibers: fbr_eio_init called twice"); abort(); } eio_loop = EV_DEFAULT; ev_idle_init(&repeat_watcher, repeat); ev_async_init(&ready_watcher, ready); ev_async_start(eio_loop, &ready_watcher); ev_unref(eio_loop); eio_init(want_poll, 0); } void fbr_ev_eio_init(FBR_P_ struct fbr_ev_eio *ev, eio_req *req) { ev_base_init(FBR_A_ &ev->ev_base, FBR_EV_EIO); ev->req = req; } static void eio_req_dtor(_unused_ FBR_P_ void *_arg) { eio_req *req = _arg; eio_cancel(req); } static int fiber_eio_cb(eio_req *req) { struct fbr_fiber *fiber; struct fbr_ev_eio *ev = req->data; struct fbr_context *fctx = ev->ev_base.fctx; int retval; ENSURE_ROOT_FIBER; ev_unref(eio_loop); if (EIO_CANCELLED(req)) return 0; retval = fbr_id_unpack(FBR_A_ &fiber, ev->ev_base.id); if (-1 == retval) { fbr_log_e(FBR_A_ "libevfibers: fiber is about to be called by" " the eio callback, but it's id is not valid: %s", fbr_strerror(FBR_A_ fctx->f_errno)); abort(); } post_ev(FBR_A_ fiber, &ev->ev_base); retval = fbr_transfer(FBR_A_ fbr_id_pack(fiber)); assert(0 == retval); return 0; } #define FBR_EIO_PREP \ eio_req *req; \ struct fbr_ev_eio e_eio; \ int retval; \ struct fbr_destructor dtor = FBR_DESTRUCTOR_INITIALIZER; \ ev_ref(eio_loop); #define FBR_EIO_WAIT \ if (NULL == req) { \ ev_unref(eio_loop); \ return_error(-1, FBR_EEIO); \ } \ dtor.func = eio_req_dtor; \ dtor.arg = req; \ fbr_destructor_add(FBR_A_ &dtor); \ fbr_ev_eio_init(FBR_A_ &e_eio, req); \ retval = fbr_ev_wait_one(FBR_A_ &e_eio.ev_base); \ fbr_destructor_remove(FBR_A_ &dtor, 0 /* Call it? */); \ if (retval) \ return retval; #define FBR_EIO_RESULT_CHECK \ if (0 > req->result) { \ errno = req->errorno; \ return_error(-1, FBR_ESYSTEM); \ } #define FBR_EIO_RESULT_RET \ FBR_EIO_RESULT_CHECK \ return req->result; int fbr_eio_open(FBR_P_ const char *path, int flags, mode_t mode, int pri) { FBR_EIO_PREP; req = eio_open(path, flags, mode, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_truncate(FBR_P_ const char *path, off_t offset, int pri) { FBR_EIO_PREP; req = eio_truncate(path, offset, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_chown(FBR_P_ const char *path, uid_t uid, gid_t gid, int pri) { FBR_EIO_PREP; req = eio_chown(path, uid, gid, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_chmod(FBR_P_ const char *path, mode_t mode, int pri) { FBR_EIO_PREP; req = eio_chmod(path, mode, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_mkdir(FBR_P_ const char *path, mode_t mode, int pri) { FBR_EIO_PREP; req = eio_mkdir(path, mode, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_rmdir(FBR_P_ const char *path, int pri) { FBR_EIO_PREP; req = eio_rmdir(path, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_unlink(FBR_P_ const char *path, int pri) { FBR_EIO_PREP; req = eio_unlink(path, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_utime(FBR_P_ const char *path, eio_tstamp atime, eio_tstamp mtime, int pri) { FBR_EIO_PREP; req = eio_utime(path, atime, mtime, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_mknod(FBR_P_ const char *path, mode_t mode, dev_t dev, int pri) { FBR_EIO_PREP; req = eio_mknod(path, mode, dev, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_link(FBR_P_ const char *path, const char *new_path, int pri) { FBR_EIO_PREP; req = eio_link(path, new_path, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_symlink(FBR_P_ const char *path, const char *new_path, int pri) { FBR_EIO_PREP; req = eio_symlink(path, new_path, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_rename(FBR_P_ const char *path, const char *new_path, int pri) { FBR_EIO_PREP; req = eio_rename(path, new_path, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_mlock(FBR_P_ void *addr, size_t length, int pri) { FBR_EIO_PREP; req = eio_mlock(addr, length, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_close(FBR_P_ int fd, int pri) { FBR_EIO_PREP; req = eio_close(fd, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_sync(FBR_P_ int pri) { FBR_EIO_PREP; req = eio_sync(pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_fsync(FBR_P_ int fd, int pri) { FBR_EIO_PREP; req = eio_fsync(fd, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_fdatasync(FBR_P_ int fd, int pri) { FBR_EIO_PREP; req = eio_fdatasync(fd, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_futime(FBR_P_ int fd, eio_tstamp atime, eio_tstamp mtime, int pri) { FBR_EIO_PREP; req = eio_futime(fd, atime, mtime, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_ftruncate(FBR_P_ int fd, off_t offset, int pri) { FBR_EIO_PREP; req = eio_ftruncate(fd, offset, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_fchmod(FBR_P_ int fd, mode_t mode, int pri) { FBR_EIO_PREP; req = eio_fchmod(fd, mode, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_fchown(FBR_P_ int fd, uid_t uid, gid_t gid, int pri) { FBR_EIO_PREP; req = eio_fchown(fd, uid, gid, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_dup2(FBR_P_ int fd, int fd2, int pri) { FBR_EIO_PREP; req = eio_dup2(fd, fd2, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } ssize_t fbr_eio_seek(FBR_P_ int fd, off_t offset, int whence, int pri) { FBR_EIO_PREP; req = eio_seek(fd, offset, whence, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_CHECK; return req->offs; } ssize_t fbr_eio_read(FBR_P_ int fd, void *buf, size_t length, off_t offset, int pri) { FBR_EIO_PREP; req = eio_read(fd, buf, length, offset, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } ssize_t fbr_eio_write(FBR_P_ int fd, void *buf, size_t length, off_t offset, int pri) { FBR_EIO_PREP; req = eio_write(fd, buf, length, offset, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_mlockall(FBR_P_ int flags, int pri) { FBR_EIO_PREP; req = eio_mlockall(flags, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_msync(FBR_P_ void *addr, size_t length, int flags, int pri) { FBR_EIO_PREP; req = eio_msync(addr, length, flags, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_readlink(FBR_P_ const char *path, char *buf, size_t size, int pri) { FBR_EIO_PREP; req = eio_readlink(path, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_CHECK; strncpy(buf, req->ptr2, min(size, (size_t)req->result)); return req->result; } int fbr_eio_realpath(FBR_P_ const char *path, char *buf, size_t size, int pri) { FBR_EIO_PREP; req = eio_realpath(path, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_CHECK; strncpy(buf, req->ptr2, min(size, (size_t)req->result)); return req->result; } int fbr_eio_stat(FBR_P_ const char *path, EIO_STRUCT_STAT *statdata, int pri) { EIO_STRUCT_STAT *st; FBR_EIO_PREP; req = eio_stat(path, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_CHECK; st = (EIO_STRUCT_STAT *)req->ptr2; memcpy(statdata, st, sizeof(*st)); return req->result; } int fbr_eio_lstat(FBR_P_ const char *path, EIO_STRUCT_STAT *statdata, int pri) { EIO_STRUCT_STAT *st; FBR_EIO_PREP; req = eio_lstat(path, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_CHECK; st = (EIO_STRUCT_STAT *)req->ptr2; memcpy(statdata, st, sizeof(*st)); return req->result; } int fbr_eio_fstat(FBR_P_ int fd, EIO_STRUCT_STAT *statdata, int pri) { EIO_STRUCT_STAT *st; FBR_EIO_PREP; req = eio_fstat(fd, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_CHECK; st = (EIO_STRUCT_STAT *)req->ptr2; memcpy(statdata, st, sizeof(*st)); return req->result; } int fbr_eio_statvfs(FBR_P_ const char *path, EIO_STRUCT_STATVFS *statdata, int pri) { EIO_STRUCT_STATVFS *st; FBR_EIO_PREP; req = eio_statvfs(path, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_CHECK; st = (EIO_STRUCT_STATVFS *)req->ptr2; memcpy(statdata, st, sizeof(*st)); return req->result; } int fbr_eio_fstatvfs(FBR_P_ int fd, EIO_STRUCT_STATVFS *statdata, int pri) { EIO_STRUCT_STATVFS *st; FBR_EIO_PREP; req = eio_fstatvfs(fd, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_CHECK; st = (EIO_STRUCT_STATVFS *)req->ptr2; memcpy(statdata, st, sizeof(*st)); return req->result; } int fbr_eio_sendfile(FBR_P_ int out_fd, int in_fd, off_t in_offset, size_t length, int pri) { FBR_EIO_PREP; req = eio_sendfile(out_fd, in_fd, in_offset, length, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_readahead(FBR_P_ int fd, off_t offset, size_t length, int pri) { FBR_EIO_PREP; req = eio_readahead(fd, offset, length, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_syncfs(FBR_P_ int fd, int pri) { FBR_EIO_PREP; req = eio_syncfs(fd, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_sync_file_range(FBR_P_ int fd, off_t offset, size_t nbytes, unsigned int flags, int pri) { FBR_EIO_PREP; req = eio_sync_file_range(fd, offset, nbytes, flags, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } int fbr_eio_fallocate(FBR_P_ int fd, int mode, off_t offset, off_t len, int pri) { FBR_EIO_PREP; req = eio_fallocate(fd, mode, offset, len, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } static void custom_execute_cb(eio_req *req) { struct fbr_ev_eio *ev = req->data; req->result = ev->custom_func(ev->custom_arg); } eio_ssize_t fbr_eio_custom(FBR_P_ fbr_eio_custom_func_t func, void *data, int pri) { FBR_EIO_PREP; e_eio.custom_func = func; e_eio.custom_arg = data; req = eio_custom(custom_execute_cb, pri, fiber_eio_cb, &e_eio); FBR_EIO_WAIT; FBR_EIO_RESULT_RET; } #else void fbr_eio_init(FBR_PU) { fbr_log_e(FBR_A_ "libevfibers: libeio support is not compiled"); abort(); } #endif
Lupus/libevfibers
include/evfibers_private/fiber.h
/******************************************************************** Copyright 2013 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ********************************************************************/ #ifndef _FBR_FIBER_PRIVATE_H_ #define _FBR_FIBER_PRIVATE_H_ #include <stdarg.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #include <sys/queue.h> #include <evfibers/fiber.h> #include <evfibers_private/trace.h> #include <coro.h> #define max(a,b) ({ \ const typeof(a) __tmp_a = (a); \ const typeof(b) __tmp_b = (b); \ __tmp_a > __tmp_b ? __tmp_a : __tmp_b; \ }) #define min(a,b) ({ \ const typeof(a) __tmp_a = (a); \ const typeof(b) __tmp_b = (b); \ __tmp_a < __tmp_b ? __tmp_a : __tmp_b; \ }) #define _unused_ __attribute__((unused)) #ifndef LIST_FOREACH_SAFE #define LIST_FOREACH_SAFE(var, head, field, next_var) \ for ((var) = ((head)->lh_first); \ (var) && ((next_var) = ((var)->field.le_next), 1); \ (var) = (next_var)) #endif #ifndef TAILQ_FOREACH_SAFE #define TAILQ_FOREACH_SAFE(var, head, field, next_var) \ for ((var) = ((head)->tqh_first); \ (var) ? ({ (next_var) = ((var)->field.tqe_next); 1; }) \ : 0; \ (var) = (next_var)) #endif #define ENSURE_ROOT_FIBER do { \ assert(fctx->__p->sp->fiber == &fctx->__p->root); \ } while (0) #define CURRENT_FIBER (fctx->__p->sp->fiber) #define CURRENT_FIBER_ID (fbr_id_pack(CURRENT_FIBER)) #define CALLED_BY_ROOT ((fctx->__p->sp - 1)->fiber == &fctx->__p->root) #define unpack_transfer_errno(value, ptr, id) \ do { \ if (-1 == fbr_id_unpack(fctx, ptr, id)) \ return (value); \ } while (0) #define return_success(value) \ do { \ fctx->f_errno = FBR_SUCCESS; \ return (value); \ } while (0) #define return_error(value, code) \ do { \ fctx->f_errno = (code); \ return (value); \ } while (0) #ifndef LIST_FOREACH_SAFE #define LIST_FOREACH_SAFE(var, head, field, next_var) \ for ((var) = ((head)->lh_first); \ (var) && ((next_var) = ((var)->field.le_next), 1); \ (var) = (next_var)) #endif #ifndef TAILQ_FOREACH_SAFE #define TAILQ_FOREACH_SAFE(var, head, field, next_var) \ for ((var) = ((head)->tqh_first); \ (var) ? ({ (next_var) = ((var)->field.tqe_next); 1; }) \ : 0; \ (var) = (next_var)) #endif #define ENSURE_ROOT_FIBER do { \ assert(fctx->__p->sp->fiber == &fctx->__p->root); \ } while (0) #define CURRENT_FIBER (fctx->__p->sp->fiber) #define CURRENT_FIBER_ID (fbr_id_pack(CURRENT_FIBER)) #define CALLED_BY_ROOT ((fctx->__p->sp - 1)->fiber == &fctx->__p->root) #define unpack_transfer_errno(value, ptr, id) \ do { \ if (-1 == fbr_id_unpack(fctx, ptr, id)) \ return (value); \ } while (0) #define return_success(value) \ do { \ fctx->f_errno = FBR_SUCCESS; \ return (value); \ } while (0) #define return_error(value, code) \ do { \ fctx->f_errno = (code); \ return (value); \ } while (0) struct mem_pool { void *ptr; fbr_alloc_destructor_func_t destructor; void *destructor_context; LIST_ENTRY(mem_pool) entries; }; LIST_HEAD(mem_pool_list, mem_pool); TAILQ_HEAD(fiber_destructor_tailq, fbr_destructor); LIST_HEAD(fiber_list, fbr_fiber); struct fbr_fiber { uint64_t id; char name[FBR_MAX_FIBER_NAME]; fbr_fiber_func_t func; void *func_arg; coro_context ctx; char *stack; size_t stack_size; struct { struct fbr_ev_base **waiting; int arrived; } ev; struct trace_info reclaim_tinfo; struct fiber_list children; struct fbr_fiber *parent; struct mem_pool_list pool; struct { LIST_ENTRY(fbr_fiber) reclaimed; LIST_ENTRY(fbr_fiber) children; } entries; struct fiber_destructor_tailq destructors; void *user_data; void *key_data[FBR_MAX_KEY]; int no_reclaim; int want_reclaim; struct fbr_cond_var reclaim_cond; }; TAILQ_HEAD(mutex_tailq, fbr_mutex); struct fbr_stack_item { struct fbr_fiber *fiber; struct trace_info tinfo; }; struct fbr_context_private { struct fbr_stack_item stack[FBR_CALL_STACK_SIZE]; struct fbr_stack_item *sp; struct fbr_fiber root; struct fiber_list reclaimed; struct ev_async pending_async; struct fbr_id_tailq pending_fibers; int backtraces_enabled; uint64_t last_id; uint64_t key_free_mask; const char *buffer_file_pattern; struct ev_loop *loop; }; struct fbr_mq { struct fbr_context *fctx; void **rb; unsigned head; unsigned tail; unsigned max; int flags; struct fbr_cond_var bytes_available_cond; struct fbr_cond_var bytes_freed_cond; }; #endif
SLingFeng/RxSwiftTest
test/Pods/Target Support Files/WPAttributedMarkup/WPAttributedMarkup-umbrella.h
<filename>test/Pods/Target Support Files/WPAttributedMarkup/WPAttributedMarkup-umbrella.h #ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif #import "NSMutableString+TagReplace.h" #import "NSString+WPAttributedMarkup.h" #import "WPAttributedStyleAction.h" #import "WPHotspotLabel.h" #import "WPTappableLabel.h" FOUNDATION_EXPORT double WPAttributedMarkupVersionNumber; FOUNDATION_EXPORT const unsigned char WPAttributedMarkupVersionString[];
guyanyijiu/qx_partner
qx_partner.c
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2017 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | <EMAIL> so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "php_qx_partner.h" /* If you declare any globals in php_qx_partner.h uncomment this: ZEND_DECLARE_MODULE_GLOBALS(qx_partner) */ /* True global resources - no need for thread safety here */ static int le_qx_partner; /* {{{ PHP_INI */ PHP_INI_BEGIN() PHP_INI_ENTRY("qx_partner.id", "0", PHP_INI_ALL, NULL) PHP_INI_ENTRY("qx_partner.mark", "default", PHP_INI_ALL, NULL) PHP_INI_END() /* }}} */ /* Remove the following function when you have successfully modified config.m4 so that your module can be compiled into PHP, it exists only for testing purposes. */ /* Every user-visible function in PHP should document itself in the source */ /* {{{ proto string confirm_qx_partner_compiled(string arg) Return a string to confirm that the module is compiled in */ PHP_FUNCTION(confirm_qx_partner_compiled) { char *arg = NULL; size_t arg_len, len; zend_string *strg; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE) { return; } strg = strpprintf(0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "qx_partner", arg); RETURN_STR(strg); } /* }}} */ /* The previous line is meant for vim and emacs, so it can correctly fold and unfold functions in source code. See the corresponding marks just before function definition, where the functions purpose is also documented. Please follow this convention for the convenience of others editing your code. */ /* {{{ php_qx_partner_init_globals */ /* Uncomment this function if you have INI entries static void php_qx_partner_init_globals(zend_qx_partner_globals *qx_partner_globals) { qx_partner_globals->global_value = 0; qx_partner_globals->global_string = NULL; } */ /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(qx_partner) { REGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(qx_partner) { UNREGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request start */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(qx_partner) { #if defined(COMPILE_DL_QX_PARTNER) && defined(ZTS) ZEND_TSRMLS_CACHE_UPDATE(); #endif return SUCCESS; } /* }}} */ /* Remove if there's nothing to do at request end */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(qx_partner) { return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(qx_partner) { php_info_print_table_start(); php_info_print_table_header(2, "qx_partner support", "enabled"); php_info_print_table_row(2, "version", PHP_QX_PARTNER_VERSION); php_info_print_table_row(2, "author", PHP_QX_PARTNER_AUTHOR); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ qx_partner_functions[] * * Every user visible function must have an entry in qx_partner_functions[]. */ const zend_function_entry qx_partner_functions[] = { PHP_FE(confirm_qx_partner_compiled, NULL) /* For testing, remove later. */ PHP_FE_END /* Must be the last line in qx_partner_functions[] */ }; /* }}} */ /* {{{ qx_partner_module_entry */ zend_module_entry qx_partner_module_entry = { STANDARD_MODULE_HEADER, "qx_partner", qx_partner_functions, PHP_MINIT(qx_partner), PHP_MSHUTDOWN(qx_partner), PHP_RINIT(qx_partner), /* Replace with NULL if there's nothing to do at request start */ PHP_RSHUTDOWN(qx_partner), /* Replace with NULL if there's nothing to do at request end */ PHP_MINFO(qx_partner), PHP_QX_PARTNER_VERSION, STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_QX_PARTNER #ifdef ZTS ZEND_TSRMLS_CACHE_DEFINE() #endif ZEND_GET_MODULE(qx_partner) #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
Pasyware/Http_Sniffer
src/hash_table.c
<filename>src/hash_table.c /* * hash_table.c * * Created on: Mar 16, 2012 * Author: front */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <string.h> #include <assert.h> #include <sys/time.h> #include <unistd.h> #include "util.h" #include "flow.h" #include "packet.h" #define HASH_SIZE 10007 #define HASH_FLOW(flow_socket) ( \ ( (flow_socket.sport & 0xff) | ((flow_socket.dport & 0xff) << 8) | \ ((flow_socket.saddr & 0xff) << 16) | ((flow_socket.daddr & 0xff) << 24) \ ) % HASH_SIZE) static hash_mb_t *flow_hash_table[HASH_SIZE]; static int flow_cnt = 0; /* flows live in hash table */ /* Initiate the flow hash table with no flows */ int flow_hash_init(void) { int ret, i; flow_cnt = 0; for(i=0; i<HASH_SIZE; i++){ flow_hash_table[i] = MALLOC(hash_mb_t, 1); flow_hash_table[i]->first = NULL; flow_hash_table[i]->last = NULL; flow_hash_table[i]->elm_cnt = 0; ret = pthread_mutex_init(&(flow_hash_table[i]->mutex), NULL); if (ret != 0) return -1; } return 0; } /* Create a new record in hash table according to flow's socket */ flow_t* flow_hash_new(flow_s s) { flow_t *f = NULL; hash_mb_t *hm = NULL; f = flow_new(); f->socket.saddr = s.saddr; f->socket.daddr = s.daddr; f->socket.sport = s.sport; f->socket.dport = s.dport; hm = flow_hash_table[HASH_FLOW(s)]; pthread_mutex_lock(&(hm->mutex)); if(hm->elm_cnt == 0 ){ f->next = NULL; f->prev = NULL; hm->first = f; }else{ hm->last->next = f; f->prev = hm->last; } hm->last = f; hm->last->next = NULL; f->hmb = hm; hm->elm_cnt++; flow_cnt++; pthread_mutex_unlock(&(hm->mutex)); return f; } /* Delete a flow record in hash table */ flow_t* flow_hash_delete(flow_t *f) { hash_mb_t *hm = NULL; hm = f->hmb; if( hm->elm_cnt == 1 && f == hm->first){ hm->first = NULL; hm->last = NULL; }else{ if(f->prev == NULL){ /* the first flow record */ hm->first = f->next; hm->first->prev = NULL; }else if(f->next == NULL){ hm->last = f->prev; hm->last->next = NULL; }else{ f->prev->next = f->next; f->next->prev = f->prev; } } f->next = NULL; f->prev = NULL; hm->elm_cnt--; flow_cnt--; return f; } /* Try to find a flow record in hash table based on its socket */ flow_t* flow_hash_find(flow_s s) { hash_mb_t *hm = NULL; flow_t *flow = NULL; hm = flow_hash_table[HASH_FLOW(s)]; pthread_mutex_lock(&(hm->mutex)); if (hm->elm_cnt > 0){ flow = hm->first; while(flow != NULL){ if(flow_socket_cmp(&s, &flow->socket) == 0){ pthread_mutex_unlock(&(hm->mutex)); return flow; }else{ flow = flow->next; continue; } } } pthread_mutex_unlock(&(hm->mutex)); return NULL; } /* * Add a packet to hash table * Link the packet to flow's packet list if the flow has already existed; * Otherwise, make a new flow record and add the packet to it. */ int flow_hash_add_packet(packet_t *packet) { flow_s cs; flow_t *f = NULL; cs.saddr = packet->daddr; cs.sport = packet->dport; cs.daddr = packet->saddr; cs.dport = packet->sport; f = flow_hash_find(cs); if(f != NULL){ flow_add_packet(f, packet, 0); }else{ cs.saddr = packet->saddr; cs.daddr = packet->daddr; cs.sport = packet->sport; cs.dport = packet->dport; f = flow_hash_find(cs); if(f != NULL){ flow_add_packet(f, packet, 1); }else{ /* * New flow record. */ if(packet->tcp_flags == TH_SYN){ f = flow_hash_new(cs); flow_add_packet(f, packet, 1); }else{ packet_free(packet); } } } return 0; } /* Clear the flow hash table thoroughly */ int flow_hash_clear(void) { int i = 0; for(i=0; i<HASH_SIZE; i++){ pthread_mutex_lock(&(flow_hash_table[i]->mutex)); } flow_t *f = NULL; flow_cnt = 0; for(i=0; i<HASH_SIZE; i++){ while(flow_hash_table[i]->first != NULL ){ f = flow_hash_table[i]->first; flow_hash_table[i]->first = flow_hash_table[i]->first->next; flow_free(f); flow_hash_table[i]->elm_cnt--; } flow_hash_table[i]->first = NULL; flow_hash_table[i]->last = NULL; } for(i=0; i<HASH_SIZE; i++){ pthread_mutex_unlock(&(flow_hash_table[i]->mutex)); } return 0; } /* Return the size of hash table */ int flow_hash_size(void) { return HASH_SIZE; } /* Return the flow count of hash table */ int flow_hash_fcnt(void) { return flow_cnt; } /* Return the count of hash slots consumed */ int flow_hash_scnt(void) { int i = 0; int slot_consumed = 0; for(i=0; i<HASH_SIZE; i++) { pthread_mutex_lock(&(flow_hash_table[i]->mutex)); } for(i=0; i<HASH_SIZE; i++) { if(flow_hash_table[i]->first != NULL) { slot_consumed++; } } for(i=0; i<HASH_SIZE; i++) { pthread_mutex_unlock(&(flow_hash_table[i]->mutex)); } return slot_consumed; } /* * Close a flow forcedly if the delta time is lower than timeout. * Then add the flow to flow queue. * Return the number of flows deleted forcedly. */ int flow_scrubber(const int timeout) { int i = 0; unsigned long delta = 0; flow_t *flow = NULL, *flow_next = NULL; struct timeval tv; struct timezone tz; int num = 0; for (i=0; i<HASH_SIZE; i++){ pthread_mutex_lock(&(flow_hash_table[i]->mutex)); flow = flow_hash_table[i]->first; while(flow != NULL){ flow_next = flow->next; gettimeofday(&tv, &tz); delta = abs(tv.tv_sec - flow->last_action_sec); if (delta > timeout){ num++; flow->close = FORCED_CLOSE; // Close flow forcedly. flow_queue_enq(flow_hash_delete(flow)); } flow = flow_next; } assert(flow == NULL); pthread_mutex_unlock(&(flow_hash_table[i]->mutex)); } return num; } /* Print hash table details for debugging */ void flow_hash_print(void) { printf("(Hash size)%d : (Consumed)%d : (Flows)%d\n", flow_hash_size(), flow_hash_scnt(), flow_hash_fcnt() ); }
Pasyware/Http_Sniffer
src/tcp.c
/* * tcp.c * * Created on: Jun 15, 2011 * Author: chenxm */ #include <assert.h> #include "order.h" /* * Search for a continuous segment in order */ static seq_t *tcp_cont_seq(seq_t *lst) { while (lst->next != NULL && lst->nxt_seq == lst->next->seq) lst = lst->next; return lst; } /* * reorder the TCP packets */ int tcp_order(order_t *ord, seq_t *new_seq, BOOL src){ seq_t **plist=NULL, **plist_last=NULL, *pre=NULL, *cp=NULL, *aft=NULL; u_int32_t fr=0, bk=0; if(src == TRUE){ plist = &(ord->src); plist_last = &(ord->last_src); }else{ plist = &(ord->dst); plist_last = &(ord->last_dst); } if( (*plist) == NULL ){ /* first packet */ (*plist) = new_seq; (*plist_last) = new_seq; ord->num++; return 0; }else{ /* set some variables fr,pre,cp,aft,bk to add a new seq to order */ if((*plist_last)->nxt_seq == new_seq->seq){ fr = ((*plist_last)->seq); pre = (*plist_last); cp = tcp_cont_seq((*plist_last)); aft = cp->next; bk = bk = cp->nxt_seq - 1; } else{ cp = (*plist); /* search position */ pre = cp; while(cp != NULL && (cp->nxt_seq) <= (new_seq->seq)){ /* not (cp->nxt_seq) <= (new_seq->seq) */ pre = cp; cp = cp->next; } if( cp == NULL){ /* at list end */ pre->next = new_seq; (*plist_last) = new_seq; ord->num++; return 0; }else{ fr = pre->seq; /* start of continuous segment */ cp = tcp_cont_seq(pre); /* the last seq_t in a continuous segment */ aft = cp->next; bk = cp->nxt_seq - 1; /* end of continuous segment */ } } /* add new seq to the right position */ if((new_seq->seq) >= fr && (new_seq->seq) <= bk ){ if( (new_seq->nxt_seq -1) <= bk){ /* retransmission */ seq_free(new_seq); return 1; }else{ /* adjust the packet */ u_int32_t delta = (new_seq->nxt_seq-1) - bk; if(new_seq->pkt != NULL){ if(new_seq->pkt->tcp_data != NULL){ /* check if we store the packet payload */ new_seq->pkt->tcp_data = new_seq->pkt->tcp_data + (new_seq->pkt->tcp_dl - delta); } new_seq->pkt->tcp_dl = delta; } new_seq->seq = bk + 1; /* update order */ cp->next = new_seq; (*plist_last) = new_seq; if( aft != NULL ){ new_seq->next = aft; /* Connect with follower */ if(new_seq->nxt_seq <= aft->seq){ new_seq->next = aft; (*plist_last) = new_seq; ord->num++; return 0; }else{ /* partially overlapped */ if(new_seq->pkt != NULL){ new_seq->pkt->tcp_dl -= (new_seq->nxt_seq - aft->seq); } new_seq->nxt_seq = aft->seq; new_seq->next = aft; (*plist_last) = new_seq; ord->num++; return 0; } } return 0; } }else{ cp->next = new_seq; if(aft != NULL){ if(new_seq->nxt_seq <= aft->seq){ new_seq->next = aft; (*plist_last) = new_seq; ord->num++; return 0; }else{ /* partially overlapped */ if(new_seq->pkt != NULL){ new_seq->pkt->tcp_dl -= (new_seq->nxt_seq - aft->seq); } new_seq->nxt_seq = aft->seq; new_seq->next = aft; (*plist_last) = new_seq; ord->num++; return 0; } } return 0; } } } /* for debugging */ /* check the if TCP is ordered correctly */ int tcp_order_check(order_t *order){ u_int32_t seq, next_seq; int src_check = 0, dst_check = 0; seq_t *ps; if(order == NULL){ return 0; } ps = order->src; if(ps == NULL){ src_check = 1; }else{ while(ps->next != NULL){ if(ps->nxt_seq == ps->next->seq){ ps = ps->next; }else{ printf("%lu\t%lu\n", ps->nxt_seq, ps->next->seq); src_check = 0; break; } } if(ps->next == NULL){ src_check = 1; } } ps = order->dst; if( ps == NULL){ dst_check = 1; }else{ while(ps->next != NULL){ if(ps->nxt_seq == ps->next->seq){ ps = ps->next; }else{ printf("%lu\t%lu\n", ps->nxt_seq, ps->next->seq); dst_check = 0; break; } } if(ps->next == NULL){ dst_check = 1; } } if(src_check == 1 && dst_check == 1){ return TRUE; } return FALSE; }
Pasyware/Http_Sniffer
src/packet.c
<reponame>Pasyware/Http_Sniffer /* * packet.c * * Created on: Mar 16, 2012 * Author: chenxm * Email: <EMAIL> */ #include <stdlib.h> #include <string.h> #include <pthread.h> #include <netinet/in.h> #include "packet.h" #include "util.h" /* * Create new packet */ packet_t* packet_new(void) { packet_t *pkt; pkt = MALLOC(packet_t, 1); memset(pkt, 0, sizeof(packet_t)); pkt->tcp_odata = NULL; pkt->tcp_data = pkt->tcp_odata; pkt->next = NULL; return pkt; } /* * Free a memory block allocated to a packet_t object */ void packet_free(packet_t *pkt) { if(pkt != NULL) { if(pkt->tcp_odata != NULL) { free(pkt->tcp_odata); } free(pkt); } } /* * Parse the ethernet header with little endian format */ ethhdr * packet_parse_ethhdr(const char *p) { ethhdr *hdr, *tmp; tmp = p; hdr = MALLOC(ethhdr, 1); memset(hdr, 0, sizeof(ethhdr)); memcpy(hdr->ether_dhost, tmp->ether_dhost, 6 * sizeof(u_int8_t)); memcpy(hdr->ether_shost, tmp->ether_shost, 6 * sizeof(u_int8_t)); hdr->ether_type = ntohs(tmp->ether_type); return hdr; } /* * Parse the IP header with little endian format */ iphdr * packet_parse_iphdr(const char *p) { iphdr *hdr, *tmp; tmp = (iphdr *)p; hdr = MALLOC(iphdr, 1); memset(hdr, '\0', sizeof(iphdr)); hdr->ihl = tmp->ihl; hdr->version = tmp->version; hdr->tos = tmp->tos; hdr->tot_len = ntohs(tmp->tot_len); hdr->id = ntohs(tmp->id); hdr->frag_off = ntohs(tmp->frag_off); hdr->ttl = tmp->ttl; hdr->protocol = tmp->protocol; hdr->check = ntohs(tmp->check); hdr->saddr = ntohl(tmp->saddr); hdr->daddr = ntohl(tmp->daddr); return hdr; } /* * Parse the TCP header with little endian format */ tcphdr * packet_parse_tcphdr(const char *p) { tcphdr *hdr, *tmp; tmp = (tcphdr *)p; hdr = MALLOC(tcphdr, 1); memset(hdr, '\0', sizeof(tcphdr)); hdr->th_sport = ntohs(tmp->th_sport); hdr->th_dport = ntohs(tmp->th_dport); hdr->th_seq = ntohl(tmp->th_seq); hdr->th_ack = ntohl(tmp->th_ack); hdr->th_x2 = tmp->th_x2; hdr->th_off = tmp->th_off; hdr->th_flags = tmp->th_flags; hdr->th_win = ntohs(tmp->th_win); hdr->th_sum = ntohs(tmp->th_sum); hdr->th_urp = ntohs(tmp->th_urp); return hdr; } /* Free the ethernet header */ void free_ethhdr(ethhdr *h) { free(h); } /* Free the IP header */ void free_iphdr(iphdr *h) { free(h); } /* Free the TCP header */ void free_tcphdr(tcphdr *h) { free(h); }
Pasyware/Http_Sniffer
include/flow.h
<filename>include/flow.h<gh_stars>100-1000 /* * flow.h * * Created on: Jun 10, 2011 * Author: chenxm */ #ifndef FLOW_H_ #define FLOW_H_ #include <pthread.h> #include <sys/types.h> #include "packet.h" #include "order.h" #include "http.h" #include "util.h" /** * flow socket */ typedef struct _flow_s flow_s; struct _flow_s { u_int32_t saddr; u_int32_t daddr; u_int16_t sport; u_int16_t dport; }; /** * Hash management block */ typedef struct _hash_mb_t hash_mb_t; /** * Structure flow_t to store flow's info */ typedef struct _flow_t flow_t; struct _hash_mb_t { flow_t *first; flow_t *last; pthread_mutex_t mutex; int elm_cnt; }; /** * Extendable flow structure which stores src/dst packet queues. */ struct _flow_t { flow_t *next; flow_t *prev; /* Packets of flow */ packet_t *pkt_src_f; /* front of packets src queue */ packet_t *pkt_src_e; /* end of packets src queue */ packet_t *pkt_dst_f; /* front of packets dst queue */ packet_t *pkt_dst_e; /* end of packets dst queue */ u_int32_t pkt_src_n; /* number of packet in src queue */ u_int32_t pkt_dst_n; /* number of packet in dst queue */ u_int32_t pkts_src; /* total packets count of the flow sent by src */ u_int32_t pkts_dst; /* total packets count of the flow sent by dst */ order_t *order; /* info to order the packet */ hash_mb_t *hmb; /* hash management block */ /* TCP info */ flow_s socket; /* flow socket with 4 tuple */ u_int8_t rtt; /* round trip time (us) */ time_t syn_sec; /* syn time in sec */ time_t syn_usec; /* syn time in usec */ time_t ack2_sec; /* third handshake time in sec */ time_t ack2_usec; /* third handshake time in usec */ time_t fb_sec; /* first byte time of flow payload in sec */ time_t fb_usec; /* first byte time of flow payload in usec */ time_t lb_sec; /* last byte time of flow payload in sec */ time_t lb_usec; /* last byte time of flow payload in usec */ u_int32_t payload_src; /* bytes of payload sent from source to destination */ u_int32_t payload_dst; /* bytes of payload sent from destination to source */ /* HTTP info*/ BOOL http; /* carrying www ? */ http_pair_t *http_f; /* front of HTTP pair queue */ http_pair_t *http_e; /* end of HTTP pair queue */ u_int32_t http_cnt; /* count of HTTP pairs */ /* Control */ time_t last_action_sec; /* latest modified time to the flow in seconds */ time_t last_action_usec; /* latest modified time to the flow in microseconds */ u_int8_t close; #define CLIENT_CLOSE 0x01 #define SERVER_CLOSE 0x02 #define FORCED_CLOSE 0x04 }; /** * Basic flow functions * flow.c */ int flow_init(void); /* Initiate both flow hash table and flow queue */ flow_t* flow_new(void); /* Create a flow_t object */ int flow_free(flow_t*); /* Free a flow_t object */ int flow_add_packet(flow_t *f, packet_t *packet, BOOL src); /* Add a packet_t object to flow's packet_t chain */ int flow_socket_cmp(flow_s *a, flow_s *b); /* Compare flows' sockets */ int flow_extract_http(flow_t *f); /* Extract http_pair_t objects from flow's packet_t chain */ int flow_add_http(flow_t *f, http_pair_t *h); /* Add a http_pair_t objects to flow's http_pair_t chain */ /** * Functions of flow hash table * hash_table.c */ int flow_hash_init(void); /* Initiate the flow hash table with no flows */ flow_t* flow_hash_new(flow_s s); /* Create a new record in hash table according to flow's socket */ flow_t* flow_hash_delete(flow_t *f); /* Delete a flow record in hash table */ flow_t* flow_hash_find(flow_s s); /* Try to find a flow record in hash table based on its socket */ int flow_hash_add_packet(packet_t *packet); /* Add a packet to one of the flow records in hash table */ int flow_hash_clear(void); /* Clear all records of flow hash table */ int flow_hash_size(void); /* Size of flow hash table */ int flow_hash_fcnt(void); /* Number of flows online */ int flow_hash_scnt(void); /* Count of hash slots consumed */ int flow_scrubber(const int timeslot); /* Remove a flow record from hash table manually if the arriving period is greater than the timeslot */ void flow_hash_print(void); /* Print hash table details for debugging */ /** * Functions of flow queue for further processing * queue.c */ int flow_queue_init(void); /* Initialize a flow queue */ int flow_queue_enq(flow_t *flow); /* Add a flow_t object to queue */ flow_t* flow_queue_deq(void); /* Fetch a flow_t object from queue and remove it from queue */ int flow_queue_clear(void); /* Clear all item in queue */ int flow_queue_len(void); /* Length of queue */ void flow_queue_print(void); /* Print queue details for debugging */ #endif /* FLOW_H_ */
Pasyware/Http_Sniffer
include/tcp.h
/* * tcp.h * * Created on: Jun 15, 2011 * Author: chenxm */ #ifndef __TCP_H__ #define __TCP_H__ #include "order.h" #include "util.h" int tcp_order(order_t *ord, seq_t *new_seq, BOOL src); int tcp_order_check(order_t *order); // for debugging #endif /* __TCP_H__ */
Pasyware/Http_Sniffer
include/order.h
<reponame>Pasyware/Http_Sniffer #ifndef __ORDER_H__ #define __ORDER_H__ #include <sys/types.h> #include "packet.h" #include "util.h" typedef struct _seq_t seq_t; struct _seq_t{ packet_t *pkt; /* packet */ u_int32_t seq; /* seq order */ u_int32_t nxt_seq; /* next in seq order */ BOOL ack; /* acknowledged */ u_int8_t th_flags; /* TCP flags of packet */ time_t cap_sec; time_t cap_usec; seq_t *next; /* next in seq order */ }; /* data to order a TCP stream */ typedef struct _order_t order_t; struct _order_t { seq_t *src; /* source packet list ordered */ seq_t *dst; /* destination packet list ordered */ seq_t *last_src; /* last in src queue inserted */ seq_t *last_dst; /* last in dst queue inserted */ u_int32_t num; /* number of packet in queue */ BOOL rst; /* reset */ }; seq_t *seq_new(void); void seq_free(seq_t *seq); order_t *order_new(void); void order_free(order_t *order); seq_t *seq_pkt(packet_t *p); #endif /* __ORDER_H__ */
Pasyware/Http_Sniffer
src/order.c
<filename>src/order.c<gh_stars>100-1000 /* * order.c * * Created on: Jun 14, 2011 * Author: chenxm */ #include "packet.h" #include "util.h" #include "order.h" seq_t *seq_new(void){ seq_t *seq; seq = MALLOC(seq_t, 1); memset(seq, 0, sizeof(seq_t)); return seq; } void seq_free(seq_t *seq){ /* packet is freed by packet_free to avoid double free */ free(seq); } order_t *order_new(void){ order_t *order; order = MALLOC(order_t, 1); memset(order, 0, sizeof(order_t)); return order; } void order_free(order_t *order){ seq_t *s = NULL; while(order->src != NULL){ s = order->src; order->src = order->src->next; seq_free(s); } while(order->dst != NULL){ s = order->dst; order->dst = order->dst->next; seq_free(s); } free(order); } seq_t *seq_pkt(packet_t *p){ seq_t *s; s = MALLOC(seq_t, 1); s->pkt = p; if ((p->tcp_flags & TH_ACK) == TH_ACK) s->ack = TRUE; else s->ack = FALSE; s->next = NULL; s->seq = p->tcp_seq; if((p->tcp_flags & TH_SYN) == TH_SYN || (p->tcp_flags & TH_FIN) == TH_FIN){ s->nxt_seq = p->tcp_seq + p->tcp_dl +1; }else{ s->nxt_seq = p->tcp_seq + p->tcp_dl; } s->th_flags = p->tcp_flags; s->cap_sec = p->cap_sec; s->cap_usec = p->cap_usec; return s; }
Pasyware/Http_Sniffer
src/flow_queue.c
/* * queue.c * * Created on: Mar 16, 2012 * Author: front */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <string.h> #include <assert.h> #include <sys/time.h> #include <unistd.h> #include "util.h" #include "flow.h" static pthread_mutex_t mutex_queue; static flow_t *flow_queue_first = NULL; static flow_t *flow_queue_last = NULL; static int flow_qlen = 0; /* flow queue length */ /************************ * flow queue functions * ************************/ int flow_queue_init(void) { int ret = 0; ret = pthread_mutex_init(&mutex_queue, NULL); if(ret != 0){ return -1; } flow_queue_first = NULL; flow_queue_last = NULL; flow_qlen = 0; return 0; } int flow_queue_enq(flow_t *flow) { pthread_mutex_lock(&mutex_queue); if (flow_qlen == 0){ flow_queue_first = flow; flow_queue_last = flow; flow_queue_last->next = NULL; flow_qlen++; pthread_mutex_unlock(&mutex_queue); return 0; } flow_queue_last->next = flow; flow_queue_last = flow; flow_queue_last->next = NULL; flow_qlen++; pthread_mutex_unlock(&mutex_queue); return 0; } flow_t* flow_queue_deq(void) { pthread_mutex_lock(&mutex_queue); flow_t *f = NULL; if(flow_qlen == 0){ pthread_mutex_unlock(&mutex_queue); return NULL; }else if(flow_qlen == 1){ flow_queue_last = NULL; } f = flow_queue_first; flow_queue_first = flow_queue_first->next; flow_qlen--; pthread_mutex_unlock(&mutex_queue); return f; } int flow_queue_clear(void) { pthread_mutex_lock(&mutex_queue); flow_t *f; while(flow_qlen > 0){ f = flow_queue_first; flow_queue_first = flow_queue_first->next; flow_free(f); flow_qlen--; } flow_queue_first = NULL; flow_queue_last = NULL; flow_qlen = 0; pthread_mutex_unlock(&mutex_queue); return 0; } int flow_queue_len(void) { return flow_qlen; } void flow_queue_print(void) { printf("(Flow queue length)%d\n", flow_queue_len()); }
Pasyware/Http_Sniffer
include/util.h
<gh_stars>100-1000 /* util.h */ #ifndef __UTIL_H__ #define __UTIL_H__ #include <sys/types.h> /************************Macros*****************************/ #define MALLOC(type, num) (type *) check_malloc((num) * sizeof(type)) #ifndef BOOL #define BOOL int #endif /* BOOL */ #ifndef TRUE #define TRUE 1 #endif /* TRUE */ #ifndef FALSE #define FALSE 0 #endif /* FALSE */ /**********************Functions*****************************/ void *check_malloc(unsigned long size); char *ip_ntos(u_int32_t n); u_int32_t ip_ston(char *s); #endif /* __UTIL_H__ */
Pasyware/Http_Sniffer
src/packet_queue.c
/* * queue.c * * Created on: Mar 16, 2012 * Author: chenxm * Email: <EMAIL> */ #include <stdlib.h> #include <string.h> #include <pthread.h> #include "packet.h" #include "util.h" /* Queue vars */ static unsigned int que_len = 0; static packet_t *pkt_first = NULL; static packet_t *pkt_last = NULL; static pthread_mutex_t mutex; BOOL packet_queue_init(void) { int ret; pkt_first = NULL; pkt_last = NULL; que_len = 0; ret = pthread_mutex_init(&mutex, NULL); if(ret != 0) { return FALSE; } return TRUE; } BOOL packet_queue_enq(packet_t *pkt) { pthread_mutex_lock(&mutex); if(que_len == 0) { pkt_first = pkt; pkt_last = pkt; pkt_last->next = NULL; que_len++; pthread_mutex_unlock(&mutex); return TRUE; } pkt_last->next = pkt; pkt_last = pkt; pkt_last->next = NULL; que_len++; pthread_mutex_unlock(&mutex); return TRUE; } packet_t * packet_queue_deq(void) { pthread_mutex_lock(&mutex); packet_t *pkt; if(que_len == 0) { pthread_mutex_unlock(&mutex); return NULL; } else if (que_len == 1 ) { pkt_last = NULL; } pkt = pkt_first; pkt_first = pkt_first->next; que_len--; pthread_mutex_unlock(&mutex); return pkt; } BOOL packet_queue_clr(void) { pthread_mutex_lock(&mutex); packet_t *pkt; while(que_len > 0) { pkt = pkt_first; pkt_first = pkt_first->next; packet_free(pkt); que_len--; } pkt_first = NULL; pkt_last = NULL; que_len = 0; pthread_mutex_unlock(&mutex); return TRUE; } unsigned int packet_queue_len(void) { return que_len; } void packet_queue_print(void) { printf("(Packet queue length)%d\n", packet_queue_len()); }
Pasyware/Http_Sniffer
src/main.c
<filename>src/main.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <time.h> #include <assert.h> #include <unistd.h> /* getopt() */ #include <netinet/in.h> #include <pcap.h> #include "packet.h" #include "flow.h" #include "util.h" #include "io.h" int GP_CAP_FIN = 0; /* Flag for offline PCAP sniffing */ #ifndef DEBUGGING #define DEBUGGING 0 void debugging_print(void){ while(1){ if ( GP_CAP_FIN == 1 ){ break; }else{ packet_queue_print(); flow_hash_print(); flow_queue_print(); sleep(1); } } pthread_exit(NULL); } #endif /** * Help function to print usage information. */ void print_usage(const char* pro_name){ printf("Usage: %s -i interface [-f tracefile] [-o dumpfile]\n", pro_name); } /** * Parse packets' header information and return a packet_t object */ packet_t* packet_preprocess(const char *raw_data, const struct pcap_pkthdr *pkthdr) { packet_t *pkt = NULL; /* new packet */ char *cp = raw_data; ethhdr *eth_hdr = NULL; iphdr *ip_hdr = NULL; tcphdr *tcp_hdr = NULL; /* Parse libpcap packet header */ pkt = packet_new(); pkt->cap_sec = pkthdr->ts.tv_sec; pkt->cap_usec = pkthdr->ts.tv_usec; pkt->raw_len = pkthdr->caplen; /* Parse ethernet header and check IP payload */ eth_hdr = packet_parse_ethhdr(cp); if(eth_hdr->ether_type != 0x0800){ free_ethhdr(eth_hdr); packet_free(pkt); return NULL; } /* Parse IP header and check TCP payload */ cp = cp + sizeof(ethhdr); ip_hdr = packet_parse_iphdr(cp); pkt->saddr = ip_hdr->saddr; pkt->daddr = ip_hdr->daddr; pkt->ip_hl = (ip_hdr->ihl) << 2; /* bytes */ pkt->ip_tol = ip_hdr->tot_len; pkt->ip_pro = ip_hdr->protocol; if(pkt->ip_pro != 0x06){ free_ethhdr(eth_hdr); free_iphdr(ip_hdr); packet_free(pkt); return NULL; } /* Parse TCP header */ cp = cp + pkt->ip_hl; tcp_hdr = packet_parse_tcphdr(cp); pkt->sport = tcp_hdr->th_sport; pkt->dport = tcp_hdr->th_dport; pkt->tcp_seq = tcp_hdr->th_seq; pkt->tcp_ack = tcp_hdr->th_ack; pkt->tcp_flags = tcp_hdr->th_flags; pkt->tcp_win = tcp_hdr->th_win; pkt->tcp_hl = tcp_hdr->th_off << 2; /* bytes */ pkt->tcp_dl = pkt->ip_tol - pkt->ip_hl - pkt->tcp_hl; pkt->http = 0; /* default */ /* Check the TCP ports to identify if the packet carries HTTP data We only consider normal HTTP traffic without encryption */ if( !(tcp_hdr->th_sport == 80 || tcp_hdr->th_dport == 80 || \ tcp_hdr->th_sport == 8080 || tcp_hdr->th_dport == 8080 || \ tcp_hdr->th_sport == 8000 || tcp_hdr->th_dport == 8000)){ free_ethhdr(eth_hdr); free_iphdr(ip_hdr); free_tcphdr(tcp_hdr); packet_free(pkt); return NULL; } /* Process packets of flows which carry HTTP traffic */ if(pkt->tcp_dl != 0){ cp = cp + pkt->tcp_hl; if( !IsHttpPacket(cp, pkt->tcp_dl) ){ /* If the packet is not HTTP, we erase the payload. */ pkt->tcp_odata = NULL; pkt->tcp_data = pkt->tcp_odata; }else{ /* Yes, it's HTTP packet */ char *head_end = NULL; int hdl = 0; head_end = IsRequest(cp, pkt->tcp_dl); if( head_end != NULL ){ /* First packet of request. */ hdl = head_end - cp + 1; pkt->http = HTTP_REQ; /* Fake TCP data length with only HTTP header. */ pkt->tcp_dl = hdl; } head_end = IsResponse(cp, pkt->tcp_dl); if( head_end != NULL ){ /* First packet of response. */ hdl = head_end - cp + 1; pkt->http = HTTP_RSP; /* Fake TCP data length with only HTTP header. */ pkt->tcp_dl = hdl; } /* Allocate memory to store HTTP header. */ pkt->tcp_odata = MALLOC(char, pkt->tcp_dl + 1); pkt->tcp_data = pkt->tcp_odata; memset(pkt->tcp_odata, 0, pkt->tcp_dl + 1); memcpy(pkt->tcp_odata, cp, pkt->tcp_dl); } }else{ pkt->tcp_odata = NULL; pkt->tcp_data = pkt->tcp_odata; } free_ethhdr(eth_hdr); free_iphdr(ip_hdr); free_tcphdr(tcp_hdr); return pkt; } /** * Fetch a packet from packet queue and add it to any flow. */ int process_packet_queue(void){ packet_t *pkt = NULL; while(1){ pkt = packet_queue_deq(); if (pkt != NULL){ flow_hash_add_packet(pkt); continue; } else if ( GP_CAP_FIN == 1 ) { break; } else { nanosleep((const struct timespec[]){{0, 100000000L}}, NULL); } } pthread_exit("Packet processing finished.\n"); return 0; } /** * Fetch a flow from flow queue and process it */ int process_flow_queue(const char* dump_file){ flow_t *flow = NULL; char* file_name = NULL; while(1){ file_name = NULL; if (dump_file != NULL) file_name = dump_file; flow = flow_queue_deq(); if(flow != NULL){ flow_extract_http(flow); if (file_name == NULL){ /* Generate time-dependent output file */ static char file_name_buf[64]; struct tm *timeinfo = NULL; time_t raw_time; char time_buf[20]; memset(file_name_buf, 0, sizeof(file_name_buf)); memset(time_buf, 0, sizeof(time_buf)); time( &raw_time ); timeinfo = localtime( &raw_time ); strftime(time_buf, sizeof(time_buf), "%Y%m%d%H", timeinfo); strcat(file_name_buf, time_buf); strcat(file_name_buf, ".txt"); file_name = file_name_buf; } save_flow_json(flow, file_name); flow_print(flow); flow_free(flow); continue; } else if (GP_CAP_FIN == 1) { break; } else { nanosleep((const struct timespec[]){{0, 100000000L}}, NULL); } } pthread_exit("Flow processing finished.\n"); return 0; } /** * Scrub flow hash table to forcely close dead flows. */ void scrubbing_flow_htbl(void){ int num = 0; while(1){ sleep(1); if (GP_CAP_FIN == 0){ num = flow_scrubber(60*10); /* flow timeout in seconds */ }else{ num = flow_scrubber(-1); /* cleanse all flows */ break; } } pthread_exit(NULL); } /** * Main capture function */ int capture_main(const char* interface, void (*pkt_handler)(void*), int livemode){ char errbuf[PCAP_ERRBUF_SIZE]; memset(errbuf, 0, PCAP_ERRBUF_SIZE); char *raw = NULL; pcap_t *cap = NULL; struct pcap_pkthdr pkthdr; packet_t *packet = NULL; extern int GP_CAP_FIN; // printf("%s mode ...\n", livemode==1 ? "Online" : "Offline"); if ( livemode==1 ) { cap = pcap_open_live(interface, 65535, 0, 1000, errbuf); } else { cap = pcap_open_offline(interface, errbuf); } if( cap == NULL) { printf("%s\n",errbuf); exit(1); } while(1){ raw = pcap_next(cap, &pkthdr); if( NULL != raw){ packet = packet_preprocess(raw, &pkthdr); if( NULL != packet ){ pkt_handler(packet); } } else if ( livemode==0 ) { GP_CAP_FIN = 1; break; } else { nanosleep((const struct timespec[]){{0, 100000000L}}, NULL); } } if( cap != NULL) pcap_close(cap); return 0; } /** * Main portal of http-sniffer */ int main(int argc, char *argv[]){ char* interface = NULL; char* dumpfile = NULL; char* tracefile = NULL; int opt; // Parse arguments while((opt = getopt(argc, argv, ":i:f:o:h")) != -1){ switch(opt){ case 'h': print_usage(argv[0]); return (1); case 'i': interface = optarg; break; case 'o': dumpfile = optarg; break; case 'f': tracefile = optarg; break; default: print_usage(argv[0]); return (1); } } // Check interfaces if (interface == NULL && tracefile == NULL){ print_usage(argv[0]); return (1); } time_t start, end; time(&start); void *thread_result; pthread_t job_pkt_q; pthread_t job_flow_q; pthread_t job_scrb_htbl; #if DEBUGGING == 1 pthread_t job_debug_p; #endif printf("Http-sniffer started: %s", ctime(&start)); /* Initialization of packet and flow data structures */ packet_queue_init(); flow_init(); /* Start packet receiving thread */ pthread_create(&job_pkt_q, NULL, (void*)process_packet_queue, NULL); /* Start dead flow cleansing thread */ pthread_create(&job_scrb_htbl, NULL, (void*)scrubbing_flow_htbl, NULL); /* Start flow processing thread */ pthread_create(&job_flow_q, NULL, (void*)process_flow_queue, dumpfile); #if DEBUGGING == 1 pthread_create(&job_debug_p, NULL, (void*)debugging_print, NULL); #endif /* Start main capture in live or offline mode */ if (interface != NULL) capture_main(interface, packet_queue_enq, 1); else capture_main(tracefile, packet_queue_enq, 0); // Wait for all threads to finish pthread_join(job_pkt_q, &thread_result); pthread_join(job_flow_q, &thread_result); pthread_join(job_scrb_htbl, &thread_result); #if DEBUGGING == 1 pthread_join(job_debug_p, &thread_result); #endif time(&end); printf("Time elapsed: %d s\n", (int)(end - start)); return 0; }
Pasyware/Http_Sniffer
include/io.h
/* * io.h * * Created on: Mar. 12, 2015 * Author: chenxm */ #ifndef IO_H_ #define IO_H_ void flow_print(const flow_t *flow); void save_flow_json(const flow_t *flow, const char* file); #endif
souravverma94/grpc-fs
messages.h
<gh_stars>1-10 #pragma once #include <cstdint> #include <string> #include "grpc_fs.grpc.pb.h" grpcfs::FileId MakeFileId(std::int32_t id); grpcfs::FileContent MakeFileContent(std::int32_t id, std::string name, const void* data, size_t data_len);
souravverma94/grpc-fs
sequential_file_reader.h
<reponame>souravverma94/grpc-fs #pragma once #include <string> #include <cstdint> #include <memory> #include <functional> // SequentialFileReader: Read a file using using mmap(). Attempt to overlap reads of the file and writes by the user's code // by reading the next segment class SequentialFileReader { public: SequentialFileReader(SequentialFileReader&&); SequentialFileReader& operator=(SequentialFileReader&&); ~SequentialFileReader(); // Read the file, calling OnChunkAvailable() whenever data are available. It blocks until the reading // is complete. void Read(size_t max_chunk_size); std::string GetFilePath() const { return m_file_path; } protected: // Constructor. Attempts to open the file, and throws std::system_error if it fails to do so. SequentialFileReader(const std::string& file_name); // TODO: Also provide a constructor that doesn't open the file, and a separate Open method. // OnChunkAvailable: The user needs to override this function to get called when data become available. virtual void OnChunkAvailable(const void* data, size_t size) = 0; private: std::string m_file_path; std::unique_ptr< const std::uint8_t, std::function<void(const std::uint8_t*)> > m_data; size_t m_size; };
a2gs/calcDate
src/libAddSubDate.c
/* <NAME> (a2gs) * <EMAIL> * * Lib calcDate * * MIT License * */ /* libAddSubDate.c * Lib do add/subtract date. * * Who | When | What * --------+------------+---------------------------- * a2gs | 03/03/2019 | Creation * | | */ /* *** INCLUDES ************************************************************************ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "libAddSubDate.h" /* *** DEFINES AND LOCAL DATA TYPE DEFINATION ****************************************** */ /* *** LOCAL PROTOTYPES (if applicable) ************************************************ */ /* *** EXTERNS / LOCAL / GLOBALS VARIEBLES ********************************************* */ /* *** FUNCTIONS *********************************************************************** */ /* int a2gs_DateCalculation(struct tm *dataStart, a2gs_AddSubOperation_e op, long delta, struct tm *dataEnd) * * * * INPUT: * dataStart - * op - * delta - * OUTPUT: * dataEnd - * 0 - * -1 - */ int a2gs_DateCalculation(struct tm *dataStart, a2gs_AddSubOperation_e op, long delta, struct tm *dataEnd) { struct tm *dataOut; time_t dataInBroken, dataOutBroken; dataInBroken = mktime(dataStart); if(dataInBroken == (time_t)-1) return(-1); if (op == ADD) dataOutBroken = dataInBroken + delta; else if(op == SUB) dataOutBroken = dataInBroken - delta; dataOut = gmtime(&dataOutBroken); memcpy(dataEnd, dataOut, sizeof(struct tm)); return(0); } /* * 1 - is * 0 - is not */ int a2gs_AddSubDate_isLeapYear(int year) { int m4 = 0, m100 = 0, m400 = 0; m4 = year % 4; m100 = year % 100; m400 = year % 400; if(((m4 == 0) && (m100 == 0) && (m400 == 0)) || ((m4 == 0) && (m100 != 0))) return(1); return(0); } int a2gs_AddSubDate(int dia, int mes, int ano, int hora, int min, int seg, a2gs_AddSubOperation_e op, long delta, struct tm *dataEnd) { struct tm dataStart; char *tzname_save[2]; long timezone_save; int daylight_save; char *envTZ_save = NULL; char fullEnvTZ_save[80] = {0}; extern long timezone; extern char *tzname[2]; extern int daylight; if (mes == 1 && (dia < 1 || dia > 31)) return(-1); else if(mes == 2 && (dia < 1 || dia > 29)) return(-1); else if(mes == 3 && (dia < 1 || dia > 31)) return(-1); else if(mes == 4 && (dia < 1 || dia > 30)) return(-1); else if(mes == 5 && (dia < 1 || dia > 31)) return(-1); else if(mes == 6 && (dia < 1 || dia > 30)) return(-1); else if(mes == 7 && (dia < 1 || dia > 31)) return(-1); else if(mes == 8 && (dia < 1 || dia > 31)) return(-1); else if(mes == 9 && (dia < 1 || dia > 30)) return(-1); else if(mes == 10 && (dia < 1 || dia > 31)) return(-1); else if(mes == 11 && (dia < 1 || dia > 30)) return(-1); else if(mes == 12 && (dia < 1 || dia > 31)) return(-1); if(seg < 0 || seg > 59) return(-1); if(min < 0 || min > 59) return(-1); if(hora < 0 || hora > 23) return(-1); memset(&dataStart, 0, sizeof(struct tm)); memset(dataEnd, 0, sizeof(struct tm)); /* Saving the TimeZone */ tzset(); tzname_save[0] = tzname[0]; tzname_save[1] = tzname[1]; timezone_save = timezone; daylight_save = daylight; envTZ_save = secure_getenv("TZ"); /* Setting timezone to UTC */ daylight = 0; timezone = 0; tzname[0] = tzname[1] = "GMT"; if(setenv("TZ", "UTC", 1) == -1) return(-1); dataStart.tm_sec = seg; dataStart.tm_min = min; dataStart.tm_hour = hora; dataStart.tm_mday = dia; dataStart.tm_mon = mes - 1; dataStart.tm_year = ano - 1900; dataStart.tm_isdst = 0; if(a2gs_DateCalculation(&dataStart, op, delta, dataEnd) == -1) return(-1); /* Restoring the TimeZone */ tzname[0] = tzname_save[0]; tzname[1] = tzname_save[1]; timezone = timezone_save; daylight = daylight_save; snprintf(fullEnvTZ_save, sizeof(fullEnvTZ_save), "TZ=%s", envTZ_save); if(putenv(fullEnvTZ_save) != 0) return(-1); return(0); }
a2gs/calcDate
src/sample.c
/* <NAME> (a2gs) * <EMAIL> * * Sample lib calcDate * * MIT License * */ /* sample.c * Sample to lib calcDate * * Who | When | What * --------+------------+---------------------------- * a2gs | 03/03/2019 | Creation * | | */ /* *** INCLUDES ************************************************************************ */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include "libAddSubDate.h" /* *** DEFINES AND LOCAL DATA TYPE DEFINATION ****************************************** */ /* *** LOCAL PROTOTYPES (if applicable) ************************************************ */ /* *** EXTERNS / LOCAL / GLOBALS VARIEBLES ********************************************* */ /* *** FUNCTIONS *********************************************************************** */ int main(int argc, char *argv[]) { int dia = 0; int mes = 0; int ano = 0; int hora = 0; int min = 0; int seg = 0; unsigned long delta = 0; char typeDelta = 0; a2gs_AddSubOperation_e op; struct tm endDate; int ret = 0; if(argc != 10){ printf("%s <DAY> <MONTH> <YEAR> <HOURS> <MINUTES> <SECONDS> [+-] <S|D> <DELTA (seconds|days)>\n", argv[0]); return(0); } dia = atoi(argv[1]); mes = atoi(argv[2]); ano = atoi(argv[3]); hora = atoi(argv[4]); min = atoi(argv[5]); seg = atoi(argv[6]); if (argv[7][0] == '+') op = ADD; else if(argv[7][0] == '-') op = SUB; else{ printf("Only '+' or '-' as operation types.\n"); return(0); } if (argv[8][0] == 'D' || argv[8][0] == 'd'){ typeDelta = 'D'; delta = A2GS_ADDSUBDATE_DAY_TO_SECONDS(atol(argv[9])); }else if(argv[8][0] == 'S' || argv[8][0] == 's'){ typeDelta = 'S'; delta = atol(argv[9]); }else{ printf("Only 'S|s' or 'D|d' as delta types.\n"); return(0); } ret = a2gs_AddSubDate(dia, mes, ano, hora, min, seg, op, delta, &endDate); if(ret == -1){ printf("Data format error.\n"); return(-1); } printf("%02d/%02d/%02d %02d:%02d:%02d %c %s %s = %02d/%s (%02d)/%02d %02d:%02d:%02d, Week: %s (%d), Day in the year: %d, Leap year: %s, Daylight saving time: %d\n", dia, mes, ano, hora, min, seg, argv[7][0], argv[9], (typeDelta == 'S' ? "sec(s)" : "day(s)"), endDate.tm_mday, A2GS_ADDSUBDATE_N_MONTH_TO_MONTH_STR(endDate.tm_mon), A2GS_ADDSUBDATE_MONTH(endDate.tm_mon), A2GS_ADDSUBDATE_YEAR(endDate.tm_year), endDate.tm_hour, endDate.tm_min, endDate.tm_sec, A2GS_ADDSUBDATE_N_DAY_TO_WEEK_STR(endDate.tm_wday), A2GS_ADDSUBDATE_WEEK(endDate.tm_wday), endDate.tm_yday, (a2gs_AddSubDate_isLeapYear(A2GS_ADDSUBDATE_YEAR(endDate.tm_year)) ? "yes" : "no"), endDate.tm_isdst); return(0); }
a2gs/calcDate
inc/libAddSubDate.h
/* <NAME> (a2gs) * <EMAIL> * * Lib calcDate * * MIT License * */ /* libAddSubDate.h * Library calcDate include file * * Who | When | What * --------+------------+---------------------------- * a2gs | 03/03/2019 | Creation * | | */ #ifndef __LIB_A2GS_ADDSUBDATE_H__ #define __LIB_A2GS_ADDSUBDATE_H__ /* *** INCLUDES ************************************************************************ */ #include <time.h> /* *** DEFINES ************************************************************************* */ #define A2GS_ADDSUBDATE_DAY_TO_SECONDS(__a2gs_addsubdate_dayToSec__) ((time_t)((60*60*24) * __a2gs_addsubdate_dayToSec__)) #define A2GS_ADDSUBDATE_N_DAY_TO_WEEK_STR(__a2gs_addsubdate_nWeekDay__) (a2gs_AddSubDate_weekDay[__a2gs_addsubdate_nWeekDay__]) #define A2GS_ADDSUBDATE_N_MONTH_TO_MONTH_STR(__a2gs_addsubdate_nMonth__) (a2gs_AddSubDate_Months[__a2gs_addsubdate_nMonth__]) #define A2GS_ADDSUBDATE_YEAR(__a2gs_addsubdate_nYear__) (__a2gs_addsubdate_nYear__ + 1900) #define A2GS_ADDSUBDATE_MONTH(__a2gs_addsubdate_nMonth__) (__a2gs_addsubdate_nMonth__ + 1) #define A2GS_ADDSUBDATE_WEEK(__a2gs_addsubdate_nWeek__) (__a2gs_addsubdate_nWeek__ + 1) /* *** DATA TYPES ********************************************************************** */ typedef enum{ ADD = 1, SUB }a2gs_AddSubOperation_e; static char *a2gs_AddSubDate_weekDay[] = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}; static char *a2gs_AddSubDate_Months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; /* *** INTERFACES / PROTOTYPES ********************************************************* */ /* int a2gs_AddSubDate(int dia, int mes, int ano, int hora, int min, int seg, a2gs_AddSubOperation_e op, long delta, struct tm *dataEnd) * * <Description> * * INPUT: * dia - Start day * mes - Start month * ano - Start year * hora - Start hour * min - Start minute * seg - Start second * op - Operation (ADD/SUB) * delta - Offset in seconds (can be used A2GS_ADDSUBDATE_DAY_TO_SECONDS()) * OUTPUT: * dataEnd - Calculated date * 0 - Ok * -1 - Error (maybe input format error) */ int a2gs_AddSubDate(int dia, int mes, int ano, int hora, int min, int seg, a2gs_AddSubOperation_e op, long delta, struct tm *dataEnd); /* int a2gs_AddSubDate_isLeapYear(int year) * * Return if a year (YYYY) is lead or not. * * INPUT: * year - year to check * OUTPUT: * 0 - is not a leap year * 1 - is a leap year */ int a2gs_AddSubDate_isLeapYear(int year); /* *** EXAMPLE ************************************************************************* */ #if 0 #endif #endif
me-ve/txt_to_c_array
txt_to_c_array.c
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #define ARRAY_TYPE_INDEX 3 #define ARRAY_NAME_INDEX 4 int main(int argc, char **argv){ if(argc != 5){ fprintf(stderr, "Usage: %s <input> <output> <array_type> <array_name>\n", argv[0]); return 1; } FILE *input = fopen(argv[1], "r"); if(input == NULL){ fprintf(stderr, "File %s doesn't exist.\n", argv[1]); return 2; } FILE *output = fopen(argv[2], "w"); if(output == NULL){ fprintf(stderr, "File %s cannot be created.\n", argv[2]); return 3; } char *line = NULL; size_t len = 0; ssize_t read; fprintf(output, "%s %s[] = {\n", argv[ARRAY_TYPE_INDEX], argv[ARRAY_NAME_INDEX]); while((read = getline(&line, &len, input) != -1)){ char *c = strchr(line, '\n'); if(c){ *c = ','; } fprintf(output, "\t%s\n", line); } fprintf(output, "};\n"); fclose(input); fclose(output); }
maximeh/dispatch
src/dispatch.c
/* Author: <NAME> <EMAIL> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* We want POSIX.1-2008 + XSI, i.e. SuSv4, features */ #define _XOPEN_SOURCE 700 #include <errno.h> // for errno, EINVAL #include <ftw.h> // for nftw, FTW (ptr only), FTW_D, FTW_DNR, etc #include <getopt.h> // for getopt, optind, optarg #include <limits.h> // for PATH_MAX #include <stdio.h> // for fprintf, stderr, fputs, printf, sprintf, etc #include <stdlib.h> // for EXIT_SUCCESS #include <string.h> // for memcpy, memset, strerror, strlen, strstr #include <sys/stat.h> // for stat #include <taglib/tag_c.h> // for taglib_file_free, taglib_file_is_valid, etc #include "files.h" // for copy, get_filename_ext, mkdir_p #include "tools.h" // for append_esc, DPRINTF, append, filename /* POSIX.1 says each process has at least 20 file descriptors. * Three of those belong to the standard streams. * Here, we use a conservative estimate of 15 available; * assuming we use at most two for other uses in this program, * we should never run into any problems. * Most trees are shallower than that, so it is efficient. * Deeper trees are traversed fine, just a bit slower. * (Linux allows typically hundreds to thousands of open files, * so you'll probably never see any issues even if you used * a much higher value, say a couple of hundred, but * 15 is a safe, reasonable value.) */ #ifndef USE_FDS #define USE_FDS 15 #endif int _debug = 0; static const char *ALLOWED_EXTENSIONS = "mp3m4aflacogg"; static const char *DEFAULT_FMT = "%a/%A/%t - %T"; static char *FMT = NULL; static char *DST = NULL; static void usage(void) { (void)fprintf(stdout, "dispatch [-h] [-d] [-f FORMAT] SOURCE DEST\n"); fputs("\t-h\t\tThis usage statement\n" "\t-d\t\tDebug output (-dd for more, ...)\n" "\t-f\t\tPath format - Tag supported:\n" "\t\t\t\t- %a (artist)\n" "\t\t\t\t- %A (album)\n" "\t\t\t\t- %y (year)\n" "\t\t\t\t- %t (track)\n" "\t\t\t\t- %T (title)\n", stdout); } static int build_path_from_tag(const char *filepath, struct filename *fn) { TagLib_File *file; TagLib_Tag *tag; int ret = -1; char *p = FMT; file = taglib_file_new(filepath); if (!file) { fprintf(stderr, "'%s' type cannot be determined" " or file cannot be opened.\n", filepath); goto free_taglib; } if (!taglib_file_is_valid(file)) { fprintf(stderr, "The file %s is not valid\n", filepath); goto free_taglib; } tag = taglib_file_tag(file); if (!tag) { fprintf(stderr, "The file %s is not valid.\n", filepath); goto free_taglib; } while (*p) { if (*p != '%') { ret = append(fn, "%c", *p++); } else { switch (*++p) { case 'a': ret = append_esc(fn, "%s", taglib_tag_artist(tag)); break; case 'A': ret = append_esc(fn, "%s", taglib_tag_album(tag)); break; case 't': ret = append_esc(fn, "%02d", taglib_tag_track(tag)); break; case 'T': ret = append_esc(fn, "%s", taglib_tag_title(tag)); break; case 'y': ret = append_esc(fn, "%d", taglib_tag_year(tag)); break; default: break; } ++p; } if (ret) goto free_taglib; } free_taglib: taglib_tag_free_strings(); taglib_file_free(file); return ret; } static int dispatch_entry(const char *filepath, const struct stat *info, const int typeflag, struct FTW *pathinfo) { const off_t filesize = info->st_size; const char *extension; struct filename fn; char *final_path; /* Don't bother to handle links */ if (typeflag == FTW_SL) return 0; if (typeflag == FTW_SLN) { DPRINTF(2, "%s (dangling symlink)\n", filepath); return 0; } if (typeflag == FTW_D || typeflag == FTW_DP) { DPRINTF(2, "directory: %s/\n", filepath); return 0; } if (typeflag == FTW_DNR) { DPRINTF(2, "%s/ (unreadable)\n", filepath); return 0; } if (typeflag == FTW_F) { extension = get_filename_ext(filepath); if (!extension) { DPRINTF(1, "'%s' doesn't have an extension.\n", filepath); return 0; } /* Check that the extension is valid */ if (!strstr(ALLOWED_EXTENSIONS, extension)) { DPRINTF(1, "'%s' doesn't have a valid extension.\n" "Valid extension are: " "mp3, m4a, flac and ogg\n", filepath); return 0; } /* Okey, so we are should be able to treat this file */ fn.path = calloc(PATH_MAX, sizeof(*fn.path)); if (!fn.path) return -ENOMEM; fn.used = 0; if (build_path_from_tag(filepath, &fn)) { free(fn.path); return 0; } final_path = calloc(PATH_MAX, sizeof(*final_path)); sprintf(final_path, "%s/%s.%s", DST, fn.path, extension); free(fn.path); fn.path = NULL; /* We have a path, yeah ! Now copy that sucker to its final destination */ printf("%s => %s\n", filepath, final_path); mkdir_p(final_path); if (copy(filepath, final_path, filesize)) fprintf(stderr, "Could not copy %s to %s\n", filepath, final_path); free(final_path); final_path = NULL; } else DPRINTF(2, "%s/ (unreadable)\n", filepath); return 0; } int main(int argc, char **argv) { int c, ret; size_t len; while ((c = getopt(argc, argv, "dhf:")) != -1) { switch (c) { case 'f': len = strlen(optarg) + 1; FMT = calloc(len, sizeof(*FMT)); memcpy(FMT, optarg, len); break; case 'd': ++_debug; break; case 'h': default: usage(); free(FMT); return EXIT_SUCCESS; } } argc -= optind; argv += optind; if (argc != 2) { usage(); ret = EXIT_FAILURE; goto free_fmt; } /* Invalid directory path? */ if (argv[0] == NULL || *argv[0] == '\0') { usage(); ret = EXIT_FAILURE; goto free_fmt; } DPRINTF(1, "Searching in '%s'\n", argv[0]); DPRINTF(1, "Will move in '%s'\n", argv[1]); len = strlen(argv[1]) + 1; DST = calloc(len, sizeof(*DST)); memcpy(DST, argv[1], len); if (FMT == NULL) { len = strlen(DEFAULT_FMT) + 1; FMT = calloc(len, sizeof(*FMT)); memcpy(FMT, DEFAULT_FMT, len); } if (nftw(argv[0], dispatch_entry, USE_FDS, FTW_PHYS)) { ret = EXIT_FAILURE; goto free_dst; } ret = EXIT_SUCCESS; free_dst: free(DST); free_fmt: free(FMT); return ret; }
maximeh/dispatch
src/tools.c
/* Author: <NAME> <EMAIL> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdarg.h> // for va_end, va_list, va_start #include <stdio.h> // for vsprintf #include "tools.h" // for filename int append(struct filename *fn, const char *fmt, ...) { va_list arg; int ret; va_start(arg, fmt); ret = vsprintf(fn->path + fn->used, fmt, arg); va_end(arg); fn->used += ret; if (ret > 0) return 0; return ret; } int append_esc(struct filename *fn, const char *fmt, ...) { va_list arg; int ret; int cur = fn->used; va_start(arg, fmt); ret = vsprintf(fn->path + fn->used, fmt, arg); va_end(arg); fn->used += ret; if (ret > 0) ret = 0; for (; cur < fn->used; ++cur) { if (fn->path[cur] == '/') fn->path[cur] = '_'; } return ret; }
maximeh/dispatch
src/tools.h
/* Author: <NAME> <EMAIL> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #define DEBUG #ifdef DEBUG extern int _debug; #define DPRINTF(level, ...) \ do { \ if (_debug >= level) \ printf(__VA_ARGS__); \ } while(0) #else #define DPRINTF(...) do {} while(0) #endif struct filename { char *path; int used; }; int append(struct filename *fn, const char *fmt, ...); int append_esc(struct filename *fn, const char *fmt, ...);
maximeh/dispatch
src/files.c
/* Author: <NAME> <EMAIL> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "files.h" #include <errno.h> // for errno, EINTR #include <fcntl.h> // for open, posix_fadvise, posix_fallocate, O_CREAT #include <libgen.h> // for dirname #include <limits.h> // for PATH_MAX #include <stdio.h> // for fprintf, stderr #include <stdlib.h> // for size_t, NULL #include <string.h> // for strerror, strlen, strncpy, strrchr #include <sys/sendfile.h> // for sendfile #include <sys/stat.h> // for mkdir, S_IRWXU #include <unistd.h> // for close, off_t #include "tools.h" // for DPRINTF int mkdir_p(const char *path) { char opath[PATH_MAX]; char *dname; const size_t len = strlen(path); strncpy(opath, path, len); dname = dirname(opath); char *p = dname; for (; *p; ++p) { if (*p != '/') continue; *p = '\0'; DPRINTF(2, "create: %s\n", dname); mkdir(dname, S_IRWXU); *p = '/'; } DPRINTF(2, "create: %s\n", dname); mkdir(dname, S_IRWXU); return 0; } const char * get_filename_ext(const char *filename) { const char *dot = strrchr(filename, '.'); return (!dot || dot == filename) ? NULL: ++dot; } int copy(const char *src, const char *dest, const off_t filesize) { int err = 0; int in, out; off_t ofs = 0; in = open(src, O_RDONLY); if (in == -1) { fprintf(stderr, "%s\n", strerror(errno)); return 1; } out = open(dest, O_WRONLY | O_CREAT); if (out == -1) { close(in); fprintf(stderr, "%s\n", strerror(errno)); return 1; } if ((err = posix_fadvise(in, 0, filesize, POSIX_FADV_WILLNEED))) { fprintf(stderr, "ERROR: %s\n", strerror(err)); goto close_fds; } if ((err = posix_fadvise(in, 0, filesize, POSIX_FADV_SEQUENTIAL))) { fprintf(stderr, "ERROR: %s\n", strerror(err)); goto close_fds; } if ((err = posix_fallocate(out, 0, filesize))) { fprintf(stderr, "ERROR: %s\n", strerror(err)); goto close_fds; } while(ofs < filesize) { if(sendfile(out, in, &ofs, (size_t)(filesize - ofs)) == -1) { if (errno == EINTR) { err = EINTR; goto close_fds; } continue; } } close_fds: close(in); close(out); return err; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc02.c
<reponame>eduardocastrodev/study-notes /* * Descrição: Lista 03 - Questão 02 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main() { int number; printf("Digite um número: "); scanf("%d", &number); printf("O valor lido foi %d. \n", number); return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc04.c
/* * Descrição: Lista 03 - Questão 04 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main() { float number; printf("Digite um número: "); scanf("%f", &number); printf("O valor lido foi %d. \n", number); return 0; } /* * Como visto em aulas anteriores, os tipos de dados representam o tamanho dos * espaços alocados na memória. Ao tentar imprimir uma variável incorretamente, * ocorre um problema de incompatibilidade. */
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc10.c
<filename>01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc10.c /* * Descrição: Lista 03 - Questão 10 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main() { int day, month, year; do { printf("Dia: "); scanf("%d", &day); } while (day < 1 || day > 31); do { printf("Mẽs: "); scanf("%d", &month); } while (month < 1 || month > 12); printf("Ano: "); scanf("%d", &year); printf("A data digitada foi %d/%d/%d!\n", day, month, year); return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc08.c
/* * Descrição: Lista 03 - Questão 08 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main(){ int x, y; printf("Digite um numero: "); scanf(" %d", &x); printf("Digite outro numero: "); scanf(" %d", &y); printf("Ordem da digitação: \n"); printf(" x=%d, y=%d\n", x, y); // Troca de valores forma 1 x= x + y; y= x - y; x= x - y; // Troca de valores forma 2 // x = (x * y); // y = x / y; // x = x / y; printf("Ordem inversa: \n"); printf(" x=%d, y=%d\n", x, y); return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc13.c
<reponame>eduardocastrodev/study-notes<gh_stars>0 /* * Descrição: Lista 03 - Questão 13 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main() { char c; printf("Digite um caracter: "); scanf(" %c", &c); for (int i = 0; i < 3; i++) { printf("%c\n", c); } return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc03.c
<filename>01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc03.c /* * Descrição: Lista 03 - Questão 03 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main() { int number; printf("Digite um número: "); scanf("%d", &number); printf("O valor lido foi %f. \n", number); return 0; } /* * Como visto em aulas anteriores, os tipos de dados representam o tamanho dos * espaços alocados na memória. Ao tentar imprimir uma variável incorretamente, * ocorre um problema de incompatibilidade. */
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-Uni08/Exerc03.c
/** * Arquivo: Exerc01 * Autor: <NAME> (<EMAIL>) * Data: 2022-01-22 * Descrição: * Elabore algoritmos em C para ler uma matriz de inteiros N x N e: a. Mostrar cada elemento da matriz; b. Calcular e mostrar a soma dos elementos da matriz; c. Calcular e mostrar o maior e o menor elemento da matriz; d. Exibir cada elemento cujo valor seja maior que 50; e. Exibir cada elemento cujo valor seja par; f. Calcular e exibir a quantidade de elementos pares da matriz. */ #include <stdio.h> #include <locale.h> #include <stdlib.h> int main() { setlocale(LC_ALL, "Portuguese"); int n; printf("Sendo uma matriz NxN, digite o valor para N: "); scanf("%d", &n); int N[n][n], i, j; int maior, menor, soma=0, pares=0; // Inserindo valores randômicos for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { N[i][j] = (rand() % 100); } } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { // Calculando a soma soma += N[i][j]; // Maior ou menor if (N[i][j] == N[0][0]) { maior = N[i][j]; menor = N[i][j]; } else { if (maior < N[i][j]) maior = N[i][j]; if (menor > N[i][j]) menor = N[i][j]; } // Calculo de Elementos Pares pares++; } } // Imprimir elementos printf("A representação da matriz é: \n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%d ", N[i][j]); } printf("\n"); } // Exibir a Soma, Maior e Menor printf("A soma de todos os elementos é: %d\n", soma); printf("O maior elemento é: %d\n", maior); printf("O menor elemento é: %d\n", menor); // Exibir Maiores que 50 printf("Os elementos maiores que 50 são: \n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (N[i][j] > 50) printf("%d ", N[i][j]); } } printf("\n"); // Exibir Pares printf("Os elementos pares são: \n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (N[i][j] % 2 == 0) printf("%d ", N[i][j]); } } printf("\n\n"); return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc01.c
/* * Descrição: Lista 03 - Questão 01 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main() { printf("Início do programa\n"); printf("----\n"); printf("Fim do programa\n"); return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc12.c
/* * Descrição: Lista 03 - Questão 12 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main() { char c; printf("Digite um caractere: "); scanf("%c", &c); printf("O caractere digitado foi \"%c\"\n", c); return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc07.c
<reponame>eduardocastrodev/study-notes<filename>01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc07.c /* * Descrição: Lista 03 - Questão 07 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main(){ int number[2]; for (int i = 0; i <= 1; i++) { printf("Digite um numero: "); scanf(" %d", &number[i]); } printf("Ordem inversa: \n"); for (int i = 1; i >= 0; i--) { printf("%d ", number[i]); } printf("\n"); return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc06.c
/* * Descrição: Lista 03 - Questão 06 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main(){ char c; printf("Digite um caractere: "); scanf(" %c",&c); printf("O caractere %c assume os seguintes valores: \n", c); printf("Em decimal: %d \n",c); printf("Em octal: %o \n",c); printf("Em hexadecimal: %x \n",c); return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc14.c
/* * Descrição: Lista 03 - Questão 14 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main() { char c; int i; float f; printf("Digite um caracter: "); scanf(" %c", &c); printf("Digite um numero inteiro: "); scanf(" %d", &i); printf("Digite um numero real: "); scanf(" %f", &f); // OUTPUT printf("\n--> Espaços:\n%c %d %.2f\n", c, i, f); printf("\n--> Tabulações:\n%c \t%d \t%.2f\n", c, i, f); printf("\n--> Nova linha:\n%c \n%d \n%.2f\n", c, i, f); return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc09.c
<reponame>eduardocastrodev/study-notes /* * Descrição: Lista 03 - Questão 09 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main() { float number[2]; for (int i = 0; i <= 1; i++) { printf("Digite o %dº numero: ", (i + 1)); scanf(" %f", &number[i]); } for (int i = 1; i >= 0; i--) { printf("O %dº numero foi: %.2f\n", (i + 1), number[i]); } return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-Uni08/Exerc01.c
<gh_stars>0 /** * Arquivo: Exerc01; * Autor: <NAME> (<EMAIL>); * Data: 2022-01-22; * Descrição: * Ler um vetor Q de 20 posições (aceitar somente números positivos). Escrever a * seguir o valor do maior elemento de Q e a respectiva posição que ele ocupa no vetor. */ #include <stdio.h> int main() { int Q[21], i, maior, menor; for (i = 0; i < 20; i++) { do { printf("Digite o %dº valor: ", (i+1)); scanf("%d", &Q[i]); if (Q[i] < 0) printf("<< ERRO >> -- Apenas valores positivos sao aceitos, digite novamente!\n"); } while ((Q[i] < 0)); } for (i = 0; i < 20; i++) { if (i == 0) { maior = Q[i]; menor = Q[i]; } else { if (Q[i] > maior) { maior = Q[i]; } if (Q[i] < menor) { menor = Q[i]; } } } printf("O maior elemento de Q e: %d\n", maior); printf("O menor elemento de Q e: %d\n", menor); return 0; }
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc11.c
/* * Descrição: Lista 03 - Questão 11 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main() { const int NUMBER = 5; printf("valor da constante: %d\n", NUMBER); scanf("%d", &NUMBER); printf("Valor trocado: %d\n", NUMBER); return 0; } /* * Podem ocorrer erros ao tentar trocar o valor de uma constante. * Como o nome já diz, o valor deve permanecer o mesmo (constante) durante toda * a execução do programa. */
eduardocastrodev/study-notes
01-SEMESTRE/PROGRAMACAO-COMPUTACIONAL-SBL0086/langC-lista03/Exerc05.c
/* * Descrição: Lista 03 - Questão 05 * Aluno: <NAME> * Matrícula: 514554 * Data atual: 16/11/2021 */ #include <stdio.h> int main(){ double number=0.0; printf("Digite um número: "); scanf("%lf",&number); printf("O numero %.6lf em notacao cientifica fica %.4e\n", number, number); return 0; }
syang2forever/jos
jos/lib/ipc.c
<reponame>syang2forever/jos // User-level IPC library routines #include <inc/lib.h> // Receive a value via IPC and return it. // If 'pg' is nonnull, then any page sent by the sender will be mapped at // that address. // If 'from_env_store' is nonnull, then store the IPC sender's envid in // *from_env_store. // If 'perm_store' is nonnull, then store the IPC sender's page permission // in *perm_store (this is nonzero iff a page was successfully // transferred to 'pg'). // If the system call fails, then store 0 in *fromenv and *perm (if // they're nonnull) and return the error. // Otherwise, return the value sent by the sender // // Hint: // Use 'thisenv' to discover the value and who sent it. // If 'pg' is null, pass sys_ipc_recv a value that it will understand // as meaning "no page". (Zero is not the right value, since that's // a perfectly valid place to map a page.) int32_t ipc_recv(envid_t *from_env_store, void *pg, int *perm_store) { // LAB 4: Your code here. pg = pg == NULL ? (void *)UTOP : pg; int r; if ((r = sys_ipc_recv(pg)) < 0) { if (from_env_store != NULL) { *from_env_store = 0; } if (perm_store != NULL) { *perm_store = 0; } return r; } else { if (from_env_store != NULL) { *from_env_store = thisenv->env_ipc_from; } if (perm_store != NULL) { *perm_store = thisenv->env_ipc_perm; } return thisenv->env_ipc_value; } return 0; } // Send 'val' (and 'pg' with 'perm', if 'pg' is nonnull) to 'toenv'. // This function keeps trying until it succeeds. // It should panic() on any error other than -E_IPC_NOT_RECV. // // Hint: // Use sys_yield() to be CPU-friendly. // If 'pg' is null, pass sys_ipc_try_send a value that it will understand // as meaning "no page". (Zero is not the right value.) void ipc_send(envid_t to_env, uint32_t val, void *pg, int perm) { // LAB 4: Your code here. pg = pg == NULL ? (void *)UTOP : pg; int r; while ((r = sys_ipc_try_send(to_env, val, pg, perm)) < 0) { if (r != -E_IPC_NOT_RECV) { panic("sys_ipc_try_send: %e\n", r); } sys_yield(); } } // Find the first environment of the given type. We'll use this to // find special environments. // Returns 0 if no such environment exists. envid_t ipc_find_env(enum EnvType type) { int i; for (i = 0; i < NENV; i++) if (envs[i].env_type == type) return envs[i].env_id; return 0; }
syang2forever/jos
jos/user/faultnostack.c
<reponame>syang2forever/jos<gh_stars>100-1000 // test user fault handler being called with no exception stack mapped #include <inc/lib.h> void _pgfault_upcall(); void umain(int argc, char **argv) { sys_env_set_pgfault_upcall(0, (void*) _pgfault_upcall); *(int*)0 = 0; }
syang2forever/jos
jos/user/faultallocbad.c
// test user-level fault handler -- alloc pages to fix faults // doesn't work because we sys_cputs instead of cprintf (exercise: why?) #include <inc/lib.h> void handler(struct UTrapframe *utf) { int r; void *addr = (void*)utf->utf_fault_va; cprintf("fault %x\n", addr); if ((r = sys_page_alloc(0, ROUNDDOWN(addr, PGSIZE), PTE_P|PTE_U|PTE_W)) < 0) panic("allocating at %x in page fault handler: %e", addr, r); snprintf((char*) addr, 100, "this string was faulted in at %x", addr); } void umain(int argc, char **argv) { set_pgfault_handler(handler); sys_cputs((char*)0xDEADBEEF, 4); }
syang2forever/jos
jos/kern/cpu.h
#ifndef JOS_INC_CPU_H #define JOS_INC_CPU_H #include <inc/types.h> #include <inc/memlayout.h> #include <inc/mmu.h> #include <inc/env.h> // Maximum number of CPUs #define NCPU 8 // Values of status in struct Cpu enum { CPU_UNUSED = 0, CPU_STARTED, CPU_HALTED, }; // Per-CPU state struct CpuInfo { uint8_t cpu_id; // Local APIC ID; index into cpus[] below volatile unsigned cpu_status; // The status of the CPU struct Env *cpu_env; // The currently-running environment. struct Taskstate cpu_ts; // Used by x86 to find stack for interrupt }; // Initialized in mpconfig.c extern struct CpuInfo cpus[NCPU]; extern int ncpu; // Total number of CPUs in the system extern struct CpuInfo *bootcpu; // The boot-strap processor (BSP) extern physaddr_t lapicaddr; // Physical MMIO address of the local APIC // Per-CPU kernel stacks extern unsigned char percpu_kstacks[NCPU][KSTKSIZE]; int cpunum(void); #define thiscpu (&cpus[cpunum()]) void mp_init(void); void lapic_init(void); void lapic_startap(uint8_t apicid, uint32_t addr); void lapic_eoi(void); void lapic_ipi(int vector); #endif
syang2forever/jos
jos/user/faultevilhandler.c
// test evil pointer for user-level fault handler #include <inc/lib.h> void umain(int argc, char **argv) { sys_page_alloc(0, (void*) (UXSTACKTOP - PGSIZE), PTE_P|PTE_U|PTE_W); sys_env_set_pgfault_upcall(0, (void*) 0xF0100020); *(int*)0 = 0; }
syang2forever/jos
jos/user/yield.c
<filename>jos/user/yield.c // yield the processor to other environments #include <inc/lib.h> void umain(int argc, char **argv) { int i; cprintf("Hello, I am environment %08x.\n", thisenv->env_id); for (i = 0; i < 5; i++) { sys_yield(); cprintf("Back in environment %08x, iteration %d.\n", thisenv->env_id, i); } cprintf("All done in environment %08x.\n", thisenv->env_id); }
syang2forever/jos
jos/kern/sched.h
<reponame>syang2forever/jos<gh_stars>100-1000 /* See COPYRIGHT for copyright information. */ #ifndef JOS_KERN_SCHED_H #define JOS_KERN_SCHED_H #ifndef JOS_KERNEL # error "This is a JOS kernel header; user programs should not #include it" #endif // This function does not return. void sched_yield(void) __attribute__((noreturn)); #endif // !JOS_KERN_SCHED_H
syang2forever/jos
jos/fs/test.c
#include <inc/x86.h> #include <inc/string.h> #include "fs.h" static char *msg = "This is the NEW message of the day!\n\n"; void fs_test(void) { struct File *f; int r; char *blk; uint32_t *bits; // back up bitmap if ((r = sys_page_alloc(0, (void*) PGSIZE, PTE_P|PTE_U|PTE_W)) < 0) panic("sys_page_alloc: %e", r); bits = (uint32_t*) PGSIZE; memmove(bits, bitmap, PGSIZE); // allocate block if ((r = alloc_block()) < 0) panic("alloc_block: %e", r); // check that block was free assert(bits[r/32] & (1 << (r%32))); // and is not free any more assert(!(bitmap[r/32] & (1 << (r%32)))); cprintf("alloc_block is good\n"); if ((r = file_open("/not-found", &f)) < 0 && r != -E_NOT_FOUND) panic("file_open /not-found: %e", r); else if (r == 0) panic("file_open /not-found succeeded!"); if ((r = file_open("/newmotd", &f)) < 0) panic("file_open /newmotd: %e", r); cprintf("file_open is good\n"); if ((r = file_get_block(f, 0, &blk)) < 0) panic("file_get_block: %e", r); if (strcmp(blk, msg) != 0) panic("file_get_block returned wrong data"); cprintf("file_get_block is good\n"); *(volatile char*)blk = *(volatile char*)blk; assert((uvpt[PGNUM(blk)] & PTE_D)); file_flush(f); assert(!(uvpt[PGNUM(blk)] & PTE_D)); cprintf("file_flush is good\n"); if ((r = file_set_size(f, 0)) < 0) panic("file_set_size: %e", r); assert(f->f_direct[0] == 0); assert(!(uvpt[PGNUM(f)] & PTE_D)); cprintf("file_truncate is good\n"); if ((r = file_set_size(f, strlen(msg))) < 0) panic("file_set_size 2: %e", r); assert(!(uvpt[PGNUM(f)] & PTE_D)); if ((r = file_get_block(f, 0, &blk)) < 0) panic("file_get_block 2: %e", r); strcpy(blk, msg); assert((uvpt[PGNUM(blk)] & PTE_D)); file_flush(f); assert(!(uvpt[PGNUM(blk)] & PTE_D)); assert(!(uvpt[PGNUM(f)] & PTE_D)); cprintf("file rewrite is good\n"); }
syang2forever/jos
jos/user/idle.c
<reponame>syang2forever/jos<gh_stars>100-1000 // idle loop #include <inc/x86.h> #include <inc/lib.h> void umain(int argc, char **argv) { binaryname = "idle"; // Loop forever, simply trying to yield to a different environment. // Instead of busy-waiting like this, // a better way would be to use the processor's HLT instruction // to cause the processor to stop executing until the next interrupt - // doing so allows the processor to conserve power more effectively. while (1) { sys_yield(); } }
syang2forever/jos
jos/lib/libmain.c
<filename>jos/lib/libmain.c // Called from entry.S to get us going. // entry.S already took care of defining envs, pages, uvpd, and uvpt. #include <inc/lib.h> extern void umain(int argc, char **argv); const volatile struct Env *thisenv; const char *binaryname = "<unknown>"; void libmain(int argc, char **argv) { // set thisenv to point at our Env structure in envs[]. // LAB 3: Your code here. thisenv = &envs[ENVX(sys_getenvid())]; // save the name of the program so that panic() can use it if (argc > 0) binaryname = argv[0]; // call user main routine umain(argc, argv); // exit gracefully exit(); }
syang2forever/jos
jos/user/sendpage.c
<filename>jos/user/sendpage.c // Test Conversation between parent and child environment // Contributed by <NAME> at <NAME> #include <inc/lib.h> const char *str1 = "hello child environment! how are you?"; const char *str2 = "hello parent environment! I'm good."; #define TEMP_ADDR ((char*)0xa00000) #define TEMP_ADDR_CHILD ((char*)0xb00000) void umain(int argc, char **argv) { envid_t who; if ((who = fork()) == 0) { // Child ipc_recv(&who, TEMP_ADDR_CHILD, 0); cprintf("%x got message: %s\n", who, TEMP_ADDR_CHILD); if (strncmp(TEMP_ADDR_CHILD, str1, strlen(str1)) == 0) cprintf("child received correct message\n"); memcpy(TEMP_ADDR_CHILD, str2, strlen(str2) + 1); ipc_send(who, 0, TEMP_ADDR_CHILD, PTE_P | PTE_W | PTE_U); return; } // Parent sys_page_alloc(thisenv->env_id, TEMP_ADDR, PTE_P | PTE_W | PTE_U); memcpy(TEMP_ADDR, str1, strlen(str1) + 1); ipc_send(who, 0, TEMP_ADDR, PTE_P | PTE_W | PTE_U); ipc_recv(&who, TEMP_ADDR, 0); cprintf("%x got message: %s\n", who, TEMP_ADDR); if (strncmp(TEMP_ADDR, str2, strlen(str2)) == 0) cprintf("parent received correct message\n"); return; }
syang2forever/jos
jos/kern/kclock.h
<filename>jos/kern/kclock.h /* See COPYRIGHT for copyright information. */ #ifndef JOS_KERN_KCLOCK_H #define JOS_KERN_KCLOCK_H #ifndef JOS_KERNEL # error "This is a JOS kernel header; user programs should not #include it" #endif #define IO_RTC 0x070 /* RTC port */ #define MC_NVRAM_START 0xe /* start of NVRAM: offset 14 */ #define MC_NVRAM_SIZE 50 /* 50 bytes of NVRAM */ /* NVRAM bytes 7 & 8: base memory size */ #define NVRAM_BASELO (MC_NVRAM_START + 7) /* low byte; RTC off. 0x15 */ #define NVRAM_BASEHI (MC_NVRAM_START + 8) /* high byte; RTC off. 0x16 */ /* NVRAM bytes 9 & 10: extended memory size (between 1MB and 16MB) */ #define NVRAM_EXTLO (MC_NVRAM_START + 9) /* low byte; RTC off. 0x17 */ #define NVRAM_EXTHI (MC_NVRAM_START + 10) /* high byte; RTC off. 0x18 */ /* NVRAM bytes 38 and 39: extended memory size (between 16MB and 4G) */ #define NVRAM_EXT16LO (MC_NVRAM_START + 38) /* low byte; RTC off. 0x34 */ #define NVRAM_EXT16HI (MC_NVRAM_START + 39) /* high byte; RTC off. 0x35 */ unsigned mc146818_read(unsigned reg); void mc146818_write(unsigned reg, unsigned datum); #endif // !JOS_KERN_KCLOCK_H
syang2forever/jos
jos/inc/kbdreg.h
#ifndef JOS_KBDREG_H #define JOS_KBDREG_H // Special keycodes #define KEY_HOME 0xE0 #define KEY_END 0xE1 #define KEY_UP 0xE2 #define KEY_DN 0xE3 #define KEY_LF 0xE4 #define KEY_RT 0xE5 #define KEY_PGUP 0xE6 #define KEY_PGDN 0xE7 #define KEY_INS 0xE8 #define KEY_DEL 0xE9 /* This is i8042reg.h + kbdreg.h from NetBSD. */ #define KBSTATP 0x64 /* kbd controller status port(I) */ #define KBS_DIB 0x01 /* kbd data in buffer */ #define KBS_IBF 0x02 /* kbd input buffer low */ #define KBS_WARM 0x04 /* kbd input buffer low */ #define KBS_OCMD 0x08 /* kbd output buffer has command */ #define KBS_NOSEC 0x10 /* kbd security lock not engaged */ #define KBS_TERR 0x20 /* kbd transmission error or from mouse */ #define KBS_RERR 0x40 /* kbd receive error */ #define KBS_PERR 0x80 /* kbd parity error */ #define KBCMDP 0x64 /* kbd controller port(O) */ #define KBC_RAMREAD 0x20 /* read from RAM */ #define KBC_RAMWRITE 0x60 /* write to RAM */ #define KBC_AUXDISABLE 0xa7 /* disable auxiliary port */ #define KBC_AUXENABLE 0xa8 /* enable auxiliary port */ #define KBC_AUXTEST 0xa9 /* test auxiliary port */ #define KBC_KBDECHO 0xd2 /* echo to keyboard port */ #define KBC_AUXECHO 0xd3 /* echo to auxiliary port */ #define KBC_AUXWRITE 0xd4 /* write to auxiliary port */ #define KBC_SELFTEST 0xaa /* start self-test */ #define KBC_KBDTEST 0xab /* test keyboard port */ #define KBC_KBDDISABLE 0xad /* disable keyboard port */ #define KBC_KBDENABLE 0xae /* enable keyboard port */ #define KBC_PULSE0 0xfe /* pulse output bit 0 */ #define KBC_PULSE1 0xfd /* pulse output bit 1 */ #define KBC_PULSE2 0xfb /* pulse output bit 2 */ #define KBC_PULSE3 0xf7 /* pulse output bit 3 */ #define KBDATAP 0x60 /* kbd data port(I) */ #define KBOUTP 0x60 /* kbd data port(O) */ #define K_RDCMDBYTE 0x20 #define K_LDCMDBYTE 0x60 #define KC8_TRANS 0x40 /* convert to old scan codes */ #define KC8_MDISABLE 0x20 /* disable mouse */ #define KC8_KDISABLE 0x10 /* disable keyboard */ #define KC8_IGNSEC 0x08 /* ignore security lock */ #define KC8_CPU 0x04 /* exit from protected mode reset */ #define KC8_MENABLE 0x02 /* enable mouse interrupt */ #define KC8_KENABLE 0x01 /* enable keyboard interrupt */ #define CMDBYTE (KC8_TRANS|KC8_CPU|KC8_MENABLE|KC8_KENABLE) /* keyboard commands */ #define KBC_RESET 0xFF /* reset the keyboard */ #define KBC_RESEND 0xFE /* request the keyboard resend the last byte */ #define KBC_SETDEFAULT 0xF6 /* resets keyboard to its power-on defaults */ #define KBC_DISABLE 0xF5 /* as per KBC_SETDEFAULT, but also disable key scanning */ #define KBC_ENABLE 0xF4 /* enable key scanning */ #define KBC_TYPEMATIC 0xF3 /* set typematic rate and delay */ #define KBC_SETTABLE 0xF0 /* set scancode translation table */ #define KBC_MODEIND 0xED /* set mode indicators(i.e. LEDs) */ #define KBC_ECHO 0xEE /* request an echo from the keyboard */ /* keyboard responses */ #define KBR_EXTENDED 0xE0 /* extended key sequence */ #define KBR_RESEND 0xFE /* needs resend of command */ #define KBR_ACK 0xFA /* received a valid command */ #define KBR_OVERRUN 0x00 /* flooded */ #define KBR_FAILURE 0xFD /* diagnosic failure */ #define KBR_BREAK 0xF0 /* break code prefix - sent on key release */ #define KBR_RSTDONE 0xAA /* reset complete */ #define KBR_ECHO 0xEE /* echo response */ #endif /* !JOS_KBDREG_H */